body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p><strong>Prototype:</strong></p>
<pre><code>char *fgetline_alloc( FILE *fp, bool flush, int *nchars, bool eolend );
</code></pre>
<p>I realize this C99 function may be a bit more involved than expected, hence asking for reviews before using it for real (it's tested, but not extensively). I'll post the source code first, followed by detailed description (which I removed from the source code). I am leaving it in (simplified) debug mode.</p>
<p>I'm also providing quite a few sample-use examples, at the end of the post.</p>
<p>Briefly, the general idea is to return the input as a dynamically allocated c-string (<code>nul</code>-terminated buffer of <code>char</code>s). <code>flush</code> may be set to <code>true</code> for interactive input validation in a loop, from <code>stdin</code>. <code>eolend</code> specifies whether the result will end with EOL or not. <code>nchars</code> specifies either the max count of <code>char</code>s to be read (positive value), or an initial alloc-ahead size in <code>char</code>s (0 or negative value). It also passes back the count of successfully read <code>char</code>s. For details, please see the <strong>Details</strong> section below the source code.</p>
<p>If cleared, I intend to also make a <code>wchar_t</code> version of it.</p>
<p>Besides anything else you spot, I'd be interested in your opinions about:</p>
<ul>
<li>guarding against passed-in overflow of <code>*nchars</code> (is it possible? if
so is it worth it?)</li>
<li>my approach of preventing <code>int</code> overflow for the params of <code>malloc()</code> and <code>realloc()</code></li>
<li><code>realloc()</code>ing the resulting <code>buf</code> to its exact size at the end (I currently don't)</li>
</ul>
<p>Thanks in advance to anyone taking the time to review this.</p>
<h2>Source Code</h2>
<pre><code>/* tab space: 4 (regular, not spaces) */
#include <stdio.h> // for debug messages
#include <stdlib.h>
#include <stdbool.h> // C99 - bool, true, false
#include <limits.h> // C99 - for INT_MAX, etc
#include <errno.h>
#define MYDEBUG 1
#if MYDEBUG
#define DBGMSG( ... )\
do{\
fprintf(stderr, "*** %s(): ", __func__ );\
fprintf( stderr, __VA_ARGS__ );\
}while(0)
#endif
// -----------------------------------------------
// Read a line from an already open text-stream, and Return it as a dynamically
// allocated c-string. Return NULL on failure (errno is also set). The caller
// is responsible for freeing the returned c-string.
// NOTE: Description details removed for brevity.
//
char *fgetline_alloc( FILE *fp, bool flush, int *nchars, bool eolend )
{
errno = 0;
// sanity checks and early exits
if ( !fp ) {
DBGMSG( "invalid stream\n" );
errno = EDOM;
goto fail;
}
if ( ferror(fp) ) {
DBGMSG( "stream error\n" );
goto fail;
}
if ( feof(fp) ) {
DBGMSG( "already at EOF\n" );
goto fail;
}
// This can't handle passed-in wrap-around overflow, but with sane values
// it quits before passing an overflowed param to malloc() later on. The max
// initially allocated size is abs(*nchars)+1+1 chars when eolend is true
// (the 2nd +1 is for `\0'), so here we actually define the sane domain for
// *nchars' to [INT_MIN+2, INT_MAX-2] inclusive.
if ( nchars ) {
if ( *nchars > 0 && 2 > (INT_MAX - *nchars) ) {
DBGMSG( "int arg too big (*nchars=%d)\n", *nchars );
errno = EDOM;
goto fail;
}
if ( *nchars < 0 && -2 < (INT_MIN - *nchars) ) {
DBGMSG( "int arg too small (*nchars=%d)\n", *nchars );
errno = EDOM;
goto fail;
}
}
// distinguish fixed mode (true) from alloc-ahead mode (false)
bool ncharsFixed = ( nchars && *nchars > 0 );
// # of chars to allocate (either fixed or initial alloc-ahead)
int _nchars = 128; // default alloc-ahead (*nchars == 0)
if ( nchars ) {
if ( *nchars < 0 ) { // user-defined alloc-ahead
_nchars = -(*nchars);
}
else if ( *nchars > 0 ) { //fixed *nchars (no alloc-ahead)
_nchars = *nchars;
}
}
// initial alloc size depends on eolend (but always +1 for nul-terminator)
char *buf = malloc( eolend ? _nchars+1+1 : _nchars+1 );
if ( !buf ) {
DBGMSG( "failed to alloc %d bytes\n", eolend ? _nchars+1+1 : _nchars+1 );
goto fail;
}
// read chars into buf until EOL/EOF, or until *nchars if in fixed mode
int i = 0; // count of successfully read chars
int c = EOF;
while ( (c=fgetc(fp)) != '\n' && c != EOF ) {
if ( i == _nchars ) {
// fixed *nchars reached? we are done
if ( ncharsFixed ) {
break;
}
// alloc-ahead _nchars reached? grow buffer size and keep going
if ( _nchars > (INT_MAX - _nchars - 1) ) { // guard int overflow
free( buf );
DBGMSG( "(_nchars=%d) *= 2 would overflow \n", _nchars );
errno = ERANGE;
goto fail;
}
_nchars *= 2;
char *tmpbuf = realloc( buf, _nchars+1 );
if ( !tmpbuf ) {
free( buf );
DBGMSG( "failed to realloc %d bytes\n", _nchars+1 );
goto fail;
}
buf = tmpbuf;
}
buf[i++] = c;
}
// line longer than *nchars? Put back the last unprocessed c, so subsequent
// function call will not skip it. NOTE: when in alloc-ahead mode the loop
// stops ONLY after reading EOL or EOF, thus the following if-check fails.
if ( c != '\n' && c != EOF ) {
ungetc(c, fp);
if ( flush ) { // if specified, also flush extra chars
for (int ch; (ch=fgetc(fp)) != '\n' && ch != EOF;)
;
}
}
// if specified, append EOL
if ( eolend ) {
buf[i++] = '\n';
}
buf[i] = '\0'; // nul-terminator
// At this point, should we realloc() buf to its exact size?
// if ( !ncharsFixed && i < _nchars) {
// char *tmpbuf = realloc(buf, _nchars+1);
// if ( tmpbuf ) {
// buf = tmpbuf;
// }
// }
if ( nchars ) { // pass to caller # of read chars
*nchars = i;
}
return buf;
fail:
if ( nchars ) {
*nchars = 0;
}
return NULL;
}
</code></pre>
<h2>Details</h2>
<pre><code>char *fgetline_alloc( FILE *fp, bool flush, int *nchars, bool eolend );
</code></pre>
<p><strong>Arguments:</strong></p>
<p><strong>fp</strong>: (<code>FILE *</code>) An already opened input text-stream (it may be <code>stdin</code>).</p>
<p><strong>flush</strong>: (<code>bool</code>) <code>true</code> if extra <code>char</code>s should be flushed when the line to be read is longer than positive <code>*nchars</code>. It is ignored when <code>*nchars</code> is negative or 0 (see below). In most cases it should be <code>false</code>, but setting it to <code>true</code> can help in validating interactive input with a loop.</p>
<p><strong>nchars</strong>: (<code>int *</code>) Pointer to an integer specifying either a fixed count of <code>char</code>s to be read, or an initial alloc-ahead size (in <code>char</code>s). When non-<code>NULL</code>, it passes-back the count of successfully read <code>chars</code>, excluding <code>nul-terminator</code> (0 on error). Passing <code>*nchars</code> as 0, or <code>nchars</code> as <code>NULL</code>, enables alloc-ahead mode with default initial size (128 chars). To enable alloc-ahead mode with a different initial size, pass <code>*nchars</code> with a negative value (see examples). In alloc-ahead mode the initial size auto-grows (doubled) if need be. Also, in alloc-ahead mode the <code>flush</code> argument is ignored by the function.</p>
<p><strong>eolend</strong>: (<code>bool</code>) Determines if the returned c-string will end with EOL (<code>true</code>) or not (<code>false</code>). When looping the function to read multiple lines, this arg helps in getting consistent results regardless of the stream's last line, which may or may not end with EOL (it may end with just <code>EOF</code>).</p>
<p><strong>Remarks:</strong></p>
<ol>
<li><p><strong>Failed</strong> calls of the function can be identified by checking its return value against <code>NULL</code>, or by checking the updated <code>*nchars</code> value against 0. <code>errno</code> is also set either directly by the function or implicitly by the C runtime, thus the caller may additionally use <code>perror()</code>.</p>
</li>
<li><p>There is <strong>no "partial success"</strong>, meaning that even if partial data have been successfully read when an error occurs, they are discarded and the function fails.</p>
</li>
<li><p>Valid domain for <code>*nchars</code> is [<code>INT_MIN</code>+2 to <code>INT_MAX</code>-2] inclusive, but memory allocation may be denied for extreme values. If so, the function fails and a subsequent call to <code>perror()</code> will report <em>"not enough space"</em>, or similar.</p>
</li>
<li><p>When <code>eolend</code> is <code>true</code> and <code>*nchars</code> is positive (fixed allocation), lines longer than <code>*nchars</code> are truncated to <code>*nchars</code>, followed by EOL as an <strong>extra</strong> <code>char</code>.</p>
<p>For example, when:</p>
<pre><code> int nchars = 2;
char *str = fgetline_alloc(stdin, flush, &nchars, true);
</code></pre>
<p>and then feeding <code>stdin</code> with "12345", will set str to "12\n". Thus the passed-back value of <code>nchars</code> willbe <strong>3</strong> (not the original 2).</p>
</li>
</ol>
<h2>Sample Usage Examples</h2>
<p><strong>With Text Files:</strong></p>
<pre><code>/* C99 */
// prep
char *input = NULL;
int nchars;
bool flush = true;
bool eolend = true; // always EOL (false or !eolend means: never EOL)
// Read every line of a text-file, ensuring EOL and outputting the line along with its length
FILE *fp = fopen( "in.txt", "r" ); // any text file
if ( fp ) {
nchars = 0; // default alloc-ahead (also causes flush to get ignored)
while ( (input = fgetline_alloc(fp, !flush, &nchars, eolend)) ) {
printf( "(%u/%d): %s", strlen(input), nchars, input );
free( input );
nchars = 0; // reset for next call
}
fclose( fp );
}
// Store up to MAXLINES lines of a text-file in a custom array of lines, rejecting EOLs
struct Line {
char *data;
int len;
} lines[MAXLINES+1] = {{NULL,-1}}; // assuming proper MAXLINES (+1 for sentinel)
FILE *fp = fopen( "in.txt", "r" ); // any text file
if ( fp ) {
int i = 0; // lines counter
nchars = -256; // 256 chars alloc-ahead (also causes flush to get ignored)
while ( i < MAXLINES
&& (input=fgetline_alloc(fp, !flush, &nchars, !eolend)) ) {
printf( "Adding line[%d] (%d chars): %s\n", i, nchars, input );
lines[i].data = input;
lines[i].len = nchars;
nchars = -256; // reset for next call
i++;
}
fclose( fp );
printf( "%d lines read\n", i );
lines[i].len = -1; // sentinel for lines array
}
// verify and cleanup lines array
for (int i=0; lines[i].len > -1 && i < MAXLINES; i++) {
printf( "Line[%d] (%d chars): %s\n", i, lines[i].len, lines[i].data );
free( lines[i].data );
lines[i].data = NULL;
lines[i].len = -1;
}
</code></pre>
<p><strong>With <code>stdin</code> (Interactive Input):</strong></p>
<pre><code>/* C99 */
/* Omitting proper checking and freeing for brevity */
// prep
char *input;
int nchars;
bool flush = true; // flush if line is longer than non-zero positive nchars
bool eolend = true; // always EOL (false or !eolend means: never EOL)
// Read up to 100 chars (strip EOL, flush extra chars)
nchars = 100;
input = fgetline_alloc(stdin, flush, &nchars, !eolend);
// Read whole line with default alloc-ahead (strip EOL, ignore flush)
nchars = 0; // also causes flush to get ignored
input = fgetline_alloc(stdin, flush, &nchars, !eolend);
// Read whole line with 64 chars alloc-ahead (strip EOL, ignore flush)
nchars = -64; // intentionally negative (also causes flush to get ignored)
input = fgetline_alloc(stdin, flush, &nchars, !eolend);
/* Using proper checking and freeing */
// Validation loop (32 chars alloc-ahead, strip EOL, ignore flush)
puts( "Enter phrases (\"end\" without quotes to stop):");
for (;;) {
nchars = -32; // intentionally negative (also causes flush to get ignored)
input = fgetline_alloc(stdin, flush, &nchars, !eolend);
if ( !input ) {
perror( "*** fgetline_alloc() failed" );
break;
}
if (input && 0 == strcmp(input, "end") ) {
free( input );
break;
}
printf( " %d chars in \"%s\"\n", nchars, input );
free( input );
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T18:48:28.810",
"Id": "514955",
"Score": "0",
"body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T18:52:05.217",
"Id": "514956",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀm, thank you for rolling it back and apologies for my ignorance. I did read the general guidelines before posting, but I apparently missed the ones you just linked to (going over them as we speak)."
}
] |
[
{
"body": "<p>The macro is a little over-complex. If we're happy to always provide a string literal as format specifier (and we should be, for debugging), then just concatenate the prefix:</p>\n<pre><code>#define DBGMSG(format, ... )\\\n fprintf(stderr, "*** %s(): " format, __func__, __VA_ARGS__ )\n</code></pre>\n<p>Now it's a single expression, we no longer need the <code>do … while(0)</code> wrapper, and can use the return value normally.</p>\n<hr />\n<p>Using the sign of one argument to switch behaviours is an awkward design choice. It's too easy for an arithmetic error to cause an unintended switch of mode instead of a more visible, and thus correctable, error (either a log message or failure to allocate).</p>\n<p>I would prefer to see an extra <code>bool</code> parameter (or more likely a "flags" argument where we can OR together named constants for the options - that's more readable at call sites). We could possibly abstract that behind a pair of clearly-named wrapper functions that then form the main public interface, but given the other switches, I wouldn't do that (we'd need 8 functions already to cover all the flag combinations).</p>\n<hr />\n<blockquote>\n<pre><code> int _nchars = 128; \n</code></pre>\n</blockquote>\n<p>Avoid identifiers with leading underscores, even if you do happen to know the tricky details of what you can legally use in every given context, and what's reserved for the implementation.</p>\n<p>In any case, please don't name a variable so similarly to a formal parameter - it causes no end of confusion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T18:42:45.180",
"Id": "514952",
"Score": "0",
"body": "Thank you for taking the time Toby, I appreciate it! I already up-voted your reply and edited my post according to your suggestions, but please allow me a few more days in case anyone else shows up. I mean before accepting it! Btw, any thoughts about the 3 bullets in my post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T06:00:54.337",
"Id": "514984",
"Score": "1",
"body": "I didn't have time for a really in-depth review, but saw nothing else odd during a quick skim - so don't accept this answer unless you really get nothing else! No comments on your specific questions - I think your approaches to all three are at least as good as the choices I would have made. Perhaps continuing to use a multiplier of 2 is getting a bit crazy when the size gets very large - perhaps switch to linear growth at some threshold?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T11:58:37.833",
"Id": "515009",
"Score": "0",
"body": "Just saw your edit Toby, thanks! No doubt, signedness is indeed an awkward choice. I debated among several approaches (even having 2 separate funcs). Tbh I'm not very fond of `bool` params; I think they severely hurt readability when passed as direct values instead of named entities (toggled when needed). And there's 2 of them already. I prefer a flags bitmask instead too, but would require interfacing bit constants. Still not sure which of the 2 is easier from the user pov. If the func goes into a lib, `flags` makes much more sense, along with specialized negative error-codes via `nchars`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T12:03:48.563",
"Id": "515011",
"Score": "0",
"body": "`perhaps switch to linear growth at some threshold?`, I like this, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:35:23.617",
"Id": "515018",
"Score": "0",
"body": "I would definitely go with the flags bits - it's much easier to both read and write a combination of nice named constants than a sequence of bools when you can never remember which is which. When I wrote \"more likely\" in the parentheses, I really meant \"_much much_ more likely\"..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:27:04.003",
"Id": "515028",
"Score": "0",
"body": "Yeap, bit flags instead of multiple `bool`s is a no-brainer (also one of the reasons I separated `flush` and `eolend` to opposite sides of `nchars` in the params list, being a tiny bit easier to remember compared to being sequentially listed). When I said *\"not sure which of the 2 is easier from a user pov\"* I meant a \"library-like\" implementation with interface dependencies (custom constants, errors, etc) VS the \"free-roaming\" one I posted here (no dependencies, but unconventional usage). Still debating (I'll probably end up doing both)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:37:12.717",
"Id": "515029",
"Score": "0",
"body": "I'd not heard that \"library-like\" term before, but that's what I would go for. It's not like there's a significant cost to declaring a few constants in addition to the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T10:15:35.237",
"Id": "515110",
"Score": "0",
"body": "That was just a coined up term, not a real one, meaning the need for some kind of supporting interface in-order to use the function. I accepted the answer since no-one stepped in. Thanks again for a good review Toby!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T15:06:10.397",
"Id": "260940",
"ParentId": "260939",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260940",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T14:48:04.260",
"Id": "260939",
"Score": "4",
"Tags": [
"c"
],
"Title": "fgetline_alloc An involved C function for reading lines of arbitrary length"
}
|
260939
|
<p>I am using this merge sort function to sort table rows by Date, Letter, and Number. It works, but it is super messy and hard for others to read.</p>
<p>The dates are being sorted in two formats YYYY-MM-DD and MM/DD/YYYY which is why there are if statements regulating each format.</p>
<p>And the reason I am differentiating between letters and numbers is because when using comparison operators with stringified numbers, it would not process them correctly.</p>
<p>If someone could help me make this code more readable, that would be great, thanks :)</p>
<p>Merge Function:</p>
<pre><code>const Merge = (left_arr, right_arr, is_date) => {
let arr = [];
while (left_arr.length && right_arr.length) {
// Check for undefined variables
let variable1 = (left_arr[0].getElementsByTagName("td")[sortIndex].innerText == undefined) ? "" : left_arr[0].getElementsByTagName("td")[sortIndex].innerText;
let variable2 = (right_arr[0].getElementsByTagName("td")[sortIndex].innerText == undefined) ? "" : right_arr[0].getElementsByTagName("td")[sortIndex].innerText;
if (is_date) {
// Get the indexer for the dates
let indexer1 = (variable1.charAt(4) == "-") ? "-" : "/";
let indexer2 = (variable1.charAt(4) == "-") ? "-" : "/";
let var1year;
let var2year;
if (indexer1 == "-") {
var1year = variable1.substring(0, 4);
} else {
var1year = variable1.substring(variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 1, variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 5);
}
if (indexer2 == "-") {
var2year = variable2.substring(0, 4);
} else {
var2year = variable2.substring(variable2.indexOf(indexer2, variable2.indexOf(indexer2) + 1) + 1, variable2.indexOf(indexer2, variable2.indexOf(indexer2) + 1) + 5);
}
if (var1year == var2year) {
// Month
let var1month;
let var2month;
if (indexer1 == "-") {
var1month = variable1.substring(variable1.indexOf(indexer1) + 1, variable1.indexOf(indexer1) + 3);
} else {
var1month = variable1.substring(0, variable1.indexOf(indexer1));
}
if (indexer2 == "-") {
var2month = variable2.substring(variable2.indexOf(indexer2) + 1, variable2.indexOf(indexer2) + 3);
} else {
var2month = variable2.substring(0, variable2.indexOf(indexer2));
}
if (var1month == var2month) {
// Day
let var1day;
let var2day;
if (indexer1 == "-") {
var1day = variable1.substring(variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 1, variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 3);
} else {
var1day = variable1.substring(variable1.indexOf(indexer1) + 1, variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1));
}
if (indexer2 == "-") {
var2day = variable2.substring(variable2.indexOf(indexer2, variable2.indexOf(indexer2) + 1) + 1, variable2.indexOf(indexer2, variable2.indexOf(indexer2) + 1) + 3);
} else {
var2day = variable2.substring(variable2.indexOf(indexer2) + 1, variable2.indexOf(indexer2, variable2.indexOf(indexer2) + 1));
}
if (var1day == var2day) {
arr.push(right_arr.shift());
} else if (Number(var1day) < Number(var2day)) {
arr.push(left_arr.shift());
} else if (Number(var1day) > Number(var2day)) {
arr.push(right_arr.shift());
}
} else if (Number(var1month) < Number(var2month)) {
arr.push(left_arr.shift());
} else if (Number(var1month) > Number(var2month)) {
arr.push(right_arr.shift());
}
} else if (var1year < var2year) {
arr.push(left_arr.shift());
} else if (var1year > var2year) {
arr.push(right_arr.shift());
}
} else {
if (isNaN(variable1) && isNaN(variable2)) {
// Letter
let len = (variable1.length <= variable2.length ? variable1.length : variable2.length);
for (let i = 0; i < len; i++) {
if (variable1[i] < variable2[i]) {
arr.push(left_arr.shift());
break;
} else if (variable1[i] > variable2[i]) {
arr.push(right_arr.shift());
break;
} else if (variable1[i] == variable2[i]) {
if (i == len - 1) {
arr.push(right_arr.shift());
break;
} else {
continue;
}
}
}
} else {
// Number
variable1 = Number(variable1);
variable2 = Number(variable2);
if (variable1 < variable2) {
arr.push(left_arr.shift());
} else {
arr.push(right_arr.shift());
}
}
}
}
return [...arr, ...left_arr, ...right_arr];
}
</code></pre>
<p>MergeSort Function:</p>
<pre><code>const MergeSort = (array, is_date) => {
const half = array.length / 2;
if (array.length < 2) {
return array;
}
const left = array.splice(0, half);
return Merge(MergeSort(left, is_date), MergeSort(array, is_date), is_date);
}
</code></pre>
<p>SortTable Function:</p>
<pre><code>const SortTable = (tablestr, sort_index, currentElement) => {
var currentTable = document.getElementsByClassName(`${tablestr}-table-body`)[0];
let wishdir = "down";
let isDate = false;
let rowTitle = currentElement.innerHTML.toLowerCase();
if (sorted == true) {
// change direction if clicked again
wishdir = "up";
sorted = false;
} else {
sorted = true;
}
// Global variable used elsewhere
currentSortIndex = sort_index;
sortIndex = sort_index;
// Checks for specific date keywords in row title
if (rowTitle.includes("date")) {
isDate = true;
}
// Convert the collection into an array
const init_array = [...currentTable.rows];
// Replace characters
for (let i = 0; i < init_array.length; i++) {
init_array[i].innerText.replace("-", "");
init_array[i].innerText.replace("(", "");
init_array[i].innerText.replace(")", "");
init_array[i].innerText.replace(" ", "");
}
// Sort
const result = MergeSort(init_array, isDate);
// Remove and then add the rows back in
currentTable.innerHTML = "";
if (wishdir == "down") {
for (let c = 0; c < result.length; c++) {
currentTable.appendChild(result[c]);
}
} else if (wishdir == "up") {
result.reverse();
for (let c = 0; c < result.length; c++) {
currentTable.appendChild(result[c]);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T18:55:12.210",
"Id": "514957",
"Score": "1",
"body": "Separate the date compairison from the merge sort logic. Merge() should accept a compare function as a parameter."
}
] |
[
{
"body": "<h2>Code Style</h2>\n<ul>\n<li>You seem to use var, let, and const randomly. Pick a style and stick with it.</li>\n<li>The Javascript community generally uses camelCase for both variable names and function names. While it's not extremely important, I would recommend following suit.</li>\n<li>Always use <code>===</code> when comparing two values. The only exception should be when you want to use <code>== null</code> as a shorthand to check for both null and undefined.</li>\n<li>Any reason you're doing <code>string.charAt(index)</code> instead of <code>string[index]</code>? You can just use the simpler option here unless you have a good reason not to do so.</li>\n</ul>\n<p>You have a lot of long lines that could be broken up over multiple lines (either by just adding new lines in the right places or by using intermediate variables)</p>\n<p>Take this for example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var1year = variable1.substring(variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 1, variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 5);\n</code></pre>\n<p>And comopare it with this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var1year = variable1.substring(\n variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 1,\n variable1.indexOf(indexer1, variable1.indexOf(indexer1) + 1) + 5\n);\n</code></pre>\n<p>Here's another minor improvement - there's a couple places where you have code such as the following:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>if (conditionA) {\n ...\n} else {\n if (conditionB) {\n ...\n } else {\n ...\n }\n}\n</code></pre>\n<p>This could be rewritten as this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>if (conditionA) {\n ...\n} else if (conditionB) {\n ...\n} else {\n ...\n}\n</code></pre>\n<h2>Minor Simplifications</h2>\n<p>Here are a handful of simplifications you can do, using different language features you might not be aware of.</p>\n<p>This:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let variable1 = (leftArr[0].getElementsByTagName("td")[sortIndex].innerText == undefined) ? "" : leftArr[0].getElementsByTagName("td")[sortIndex].innerText;\n</code></pre>\n<p>can be written a lot simpler by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">nullish coalescing operator (??)</a></p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let variable1 = leftArr[0].getElementsByTagName("td")[sortIndex].innerText ?? ""\n</code></pre>\n<p>this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let len = (variable1.length <= variable2.length ? variable1.length : variable2.length);\n</code></pre>\n<p>Can be simplified by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min\" rel=\"nofollow noreferrer\">Math.min()</a></p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let len = Math.min(variable1.length, variable2.length);\n</code></pre>\n<p>You really like using <code>.substring()</code> everywhere to split apart the date string. Try using <code>string.split()</code> instead. With a little destructuring, a whole lot of code can be greatly simplified.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>> let [year, month, day] = '12/34/5678'.split('/');\n> console.log(year, month, day)\n12 34 5678\n</code></pre>\n<p>This chunk of code isn't doing anything:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>initArray[i].innerText.replace("-", "");\n</code></pre>\n<p>Strings are immutable - <code>.replace()</code> does not modify the string, instead, it returns a new string with certain characters replaced by other characters.</p>\n<p>I presume you're building a custom sorting function here simply for the practice? In a real-world application, we would just use the built-in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\">sort()</a> function.</p>\n<h2>Overall design</h2>\n<p>Your sort function is doing too many things, and is not general-purpose at all. (e.g. you've got UI code mixed into the algorithm). Additionally, all parameters to this function should be made explicit - i.e. don't force your caller to correctly set a global sortIndex variable before calling mergeSort - just pass sortIndex into the function instead as an explicit parameter. In general, do what you can to avoid global variables - it makes for difficult-to-follow logic (it certainly caught me off guard when I realized that this function relied on a global variable to function properly). When you have to use a global variable, make it explicit by assigning or reading from <code>globalThis</code>. e.g. <code>globalThis.myGlobal = 2; console.log(globalThis.myGlobal)</code>.</p>\n<p>To make your sorting function more general purpose, just have it take a function parameter that tells the sort function how you want to sort the given array.</p>\n<p>After applying all of these suggestions above, I made the following rewrite. (This by no means is perfect - there's a lot more I could add to simplify it further, nor is it tested, but it gives you a taste of how this advice can be applied).</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const strIsNumb = str => !isNaN(Number(str));\n\nfunction dateStrToTimestamp(dateStr) {\n let divider = dateStr.includes("-") ? "-" : "/";\n if (divider === "-") {\n let [year, month, day] = dateStr.split(divider);\n return new Date(year, month, day).valueOf();\n } else {\n let [month, day, year] = dateStr.split(divider);\n return new Date(year, month, day).valueOf();\n }\n}\n\nconst merge = (leftArr, rightArr, calcSortKey) => {\n let arr = [];\n while (leftArr.length && rightArr.length) {\n let variable1 = calcSortKey(leftArr[0]);\n let variable2 = calcSortKey(rightArr[0]);\n\n if (variable1 < variable2) {\n arr.push(leftArr.shift());\n } else {\n arr.push(rightArr.shift());\n }\n }\n return [...arr, ...leftArr, ...rightArr];\n};\n\nconst mergeSort = (array, calcSortKey) => {\n const half = array.length / 2;\n if (array.length < 2) {\n return array;\n }\n const left = array.splice(0, half);\n return merge(mergeSort(left, calcSortKey), mergeSort(array, calcSortKey), calcSortKey);\n};\n\n// ...\n\n// Example usage of the new sort function:\nconst calcSortKey = cellEl => {\n const cellText = cellEl.getElementsByTagName("td")[sortIndex].innerText ?? "";\n if (isDate) return dateStrToTimestamp(cellText);\n if (strIsNumb(cellText)) return Number(cellText);\n return cellText;\n};\n\nlet result = mergeSort(initArray, calcSortKey);\n</code></pre>\n<p>In this rewrite, I'm passing in a function to mergeSort() that tells mergeSort how to convert a given array value into something that can be sorted using javascript's <code><</code>, <code>></code>, and <code>===</code> operators. This gives the mergeSort() function flexibility to be used in a wide variety of places. For your specific scenario, you're wanting to sort arrays of elements. So, this calcSortKey function will take each element, look-up the corresponding text data, then parse it if needed.</p>\n<p>I'm using the following algorithm to parse the text data:</p>\n<ul>\n<li>If the string contains a number, turn it into a number</li>\n<li>If it contains a string, just return it. (Strings compare just fine in Javascript when used with <code><</code>, <code>></code>, and <code>===</code> operators - no need to compare character-by-character like you were doing)</li>\n<li>If we're parsing a date column, always parse the string as a date, then turn that date into a timestamp, as that's comparable with the <code><</code>, <code>></code>, and <code>===</code> operators.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:21:34.603",
"Id": "515040",
"Score": "0",
"body": "This is all very useful, thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T02:34:00.553",
"Id": "260960",
"ParentId": "260946",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "260960",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T17:04:54.000",
"Id": "260946",
"Score": "5",
"Tags": [
"javascript",
"mergesort"
],
"Title": "Merge Sort implementation is messy"
}
|
260946
|
<p><strong>Hello everyone!</strong></p>
<p>In today's assignment I had to complete a rather unusual translator, take a look at my solution, tell me what I can do to make it better and show off yours!</p>
<p>Write a function that translates some text into New Polish and vice versa. Polish is translated into New Polish by taking the last letter of each word, moving it to the beginning of the word and adding <code>ano</code> at the beginning. <code>Tom has a cat'</code> becomes <code>['Anomto anosha anoa anotca']</code>.</p>
<pre><code>def new_polish_translator(input):
result = ''
content = input.replace(',', '').replace('.', '').replace('?', '').replace('-', '')
#Dzieli na linie bez wchodzenia do nowej linii (\n)
lines = [line.rstrip() for line in content.split("\n")]
lines = [line for line in lines if len(line) > 0]
#sprawdza czy nie jest przetlumaczony
if all(line[-3::] == 'ano' for line in lines for word in line.split(' ')):
result = ' '.join(lines)
#sprawdza czy nie jest
else:
result = ' '.join('ano' + word[-1] + word[0:-1] for line in lines for word in line.split(' '))
result = result.capitalize()
return result
new_polish_translator("Tom has a cat")
</code></pre>
<p>result:</p>
<pre><code>'Anomto anosha anoa anotca'
</code></pre>
<p><strong>Have a great day!</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T23:11:48.703",
"Id": "514968",
"Score": "1",
"body": "Not super important, but I'll just note that this is basically just a variation of \"Pig Latin\"."
}
] |
[
{
"body": "<p>Your code is reasonable, but it does get tripped up if the text (<code>input</code>)\ncontains multiple adjacent spaces or the cleaned text (<code>content</code>) ends up\ncontaining multiple adjacent spaces. It also could be simplified here and\nthere. Some suggestions to consider: (1) parameterize the function so the user\ncan control which punctuation characters to remove; (2) since the algorithm is\nfundamentally a word-based translation, it makes sense to convert the text to\nwords early; (3) the check for already-translated text is not robust to\ncapitalization; and (4) use the no-argument form of <code>split()</code> to avoid the bug\nnoted above. Here's one way to make those changes:</p>\n<pre><code>def new_polish_translator(text, replace = ',.?-'):\n # Remove unwanted punctuation.\n for char in replace:\n text = text.replace(char, '')\n\n # Convert to words.\n words = text.split()\n\n # Translate, unless the text is already New Polish.\n prefix = 'ano'\n if all(w.lower().startswith(prefix) for w in words):\n np_words = words\n else:\n np_words = [prefix + w[-1] + w[0:-1] for w in words]\n\n # Return new text.\n return ' '.join(np_words).capitalize()\n</code></pre>\n<p>As you know already, this problem raises some tricky questions related to how\nthe algorithm defines a "word". Simply splitting on whitespace and removing a\nfew common punctuation markers will fail to handle a variety of human language\ninputs reasonably. There are other types of punctation (colon, semicolon, dash,\nand some weird ones), some words have internal punctuation (apostrophe), some\nwords contain or even start with digits, some words convey additional meaning\nwith capitalization, and some texts care about internal whitespace. Consider\nthis specimen from Ogden Nash, and notice the details of spacing and\npunctuation lost during translation:</p>\n<pre class=\"lang-none prettyprint-override\"><code># English.\n\nThe camel has a single hump;\nThe dromedary, two;\nOr else the other way around.\nI'm never sure. Are you?\n\n# New Polish.\n\nAnoeth anolcame anosha anoa anoesingl ano;hump anoeth anoydromedar ano;two anoro anoeels anoeth anorothe anoywa anodaroun anomi' anorneve anoesur anoear anouyo\n</code></pre>\n<p>Is there a a <strong>practical</strong> way to make a translator that preserves more of\nthose details? One approach is to use a basic tokenizing technique to decompose\nthe input text into various tokens, some of which will be preserved as-is and\nsome of which will be word-translated. These tokenizers are easy to build\nbecause they follow a simple pattern: try to match a sequence of regular\nexpressions; stop on the first match; emit a <code>Token</code>; then re-enter the loop.\nIn these situations, it helps to define some simple data-objects to represent\nsearch patterns and tokens. A sketch is shown below. It is purposely unfinished\nin the sense that it is missing some error handling (eg, checking that the\npatterns exhaust the text) and\nit doesn't try to preserve the original word capitalization. But those\nimprovements are fairly easy to add if you are so inclined.</p>\n<pre><code>from collections import namedtuple\nimport re\n\nPattern = namedtuple('Pattern', 'kind regex')\nToken = namedtuple('Token', 'kind text')\n\ndef new_polish_translator(text):\n # Define the search patterns.\n patterns = [\n Pattern('whitespace', re.compile('\\s+')),\n Pattern('word', re.compile('[A-Za-z]+')),\n Pattern('other', re.compile('\\S+')),\n ]\n\n # Translate only Token(kind=word). Preserve the rest.\n words = []\n for tok in tokenize(text, patterns):\n if tok.kind == 'word':\n w = tok.text\n words.append('ano' + w[-1] + w[0:-1])\n else:\n words.append(tok.text)\n\n # Return joined text.\n return ''.join(words)\n\ndef tokenize(text, patterns):\n pos = 0\n limit = len(text)\n while pos < limit:\n for p in patterns:\n m = p.regex.match(text, pos = pos)\n if m:\n txt = m.group(0)\n pos += len(txt)\n yield Token(p.kind, txt)\n break\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>anoeTh anolcame anosha anoa anoesingl anophum;\nanoeTh anoydromedar, anootw;\nanorO anoeels anoeth anorothe anoywa anodaroun.\nanoI'm anorneve anoesur. anoeAr anouyo?\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T22:21:37.323",
"Id": "260955",
"ParentId": "260949",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T19:07:24.253",
"Id": "260949",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "NewPolish - unconventional translator in Python"
}
|
260949
|
<p>As the title indicates this is one of the last most problems of Project Euler. The problem is straightforward. However, similar to the rest of the Euler Project problems either <code>Memory Error</code> or long execution times are problems. An explanation of the problem is:</p>
<blockquote>
<p>Consider the Fibonacci sequence <span class="math-container">\$\{1,2,3,5,8,13,21,\ldots\} \$</span>.</p>
<p>We let <span class="math-container">\$f(n)\$</span> be the number of ways of representing an integer
<span class="math-container">\$n\ge 0\$</span> as the sum of different Fibonacci numbers. For example,
<span class="math-container">\$16 = 3+13 = 1+2+13 = 3+5+8 = 1+2+5+8\$</span> and hence <span class="math-container">\$f(16) = 4\$</span> . By
convention <span class="math-container">\$f(0) = 1\$</span> .</p>
<p>Further we define, <span class="math-container">\$\displaystyle S(n) = \sum_{k=0}^n f(k)\$</span> You
are given <span class="math-container">\$S(100) = 415\$</span> and <span class="math-container">\$S(10^4) = 312807 \$</span> .</p>
<p>Find <span class="math-container">\$ \displaystyle S(10^{13})\$</span> .</p>
</blockquote>
<p>I'll show my code, and then explain what I have done so far. Lastly, ask for any kind of help. Thanks in advance.</p>
<pre><code>"""
* EULER PROJECT PROBLEM 755
"""
import itertools
def sumOfList(aList):
sumL = 0
for x in aList:
sumL += x
yield sumL
mostList = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657,
46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465,
14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170,
1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173,
86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920,
2504730781961, 4052739537881, 6557470319842]
def fibonList(x):
fibonSeq = []
firstT = 0
while mostList[firstT] <= x:
fibonSeq.append(mostList[firstT])
firstT += 1
yield fibonSeq
def powerset(iterable):
b = list(set(iterable))
for s in range(1, len(b) + 1):
for comb in itertools.combinations(b, s):
yield comb
def repWay(x):
ways = 0
for each in fibonList(x):
for i, combo in enumerate(powerset(each), 1):
for ea in sumOfList(combo):
if ea == x:
ways += 1
yield ways
def rangerepWays(x):
generalSum = 0
for i in range(x + 1):
for x in repWay(i):
generalSum += x
yield generalSum + 1 # + 1 because 0 = 0, while creating fib list I didn't incorporate 0 into fiblist.
for x in rangerepWays(10 ** 2):
print(x)
</code></pre>
<h3>1- First: It works, but, unfortunately, is too slow.</h3>
<ul>
<li>I have tested the program with the given examples in the question and it works. It passed both.</li>
</ul>
<h3>2- Second: What I have done</h3>
<ul>
<li>As you can see, the functions don't return anything, instead, I used
generators to avoid <code>Memory Error</code> errors.</li>
<li>To prevent calculating Fibonacci numbers that are below a number at each recursion, I
first created mostList than created a list whose elements are
smaller than an upper limit.</li>
</ul>
<h3>3- Third: What else can be done?</h3>
<ul>
<li>I am aware of this is one of the last questions of the Euler Project. Therefore, probably it requires a deep knowledge of mathematics. However, I lack that. It is okay if you share just only the names of applicable formulas or theories. I can try them to implement my current code.</li>
<li>My code may also have algorithmic fallacies or misinterpretations of the question. If there is one, you can just mention where it is and why there is a problem, not the solution.</li>
</ul>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T04:43:44.873",
"Id": "514977",
"Score": "0",
"body": "The answer may lie here https://en.wikipedia.org/wiki/Fibonacci_number#/media/File:Thirteen_ways_of_arranging_long_and_short_syllables_in_a_cadence_of_length_six.svg . I 'm not sure but the classic dynamic programming problem of rod cutting might be the solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T04:46:21.200",
"Id": "514978",
"Score": "0",
"body": "Secondly try implementing this algorithm in c, it should run much much faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T05:28:25.517",
"Id": "514980",
"Score": "0",
"body": "@VisheshMangla okay, thanks. I will edit as soon as I try these."
}
] |
[
{
"body": "<p>A low hanging fruit first. You don't need to work through the entire powerset. Given that <span class=\"math-container\">\\$i_0 < i_1 < ... < i_k\\$</span>, and <span class=\"math-container\">\\$N = F_{i_0} + F_{i_1} + ... + F_{i_k}\\$</span>, how small <span class=\"math-container\">\\$F_{i_k}\\$</span> could be?</p>\n<p>Recall that <span class=\"math-container\">\\$F_0 + F_1 + ... + F_n = F_{n+2} - 2\\$</span>. As long as <span class=\"math-container\">\\$F_{n+2} - 2 < N\\$</span>, a representation is impossible, so the term <span class=\"math-container\">\\$F_n\\$</span> cannot be the largest. Therefore, the largest term in the representation must satisfy both <span class=\"math-container\">\\$F_n \\le N\\$</span> <em>and</em> <span class=\"math-container\">\\$F_{n+2} - 2 \\ge N\\$</span>. Since the Fibonacci numbers grow exponentially, this observation drastically reduces the choice of the largest term (one or two possibilities, depending on how <span class=\"math-container\">\\$N\\$</span> compares to <span class=\"math-container\">\\$F_{n+1}\\$</span>).</p>\n<p>That alone shall give you a boost.</p>\n<hr />\n<p>Yet it is still bruteforcing. As you correctly say, there must be an underlying math.</p>\n<p>I played with your program, printing the total number of representations for numbers between <span class=\"math-container\">\\$F_n\\$</span> and <span class=\"math-container\">\\$F_{n+1}\\$</span>. The results are surprising:</p>\n<pre><code>Range Total\n3..4 3\n5..7 5\n8..12 11\n13..20 21\n21..33 43\n34..54 85\n</code></pre>\n<p>Hmm... <span class=\"math-container\">\\$T_{n+1} = 2T_n - 1\\$</span>. Something to prove about, isn't it? Try. I don't want to spoil the fun.</p>\n<hr />\n<p>For a proper review:</p>\n<ul>\n<li><p>I don't see the reason for <code>sumOfList</code>, <code>fibList</code>, <code>repWay</code>, and <code>rangerepWays</code> being generators. <code>yield</code> only make sense if it breaks the natural control flow, while preserving some execution context. Those above have no context to preserve; they can safely <code>return</code>. Making them generators only adds overhead.</p>\n<p><code>powerset</code> is a different story. It yields in the midst of a (nested) loop.</p>\n</li>\n<li><p>Naming deserves some attention. It took me a while to understand what, say, <code>repWays</code> is supposed to accomplish. Along the same line, <code>mostList</code> is a list of the Fibonacci numbers, isn't it? - so name it accordingly.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T06:01:57.610",
"Id": "260963",
"ParentId": "260951",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "260963",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T20:29:37.713",
"Id": "260951",
"Score": "2",
"Tags": [
"python",
"performance",
"programming-challenge",
"fibonacci-sequence"
],
"Title": "Project Euler Problem #755"
}
|
260951
|
<p>I'm trying to implement a graph structure in python, making use of the classes Vertex, Edge and Graph. The goal is to read a csv file that contains users names and a number (weight), like such <strong>Lynch,Arnold,23</strong></p>
<p>The entire structure of the code that I have at the moment is the following:</p>
<pre><code>"""Modules"""
import csv
class Graph:
'''
Representation of a simple graph using an adjacency map.
There exist nested Classes for Vertex and Edge objects and
useful methods for vertex and edge, edge incidence and
vertex degree retrieval plus edge and vertex insertion
'''
# == Class Vertex == #
class Vertex:
'''
Class for representing vertex structure for a graph.
'''
__slots__ = '_element'
def __init__(self, x):
'''
Do not call constructor directly. Use Graph's insert_vertex(x).
'''
self._element = x
def element(self):
'''
Return element associated with this vertex.
'''
return self._element
def __hash__(self):
'''
will allow vertex to be a map/set key
'''
return hash(id(self))
def __repr__(self):
return '{0}'.format(self._element)
# == Class Edge == #
class Edge:
'''
Class for representing edge structure for a graph.
'''
__slots__ = '_origin', '_destination', '_weight'
def __init__(self, u, v, x):
'''
Do not call constructor directly. Use Graph's insert_edge(x).
'''
self._origin = u
self._destination = v
self._weight = x
def endPoints(self):
'''
Return (u,v) tuple for vertices u and v.
'''
return (self._origin, self._destination)
def opposite(self, v):
'''
Return the vertex that is opposite v on this edge.
'''
return self._destination if self._origin == v else self._origin
def element(self):
'''
Return element associated with this edge.
'''
return self._weight
def __hash__(self):
'''
will allow edge to be a map/set key
'''
return hash(id(self))
def __repr__(self):
if self._weight is None:
return '({0}, {1})'.format(self._origin, self._destination)
return '({0}, {1}, {2})'.format(self._origin, self._destination, self._weight)
# == Class Graph == #
def __init__(self, directed=False):
'''
Create an empty graph (undirected, by default).
Graph is directed if optional paramter is set to True.
'''
self._outgoing = {}
self._incoming = {} if directed else self._outgoing
self.edges = dict()
self.nodes = set()
def __getitem__(self, arg):
return self._incoming[arg]
def is_directed(self):
'''
Return True if graph is directed
'''
return self._outgoing is not self._incoming
def vertex_count(self):
'''
Return the vertices count
'''
return len(self._outgoing)
def vertices(self):
'''
Return an iterator over the graph's vertices
'''
return self._outgoing.keys()
def get_vertex(self, el):
'''
Return the graph's vertex with corresponding element
equal to el. Return None on failure
'''
for vertex in self.vertices():
if vertex.element() == el:
return vertex
return None
def edges_count(self):
'''
Return the edges count
'''
edges = set()
for secondary_map in self._outgoing.values():
edges.update(secondary_map.values())
return len(edges)
def edges(self):
'''
Return a set of graph's edges
'''
edges = set()
for secondary_map in self._outgoing.values():
edges.update(secondary_map.values())
return edges
def get_edge(self, u, v):
'''
Return the edge from u to v
'''
return self._outgoing[u].get(v)
def degree(self, v, outgoing=True):
'''
Return the number of incident vertices to v
If graph is directed then handle the case of indegree
'''
inc = self._outgoing if outgoing else self._incoming
return len(inc[v])
def incident_edges(self, v, outgoing=True):
'''
Return all incident edges to node v.
If graph is directed, handle the case of incoming edges
'''
inc = self._outgoing if outgoing else self._incoming
if v not in inc:
return None
for edge in inc[v].values():
yield edge
def adjacent_vertices(self, v, outgoing=True):
'''
Return adjacent vertices to a given vertex
'''
if outgoing:
if v in self._outgoing:
return self._outgoing[v].keys()
else:
return None
else:
if v in self._incoming:
return self._incoming[v].keys()
else:
return None
def insert_vertex(self, x=None):
'''
Insert and return a new Vertex with element x
'''
for vertex in self.vertices():
if (vertex.element() == x):
# raise exception if vertice exists in graph
# exception can be handled from the class user
raise Exception('Vertice already exists')
v = self.Vertex(x)
self._outgoing[v] = {}
if self.is_directed:
self._incoming[v] = {}
return v
def insert_edge(self, u, v, x=None):
'''
Insert and return a new Edge from u to v with auxiliary element x.
'''
if (v not in self._outgoing) or (v not in self._outgoing):
# raise exception if one of vertices does not exist
# exception can be handled from the class user
raise Exception('One of the vertices does not exist')
if self.get_edge(u, v):
# no multiple edges
# exception can be handled from the class user
raise Exception('Edge already exists.')
e = self.Edge(u, v, x)
self._outgoing[u][v] = e
self._incoming[v][u] = e
return e
def remove_edge(self, u, v):
if not self.get_edge(u, v):
# exception for trying to delete non-existent edge
# can be handled from class user
raise Exception('Edge is already non-existent.')
u_neighbours = self._outgoing[u]
del u_neighbours[v]
v_neighbours = self._incoming[v]
del v_neighbours[u]
return None
def remove_vertex(self, x):
'''
Delete vertex and all its adjacent edges from graph
'''
if (x not in self._outgoing) and (x not in self._incoming):
raise Exception('Vertex already non-existent')
secondary_map = self._outgoing[x]
for vertex in secondary_map:
# delete reference to incident edges
if self.is_directed():
del self._incoming[vertex][x]
else:
del self._outgoing[vertex][x]
# delete reference to the vertex itself
del self._outgoing[x]
return None
def printG(self):
'''Mostra o grafo por linhas'''
print('Grafo Orientado:', self.is_directed())
'''Mostra o número de vertices'''
print("Número de Vertices: {}".format(G.vertex_count()))
'''Mostra o número de arestas'''
print("Número de Arestas: {}".format(G.edges_count()))
for v in self.vertices():
print('\nUser: ', v, ' grau_in: ', self.degree(v, False), end=' ')
if self.is_directed():
print('grau_out: ', self.degree(v, False))
for i in self.incident_edges(v):
print(' ', i, end=' ')
if self.is_directed():
for i in self.incident_edges(v, False):
print(' ', i, end=' ')
def read_csv(filename):
G = Graph()
with open(filename, 'r') as csv_file:
data = csv.reader(csv_file)
for linha in data:
id_origem = linha[0]
id_destino = linha[1]
peso = linha[2] if len(linha) > 2 else 1 # None
v_origem = G.insert_vertex(id_origem)
v_destino = G.insert_vertex(id_destino)
G.insert_edge(v_origem, v_destino, peso)
return G
if __name__ == "__main__":
# Ficheiro CSV
filename = "Data_Facebook_TESTE.csv"
# Criação do objeto grafo
G = read_csv(filename)
# Print do grafo
G.printG()
</code></pre>
<p>Based on the structure of the code that I already have, can anyone review the code and suggest some improvements?</p>
<p>Below, are some lines of the CSV file:</p>
<pre><code>Lynch,Arnold,23
Murray,Douglas,29
Clark,Thornton,30
Schneider,Chambers,80
Ryan,Wilson,19
Wells,Schwartz,15
Berry,Silva,21
Garrett,Neal,17
Hughes,Bailey,13
Wong,Robinson,39
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T20:54:01.850",
"Id": "260952",
"Score": "0",
"Tags": [
"python",
"graph"
],
"Title": "Graph Implementation for Social Network"
}
|
260952
|
<p>I wrote a simple Zoopla real estate scraper for just practicing what I learned so far in Python, Requests, BeautifulSoup and overall web scraping fundamentals. By looking at my code I feel like there would be a better and more elegant way to write it but unfortunately as a beginner I don't know yet. So, I believe I should let experienced guys here at Stack Exchange to review my code for enhancement.</p>
<pre><code>import requests
import json
import csv
import time
from bs4 import BeautifulSoup as bs
class ZooplaScraper:
results = []
def fetch(self, url):
print(f'HTTP GET request to URL: {url}', end='')
res = requests.get(url)
print(f' | Status code: {res.status_code}')
return res
def parse(self, html):
content = bs(html, 'html.parser')
content_array = content.select('script[id="__NEXT_DATA__"]')
content_dict = json.loads(content_array[0].string)
content_details = content_dict['props']['initialProps']['pageProps']['regularListingsFormatted']
for listing in content_details:
self.results.append ({
'listing_id': listing['listingId'],
'name_title': listing['title'],
'names': listing['branch']['name'],
'addresses': listing['address'],
'agent': 'https://zoopla.co.uk' + listing['branch']['branchDetailsUri'],
'phone_no': listing['branch']['phone'],
'picture': listing['image']['src'],
'prices': listing['price'],
'Listed_on': listing['publishedOn'],
'listing_detail_link': 'https://zoopla.co.uk' + listing['listingUris']['detail']
})
def to_csv(self):
with open('zoopla.csv', 'w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=self.results[0].keys())
writer.writeheader()
for row in self.results:
writer.writerow(row)
print('Stored results to "zoopla.csv"')
def run(self):
for page in range(1, 5):
url = 'https://www.zoopla.co.uk/for-sale/property/london/?page_size=25&q=London&radius=0&results_sort=newest_listings&pn='
url += str(page)
res = self.fetch(url)
self.parse(res.text)
time.sleep(2)
self.to_csv()
if __name__ == '__main__':
scraper = ZooplaScraper()
scraper.run()
</code></pre>
<p>Basically in this scraper I mostly did is JSON parsing. Problem was all the data on the website was coming from JavaScript under the <code>script</code> tag so I have to select that tag and then pass it to <code>json.loads()</code> and parse the JSON dict to find the right key-value pair.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T15:32:13.040",
"Id": "515038",
"Score": "1",
"body": "Your code is incorrectly indented, particularly the class methods."
}
] |
[
{
"body": "<ul>\n<li>Make a Session instead of issuing individual Requests <code>get</code>; this promotes explicit connection pooling, cookie sharing etc.</li>\n<li>There's no need for your current <code>print</code>s. If you find them to be of very high value, convert them into real logging calls</li>\n<li>Pre-define your script tag loading via a <code>SoupStrainer</code></li>\n<li>Use <code>urljoin</code> and centralize your root URL definition</li>\n<li>Do not keep <code>results</code> as a member; it's the result of a method call</li>\n<li>Do not represent results as a list; it can be an iterator so that results can be depaginated and streamed to disk while keeping memory occupation relatively low</li>\n<li>Parametrize your fetch function to represent the actual parameters on the web call</li>\n<li>Consider using PEP484 type hints</li>\n<li>Your <code>open</code> is <a href=\"https://docs.python.org/3/library/csv.html#csv.writer\" rel=\"nofollow noreferrer\">missing</a> <code>newline=''</code></li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from functools import partial\nfrom typing import Any, Dict, Iterable, List\n\nimport json\nimport csv\nfrom urllib.parse import urljoin\n\nfrom bs4 import BeautifulSoup, SoupStrainer\nfrom requests import Session\n\n\nJSON = Dict[str, Any]\n\n\nclass ZooplaScraper:\n ROOT = 'https://zoopla.co.uk'\n from_root = partial(urljoin, ROOT)\n\n def __init__(self):\n self.session = Session()\n\n strainer = SoupStrainer('script', id='__NEXT_DATA__')\n self.load_script = partial(\n BeautifulSoup, features='html.parser', parse_only=strainer,\n )\n\n def fetch(\n self, query: str = 'London', radius: int = 0,\n sort: str = 'newest_listings', page: int = 1,\n ) -> str:\n with self.session.get(\n self.from_root(f'for-sale/property/{query.lower()}/'),\n params={\n 'page_size': 25,\n 'q': query,\n 'radius': radius,\n 'results_sort': sort,\n 'pn': page,\n }\n ) as resp:\n resp.raise_for_status()\n return resp.text\n\n def load(self, html: str) -> List[JSON]:\n script = self.load_script(html)\n data = json.loads(script.string)\n return data['props']['initialProps']['pageProps']['regularListingsFormatted']\n\n @classmethod\n def serialise(cls, listings: Iterable[JSON]) -> Iterable[JSON]:\n for listing in listings:\n yield {\n 'listing_id': listing['listingId'],\n 'name_title': listing['title'],\n 'names': listing['branch']['name'],\n 'addresses': listing['address'],\n 'agent': cls.from_root(listing['branch']['branchDetailsUri']),\n 'phone_no': listing['branch']['phone'],\n 'picture': listing['image']['src'],\n 'prices': listing['price'],\n 'listed_on': listing['publishedOn'],\n 'listing_detail_link': cls.from_root(listing['listingUris']['detail']),\n }\n\n def run(\n self,\n query: str = 'London', radius: int = 0, sort: str = 'newest_listings',\n ) -> Iterable[JSON]:\n for page in range(1, 5):\n yield from self.serialise(\n self.load(\n self.fetch(query, radius, sort, page)\n )\n )\n\n @staticmethod\n def to_csv(results: Iterable[JSON], filename: str = 'zoopla.csv') -> None:\n with open(filename, 'w', newline='') as csv_file:\n first = next(results)\n writer = csv.DictWriter(csv_file, fieldnames=first.keys())\n writer.writeheader()\n writer.writerow(first)\n writer.writerows(results)\n\n\nif __name__ == '__main__':\n scraper = ZooplaScraper()\n scraper.to_csv(scraper.run())\n</code></pre>\n<h2>Experimental</h2>\n<p>This is an experimental, alternate implementation that:</p>\n<ul>\n<li>Streams the HTTP response and does not need the entire response content to complete</li>\n<li>Streams the parsed HTML elements and does not need the entire document tree to complete</li>\n<li>Streams the JSON body and does not need the entire dictionary tree to complete</li>\n</ul>\n<p>It is somewhat iterator-heavy, and built more as a proof of concept to demonstrate that this is possible. Advantages include that worst-case memory usage should be reduced, and that BeautifulSoup is no longer needed. Disadvantages include that a new dependency, JsonSlicer, is needed; and this <em>might</em> introduce subtle HTTP inefficiencies from connections that are reset before complete response transmission.</p>\n<pre><code>import csv\nimport logging\nfrom functools import partial\nfrom html.parser import HTMLParser\nfrom typing import Any, Dict, Iterable, Tuple, Optional\nfrom urllib.parse import urljoin\n\nfrom jsonslicer import JsonSlicer\nfrom requests import Session, Response\n\nJSON = Dict[str, Any]\n\n\nclass StreamParser(HTMLParser):\n def __init__(self, resp: Response):\n resp.raise_for_status() # If the response failed, it can't be parsed\n self.resp = resp # Keep the response so we can stream from it\n self.in_tag = False # Parser state: if we're in the script tag\n self.done = False # Whether we're done the script tag\n self.queue = [] # Queue of text element chunks in the script\n super().__init__() # Initialize the base parser\n\n def __enter__(self):\n # Start the data chunk iterator\n self.chunks = self.data_chunks()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n # When we're done, tell the HTTP response stream to close\n self.resp.close()\n\n def data_chunks(self) -> Iterable[str]:\n # Stream in arbitrary-sized chunks from the response\n for chunk in self.resp.iter_content(\n chunk_size=None, # Get whatever chunks are sent our way\n decode_unicode=True, # Needed for HTMLParser compatibility\n ):\n logging.debug(\n f'{len(chunk)}-character chunk: '\n f'{chunk[:10]}...{chunk[-10:]}'\n )\n # Feed this chunk to the parser, which will in turn call our handle\n # methods and populate the queue\n self.feed(chunk)\n yield from self.queue\n self.queue.clear()\n\n # We only care about one tag. Once that's parsed, we're done\n # iterating\n if self.done:\n break\n\n def read(self, n: Optional[int] = -1) -> str:\n # Will be called by JsonSlicer. We only support partial reads for\n # efficiency's sake; we do not build up our own buffer string.\n if n is None or n < 0:\n raise NotImplementedError('Read-to-end not supported')\n try:\n return next(self.chunks)\n except StopIteration:\n return '' # end of stream\n\n def handle_starttag(self, tag: str, attrs: Iterable[Tuple[str, str]]):\n self.in_tag = tag == 'script' and any(\n k == 'id' and v == '__NEXT_DATA__' for k, v in attrs\n )\n\n def handle_data(self, data: str) -> None:\n if self.in_tag:\n self.queue.append(data)\n\n def handle_endtag(self, tag: str) -> None:\n if self.in_tag:\n self.in_tag = False\n self.done = True\n\n def __iter__(self) -> Iterable[JSON]:\n # Iterating over this object will magically produce individual listing\n # dictionaries. We're an iterator; we delegate to the JsonSlicer\n # iterator; and it in turn invokes read() which uses our data_chunks\n # iterator.\n return JsonSlicer(file=self, path_prefix=(\n 'props', 'initialProps', 'pageProps', 'regularListingsFormatted', None,\n ))\n\n\nclass ZooplaScraper:\n ROOT = 'https://zoopla.co.uk'\n from_root = partial(urljoin, ROOT)\n\n def __init__(self):\n self.session = Session()\n\n def fetch(\n self, query: str = 'London', radius: int = 0,\n sort: str = 'newest_listings', page: int = 1,\n ) -> StreamParser:\n\n resp = self.session.get(\n self.from_root(f'for-sale/property/{query.lower()}/'),\n params={\n 'page_size': 25,\n 'q': query,\n 'radius': radius,\n 'results_sort': sort,\n 'pn': page,\n },\n stream=True,\n )\n\n return StreamParser(resp)\n\n @classmethod\n def serialise(cls, listing: JSON) -> JSON:\n # Convert from the site's representation of a listing dict to our own\n return {\n 'listing_id': listing['listingId'],\n 'name_title': listing['title'],\n 'names': listing['branch']['name'],\n 'addresses': listing['address'],\n 'agent': cls.from_root(listing['branch']['branchDetailsUri']),\n 'phone_no': listing['branch']['phone'],\n 'picture': listing['image']['src'],\n 'prices': listing['price'],\n 'listed_on': listing['publishedOn'],\n 'listing_detail_link': cls.from_root(listing['listingUris']['detail']),\n }\n\n def run(\n self,\n query: str = 'London', radius: int = 0, sort: str = 'newest_listings',\n max_pages: int = 4,\n ) -> Iterable[JSON]:\n for page in range(1, max_pages + 1):\n with self.fetch(query, radius, sort, page) as stream:\n for n_listings, data in enumerate(stream):\n yield self.serialise(data)\n logging.info(f'Page {page}: {n_listings} listings')\n\n @staticmethod\n def to_csv(results: Iterable[JSON], filename: str = 'zoopla.csv') -> None:\n with open(filename, 'w', newline='') as csv_file:\n first = next(results)\n writer = csv.DictWriter(csv_file, fieldnames=first.keys())\n writer.writeheader()\n writer.writerow(first)\n writer.writerows(results)\n logging.info(f'Write to {filename} complete')\n\n\nif __name__ == '__main__':\n # Will include debugging statements from urllib3\n logging.basicConfig(level=logging.INFO) # Switch to DEBUG for more verbosity\n\n scraper = ZooplaScraper()\n scraper.to_csv(scraper.run())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:29:49.647",
"Id": "260987",
"ParentId": "260953",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-19T20:55:55.703",
"Id": "260953",
"Score": "3",
"Tags": [
"python-3.x",
"json",
"web-scraping",
"beautifulsoup"
],
"Title": "Refactor Web Scraper"
}
|
260953
|
<p>I have wrote following solution for one answer but I want to refactor to make it more simple and readable.</p>
<p>I am receiving params</p>
<pre><code>sample_params = [{ user_id: 1, email: 'example1@example.com' },
{ user_id: 5, email: 'example5@example.com' },
{ user_id: 13, email: 'example13@example.com'}]
</code></pre>
<p>I want to create following hash to replace emails received from params</p>
<pre><code>[
{department_id: 1, users: [{user_id: 1, email: 'example1@example.com'},
{user_id: 5, email: 'example5@example.com'}]},
{department_id: 2, users: [{ user_id: 13, email: 'example13@example.com']
</code></pre>
<p>I am retrieving data from db using following codes</p>
<pre><code>data =
User
.where(id: sample_params.pluck(:user_id))
.pluck(:department_id, :id)
.group_by(&:first).map do |department_id, users|
{ department_id: department_id,
users: users.map { |_, id| id } }
end
</code></pre>
<p>and then I am creating hash using following</p>
<pre><code>result = []
data.each do |department|
department_users = []
department[:users].each do |user|
emails = sample_params.select { |user| user[:user_id] == 1 }[0][:email];
department_users << { id: user, emails: emails }
end; result << {department_id: department[:department_id], users: department_users}
end
</code></pre>
<p>How can I refactor to get following benefits</p>
<ul>
<li>Easy to read</li>
<li>less number of lines</li>
<li>Performance It has one query of sql so not an issue but on memory I am saving all in array.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:41:25.153",
"Id": "514994",
"Score": "0",
"body": "I changed title but I want to refactor code so it was part of title but now removed it."
}
] |
[
{
"body": "<p>Not sure if it's what you're looking for, in terms of readability:</p>\n<pre><code>data = User.where(id: sample_params.pluck(:user_id))\n .pluck(:department_id, :id).group_by {|u| u.shift }\n\nresults = data.map do |department_id, user_ids|\n users = user_ids.flatten.map do |id| \n email = sample_params.find { |user| user[:user_id] == id }[:email]\n {user_id: id, email: email}\n end\n { department_id: department_id, users: users }\nend\n</code></pre>\n<p>About saving memory because of the array, there will be always the queried data to the db in memory, besides this new array you're generating. The garbage collector won't take care of all these until your http request has been finished, so I'm not sure if there's something here you can do to improve the use of space.<br />\nIf this is the case where there are thousands of users mapped to this json, maybe you should consider to use <a href=\"https://api.rubyonrails.org/v6.1.3.1/classes/ActiveRecord/Batches.html#method-i-find_each\" rel=\"nofollow noreferrer\"><code>.find_each</code></a>, maybe <a href=\"https://guides.rubyonrails.org/caching_with_rails.html\" rel=\"nofollow noreferrer\">caching data</a> or another approach, but only you know what's the nature of the data you're querying.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T11:14:21.347",
"Id": "515295",
"Score": "0",
"body": "I think this enough as it already make little bit improvement and readability. You are right but we don't have much data it is in params so there would be mostly 10-20 users to be updated. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T03:07:01.177",
"Id": "261123",
"ParentId": "260961",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261123",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T03:23:58.157",
"Id": "260961",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"hash"
],
"Title": "How to reduce code in hash created using Database and Params in rails"
}
|
260961
|
<p>I thought this community is better place to ask my question so I ask here rather than at StackOverflow.
Recently, I learned that <code>Numba</code> can make Python function which uses <code>numpy</code> modules and <code>for</code> loops super faster so I was trying to implement it to my code in order to optimize execution time. However, ironically, using it made the code execution time much slower. Following codes show the comparison between 1) code using Numba and 2) original code.</p>
<p>Also, I use 2 data as an input (<code>numpy.ndarray</code>) with names <code>n</code> and <code>e</code> which are both <code>float32</code> arrays of length 201. You can test my code with these data.</p>
<pre><code>n=np.array([0.00000000e+00, -2.90246233e-02, -2.24490568e-01,
-7.16749728e-01, -1.57171035e+00, -2.77444601e+00,
-4.22764540e+00, -5.76536274e+00, -7.17996216e+00,
-8.25780201e+00, -9.09192276e+00, -9.90472031e+00,
-1.06955252e+01, -1.14638758e+01, -1.22095718e+01,
-1.29326763e+01, -1.36334448e+01, -1.43122253e+01,
-1.49694138e+01, -1.56054220e+01, -1.62206211e+01,
-1.68152523e+01, -1.73894081e+01, -1.79430256e+01,
-1.84757977e+01, -1.89870377e+01, -1.94757748e+01,
-1.99407864e+01, -2.03805809e+01, -2.07932720e+01,
-2.11767120e+01, -2.15285759e+01, -2.18464222e+01,
-2.21277046e+01, -2.23698120e+01, -2.25701656e+01,
-2.27262192e+01, -2.28354397e+01, -2.28954563e+01,
-2.29041901e+01, -2.28599644e+01, -2.27614594e+01,
-2.26076698e+01, -2.23979702e+01, -2.21322174e+01,
-2.18107166e+01, -2.14341793e+01, -2.10038280e+01,
-2.05215683e+01, -1.99899464e+01, -1.94121590e+01,
-1.87920952e+01, -1.81344280e+01, -1.74445496e+01,
-1.67284374e+01, -1.59926023e+01, -1.52440386e+01,
-1.44902058e+01, -1.37389374e+01, -1.29982576e+01,
-1.22761898e+01, -1.15806122e+01, -1.09191751e+01,
-1.02992201e+01, -9.72764969e+00, -9.21087074e+00,
-8.75471401e+00, -8.36433029e+00, -8.04401970e+00,
-7.79723310e+00, -7.62662983e+00, -7.53405952e+00,
-7.52038527e+00, -7.58545780e+00, -7.72822046e+00,
-7.94686508e+00, -8.23878956e+00, -8.60053539e+00,
-9.02776337e+00, -9.51539421e+00, -1.00577345e+01,
-1.06485300e+01, -1.12809696e+01, -1.19478493e+01,
-1.26417017e+01, -1.33548985e+01, -1.40797272e+01,
-1.48085299e+01, -1.55338354e+01, -1.62484665e+01,
-1.69456844e+01, -1.76192360e+01, -1.82633667e+01,
-1.88728962e+01, -1.94433289e+01, -1.99709244e+01,
-2.04526272e+01, -2.08860626e+01, -2.12695827e+01,
-2.16023121e+01, -2.18841362e+01, -2.21156521e+01,
-2.22980556e+01, -2.24331856e+01, -2.25235310e+01,
-2.25722427e+01, -2.25830765e+01, -2.25602932e+01,
-2.25085907e+01, -2.24330215e+01, -2.23388729e+01,
-2.22315712e+01, -2.21166210e+01, -2.19994831e+01,
-2.18853989e+01, -2.17793064e+01, -2.16857681e+01,
-2.16088982e+01, -2.15522213e+01, -2.15185966e+01,
-2.15101852e+01, -2.15284405e+01, -2.15740509e+01,
-2.16469669e+01, -2.17463741e+01, -2.18707085e+01,
-2.20176525e+01, -2.21841602e+01, -2.23664932e+01,
-2.25603275e+01, -2.27608757e+01, -2.29629631e+01,
-2.31610470e+01, -2.33492279e+01, -2.35214043e+01,
-2.36715298e+01, -2.37937660e+01, -2.38824825e+01,
-2.39323406e+01, -2.39385643e+01, -2.38971081e+01,
-2.38046494e+01, -2.36585808e+01, -2.34572048e+01,
-2.31998024e+01, -2.28866425e+01, -2.25189037e+01,
-2.20986404e+01, -2.16287670e+01, -2.11129856e+01,
-2.05556641e+01, -1.99617062e+01, -1.93365269e+01,
-1.86859131e+01, -1.80159054e+01, -1.73325996e+01,
-1.66420517e+01, -1.59501858e+01, -1.52626762e+01,
-1.45847788e+01, -1.39213161e+01, -1.32765999e+01,
-1.26543894e+01, -1.20577383e+01, -1.14889488e+01,
-1.09496098e+01, -1.04407034e+01, -9.96269608e+00,
-9.51548195e+00, -9.09836483e+00, -8.71012592e+00,
-8.34911537e+00, -8.01335907e+00, -7.70055103e+00,
-7.40815973e+00, -7.13349152e+00, -6.87368536e+00,
-6.62575817e+00, -6.38672686e+00, -6.15366173e+00,
-5.92375469e+00, -5.69433641e+00, -5.46290398e+00,
-5.22722960e+00, -4.98536777e+00, -4.73564768e+00,
-4.47674179e+00, -4.20764303e+00, -3.92769504e+00,
-3.63661599e+00, -3.33451986e+00, -3.02191830e+00,
-2.61823845e+00, -2.09174943e+00, -1.52332258e+00,
-9.90778685e-01, -5.54975927e-01, -2.49610826e-01,
-7.68868327e-02, -9.74494778e-03, 0.00000000e+00], dtype=float32)
e=np.array([0.00000000e+00, -2.39476264e-02, -1.95374981e-01,
-6.55762613e-01, -1.50696099e+00, -2.77968431e+00,
-4.41394567e+00, -6.25681400e+00, -8.07964897e+00,
-9.61341381e+00, -1.09259253e+01, -1.22610502e+01,
-1.36115866e+01, -1.49705763e+01, -1.63314114e+01,
-1.76879139e+01, -1.90344372e+01, -2.03657932e+01,
-2.16773891e+01, -2.29651966e+01, -2.42257977e+01,
-2.54562702e+01, -2.66542950e+01, -2.78181095e+01,
-2.89464245e+01, -3.00384007e+01, -3.10936413e+01,
-3.21121521e+01, -3.30942726e+01, -3.40405350e+01,
-3.49516640e+01, -3.58286057e+01, -3.66724052e+01,
-3.74841537e+01, -3.82649269e+01, -3.90158615e+01,
-3.97381325e+01, -4.04328537e+01, -4.11011162e+01,
-4.17439575e+01, -4.23624077e+01, -4.29573746e+01,
-4.35296898e+01, -4.40801773e+01, -4.46096611e+01,
-4.51190338e+01, -4.56091652e+01, -4.60809402e+01,
-4.65354042e+01, -4.69738083e+01, -4.73974800e+01,
-4.78078232e+01, -4.82064171e+01, -4.85949020e+01,
-4.89749336e+01, -4.93481598e+01, -4.97163124e+01,
-5.00811615e+01, -5.04445229e+01, -5.08082886e+01,
-5.11744041e+01, -5.15448380e+01, -5.19215736e+01,
-5.23065796e+01, -5.27017555e+01, -5.31089096e+01,
-5.35298271e+01, -5.39661331e+01, -5.44192924e+01,
-5.48905334e+01, -5.53807945e+01, -5.58906784e+01,
-5.64204826e+01, -5.69702682e+01, -5.75397987e+01,
-5.81285400e+01, -5.87356644e+01, -5.93601112e+01,
-6.00004807e+01, -6.06552086e+01, -6.13225784e+01,
-6.20007973e+01, -6.26880646e+01, -6.33824730e+01,
-6.40822220e+01, -6.47855148e+01, -6.54907074e+01,
-6.61962433e+01, -6.69004745e+01, -6.76018448e+01,
-6.82988281e+01, -6.89898987e+01, -6.96735458e+01,
-7.03481979e+01, -7.10121918e+01, -7.16639557e+01,
-7.23019028e+01, -7.29244461e+01, -7.35300446e+01,
-7.41171265e+01, -7.46841965e+01, -7.52298584e+01,
-7.57526855e+01, -7.62513962e+01, -7.67248459e+01,
-7.71719666e+01, -7.75918121e+01, -7.79834213e+01,
-7.83460007e+01, -7.86789093e+01, -7.89816742e+01,
-7.92538223e+01, -7.94950333e+01, -7.97050018e+01,
-7.98835449e+01, -8.00305862e+01, -8.01461563e+01,
-8.02304077e+01, -8.02836456e+01, -8.03062363e+01,
-8.02987900e+01, -8.02619324e+01, -8.01963196e+01,
-8.01027451e+01, -7.99821243e+01, -7.98353271e+01,
-7.96633453e+01, -7.94671249e+01, -7.92478104e+01,
-7.90065460e+01, -7.87445374e+01, -7.84630661e+01,
-7.81635818e+01, -7.78474579e+01, -7.75161743e+01,
-7.71711807e+01, -7.68137894e+01, -7.64451599e+01,
-7.60662384e+01, -7.56776810e+01, -7.52800369e+01,
-7.48734894e+01, -7.44580231e+01, -7.40333176e+01,
-7.35989304e+01, -7.31542664e+01, -7.26986237e+01,
-7.22311020e+01, -7.17508316e+01, -7.12570038e+01,
-7.07489014e+01, -7.02259598e+01, -6.96877289e+01,
-6.91337738e+01, -6.85638351e+01, -6.79777908e+01,
-6.73756409e+01, -6.67574463e+01, -6.61231613e+01,
-6.54727097e+01, -6.48059692e+01, -6.41226959e+01,
-6.34223747e+01, -6.27042465e+01, -6.19672279e+01,
-6.12100372e+01, -6.04309807e+01, -5.96278610e+01,
-5.87980995e+01, -5.79385986e+01, -5.70459251e+01,
-5.61163254e+01, -5.51455879e+01, -5.41292572e+01,
-5.30626335e+01, -5.19408646e+01, -5.07591400e+01,
-4.95127220e+01, -4.81970291e+01, -4.68076973e+01,
-4.53407593e+01, -4.37926598e+01, -4.21605453e+01,
-4.04422188e+01, -3.86362457e+01, -3.67420464e+01,
-3.47598801e+01, -3.26910439e+01, -3.05377808e+01,
-2.83032646e+01, -2.59916306e+01, -2.36078224e+01,
-2.05195694e+01, -1.64658623e+01, -1.20626736e+01,
-7.90684271e+00, -4.47298717e+00, -2.03672314e+00,
-6.36906505e-01, -8.22197124e-02, 0.00000000e+00], dtype=float32)
</code></pre>
<p>##########################################################################</p>
<pre><code># import libraries
import numpy as np
from numba import jit
import time
</code></pre>
<h2>Original code</h2>
<p>I define 2 functions (<code>rotate_ne_rt</code> and <code>Grid_Search</code>) which take <code>n</code> and <code>e</code> as inputs.</p>
<pre><code>def rotate_ne_rt(n, e, ba):
if len(n) != len(e):
raise TypeError("North and East component have different length.")
if ba < 0 or ba > 360:
raise ValueError("Back Azimuth should be between 0 and 360 degrees.")
ba = np.radians(ba)
r = - e * np.sin(ba) - n * np.cos(ba)
t = - e * np.cos(ba) + n * np.sin(ba)
return r, t
def Grid_Search(n, e):
energy_1=[]
for angle in np.arange(0, 360, 1):
r, t=rotate_ne_rt(n, e, ba=angle)
average_energy=np.mean(t**2) # Average transverse energy to be minimized
energy_1.append(average_energy)
best_angle=np.argmin(np.array(energy_1))
return best_angle
</code></pre>
<p>Following script shows the time spent in execution.</p>
<pre><code>start=time.time()
print(Grid_Search(n, e))
end=time.time()
print("Elapsed (after compilation) = %s" % (end - start))
</code></pre>
<p><a href="https://i.stack.imgur.com/5JSpS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5JSpS.png" alt="no numba" /></a></p>
<h2>Code using <code>Numba</code></h2>
<p>I define 2 functions (<code>rotate_ne_rt</code> and <code>Grid_Search</code>) which take <code>n</code> and <code>e</code> as inputs.</p>
<pre><code>@jit(nopython=True)
def rotate_ne_rt(n, e, ba):
if len(n) != len(e):
raise TypeError("North and East component have different length.")
if ba < 0 or ba > 360:
raise ValueError("Back Azimuth should be between 0 and 360 degrees.")
ba = np.radians(ba)
r = - e * np.sin(ba) - n * np.cos(ba)
t = - e * np.cos(ba) + n * np.sin(ba)
return r, t
@jit(nopython=True)
def Grid_Search(n, e):
energy_1=[]
for angle in np.arange(0, 360, 1):
r, t=rotate_ne_rt(n, e, ba=angle)
average_energy=np.mean(t**2) # Average transverse energy to be minimized
energy_1.append(average_energy)
best_angle=np.argmin(np.array(energy_1))
return best_angle
</code></pre>
<p>Following script shows the time spent in execution.</p>
<pre><code>start=time.time()
print(Grid_Search(n, e))
end=time.time()
print("Elapsed (after compilation) = %s" % (end - start))
</code></pre>
<p><a href="https://i.stack.imgur.com/IZPoi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IZPoi.png" alt="with numba" /></a></p>
<p>As you can see, execution is almost 60 times slower when using <code>numba</code> which is undesirable.
What am I misunderstanding about <code>numba</code> for this case and is there a way to efficiently use <code>numba</code> to make my code much faster than not using it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T06:40:51.063",
"Id": "514986",
"Score": "1",
"body": "We require that the poster know why the code is written the way it is. 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-05-20T06:42:48.067",
"Id": "514987",
"Score": "0",
"body": "@BCdotWEB I am new to this community so I was unaware of it. I will try reading the guides."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T10:03:40.797",
"Id": "515001",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>Actually, it is embarrassing to answer my question, but I think the problem was about the initial compilation time using <code>numba</code>. After I executed function <code>Grid_Search</code> once and executed it again, it outperforms original code in terms of execution time.</p>\n<p><a href=\"https://i.stack.imgur.com/6EnRR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6EnRR.png\" alt=\"fixed\" /></a></p>\n<p>If you have other suggestions to make execution time faster, please tell me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T15:18:52.173",
"Id": "515036",
"Score": "1",
"body": "It's not embarassing to answer your own question, it happens :) However, I think that in the future this is the kind of test you should run before posting you question ahah"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T06:41:06.117",
"Id": "260965",
"ParentId": "260964",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T06:20:28.810",
"Id": "260964",
"Score": "3",
"Tags": [
"performance",
"python-3.x",
"comparative-review",
"numpy",
"numba"
],
"Title": "Using Numba works slower than not using it for my Python code"
}
|
260964
|
<p>My code for a LocalBinaryPatern in python is running very slow. I tried optimizing it with tips from online. I'am still getting used to python, and programming in General so any tips are very welcome! Here is the code:</p>
<pre><code>def localbinarypattern(image, radius=2):
h, w = image.shape
if radius == 1:
return 0
else:
abase = math.pi/4
xshift, yshift = [0 for _ in range(8)], [0 for _ in range(8)]
for i in range(8):
xshift[i] = - radius * sin(i*abase)
yshift[i] = radius * cos(i*abase)
feat = [0 for _ in range(255)]
lbp = [0 for _ in range(8)]
base = [1, 2, 4,8, 16, 32, 64, 128]
for y in (range(radius, (h-radius))):
for x in (range(radius, (w-radius))):
lbp = [0 for _ in range(8)]
for i in range(8):
cx = xshift[i]+x
cy = yshift[i]+y
ry = int(cy+0.5)
rx = int(cx + 0.5)
if image[ry][rx] > 0:
lbp[i] = 1
bits = 0
for i in range(8):
bits += int(lbp[i]*base[i])
if bits < 255:
feat[bits] += 1
sum_lbp = 0
for i in range(len(feat)):
sum_lbp += feat[i]
if sum_lbp ==0:
print ("warning: the sum of LBP feature is zero!\n")
else:
for i in range(len(feat)):
feat[i] /= sum_lbp
return feat
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:00:41.870",
"Id": "514990",
"Score": "0",
"body": "small tip: `feat = [0 for _ in range(255)]` => `feat = [0]*255`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:01:44.443",
"Id": "514991",
"Score": "0",
"body": "also `sum_lbp = 0\n for i in range(len(feat)):\n sum_lbp += feat[i]` => `sum_lbp = sum(feat)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:01:57.840",
"Id": "514992",
"Score": "0",
"body": "but this question seems best suited for codereview"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:03:57.713",
"Id": "514993",
"Score": "0",
"body": "Thanks had not heard of codereview! beter check it out thanks for the tips though!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:52:54.537",
"Id": "515022",
"Score": "1",
"body": "Hey, welcome to Code Review! Can you please add your imports, currently it is unclear if e.g. `sin` is from `math` or `numpy`. If you could also add some example in-/output, then answering this question would get a lot easier."
}
] |
[
{
"body": "<h1>No <code>else</code> after <code>return</code></h1>\n<p>You have code like</p>\n<pre><code>if x:\n return 0\nelse:\n ...\n</code></pre>\n<p>Just drop the <code>else</code>, because you previously already returned. Use else branches only if the code converges again after the two branches, not if you exit the function (<code>raise</code>, <code>return</code> or <code>exit()</code>).</p>\n<h1>Double Initialization</h1>\n<p>You have code creating two lists:</p>\n<pre><code> xshift, yshift = [0 for _ in range(8)], [0 for _ in range(8)]\n\n for i in range(8):\n xshift[i] = - radius * sin(i*abase)\n yshift[i] = radius * cos(i*abase)\n</code></pre>\n<p>You can combine those:</p>\n<pre><code>xshift = [-radius * sin(i * abase) for i in range(8)]\nxshift = [ radius * cos(i * abase) for i in range(8)]\n</code></pre>\n<h1>Further Dead Code</h1>\n<ul>\n<li>Initialization of <code>h, w</code> at the beginning can be moved down, after checking the radius.</li>\n<li><code>lbp = [0 for _ in range(8)]</code> -- you're doing that once before the loop and then in every iteration.</li>\n</ul>\n<h1>C-isms in Loop Iteration</h1>\n<p>It looks like you're used to writing in C (or a similar language) where you can only access an array by index. It shows e.g. in this code:</p>\n<pre><code>sum_lbp = 0\nfor i in range(len(feat)):\n sum_lbp += feat[i]\n</code></pre>\n<p>In Python, you would write this loop like this instead:</p>\n<pre><code>sum_lbp = 0\nfor value in feat:\n sum_lbp += value\n</code></pre>\n<p>An additional minor improvement specific to this case is to write it in one line:</p>\n<pre><code>sum_lbp = sum(feat)\n</code></pre>\n<p>Get familiar with the tools Python gives you at hand, they can make your life easier. In this case it's just the <code>sum()</code> function, but also you're not making use of e.g. dictionaries, which could make this code cleaner.</p>\n<h1>Redundant Parentheses</h1>\n<p>Here are two redundant pairs of partheses:</p>\n<pre><code>for x in (range(radius, (w-radius))):\n</code></pre>\n<p>Same code without them:</p>\n<pre><code>for x in range(radius, w - radius):\n</code></pre>\n<h1>Redundant Type Conversions</h1>\n<p>Looking at <code>int(lbp[i]*base[i])</code>, I wonder why you <code>int()</code> the product. Both only contain integers, as far as I can tell.</p>\n<h1>Off-by-one Error</h1>\n<p>This code looks suspicious:</p>\n<pre><code>feat = [0 for _ in range(255)]\n...\nbits = 0\nfor i in range(8):\n bits += int(lbp[i]*base[i])\n\nif bits < 255:\n feat[bits] += 1\n</code></pre>\n<p>Since an octet can take 256 different values, I'd expect <code>feat</code> to have 256 values as well. That way you could eliminate the <code>bits < 255</code> check. Another way to simplify this is to reuse the <code>sum()</code> function again. Also, <code>base[i]</code> is <code>1 << i</code> and <code>lbp[i]</code> is either zero or one, so you can also write this <code>lbp[i] << i</code> eliminating <code>base</code> entirely.</p>\n<h1>Further Redundant Code</h1>\n<p>Look at the inner loop:</p>\n<pre><code># init `lbp` with zeroes\nlbp = [0 for _ in range(8)]\n# actually fill `lbp`\nfor i in range(8):\n ...\n if image[ry][rx] > 0:\n lbp[i] = 1\n# compute values from `lbp` \nbits = 0\nfor i in range(8):\n bits += int(lbp[i]*base[i])\n</code></pre>\n<p>This uses too many temporaries. Instead, try this approach:</p>\n<pre><code>bits = 0\nfor i in range(8):\n ...\n if image[ry][rx] > 0:\n bits += 1 << i\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:17:57.277",
"Id": "260982",
"ParentId": "260967",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T07:58:50.777",
"Id": "260967",
"Score": "0",
"Tags": [
"python",
"performance"
],
"Title": "My code for a LocalBinaryPatern in python is running very slow. Any tips?"
}
|
260967
|
<p>I need some help to evaluate whether I am doing it right. The scenario is, a 3rd party application is sending a webhook request after a successful payment but the problem is that sometimes this application may send the same notification more than once. So it is recommended to ensure that implementation of the webhook is idempotent. So steps that I am implementing for this are if signature is correct (assume it is correct), find orders record in the database using <code>orderId</code> in the request params. Please note: <code>orderId</code> in request params is <code>payment_gateway_order_identifier</code> in orders table. If <code>txStatus</code> is <code>'SUCCESS'</code> AND haven't already processed COLLECTION payment for this same order, create payments record. 201 response with nothing in the response body. Otherwise, 201 response with nothing in the response body. Otherwise, 422 response with <code>{message: "Signature is incorrect"}</code> in response body.</p>
<h2>views.py</h2>
<pre><code> @api_view(['POST'])
def cashfree_request(request):
if request.method == 'POST':
data=request.POST.dict()
payment_gateway_order_identifier= data['orderId']
amount = data['orderAmount']
transaction_status = data['txStatus']
signature = data['signature']
if(computedsignature==signature): #assume it to be true
order=Orders.objects.get(
payment_gateway_order_identifier=payment_gateway_order_identifier)
if transaction_status=='SUCCESS':
try:
payment= Payments.objects.get(orders=order)
return Response({"Payment":"Done"},status=status.HTTP_200_OK)
except (Payments.DoesNotExist):
payment = Payments(orders=order,amount=amount,datetime=datetime)
payment.save()
return Response(status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)
</code></pre>
<h2>models.py</h2>
<pre><code> class Orders(models.Model):
id= models.AutoField(primary_key=True)
amount = models.DecimalField(max_digits=19, decimal_places=4)
payment_gateway_order_identifier = models.UUIDField(
primary_key=False,default=uuid.uuid4,editable=False,unique=True)
class Payments(models.Model):
id = models.AutoField(primary_key=True)
orders = models.ForeignKey(Orders, on_delete=models.CASCADE)
amount = models.DecimalField(max_digits=19, decimal_places=4, verbose_name='Price in INR')
datetime = models.DateTimeField(auto_now=False,auto_now_add=False)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T15:07:49.583",
"Id": "515034",
"Score": "2",
"body": "Based on your wording, _sometimes this application may send the same notification more than once_ is a little ambigious. Is this an issue you need help fixing (in which case this question is off-topic and needs to move to StackOverflow)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T15:08:45.390",
"Id": "515035",
"Score": "1",
"body": "Otherwise, if it's true that _I need help to evaluate whether I am doing it right or is there a better way_ and your code _is_ already doing what it should, then this question is on-topic but you might want to revisit its wording to make that clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:30:09.443",
"Id": "515044",
"Score": "1",
"body": "No actually i just need an evaluation weather i have written the code in correct way though it is working fine."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:07:10.010",
"Id": "260968",
"Score": "1",
"Tags": [
"python",
"database",
"django",
"web-services",
"django-template-language"
],
"Title": "processing webhook request coming from a 3rd party application"
}
|
260968
|
<p>Solved task is pretty straightforward: mounting partition if not mounted already, to start executable.</p>
<p>There is a couple of checks and notifications because it is supposed to be launched from X and there are no way to see <code>stdout</code>/<code>stderr</code> stream. I have started with much larger version and a lot of error handling, that is why it has a function despite being so simple. On the other hand, it is much more cleaner of what is going on, when you read it and it will be easier to come back to it later on.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash
DEVICE="/dev/sda5"
PARTITION="/mnt/Games"
EXECUTABLE="$PARTITION/MultiMC/MultiMC"
launch() {
if ! findmnt "$PARTITION"; then
DETAILS=`SUDO_ASKPASS="$(which ssh-askpass)" sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1`
[ $? -ne 0 ] && return 1
fi
notify-send "Launching.."
exec "$EXECUTABLE"
}
launch || notify-send "Launching failed" "$DETAILS"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T09:52:19.450",
"Id": "514997",
"Score": "1",
"body": "Terminology: a _partition_ is a part of a disk (such as `/dev/sda5`). The filesystem directory to which we attach its filesystem (`/mnt/Games`) is called a __mount point__."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T09:54:02.020",
"Id": "514998",
"Score": "1",
"body": "Does your system have `pmount`? That could be configured to let ordinary users mount the filesystem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T10:44:06.387",
"Id": "515003",
"Score": "0",
"body": "@TobySpeight no I doesn't. I have some trouble configuring `fstab` to mount that partition that is why I ended up with writing the wrapper. Literally same `/dev/sda5 /mnt/Games` works if you will execute `sudo mount` command but didn't not work if you will place it into fstab under \"defaults,user\" and do `mount` (have some permission issues launching executable)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T10:46:56.017",
"Id": "515004",
"Score": "0",
"body": "That should work for you - might be worth describing that problem on [unix.se] to find out if you can solve it. Might help reduce the complexity here!"
}
] |
[
{
"body": "<h2>Shell Errorhandling</h2>\n<p>There's one thing I would have done differently (though it's not relevant to the small piece of code here) and that is the error handling inside the function.</p>\n<ol>\n<li>You can use <code>set -e</code> to automatically exit the function, you could eliminate the <code>[ $? -ne 0 ] && return 1</code> line with that.</li>\n<li>Optionally, I would only have set that flag inside the function only, using <code>local -</code>.</li>\n</ol>\n<h2>Backticks</h2>\n<p>Another thing is the use of backticks. I believe you could just write that</p>\n<pre><code>DETAILS=$(\n SUDO_ASKPASS="$(which ssh-askpass)" \\\n sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1\n)\n</code></pre>\n<p>avoiding deeply indented code like that and making it a bit easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T05:12:51.107",
"Id": "515078",
"Score": "0",
"body": "`set -e` is not an option as you have no chance to sent notification about what went wrong because it terminates bash process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T05:21:27.000",
"Id": "515080",
"Score": "0",
"body": "Can you explain what you mean by `local -` ? I have a trouble to find out what it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:12:54.677",
"Id": "515086",
"Score": "0",
"body": "It's in the Bash manpage, it causes a subsequent `set` call to be only effective locally."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:18:49.563",
"Id": "260978",
"ParentId": "260970",
"Score": "3"
}
},
{
"body": "<p><code>[ $? -ne 0 ]</code> is a well-known over-complication - you can replace that with a simple <code>||</code> in the pipeline:</p>\n<pre><code>DETAILS=`SUDO_ASKPASS="$(which ssh-askpass)" sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1` \\\n || return $?\n</code></pre>\n<p>And in fact we can have a whole chain here:</p>\n<pre><code>launch() {\n findmnt "$PARTITION" \\\n || DETAILS=`SUDO_ASKPASS="$(which ssh-askpass)" sudo --askpass mount "$DEVICE" "$PARTITION" 2>&1` \\\n || return $?\n notify-send "Launching.."\n exec "$EXECUTABLE"\n}\n</code></pre>\n<hr />\n<p>If you have <code>chronic</code> installed, that could replace the tedious saving of output into <code>DETAILS</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>NAME\n chronic - runs a command quietly unless it fails\n\nSYNOPSIS\n chronic [-ev] COMMAND...\n\nDESCRIPTION\n chronic runs a command, and arranges for its standard out and standard\n error to only be displayed if the command fails (exits nonzero or\n crashes). If the command succeeds, any extraneous output will be\n hidden.\n</code></pre>\n<p>So,</p>\n<pre><code>launch() {\n findmnt "$PARTITION" \\\n || SUDO_ASKPASS="$(which ssh-askpass)" \\\n chronic sudo --askpass mount "$DEVICE" "$PARTITION" \\\n || return $?\n notify-send "Launching.."\n exec "$EXECUTABLE"\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:21:52.077",
"Id": "515041",
"Score": "0",
"body": "Thanks for the chronic tip. That looks handy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T02:32:22.817",
"Id": "515075",
"Score": "1",
"body": "You have forgot about `DETAILS` variable in case of chronic or how to send output to `notify-send` without this var?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:25:35.177",
"Id": "260979",
"ParentId": "260970",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260979",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:45:21.647",
"Id": "260970",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Wrapper to mount partition before launching executable"
}
|
260970
|
<p>I have been playing around with numpy and matplotlib.</p>
<p>My little project was to create a scatter plot ranging from -1 to 1 on both X and Y, but where the shading is done with the XOR scheme.</p>
<p>The following is the code that I have implemented (it is in a cell of a jupyter notebook, hence the trailing <code>;</code> after <code>plt.scatter</code>):</p>
<pre class="lang-py prettyprint-override"><code>arr_size = 2000
X = np.random.uniform(low=-1.0, high=1.0, size=(arr_size, arr_size))
colour = np.zeros(arr_size)
for i in range(arr_size):
if X[0, i] > 0 and X[1, i] < 0:
colour[i] = 1
elif X[0, i] < 0 and X[1, i] > 0:
colour[i] = 1
plt.scatter(X[0], X[1], c=colour);
</code></pre>
<p>The output that I generated was:</p>
<p><a href="https://i.stack.imgur.com/9P3r7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9P3r7.png" alt="enter image description here" /></a></p>
<p>Which is the desired output.</p>
<p>However, I am on a bit of a campaign to make my numpy code run faster (I am on an ML course and we have been taught to remove for loops wherever possible). Can anyone show me how to make this code more efficient?</p>
<p>Cheers</p>
|
[] |
[
{
"body": "<p>Since <code>(a < 0 and b > 0) or (a > 0 and b < 0)</code> can be summarized as <code>a*b < 0</code>, moreover <code>*</code> and <code><</code> work on vectors, we get the one-liner:</p>\n<pre><code>plt.scatter(X[0], X[1], c=X[0]*X[1] < 0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T09:17:04.227",
"Id": "260972",
"ParentId": "260971",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "260972",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T08:55:35.157",
"Id": "260971",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy",
"matplotlib"
],
"Title": "Removing Loop from Numpy XOR"
}
|
260971
|
<p>I am writing a Python code for KMeans clustering.</p>
<p>The aim of this post is to find out <strong>how I can make my below mentioned code optimal when the number of clusters is very large.</strong> I am dealing with <strong>data with tens of millions of samples and scores of features</strong>. The n<strong>umber of clusters that I am talking about is of the order of 500000</strong>. I have checked the correctness of the code by comparing that with results from scikit-learn's implementation of KMeans clustering.</p>
<p>I am aware that I can use sckit learn for KMeans clustering. But, I am writing my own custom Python code for a few purposes which include but are not limited to the below reasons.</p>
<ul>
<li>To be able to change distance functions for my specific work assignments : from Euclidean distance to <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.15.4028&rep=rep1&type=pdf" rel="noreferrer">Huang distance</a>.</li>
<li>To use this custom code for various other tasks like anomaly detection.</li>
</ul>
<p>Below is my code:</p>
<pre><code>class KMeans:
def __init__(self, arr, k):
self.arr = arr
self.k = k
# Main driver function
def loop_over_centers(self, max_iter):
# Choose random centroids.
random_centers = np.random.choice(len(self.arr), self.k, replace=False)
# Iterate till a certain max number of iterations.
for iteration in range(0, max_iter, 1):
cluster_dict = defaultdict(list)
if iteration == 0:
chosen_centers = random_centers
# Assign samples to cluster centers based on minimum distance
for i in range(len(self.arr)):
distance_list = []
for center in chosen_centers:
distance_list += [self.distance(self.arr[center], self.arr[i])]
cluster_dict[chosen_centers[np.argmin(distance_list)]] += [i]
chosen_centers = self.update_center(cluster_dict)
return cluster_dict
# Distance between two arrays
def distance(self, arr1, arr2):
return np.sqrt(np.sum(np.subtract(arr1, arr2) ** 2))
# Gives new centroids with each new iteration
def update_center(self, cluster_dict):
cluster_center = []
for cluster in list(cluster_dict.keys()):
cluster_list = []
# Find samples corresponding to each cluster.
for sample in cluster_dict[cluster]:
cluster_list += [self.arr[sample]]
# Mean of samples in a given cluster.
cluster_mean = np.mean(np.array(cluster_list), axis=0).tolist()
distance_from_mean = []
# Find which sample is closest to mean of cluster.
for sample in cluster_dict[cluster]:
distance_from_mean += [self.distance(cluster_mean, self.arr[sample])]
# Build an updated list of cluster centers.
cluster_center += [cluster_dict[cluster][np.argmin(distance_from_mean)]]
return cluster_center
arr = [[12, 3, 5], [1, 6, 7], [8, 92, 1], [6, 98, 2], [5, 90, 3], [29, 5, 6], [11,4,4], [30, 6, 5],]
testKMeans = KMeans(arr, 3)
testKMeans.loop_over_centers(1000)
</code></pre>
<p>In a real world case, <code>arr</code> will have tens of millions of samples and I would like to have about 500000 cluster centroids. At present the performance of code is okay when <code>arr</code> has tens of millions of samples and number of cluster centroids is small (10-20). But is very slow when the number of clusters is very large (hundreds of thousands).</p>
<p><strong>How can I improve the runtime performance of this code for large number of cluster centers?</strong>.</p>
|
[] |
[
{
"body": "<p>First, some Python improvements. You do repeated lookups of the kind <code>cluster_dict[cluster]</code>. If you were to directly iterate over <code>cluster_dict.values()</code> these would all be not needed. Also, list comprehensions are usually faster than building a simple list with a <code>for</code> loop. And finally, docstrings go inside the function:</p>\n<pre><code>def update_center(self, cluster_dict):\n """Gives new centroids with each new iteration."""\n cluster_center = []\n\n for cluster in cluster_dict.values():\n cluster_list = [self.arr[sample] for sample in cluster]\n\n # Mean of samples in a given cluster.\n cluster_mean = np.mean(np.array(cluster_list), axis=0).tolist()\n\n # Find which sample is closest to mean of cluster.\n smallest_distance_from_mean = np.argmin([self.distance(cluster_mean, sample)\n for sample in cluster_list])\n\n # Build an updated list of cluster centers.\n cluster_center.append(cluster[smallest_distance_from_mean])\n\n return cluster_center\n</code></pre>\n<p>Another small improvement is not to calculate the <code>sqrt</code> in your distance function, since you only ever need the minimum value, so the squared values work just fine.</p>\n<pre><code>def distance(self, arr1, arr2):\n """Squared distance between two arrays"""\n return np.sum(np.subtract(arr1, arr2) ** 2)\n</code></pre>\n<p>However, the greatest improvements are probably to be gained by not using lists everywhere, but to use <code>numpy</code> wherever you can:</p>\n<pre><code>class KMeans:\n def __init__(self, arr, k):\n self.arr = np.array(arr)\n self.k = k\n\n def loop_over_centers(self, max_iter):\n\n # Choose random centroids.\n chosen_centers = np.random.choice(len(self.arr), self.k, replace=False)\n\n # Iterate till a certain max number of iterations.\n for _ in range(max_iter):\n\n cluster_dict = defaultdict(list)\n\n # Assign samples to cluster centers based on minimum distance\n centers = self.arr[chosen_centers]\n for i, sample in enumerate(self.arr):\n closest_center = np.argmin(np.sum((centers - sample)**2, axis=1))\n cluster_dict[chosen_centers[closest_center]].append(i)\n chosen_centers = self.update_center(cluster_dict)\n\n return cluster_dict\n\n def update_center(self, cluster_dict):\n """Gives new centroids with each new iteration."""\n cluster_center = []\n \n for cluster in cluster_dict.values():\n samples = self.arr[cluster]\n # Mean of samples in a given cluster.\n cluster_mean = np.mean(samples, axis=0)\n closest_sample = np.argmin(np.sum((samples - cluster_mean)**2, axis=1))\n cluster_center.append(cluster[closest_sample])\n\n return cluster_center\n</code></pre>\n<p>Your code takes 391 ms ± 21.7 ms on my machine, the first two changes drop this down to 340 ms ± 15.9 ms and the final change to 145 µs ± 588 ns, <strong>faster by a factor 2700</strong>!</p>\n<p>You could go even further by doing this part without the <code>for</code> loop using only array operations as well:</p>\n<pre><code> for i, sample in enumerate(self.arr):\n closest_center = np.argmin(np.sum((centers - sample)**2, axis=1))\n cluster_dict[chosen_centers[closest_center]].append(i)\n</code></pre>\n<p>However, this will then take <code>k * len(arr) * dim(arr)</code> memory, which may be a bit too much if both are very large.</p>\n<p>Note: You can factor out the distance into a function again, I just don't want to rerun the timings...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:33:33.033",
"Id": "260980",
"ParentId": "260973",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260980",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T10:28:13.673",
"Id": "260973",
"Score": "7",
"Tags": [
"python",
"performance",
"algorithm",
"machine-learning"
],
"Title": "Optimize K-Mean for large number of clusters"
}
|
260973
|
<p>I have a simple class that listens click and draws two points on the page.</p>
<p>If first point is not exist it is drawn. When second point is present it should be changed after each click.</p>
<p>I dislike this part of code:</p>
<pre><code>this.point2.element.style.left = `${e.x}px`;
this.point2.element.style.top = `${e.y}px`;
</code></pre>
<p>Full code:</p>
<pre><code>export class Kizda {
private point1: { element: HTMLElement; pointMeter: Point };
private point2: { element: HTMLElement; pointMeter: Point };
getPoints() {
return { point1: this.point1, point2: this.point2 };
}
action(e: MouseEvent): void {
const point = this.getMouseMPoint(e);
function createPoint(color: string): HTMLElement {
let pointSize = 12;
let pointElement = document.createElement('div');
pointElement.style.position = 'absolute';
pointElement.style.width = `${pointSize}px`;
pointElement.style.height = `${pointSize}px`;
pointElement.style.left = `${e.x}px`;
pointElement.style.top = `${e.y}px`;
pointElement.style.background = color;
pointElement.style.borderRadius = '50%';
document.body.append(pointElement);
return pointElement;
}
if (!this.point1) {
this.point1 = { pointMeter: point, element: createPoint('red') };
return;
}
if (!this.point2) {
this.point2 = { pointMeter: point, element: createPoint('green') };
return;
} else {
this.point2.element.style.left = `${e.x}px`;
this.point2.element.style.top = `${e.y}px`;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:21:40.160",
"Id": "515015",
"Score": "2",
"body": "Welcome to the Code Review Community. Unlike Stack Overflow we do not answer `How to` questions. because they indicate the code is not working as expected. On Code Review the code must be working before we can answer. If your code is working please change the title to indicate what the code does. It would be helpful for you to read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)"
}
] |
[
{
"body": "<p>There are some repetitions in the current implementation, which can be refactored and the code will become clearer. For example:</p>\n<ul>\n<li>Use a custom <code>type</code> or <code>interface</code> for the private members.</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>interface MyPoint { // of course, choose a better name than MyPoint, which matches your context!\n element: HTMLElement; \n pointMeter: Point;\n}\n\nexport class Kizda {\n private point1: MyPoint;\n private point2: MyPoint;\n\n ...\n}\n</code></pre>\n<ul>\n<li>The <code>createPoint</code> function produces only a part of the point object, but it can indeed produce instances of <code>MyPoint</code>. And it does not need to be nested inside the <code>action</code> function:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>private createPoint(e: MouseEvent, color: string): MyPoint {\n const size = '12px';\n const element = document.createElement('div');\n const style = element.style;\n\n style.position = 'absolute';\n style.width = size;\n style.height = size;\n style.background = color;\n style.borderRadius = '50%';\n\n this.setCoordinates(element, e);\n\n document.body.append(element);\n\n const pointMeter = this.getMouseMPoint(e);\n return { element, pointMeter };\n}\n\nprivate setCoordinates(point: HTMLElement, e: MouseEvent): void {\n const style = point.style;\n style.left = `${e.x}px`;\n style.top = `${e.y}px`;\n}\n</code></pre>\n<ul>\n<li>Finally, adjust the implementation of the <code>action</code> method by reusing the refactored items:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>public action(e: MouseEvent): void {\n if (!this.point1) {\n this.point1 = this.createPoint(e, 'red');\n }\n else if (!this.point2) {\n this.point2 = this.createPoint(e, 'green');\n }\n else {\n this.setCoordinates(this.point2.element, e);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T07:13:28.493",
"Id": "261054",
"ParentId": "260975",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T10:49:18.627",
"Id": "260975",
"Score": "1",
"Tags": [
"javascript",
"typescript",
"dom"
],
"Title": "How to keep current HtmlElement active and change its properties?"
}
|
260975
|
<p>I have the following working code to get IPv4/v6 addresses from host names:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <array>
using std::array;
#include <iostream>
using std::cout;
#include <netdb.h>
#include <stdexcept>
using std::domain_error;
#include <sys/socket.h>
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <boost/asio.hpp>
using boost::asio::ip::address;
using boost::asio::ip::address_v4;
using boost::asio::ip::address_v6;
vector<address> getAddresses(string const &hostname)
{
struct addrinfo req = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
struct addrinfo *pai;
int error = getaddrinfo(hostname.c_str(), nullptr, &req, &pai);
if (error)
throw domain_error("Could not resolve host name.");
vector<address> addresses;
for(struct addrinfo *info = pai; info != nullptr; info = info->ai_next) {
if (info->ai_family == AF_INET) {
auto ipv4socket = reinterpret_cast<struct sockaddr_in*>(info->ai_addr);
auto ipv4addr = address_v4(htonl(ipv4socket->sin_addr.s_addr));
addresses.emplace_back(ipv4addr);
} else {
auto ipv6socket = reinterpret_cast<struct sockaddr_in6*>(info->ai_addr);
auto ipv6base = reinterpret_cast<unsigned char*>(ipv6socket->sin6_addr.s6_addr);
array<unsigned char, 16> bytearray = {
ipv6socket->sin6_addr.s6_addr[0],
ipv6socket->sin6_addr.s6_addr[1],
ipv6socket->sin6_addr.s6_addr[2],
ipv6socket->sin6_addr.s6_addr[3],
ipv6socket->sin6_addr.s6_addr[4],
ipv6socket->sin6_addr.s6_addr[5],
ipv6socket->sin6_addr.s6_addr[6],
ipv6socket->sin6_addr.s6_addr[7],
ipv6socket->sin6_addr.s6_addr[8],
ipv6socket->sin6_addr.s6_addr[9],
ipv6socket->sin6_addr.s6_addr[10],
ipv6socket->sin6_addr.s6_addr[11],
ipv6socket->sin6_addr.s6_addr[12],
ipv6socket->sin6_addr.s6_addr[13],
ipv6socket->sin6_addr.s6_addr[14],
ipv6socket->sin6_addr.s6_addr[15]
};
auto ipv6addr = address_v6(bytearray, ipv6socket->sin6_scope_id);
addresses.emplace_back(ipv6addr);
}
}
return addresses;
}
int main()
{
auto addresses = getAddresses("heise.de");
for (auto ipa : addresses)
cout << "Address: " << ipa << "\n";
return 0;
}
</code></pre>
<p>I find the conversion fom <code>uint8_t[16]</code> (<code>ipv6socket->sin6_addr.s6_addr</code>) to <code>std::array<unsigned char, 16></code> a bit verbose.
I also considered doing it in a for-loop, but this would still seem cumbersome to me, somehow.
I tried <code>static_cast</code> and <code>reinterpret_cast</code> to no avail.
Is there a possibility to do this conversion in a simpler way, preferably a one-liner?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T11:29:52.510",
"Id": "515006",
"Score": "1",
"body": "You object to a for loop, would you object to `std::copy` or something similar?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T11:31:36.027",
"Id": "515007",
"Score": "0",
"body": "I would not. I am explicitely looking for alternatives."
}
] |
[
{
"body": "<p>I agree with you that the copying of data from <code>s6_addr</code> seems cumbersome. I would instead just cast without copying:</p>\n<pre><code>auto& bytearray = reinterpret_cast<std::array<unsigned char,16>&>(ipv6socket->sin6_addr.s6_addr);\n</code></pre>\n<p>(If we had needed to copy, we could change <code>auto&</code> to plain <code>auto</code>).</p>\n<p>Apart from this, the variable <code>ipv6base</code> is never used, so should just be removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:50:07.747",
"Id": "515021",
"Score": "0",
"body": "Thank you so much. Such a noob mistake from me. I forgot the ampersands. :facepalm:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:08:36.847",
"Id": "515024",
"Score": "0",
"body": "Oh, I've done the same myself from time to time. Easy to get wrong, and very hard to spot what's incorrect!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:11:47.013",
"Id": "515025",
"Score": "0",
"body": "Using a type-change cast like that, with modern compilers you have to beware of _undefined behavior_. The old tricks using a union or type puns are now technically illegal. How is this not falling into that trap?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:14:25.737",
"Id": "515026",
"Score": "0",
"body": "Good point @JDługosz. I can't prove that this is legal. I think it's _likely_ to be safe in this context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:21:01.770",
"Id": "515027",
"Score": "0",
"body": "https://en.cppreference.com/w/cpp/language/reinterpret_cast \"Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true: ... AliasedType is std::byte, char, or unsigned char: this permits examination of the object representation of any object as an array of bytes.\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T13:47:51.417",
"Id": "260981",
"ParentId": "260976",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260981",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T11:05:08.607",
"Id": "260976",
"Score": "1",
"Tags": [
"c++",
"array",
"c++17",
"networking"
],
"Title": "Gather all IP addresses of a host as a vector"
}
|
260976
|
<p>I've made a program which reads from the console and writes it in a <code>.txt</code> file. This programm should write in a file with <code>\n</code>.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream fich("file.txt");
if (!fich)
cerr << "Error!\n";
char fst = 'l';
string c;
while (fst != '\0') {
getline(cin, c);
fst = c[0];
fich << c << endl;
}
fich.close();
return 0;
}
</code></pre>
<p>This program ends when the user inputs nothing and then a <code>\n</code>, because, doing that, the <code>string c</code> will only have a <code>\0</code> end of string element.</p>
<p>I was wondering if there is any way of doing this more efficiently, maybe without needing a "void <code>\n</code>" line to finish the program.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:37:46.367",
"Id": "515089",
"Score": "0",
"body": "I guess `main2()` is a typo that should be `main()`, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T22:40:35.957",
"Id": "515566",
"Score": "1",
"body": "`c[0]` on an empty string is not guaranteed to be `\\0`! Your test should be: `while(getline(std::cin, c)) {` Then you can end input by typing the EOF control code for your platform. `<ctrl>-D` on linux. This also makes it work nicely with files piped to the standard input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T15:46:57.093",
"Id": "515803",
"Score": "0",
"body": "@uli It was a typo, i corrected it, aprecciate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T15:54:31.877",
"Id": "515805",
"Score": "0",
"body": "@MartinYork Isn't the string empty when I create it? I thought that if it's empty then the `\\0` element should be in `string[0]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T15:57:00.143",
"Id": "515806",
"Score": "0",
"body": "Please be aware that changing the code after you have an answer generally isn't permitted because it may invalidate the answer. In this case `main2()` wasn't mentioned in either answer so it is ok. Please read [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T16:12:05.813",
"Id": "515810",
"Score": "0",
"body": "@pacmaninbw I am aware, but `main2()` was just a typo, then I thought it wouldn't be any problem at all. I 'll read it, apreciate it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T16:47:36.903",
"Id": "515813",
"Score": "0",
"body": "If you just want to copy a file, you can use [`std::filesystem::copy_file()`](https://en.cppreference.com/w/cpp/filesystem/copy_file)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T16:50:10.713",
"Id": "515814",
"Score": "1",
"body": "You are thinking of a C-String. The C++ `std::string` class does not use a null terminator. Accessing at `size()` using `operator[]` is undefined behavior. Now there is a method that will give you a null terminated string that looks like a C-String call `c_str()` this guarantees a null terminated string. But why not just call `empty()` to test for an empty string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T02:43:21.647",
"Id": "515852",
"Score": "0",
"body": "@G.Sliepen I want to write in a file, not copy it"
}
] |
[
{
"body": "<h1>Error Handling</h1>\n<p>You check whether the output file was opened correctly, but all you do is output a message (you don't even say what's wrong!) and then you keep on ignoring it. What if <code>file.txt</code> is a directory or read-only? I guess you haven't tested these cases. By default, throw an exception if you can't continue at some point. In this case, <code>throw std::runtime_error("failed to open output file")</code>.</p>\n<h1>Loop Condition</h1>\n<p>You are reading until the line is empty. This is okay-ish, but why don't you just check whether <code>c.empty()</code> and then break from the loop? Another case is that the end of the input is reached. In that case, the streamstate is set to failed. I'm not sure what happens in <code>getline()</code> then (read the docs at cppreference.com), but if it just doesn't change the string passed by reference, you may end up in an endless loop.</p>\n<p>As an alternative I would use <code>getline(cin, c)</code> as loop condition. If this succeeds, you have received a line which can then write to the output file. Otherwise, you either had an error or you reached the end of the input.</p>\n<h1>Closing Filestreams</h1>\n<p>If you didn't call <code>fich.close()</code>, when would it be closed? However, consider the possibility that the file can't be written fully. You'll never notice this, neither with your code nor if you let the destructor do its work. So, what I'd rather do there is a call to <code>fiche.flush()</code> followed by a check of the streamstate.</p>\n<h1>Efficiency</h1>\n<p>I wouldn't bother with that at the moment. Point is, you're still learning to walk, so don't try to run yet. Still, what you're doing is inefficient. Firstly, writing in size of lines is useless, because you're just moving bytes from one file to the other. Secondly, <code>endl</code> implies a newline <em>and</em> a flush. So this is not really a cheap operation! In addition, there is a lot of stuff going on in C++ IOStreams that there's a whole book about their internals. Lastly, copying files can sometimes be done more efficiently using OS features which will avoid looking at the data more than necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T22:41:42.133",
"Id": "515567",
"Score": "0",
"body": "Yes a file will be closed correctly. The `std::ofstream` destructor calls close. In \"most\" cases not calling close is the correct action. Also manually calling flush is \"usually\" the wrong thing to do. The system implementation will auto flush when needed; manually calling flush is the cause of most speed issues in beginners C++ application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T06:48:28.010",
"Id": "515577",
"Score": "0",
"body": "Speed issues in beginners' applications? Uselessly flushing is a source for bad performance, that much I agree with. However, if you don't flush your stream after you're done writing, you don't know whether the data was written. If there is buffered data that doesn't fit on the storage, you will only get corrupted data and you may not even notice until it's too late."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T13:48:52.987",
"Id": "515607",
"Score": "1",
"body": "_\"I'm not sure what happens in getline() then (read the docs at cppreference.com), but if it just doesn't change the string passed by reference, you may end up in an endless loop.\"_ The string is cleared first. So if there is an EOF or other problem, you will read an empty string."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:37:49.907",
"Id": "261019",
"ParentId": "260983",
"Score": "4"
}
},
{
"body": "<p>The <code>\\0</code> does not show up as a legal element of the <code>string</code>. In an empty <code>string</code>, doing <code>c[0]</code> is an error!</p>\n<p>You don't need <code>fst</code> at all. You should use <code>c.empty()</code> to check for an empty string.</p>\n<p>If you're not on a Unix-like system, be sure to open the file in Text mode, or you'll end up with stray <code>\\r</code> characters in your string.</p>\n<p>Your names, <code>fst</code>, <code>fich</code>, are confusing. Using <code>c</code> for a string is unusual and confusing to experienced programmers.</p>\n<p>Don't write <code>using namespace std;</code>.</p>\n<p>You can use a <strong>mid-decision loop</strong> to simplify your variables and logic. Something like:</p>\n<pre><code>for (;;) {\n getline (cin, s);\n if (s.empty()) break;\n outfile << s << '\\n';\n}\n</code></pre>\n<p>As as already been pointed out, the whole idea of reading and writing a line at a time is not "efficient". It might be what you need, though, for an interactive program where the user is typing something. If you are implementing something like <code>cat</code> though it is less efficient than reading entire blocks using low-level primitives. The <code>iostream</code> implementation reads the file in a low-level way, and <code>getline</code> goes through that data (that's already been read into memory) just to locate the end-of-line characters; then copies that to another string. If you just wanted to copy everything, that's clearly extra overhead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:04:18.650",
"Id": "261039",
"ParentId": "260983",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261019",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T14:19:30.367",
"Id": "260983",
"Score": "4",
"Tags": [
"c++",
"file-system"
],
"Title": "Efficiently write in a file in C++"
}
|
260983
|
<p>I have an inner class for filtering:</p>
<pre><code>private class RegSpecification implements Specification<Reg> {
private final transient RegFilterDTO filter;
private transient Predicate predicate;
private transient CriteriaBuilder cb;
public RegSpecification(RegFilterDTO filter) {
this.filter = filter;
}
@Override
public Predicate toPredicate(Root<Reg> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
// this.cb = cb;
this.predicate = cb.conjunction();
Join<Reg, Acct> userJoin = root.join(acct, JoinType.INNER);
predicate = eqEnumVal(predicate, cb, root.get(regType), RegType.class, filter.getRegType());
predicate = eq(predicate, cb, userJoin.get(Acct_.id), filter.getAcctId());
predicate = like(predicate, cb, root.get(regNumber), filter.getRegNumber());
return predicate;
}
}
</code></pre>
<p>And I made a helper class, to be used by other class as well who implements filtering by <code>Specification</code> (methods are public since some services are in other packages):</p>
<pre><code>public class PredicateBuilder {
public static Predicate like(Predicate predicate, CriteriaBuilder cb, Path<String> path, String value) {
if (StringUtils.isNotEmpty(value)) {
return cb.and(predicate, cb.like(cb.lower(path), "%" + value.toLowerCase() + "%"));
}
return predicate;
}
public static <T> Predicate eq(Predicate predicate, CriteriaBuilder cb, Path<T> path, T value) {
if (value != null) {
return cb.and(predicate, cb.equal(path, value));
}
return predicate;
}
public static <T extends Enum<T>> Predicate eqEnumVal(Predicate predicate, CriteriaBuilder cb,
Path<T> path, Class<T> enumType, String name) {
if (StringUtils.isNotEmpty(name)) {
return eq(predicate, cb, path, Enum.valueOf(enumType, name));
}
return predicate;
}
}
</code></pre>
<p><strong>Question is</strong><br>
Can I use private local variables in my RegSpecification so I won't have to use <code>predicate = ...</code> every time I call the helper class and some generic method to pass the predicate and cb to the helper class (so I won't have to pass the predicate and cb in my helper class methods)?</p>
<p>Where I could just do something like:</p>
<pre><code>PredicateBuilder.with(predicate, cb)
...
like(userJoin.get(Acct_.id), filter.getAcctId());
eq(userJoin.get(Acct_.id), filter.getAcctId());
like(root.get(regNumber), filter.getRegNumber());
...
.build();
</code></pre>
<p>in my <code>toPredicate</code> method.</p>
<p>Or any suggestions to make the code cleaner?</p>
<p>(Should I also annotate the helper class with <code>@Component</code>?)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T18:48:30.120",
"Id": "515993",
"Score": "2",
"body": "Hi sophie. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the question & answer style of Code Review. As such we have rolled back your latest edit. Please see [what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<p>I would suggest that the <code>PredicateBuilder</code> actually follows a builder like pattern, where methods are cascaded to create the object. Currently the <code>predicate</code> object is updated with seaparate calls to the static method in the <code>PredicateBuilder</code>. Rather than that you could follow the below approach which is more in line with a "builder".</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class PredicateBuilder {\n\n private Predicate predicate;\n private CriteriaBuilder cb;\n private List<Consumer<PredicateBuilder>> tasks = new ArrayList<>();\n \n private PredicateBuilder(){\n }\n \n public static PredicateBuilder with(Predicate p, CriteriaBuilder c) {\n PredicateBuilder instance = new PredicateBuilder();\n instance.predicate = p;\n instance.cb = c;\n return instance;\n }\n\n public PredicateBuilder tasks(List<Consumer<PredicateBuilder>> tasks) {\n this.tasks = tasks;\n return this;\n }\n\n public Predicate build() {\n for(Consumer<PredicateBuilder> task : tasks) {\n task.accept(this);\n }\n return this.predicate;\n }\n \n public PredicateBuilder like(Path<String> path, String value) {\n if (StringUtils.isNotEmpty(value)) {\n CriteriaBuilder c = this.cb;\n this.predicate = c.and(this.predicate,\n c.like(c.lower(path), "%" + value.toLowerCase() + "%"));\n }\n return this;\n }\n\n public <T> PredicateBuilder eq(Path<T> path, T value) {\n if (value != null) {\n CriteriaBuilder c = this.cb;\n this.predicate = c.and(this.predicate, c.equal(path, value));\n }\n return this;\n }\n\n public <T extends Enum<T>> PredicateBuilder eqEnumVal(Path<T> path, Class<T> enumType, String name) {\n if (StringUtils.isNotEmpty(name)) {\n return eq(path, Enum.valueOf(enumType, name));\n }\n return this;\n }\n\n} \n</code></pre>\n<p>Then you could invoke as below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List<Consumer<PredicateBuilder>> tasks \n = List.of(pb -> pb.eqEnumVal(root.get(regType), RegType.class, filter.getRegType()),\n pb -> pb.eq(userJoin.get(Acct_.id), filter.getAcctId()),\n pb -> pb.like(root.get(regNumber), filter.getRegNumber()));\nreturn PredicateBuilder.with(predicate, cb)\n .tasks(tasks)\n .build();\n</code></pre>\n<p>This way you could provide tasks if you want them to execute conditionally or directly invoke the methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:23:54.563",
"Id": "515067",
"Score": "0",
"body": "Thank you! I am having trouble though with the tasks. I had to do `.tasks(new Runnable[] {...})` for it to compile. Also, I have warnings like: `Static member 'PredicateBuilder.tasks(java.lang.Runnable[])' accessed via instance reference` and \n`Static member 'PredicateBuilder.build()' accessed via instance reference`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T04:39:08.847",
"Id": "515077",
"Score": "0",
"body": "@sophie I actually forgot to make a few changes. The `tasks` and `build` need not be static and the parameter to tasks should be `Runnable... tasks` instead of `Runnable[] tasks`. This would allow the comma separated list to be passed. I have made the edits to the answer. Please try now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:14:00.490",
"Id": "515088",
"Score": "0",
"body": "Thank you Gautham. May I also know the use of thread/Runnable here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:43:28.360",
"Id": "515091",
"Score": "0",
"body": "@sophie Since Runnable represents a functional interface which takes no arguments and returns nothing, I had used runnable to keep the list of actions to be done. The actual method execution happens only when the `run` is invoked (inside `build`). In this way, the caller method could pass the list of actions to be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T07:05:11.053",
"Id": "515093",
"Score": "0",
"body": "Oh. Thank you for the explanation! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T17:26:27.093",
"Id": "515982",
"Score": "1",
"body": "I am having a problem with the instance being static - if I run 2 consecutive queries, the predicate are the same now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T17:43:48.103",
"Id": "515984",
"Score": "1",
"body": "@sophie I have updated the code. Not much changes - instance and tasks are now removed. All methods except `with` are made `non-static`. Replace every usage of `instance` with `this` (except in the `with` method). And changes to how the builder is invoked. I believe it looks more clean than the first version. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T18:07:54.690",
"Id": "515986",
"Score": "0",
"body": "thank you, I have to `return this` (PredicateBuilder) with all this methods right? Also, I have conditional statements before in my tasks like: ` () -> { if (...) { otherPredicate(predicate); } },` how can I apply it given it is built with `.eq`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T18:26:27.890",
"Id": "515990",
"Score": "0",
"body": "also I am having warnings again like: \"static\" members should be accessed statically, so instead of `with`, I replaced it with a constructor and assigned: `this.predicate = p;` and `this.cb = c;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T18:50:03.897",
"Id": "515994",
"Score": "1",
"body": "Hi Gautham M. Answers must make at least one [insightful observation](/help/how-to-answer), and must explain why the change is better than the OP's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T19:22:14.980",
"Id": "516001",
"Score": "0",
"body": "@GauthamM sorry, the static issue is okay now, but any suggestions on how to incorporate conditional statements when calling the Predicate Builder's methods before calling `getPredicate()` ? I have IF-ELSE statements before when I used the Tasks, like`if () eq(..) else isNull(..)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-03T17:34:31.853",
"Id": "516242",
"Score": "1",
"body": "@sophie updated. you could do it using consumer instead of runnable. check this https://stackoverflow.com/q/12462079/7804477 to know why i used a list instead of varargs."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T17:11:11.587",
"Id": "260990",
"ParentId": "260984",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260990",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T15:47:10.063",
"Id": "260984",
"Score": "2",
"Tags": [
"java"
],
"Title": "Writing a clean Predicate Builder"
}
|
260984
|
<p><strong>Problem:</strong></p>
<p>Given a string <code>aaabbcccaad</code> print the no. of occurrence of the character in the same order in which the character occurred.</p>
<p>Expected output:
<code>(a, 3), (b, 2), (c, 3), (a, 2), (d, 1)</code></p>
<p><strong>The approach:</strong></p>
<ol>
<li>Loop through each character.</li>
<li>When the next character is not same as the current character, record the next character and its position.</li>
<li>count of occurence = Iterate the <code>pos_list</code> (position list ), take the difference</li>
<li>Return character and its count in in the same order</li>
</ol>
<p><strong>Solution:</strong></p>
<pre><code>def seq_count(word):
wlen = len(word)
pos = 0
pos_list=[pos]
alph = [word[0]]
result = []
for i in range(wlen):
np = i+1
if np < wlen:
if word[i] != word[i+1]:
pos = i+1
pos_list.append(pos)
alph.append(word[i+1])
pos_list.append(wlen)
for i in range(len(pos_list)-1):
result.append((alph[i], pos_list[i+1] - pos_list[i]))
return result
print seq_count("aaabbcccaad")
</code></pre>
<p>Note:</p>
<p>I know this may not be the conventional solution, i was finding difficult to count the character and maintain its count as we iterate through the string, since I'm a beginner in python. Pls let me know how can i do it better.</p>
|
[] |
[
{
"body": "<p>Problems like this tend to be annoying: so close to a simple solution, except for the need to be adjusting state during the loop. In this case, <code>itertools.groupby()</code> offers a shortcut, because its grouping function defaults to an identity, which is exactly what you need.</p>\n<pre><code>from itertools import groupby\n\ndef seq_count(word):\n return [\n (char, len(tuple(g)))\n for char, g in groupby(word)\n ]\n</code></pre>\n<p>If you don't want to use another library, you can reduce the bookkeeping a bit by yielding rather than returning and by iterating directly over the characters rather than messing around with indexes. But even with such simplifications, tedious annoyances remain. Anyway, here's one way to reduce the pain a little. The small code comments are intended to draw attention to the general features of this pattern, which occurs in many types of problems.</p>\n<pre><code>def seq_count(word):\n if word:\n # Initialize.\n prev, n = (word[0], 0)\n # Iterate.\n for char in word:\n if char == prev:\n # Adjust state.\n n += 1\n else:\n # Yield and reset.\n yield (prev, n)\n prev, n = (char, 1)\n # Don't forget the last one.\n if n:\n yield (prev, n)\n\nexp = [('a', 3), ('b', 2), ('c', 3), ('a', 2), ('d', 1)]\ngot = list(seq_count("aaabbcccaad"))\nprint(got == exp) # True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:30:59.157",
"Id": "515050",
"Score": "0",
"body": "Thanks! The first solution looks really good. But most of the interviewers won't accept that. Any suggestions to improve upon these kinda solution thinking?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:50:39.637",
"Id": "515056",
"Score": "2",
"body": "@ManivG Find better interviewers! Mostly I'm joking, but not entirely. Don't forget that you are interviewing them too. Sensible interviewers will reward a candidate familiar with the full power of a language (eg knowing `itertools`), even if they also ask for a roll-your-own solution. As far as improving, I advise lots of practice trying to solve **practical problems** (eg on StackOverflow or here). Place less emphasis on problems requiring semi-fancy algorithms and focus heavily on bread-and-butter questions. Pay attention to how different people solve such problems and steal their ideas."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T17:14:15.327",
"Id": "260991",
"ParentId": "260986",
"Score": "3"
}
},
{
"body": "<p>For a recent version of Python (>= 3.7 I think), a <code>dict</code> is ordered by the insertion order of the keys. A <code>collections.Counter()</code> is a subclass of <code>dict</code>, so it is also ordered. The simplest solution is to use a Counter:</p>\n<pre><code>from collections import Counter\n\ndef seq_count(word):\n return list(Counter(word).items())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T05:04:31.747",
"Id": "261088",
"ParentId": "260986",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:04:50.980",
"Id": "260986",
"Score": "2",
"Tags": [
"python"
],
"Title": "Return character frequency in the order of occurrence"
}
|
260986
|
<p>I have been trying to write a number guessing game and I am trying to condense the second while loop when guess =! random_number. <br>I can't figure out if there is any better way to shorten the code but to still achieve the same result. I wonder if someone is able to help me out. <br> If there's anything else which is redundant or not efficient in my code or how i could code it better please criticize the hell out me my work!</p>
<pre><code>import random
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
#ranges must be integers
min_range = int(inputNumber("Please insert the min range: "))
temp_range = int(inputNumber("Please insert the max range: "))
#max range must be bigger than min
while min_range >= temp_range:
temp_range = int(inputNumber("Please insert a max range which is smaller than min range!: ")) + 1
max_range = temp_range
random_number = random.randint(min_range, max_range)
guess = int(input("Please enter your guess: "))
counter = 1; # you guessed once already
while guess != random_number: # 1 guess incorrect
print(f"{random_number} is the random number")# to see for myself which is the random numb
if min_range < guess < max_range: # WITHIN THE RANGE
if random_number - random_number / 12 < guess-random_number < random_number + random_number / 12: # 3 super hot
print("Please try again, you are super hot!")
elif random_number - random_number / 8 < guess-random_number < random_number + random_number / 8: # 3 hot
print("Please try again, you are hot!")
elif guess < random_number - random_number / 2 or guess-random_number > random_number + random_number / 2: # 3 cold
print("Please try again, you are cold!")
else: # OUTSIDE RANGE
print("You are outside the range, try again!")
guess = int(input())
counter += 1
if guess == random_number: # guess correct
print(f"Congratulations, you guessed correctly in {counter} tries!")
</code></pre>
<p>edit: thanks you all so much for taking the time to review my code, i will try to improve on the noted points, much appreciated (:</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:39:54.960",
"Id": "515053",
"Score": "2",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p>Miscellaneous notes:</p>\n<ul>\n<li>you don't need a <code>break</code> after a <code>return</code></li>\n<li>you could (attempt to) return directly from the input; "except" will still catch and cycle errors</li>\n<li><code>inputNumber()</code> explicitly returns an integer; no need to cast again.</li>\n<li><code>temp_range</code> isn't really needed - you can just use <code>max_range</code>, no loss to readability.</li>\n<li>no need to add one to <code>max_range</code> (in the validation loop) - <code>randint()</code> includes the top limit.</li>\n<li><code>random_number</code> is an unhelpful variable name - I've called this <code>target</code></li>\n<li>using <code>inputNumber()</code> for the <code>guess</code> also seems sensible.</li>\n<li><code>guess</code> should be checked against the <strong>inclusive</strong> range - min and max are possible values.</li>\n<li><em>personally</em> I think the temperature categories should reflect the size of the range, rather than the size of the chosen number... however</li>\n<li>your calculation is wrong anyway; you are testing the difference between <code>guess</code> and <code>target</code> so you should test against the small fraction of <code>target</code>, not <code>target</code> reduced by a fraction (or should just check <code>guess</code> against the numbers you calculate).</li>\n<li>the "hot" range (outside "super hot") is actually smaller than the "super hot" range - I adjusted this out to 1/4 of <code>target</code></li>\n<li>after correction, there's a range that gets no message, which can be covered in an <code>else</code> clause. I reordered so all tests are for "in this range" and the <code>else</code> covers the "cold" option.</li>\n</ul>\n<p>To condense the message selection, you could set up a list of boundaries changing from one condition to another, and step through (or search) to find the applicable message. However I'm not sure that's a lot clearer in this case.</p>\n<p>With updates reflecting most of these:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nCHEATING = True\n\ndef inputNumber(message):\n while True:\n try:\n return int(input(message))\n except ValueError:\n print("Not an integer! Try again.")\n\n#ranges must be integers\nmin_range = inputNumber("Please insert the min range: ")\nmax_range = inputNumber("Please insert the max range: ")\n\n#max range must be bigger than min\nwhile min_range >= max_range:\n max_range = inputNumber("Please insert a max range which is bigger than min range!: ")\n\ntarget = random.randint(min_range, max_range)\n\nguess = inputNumber("Please enter your guess: ")\ncounter = 1; # you guessed once already\nwhile guess != target: # 1 guess incorrect\n if CHEATING: print(f"{target} is the random number")# to see for myself which is the random numb\n if min_range <= guess <= max_range: # WITHIN THE RANGE\n if -target / 12 < guess-target < target / 12: # 3 super hot\n print("Please try again, you are super hot!")\n elif -target / 4 < guess-target < target / 4: # 3 hot\n print("Please try again, you are hot!")\n elif -target / 2 < guess-target < target / 2: # a bit meh\n print("Not great, not terrible - please try again")\n else: # 3 cold\n print("Please try again, you are cold!")\n\n else: # OUTSIDE RANGE\n print("You are outside the range, try again!")\n guess = inputNumber("Next guess? ")\n counter += 1\nif guess == target: # guess correct\n print(f"Congratulations, you guessed correctly in {counter} tries!")```\n</code></pre>\n<p>PS: "please criticize the hell out my work" is an excellent attitude, if you have the fortitude for it, and a great way to learn.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T17:50:45.370",
"Id": "260993",
"ParentId": "260988",
"Score": "2"
}
},
{
"body": "<p>The biggest sources of repetition in your code are the mathematical\ncalculations of the difference between the random number and the user's guess,\nalong with the need to re-ask the user for another guess on a couple of\noccasions. You already have a function to get an integer from the user, so take\nadvantage of it! Also, you could enhance that function to eliminate the need to\nrepeat yourself when collecting <code>max_range</code>. Finally, I did not\nfully understand the intended logic of your difference calculation,\nso I improvised to use a modified approach\n(percentage difference relative to the overall span of the range). In any case,\nthe important point is to <strong>make the calculation once</strong>. Then use the result to\nselect the adjective. Some possible edits for you to consider:</p>\n<pre><code>import random\n\n# An enhanced function taking an optional minimum value.\n# If needed, you could enhance further by changing that\n# parameter to a `range()` if you want to restrict both sides.\n# If you were do to that, you could further simplify the\n# guessing loop.\ndef inputNumber(message, min_val = 0):\n while True:\n try:\n n = int(input(message))\n if n >= min_val:\n return n\n else:\n print(f"Must be greater than {min_val}. Try again")\n except ValueError:\n print("Not an integer! Try again.")\n\n# No need to convert these values to integers.\n# The function already does that.\nmin_range = inputNumber("Please insert the min range: ")\nmax_range = inputNumber("Please insert the max range: ", min_val = min_range)\nrandom_number = random.randint(min_range, max_range)\ncounter = 0\n\n# When getting user input, a while-True loop is usually\n# the right way to start. If you ask before the loop,\n# you have to re-ask if the user makes a mistake.\nwhile True:\n counter += 1\n guess = inputNumber("Please enter your guess: ")\n if guess == random_number:\n print(f"Congratulations, you guessed correctly in {counter} tries!")\n break\n # This comparison should use <= rather than < I think.\n elif min_range <= guess <= max_range:\n diff_pct = abs(guess - random_number) / (max_range - min_range)\n adjective = (\n 'super hot' if diff_pct < .2 else\n 'hot' if diff_pct < .4 else\n 'cold'\n )\n print(f"Please try again, you are {adjective}!")\n else:\n print("You are outside the range, try again!")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:08:34.610",
"Id": "260996",
"ParentId": "260988",
"Score": "1"
}
},
{
"body": "<p>I'll add some points to <a href=\"https://codereview.stackexchange.com/a/260993/239401\">Joffan's answer</a>, which already provides some great improvements.</p>\n<hr />\n<p><strong>Naming</strong></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8</a>: Variable and function names should follow snake_case instead of camelCase.</p>\n<hr />\n<p><strong>input_number</strong></p>\n<p>This function should be a lot simpler:</p>\n<pre><code>def input_number(message):\n while True:\n try:\n return int(input(message))\n except ValueError:\n print("Not an integer! Try again.")\n</code></pre>\n<hr />\n<p><strong>main()</strong></p>\n<p>It's a good idea to wrap your procedure into a <code>main()</code> function, which provides a standard entry point. It also makes the functionality of your code clearer at a glance. Since a function will not run on its own when we execute the script, we need to call it. For most use cases, we should wrap it in a <code>if __name__ == “__main__”:</code> condition.</p>\n<pre><code>def main():\n # this is where your procedure now runs\n\nif __name__ == “__main__”:\n main()\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">What does if <strong>name</strong> == “<strong>main</strong>”: do?</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:19:07.777",
"Id": "260997",
"ParentId": "260988",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260993",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:35:47.243",
"Id": "260988",
"Score": "0",
"Tags": [
"python"
],
"Title": "Is there a better way to condense the while loop?"
}
|
260988
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/260782/231235">Android app class serialization</a>. The implementation of <code>User</code> class has been updated and the functionality of null string checking, password strength checking and the correctness of date formatting are considered in this post. The part of password strength checking has been implemented in <code>PasswordStrength</code> class.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p>Project name: UserClassTest</p>
</li>
<li><p><code>PasswordStrength.java</code> implementation:</p>
<pre><code>package com.example.userclasstest;
import java.util.ArrayList;
public class PasswordStrength {
private ArrayList<String> commonPasswords = new ArrayList<>();
private int minimumLengthRequired = 8;
public enum Level {
Weak,
Medium, // TODO: Implement the determination of medium level password
Strong // TODO: Implement the determination of strong level password
}
private Level passwordStrengthLevel;
public PasswordStrength(String input)
{
CreateCommonPasswordsList();
if (LengthCheck(input) == false)
{
this.passwordStrengthLevel = Level.Weak;
return;
}
if (this.commonPasswords.contains(input))
{
this.passwordStrengthLevel = Level.Weak;
return;
}
this.passwordStrengthLevel = Level.Medium;
return;
}
private void CreateCommonPasswordsList()
{
this.commonPasswords.add("111111");
this.commonPasswords.add("123123");
this.commonPasswords.add("12345");
this.commonPasswords.add("123456");
this.commonPasswords.add("12345678");
this.commonPasswords.add("123456789");
this.commonPasswords.add("1234567890");
this.commonPasswords.add("picture1");
this.commonPasswords.add("password");
this.commonPasswords.add("password123");
this.commonPasswords.add("Password");
this.commonPasswords.add("Password123");
this.commonPasswords.add("Password123");
}
private boolean LengthCheck(String input)
{
if (input.length() > minimumLengthRequired)
{
return true;
}
return false;
}
public boolean IsPasswordWeak()
{
return this.passwordStrengthLevel.equals(Level.Weak);
}
}
</code></pre>
</li>
<li><p><code>User.java</code> implementation:</p>
<pre><code>package com.example.userclasstest;
import android.content.Context;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class User implements java.io.Serializable{
private String fullName;
private String personalID;
private String dateOfBirth;
private String cellPhoneNumber;
private String emailInfo;
private String password;
public User(String fullNameInput,
String personalIDInput,
String dateOfBirthInput,
String cellPhoneNumberInput,
String emailInfoInput,
String passwordInput) throws NoSuchAlgorithmException, NullPointerException, IllegalArgumentException
// User object constructor
{
// Reference: https://stackoverflow.com/a/6358/6667035
if (fullNameInput == null) {
throw new NullPointerException("fullNameInput must not be null");
}
this.fullName = fullNameInput;
if (personalIDInput == null) {
throw new NullPointerException("personalIDInput must not be null");
}
this.personalID = personalIDInput;
if (dateOfBirthInput == null) {
throw new NullPointerException("dateOfBirthInput must not be null");
}
if (IsDateValid(dateOfBirthInput) == false)
{
throw new IllegalArgumentException("dateOfBirthInput is invalid");
}
this.dateOfBirth = dateOfBirthInput;
if (cellPhoneNumberInput == null) {
throw new NullPointerException("cellPhoneNumberInput must not be null");
}
this.cellPhoneNumber = cellPhoneNumberInput;
if (emailInfoInput == null) {
throw new NullPointerException("emailInfoInput must not be null");
}
this.emailInfo = emailInfoInput;
if (passwordInput == null) {
throw new NullPointerException("passwordInput must not be null");
}
if (new PasswordStrength(passwordInput).IsPasswordWeak())
{
throw new IllegalArgumentException("Password is weak!");
}
this.password = HashingMethod(passwordInput);
}
// Reference: https://stackoverflow.com/a/20231617/6667035
private boolean IsDateValid(String dateStr) {
if (dateStr.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
return true;
else
return false;
}
public String GetFullName()
{
return this.fullName;
}
public String GetPersonalID()
{
return this.personalID;
}
public String GetDateOfBirth()
{
return this.dateOfBirth;
}
public String GetCellPhoneNumber()
{
return this.cellPhoneNumber;
}
public String GetEmailInfo()
{
return this.emailInfo;
}
public String GetHash() throws NoSuchAlgorithmException
{
return HashingMethod(this.fullName + this.personalID);
}
public String GetHashedPassword() throws NoSuchAlgorithmException
{
return this.password;
}
public boolean CheckPassword(String password)
{
boolean result = false;
try {
result = this.password.equals(HashingMethod(password));
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
//**********************************************************************************************
// Reference: https://stackoverflow.com/a/2624385/6667035
private String HashingMethod(String InputString) throws NoSuchAlgorithmException
{
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
String stringToHash = InputString;
messageDigest.update(stringToHash.getBytes());
String stringHash = new String(messageDigest.digest());
return stringHash;
}
}
</code></pre>
</li>
<li><p><code>MainActivity.java</code> implementation:</p>
<pre><code>package com.example.userclasstest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
User currentUser = null;
try {
currentUser = new User(
"Mike",
"M12345678",
"10/13/1990",
"(555) 555-1234",
"123456@test.com",
"p?@nY4q~?A-)T#+^");
}
catch (Exception e)
{
ShowToast(e.getMessage(), Toast.LENGTH_LONG);
e.printStackTrace();
Log.d("onCreate", e.getMessage());
return;
}
ShowToast(currentUser.GetFullName(), Toast.LENGTH_SHORT);
}
private void ShowToast(String Text, int Duration)
{
Context context = getApplicationContext();
CharSequence text = Text;
int duration = Duration;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
</code></pre>
</li>
</ul>
<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/260782/231235">Android app class serialization</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The implementation of <code>User</code> class has been updated and the functionality of null string checking, password strength checking and the correctness of date formatting are considered in this post.</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>
|
[] |
[
{
"body": "<h2>Dates</h2>\n<pre><code>// Reference: https://stackoverflow.com/a/20231617/6667035\nprivate boolean IsDateValid(String dateStr) {\n if (dateStr.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))\n return true;\n else\n return false;\n}\n</code></pre>\n<p>Did you read the comment the OP posted after that linked answer?</p>\n<blockquote>\n<p>Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable</p>\n</blockquote>\n<p>As an example... "99/99/2021" is a valid date...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:13:41.700",
"Id": "515087",
"Score": "1",
"body": "Don't delete your answer, because your main concern about `CurrentUser` is IMO not correct. `CurrentUser` is created inside the `Try` block. See first version inside the edit history of the question. Nevertheless your answer shows some valid points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T08:50:34.740",
"Id": "515101",
"Score": "0",
"body": "@heslacher Thanks, you're right, I missed the return in the exception handler so the line I was worried about wouldn't have run. I've updated my answer so that it's now in line with the current version of the question (since I caused the edits) and I'll revisit when I have a keyboard."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:45:35.093",
"Id": "261000",
"ParentId": "260989",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261000",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T16:52:24.840",
"Id": "260989",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"android",
"classes",
"null"
],
"Title": "Android APP User class implementation"
}
|
260989
|
<p>I made this c# hangman game...</p>
<p>I would like to know what you all think about it.</p>
<p>This is a pretty basic but still gets the job done let me know what you think.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace idontknow
{
class thehangedman
{
public bool status = true;
public int turnsleft;
public string strdisplay;
private string originalstr;
public thehangedman(string oristr,int turnsava)
{
this.originalstr = oristr.ToLower();
this.strdisplay = string.Concat(Enumerable.Repeat("*", oristr.Length));
this.turnsleft = turnsava;
}
public string attemptchar(char attempt)
{
if(this.originalstr.Contains(attempt))
{
for (int i = 0; i < this.originalstr.Length; i++)
{
if (this.originalstr[i] == attempt)
{
StringBuilder sb = new StringBuilder(this.strdisplay);
sb[i] = attempt;
this.strdisplay = sb.ToString();
}
}
if (this.originalstr == this.strdisplay)
{
this.status = false;
return "GG kid you won";
}
return "You found a char";
}
else
{
if(this.turnsleft == 0)
{
this.status = false;
return "No attemps left originalstring = " + this.originalstr;
}
return "Char not in string attemps left = " + this.turnsleft--;
}
}
}
class Program
{
static void Main(string[] args)
{
var Game1 = new thehangedman(Console.ReadLine(),6);
while(Game1.status){
Console.WriteLine(Game1.strdisplay);
Console.WriteLine(Game1.attemptchar(char.Parse(Console.ReadLine())));
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The common C# naming conventions are to have class/struct fields, method parameters and local variable in camelCase and namespaces, type names, property, and method names in PascalCase. Additionally, field names are often introduced with an underscore.</p>\n<p>Example:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>namespace MyName.Games.Hangman\n{\n class TheHangedMan\n {\n private string _originalString;\n\n public string AttemptCharacter(char attempt)\n {\n string localVariable;\n }\n }\n}\n</code></pre>\n<hr />\n<p>Fields (i.e., class or struct variables) should be private or protected. (Protected means available to derived classes.)</p>\n<p>Expose them through properties. If they are initialized through an initializer in the declaration or within the constructor, they can be read-only. This makes clear that they will not and should not change during the whole lifetime of the game.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private readonly string _originalString;\n</code></pre>\n<p><code>strdisplay</code> is exposed. You could implement it like this</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private _displayText; // A better name than strdisplay!\npublic string DisplayText { get { return _displayText; } }\n\n// or with the newer syntax\npublic string DisplayText => _displayText;\n</code></pre>\n<p>You can also use an auto property which inherently creates an invisible field:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public string DisplayText { get; private set; }\n</code></pre>\n<p>You can assign it a value in the class with <code>DisplayText = "value";</code> but you can only read it from outside.</p>\n<hr />\n<p>You do not need the <code>this</code> keyword. E.g.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private readonly string _originalString;\nprivate int _turnsLeft;\n\npublic TheHangedMan(string originalString, int turnsAvailable)\n{\n _originalString = originalString;\n _turnsLeft = turnsAvailable;\n}\n</code></pre>\n<hr />\n<p>When you are writing the code, it seems to be a good idea to use abbreviations for identifiers, but when looking at your code six month later and for other people, this makes reading difficult. <code>turnsava</code>: it took me a while to understand it. Is it something with "turn" and "save"? Oh no, it is "turns available"!</p>\n<p>Common abbreviations and math symbols are okay (like <code>i</code> for the loop index). Also, sometimes the meaning of an abbreviation can be inferred easily from the context. Especially when used only locally. Like in the case of <code>var sb = new StringBuilder(DisplayText);</code>.</p>\n<p>Good names are important for the understanding of the code.</p>\n<p><code>bool status</code>. What does this mean? <code>true</code> = there is a status, <code>false</code> there is no status? Obviously not. Better <code>_isRunning</code>.</p>\n<p>Another option is to have the status be an enum. E.g.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>enum GameStatus\n{\n Running,\n Won,\n Lost\n}\n</code></pre>\n<p>Then the name "status" makes sense</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public GameStatus Status { get; private set; }\n</code></pre>\n<hr />\n<p>One empty line between type declarations (between the two classes), between field declarations and constructors/methods and between methods/constructors enhances readability.</p>\n<hr />\n<p>lines like <code>Console.WriteLine(Game1.attemptchar(char.Parse(Console.ReadLine())));</code> are compact but often difficult to read. Using a temporary variable gives you the opportunity to use descriptive names for intermediate results:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>char attempt = Char.Parse(Console.ReadLine());\nstring message = game.AttemptCharacter(attempt);\nConsole.WriteLine(message);\n</code></pre>\n<hr />\n<p>There are always many ways to solve problems. Here are some alternatives (which does not mean that your solution was not good):</p>\n<p><code>new String(' ', originalString.Length);</code> instead of <code>String.Concat(Enumerable.Repeat("*", originalString.Length))</code>.</p>\n<p>Instead of creating a <code>StringBuilder</code> each time for the manipulation of the display string, you could create one as class field</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private readonly StringBuilder _displayTextBuilder;\n</code></pre>\n<p>and then dynamically create the display string from it when needed</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public string DisplayText => _displayTextBuilder.ToString();\n</code></pre>\n<p>Note that the <code>StringBuilder</code> can be read-only because it is a reference type. Here <code>readonly</code> means that you cannot replace it by another instance or by <code>null</code>. It does not apply to its fields (i.e., its content).</p>\n<p>This reduces updating a character to the one-liner <code>_displayTextBuilder[i] = attempt;</code>.</p>\n<p>But since the length of the display string is constant, we can simply store it as character array <code>char[]</code> (this is the solution I have chosen).</p>\n<p>Just take the first character of the string with <code>Console.ReadLine()[0]</code> instead of <code>Char.Parse(Console.ReadLine())</code></p>\n<hr />\n<p>My attempt to write it better:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\n\nnamespace MyName.Games.Hangman\n{\n class TheHangedMan\n {\n private readonly string _originalString;\n private readonly char[] _displayChars;\n public int _turnsLeft;\n\n public TheHangedMan(string originalString, int turnsAvailable)\n {\n _originalString = originalString.ToLower();\n _turnsLeft = turnsAvailable;\n _displayChars = new String(' ', originalString.Length).ToCharArray();\n }\n\n public bool IsRunning { get; private set; } = true;\n\n public string DisplayText => new String(_displayChars);\n\n public string AttemptCharacter(char attempt)\n {\n if (_originalString.Contains(attempt)) {\n for (int i = 0; i < _originalString.Length; i++) {\n if (_originalString[i] == attempt) {\n _displayChars[i] = attempt;\n }\n }\n if (_originalString == DisplayText) {\n IsRunning = false;\n return "GG kid you won";\n }\n return "You found a char";\n } else {\n if (_turnsLeft == 0) {\n IsRunning = false;\n return "No attemps left originalstring = " + _originalString;\n }\n return "Char not in string attemps left = " + _turnsLeft--;\n }\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n string inputString = Console.ReadLine();\n var game = new TheHangedMan(inputString, 6);\n while (game.IsRunning) {\n Console.WriteLine(game.DisplayText);\n char attempt = Console.ReadLine()[0];\n string message = game.AttemptCharacter(attempt);\n Console.WriteLine(message);\n }\n }\n }\n}\n</code></pre>\n<p>But there is always something to be improved... maybe <code>GuessCharacter</code> instead of <code>AttemptCharacter</code>... it's up to you!</p>\n<p>See also: <a href=\"https://www.matheus.ro/2017/12/11/clean-code-boy-scout-rule/\" rel=\"nofollow noreferrer\">The Boy Scout Rule</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:27:34.163",
"Id": "260998",
"ParentId": "260992",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260998",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T17:24:05.370",
"Id": "260992",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"game",
"hangman"
],
"Title": "A C# hangman game"
}
|
260992
|
<p>C++ has the function <a href="https://en.cppreference.com/w/cpp/algorithm/sample" rel="noreferrer">std::sample</a> which randomly samples from a range and places the results via an output iterator. My goal is to create a utility that directly returns a single value in the event that we only want to sample a single random element from the container.</p>
<pre><code>#include <iostream>
#include <random>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <array>
template<class InputIt, class URBG>
auto singleRandomSample(InputIt t_begin, InputIt t_end, URBG&& rng)
{
using value_type = typename std::iterator_traits<InputIt>::value_type;
std::array<value_type, 1> out;
std::sample(t_begin, t_end, out.begin(), 1, rng);
return out.at(0);
}
int main()
{
std::default_random_engine rng{ std::random_device{}() };
std::unordered_set<char> vowels{ 'a', 'e', 'i', 'o', 'u', 'y' };
for (std::size_t i = 0; i < 10; ++i)
{
auto randomVowel = singleRandomSample(vowels.begin(), vowels.end(), rng);
std::cout << "Random vowel: " << randomVowel << '\n';
}
}
</code></pre>
<p>This function creates a temporary container <code>out</code> to which a single element is added, then returns that element by value. It uses an <code>std::array</code> because I know I only need room for a single element, although if I decided it was important to be able to use this with non-default-constructible types I could switch to a <code>std::vector</code> and a <code>std::back_inserter</code>.</p>
<p>Is it correct to call <code>std::sample</code> using <code>rng</code> as an argument directly, or should I be using <code>std::forward(rng)</code>?</p>
<p>It feels slightly clunky to have an entire temporary container just to store a single value that's immediately returned. Is there another way this functionality could be implemented?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T19:54:28.543",
"Id": "515063",
"Score": "0",
"body": "My goal was to, as much as possible, delegate implementation details to `std::sample`. The theory is that `std::sample` already works, but in the specific case that we only want a single element we can simplify the return type. As you identified my implementation doesn't work with non-default constructible types although it's not hard to modify it to do so. It _does_ work with things like associative containers which I consider nice."
}
] |
[
{
"body": "<p><strong>Interface</strong></p>\n<p>First of all, I would consider usage cases. If there is significant need for sampling from one-pass-only sequences (streaming from a file or network), then I would keep current interface of returning selected value. This might open a can of worms though.</p>\n<p>Otherwise I would tighten iterator requirement to forward iterator and return that iterator. Such interface would free from dealing with non-X-constructible types (where X is one or more from default, copy and move).</p>\n<p>I would name the function as below:</p>\n<ul>\n<li><p>sample_single_value (in case of first interface)</p>\n</li>\n<li><p>select_uniformly (second interface)</p>\n</li>\n<li><p>pick_uniformly (second interface, though don’t like this one much)</p>\n</li>\n</ul>\n<p><strong>Implementation</strong></p>\n<p>After checking out libstdc++ and libc++, it seems like both implement reservoir sampling, which is not hard to implement by hand for the second interface. For the first interface the current implementation looks fine (writing by hand would be more error prone and less readable).</p>\n<p><strong>Optimization for random access iterator case</strong></p>\n<p>One might be tempted to optimize for the case when population size is known, but due to the nature of RNG source being non-reentrant, the optimization will very likely produce different result due to difference in number of RNG invocations. I would not advise implementing the optimization, or at the very least I would put this quirk in big, bold, red font in the documentation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T19:54:50.847",
"Id": "261003",
"ParentId": "260995",
"Score": "3"
}
},
{
"body": "<p>A pointer is an iterator.</p>\n<pre><code>template <typename InputIterator, typename URBG>\nauto singleRandomSample(InputIterator first, InputIterator last, URBG&& rng)\n{\n using value_type = typename std::iterator_traits<InputIterator>::value_type;\n\n auto result = value_type{};\n\n std::sample(first, last, &result, 1, std::forward<URBG>(rng));\n\n return result;\n}\n</code></pre>\n<p>Or, with a better, C++20 interface:</p>\n<pre><code>template <std::input_iterator I, std::sentinel_for<I> S, typename URBG>\n requires std::uniform_random_bit_generator<std::remove_reference_t<URBG>>\nauto singleRandomSample(I first, S last, URBG&& rng)\n{\n auto result = std::iter_value_t<I>{};\n\n std::ranges::sample(first, last, &result, 1, std::forward<URBG>(rng));\n\n return result;\n}\n\ntemplate <std::input_range R, typename URBG>\n requires std::uniform_random_bit_generator<std::remove_reference_t<URBG>>\nauto singleRandomSample(R&& r, URBG&& rng)\n{\n auto result = std::ranges::range_value_t<R>{};\n\n std::ranges::sample(r, &result, 1, std::forward<URBG>(rng));\n\n return result;\n}\n</code></pre>\n<p>This requires the value type of the range to be default-constructible, but you were already counting on that with the array solution.</p>\n<p>If you want a solution that does not require default construction, you could probably do something like using an optional type—like <code>std::optional</code>, or <code>std::variant</code> with <code>std::monostate</code>—and a custom output iterator that does an emplace into it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:19:23.197",
"Id": "515065",
"Score": "0",
"body": "I believe there is UB with this solution. Going one past the last element is allowed for arrays, but I’m not sure if it is allowed for objects. I don’t think it will cause problems with current compilers, but legality seems a bit unclear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:22:30.147",
"Id": "515066",
"Score": "2",
"body": "No, there is no UB. You are allowed to increment one past any valid pointer. You just can’t dereference it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:28:30.313",
"Id": "515068",
"Score": "0",
"body": "Oh, it wouldn't have occurred to me to use a pointer as an output iterator, that's definitely much nicer than a `std::array<value_type, 1>`. And thank you for the C++20 version, it's very cool seeing examples of concepts and requirements for something like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T22:02:57.557",
"Id": "515069",
"Score": "2",
"body": "Hm, realized I’d better back up my claim that it’s not UB. So [[expr.add] sub-subpara 4.2](http://eel.is/c++draft/expr.add#4.2) explains what we all understand about arrays and pointer arithmetic. But note [the footnote](http://eel.is/c++draft/expr.add#footnote-73): “… an object that is not an array element is considered to belong to a single-element array for this purpose…”. So as long as you have a pointer to a valid object—in an array or not—then you can always increment it *at least* once. If it is the last in an array—including a single-element array—you get a “one-past-the-end” pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T10:37:37.330",
"Id": "515111",
"Score": "0",
"body": "@indi, Thanks! I didn't know one element array and an object are equivalent."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:16:00.830",
"Id": "261005",
"ParentId": "260995",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "261005",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:07:53.757",
"Id": "260995",
"Score": "7",
"Tags": [
"c++",
"random"
],
"Title": "Convenience function wrapping C++17's std::sample for distance=1 case"
}
|
260995
|
<p>I'm new to C as in I've only studied it for a year and it's my first language. I still don't know how to handle real world code and so would like to see how a real world programmer would write up a program that can find and replace text in a text file.</p>
<p>It took me 3 days to figure this out and I've tried my best to write it to standards. If anyone can suggest a way to improve this code without resorting to advanced techniques such as vectors or data structures, that would be great.</p>
<p>Here is my attempt:</p>
<pre><code>#include <string.h>
#include <stdlib.h>
#define CUTOFF 100
void *malloc_safe(size_t size); // Wrapper for malloc() that includes exiting the program upon failure of dynamic memory allocation
void *realloc_safe(void *ptr, size_t new_size); // Wrapper for realloc() that includes exiting the program upon failure of dynamic memory allocation
char *dynamic_input_fgets(void); // Initiates an input sequence with fgets() and returns the user input as a string in dynamically allocated memory
void strcpy_0n(char *dest, const char *source, size_t num); // Copies `num` number of characters from `source` into `dest`, but without copying the null-terminator into the destination.
void strshift(char *str, int num, int direction); // Shifts all characters in the null terminated string `str` by `num` indexes left or right depending on the integer `direction`. direction can only be 1(shift right) or -1(shift left).
int main(void)
{
char file_loc[1024];
char *find_str, *replace_str, *file_content_stream;
FILE *fp;
int i, cur_sizeof_malloc_str;
printf("Find and Replace a string in a text file. \nEnter file location: ");
fgets(file_loc, 1024, stdin);
if (strrchr(file_loc, '\n') != NULL)
*(strrchr(file_loc, '\n')) = '\0';
fp = fopen(file_loc, "r+");
if (fp == NULL)
{
printf("\nError opening file: Are you sure the file exists? ");
return 5;
}
printf("\nEnter string to find: ");
find_str = dynamic_input_fgets();
printf("\nEnter string to replace: ");
replace_str = dynamic_input_fgets();
// import file contents into program memory
file_content_stream = malloc_safe(CUTOFF + 5);
cur_sizeof_malloc_str = CUTOFF + 5;
*file_content_stream = 0;
while (1)
{
char tempstore[CUTOFF] = {0};
if (fgets(tempstore, CUTOFF, fp) == NULL)
{
if (feof(fp))
break;
printf("\n\nAbnormal program termination. File access function \"fgets()\" failed");
return 126;
}
strcat(file_content_stream, tempstore);
cur_sizeof_malloc_str = cur_sizeof_malloc_str + CUTOFF;
file_content_stream = realloc_safe(file_content_stream, cur_sizeof_malloc_str);
}
fclose(fp);
// find and replace action
for (i = 0; ; i++)
{
char *occurrence = strstr(file_content_stream, find_str);
if (occurrence == NULL)
break;
else
{
// turns out find and replace is easier said than done
// case: replace string is smaller or equal to find string...
{
int length_find_str = strlen(find_str);
int length_replace_str = strlen(replace_str);
// reallocate to increase space for larger string if string is longer...
if (length_find_str < length_replace_str)
{
int offset = length_replace_str - length_find_str;
file_content_stream = realloc_safe(file_content_stream, strlen(file_content_stream) + offset + 5);
// this causes occurrence to become invalid, refind occurrence again...
occurrence = strstr(file_content_stream, find_str);
if (occurrence == NULL)
break;
strshift(occurrence + length_find_str, offset, 1);
strcpy_0n(occurrence, replace_str, length_replace_str);
}
else // replace_str is smaller or equal, so no need to reallocate...
{
int offset = length_find_str - length_replace_str;
if (offset == 0)
{
strcpy_0n(occurrence, replace_str, length_replace_str);
}
else
{
strcpy_0n(occurrence, replace_str, length_replace_str);
strshift(occurrence + length_find_str, offset, -1);
}
}
}
}
}
if (i == 0)
{
printf("No matches found. ");
return 0;
}
else
{
fp = fopen(file_loc, "w");
if (fp == NULL)
{
printf("\nError opening/creating file: Are you sure the file exists? ");
return 5;
}
fputs(file_content_stream, fp);
printf("\n\nFound and replaced %d match(es)", i);
fclose(fp);
return 0;
}
}
void *malloc_safe(size_t size)
{
void *addr = malloc(size);
if (addr == NULL)
{
printf("\n\nAbnormal program termination. Call to dynamic memory allocation failed");
exit(255);
}
else
return addr;
}
void *realloc_safe(void *ptr, size_t new_size)
{
void *addr = realloc(ptr, new_size);
if (addr == NULL)
{
printf("\n\nAbnormal program termination. Call to dynamic memory allocation failed");
exit(255);
}
else
return addr;
}
char *dynamic_input_fgets(void)
{
char *str = malloc_safe(CUTOFF + 5);
int cur_sizeof_malloc_str = CUTOFF + 5;
*str = 0;
while (1)
{
char tempstore[CUTOFF] = {0};
fgets(tempstore, CUTOFF, stdin);
strcat(str, tempstore);
if (strrchr(str, '\n') != NULL) // so it has a newline at the end which means user ended input
{
str[strlen(str) - 1] = '\0';
break;
}
cur_sizeof_malloc_str = cur_sizeof_malloc_str + CUTOFF;
str = realloc_safe(str, cur_sizeof_malloc_str);
}
return str;
}
void strcpy_0n(char *dest, const char *source, size_t num)
{
size_t i;
for (i = 0; i < num; i++)
{
*dest = *source;
dest++;
source++;
}
}
void strshift(char *str, int num, int direction)
{
int i = strlen(str);
// strshift assumes there is enough allocated memory to support shift left/right movements and hence makes no checks on illegal memory access. Ensure you have allocated enough space in memory to support shift right and left.
switch (direction)
{
case 1: // shift right by num indexes/chars
for(; i >= 0 ; i--)
str[i + num] = str[i];
num--;
for(; num >= 0; num--)
str[num] = 178; // masking agent for debug, usually this shouldn't even be visible once you have overwritten it.
break;
case -1: // shift left by num indexes/chars
for (i = -num; str[i + num] != 0; i++)
str[i] = str[i + num];
str[i] = str[i + num]; // copies the null terminator too, couldn't figure out how to put this into the for loop without messing up the program.
break;
default:
printf("Secondary compile error: Illegal parameter int direction for function strshift(). Program aborting.");
exit(255);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I would not go into whether your program is working or not but I would like to give my views after seeing your code.</p>\n<p>Pointer copy can be cleaned up:</p>\n<pre><code>void strcpy_0n(char *dest, const char *source, size_t num)\n{\n ...\n *dest = *source;\n dest++;\n source++;\n ...\n}\n</code></pre>\n<p>to</p>\n<pre><code>*dest++ = *source++;\n</code></pre>\n<p><code>fgets</code> copies <code>\\0</code> at the end. So, no need to add <code>\\0</code> yourself. Same for every <code>fgets</code> in your code. Example: the following will read up to <code>1023</code> chars or <code>\\n</code> and add <code>\\0</code>.</p>\n<pre><code>fgets(file_loc, 1024, stdin);\nif (strrchr(file_loc, '\\n') != NULL)\n *(strrchr(file_loc, '\\n')) = '\\0';\n</code></pre>\n<p>Fixed type in <code>*str = 0;</code> Also, why add 5 chars? <code>+1</code> is good enough.</p>\n<pre><code>...\nfile_content_stream = realloc_safe(file_content_stream, strlen(file_content_stream) + offset + 5);\n...\n\nchar *dynamic_input_fgets(void)\n{\n char *str = malloc_safe(CUTOFF + 5);\n int cur_sizeof_malloc_str = CUTOFF + 5;\n *str = '\\0';\n\n ...\n}\n</code></pre>\n<p>Reading a whole file is never good practice as the file can be huge. But if you want to read it all, don't <code>malloc/realloc</code> a huge number of times as this decreases performance. Instead use <code>ftell</code> to get the size of file, <code>malloc</code> once and read till <code>feof</code>.</p>\n<pre><code>while (!feof(fp)) {\n fgets(...)\n}\n</code></pre>\n<p>Unnecessary re-calculation of fixed values and can be moved out of <code>for (i = 0; …; i++)</code>:</p>\n<pre><code>int length_find_str = strlen(find_str);\nint length_replace_str = strlen(replace_str);\nint offset = length_replace_str - length_find_str;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T12:15:22.640",
"Id": "515117",
"Score": "0",
"body": "Thanks a lot for your review! \n\n1) First of all, I already know that fgets always returns a null-terminated string. The main purpose was actually to remove the newline character that results when you exit the input sequence by pressing Enter. Having the newline character at the end results in a fail on my system (Windows, mingw-w64) as the system cannot find the specified file. This makes sense, as the newline character is not a part of the file's name.\n2) `Fixed type in *str = 0;` I didn't get what you meant by this... Can you please elaborate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T12:23:04.857",
"Id": "515118",
"Score": "0",
"body": "3) Nice catch with the unnecessary recalculations, now I'm looking at the code and thinking... 'Oh yeah, that IS unnecessary...'\n4) About your opinion on the `while (!(feof()))`, please look at this thread https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong\nEven before stackoverflow, I personally always had problems with logic when I tried `while(!feof(fp))`, so I personally abhor using this construct to stop the loop and prefer breaking instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:59:55.480",
"Id": "515129",
"Score": "0",
"body": "`*str = 0` did you intend to have `0` or `\\0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T17:25:21.157",
"Id": "515133",
"Score": "0",
"body": "they are literally the exact same thing though..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:13:49.837",
"Id": "515326",
"Score": "1",
"body": "`*dest++ = *source++;` is not necessarily an improvement. Yes it is commonly used but that doesn't make that line readable in itself - the only reason people can read it without trouble is because they have seen it before. Everyone else get a \"WTF\" moment. And since it doesn't lead to any efficiency improvement, there's no apparent need to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:37:54.937",
"Id": "515344",
"Score": "0",
"body": "@Lundin This is exactly why I broke down that construct when I wrote it... I already knew of this compact construct but it wasn't immediately clear what the order of operations is and I prefer clarity in code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T06:31:49.277",
"Id": "515377",
"Score": "0",
"body": "@AhnafAbdullah Yep so leave that part as it is. _However_ `while(*dest++ = *source++)` checks for null termination, your code doesn't do that. You only check the counter. You should check for both. Not sure if any review caught that problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T22:00:45.443",
"Id": "515460",
"Score": "0",
"body": "@Lundin the entire point of that function is to copy characters to and from a string independent of the null-terminator...\n```for (i = 0; i < num; i++) { *dest = *source; dest++; source++; }\n```\nI don't want it to check for null-termination because it's only supposed to copy num number of characters"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T05:59:18.110",
"Id": "515477",
"Score": "0",
"body": "@AhnafAbdullah Then it's just nonsense, use memcpy."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T09:55:18.967",
"Id": "261028",
"ParentId": "261001",
"Score": "3"
}
},
{
"body": "<p>In addition to mangupt's excellent points, I would like to add:</p>\n<h1>Split up the code into more functions</h1>\n<p>Your <code>main()</code> is still quite large, and there are lots of opportunities to split off functionality into their own functions. This keeps <code>main()</code> smaller and easier to read and maintain. For example, consider the code that removes the newline character:</p>\n<pre><code>if (strrchr(file_loc, '\\n') != NULL)\n *(strrchr(file_loc, '\\n')) = '\\0';\n</code></pre>\n<p>Even for just these two lines you can create a function:</p>\n<pre><code>static void remove_newline(char *line) {\n char *newline = strchr(line, '\\n');\n if (newline)\n *newline = '\\0';\n}\n</code></pre>\n<p>Since this piece of code now has a proper name, it's much clearer what you are doing when you call it from <code>main()</code>.</p>\n<h1>Avoid magic numbers</h1>\n<p>Avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>, like 1024 for the size of <code>file_loc</code>. The first thing to do is to give them a proper name:</p>\n<pre><code>#define MAX_FILENAME_SIZE 1024\n</code></pre>\n<p>And then use the name instead of the number where appropriate. However, also think about why you chose this particular number. What is special about 1024? Are all filenames guaranteed to be less than 1024 characters? What happens if someone inputs a filename that is longer?</p>\n<p>Other examples in your code are 5, 126 and 255 for the exit codes. Why did you pick those values? Does it matter for the caller that they get different codes because of different errors? If there is no good reason, I recommend you just use <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a> for the return codes.</p>\n<h1>Use <code>memmove()</code> and <code>memcpy()</code></h1>\n<p>Your <code>strshift()</code> function is not necessary, the standard library provides you with <a href=\"https://en.cppreference.com/w/c/string/byte/memmove\" rel=\"nofollow noreferrer\"><code>memmove()</code></a> which basically does the same thing. The <code>strcpy_0n()</code> blindly copies <code>num</code> bytes, so it can be replaced with <a href=\"https://en.cppreference.com/w/c/string/byte/memcpy\" rel=\"nofollow noreferrer\"><code>memcpy()</code></a>.</p>\n<h1>Consider not reading in the whole file</h1>\n<p>There are several issues with reading in the whole file in memory, and then doing search/replace actions on it. First, consider that files might be much bigger than the amount of available memory. But more importantly, even if it fits in memory, calling <code>strshift()</code> or <code>memmove()</code> repeatedly might be very costly if the buffer is large. Even worse, if the replacement string is larger than the search string, you have to grow the buffer for every occurence of the search string.</p>\n<p>I suggest you try to make it work by reading input into a small, fixed buffer. Scan for the string in that, if not found you just print the whole buffer. If it is found, print everything up to the start of the occurence of the search string, then print the replacement string, then continue search from right after the first occurence of the search string, until you reach the end of the buffer. Then read in the next part of the file and repeat. The only problem left is to properly handle the search string starting near the end of the buffer, so it was not fully read in, but that is also easily solvable.</p>\n<h1>Make your program work without needing interactive I/O</h1>\n<p>After starting your program, it asks you to enter the filenames and search and replacement strings. While this is fine if you just run the program manually once or twice, it becomes a problem if you want to use your program in a more automated fashion, like having another script call it to search and replace things. Even for interactive use, it's much nicer if you can specify everything on the command line, since shells typically have a history, globbing/tab completion for filenames and so on. I suggest you do the following things instead:</p>\n<h2>Read the search and replacement strings from the program's arguments</h2>\n<p>You can have the <a href=\"https://en.cppreference.com/w/cpp/language/main_function\" rel=\"nofollow noreferrer\"><code>main()</code> function</a> read the arguments given on the command line when your program was started. Use this for the search and replacement string:</p>\n<pre><code>int main(int argc, char *argv[]) {\n if (argc <= 2) {\n fprintf(stderr, "Not enough arguments!\\n");\n return EXIT_FAILURE;\n }\n\n const char *find_str = argv[1];\n const char *replace_str = argv[2];\n\n ...\n}\n</code></pre>\n<h2>Read the file from <code>stdin</code> and write the output to <code>stdout</code></h2>\n<p>Instead of asking for filenames and opening the files yourself, just use <code>stdin</code> and <code>stdout</code>. On the command line you can use input redirection to ensure it reads from a given file and writes to another file. Combined with the above arguments for the search and replacement string, this would then look like:</p>\n<pre><code>./search_and_replace speling spelling < input.txt > output.txt\n</code></pre>\n<p>But even better, you can now make your program part of more complex commands, for example (my aplogies for the <a href=\"https://en.wikipedia.org/wiki/Cat_(Unix)#Useless_use_of_cat\" rel=\"nofollow noreferrer\">useless use of cat</a> here):</p>\n<pre><code>cat input.txt | ./search_and_replace speling spelling | head -10\n</code></pre>\n<p>Note that input redirection is also working on Windows.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:16:47.903",
"Id": "515329",
"Score": "1",
"body": "`strncpy` is dangerous and should be avoided when possible. In particular, do not tell newbies to use it! See [Is strcpy dangerous and what should be used instead?](https://software.codidact.com/posts/281518)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T16:50:46.733",
"Id": "515341",
"Score": "0",
"body": "@Lundin Good point, and it wasn't even necessary to use `strncpy()` as a replacement, it was actually doing the same as `memcpy()`. I updated the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:35:12.880",
"Id": "515342",
"Score": "0",
"body": "Thanks for the review! \n1) You should see my previous code bases lol... Back when I was new I'd write everything into the main function to the point where I'd copy and paste huge chunks of code... I've grown out of this odd behaviour now but I think making a function that's only two lines long and called only twice is a bit ridiculous\n2) Excellent point about avoiding magic numbers, though I only use macros for meaningful numbers... 1024 is not a random number but its a number large enough to store a file name, and I hope the user will never find/replace a file larger in name than that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:40:39.427",
"Id": "515345",
"Score": "0",
"body": "3) **I believe memmove() does not behave in the same way as strshift()** and hence I avoided using those. I just needed to shift the contents in the string and writing down this function was a part of the problem-solving that allowed me to achieve the goals of this program (also, I prefer avoiding memory management functions cause they are quite hard to use...)\n4) Input redirection is really hard for me, and since I am on Windows I avoided implementing that. For example `./search_and_replace speling spelling < input.txt > output.txt` I have no idea what happens here or how this works..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:42:30.600",
"Id": "515346",
"Score": "0",
"body": "Every other point made in this post was extremely helpful, thanks! Reading the search and replace strings from program's arguments is a very good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T20:51:23.817",
"Id": "515351",
"Score": "1",
"body": "1) Functions have the benefit that *you* can give them a *name*. Even if it's two lines of code that are only used once, you still get the benefit that the name will document what those two lines of code do. Very useful for others, and your future self when you're reading back your old code :) 4) If you start your program from [cmd.exe](https://en.wikipedia.org/wiki/Cmd.exe), that line should cause `stdin` to read from input.txt and `stdout` to write to output.txt. See [this manual](https://ss64.com/nt/syntax-redirection.html)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T11:32:01.550",
"Id": "261035",
"ParentId": "261001",
"Score": "4"
}
},
{
"body": "<p>Good points made already, let me add a few more if I may. Before that, a small comment regarding:</p>\n<blockquote>\n<p>I still don't know how to handle real world code and so would like to\nsee how a real world programmer would write up a program that can find\nand replace text in a text file. ... If anyone can suggest a way to\nimprove this code without resorting to advanced techniques such as\nvectors or data structures, that would be great.</p>\n</blockquote>\n<p>Well, in the real-world, search & replace is much more involved than adding a couple of data-structures. Wikipedia summarizes it nicely I think, just for <a href=\"https://en.wikipedia.org/wiki/String-searching_algorithm\" rel=\"nofollow noreferrer\">searching</a>.</p>\n<p>Anyway, back to reviewing.</p>\n<h2>Coding Style</h2>\n<pre><code>int main(void)\n{\n char file_loc[1024];\n char *find_str, *replace_str, *file_content_stream;\n FILE *fp;\n int i, cur_sizeof_malloc_str;\n ...\n\nwhile (1)\n{\n char tempstore[CUTOFF] = {0};\n if (fgets(tempstore, CUTOFF, fp) == NULL)\n {\n ...\n strcat(file_content_stream, tempstore);\n cur_sizeof_malloc_str = cur_sizeof_malloc_str + CUTOFF;\n file_content_stream = realloc_safe(file_content_stream, cur_sizeof_malloc_str);\n ...\n\n// find and replace action\nfor (i = 0; ; i++)\n{\n char *occurrence = strstr(file_content_stream, find_str);\n if (occurrence == NULL)\n break;\n else\n {\n {\n int length_find_str = strlen(find_str);\n int length_replace_str = strlen(replace_str);\n ...\n</code></pre>\n<p>There are lots of style guidelines, but when it comes to plain standard C (pretty rare in the real word) consider taking a minimalistic approach, ideally using common idioms and conventions.</p>\n<p>Consider keeping your variable names short but descriptive, and only use underscores when naming functions. If need be, a short in-line comment can provide a brief hint.</p>\n<p>Also consider defining each variable on its own line, and probably initialize them with default/fallback values.</p>\n<p>These few and easily picked up suggestions all help in keeping the code clean and easily maintainable.</p>\n<p>In the following sample I've also added uppercase comments to draw your attention to a few more things I think you should consider:</p>\n<pre><code>/* K&R INDENT STYLE (mostly) */\n\nint main(void)\n{\n char fname[MAX_FNAME] = {'\\0'}; // absolute or relative path (c-string)\n char *fbuf = NULL; // file contents (c-string)\n char *tokfind = NULL; // find token (c-string)\n char *tokrepl = NULL; // replace-with token (c-string)\n FILE *fp = NULL;\n int allocsz = 32; // initial alloc-ahead size\n int i;\n ...\n\nwhile (1) {\n char tmpbuf[CUTOFF] = {'\\0'};\n if (fgets(tmpbuf, CUTOFF, fp) == NULL) {\n ...\n strcat(fbuf, tmpbuf);\n allocsz += CUTOFF;\n fbuf = realloc_safe(fbuf, allocsz);\n ...\n\n// find and replace action\nfor (i=0; /* void */ ; i++) {\n char *cpmatch = strstr(fbuf, tokfind); /* "cp" PREFIX IS char-pointer IDIOM */\n if (cpmatch == NULL)\n break;\n \n /* NO NEED FOR else AFTER if () {...; break;}\n (IT SAVES US 1 LEVEL OF INDENTATION) */\n \n /* WHY THE EXTRA SCOPE-NESTING HERE? */\n {\n /* SHOULD MOVE THESE OUTSIDE THE LOOP */\n int len1tokfind = strlen(tokfind);\n int len2tokrepl = strlen(tokrepl);\n ...\n\n \n</code></pre>\n<h2>Function Prototyping</h2>\n<p>Function prototypes are quite useful in large projects, especially for providing public interfaces to private implementations, but in tiny 1-module programs like this, they are of little use (if any at all). They just clutter the code for no good reason.</p>\n<p>Consider defining your functions in their calling order (with <code>main()</code> defined last) and remove their declarations (prototypes). Often this also helps in better organizing the logic of the program.</p>\n<p>Either way, please document your function definitions (it doesn't have to be a long text). Right now they are all undocumented.</p>\n<h2>Re-inventing the Wheel</h2>\n<p>Avoid re-implementing already available well-tested functions, unless they really (really really really) don't cut it for you (that said, re-inventing the wheel can be an awesome learning-experience).</p>\n<p>For example:</p>\n<pre><code>// Initiates an input sequence with fgets() and returns\n// the user input as a string in dynamically allocated memory\nchar *dynamic_input_fgets(void);\n</code></pre>\n<p>Although the standard C library doesn't provide an equivallent function, the almost everywhere available, open-source function: <strong><a href=\"https://linux.die.net/man/3/getline\" rel=\"nofollow noreferrer\"><code>getline()</code></a></strong> does exactly that, and more (btw, from a beginner's POV, using it properly is also a good learning-experience).</p>\n<h2>Error Handling</h2>\n<p>It's been already mentioned by <a href=\"https://codereview.stackexchange.com/a/261035/242439\">G.Sliepen</a> that for this program multiple exit codes don't make much sense (if any at all).</p>\n<p>If you really have to, the standard C library provides the <a href=\"https://en.wikipedia.org/wiki/Errno.h\" rel=\"nofollow noreferrer\"><code>errno.h</code></a> header, for basic error-handling. Consider using that instead.</p>\n<p>For debugging purposes, you may also want to check out the <a href=\"https://en.wikipedia.org/wiki/Assert.h\" rel=\"nofollow noreferrer\"><code>assert.h</code></a> header and the <code>assert()</code> macro. It's main purpose is to immediately exit on error, thus making it easier to find the cause.</p>\n<p>In production code, errors are usually handled quite differently, with several approaches and mechanisms depending on the project, but they rarely exit immediately.</p>\n<p>Instead of printing error-messages and exiting from within functions, consider making them return errors (either directly or via a parameter which can be anything, ranging from a simple type to a pointer to an error-handler mechanism).</p>\n<p>This way you can have a centralized error-handler, responsible for messaging and further actions (it can be your <code>main()</code> for starters).</p>\n<p>Btw, I see <strong>no good reason</strong> for having <code>malloc_safe()</code> and <code>realloc_safe()</code>. All they do is hiding error-checking one level deeper, and that's rarely a good thing. Just do your error-checking immediately after calling <code>malloc()</code> or <code>realloc()</code>, in the same scope.</p>\n<p>Another point regarding errors:</p>\n<pre><code>printf("\\nError opening file: Are you sure the file exists? ");\n</code></pre>\n<p>Consider directing all your error-messages to <code>stderr</code> instead of <code>stdout</code>:</p>\n<pre><code>fprintf(stderr, "Error opening file %s\\n", fname);\n</code></pre>\n<p>It's not only good practice, but it can also help in separating normal output from error-messages via redirection (2 is the <code>stderr</code> stream id). See also <a href=\"https://stackoverflow.com/questions/19870331/why-use-stderr-when-printf-works-fine/19870435\">this topic</a>.</p>\n<p>On a last note for this section, <strong>validate</strong> the results of functions before using them. For example:</p>\n<pre><code>printf("\\nEnter string to find: ");\nfind_str = dynamic_input_fgets();\n\nprintf("\\nEnter string to replace: ");\nreplace_str = dynamic_input_fgets();\n</code></pre>\n<p>Here you don't check the returned values of <code>find_str</code> and <code>replace_str</code> before using them later on. When the user enters here 2 empty strings, your program goes into an infinite-loop later on (alternatively you can catch the error then, but you don't do that either).</p>\n<p>You could easily prevent that, by demanding valid input before accepting it. Something like this:</p>\n<pre><code>for (;;) {\n printf("\\nEnter string to find: ");\n find_str = dynamic_input_fgets();\n if ( !find_str ) {\n /* fatal error: exit or direct flow to the error-handler */\n }\n // stop if valid\n if ( *find_str != '\\0' ) {\n break;\n }\n // keep asking if invalid\n free( find_str );\n puts( "please type in at least 1 character" );\n}\n</code></pre>\n<h2>Being Consistent</h2>\n<p>Using the same example again:</p>\n<pre><code>printf("Find and Replace a string in a text file. \\nEnter file location: ");\nfgets(file_loc, 1024, stdin);\n...\nprintf("\\nEnter string to find: ");\nfind_str = dynamic_input_fgets();\n\nprintf("\\nEnter string to replace: ");\nreplace_str = dynamic_input_fgets();\n</code></pre>\n<p>Consider being consistent across similar situations. In the above example, you have 3 c-strings which all can benefit from being dynamically allocated, but the 1st one is defined statically and read with <code>fgets()</code> while the last 2 are properly defined as dynamic and read with <code>dynamic_input_fgets()</code>. I see no good reason for that, especially having <code>file_loc</code> as a static c-string limited to 1024 bytes long. My guess would be some kind of issue with your custom <code>dynamic_input_fgets()</code> when it comes to <code>file_loc</code>, but if so, that could be another reason for using <code>getline()</code> instead of your custom one.</p>\n<p>Consider the following alternative approach which stays consistent across all these 3 c-strings regarding their definition and inputting, and also summarizes most of my suggestions so far (it also uses some trivial custom functions like <code>str_trim()</code>, <code>str_clear_eol()</code>, <code>file_exists()</code>, etc, but the main point stays the same).</p>\n<pre><code>char *fname = NULL; // absolute or relative path (c-string)\nchar *tokfind = NULL; // find token (c-string)\nchar *tokrepl = NULL; // replace-with token (c-string)\nsize_t linesz = 0; // for passing it to getline()\n\n// get & validate the filename\nprintf("Enter filename: ");\nif ( -1 == getline(&fname, &linesz, stdin) ) {\n goto cleanup_and_fail;\n}\nstr_trim( fname );\nif ( !file_exists(fname) ) {\n fprintf(stderr, "No such file found\\n");\n goto cleanup_and_fail;\n}\n\n// get & validate the find token\nfor (;;) {\n printf("Enter string to find: ");\n if ( -1 == getline( &tokfind, &linesz, stdin) ) {\n fprintf(stderr, "stdin read error, aborting!\\n");\n goto cleanup_and_fail;\n }\n str_clear_eol( tokfind );\n if ( *tokfind != '\\0' ) {\n break;\n }\n puts( "please type in at least 1 character, try again..." );\n}\n\n// get & validate the replace-with token\n...\n</code></pre>\n<p>The <code>goto</code> statements used like that can help in cleaning-up before exiting (successfully or not) without cluttering the main body of the code. I'm addressing that in the <strong>Cleaning Up</strong> section, below.</p>\n<h2>Cleaning Up</h2>\n<p>Consider cleaning up your dynamically allocated memory before exiting (successfully or not). In some cases it doesn't matter, but in others it does (memory leaks). In any case, consider making it a habit to <strong>always</strong> clean up.</p>\n<p>This is often easier said than done, but I really think you should deal with it if you are to use C seriously.</p>\n<p>You don't do it in your code, but in this case it's easy to add it. In a nutshell you want to <code>free()</code> everything you have successfully <code>malloc()</code>/<code>calloc()</code>/<code>realloc()</code>'ed. That pretty much means your:</p>\n<pre><code>char *find_str, *replace_str, *file_content_stream;\n</code></pre>\n<p>and if you follow my suggestion and change <code>file_loc</code> to a dynamically allocated buffer, then that one too.</p>\n<p>Instead of repeating the cleanup code at several exit points scattered around, you can gather it at the bottom of <code>main()</code> (or another error-handler) as following (btw, that's another reason of having a centralized error-handling scope, instead of exiting from within functions on error):</p>\n<pre><code>int main( void )\n{\n // will be dynamically allocated\n char *fname = NULL; // absolute or relative (c-string)\n char *fbuf = NULL; // file contents (c-string)\n char *tokfind = NULL; // find token (c-string)\n char *tokrepl = NULL; // replace token (c-string)\n ...\n\n /* dynamic allocation of any or all of the above */\n ...\n\n if ( fatal-error ) {\n // whatever extra work needed\n goto cleanup_and_fail;\n }\n ...\n\n if ( conditional-normal-exit ) {\n goto cleanup_and_exit;\n }\n ...\n\ncleanup_and_exit:\n free( fname );\n free( tokfind );\n free( tokrepl );\n free( fbuf );\n return EXIT_SUCCESS;\n\ncleanup_and_fail:\n free( fname );\n free( tokfind );\n free( tokrepl );\n free( fbuf );\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>Hopefully, the sample code at the end of the <strong>Being Consistent</strong> section makes more sense now.</p>\n<p>Anyway, that's a simplification of the general idea (in the real-word you often work with class-like instants, with their own destructors).</p>\n<h2>Scalability</h2>\n<p>If you plan to use the search & replace functionality in different parts of the program, say after adding more features (or even to other projects) consider making it a re-usable function.</p>\n<p>For example, a function accepting a source c-string and returning the processed result along with supporting information.</p>\n<p>Or a function that accepts a text-stream pointer to modify its contents.</p>\n<p>Or any re-usable combination.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T13:58:58.790",
"Id": "515798",
"Score": "0",
"body": "Thank you for your lengthy discourse! First of all I'd like to say that I avoided freeing the allocated memory because it's a small application and closing the program frees the memory anyway. Your example codes definitely look very professional and feel as if it was part of something that was much larger in size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T14:09:13.787",
"Id": "515800",
"Score": "0",
"body": "2) My reasoning behind giving file_loc 1024 characters was because it's much simpler to have a static char array instead of a malloc-string and that it's very unlikely that a file location string will be larger than 1024 characters. It was my way of simplifying and making optimizations. There's no issue with dynamic_input_fgets() at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T14:09:22.820",
"Id": "515801",
"Score": "0",
"body": "3) malloc_safe and realloc_safe are just function wrappers that behave in the same way as malloc/realloc (because they have the same parameters and return types) except that they check for NULL returns and perform error handling, because copying and pasting the same code multiple times in the program made it quite redundant. While your method of error handling is very elegant it is also quite hard for me and would require some getting used to (not something that I as a beginner would think of on my own)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-04T11:10:05.683",
"Id": "518310",
"Score": "0",
"body": "@AhnafAbdullah, sorry for the late response. 1) Yes, cleanup is not necessary here, and actually when it has lots to do it's often omitted on purpose to speed up termination. However it hurts scalability and one has to remember to do it after scaling up the project. 2) It is not that rare in our Unicode world, since files can be nested deep down in the path tree, with the naming of each node being controlled by the user. Btw, the find & replace tokens are way less likely to ever be longer than 1024 bytes, so if nothing else it would make more sense to have those fixed, instead of the filename."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-04T11:17:29.693",
"Id": "518311",
"Score": "1",
"body": "@AhnafAbdullah, 3) Yeah I get why you did it, but my whole reply was a response to your original \"how real-world programmers would do things\" query. So, this is not how error-handling is done out there ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:18:16.877",
"Id": "261082",
"ParentId": "261001",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261082",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T18:46:02.367",
"Id": "261001",
"Score": "4",
"Tags": [
"beginner",
"c",
"text-editor"
],
"Title": "C: Find and Replace in a text file (by a new programmer)"
}
|
261001
|
<p>I have made this small checkout stepper with Vue (v 2.x.x):</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>var app = new Vue({
el: "#cart",
data: {
stepCounter: 1,
steps: [{
step: 1,
completed: false,
text: "Cart"
},
{
step: 2,
completed: false,
text: "Shipping"
},
{
step: 3,
completed: false,
text: "Payment"
},
{
step: 4,
completed: false,
text: "Confirmation"
}
]
},
methods: {
doPrev: function() {
if (this.stepCounter > 1) {
this.stepCounter--;
this.doCompleted();
}
},
doNext: function() {
if (this.stepCounter <= this.steps.length) {
this.stepCounter++;
this.doCompleted();
}
},
doCompleted: function() {
this.steps.forEach(item => {
item.completed = item.step < this.stepCounter;
});
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
font-family: "Poppins", sans-serif;
}
.progressbar {
display: flex;
list-style-type: none;
counter-reset: steps;
padding-top: 50px;
justify-content: space-between;
}
.progressbar li {
font-size: 13px;
text-align: center;
position: relative;
flex-grow: 1;
flex-basis: 0;
color: rgba(0, 0, 0, 0.5);
font-weight: 600;
}
.progressbar li.completed {
color: #ccc;
}
.progressbar li.active {
color: #4caf50;
}
.progressbar li::after {
counter-increment: steps;
content: counter(steps, decimal);
display: block;
width: 30px;
height: 30px;
line-height: 30px;
border: 2px solid rgba(0, 0, 0, 0.5);
background: #fff;
border-radius: 50%;
position: absolute;
left: 50%;
margin-left: -15px;
margin-top: -60px;
}
.progressbar li.active::after,
.progressbar li.completed::after {
background: #4caf50;
border-color: rgba(0, 0, 0, 0.15);
color: #fff;
}
.progressbar li.completed::after {
content: '\2713';
}
.progressbar li::before {
content: "";
position: absolute;
top: -26px;
left: -50%;
width: 100%;
height: 2px;
background: rgba(0, 0, 0, 0.5);
z-index: -1;
}
.progressbar li.active::before,
.progressbar li.completed::before,
.progressbar li.active+li::before {
background: #4caf50;
}
.progressbar li:first-child::before {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div id="cart" class="mt-2">
<div class="container">
<ul class="progressbar">
<li v-for="(step, index) in steps" v-bind:class="{ active: index + 1 === stepCounter, completed: step.completed === true }">{{step.text}}</li>
</ul>
</div>
<div class="container px-4 mt-5 text-center">
<div class="d-flex justify-content-between">
<button type="button" class="btn btn-sm btn-success" v-bind:class="{ disabled : stepCounter === 1}" @click="doPrev()">Prev</button>
<button type="button" class="btn btn-sm btn-success" v-bind:class="{ disabled : stepCounter > steps.length}" @click="doNext()">Next</button>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<h3>Questions</h3>
<ol>
<li>Is there any room for "shortening" the code?</li>
<li>Anything inconsistent at the logic level?</li>
</ol>
|
[] |
[
{
"body": "<blockquote>\n<h3>Is there any room for "shortening" the code?</h3>\n</blockquote>\n<h3>Shorthands</h3>\n<p><a href=\"https://vuejs.org/v2/guide/syntax.html#Shorthands\" rel=\"nofollow noreferrer\">Shorthands</a> can simplify the markup. The click handlers already use the shorthand <code>@click</code> instead of <code>v-on:click</code>. The bindings can be simplified as well. For example - instead of:</p>\n<blockquote>\n<pre><code>v-bind:class="..."\n</code></pre>\n</blockquote>\n<p>the <code>v-bind</code> can be omitted:</p>\n<pre><code>:class="..."\n</code></pre>\n<h3>Watch out!</h3>\n<p><a href=\"https://wiki.godvillegame.com/images/thumb/b/b8/Ceiling_cat.jpg/298px-Ceiling_cat.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://wiki.godvillegame.com/images/thumb/b/b8/Ceiling_cat.jpg/298px-Ceiling_cat.jpg\" alt=\"1\" /></a></p>\n<p>Yesterday there was <a href=\"https://codereview.stackexchange.com/a/260915/120114\">an answer</a> to <a href=\"https://codereview.stackexchange.com/q/260898/120114\">your TODO app post</a> which suggested using <a href=\"https://vuejs.org/v2/guide/computed.html\" rel=\"nofollow noreferrer\">computed properties</a>. With the current architecture using a computed property doesn't seem feasible, but a <a href=\"https://vuejs.org/v2/guide/computed.html#Watchers\" rel=\"nofollow noreferrer\">watcher method</a> could be employed. Instead of setting up a method like <code>doCompleted()</code> that must be called manually, a watcher method can be used to adjust the values whenever that value changes.</p>\n<pre><code>watch: {\n stepCounter: function(newValue, oldValue) {\n this.steps.forEach(item => {\n item.completed = item.step < this.stepCounter;\n });\n }\n},\n</code></pre>\n<p>Note that <code>newValue</code> could be used instead of <code>this.stepCounter</code>.</p>\n<p>While it would occupy the same number of lines as the current code, it takes the burden off the methods <code>doPrev</code> and <code>doNext</code> of having to call the method <code>doCompleted</code>. See the demo below for an illustration of this.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const makeStep = (text, index) => {return {text, step: ++index, completed: false}};\nconst steps = ['Cart', 'Shipping', 'Payment', 'Confirmation'].map(makeStep);\nvar app = new Vue({\n el: \"#cart\",\n data: {\n stepCounter: 1,\n steps\n },\n watch: {\n stepCounter: function(newValue, oldValue) {\n this.steps.forEach(item => {\n item.completed = item.step < this.stepCounter;\n });\n }\n },\n methods: {\n doPrev: function() {\n if (this.stepCounter > 1) {\n this.stepCounter--;\n }\n },\n doNext: function() {\n if (this.stepCounter <= this.steps.length) {\n this.stepCounter++;\n }\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n margin: 0;\n padding: 0;\n font-family: \"Poppins\", sans-serif;\n}\n\n.progressbar {\n display: flex;\n list-style-type: none;\n counter-reset: steps;\n padding-top: 50px;\n justify-content: space-between;\n}\n\n.progressbar li {\n font-size: 13px;\n text-align: center;\n position: relative;\n flex-grow: 1;\n flex-basis: 0;\n color: rgba(0, 0, 0, 0.5);\n font-weight: 600;\n}\n\n.progressbar li.completed {\n color: #ccc;\n}\n\n.progressbar li.active {\n color: #4caf50;\n}\n\n.progressbar li::after {\n counter-increment: steps;\n content: counter(steps, decimal);\n display: block;\n width: 30px;\n height: 30px;\n line-height: 30px;\n border: 2px solid rgba(0, 0, 0, 0.5);\n background: #fff;\n border-radius: 50%;\n position: absolute;\n left: 50%;\n margin: -60px 0 0 -15px;\n}\n\n.progressbar li.active::after,\n.progressbar li.completed::after {\n background: #4caf50;\n border-color: rgba(0, 0, 0, 0.15);\n color: #fff;\n}\n\n.progressbar li.completed::after {\n content: '\\2713';\n}\n\n.progressbar li::before {\n content: \"\";\n position: absolute;\n top: -26px;\n left: -50%;\n width: 100%;\n height: 2px;\n background: rgba(0, 0, 0, 0.5);\n z-index: -1;\n}\n\n.progressbar li.active::before,\n.progressbar li.completed::before,\n.progressbar li.active+li::before {\n background: #4caf50;\n}\n\n.progressbar li:first-child::before {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js\"></script>\n<link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css\" rel=\"stylesheet\" />\n\n<div id=\"cart\" class=\"mt-2\">\n <div class=\"container\">\n <ul class=\"progressbar\">\n <li v-for=\"(step, index) in steps\" :class=\"{ active: index + 1 === stepCounter, completed: step.completed }\">{{step.text}}</li>\n </ul>\n </div>\n\n <div class=\"container px-4 mt-5 text-center\">\n <div class=\"d-flex justify-content-between\">\n <button type=\"button\" class=\"btn btn-sm btn-success\" :class=\"{ disabled : stepCounter === 1}\" @click=\"doPrev()\">Prev</button>\n <button type=\"button\" class=\"btn btn-sm btn-success\" :class=\"{ disabled : stepCounter > steps.length}\" @click=\"doNext()\">Next</button>\n </div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If the data structure can be modified such that the <em>completed</em> property isn't needed, then the markup could use the condition <code>step.step < stepCounter</code> to determine when the <code>completed</code> class is added to each list item. See the snippet below for a demonstration of this.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const makeStep = (text, index) => {return {text, step: ++index}};\nconst steps = ['Cart', 'Shipping', 'Payment', 'Confirmation'].map(makeStep);\nconst app = new Vue({\n el: \"#cart\",\n data: {\n stepCounter: 1,\n steps\n },\n methods: {\n doPrev: function() {\n if (this.stepCounter > 1) {\n this.stepCounter--;\n }\n },\n doNext: function() {\n if (this.stepCounter <= this.steps.length) {\n this.stepCounter++;\n }\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n margin: 0;\n padding: 0;\n font-family: \"Poppins\", sans-serif;\n}\n\n.progressbar {\n display: flex;\n list-style-type: none;\n counter-reset: steps;\n padding-top: 50px;\n justify-content: space-between;\n}\n\n.progressbar li {\n font-size: 13px;\n text-align: center;\n position: relative;\n flex-grow: 1;\n flex-basis: 0;\n color: rgba(0, 0, 0, 0.5);\n font-weight: 600;\n}\n\n.progressbar li.completed {\n color: #ccc;\n}\n\n.progressbar li.active {\n color: #4caf50;\n}\n\n.progressbar li::after {\n counter-increment: steps;\n content: counter(steps, decimal);\n display: block;\n width: 30px;\n height: 30px;\n line-height: 30px;\n border: 2px solid rgba(0, 0, 0, 0.5);\n background: #fff;\n border-radius: 50%;\n position: absolute;\n left: 50%;\n margin: -60px 0 0 -15px;\n}\n\n.progressbar li.active::after,\n.progressbar li.completed::after {\n background: #4caf50;\n border-color: rgba(0, 0, 0, 0.15);\n color: #fff;\n}\n\n.progressbar li.completed::after {\n content: '\\2713';\n}\n\n.progressbar li::before {\n content: \"\";\n position: absolute;\n top: -26px;\n left: -50%;\n width: 100%;\n height: 2px;\n background: rgba(0, 0, 0, 0.5);\n z-index: -1;\n}\n\n.progressbar li.active::before,\n.progressbar li.completed::before,\n.progressbar li.active+li::before {\n background: #4caf50;\n}\n\n.progressbar li:first-child::before {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js\"></script>\n<link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css\" rel=\"stylesheet\" />\n\n<div id=\"cart\" class=\"mt-2\">\n <div class=\"container\">\n <ul class=\"progressbar\">\n <li v-for=\"(step, index) in steps\" v-bind:class=\"{ active: index + 1 === stepCounter, completed: step.step < stepCounter }\">{{step.text}}</li>\n </ul>\n </div>\n\n <div class=\"container px-4 mt-5 text-center\">\n <div class=\"d-flex justify-content-between\">\n <button type=\"button\" class=\"btn btn-sm btn-success\" v-bind:class=\"{ disabled : stepCounter === 1}\" @click=\"doPrev()\">Prev</button>\n <button type=\"button\" class=\"btn btn-sm btn-success\" v-bind:class=\"{ disabled : stepCounter > steps.length}\" @click=\"doNext()\">Next</button>\n </div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>CSS: margin rules</h3>\n<p>The ruleset <code>.progressbar li::after {</code> contains these rules:</p>\n<blockquote>\n<pre><code>margin-left: -15px;\nmargin-top: -60px;\n</code></pre>\n</blockquote>\n<p>Presuming there is no margin inherited from other elements for the right and bottom, those can be combined into a single rule:</p>\n<pre><code>margin: -60px 0 0 -15px;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T05:17:13.123",
"Id": "515079",
"Score": "0",
"body": "Nitpick: wouldn't your `margin: -60px 0 0 -15px;` override some right/bottom margin defined earlier in the chain, while the two separate definition's don't?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T05:34:42.973",
"Id": "515081",
"Score": "0",
"body": "Good catch- I considered it and should have mentioned it. I have updated that section accordingly. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:39:37.697",
"Id": "261006",
"ParentId": "261004",
"Score": "4"
}
},
{
"body": "<p>Using <code>step</code> as a property inside each step is redundant and can lead to bugs if the value is incorrect. Consider what would happen if you had this:</p>\n<pre><code>data: {\n stepCounter: 1,\n steps: [{\n step: 5,\n completed: false,\n text: "Cart"\n },\n {\n step: 3,\n completed: false,\n text: "Shipping"\n },\n {\n step: 7,\n completed: false,\n text: "Payment"\n },\n {\n step: 1,\n completed: false,\n text: "Confirmation"\n }\n ]\n},\n</code></pre>\n<p>To solve this issue, remove the <code>step</code> from the data completely.</p>\n<pre><code>data: {\n stepCounter: 1,\n steps: [{\n completed: false,\n text: "Cart"\n },\n {\n completed: false,\n text: "Shipping"\n },\n {\n completed: false,\n text: "Payment"\n },\n {\n completed: false,\n text: "Confirmation"\n }\n ]\n},\n</code></pre>\n<p>A similar mistake can happen if the <code>completed</code> property is entered incorrectly. Instead, use the current <code>stepCounter</code> property to determine when to mark a step as completed.</p>\n<hr />\n<p>To make the component reusable, I would recommend using some <em>props</em> instead of only <em>data</em>. Suggested props would be the <code>stepCounter</code> and the text for each step.</p>\n<p>Preferably, I would like to see it possible to use your component like this:</p>\n<p><code><Stepper :steps="['step one', 'step two', 'step three']" currentStep="2" /></code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T21:39:46.783",
"Id": "261008",
"ParentId": "261004",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "261008",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:08:27.987",
"Id": "261004",
"Score": "4",
"Tags": [
"javascript",
"css",
"ecmascript-6",
"event-handling",
"vue.js"
],
"Title": "Vue.js checkout stepper"
}
|
261004
|
<p>I'm looking for any sort of optimization and/or conventional practice tips, such as using the appropriate data types and naming my variables appropriately.</p>
<pre><code>#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
constexpr short MIN_ELEMS = 3;
constexpr short MAX_ELEMS = 15;
constexpr short LARGEST_ELEM_INT = 99;
void fill_vector(std::vector<int> &v, short MAX_ELEMS, short LARGEST_ELEM_INT);
void print_vector(const std::vector<int>::iterator start, const std::vector<int>::iterator end);
void max_heap(const std::vector<int>::iterator elem, const std::vector<int>::iterator start, std::vector<int>::iterator end);
void heap_sort(const std::vector<int>::iterator start, const std::vector<int>::iterator end);
int main() {
srand(time(NULL));
short random_range = rand() % MAX_ELEMS + 1;
short num_of_elems = random_range < MIN_ELEMS ? MIN_ELEMS : random_range; // prevents num_of_elems from being less than MIN_ELEMS
std::vector<int> v;
fill_vector(v, num_of_elems, LARGEST_ELEM_INT);
print_vector(v.begin(), v.end());
heap_sort(v.begin(), v.end());
print_vector(v.begin(), v.end());
}
void fill_vector(std::vector<int> &v, short num_of_elems, short LARGEST_ELEM_INT) {
short i = 0;
while (++i, i <= num_of_elems) {
v.push_back(rand() % LARGEST_ELEM_INT);
}
}
void print_vector(const std::vector<int>::iterator start, const std::vector<int>::iterator end) {
for (auto elem = start; elem != end; ++elem) {
std::cout << *elem << ' ';
}
std::cout << '\n';
}
void max_heap(const std::vector<int>::iterator elem, const std::vector<int>::iterator start, const std::vector<int>::iterator end) {
auto biggest = elem;
auto left_child = start+((elem-start)*2+1);
auto right_child = start+((elem-start)*2+2);
if (left_child < end && *left_child > *biggest) {
biggest = left_child;
}
if (right_child < end && *right_child > *biggest) {
biggest = right_child;
}
if (elem != biggest) {
auto val = *biggest;
*biggest = *elem;
*elem = val;
max_heap(biggest, start, end);
}
}
void heap_sort(const std::vector<int>::iterator start, const std::vector<int>::iterator end) {
// sort vector to max heap
for (auto i = start+((end-start)/2)-1; i >= start; --i) {
max_heap(i, start, end);
}
// sort vector in ascending order
for (auto i = start; i != end-1; ++i) {
auto val = *start;
*start = *(start+(end-i-1));
*(start+(end-i-1)) = val;
max_heap(start, start, start+(end-i-1));
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Sort your includes. That way, you can keep track even if there are more of them.</p>\n</li>\n<li><p>Writing a test-program is a good idea. Though print the seed-value, and allow overriding from the command-line for reproducibility.</p>\n<p>In line with that, add a method to test whether a range is ordered, print that result and use it for the exit-code too.</p>\n</li>\n<li><p>I would expect a function named <code>print_vector()</code> to, you know, print a vector. Not an iterator-range from a vector. Also, encoding the type of an argument in the function-name hurts usability, especially in generic code.</p>\n</li>\n<li><p><code>fill_vector()</code> is a curious interface. I would expect <code>get_random_data()</code> which returns the vector.</p>\n</li>\n<li><p>Know your operators. <code>++i, i <= num_of_elems</code> is equivalent to <code>++i <= num_elements</code>.</p>\n<p>Anyway, that should be a for-loop, or you could omit <code>i</code> and just count the argument down to zero.</p>\n</li>\n<li><p>Kudos for using <code>constexpr</code> to avoid preprocessor-cnstants where not needed. Still, ALL_CAPS_AND_UNDERSCORES identifiers are generally reserved for preprocessor-macros. They warn/assure everyone that preprocessor-rules apply. Fix the naming too.</p>\n</li>\n<li><p>The C++ headers <code><cxxx></code> modelled on the C headers <code><xxx.h></code> only guarantee to put their symbols into <code>::std</code>. Don't assume they are also in the global namespace.</p>\n</li>\n<li><p><code>max_heap()</code> will often try to create pointers far beyond the passed range. Creating such a pointer invokes <em>undefined behavior</em>.<br />\nFor simple and correct code, better use indices.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T00:17:03.227",
"Id": "261012",
"ParentId": "261007",
"Score": "3"
}
},
{
"body": "<p>Unless you really need to save memory, don't use <code>short</code>. Your number-of-elements should be <code>size_t</code>. I've benchmarked x86-64 systems that 16-bit values are <em>much</em> slower than 8, 32, or 64.</p>\n<p>Don't use the C <code>NULL</code> macro. C++ has a keyword <code>nullptr</code>.</p>\n<p>It would be more readable if you made an alias for <code>std::vector<int>::iterator</code> that you use many times. Really, this ought to be a template, but I understand that writing fixed code is the first step to getting it to work and then you transform it into a template. But you should think about that later step when writing the code.</p>\n<p>It's good that you are using iterators. Most beginners seem to use arrays and index numbers instead.</p>\n<p>I think your implementation follows the algorithm's textbook description well and is easy enough to follow, but would benefit from some comments. For example, explain that <code>max_heap</code> expects a certain range of elements to already be in a heap structure and draws in a new element (assuming I got that right; I'm not following that in the code but from my memory of the algorithm).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:51:34.963",
"Id": "515128",
"Score": "0",
"body": "Most are good additional points, but at least inside `max_heap()`, indices have the advantage that even if they are grossly out-of-range, they don't cause UB."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:29:32.327",
"Id": "261043",
"ParentId": "261007",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261012",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T20:58:58.323",
"Id": "261007",
"Score": "2",
"Tags": [
"c++",
"sorting",
"heap"
],
"Title": "Trying for an efficient and readable heap-sort implementation"
}
|
261007
|
<p>I created a system that allows individuals to ask questions about code, and chat. I wanted to make this system smaller and better because this is easy to bypass for some reason.</p>
<p>The modules/packages I used for this chatroom project</p>
<pre class="lang-py prettyprint-override"><code>import os
import time
</code></pre>
<p>Now the actual script that contains about 56 lines of code!</p>
<pre class="lang-py prettyprint-override"><code>print("Codehelp || Question through a terminal.")
#### Codehelp Variables
chat = open('publiclogs.txt','r')
name = input("Enter Username: ")
crown = ""
owner = False
#### Codehelp Scripts
if name == "":
print("\nINVALID! Name must not be Empty..\n")
time.sleep(2)
exit()
while True:
with open('publiclogs.txt','a') as chat_txt:
chat_txt.close()
chat = open('chat.txt','r')
print(chat.read())
message = input("Enter Your message: ")
os.system("clear")
if message.lower() == "":
os.system("clear")
print("You must type something in order to send a message\n")
input("Press enter to continue ")
os.system("clear")
elif message.lower() == ".ask":
title = input("Enter title of Question. Also be specific: ")
description = input("Enter description: ")
tags = input("Enter TAGS. Seperate by ',': ")
os.system("clear")
with open('question.txt','a') as ask_txt:
ask_txt.write(f'TITLE: {title}\n')
ask_txt.write(f'DESCRIPTION: {description}\n')
ask_txt.write(f'TAGS: {tags}\n')
ask_txt.write(f'Written by {name}\n')
ask_txt.write(f'-------------------\n')
ask_txt.close()
with open('publiclogs.txt','a') as chat_txt:
chat_txt.write(f'New Question has been asked! View question.txt!\n')
chat_txt.close()
elif message.lower() == ".login":
print("Welcome to the Admin log-in!")
time.sleep(2)
password = input("What's the Password: ")
print("Removed from Codehelp Currently..")
else:
if owner == True:
with open('chat.txt','a') as chat_txt:
chat_txt.write(f'{crown} {name}:{message}\n')
chat_txt.close()
else:
with open('chat.txt','a') as chat_txt:
chat_txt.write(f'{name}: {message}\n')
chat_txt.close()
</code></pre>
<p>What could I do to improve this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T00:49:33.297",
"Id": "516034",
"Score": "0",
"body": "How is this a chat room? Is the file mapped to an NFS mount or something?"
}
] |
[
{
"body": "<p>I have carefully read all of your code and I would like to propose some changes, in line with the PEP8 good practice convention:</p>\n<ul>\n<li>ideally, the indentation is a multiple of 4;</li>\n<li>it is not necessary to use multiple '#' to comment a line;</li>\n<li>boolean expressions like <code>if owner == True</code> can be simplified to <code>if owner</code>;</li>\n<li>On line 27, I replaced <code>Seperate</code> with <code>Separate</code>;</li>\n<li>You can replace <code>-------------------</code> with <code>{"-" * 20}</code>;</li>\n<li>It is also possible to avoid over-repeating <code>ask_txt.write</code> by inserting newline after <code>\\n</code>;</li>\n<li>1 blank space after each comma;</li>\n<li>1 blank paragraph at the end of everything.</li>\n</ul>\n<p>Here is the entire code including the modifications I suggested:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print("Codehelp || Question through a terminal.")\n# Codehelp Variables\nchat = open('publiclogs.txt', 'r')\nname = input("Enter Username: ")\ncrown = ""\nowner = False\n# Codehelp Scripts\nif name == "":\n print("\\nINVALID! Name must not be Empty..\\n")\n time.sleep(2)\n exit()\nwhile True:\n with open('publiclogs.txt', 'a') as chat_txt:\n chat_txt.close()\n chat = open('chat.txt', 'r')\n print(chat.read())\n message = input("Enter Your message: ")\n os.system("clear")\n if message.lower() == "":\n os.system("clear")\n input("You must type something in order to send a message\\n"\n "Press enter to continue ")\n os.system("clear")\n elif message.lower() == ".ask":\n title = input("Enter title of Question. Also be specific: ")\n description = input("Enter description: ")\n tags = input("Enter TAGS. Separate by ',': ")\n os.system("clear")\n with open('question.txt', 'a') as ask_txt:\n ask_txt.write(f'TITLE: {title}\\n'\n f'DESCRIPTION: {description}\\n'\n f'TAGS: {tags}\\n'\n f'Written by {name}\\n'\n f'{"-" * 20}')\n ask_txt.close()\n with open('publiclogs.txt', 'a') as chat_txt:\n chat_txt.write(f'New Question has been asked! View question.txt!\\n')\n chat_txt.close()\n elif message.lower() == ".login":\n print("Welcome to the Admin log-in!")\n time.sleep(2)\n password = input("What's the Password: ")\n print("Removed from Codehelp Currently..")\n else:\n if owner:\n with open('chat.txt', 'a') as chat_txt:\n chat_txt.write(f'{crown} {name}:{message}\\n')\n chat_txt.close()\n else:\n with open('chat.txt', 'a') as chat_txt:\n chat_txt.write(f'{name}: {message}\\n')\n chat_txt.close()\n\n</code></pre>\n<p>Here is the complete documentation. <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T19:18:22.197",
"Id": "520140",
"Score": "0",
"body": "I have rejected two of your previously approved suggested edits. You are not allowed to edit code in questions - [1](//codereview.meta.stackexchange.com/a/6124) [2](//codereview.meta.stackexchange.com/a/6947). Additionally, please refrain from suggesting the same edit twice in the future. However, please feel free to suggest [the text changes in this edit](https://codereview.stackexchange.com/posts/253162/revisions) again if you don't edit the code. (so you get +2 rep) If you edit the code your suggestion will be rejected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T00:27:37.453",
"Id": "520156",
"Score": "0",
"body": "Thanks, I didn't know that and I really appreciate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T00:01:13.117",
"Id": "261491",
"ParentId": "261009",
"Score": "0"
}
},
{
"body": "<ul>\n<li>The original value of the <code>chat</code> variable appears to be unused - you just open the publiclogs.txt file but never use or close it</li>\n<li>Every pass through the loop you open and then immediately close the "publiclogs.txt" file again. That doesn't seem very useful</li>\n<li>Using <code>open</code> with <code>with</code> statements is good and is usually the way to go, but sometimes you use <code>open</code> on its own which just increases the risk of opening a file and forgetting to close it - you rarely want to do that</li>\n<li>On a related note, you don't need to manually close files if you opened them in the heading of a <code>with</code> statement. The <code>ask_txt.close()</code> and <code>chat_txt.close()</code> lines in the <code>.ask</code> part are unnecessary</li>\n<li>You keep re-opening "chat.txt" each pass through the loop. If you want to go back to the start of the file you usually want to use <code>chat.seek(0)</code> rather than re-opening the file. There <em>are</em> situations where closing and re-opening a file is warranted, but I'm not sure whether this is one of them</li>\n<li>A minor issue, but I find it annoying that both the variable <code>chat</code> and the variable <code>chat_txt</code> can sometimes refer to the file "chat.txt" and sometimes to the file "publiclogs.txt", with no obvious pattern as for which one is used when. It makes the logic harder to follow</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T01:30:53.600",
"Id": "516037",
"Score": "0",
"body": "_chat.seek(0), not re-open the file_ - usually I would agree, but in this specific case if the file is expected to be shared between multiple processes it's actually safer to close and re-open on each loop."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T01:15:16.120",
"Id": "261492",
"ParentId": "261009",
"Score": "0"
}
},
{
"body": "<ul>\n<li>Your initial <code>open()</code> is redundant and can be deleted</li>\n<li><code>crown</code> is unused because <code>owner</code> is hard-coded to <code>False</code></li>\n<li>Consider using <code>pathlib</code> which makes several things in your code more convenient</li>\n<li>Your <code>sleep</code> calls hinder rather than enhance usability and can be deleted</li>\n<li><code>os.system('clear')</code> is not cross-platform, and anyway it offers no usability benefit, so that can be deleted, too</li>\n<li>Your <code>with / close</code> pattern implies a double-close, which is incorrect. The point of <code>with</code> is that it already guarantees a <code>close</code>.</li>\n<li>Use <code>getpass</code> instead of <code>input</code> for the administrative password, to prevent over-the-shoulder</li>\n<li>Instead of killing the entire process on invalid username input, consider adding a validation loop</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from getpass import getpass\nfrom pathlib import Path\n\nCHAT_PATH = Path('chat.txt')\nQUESTION_PATH = Path('question.txt')\nLOG_PATH = Path('publiclogs.txt')\n\nprint("Codehelp || Question through a terminal.")\n\nwhile True:\n name = input("Username: ")\n if name != "":\n break\n print("Invalid: name must not be empty.")\n\n\nwhile True:\n if CHAT_PATH.exists():\n print(CHAT_PATH.read_text())\n\n message = input("Message: ")\n command = message.lower()\n\n if command == ".ask":\n title = input("Question title: ")\n description = input("Description: ")\n tags = input("Tags, separated by ',': ")\n\n with QUESTION_PATH.open('a') as ask_txt:\n ask_txt.write(\n f'TITLE: {title}\\n'\n f'DESCRIPTION: {description}\\n'\n f'TAGS: {tags}\\n'\n f'Written by {name}\\n'\n f'-------------------\\n'\n )\n\n with LOG_PATH.open('a') as log_txt:\n log_txt.write(f'New question has been asked! View {QUESTION_PATH}\\n')\n\n elif command == ".login":\n print("Welcome to the Admin log-in!")\n password = getpass()\n print("Removed from Codehelp currently..")\n\n else:\n with CHAT_PATH.open('a') as chat_txt:\n chat_txt.write(f'{name}: {message}\\n')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T01:41:40.500",
"Id": "261493",
"ParentId": "261009",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T21:49:52.670",
"Id": "261009",
"Score": "3",
"Tags": [
"python"
],
"Title": "python Chatroom/Codehelp through the terminal"
}
|
261009
|
<p>Recently wrote a brainfuck interpreter in Go.</p>
<p>Here's the Github Repo <a href="https://github.com/anthonygedeon/brainfuck" rel="nofollow noreferrer">Brainfuck</a></p>
<h3>Areas that need work</h3>
<p>The parsing for brackets <code>[]</code> is still buggy and is known to fail when dealing with nested loops i.e <code>[[]]</code> any hints on how to approach the problem would be greatly appreciated.</p>
<p>After looking at this <a href="https://github.com/kgabis/brainfuck-go/blob/master/bf.go" rel="nofollow noreferrer">repo</a>. He creates a compiler and then a parser to call the opcodes. Is this type of design common in writing interpreters? And should I use this design approach in my interpreter?</p>
<p>The test suite is very basic and needs more test cases, for instance, I'm using <code>scanner.Scan()</code> to get input from the user but how do I write a test case for that? Further, there is a <code>-file</code> that grabs the contents of a file when given a path to the file but I don't have a good idea of how to test it.</p>
<p>The overall structure of my code reeks of bad code smell, how can I improve it?</p>
<p>brainfuck.go</p>
<pre><code>package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
)
const memorySize = 30000
const cellLimit = 256
// incrementPointer
func incrementPointer(mem []int, ptr *int) error {
if *ptr >= len(mem)-1 {
return fmt.Errorf("memory error: %d", ptr)
}
*ptr++
return nil
}
// decrementPointer
func decrementPointer(mem []int, ptr *int) error {
if *ptr < 0 {
return fmt.Errorf("memory error: %d", ptr)
}
*ptr--
return nil
}
// incrementByte
func incrementByte(mem []int, ptr *int) {
if mem[*ptr] == cellLimit {
mem[*ptr] = 0
}
mem[*ptr]++
}
// decrementByte
func decrementByte(mem []int, ptr *int) {
if mem[*ptr] == 0 {
mem[*ptr] = cellLimit
}
mem[*ptr]--
}
// outputByte
func outputByte(mem []int, ptr *int) string {
return fmt.Sprintf("%c", mem[*ptr])
}
// storeByte
func storeByte(mem []int, ptr *int) {
var s string
fmt.Print("Waiting for input: ")
fmt.Scanln(&s)
mem[*ptr] = int([]byte(s)[0])
}
func main() {
var memory = [...]int{memorySize: 0}
var pointer int
var result string
var leftBracket int
var rightBracket int
filename := flag.String("file", "", "choose a brainfuck file.")
flag.Parse()
file, err := ioutil.ReadFile(*filename)
if err != nil && *filename != "" {
fmt.Print(err)
os.Exit(1)
}
tfile := strings.TrimSuffix(string(file), "\n")
scanner := bufio.NewScanner(os.Stdin)
if tfile == "" {
scanner.Scan()
}
text := scanner.Text()
var input string
if text != "" {
input = strings.TrimSuffix(text, "\n")
} else if tfile != "" {
input = tfile
} else {
fmt.Print("nothing to parse.")
os.Exit(1)
}
for i := 0; i < len(input); i++ {
switch input[i] {
case '>':
incrementPointer(memory[:], &pointer)
case '<':
decrementPointer(memory[:], &pointer)
case '+':
incrementByte(memory[:], &pointer)
case '-':
decrementByte(memory[:], &pointer)
case '.':
result += outputByte(memory[:], &pointer)
case ',':
storeByte(memory[:], &pointer)
case '[':
leftBracket = i
case ']':
rightBracket = i
i = leftBracket
if memory[pointer] == 0 {
i = rightBracket
}
default:
continue
}
}
fmt.Printf("%s\n", result)
}
</code></pre>
<p>brainfuck_test.go</p>
<pre><code>package main
import (
"testing"
// "fmt"
)
func TestIncrementPointer(t *testing.T) {
mem := make([]int, 4)
ptr := 0
incrementPointer(mem, &ptr)
if ptr != 1 {
t.Errorf("incrementPointer was incorrect, got %d instead", ptr)
}
}
func TestDecrementPointer(t *testing.T) {
mem := make([]int, 4)
ptr := 1
decrementPointer(mem, &ptr)
if ptr != 0 {
t.Errorf("decrementPointer was incorrect, got %d instead", ptr)
}
}
func TestIncrementByte(t *testing.T) {
mem := make([]int, 4)
ptr := 0
want := 1
incrementByte(mem, &ptr)
if mem[ptr] != want {
t.Errorf("incrementByte was incorrect, got %d instead", ptr)
}
}
func TestDecrementByte(t *testing.T) {
mem := make([]int, 4)
ptr := 0
want := 255
decrementByte(mem[:], &ptr)
if mem[ptr] != want {
t.Errorf("decrementByte was incorrect, got %d instead", ptr)
}
}
</code></pre>
<h3>Example</h3>
<pre><code>$./brainfuck *ENTER*
>++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<++.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>-]<+
$ Hello, World!
</code></pre>
|
[] |
[
{
"body": "<h1>Structure</h1>\n<p>I would expect to find something that just runs Brainfuck code, like a method or a function, not have this embedded into the main function. Similarly, retrieving the code from stdin or from a file could be moved to a separate function. It would make these things easier to understand in separation. Also, concerning this separation, get rid of the habit of declaring variables (<code>memory</code>, <code>pointer</code> etc) far away from where they are actually used.</p>\n<p>I'd expect these functions to also return an <code>error</code>, to comply with Go conventions. That would also imply that you abort execution when you get an overflow/underflow for the pointer or other fatal mistakes. If you decide to put this into a class, its state would be the memory, the pointer and the stack (I guess you'll need one) with brackets.</p>\n<p>I'm not sure how far you want to go, but maybe you want to extend tests to the functions with side effects, i.e. input and output. In that case, it would help if you defined an IO interface which can be plugged into the interpreter. It would allow creating a mock for tests.</p>\n<h1>Notes and Bugs</h1>\n<ul>\n<li>Increment and decrement byte operations are broken, they still increment the byte on overflow, after zeroing it. Consider using an explicit <code>int8</code> or <code>uint8</code> (not sure about Brainfuck's spec there). Also, Go should have a modulo function which you could use to avoid these issues.</li>\n<li>There's some "dead" code:\n<ul>\n<li><code>result</code> is used, but not really useful. Separating things probably would have shown that.</li>\n<li>Commented out <code>import fmt</code> in testfile.</li>\n<li>Trailing empty line in functions.</li>\n<li>Comments for functions that only repeat the name of the function.</li>\n</ul>\n</li>\n<li>An isolated right bracket is currently ignored. I'm not sure if that is intended.</li>\n<li>Invalid characters in the input are ignored. I'm not sure if that is intended either.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T09:31:06.913",
"Id": "261026",
"ParentId": "261011",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T23:48:16.313",
"Id": "261011",
"Score": "1",
"Tags": [
"go",
"interpreter",
"brainfuck"
],
"Title": "Go Brainf*ck Interpreter"
}
|
261011
|
<p>I have a fundamental but interesting question.</p>
<p>I have written this python code which checks the payload sent from a specific IoT topic.</p>
<p>First, I would love to get honest feedback and learn how to improve my code to be most efficient, readable, and straightforward.</p>
<p>Second I would like to know when you are using classes in python and when just functions and methods.
Before You jump, let me clarify. I know when to use classes which is obvious, and you are using many "users" who share common attributes, But !!!!!! As it seems, and maybe I am wrong here, the best practice (in most of the production code I am familiar with). It is always to force the code for use in classes, even in cases where you can easily write the code without classes.</p>
<pre><code># Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
import glob
import logging
import platform
import sys
import time
import requests
from awscrt import io, mqtt
from awsiot import mqtt_connection_builder
# This module purpose is to test valid publish to AWS IoT topics.
# It uses the Message Broker for AWS IoT to send and receive messages
# through an MQTT connection. On Run, the device connects to the server,
# subscribes to a topic.
# The device should receive messages from the message broker, since it is subscribed to a specific topic.
# Define constants
PAYLOAD_ACCEPTANCE_PERCENTAGE_TOLERANCE = 0.8
TRANSMISSION_RATE_PER_SEC = 10
NO_OF_SECONDS_TO_TEST_SUB_ON_TOPIC = 3
THINGS_URL_PROD = 'https://some_production_url'
THINGS_URL_TEST = 'https://some_production_url'
# main function
def main():
# Instantiate an object of type SubscribeOnTopics
device_1 = SubscribeOnTopics()
# Fetching the device host name.
host_name = device_1.get_hostname_from_device()
# Fetching the device drone id from dronethings table.
drone_id = str(device_1.get_drone_id(host_name))
# Subscribing to a specific topic.
device_services_topic = f'device/services/{drone_id}'
device_1.call_iot(device_services_topic)
# Defining logger
def make_logger():
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s - %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
log.addHandler(handler)
return log
class SubscribeOnTopics:
def __init__(self):
self.endpoint = "some.eu-central-1.amazonaws.com"
self.cert_filepath = r'/home/pi/drone/aws_cert/' \
+ glob.glob1("/home/pi/drone/aws_cert/", "*.crt")[0],
self.pri_key_filepath = r'/home/pi/drone/aws_cert/' \
+ glob.glob1("/home/pi/drone/aws_cert/", "*.key")[0],
self.ca_filepath = r'/home/pi/drone/aws_cert/rootCA.pem'
self.count = 0
self.count_payload = 1
def get_hostname_from_device(self):
return platform.node()
# .env file contain 2 lines:
# env=test/prod
# API_KEY=some_api_key
def convert_env_file_to_dict(self):
with open('/home/pi/Desktop/device/.env') as env_file:
env_to_dict = {}
lines = env_file.readlines()
for line in lines:
strip_line = line.replace('\n', '')
splitted_line = strip_line.split('=')
env_to_dict.update({splitted_line[0]: splitted_line[1]})
return env_to_dict
def get_device_env_value(self):
return self.convert_env_file_to_dict()['env']
def get_dronething_compatiable_url(self):
if 'test' == self.get_device_env_value():
return THINGS_URL_TEST
elif 'prod' == self.get_device_env_value():
return THINGS_URL_PROD
else:
raise Exception('The device env key did not found. Please check .env file and make sure he is valid')
def get_drone_id(self, hostname):
"""
This method extracts the desired device drone id from dronethings table.
@param hostname: str - the desired device hostname.
@return: int - device drone id.
"""
dronethings_table_response = requests.get(url=self.get_dronething_compatiable_url(),
headers={'x-api-key': self.convert_env_file_to_dict()['API_KEY']},
params={'thingName': hostname})
if dronethings_table_response.status_code != 200:
logger.error(f'\n status code : {dronethings_table_response.status_code}\n'
f'API call failed, JSON response:\n {dronethings_table_response.text} \n')
return
device_drone_id = dronethings_table_response.json().get('droneId')
if not dronethings_table_response.json():
logger.error(f'\n{hostname} does not exists in dronethings table !!!!\n'
f'verify that you specified a valid device number\n'
f' if so check dronethings table and check if it is listed there')
return
elif not device_drone_id:
logger.error(f'\n{hostname} droneId field in dronethings table is NULL ......\n'
f'make sure to fill droneId id field, for the desired device, in dronethings table ')
return
return device_drone_id
# Callback when the subscribed topic receives a message
def on_message_received(self, topic, payload):
logger.info(
"Received message from topic '{}': {}\n COUNT PAYLOADS {}".format(topic, payload, self.count_payload))
self.count_payload += 1
def call_iot(self, topic):
"""
This method connects to AWS IoT core and subscribes to a given topic. Then validates the transmission quality
according to the number of received data payloads.
@param topic: str - AWS IoT topic the method subscribe.
@return: bool - True if the received payloads are in the tolerance range, else exit with code 1..
"""
try:
# Spin up resources
event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)
mqtt_connection = mqtt_connection_builder.mtls_from_path(
endpoint=self.endpoint,
cert_filepath=self.cert_filepath[0],
pri_key_filepath=self.pri_key_filepath[0],
client_bootstrap=client_bootstrap,
ca_filepath=self.ca_filepath,
client_id='client_id',
clean_session=False,
keep_alive_secs=6)
logger.info("Connecting to {}".format(
self.endpoint))
connect_future = mqtt_connection.connect()
# Future.result() waits until a result is available
connect_future.result()
logger.info("Connected!")
except:
raise Exception('Failed to connect')
# Setting timer for subscribe duration.
try:
start_time = time.time()
seconds = NO_OF_SECONDS_TO_TEST_SUB_ON_TOPIC
while True:
current_time = time.time()
elapsed_time = current_time - start_time
if elapsed_time > seconds:
logger.info("Finished iterating in: " + str(int(elapsed_time)) + " seconds")
break
# Subscribe to topic.
logger.info(f"Subscribing to topic {topic}...")
subscribe_future, packet_id = mqtt_connection.subscribe(
topic=topic,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=self.on_message_received)
subscribe_result = subscribe_future.result()
logger.info(f"Subscribed with {str(subscribe_result['qos'])} packet no: {packet_id}")
if self.count_payload >= (seconds * TRANSMISSION_RATE_PER_SEC) * PAYLOAD_ACCEPTANCE_PERCENTAGE_TOLERANCE:
logger.info('transmission is valid')
return True
else:
logger.info('transmission rate is NOT valid')
exit(1)
except:
raise Exception('failed to Subscribe')
finally:
# Disconnect
logger.info("Disconnecting...")
disconnect_future = mqtt_connection.disconnect()
disconnect_future.result()
logger.info("Disconnected!")
if __name__ == '__main__':
logger = make_logger()
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T03:51:53.633",
"Id": "515076",
"Score": "4",
"body": "_Copyright Amazon.com, Inc._ - uh, what? Did you write this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:02:33.543",
"Id": "515085",
"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-05-25T07:23:44.123",
"Id": "515382",
"Score": "1",
"body": "Since you've lied about the version of Python in the tags; \"`f\"Subscribing to topic {topic}...\"`\" is invalid syntax in Python 2.x. And you've refused to answer if the code is yours. I'm closing your question for our AoC reason."
}
] |
[
{
"body": "<blockquote>\n<pre><code>THINGS_URL_TEST = 'https://some_production_url'\n</code></pre>\n</blockquote>\n<p>The testing URL should not be same as production URL</p>\n<hr />\n<blockquote>\n<pre><code>NO_OF_SECONDS_TO_TEST_SUB_ON_TOPIC = 3\n</code></pre>\n</blockquote>\n<p>Prefer using prefix <code>NUM</code> or <code>NUMBER</code> as <code>NO_OF</code> may not be understood by some</p>\n<hr />\n<blockquote>\n<pre><code># Define constants\n</code></pre>\n</blockquote>\n<p><a href=\"https://softwareengineering.stackexchange.com/a/173120\">Comments should say</a> "why" (when appropriate), and not "what"</p>\n<hr />\n<blockquote>\n<pre><code>device_1 = SubscribeOnTopics()\nhost_name = device_1.get_hostname_from_device()\n</code></pre>\n</blockquote>\n<p>Since you name it <code>device_1</code>, I'd assume there would be <code>device_2</code> and so on. If this is the case, it should be <code>device_1_hostname</code></p>\n<hr />\n<blockquote>\n<pre><code>def make_logger():\n log = logging.getLogger(__name__)\n ...\n return log\n</code></pre>\n</blockquote>\n<p>If it is <code>make_logger</code>, why return <code>log</code>? Variable should be named <code>logger</code> for clarity</p>\n<hr />\n<blockquote>\n<pre><code>self.cert_filepath = r'/home/pi/drone/aws_cert/'\n</code></pre>\n</blockquote>\n<p>The string constant <code>/home/pi/drone/aws_cert/</code> is used multiple times. Refactor it out into a constant variable. Join this with path components using <code>os.path.join</code></p>\n<hr />\n<blockquote>\n<pre><code>self.count = 0\n</code></pre>\n</blockquote>\n<p>What is <code>count</code>? Is it <code>subscriber_count</code>?</p>\n<hr />\n<blockquote>\n<pre><code>def get_hostname_from_device(self):\n return platform.node()\n</code></pre>\n</blockquote>\n<p><code>self</code> is unused and it does not need to be inside <code>class</code></p>\n<hr />\n<blockquote>\n<pre><code>if 'test' == self.get_device_env_value():\n</code></pre>\n</blockquote>\n<p><a href=\"https://softwareengineering.stackexchange.com/questions/16908/doesnt-if-0-value-do-more-harm-than-good\">Consensus is "Yoda conditions" should not be used</a>. It'd probably even be easier to just store the URL (production or testing) in the configuration file instead of <code>test</code> or <code>prod</code></p>\n<hr />\n<blockquote>\n<p>"The device env key did not found...and make sure he is valid..."</p>\n</blockquote>\n<p>The env key/value might have been found but may not be <code>test</code> or <code>prod</code>. Reword the error as specific as possible</p>\n<hr />\n<blockquote>\n<pre><code>self.convert_env_file_to_dict()\n</code></pre>\n</blockquote>\n<p>This is called many times and the result can probably be stored as instance variable</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T03:50:26.497",
"Id": "261014",
"ParentId": "261013",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T00:38:45.127",
"Id": "261013",
"Score": "4",
"Tags": [
"python"
],
"Title": "What's the best practices I ain't using in this code?"
}
|
261013
|
<p>I have made a simple contact management in C++.</p>
<p>It's my second project; I'm pretty sure it can be done more better and I could decrease its runtime, but I just joined the C++ community this year. So can you review my code?</p>
<p>It's a CUI-based contact management system through which you can add, delete, edit or search contacts.</p>
<pre><code>#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <conio.h>
//Used For Replacing The Line
void ReplaceLine(const std::string& ToReplace,const std::string&& Main){
std::vector<std::string>Content;
std::string s;
std::ifstream File("contacts.txt");
while(getline(File,s)){
if(s==ToReplace){
s=Main;
}
Content.push_back(s);
}
std::ofstream writer("contacts.txt",std::ostream::trunc);
for(std::string& s:Content){
writer<<s<<std::endl;
}
}
//Editing The Contact
void EditContact(const std::string& ID){
std::string NewName,NewNumber;
std::cout<<"Enter A New Name : ";
std::cin>>NewName;
std::cout<<"Enter A New Number : ";
std::cin>>NewNumber;
NewName+=" ";
ReplaceLine(ID,NewName+NewNumber);
}
//Adding New Contact
void AddContact(const std::string&& ID){
std::ofstream File("contacts.txt",std::ios_base::app);
std::string s;
std::ifstream reader("contacts.txt");
char Confirmation;
while(getline(reader,s)){
if(ID==s){
std::cout<<"Contact Already Exist!\n"<<"Do You Want To OverWrite?[Y/N]"<<std::endl<<">>";
std::cin>>Confirmation;
if(Confirmation=='Y'){
system("clear");
EditContact(ID);
std::cout<<"Contacts Overriden"<<std::endl;
system("pause");
File.close();
return;
}
else{
std::cout<<"Contacts Aren't Touched"<<std::endl;
system("pause");
File.close();
return;
}
}
}
File<<ID<<std::endl;
std::cout<<"New Contact Has Been Added"<<std::endl;
system("pause");
File.close();
}
//Deleting A Contact
void DeleteContact(const std::string&& ToDlt){
std::vector<std::string>Contact;
std::string s;
bool Deleted=false;
std::ifstream Reader("contacts.txt");
while(getline(Reader,s)){
if(s==ToDlt){
Deleted=true;
continue;
}
Contact.push_back(s);
}
std::ofstream Writer("contacts.txt",std::ios_base::trunc);
for(std::string&k : Contact){
Writer<<k<<std::endl;
}
if(!Deleted){
std::cout<<"Contact Didn't Existed!"<<std::endl;
}
else{
std::cout<<"Contact Has Been Deleted"<<std::endl;
}
}
//Searching A Contact This Wont Be Called Directly
int Search(const std::string& Query){
int Count=0;
bool IsNum=false;
if(isdigit(Query[0])){
IsNum=true;
}
std::ifstream reader("contacts.txt");
std::string Name,Number;
std::string s;
while(getline(reader,s)){
std::stringstream Extractor(s);
Extractor>>Name>>Number;
if(IsNum==true){
if(Number.find(Query)!=std::string::npos){
Count++;
std::cout<<"NAME : "<<Name<<" "<<"NUMBER : "<<Number<<std::endl;
}
}
else{
if(Name.find(Query)!=std::string::npos){
Count++;
std::cout<<"NAME : "<<Name<<" "<<"NUMBER : "<<Number<<std::endl;
}
}
}
return Count;
}
//This Is Used To Take Inputs For Searching
void Query(){
std::string Query="";
std::cout<<"Contact Search"<<std::endl;
std::cout<<">>";
while(true){
char s=getche();
//If User Presses Enter Case It Worked Atleast for mine
if(int(s)==10){
return;
}
//Handling BackSpace Case Worked In Mine :)
if(int(s)==127){
if(Query.length()==0){
Query=" ";
std::cout<<"\b"<<"\b";
}
Query.erase(Query.end()-1);
}
//Else Adding Character To Query
else{
Query.push_back(s);
}
system("clear");
//The Contacts Get Printed In Search Itself
int Searched=0;
Searched=Search(Query);
if(Searched==0){
std::cout<<"No Results Found!!"<<std::endl;
}
std::cout<<">>"<<Query;
}
system("pause");
system("clear");
}
void EditContact(const std::string&& ID){
system("clear");
std::ifstream Reader("contacts.txt");
std::string S;
bool Exist=false;
std::vector<std::string>NewBlocks;
while(getline(Reader,S)){
if(S==ID){
std::string Name,Num;
std::cout<<"Enter The New Name : ";
std::cin>>Name;
std::cin.ignore();
std::cout<<"Enter The New Number : ";
std::cin>>Num;
Name+=" ";
NewBlocks.push_back(Name+Num);
Exist=true;
continue;
}
NewBlocks.push_back(S);
}
if(!Exist){
std::cout<<"The Contact You Want To Edit Didn't Exist!!"<<std::endl;
system("pause");
return;
}
std::ofstream Writer("contacts.txt",std::ios_base::trunc);
for(std::string& Val:NewBlocks){
Writer<<Val<<std::endl;
}
std::cout<<"Contacts Has Been Edited!!"<<std::endl;
system("pause");
}
int main()
{
char Cmnd;
while(true){
std::cout<<"~Add A Conatct [1]\n~Delete A Contact [2]\n~Edit A Contact [3]\n~Search A Contact [4]\n>>";
std::cin>>Cmnd;
std::cin.ignore();
if(Cmnd=='1'){
system("clear");
std::string Name,Number;
std::cout<<"Enter Name : ";
std::cin>>Name;
std::cin.ignore();
std::cout<<"Enter Number : ";
std::cin>>Number;
Name+=" ";
AddContact(Name+Number);
system("clear");
}
else if(Cmnd=='2'){
system("clear");
std::string Name,Num;
std::cout<<"Enter The Number : ";
std::cin>>Num;
std::cin.ignore();
std::cout<<"Enter Users Name : ";
std::cin>>Name;
Name+=" ";
DeleteContact(Name+Num);
system("clear");
}
else if(Cmnd=='3'){
system("clear");
std::string Name,Num;
std::cout<<"Enter The Name : ";
std::cin>>Name;
std::cin.ignore();
std::cout<<"Enter The Number : ";
std::cin>>Num;
Name+=" ";
EditContact(Name+Num);
system("clear");
}
else if(Cmnd=='4'){
system("clear");
Query();
system("clear");
}
else{
std::cout<<"Invalid Option!!";
system("pause");
system("clear");
}
}
}
</code></pre>
<p>Please let me know anything I can improve.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T06:02:18.527",
"Id": "515084",
"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-05-21T08:18:12.267",
"Id": "515098",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T08:29:09.253",
"Id": "515099",
"Score": "0",
"body": "Thanks @TobySpeight ill keep em all in mind before posting next time"
}
] |
[
{
"body": "<p>Your C++ code is very C-like. This is one of the cases where a class would be an obvious choice to structure your code. However, before that, I would like to point out a few things in your current code.</p>\n<hr />\n<ol>\n<li>The <code>const std::string&& Main</code> should be <code>const std::string& Main</code>. A const rvalue reference is almost always semantically useless. Better yet, if you're using C++17 or newer, you can in most cases pass a <code>std::string_view</code> instead of <code>const std::string&</code>.</li>\n</ol>\n<hr />\n<ol start=\"2\">\n<li>Use <code>'\\n'</code> over <code>std::endl</code>. It can potentially impact performance (especially when performing file I/O). <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">Here's a SO thread on that</a></li>\n</ol>\n<hr />\n<ol start=\"3\">\n<li>Check whether a file stream is valid before writing or reading to it.</li>\n</ol>\n<pre><code>std::ifstream file("contacts.txt");\nif(!file)\n{\n // something went wrong, handle the error!\n}\n</code></pre>\n<hr />\n<ol start=\"4\">\n<li>As a general rule, avoid <code>system</code>. It's can be inefficient, but more notably, is not portable. Your code will not work on Linux, for example, since <code>pause</code> is not a valid shell command in Linux.</li>\n</ol>\n<hr />\n<ol start=\"5\">\n<li>You don't need to manually call <code>File.close()</code>. The file will be closed when the object <code>fstream</code> object is destroyed.</li>\n</ol>\n<hr />\n<ol start=\"6\">\n<li>Follow the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a>. In simple terms, it means a function should only do one thing. For example, your <code>EditContact()</code> function is responsible for <strong>a)</strong> opening the file, <strong>b)</strong> parsing the data, <strong>c)</strong> asking the user input and <strong>d)</strong> writing the data to the file. Break your functions into logical chunks.</li>\n</ol>\n<hr />\n<ol start=\"7\">\n<li>You can use a <code>switch</code> statement, instead of <code>if</code> inside your <code>main</code> function. Also, as mentioned above, your <code>main</code> function is doing too much. You can easily move a lot of the statements inside their own functions.</li>\n</ol>\n<hr />\n<ol start=\"8\">\n<li>As mentioned above, your code is pretty inefficient, since it's opening, parsing and writing a file almost every operation. File I/O is not cheap, and since you're using C++, you obviously care about performance.</li>\n</ol>\n<p>So what options do you have?</p>\n<p>a) Open, parse, update and close the file every time you want to do an operation on the file (this is what you're doing now). As mentioned above, this is not a very performant solution.</p>\n<p>b) Open at the start, update the file every operation, and finally close the file at the end of the program. Slightly better, but writing to the file every time is still not very good.</p>\n<p>c) Open at the start, store the data in memory, update the data that is in memory every time, and write to the file and close it at the very end. This is seemingly the best solution because memory access is orders of magnitude faster that file I/O.</p>\n<p>Okay, so we go with option (c). How do we store the data in memory? You already did in one of your functions. Store it inside a <code>std::vector</code>. Now any operation you want to do is done on the strings in the vector.</p>\n<p>We can create a class called CustomerManagementSystem.</p>\n<p>(in pseudocode)</p>\n<pre><code>class CustomerManagementSystem\n{\n CustomerManagementSystem(const std::string& str)\n {\n std::ifstream file(str)\n if(file is invalid)\n {\n // handle error\n }\n parseFile(file);\n }\n}\n</code></pre>\n<p>We can provide a constructor that takes in file name, opens it and parses the file and store the data into a <code>std::vector<std::string></code>. In fact, a better approach would be define a struct such as</p>\n<pre><code>struct CustomerInfo\n{\n std::string name;\n int number;\n};\n</code></pre>\n<p>and create a <code>std::vector<CustomerInfo></code> to store the data.</p>\n<p>When the constructor ends, the <code>file</code> is destroyed and the file is automatically closed.</p>\n<p>Now every operation you want to do can be a member function of the class.</p>\n<pre><code>void AddContact(const std::string& ID)\n{\n auto id = FindIdInVector(ID);\n if(id already exists)\n {\n UpdateID();\n }\n else\n {\n data.push_back(ID);\n }\n}\n\n\n</code></pre>\n<p>So, how do we update the file in the end? We use a powerful C++ feature called <a href=\"https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii\">Resource Acquisition Is Initialization</a>. It's a scary name, but in very simple terms: your resource (for e.g. file handles, memory, sockets, et cetera) must be created (or "acquired") in the constructor and the resource is deleted (or "freed") (for e.g. calling <code>delete</code> on some memory allocated by using <code>new</code>, or closing a file object) inside the destructor.</p>\n<p>This ensures that the resource is 'acquired' when the object is created, and 'freed' when the object goes out of scope. Not only that, but it also ensures clean up of all your resource if ever your program throws an exception.</p>\n<p>So, how do we utilize RAII inside our class?</p>\n<p>We already fulfilled the first half of the contract; in our constructor, we opened the file, and stored the data in memory.</p>\n<p>So the second half of the contract is: in the destructor, we open the file and write the stored data back into it.</p>\n<p>So, destructor will look like this:</p>\n<pre><code>~CustomerManagementSystem()\n{\n std::ofstream file(filename);\n if(!file)\n {\n // file wasn't opened! handle error here\n } \n writeToFile(file, data);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T05:24:40.517",
"Id": "261017",
"ParentId": "261015",
"Score": "6"
}
},
{
"body": "<p>I would at least consider re-structuring the program a little, to read the data from a file into memory when it starts up, then manipulating the data in memory, without reading the file again (until the next time the user starts the program).</p>\n<p>If you were going to do that, when you read it into memory, you could store the data into a <code>std::map<std::string, std::string></code>. This would make it really quick and easy to look up a contact by name (probably the most common case).</p>\n<p><code>std::map</code> also sorts all the contents, so it would be trivial to add a few things like "list all my contacts in alphabetical order".</p>\n<p>The other thing that seems like kind of a problem to me is that virtually <em>all</em> your code knows all about everything. Even the code in main knows all the details of things like exactly how the data is formatted in the file.</p>\n<p>I'd rather define something like a structure that knows how to read and write the data in the file, and that's the only part that knows or cares about the file format.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T05:29:30.413",
"Id": "261018",
"ParentId": "261015",
"Score": "5"
}
},
{
"body": "<p>This looks like it could be a great program, but it's needlessly platform-specific:</p>\n<blockquote>\n<pre><code>#include <conio.h>\n</code></pre>\n</blockquote>\n<p>If you could replace this with something more portable, then it would be much better. I recommend learning how to use the Curses library if you want to make CUI programs; see <a href=\"//stackoverflow.com/q/7469139/4850040\">What is the equivalent to <code>getch()</code> & <code>getche()</code> in Linux?</a>. That would also allow you to replace the (also non-portable) <code>system()</code> calls with more reliable functions.</p>\n<p>I note that <code>system</code> hasn't even been declared - in C++ programs, you should include <code><cstdlib></code> and call it as <code>std::system</code>.</p>\n<hr />\n<blockquote>\n<pre><code> if(Cmnd=='1'){\n ⋮\n }\n else if(Cmnd=='2'){\n ⋮\n }\n else if(Cmnd=='3'){\n ⋮\n }\n else if(Cmnd=='4'){\n ⋮\n }\n else{\n ⋮\n }\n</code></pre>\n</blockquote>\n<p>It's clearer to write this using a <code>switch</code> statement:</p>\n<blockquote>\n<pre><code> switch (command) {\n case '1':\n ⋮\n break;\n case '2':\n ⋮\n break;\n case '3':\n ⋮\n break;\n case '4':\n ⋮\n break;\n default:\n ⋮\n break;\n }\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T08:28:13.490",
"Id": "261023",
"ParentId": "261015",
"Score": "2"
}
},
{
"body": "<p>You have a lot of duplicated code to open, read, and (for modifying operations) re-write your file. What happens if you update your file format? You'll have to change just about everything!</p>\n<p>Others have said that you should suck in the entire file, and operate in memory. That would indeed give you a single place to Load and Save. On a modern machine, with the expected size of a contact file, that makes sense. Historically, reading one record at a time made sense, and might still be true if this were the contact list for a large company or something like that. But then again, they would be using a database system today.</p>\n<p>If you want to keep the unit-record batch processing flow, you should at least isolate the record reading and writing functions for reuse.</p>\n<p>It looks like you're reading in the whole file anyway, to rewrite it after a change. But I shouldn't have to read through the <code>Delete</code> function to figure that out!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:14:39.627",
"Id": "261041",
"ParentId": "261015",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T03:54:39.917",
"Id": "261015",
"Score": "2",
"Tags": [
"c++",
"beginner"
],
"Title": "Contact management program"
}
|
261015
|
<p>As far as I test, there is no any bug point tested. However, I wonder that if there is a problem with the usage of <code>arr.Length</code> or <code>arr.Length - 1</code>.
Further, as to the boundaries like begin <= end with end = mid - 1 or begin < end with end = mid as in the codes.</p>
<p>// size is array length</p>
<pre><code>private static int BinarySearch(int[] arr, int element)
{
int begin = 0;
int end = arr.Length;
for (; begin < end ;)
{
int mid = begin + (( - begin + end) / 2);
if (arr[mid] == element) return mid;
if (arr[mid] > element)
{
// in left
end = mid;
}
else
{
begin = mid + 1;
}
}
return -1;
}
</code></pre>
<p>// size is array length - 1</p>
<pre><code>private static int BinarySearch(int[] arr, int element)
{
int begin = 0;
int end = arr.Length - 1;
for (; begin < end ;)
{
int mid = begin + (( - begin + end) / 2);
if (arr[mid] == element) return mid;
if (arr[mid] > element)
{
// in left
end = mid;
}
else
{
begin = mid + 1;
}
}
return -1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T09:04:12.053",
"Id": "515103",
"Score": "0",
"body": "@BCdotWEB is it matter? It is just an algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T09:31:21.760",
"Id": "515104",
"Score": "0",
"body": "@BCdotWEB I changed the tag from java to C# based on the `Length` property. In java it would be `length`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T09:32:28.367",
"Id": "515105",
"Score": "2",
"body": "@snr it matters because we review the code. We maybe comment on namings which are part of a naming-guideline which are different for different languages."
}
] |
[
{
"body": "<blockquote>\n<p>As far as I test, there is no any bug point tested.</p>\n</blockquote>\n<p>Well, then you didn't test all of the edge cases, did you?</p>\n<p>Given the array <code>int[] arr = new[] { 1, 2, 3, 4, 5 };</code> I would at least test for the following edge-cases:</p>\n<ul>\n<li>first item -> <code>0 == BinarySearch(arr, 1);</code></li>\n<li>middle item -> <code>2 == BinarySearch(arr, 3);</code></li>\n<li>last item -> <code>4 == BinarySearch(arr, 5);</code></li>\n<li>non existing positive-item -> <code>-1 == BinarySearch(arr, 6);</code></li>\n<li>always check for zero -> <code>-1 == BinarySearch(arr, 0);</code></li>\n<li>non existing negativ-item -> <code>-1 == BinarySearch(arr, -1);</code></li>\n</ul>\n<p>That beeing said, the second version fails on the last-item-check.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T11:43:41.540",
"Id": "515115",
"Score": "0",
"body": "Thank you sir. Any idea as to the boundaries like begin <= end with end = mid - 1 or begin < end with end = mid as in the codes?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T10:01:30.120",
"Id": "261030",
"ParentId": "261024",
"Score": "2"
}
},
{
"body": "<p>I would like to elaborate on some of the comments regarding tagging with post with the correct language. As @Heslacher states, each language has its own standards and conventions.</p>\n<p>In C#, method naming suggests that <code>BinarySearch</code> is a poor name for your method. A more suitable name would be <code>FindIndex</code> or <code>FindIndexUsingBinarySearch</code>. The latter is definitely wordier but leaves little doubt as to what the method does.</p>\n<p>The comment <code>// in left</code> is not needed as it tells a developer nothing that he or she doesn't already know.</p>\n<p>A binary search requires a sorted array, or more precisely to your method, an array sorted in ascending order. With C#, the abbreviated parameter name of <code>arr</code> is frowned upon. Instead, it should be <code>array</code> or perhaps even <code>sortedArray</code>.</p>\n<p>Turning to your 2 methods and the use of <code>begin</code>, <code>end</code>, and <code>mid</code>. In both methods, <code>begin</code> and <code>mid</code> are inclusive indices to the sorted array, <strong>but <code>end</code> is an exclusive index in the first version but an inclusive index in the second</strong>. Understanding this provides insights on how to correct the second version.</p>\n<p>This original line:</p>\n<pre><code>int mid = begin + (( - begin + end) / 2);\n</code></pre>\n<p>For the first method should be:</p>\n<pre><code>int mid = begin + ((end - begin) / 2);\n</code></pre>\n<p>And for the second method, where <code>end</code> is inclusive, should be:</p>\n<pre><code>int mid = begin + ((end - begin + 1) / 2);\n</code></pre>\n<p>In the second method, you would also need to adjust:</p>\n<pre><code>end = mid;\n</code></pre>\n<p>with</p>\n<pre><code>end = mid - 1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T12:09:48.593",
"Id": "261036",
"ParentId": "261024",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T08:29:18.860",
"Id": "261024",
"Score": "-2",
"Tags": [
"c#",
"algorithm",
"binary-search"
],
"Title": "Binary Search Algorithm Difference"
}
|
261024
|
<p>I'm programming Tic-Tac-Toe using minimax algorithm with alpha-beta pruning after taking Harvard's CS-50. My logic is working perfectly, except for the return time of minimax (especially on the first call, when only one player played). I was thinking of replacing the extra recursive call of minimax to max/min value. I want to emphasize that minimax is taking relatively slow for my purposes (around 0.5 seconds) and that I can't use pre-computed data.</p>
<pre><code>import math
import copy
import time
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
if board == initial_state():
return X
X_counter = 0
O_counter = 0
for row in board:
for cell in row:
if cell == X:
X_counter += 1
elif cell == O:
O_counter += 1
return O if X_counter > O_counter else X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
possible_moves = set()
for i in range(3):
for j in range(3):
if board[i][j] is None:
possible_moves.add((i, j))
return possible_moves
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
newboard = copy.deepcopy(board)
newboard[action[0]][action[1]] = player(board)
return newboard
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
if board[0][0] == board[0][1] == board[0][2] != None: # 1, 2, 3
return board[0][0]
if board[1][0] == board[1][1] == board[1][2] != None: # 4, 5, 6
return board[1][0]
if board[2][0] == board[2][1] == board[2][2] != None: # 7, 8, 9
return board[2][0]
if board[0][0] == board[1][0] == board[2][0] != None: # 1, 4, 7
return board[0][0]
if board[0][1] == board[1][1] == board[2][1] != None: # 2, 5, 8
return board[0][1]
if board[0][2] == board[1][2] == board[2][2] != None: # 3, 6, 9
return board[0][2]
if board[0][0] == board[1][1] == board[2][2] != None: # 1, 4, 7
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != None: # 3, 5, 7
return board[0][2]
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
def check_draw(board):
for row in board:
for cell in row:
if cell is None:
return False
return True
if winner(board) is not None or check_draw(board): # or someone won , or there is a draw
return True
return False
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
temp = winner(board)
if temp == X:
return 1
elif temp == O:
return -1
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
options = actions(board)
if player(board) == X:
vT = -math.inf
move = set()
for action in options:
v, count = minvalue(result(board,action), -math.inf, math.inf, 0)
if v > vT:
vT = v
move = action
else:
vT = math.inf
move = set()
for action in options:
v, count = maxvalue(result(board,action), -math.inf, math.inf, 0)
if v < vT:
vT = v
move = action
return move
def maxvalue(board,alpha,beta,count):
"""
Calculates the max value of a given board recursively together with minvalue
"""
if terminal(board): return utility(board), count+1
v = -math.inf
posactions = actions(board)
for action in posactions:
vret, count = minvalue(result(board, action),alpha,beta,count)
v = max(v, vret)
alpha = max(alpha, v)
if alpha > beta:
break
return v, count+1
def minvalue(board,alpha,beta,count):
"""
Calculates the min value of a given board recursively together with maxvalue
"""
if terminal(board): return utility(board), count+1
v = math.inf
posactions = actions(board)
for action in posactions:
vret, count = maxvalue(result(board, action),alpha,beta,count)
v = min(v, vret)
beta = min(v, beta)
if alpha > beta:
break
return v, count + 1
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T10:01:10.670",
"Id": "261029",
"Score": "4",
"Tags": [
"python",
"tic-tac-toe"
],
"Title": "Minimax algorithm efficiency"
}
|
261029
|
<p>I have an endpoint in my RestAPI which can receive 3 optional parameters and then find information in the database with these parameters, also it is possible to combine the parameters. So, in my controller I take a Map<String, Object> which contains these parameters and then pass it to the service level, where I check which parameters were passed and then I call a specific DAO method, depends on which combination of parameters do I have. Params A and B are of type String, and C is a Map. So in the service level it looks like this:</p>
<pre><code>public Set<ResultEntry> getByParameters(Map<String, Object> query) {
Set<ResultEntry> result = new HashSet<>();
if (query.containsKey("a") && query.containsKey("b") && query.containsKey("c")) {
result.addAll(myDao.getByABC(
(String) query.get("a"), (String) query.get("b"),
(Map<String, String>) query.get("c")
));
} else if (query.containsKey("a") && query.containsKey("b") && !query.containsKey("c")) {
result.addAll(myDao.getByAB(
(String) query.get("a"), (String) query.get("b")
));
} else if (query.containsKey("a") && !query.containsKey("b") && query.containsKey("c")) {
result.addAll(myDao.getByAC(
(String) query.get("a"), (Map<String, String>) query.get("c")
));
} else if (!query.containsKey("a") && query.containsKey("b") && query.containsKey("c")) {
result.addAll(myDao.getByBC(
(String) query.get("b"), (Map<String, String>) query.get("c")
));
} else if (query.size() == 1 && query.containsKey("a")) {
result.addAll(myDao.getByA((String) query.get("a")));
} else if (query.size() == 1 && query.containsKey("b")) {
result.addAll(myDao.getByB((String) query.get("b")));
} else if (query.size() == 1 && query.containsKey("c")) {
result.addAll(myDao.getByC((Map<String, String>) query.get("c")));
}
return result;
}
</code></pre>
<p>Everything works fine, but I feel like this is not the best way to deal with such situations, using if-statements for each possible combination, so how can I improve it?</p>
|
[] |
[
{
"body": "<p>Although it works, the major issue with this approach is its extreme complexity and concreteness. If a new parameter <code>d</code> enters the game, it will became hellish to maintain!</p>\n<p><em>What can be done to improve the current implementation, without changing the approach?</em></p>\n<ul>\n<li><p>there are many repetitions of <code>.containsKey(arg)</code> calls. They can be extracted to respective <code>boolean</code>s like <code>hasA</code>, <code>hasB</code> -> the code will be more readable.</p>\n</li>\n<li><p>there are many redundant casts. <code>(String) query.get("a")</code> and the others can be extracted into respective local <code>var a = (String) query.get("a")</code> -> it will also become shorter and more readable.</p>\n</li>\n<li><p>I think that the <code>result</code> variable might be avoided, if <code>myDao.get*</code> methods already return <code>Set</code>s.</p>\n</li>\n</ul>\n<p><em>How the design can be improved?</em></p>\n<p>For the solution below, I suppose that the interface of the <code>myDao</code> object cannot be changed. If it could, there might be ways to play with method overloads, attempting to apply a pattern.</p>\n<p>The current API of <code>myDao</code> looks very concrete and clear. The names of the methods mention each expected parameter and the order and the number of the arguments is predictable for each case. So the solution that I suggest below is based on the calculation of the method to invoke by reflection.</p>\n<p>The name of the method to invoke on <code>myDao</code> can be calculated as follows:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private String calculateDaoMethodToInvoke(boolean hasA, boolean hasB, boolean hasC) {\n var builder = new StringBuilder("getBy");\n if (hasA) {\n builder.append("A");\n }\n if (hasB) {\n builder.append("B");\n }\n if (hasC) {\n builder.append("C");\n }\n return builder.toString();\n}\n</code></pre>\n<p>We can also calculate the arguments to invoke this method with:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private Object[] calculateDaoMethodArgs(String a, String b, Map<String, String> c) {\n return Stream.of(a, b, c)\n .filter(Objects::nonNull)\n .toArray();\n}\n</code></pre>\n<p>Now, since we know the name of the target method and the parameters to use, the Java reflection features can be used to produce the results.</p>\n<p>We can define a wrapper around the <code>Class.getMethod</code> call, in order to retrieve the reference to the method of <code>myDao</code> to be invoked:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private Method extractDaoMethod(String daoMethodName, Object[] params) {\n try {\n var paramTypes = Arrays.stream(params)\n .map(Object::getClass)\n .toArray(Class[]::new);\n return Dao.class.getMethod(daoMethodName, paramTypes);\n } catch (NoSuchMethodException ex) {\n throw new IllegalStateException(ex);\n }\n}\n</code></pre>\n<p>And its invocation can also be wrapped:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private Collection<ResultEntry> getByParams(String daoMethodName, Object[] params) {\n var method = extractDaoMethod(daoMethodName, params);\n try {\n return (Collection<ResultEntry>) method.invoke(myDao, params);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new IllegalStateException(ex);\n }\n}\n</code></pre>\n<p><strong>Finally</strong>, the <code>getByParameters</code> method is reduced to the following:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public Set<ResultEntry> getByParameters(Map<String, Object> query) {\n var a = (String) query.get("a");\n var b = (String) query.get("b");\n var c = (Map<String, String>) query.get("c");\n\n var daoMethodName = calculateDaoMethodToInvoke(a != null, b != null, c != null);\n var daoArgs = calculateDaoMethodArgs(a, b, c);\n return new HashSet<>(getByParams(daoMethodName, daoArgs));\n}\n</code></pre>\n<p>Please note that there are no more rigid <code>if - else if</code> chaining, the algo became flat.</p>\n<p>This approach allows to easily introduce new parameters, provided that the <code>myDao</code> API continues to respect the same convention for its method names.</p>\n<p>There can be further improvements. For example, the signatures of <code>calculateDaoMethodToInvoke</code> and <code>calculateDaoMethodArgs</code> can be changed in order to accept varargs (and corresponding changes in the implementation). It will make the introduction of new parameters even easier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T06:49:47.177",
"Id": "261090",
"ParentId": "261031",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "261090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T10:36:35.897",
"Id": "261031",
"Score": "1",
"Tags": [
"java",
"performance",
"rest",
"spring",
"hibernate"
],
"Title": "Handling multiple optional parameters in Spring"
}
|
261031
|
<p>this is a kata from codewars, here is the description of the kata:</p>
<p>think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more Italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.</p>
<p>Well, guess what? You have to build an Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence.</p>
<p>and this is my solution to it:</p>
<pre><code>function Xbonacci(signature,n){
let i=0;
let k = n - signature.length;
while(k--){
let sumNums = 0;
//let newArray = [...signature];
signature.slice(i , signature.length ).map((num)=>{
return sumNums += num;
})
signature.push(sumNums);
i++
}
return signature;
}
</code></pre>
<p>the code works well but it doesn't pass the test because of optimization. Is there any way to make this code faster or more optimized? I think the problem is the slice method but I don't what to use it instead.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T22:10:51.737",
"Id": "515139",
"Score": "0",
"body": "As a side note - don't use .map() to perform side-effects, use a for loop instead (or .forEach()). You know you're using .map() wrong if you don't use the newly constructed array that .map() returns."
}
] |
[
{
"body": "<blockquote>\n<p>I think the problem is the slice method but I don't what to use it instead.</p>\n</blockquote>\n<p>It is, but it's not as simple as taking out the <code>slice</code> and using something else in its place, the problem is more fundamental than that.</p>\n<p>This algorithm scales poorly to high values of the original length of <code>signature</code>, by the way let's call this value S so I don't have keep spelling it all out. There is an other approach that does not depend on S, by updating the "sum of past S values" in constant time. Instead of explicitly taking the window of S elements and summing it, the sum of the previous window can be updated: one new value enters the window (added to the sum), and one old value leaves the window (subtracted from the sum). The work done for each element of the output is only one addition and one subtraction, not S additions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T11:44:55.927",
"Id": "515116",
"Score": "0",
"body": "Thanks, @harold. I edited my algorithm based on your suggestion and it worked."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T11:13:20.833",
"Id": "261033",
"ParentId": "261032",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T10:59:09.400",
"Id": "261032",
"Score": "1",
"Tags": [
"javascript",
"performance"
],
"Title": "build a Xbonacci function that takes a signature of X elements ,each next element is the sum of the last X elements ,and returns the first n elements"
}
|
261032
|
<p>I am trying to plot heatmap with three variables x, y and z, each with vector length of 932826. The time taken with the function below is 28 seconds, with a bin size of 10 on each x and y. I have been using another program where the same plot happens in 6 - 7 seconds. Also, I know that the plot function of that program uses Python in the background</p>
<p>When debugging I see that the maximum time consumed is while using the griddata function. So, I was wondering if there are any alternatives that I can use instead of griddata to make the interpolation quicker</p>
<p>In future I will be handling even bigger data (8 to 10 times the size of current one), so I am in need to finding something robust, which handles all the data, without going into memory overflow</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import time
from scipy.interpolate import griddata
import os
arr_len = 932826
x = np.random.uniform(low=0, high=4496, size=arr_len)
y = np.random.uniform(low=-74, high=492, size=arr_len)
z = np.random.uniform(low=-30, high=97, size=arr_len)
x_linspace = 10
y_linspace = 10
x_lab = 'x_label'
y_lab = 'y_label'
title = 'some title'
plot_name = 'example plot'
xi = np.linspace(min(x), max(x), x_linspace)
yi = np.linspace(min(y), max(y), y_linspace)
start = time.time()
zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method='linear')
print('Time elapsed = ', time.time()-start)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T13:33:47.970",
"Id": "515120",
"Score": "0",
"body": "Do you have access to a GPU or to multiples cores to accelerate the execution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:45:20.100",
"Id": "515127",
"Score": "0",
"body": "@IEatBagels : I am not really sure. How can I find out that ? \n\nI tried using interp2d from scipy library, but it seems to give memory overflow error"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T13:16:10.393",
"Id": "261037",
"Score": "3",
"Tags": [
"python",
"scipy",
"interpolation"
],
"Title": "Speed up interpolation in Python"
}
|
261037
|
<p><strong>Write an improved code to identify a valid straight of eight cards</strong>, e.g. <code>4H,5S,AC,7C,8H,AH,0S,JC</code>. Note that the card combination may include Wilds (as we see in our example, with the Ace of Clubs standing in for a Six and the Ace of Hearts standing in for a Nine), but must include at least two "natural" cards (i.e. non-Wild cards). Note also that the sequence of the cards is significant for this group type, and that <code>4H,5S,AC,8C,7H,AH,AS,AC</code>, e.g., is not a valid straight of eight, as it is not in sequence. <strong>Aces are the only wild cards and must represent another card. Duplicate cards are allowed.</strong></p>
<p>Card inputs are in a list of 2 value strings with the value:</p>
<ul>
<li>2 to 9 - for 2 to 9</li>
<li>0 - for 10</li>
<li>J - for Jack</li>
<li>Q - for Queen</li>
<li>K - for King</li>
<li>A - for Ace</li>
</ul>
<p>The suits are shown with values S(spade), C(club), H(heart), D(diamond)</p>
<ol>
<li><strong>Example input to be checked</strong>: <code>4H,5S,AC,7C,8H,AH,0S,JC</code><br />
Output: True</li>
<li><strong>Example input to be checked</strong>: <code>AH,5S,AC,7C,AH,AH,AS,AC</code><br />
Output: True</li>
<li><strong>Example input to be checked</strong>: <code>4H,5S,AC,8C,7H,AH,AS,AC</code><br />
Output: False</li>
</ol>
<p>Here is my code:</p>
<pre><code>group = input().split(",")
if len(group) == 8:
#check for ace
ace = [0 for card in group if card[0] == 'A']
run_vals = {"0": 10, "J": 11, "Q": 12, "K":13}
if len(ace) < 6:
miss_count = 0
for index in range(len(group)-1):
if group[index][0] == "A":
miss_count += 1
if group[index+1][0] == "A" and index == len(group)-2:
miss_count += 1
continue
else:
continue
if group[index+1][0] == "A" and index == len(group)-2:
miss_count += 1
continue
if group[index+1][0] == "A" and index <len(group)-2:
continue
if group[index+1][0] in run_vals:
num1 = run_vals[group[index+1][0]]
else:
num1 = int(group[index+1][0])
if group[index][0] in run_vals:
num2 = run_vals[group[index][0]]
else:
num2 = int(group[index][0])
if (num1 - num2) != 1:
miss_count += 1
if miss_count == len(ace):
print(True)
else:
print(False)
elif len(ace) == 6:
ace_in_between = 0
range_limits = [card for card in group if card[0] != "A"]
for index in range(len(group)):
if index > group.index(range_limits[0]) and index< group.index(range_limits[1]):
ace_in_between += 1
range_limits = [run_vals[val[0]] if val[0] in run_vals else val[0] for val in range_limits]
if ace_in_between + 1 == (int(range_limits[1]) - int(range_limits[0]) ):
print(True)
else:
print(False)
else:
print(False)
else:
print(False)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T16:07:22.723",
"Id": "515130",
"Score": "1",
"body": "Could you please clarify what you are looking? Please read [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T15:40:14.023",
"Id": "515166",
"Score": "0",
"body": "Can an ace represent a “low ace”? How about a “high ace”? As in, is “ace, 2, 3 … 8” a valid straight? How about “7, 8, … king, ace”?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T15:55:23.880",
"Id": "515171",
"Score": "0",
"body": "ace only represents other cards, not an ace itself. The highest possible straight card is the King of any suit and the lowest possible straight card is the 2 of any suit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T07:55:03.180",
"Id": "515390",
"Score": "1",
"body": "Please don't vandalize your posts like that. I've rolled back your edit."
}
] |
[
{
"body": "<p>Good news! There's lots of room for improvement in your code! (How's that for a positive spin?)</p>\n<h1>Counting Aces</h1>\n<pre class=\"lang-py prettyprint-override\"><code> ace = [0 for card in group if card[0] == 'A']\n</code></pre>\n<p>This code creates a list (<code>ace</code>), which only contains <code>0</code> elements equal in number to the number of aces in <code>group</code>. The contents of the list is never used, only the length. Finally, the length of the list is queried twice.</p>\n<p>That is a very heavy implementation for a simple count of the number of aces:</p>\n<pre class=\"lang-py prettyprint-override\"><code> aces = sum(card[0] == 'A' for card in group)\n</code></pre>\n<p>Or slightly less obliquely:</p>\n<pre class=\"lang-py prettyprint-override\"><code> aces = sum(1 for card in group if card[0] == 'A')\n</code></pre>\n<h1>Decoding Cards</h1>\n<pre class=\"lang-py prettyprint-override\"><code> run_vals = {"0": 10, "J": 11, "Q": 12, "K":13}\n ...\n if group[index+1][0] in run_vals:\n num1 = run_vals[group[index+1][0]]\n else:\n num1 = int(group[index+1][0])\n\n if group[index][0] in run_vals:\n num2 = run_vals[group[index][0]]\n else:\n num2 = int(group[index][0])\n ...\n range_limits = [run_vals[val[0]] if val[0] in run_vals else val[0] for val in range_limits]\n if ace_in_between + 1 == (int(range_limits[1]) - int(range_limits[0]) ):\n</code></pre>\n<p>I'm seeing a lot of <code>in run_vals</code> tests and <code>int(...)</code> casts. Imagine how much cleaner your code could look if you simply filled in all of the <code>run_vals</code>?</p>\n<pre class=\"lang-py prettyprint-override\"><code> run_vals = {"A": 1,\n "2": 2, "3": 3, "4": 4, "5": 5,\n "6": 6, "7": 7, "8": 8, "9": 9,\n "0": 10, "J": 11, "Q": 12, "K":13}\n</code></pre>\n<p>I've added "A" mapping to <code>1</code> just for completeness. It would allow you to test <code>all(card[0] in run_vals for card in group)</code> to check that all the cards have a valid rank, such that nobody sneaks in a "1 of Spades" for example.</p>\n<p>For that matter, you could check for valid suits too, such as <code>all(card[1] in {'C', 'D', 'H', 'S'} for card in group)</code>, to avoid someone sneaking in the "7 of Pentacles".</p>\n<h1>A Straight</h1>\n<p>The problem would be dead simple if there was no wild cards. You could write:</p>\n<pre class=\"lang-py prettyprint-override\"><code> rank = [run_vals[card[0]] for card in group]\n start = rank[0]\n for idx in range(len(rank)):\n if rank[idx] != start + idx:\n return False\n return True\n</code></pre>\n<p>Supporting wild cards would be easy too, if we knew the first card was not an ace. We could just add an exception for the aces:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for idx in range(len(rank)):\n if rank[idx] != start + idx and rank[idx] != 1:\n return False\n</code></pre>\n<h1>Starting Value</h1>\n<p>What happens if the ace is the first card? Well, the second card (assume it was not an ace) would dictate the start was one rank lower. Or if that was an ace, then the third card would, and so on:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for idx in range(len(rank)):\n if rank[idx] == 1:\n start = rank[idx] - idx\n break\n else:\n return False # Only aces exist!\n</code></pre>\n<h1>Functions!</h1>\n<p>Your code is one complex script without any functions. If you haven't learned how to write them yet, learn. If you have learned, use them!</p>\n<h1>Reworked Code</h1>\n<p>The following code is a reimplementation of some of the above ideas. However, the loops like <code>for idx in len(range(list))</code> have been replaced with more Pythonic <code>for idx, value in enumerate(list)</code> loops. Loops which return a <code>False</code> if one iteration produces a <code>False</code> result have been replaced with an <code>all(...)</code> statement with a generator expression. It also demonstrates some type-hints, <code>"""docstrings"""</code> (including the use of (<code>doctest</code>) to help write code which is more understandable to others, and contain built-in unit tests.</p>\n<p>Another improvement is the problem statement states there must be at least 2 "natural" cards. Instead of testing for the number of aces is less than or equal to 6 -- a number which appears nowhere in the problem statement -- it directly tests against the given value 2.</p>\n<pre class=\"lang-py prettyprint-override\"><code>RANK = dict(zip("A234567890JQK", range(1, 14)))\nWILD = RANK['A'] \n\ndef straight_of_eight(card_string: str) -> bool:\n """\n Determine if a string of cards is an ascending straight,\n with at least 2 natural cards.\n\n >>> straight_of_eight("4H,5S,AC,7C,8H,AH,0S,JC")\n True\n\n >>> straight_of_eight("4H,5S,AC,8H,7C,AH,0S,JC")\n False\n """\n \n ranks = [RANK[card[0]] for card in card_string.split(',')]\n\n if len(ranks) != 8:\n return False # Were not given exactly 8 cards\n\n if sum(rank != WILD for rank in ranks) < 2:\n return False # Not enough natural cards\n\n # Determine starting rank for the straight\n start = next(rank - idx for idx, rank in enumerate(ranks) if rank != WILD)\n\n return 2 <= start <= 6 and all(rank == idx or rank == WILD\n for idx, rank in enumerate(ranks, start))\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n group = input()\n print(straight_of_eight(group))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T20:25:33.267",
"Id": "261046",
"ParentId": "261044",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "261046",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T15:47:16.377",
"Id": "261044",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Identify valid 8 card poker straight"
}
|
261044
|
<p>I'm developing a RPG game and being blocked by the settings of HP(hit points/health points/health power), attack and defense for the characters - Assassin, Tank and Warrior</p>
<p>I'd like to figure out the values so that the Assassin is guaranteed to defeat the Warrior, meanwhile, the Warrior is guaranteed to defeat the Tank whereas the Tank is guaranteed to defeat the Assassin.</p>
<p>So, I wrote a lab to solve this puzzle.</p>
<p>Here is part of <code>Character.java</code>, the rest of it are just auto generated setters and getters.</p>
<pre><code>private int maxHp, hp, attack, defense, level;
private int place, xp, gold;
private String name;
public void setHp(int hp) {
if (hp>maxHp){
this.hp = maxHp;
} else {
if(hp<0){
this.hp = 0;
} else {
this.hp = hp;
}
}
}
public Character(String name, int maxHp, int attack, int defense){
this(name, maxHp, attack, defense, 0, 0, 1);
}
public Character(String name, int maxHp, int attack, int defense, int xp, int gold, int level) {
// super(); // Is it necessary to call super() here?
this.name = name;
this.maxHp = maxHp;
this.hp = maxHp;
this.attack = attack;
this.defense = defense;
this.xp = xp;
this.gold = gold;
this.level = level;
}
public String toString(){
return name + "'s maxHP: " + maxHp + " Attack: " + attack + " Defense: " + defense;
}
</code></pre>
<p>The <code>Util</code> class is just a shorthand for <code>System.out.println()</code></p>
<pre><code>public class Util {
public static void pln(){
System.out.println();
}
public static void pln(Object obj) {
System.out.println(obj);
}
public static void pln(int value) {
System.out.println(value);
}
}
</code></pre>
<p>LabMain does the calculation which contains a multi-layer loop.</p>
<pre><code>class LabMain {
final static int MINHP = 1;
final static int MAXHP = 100;
final static int MINATTACK = 1;
final static int MINDEFENSE = 0;
public static boolean isBattleFinished(Character player, Character opponent,
int dmgDealt, int dmgTook) {
// the player will never win
// as they cannot deal any damage to their opponent
if (dmgDealt <= 0) {
player.setHp(0);
return true;
}
if (dmgTook < 0)
dmgTook = 0;
opponent.setHp(opponent.getHp() - dmgDealt);
player.setHp(player.getHp() - dmgTook);
if (player.getHp() <= 0) {
return true;
} else if (opponent.getHp() <= 0) {
return true;
}
return false;
}
public static int didTheyWin(Character player, Character opponent){
int dmgDealt = player.getAttack() - opponent.getDefense();
int dmgTook = opponent.getAttack() - player.getDefense();
int round = 0;
boolean isFinished = true;
do {
round++;
isFinished = isBattleFinished(player, opponent, dmgDealt, dmgTook);
} while (round<MAXHP && !isFinished);
if (player.getHp() > 0) {
return round;
}
return 0;
}
static void lab() {
for(int assassinMaxHP = MINHP; assassinMaxHP < MAXHP; assassinMaxHP+=MINHP){
Util.pln("assassinMaxHP: " + assassinMaxHP);
for(int assassinAttack = MINATTACK; assassinAttack < MAXHP; assassinAttack+=MINHP){
for(int assassinDefense = MINDEFENSE; assassinDefense < MAXHP; assassinDefense+=MINHP){
Util.pln("assassinDefense: " + assassinDefense);
for(int warriorMaxHP = MINHP; warriorMaxHP < MAXHP; warriorMaxHP+=MINHP){
Util.pln("warriorMaxHP: " + warriorMaxHP);
for(int warriorAttack = MINATTACK; warriorAttack < MAXHP; warriorAttack+=MINHP){
Util.pln( "assassinAttack: " + assassinAttack +
" assassinDefense:" + assassinDefense +
" warriorMaxHP: " + warriorMaxHP +
" warriorAttack: " + warriorAttack);
for(int warriorDefense = MINDEFENSE; warriorDefense < MAXHP; warriorDefense+=MINHP){
for(int tankMaxHP = MINHP; tankMaxHP < MAXHP; tankMaxHP+=MINHP){
for(int tankAttack = MINATTACK; tankAttack < MAXHP; tankAttack+=MINHP){
for(int tankDefense = MINDEFENSE; tankDefense < MAXHP; tankDefense+=MINHP){
Character assassin1 = new Character("A", assassinMaxHP, assassinAttack, assassinDefense);
Character warrior1 = new Character("W", warriorMaxHP, warriorAttack, warriorDefense);
if(didTheyWin(assassin1, warrior1)>0){
Character warrior2 = new Character("W", warriorMaxHP, warriorAttack, warriorDefense);
Character tank2 = new Character("T", tankMaxHP, tankAttack, tankDefense);
if(didTheyWin(warrior2, tank2)>0){
Character tank3 = new Character("T", tankMaxHP, tankAttack, tankDefense);
Character assassin3 = new Character("A", assassinMaxHP, assassinAttack, assassinDefense);
if(didTheyWin(tank3, assassin3)>0){
Util.pln("- - -");
Util.pln(assassin1);
Util.pln(warrior1);
Util.pln(tank2);
Util.pln("- - -");
System.exit(0);
}
}
}
}
}
}
}
}
}
}
}
}
}
public static void main(String[] args) {
lab();
}
}
</code></pre>
<p>I put the full code on <a href="https://github.com/albert10jp/javamud" rel="nofollow noreferrer">https://github.com/albert10jp/javamud</a></p>
<p>Here is the first finding</p>
<pre><code>A's maxHP: 1 Attack: 1 Defense: 1
W's maxHP: 5 Attack: 1 Defense: 0
T's maxHP: 2 Attack: 2 Defense: 0
</code></pre>
<p>Although W is more like the Tank whereas T is more like the Warrior :)</p>
<p>Please ignore the bunch of <code>Util.pln</code> inside <code>lab()</code> temporarily which is just an indicator to tell me my code is not in an infinite loop and I'm woking on improving it.</p>
<p>Questions:</p>
<p>1.Is there a more elegant way that I don't have to do so many layers of loops?</p>
<p>2.Is it necessary to call <code>super()</code> in the constructor of <code>Character</code>?</p>
<p>Any other comments and suggestions are also appreciated.</p>
|
[] |
[
{
"body": "<p>I would like to mention that this (<code>T > A > W > T</code>) is a very interesting problem to figure out.</p>\n<p>That being said, let me provide my inputs.</p>\n<ol>\n<li><p>Actually <code>super</code> call is necessary when your class <code>extends</code> another class. Why so? Because this helps you call the parent classes <code>constructor</code> and initialize the parent class correctly.</p>\n</li>\n<li><p>Moving onto the <code>GameLogic</code> class that you have in <strong>git</strong> but not asked for review.</p>\n<p>Functions <code>checkAct</code> and <code>battle</code> functions do some work bases on <code>act</code>. Now, this <code>if-else</code> ladder can be improved by changing this to <code>switch</code> block. You might want to clean that up.</p>\n<pre><code>switch(act) {\n case 1:\n ...\n break;\n ...\n default:\n ...\n break;\n}\n</code></pre>\n</li>\n<li><p>Now the final function <code>lab</code>. It is unnecessarily looping over tank if <code>if(didTheyWin(assassin1, warrior1)>0)</code> is false i.e. you can skip whatever <code>tank</code> values you get.</p>\n<p>Original:</p>\n<pre><code>for (assassin)\n for (warrior)\n for (tank)\n if (assassin > warrior)\n if (warrior > tank)\n if (tank > assassin)\n exit\n</code></pre>\n<p>becomes:</p>\n<pre><code>for (assassin)\n for (warrior)\n if (assassin > warrior)\n for (tank)\n if (warrior > tank)\n if (tank > assassin)\n exit\n</code></pre>\n<p>breaking the problem even further:</p>\n<pre><code>for (assassin)\n for (warrior)\n if (assassin > warrior)\n collect in set of assassin and warrior\n\nfor (warrior)\n if (warrior not in set warrior) // ignore warriors and don't bother for tank\n continue\n for (tank)\n if (warrior > tank)\n collect in set tank\n else\n remove from set warrior // this is not desired.\n\nfor (tank)\n if (tank not in set tank) // ignore tanks and don't bother for assassin\n continue\n for (assassin)\n if (assassin not in set assassin) // ignore assassin\n if (tank > assassin)\n exit / continue\n else\n remove from set assassin // this is not desired\n</code></pre>\n<p>Now the final values remaining in all the sets will be your result.</p>\n</li>\n</ol>\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T05:39:48.543",
"Id": "515276",
"Score": "0",
"body": "Thank you so much. Does \"collect in set of assassin and warrior\" mean to put all the combinations of assassins and warriors that the Assassin beats the Warrior in a list of array, which might be a huge a list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T08:15:36.407",
"Id": "515285",
"Score": "0",
"body": "first i meant separate sets for assassin and warrior. then if you have copy constructor than store objects and later match those objects down the line. else store values of HP/attack/defense and later match the values in respective loop to skip rest of the loops."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T14:52:39.843",
"Id": "261104",
"ParentId": "261047",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T22:21:02.550",
"Id": "261047",
"Score": "3",
"Tags": [
"java",
"algorithm"
],
"Title": "calculations for values that match specified criteria in a limit search space"
}
|
261047
|
<p>The Locker Problem is as followed:</p>
<blockquote>
<p>Twenty bored students take turns walking down a hall that contains
a row of closed lockers, numbered 1 to 20. The first student opens all the
lockers; the second student closes all the lockers numbered 2, 4, 6, 8, 10, 12, 14,
16, 18, 20; the third student operates on the lockers numbered 3, 6, 9, 12, 15, 18:
if a locker was closed, he opens it, and if a locker was open, he closes it; and so
on. For the ith student, he works on the lockers numbered by multiples of i: if a
locker was closed, he opens it, and if a locker was open, he closes it. What is the
number of the lockers that remain open after all the students finish their walks?</p>
</blockquote>
<p>I decided to take this problem the extra mile and instead allow the user determine how many students were in the hallway so the number isn't always 20. In what ways can I refactor my code?</p>
<pre class="lang-rust prettyprint-override"><code>use std::io;
fn main() {
// false = closed
// true = opened
let mut lockercount = String::new();
println!("How many students?");
io::stdin().read_line(&mut lockercount).expect("expected int");
let lc = lockercount.trim().parse().unwrap();
let mut lockers = vec![false; lc];
for i in 1..(lockers.len()+1) {
let mut j: usize = 1;
while i*j <= lc {
lockers[(i*j)-1] = !lockers[(i*j)-1];
j += 1;
}
}
let mut lockernum = 1;
println!("Opened lockers:");
for v in lockers {
if v == true {
print!("{}, ", lockernum);
}
lockernum += 1;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T18:50:32.547",
"Id": "515193",
"Score": "0",
"body": "Since you've mentioned _Number Theory_, I hope you know that the answer is readily available without `for i in 1..(lockers.len()+1)` loop."
}
] |
[
{
"body": "<p>Your code seems fine. However, there is one part I'd definitely change: the scope of variables. For example, <code>lockercount</code> isn't necessary for more than the initial <code>lc</code>. We can keep its scope down:</p>\n<pre><code> println!("How many students?");\n let lc = {\n let mut lockercount = String::new();\n io::stdin().read_line(&mut lockercount).expect("expected int");\n lockercount.trim().parse().unwrap()\n };\n</code></pre>\n<p>Similarly, I would prefer to use <code>enumerate</code> instead of an explicit counter. An explicit counter might not be incremented by accident, but <code>enumerate</code> on an iterator will always fit:</p>\n<pre><code> println!("Opened lockers:");\n for (n, v) in lockers.iter().enumerate() {\n if *v == true {\n print!("{}, ", n + 1);\n }\n }\n</code></pre>\n<p>We could also get rid of the <code>if</code> via <code>filter</code>, but that's a little bit much:</p>\n<pre><code> for (n, _v) in lockers.iter().enumerate().filter(|(_, &b)| b) {\n print!("{}, ", n + 1);\n }\n</code></pre>\n<p>On the algorithmic part of the code, I'd prefer to use the <code>pos</code>ition explicitly instead of <code>i*j</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> for i in 1..(lockers.len() + 1) {\n let mut pos: usize = i;\n while pos <= lc {\n lockers[pos - 1] = !lockers[pos - 1];\n pos += i;\n }\n }\n</code></pre>\n<p>Again, instead of explicitly changing a counter, I would prefer an immutable variable, for example via <code>step_by</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> for i in 1..(lockers.len() + 1) {\n for pos in (i..lc).step_by(i) {\n lockers[pos - 1] = !lockers[pos - 1];\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T19:08:02.090",
"Id": "261077",
"ParentId": "261050",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "261077",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T23:37:46.447",
"Id": "261050",
"Score": "3",
"Tags": [
"rust"
],
"Title": "Rust Locker Problem Number Theory"
}
|
261050
|
<p>The live version is at my <a href="https://github.com/tlatimer/lingoCheater" rel="nofollow noreferrer">github</a></p>
<p>Lingo is a game where the host secretly picks a 5 letter word, then provides the first letter to the player. The player then guesses a word, and the host gives feedback on what letters are right, wrong, or in the wrong position.</p>
<p>I call this feedback match_string and use the following format:</p>
<p>'s' = right letter, right position (to represent square)</p>
<p>'o' = right letter, wrong position (to represent circle)</p>
<p>'x' = letter is not in word. (to represent.. well.. X)</p>
<p>This is a cheater for Lingo. It loads data from the word list (in this case scrabble dictionary) to find potential words. It also provides guesses according to both the probability of characters in remaining words, and also an english word usage frequency.</p>
<pre><code>from collections import defaultdict, Counter
from copy import copy
from math import log
from random import choices
import re
import os
import pickle
# VARIABLES
num_loops = 10**4
word_len = 5
max_guesses = 5
word_list = 'Collins Scrabble Words (2019).txt'
freq_list = 'all.num.o5.txt'
cache_file = 'cached.pickle'
# PROGRAM
def main():
wl = WordList()
# TODO: add a mode where human can play vs comp supplied words
print("""
1. [H]uman enters guesses and match strings from an external source
2. [C]omputer plays vs itself""")
while True:
i = input('Choice?').lower()
if i in ['1', 'h']:
human_player(wl)
elif i in ['2', 'c', '']:
CompPlay(wl).cp_main()
break
else:
print('Invalid Choice')
def human_player(wl):
while True:
first_letter = input('What\'s the first letter?').upper()
pc = PossCalculator(wl, first_letter)
while True:
pc.print_best(5)
guess = input('Guess?').upper()
if guess == '':
guess = first_letter + pc.get_best(1)[0][0]
print(f'Guessing: {guess}')
elif guess[1:] not in pc.poss:
print(guess, 'is not a valid word. Please try again')
continue
match_string = input('Match String?').lower()
if not re.search(r'[sox]{'+str(word_len)+'}', match_string):
print('invalid match string. Please try again')
num_poss = pc.calc_matches(guess, match_string)
if num_poss == 1:
print(f' -={guess}=-')
break
print(f' {num_poss} words left')
if num_poss == 0:
print(' WTF did you do?')
break
def str_pos_sub(string, pos, sub):
return string[:pos] + sub + string[pos + 1:]
class CompPlay:
def __init__(self, wl):
self.wl = wl
def cp_main(self):
guess_counter = Counter()
for _ in range(num_loops):
word = self.get_word()[0]
print(f'Word is: {word}')
pc = PossCalculator(self.wl, word[0])
guesses = []
while True:
guess = word[0] + pc.get_best(1)[0][0]
if guess in guesses:
pc.poss.discard(guess[1:])
continue
guesses.append(guess)
if len(guesses) > max_guesses:
print(' :( too many guesses')
guess_counter['DQ'] += 1
break
elif guess == word:
print(f' -={word}=-')
print(f' {len(guesses)} guesses')
guess_counter[len(guesses)] += 1
break
match_string = self.get_match_string(word, guess)
num_poss = pc.calc_matches(guess, match_string)
print(f' {guess}\t{match_string}\t{num_poss} words left')
if word[1:] not in pc.poss:
print(' WTF did you do?')
guess_counter['WTF'] += 1
break
print('\n')
for guesses, count in guess_counter.most_common():
print(f'{count:5d} solved in {guesses} guesses')
def get_match_string(self, word, guess):
match_string = '.' * word_len
for pos in range(word_len):
if guess[pos] == word[pos]:
match_string = str_pos_sub(match_string, pos, 's')
word = word.replace(word[pos], '.', 1)
for pos in range(word_len):
if match_string[pos] != '.':
continue
elif guess[pos] in word[1:]:
match_string = str_pos_sub(match_string, pos, 'o')
word = word.replace(guess[pos], '.', 1)
else:
match_string = str_pos_sub(match_string, pos, 'x')
return match_string
def get_word(self):
return choices(
list(self.wl.word_freq.keys()), # population
list(self.wl.word_freq.values()), # weights # TODO: speedup by turning this into a cached cumulative list
)
class PossCalculator:
def __init__(self, wl, first_letter):
self.wl = wl
self.first_letter = first_letter
self.poss = copy(wl.starts_with(first_letter))
print(f' starting letter {first_letter}, {len(self.poss)} words left')
def calc_matches(self, guess, match_string):
guess = guess[1:]
match_string = match_string[1:]
poss_copy = copy(self.poss)
for word in poss_copy:
if not self.check_valid(guess, match_string, word):
self.poss.remove(word)
return len(self.poss)
def check_valid(self, guess, match_string, word):
pos_dict = {
's': [],
'o': [],
'x': [],
}
for pos, char in enumerate(match_string):
pos_dict[char].append(pos)
for pos in pos_dict['s']:
if guess[pos] == word[pos]:
word = str_pos_sub(word, pos, '.')
else:
return False
for pos in pos_dict['o']:
if guess[pos] in word and guess[pos] != word[pos]:
word = word.replace(guess[pos], '.', 1)
else:
return False
for pos in pos_dict['x']:
if guess[pos] in word:
return False
# You have passed the three trials of the match_string. You have proven yourself.
return True
def get_best(self, n):
char_score = Counter()
for word in self.poss:
for char in set(word):
char_score[char] += 1
word_scores = Counter()
for word in self.poss:
word_set = set(word)
for char in word_set:
word_scores[word] += char_score[char]
word_scores[word] *= (len(word_set) + 1)
avg_word_score = int(sum(word_scores.values()) / len(word_scores))
for word, score in word_scores.items():
word_scores[word] = int(score / avg_word_score * 130)
word_scores[word] += self.wl.word_freq[self.first_letter + word]
return word_scores.most_common(n)
def print_best(self, n):
for word, score in self.get_best(n):
print(f'{self.first_letter}{word}\t{score}')
class WordList:
def __init__(self):
if os.path.exists(cache_file):
print('Loading cached wordlist!') # TODO: pickle doesn't want to dump the variables, see below
# with open(cache_file, 'rb') as f:
# self.word_dict = pickle.load(f)
# self.word_freq = pickle.load(f)
else:
print('Building wordlist!')
self.build_wordlists()
def build_wordlists(self):
self.word_dict = defaultdict(set)
# word_dict is {first_letter: [rest_of_word1, rest_of_word2]}
with open(word_list) as f:
for word in f:
if len(word) == word_len+1:
self.word_dict[word[0]].add(word[1:word_len])
# we already know the first letter, so cut off with [1:]
# there's a newline while reading, so cut it off with [:5]
self.word_freq = defaultdict(lambda: 40)
with open(freq_list) as f:
for line in f:
line = line.split()
if len(line[1]) == word_len:
word = line[1].upper()
if word[1:] in self.word_dict[word[0]]:
self.word_freq[word] = int(log(int(line[0]), 6) * 40)
for word in self.word_freq:
assert word[1:] in self.word_dict[word[0]]
# with open(cache_file, 'wb') as f:
# pickle.dump((self.word_dict, self.word_freq), f)
def starts_with(self, first_letter):
return self.word_dict[first_letter]
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>The quality of your code is good.\nYou have a clear consistent style, which looks quite PEP 8 compatible.\nThe one glaring change I'd make is your variables at the top of the file are actually constants.\nAs such the names would be <code>UPPER_SNAKE_CASE</code> if you decide to follow PEP 8 here.</p>\n<p>If we look at individual lines or functions of code stand alone your code is fairly strong.\nYou don't have glaring issues by using poor 'line-level' patterns.</p>\n<p>However the code is hard to read and understand.\nI think you've focused on getting the cheating working, as such you've not put much thought into the overall structure.\nFor example you have duplicate logic in <code>human_player</code> and <code>CompPlay.cp_main</code>.\nYou can build a common interface between the two methods of play.</p>\n<p>Lets look into how we could build a common interface from the description in your question.</p>\n<ul>\n<li><p><code>choose_word</code></p>\n<blockquote>\n<p>Lingo is a game where the host secretly picks a 5 letter word, then provides the first letter to the player.</p>\n</blockquote>\n</li>\n<li><p><code>get_guess</code></p>\n<blockquote>\n<p>The player then guesses a word,</p>\n</blockquote>\n</li>\n<li><p><code>get_match</code></p>\n<blockquote>\n<p>and the host gives feedback on what letters are right, wrong, or in the wrong position.</p>\n</blockquote>\n</li>\n<li><p><code>is_match</code><br />\nPresumably we want to stop playing once we guess the right word.</p>\n</li>\n<li><p><code>complete</code><br />\nThe host would congratulate winners, we can here.</p>\n</li>\n</ul>\n<p>Here's an example implementation in Python.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Protocol\n\n\nclass IGame(Protocol):\n def choose_word(self) -> int: ...\n def get_guess(self, size: int) -> str: ...\n def get_match(self, guess: str) -> str: ...\n def is_match(self, guess: str, match: str) -> bool: ...\n def complete(self, guess: str) -> None: ...\n\n\nclass HumanGame:\n known_words: list[str]\n\n def __init__(self, known_words: list[str]) -> None:\n self.known_words = known_words\n\n def choose_word(self) -> int:\n self.word = random.choice(self.known_words)\n print(f"Computer has chosen a word starting with {self.word[0]}")\n return len(self.word)\n\n def get_guess(self, size: int) -> str:\n while True:\n guess = input(f"Guess a {size} letter word? ").upper()\n if len(guess) != size:\n print("Invalid length guess")\n continue\n break\n return guess\n\n def get_match(self, guess: str) -> str:\n characters = set(self.word)\n return "".join([\n "s"\n if g == w else\n "o"\n if g in characters else\n "x"\n for g, w in zip(guess, self.word)\n ])\n\n def is_match(self, guess: str, match: str) -> bool:\n return match == "s" * len(guess)\n\n def complete(self, guess: str) -> None:\n print(f"You are correct, {guess} is the word.")\n\n\ndef game_main(game: IGame):\n size = game.choose_word()\n while True:\n guess = game.get_guess(size)\n match = game.get_match(guess)\n if game.is_match(guess, match):\n break\n game.complete()\n\n\ndef main():\n game_main(HumanGame(["CAT", "BAT", "WAT"]))\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>From here we can then focus on picking the best.\nI find your code quite complicated.</p>\n<p>The code has two highly coupled classes to deal with picking the best.\nSome of the decisions around how to store the data make the code quite complex.\nAnd the code has a lack of Single Responsibility Principle (SRP) being applied.</p>\n<p>Lets focus just on <code>word_list</code>;</p>\n<ul>\n<li>I cannot pass a list of words to <code>WordList</code>. (impaired functionality)</li>\n<li>The code reads from the global <code>word_list</code>. (impaired functionality)</li>\n<li>The class coupled the frequency when building the word list. (increased complexity)</li>\n<li>You can only read from a file applying your filters straight away. (impaired reusability)</li>\n<li>You filter the output in <code>PossCalculator</code>. (increased complexity)</li>\n</ul>\n<p>Lets focus on what you do to the word list:</p>\n<ul>\n<li>Read from a file.</li>\n<li>Filter words by length.</li>\n<li>Filter words by starting letter.<br />\n(You actually group and then index a dictionary, but functionally the same thing.)</li>\n<li>Filter by <code>match_string</code> and <code>guess</code>.</li>\n<li>Give each word a score based on letters.</li>\n</ul>\n<p>As such we can build a single class to do everything.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\n\nclass Words(list[str]):\n @classmethod\n def from_path(cls, path: str) -> Words:\n with open(path) as f:\n return cls([word.strip() for word in f])\n\n def filter_length(self, size: int) -> Words:\n return Words([\n word\n for word in self\n if len(word) == size\n ])\n\n def filter_start(self, start: str) -> Words:\n return Words([\n word\n for word in self\n if word.startswith(start)\n ])\n\n def filter_match(self, guess: str, match: str):\n return Words([\n word\n for word in self\n if self._check_valid(guess, match, word)\n ])\n\n @staticmethod\n def _check_valid(guess: str, match: str, word: str) -> bool:\n pos_dict = {\n 's': [],\n 'o': [],\n 'x': [],\n }\n for pos, char in enumerate(match):\n pos_dict[char].append(pos)\n for pos in pos_dict['s']:\n if guess[pos] == word[pos]:\n word = word[:pos] + '.' + word[pos + 1:]\n else:\n return False\n for pos in pos_dict['o']:\n if guess[pos] in word and guess[pos] != word[pos]:\n word = word.replace(guess[pos], '.', 1)\n else:\n return False\n for pos in pos_dict['x']:\n if guess[pos] in word:\n return False\n return True\n\n def get_scores(self) -> collections.Counter[str, int]:\n char_score = collections.Counter()\n for word in self:\n for char in set(word):\n char_score[char] += 1\n word_scores = collections.Counter()\n for word in self:\n word_set = set(word)\n for char in word_set:\n word_scores[word] += char_score[char]\n return word_scores\n</code></pre>\n<p>I have gone on to change to roughly reimplement <code>CompPlay</code> with the above changes. So you can see how I'd use the code.<br />\n<sup><strong>Note</strong>: all code blocks are untested</sup></p>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\nimport random\nimport math\nimport collections\nfrom typing import Iterable, Protocol\n\n\nclass IGame(Protocol):\n def choose_word(self) -> int: ...\n def get_guess(self, size: int) -> str: ...\n def get_match(self, guess: str) -> str: ...\n def is_match(self, guess: str, match: str) -> bool: ...\n def complete(self, guess: str) -> None: ...\n\n\nclass HumanGame:\n known_words: list[str]\n\n def __init__(self, known_words: list[str]) -> None:\n self.known_words = known_words\n\n def choose_word(self) -> int:\n self.word = random.choice(self.known_words)\n print(f"Computer has chosen a word starting with {self.word[0]}")\n return len(self.word)\n\n def get_guess(self, size: int) -> str:\n while True:\n guess = input(f"Guess a {size} letter word? ").upper()\n if len(guess) != size:\n print("Invalid length guess")\n continue\n break\n return guess\n\n def get_match(self, guess: str) -> str:\n characters = set(self.word)\n return "".join([\n "s"\n if g == w else\n "o"\n if g in characters else\n "x"\n for g, w in zip(guess, self.word)\n ])\n\n def is_match(self, guess: str, match: str) -> bool:\n return match == "s" * len(guess)\n\n def complete(self, guess: str) -> None:\n print(f"You are correct, {guess} is the word.")\n\n\ndef game_main(game: IGame):\n size = game.choose_word()\n while True:\n guess = game.get_guess(size)\n match = game.get_match(guess)\n if game.is_match(guess, match):\n break\n game.complete()\n\n\nclass Words(list[str]):\n @classmethod\n def from_path(cls, path: str) -> Words:\n with open(path) as f:\n return cls([word.strip() for word in f])\n\n def filter_length(self, size: int) -> Words:\n return Words([\n word\n for word in self\n if len(word) == size\n ])\n\n def filter_start(self, start: str) -> Words:\n return Words([\n word\n for word in self\n if word.startswith(start)\n ])\n\n def filter_match(self, guess: str, match: str):\n return Words([\n word\n for word in self\n if self._check_valid(guess, match, word)\n ])\n\n @staticmethod\n def _check_valid(guess: str, match: str, word: str) -> bool:\n pos_dict = {\n 's': [],\n 'o': [],\n 'x': [],\n }\n for pos, char in enumerate(match):\n pos_dict[char].append(pos)\n for pos in pos_dict['s']:\n if guess[pos] == word[pos]:\n word = word[:pos] + '.' + word[pos + 1:]\n else:\n return False\n for pos in pos_dict['o']:\n if guess[pos] in word and guess[pos] != word[pos]:\n word = word.replace(guess[pos], '.', 1)\n else:\n return False\n for pos in pos_dict['x']:\n if guess[pos] in word:\n return False\n return True\n\n def get_scores(self) -> collections.Counter[str, int]:\n char_score = collections.Counter()\n for word in self:\n for char in set(word):\n char_score[char] += 1\n word_scores = collections.Counter()\n for word in self:\n word_set = set(word)\n for char in word_set:\n word_scores[word] += char_score[char]\n return word_scores\n\n\nclass Frequencies(dict[str, int]):\n @classmethod\n def from_frequencies(cls, frequencies: Iterable[tuple[int, str]]) -> Frequencies:\n return cls({\n word: int(math.log(frequency, 6) * 40)\n for frequency, word in frequencies\n })\n\n @classmethod\n def from_path(cls, path: str) -> Frequencies:\n with open(path) as f:\n return cls.from_frequencies(\n (int(split[0]), split[1])\n for line in f\n if (split := line.split())\n )\n\n\nclass PossCalculator:\n def __init__(self, words: Words, freqs: Frequencies) -> None:\n self.words = words\n self.freqs = freqs\n\n def calc_matches(self, guess: str, match: str) -> int:\n self.words = self.words.filter_match(guess, match)\n return len(self.words)\n\n def get_bests(self) -> collections.Counter[str, int]:\n word_scores = self.words.get_scores()\n avg_word_score = int(sum(word_scores.values()) / len(word_scores))\n for word, score in word_scores.items():\n word_scores[word] = int(score / avg_word_score * 130)\n word_scores[word] += self.freqs[word]\n return word_scores\n\n def get_best(self) -> str:\n return self.get_bests().most_common(1)[0][0]\n\n def print_best(self, n):\n for word, score in self.get_bests().most_common(n):\n print(f'{word}\\t{score}')\n\n\nclass ComputerGame:\n pos: PossCalculator\n word: str\n guesses: set[str]\n\n def __init__(self, pos: PossCalculator) -> None:\n self.pos = pos\n self.guesses = set()\n\n def choose_word(self) -> int:\n self.word = random.choices(\n list(self.pos.freqs.keys()),\n list(self.pos.freqs.values()),\n )[0]\n print(f'Word is: {self.word}')\n return len(self.word)\n\n def get_guess(self, size: int) -> str:\n while True:\n guess = self.pos.get_best()\n if guess in self.guesses:\n continue\n self.guesses.add(guess)\n return guess\n\n def get_match(self, guess: str) -> str:\n characters = set(self.word)\n return "".join([\n "s"\n if g == w else\n "o"\n if g in characters else\n "x"\n for g, w in zip(guess, self.word)\n ])\n\n def is_match(self, guess: str, match: str) -> bool:\n return match == "s" * len(guess)\n\n def complete(self, guess: str) -> None:\n print(f'{self.word} solved in {len(self.guesses)} guesses')\n\n\ndef main():\n WORD_LIST = 'Collins Scrabble Words (2019).txt'\n FREQ_LIST = 'all.num.o5.txt'\n words = Words.from_path(WORD_LIST).filter_length(5)\n frequencies = Frequencies.from_path(FREQ_LIST)\n game_main(ComputerGame(PossCalculator(words, frequencies)))\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T19:28:46.960",
"Id": "515261",
"Score": "0",
"body": "Thank you for taking the time to write all that out! some of it makes sense, and some of it makes my head spin."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T19:31:48.633",
"Id": "515262",
"Score": "0",
"body": "Apparently enter finishes the comment... anyway, i've never completely understood the variable type syntax you have, though i've seen it in popups while using pycharm... good to know that that's an actual thing, and i can see where that'd be useful instead of the occasional comment 'this is how this variable is structured'. You mentioned SRP, which I understand is part of OOP in general, but I've yet to find a good resource that i grok how to explain what should be in which classes, and where they go in a hierarchy. More reading I suppose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T21:12:29.953",
"Id": "515268",
"Score": "0",
"body": "@TomL \"i've never completely understood the variable type syntax you have\" is ok. I've only used type hints to make the code easier for me to write, feel free to ignore anything `typing` related. SRP is paradigm independent (has nothing to do with OOP). Single Responsibility Principle just says a single unit of code (a class, function, method, etc.) should have one responsibility. Contrast `build_wordlists` (which builds two different datatypes) and how the method's I've written only do one task, where the consumer of `Words` tells the class how to behave for your business goals."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T15:55:29.977",
"Id": "261071",
"ParentId": "261053",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T01:46:13.493",
"Id": "261053",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"game"
],
"Title": "python wordgame solver in 270 lines"
}
|
261053
|
<p>I recently completed the following exercise, but wanted some feedback on how idiomatic etc. my haskell program is. This is from a course which introduces us to file IO before we cover the theory of monads, so my monad-knowledge is still in its infancy. Any feedback much appreciated.</p>
<p>Here's the task:</p>
<blockquote>
<p>In <code>StudentTeacher.hs</code>, observe that we have an old version of our <code>Person</code> type with the <code>Student</code>
and <code>Teacher</code> constructor. Fill in <code>studentTeacherBasic</code> so that it will use arguments to determine
the right type of person. If the arguments contain <code>-s</code> or <code>--student</code>, read two lines, for name and age,
and make a student. If there is <code>-t</code> or <code>--teacher</code>, read two lines for the name and department. If
there are no arguments, print:</p>
<p><code>Please specify the type of person!</code></p>
<p>Print the resulting person otherwise.</p>
<p>Fill in studentTeacherAdvanced, which should have the same result as your basic version, but
read its input differently. Take a file name as the first argument. If it ends in .student, read lines from
the file assuming they contain a student's information. If it’s .teacher, assume a teacher. Print the
same failure message in any other case.</p>
</blockquote>
<p>Here's my answer:</p>
<pre class="lang-hs prettyprint-override"><code>module StudentTeacher where
import Data.List.Split (splitOn)
import Text.Read (readMaybe)
import System.IO (openFile, withFile, IOMode(..), hGetLine, hGetContents, Handle, stdin)
import System.Environment (getArgs)
import Data.Maybe (isNothing)
data Person =
Student String Int |
Teacher String String
deriving (Show)
type PersonDecoder = String -> Maybe Person
type CLIParser = [String] -> Maybe (PersonDecoder, (IO Handle))
studentTeacher :: CLIParser -> IO ()
studentTeacher cliparser = do
arguments <- getArgs
maybePerson <- case (cliparser arguments) of
Nothing -> return Nothing
Just (decoder, getHandle) -> do
handle <- getHandle
decodePersonFromHandle decoder handle
case maybePerson of
Nothing -> putStrLn "Please specify the type of person"
Just person -> print person
studentTeacherBasic :: IO ()
studentTeacherBasic = studentTeacher parseArgsFlag
decodePersonFromHandle :: PersonDecoder -> Handle -> IO (Maybe Person)
decodePersonFromHandle decoder handle = do
line1 <- hGetLine handle
line2 <- hGetLine handle
return $ decoder $ line1 ++ "\n" ++ line2
parseArgsFlag :: CLIParser
parseArgsFlag [] = Nothing
parseArgsFlag ("-t":_) = Just (decodeTeacher, wrapStdIn)
parseArgsFlag ("-s":_) = Just (decodeStudent, wrapStdIn)
parseArgsFlag ("--teacher":_) = parseArgsFlag ["-t"]
parseArgsFlag ("--student":_) = parseArgsFlag ["-s"]
wrapStdIn :: IO Handle
wrapStdIn = do
return stdin
decodeTeacher :: PersonDecoder
decodeTeacher encoded =
case lines of [] -> Nothing
[_] -> Nothing
(name:dept:_) -> Just (Teacher name dept)
where lines = splitOn "\n" encoded
decodeStudent :: PersonDecoder
decodeStudent encoded =
case lines of [] -> Nothing
[_] -> Nothing
(name:age:_) -> decodeStudentLines name age
where lines = splitOn "\n" encoded
decodeStudentLines :: String -> String -> Maybe Person
decodeStudentLines name age =
case decodedAge of Nothing -> Nothing
(Just ageInt) -> Just (Student name ageInt)
where decodedAge = readMaybe age :: Maybe Int
studentTeacherAdvanced :: IO ()
studentTeacherAdvanced = studentTeacher parseArgsSuffix
parseArgsSuffix :: CLIParser
parseArgsSuffix [] = Nothing
parseArgsSuffix (fname:_) =
if hasSuffix fname "student" then Just (decodeStudent, openFile fname ReadMode)
else if hasSuffix fname "teacher" then Just (decodeTeacher, openFile fname ReadMode)
else Nothing
hasSuffix :: String -> String -> Bool
hasSuffix filename suffix = if length components == 0 || length components == 1
then False
else last components == suffix
where
components = splitOn "." filename
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T09:17:58.780",
"Id": "515152",
"Score": "1",
"body": "You can use great http://hackage.haskell.org/package/optparse-applicative library for option parsing."
}
] |
[
{
"body": "<p>First things first: great work on adding a type signature on every function. Now, let's see how we can improve the code.</p>\n<p></p>\n<h2>Use interesting case first, others later</h2>\n<p>When we pattern match in a binding or in a <code>case</code> expression, it's often easier to start with the interesting case first and then handle the <em>Error</em> cases:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>decodeTeacher :: PersonDecoder\ndecodeTeacher encoded =\n case lines of (name:dept:_) -> Just (Teacher name dept)\n _ -> Nothing\n where lines = splitOn "\\n" encoded\n\ndecodeStudent :: PersonDecoder\ndecodeStudent encoded =\n case lines of (name:age:_) -> decodeStudentLines name age\n _ -> Nothing\n where lines = splitOn "\\n" encoded\n</code></pre>\n<p></p>\n<h2>Check the standard library for already existing functionality</h2>\n<p>We stay at those functions. The name <code>lines</code> is very unfortunate, as there is already a <code>lines</code> in the <code>Prelude</code>. It's a function with the following signature:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>lines :: String -> [String]\n</code></pre>\n<p>With that function, we can get rid of <code>splitOn</code>:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>decodeTeacher :: PersonDecoder\ndecodeTeacher encoded =\n case lines encoded of\n (name:dept:_) -> Just (Teacher name dept)\n _ -> Nothing\n\ndecodeStudent :: PersonDecoder\ndecodeStudent encoded =\n case lines encoded of\n (name:age:_) -> decodeStudentLines name age\n _ -> Nothing\n</code></pre>\n<p></p>\n<h2>Prefer simpler logic where possible</h2>\n<p>Next, we have a look at <code>parseArgsSuffix</code>:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseArgsSuffix :: CLIParser\nparseArgsSuffix [] = Nothing\nparseArgsSuffix (fname:_) =\n if hasSuffix fname "student" then Just (decodeStudent, openFile fname ReadMode)\n else if hasSuffix fname "teacher" then Just (decodeTeacher, openFile fname ReadMode)\n else Nothing\n</code></pre>\n<p>That's a rather long <code>if</code> expression. A guard may be easier to read and handle:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseArgsSuffix :: CLIParser\nparseArgsSuffix [] = Nothing\nparseArgsSuffix (fname:_)\n | fname `hasSuffix` "student" = Just (decodeStudent, openFile fname ReadMode)\n | fname `hasSuffix` "teacher" = Just (decodeTeacher, openFile fname ReadMode)\n | otherwise = Nothing\n</code></pre>\n<p>Note that we should keep the uninteresting case here first, as it improves readability. However, we're repeating ourselves. Something along</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseArgsSuffix :: CLIParser\nparseArgsSuffix [] = Nothing\nparseArgsSuffix (fname:_)\n | fname `hasSuffix` "student" = decodeVia decodeStudent \n | fname `hasSuffix` "teacher" = decodeVia decodeTeacher\n | otherwise = Nothing\n where\n decodeVia f = Just (f, openFile fname ReadMode)\n</code></pre>\n<p>might reduce the duplication. Now, let's have a look at <code>hasSuffix</code>:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>hasSuffix :: String -> String -> Bool\nhasSuffix filename suffix = if length components == 0 || length components == 1\n then False\n else last components == suffix\n where\n components = splitOn "." filename\n</code></pre>\n<p>Again, <code>splitOn</code> is an overkill here. We only want to know if our filename ends with the given extension. The function <code>isSuffixOf</code> from <code>Data.List</code> handles that fine:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>hasSuffix :: String -> String -> Bool\nhasSuffix filename suffix = ('.' : suffix) `isSuffixOf` filename\n</code></pre>\n<p>We could probably even remove <code>hasSuffix</code> completely that way.</p>\n<p></p>\n<h2>Make sure that functions are total</h2>\n<p><code>parseArgsFlag</code> is partial. If we use <code>parseArgsFlags</code> on <code>["whoops!", "-t"]</code>, then none of the patterns match:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseArgsFlag :: CLIParser\nparseArgsFlag [] = Nothing\nparseArgsFlag ("-t":_) = Just (decodeTeacher, wrapStdIn)\nparseArgsFlag ("-s":_) = Just (decodeStudent, wrapStdIn)\nparseArgsFlag ("--teacher":_) = parseArgsFlag ["-t"]\nparseArgsFlag ("--student":_) = parseArgsFlag ["-s"]\n</code></pre>\n<p>If that is intended, then everything is fine. However, if you want to handle those cases, then add a match all pattern:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseArgsFlag _ = Nothing\n</code></pre>\n<p>I would prefer something like this, by the way:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseArgsFlag :: CLIParser\nparseArgsFlag args\n | any (`elem` args) ["-t", "--teacher"] = Just (decodeTeacher, wrapStdIn)\n | any (`elem` args) ["-s", "--student"] = Just (decodeStudent, wrapStdIn)\n | otherwise = Nothing\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T18:47:16.123",
"Id": "261076",
"ParentId": "261055",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261076",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T08:33:02.043",
"Id": "261055",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Haskell program with basic CLI parsing, file reading, and decoding file contents into specified types"
}
|
261055
|
<p>I am writing a credit card generator. I have method <code>GenerateVisa()</code> who will return either a 13 or 16 numbers string.
This is the default value but GenerateVisa can also take a parameter. THis parameter will allow us to force the output to either 13 or 16.
What is this parameter? I could use a int like <code>GenerateVisa(int length = -1)</code> and write</p>
<pre><code>GenerateVisa(int length = -1)
{
if (length == -1)
return randomly 13 or 16
if (length == 13)
return 13 numbers string
if (length == 16)
return 16 numbers string
// what if we have any other value? fallback to random? throw?
}
</code></pre>
<p>I dont like this solution because it is not very good for discoverability. My current solution is to rely on an enum:</p>
<pre><code>enum VisaLength {
Random = 0,
Thirteen = 1,
Sixteen = 2
}
GenerateVisa(VisaLength length = VisaLength.Random)
{
if (length == VisaLength.Random)
return randomly 13 or 16
if (length == VisaLength.Thirteen)
return 13 numbers string
if (length == VisaLength.Sixteen)
return 16 numbers string
// what if we have any other value? fallback to random? throw?
}
</code></pre>
<p>This work quite well until I learnt that</p>
<ul>
<li>Maestro card can go from 12 to 19</li>
<li>Solo can accept 16, 18 or 19</li>
<li>Some are 16 only</li>
<li>I have 28 credit card to support with all kind of other variation</li>
</ul>
<p>You can find all this card on <a href="https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN)" rel="nofollow noreferrer">Wikipedia</a></p>
<p>Should I write a different enum each time? Is there a better way to handle that?</p>
<p>My original code is in F#, but I will gladly see how others languages deals with it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T09:58:41.117",
"Id": "515155",
"Score": "0",
"body": "Hi Aloisdg - the others aren't \"VISA\" - perhaps the generate visa method shouldn't be creating them??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T10:12:16.390",
"Id": "515156",
"Score": "0",
"body": "@MrR I have a `GenerateVisa`, a `GenerateMaestro`, a `GenerateSolo`, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T13:46:59.803",
"Id": "515162",
"Score": "2",
"body": "Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T14:05:25.287",
"Id": "515164",
"Score": "0",
"body": "@BCdotWEB would this question be more fitting over https://softwareengineering.stackexchange.com/ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:42:07.730",
"Id": "515313",
"Score": "0",
"body": "from what you have posted here it appears that you aren't finished with this portion of the code. Code Review is for Reviewing code that is fully functional as is, without any changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:48:03.623",
"Id": "515314",
"Score": "0",
"body": "I am done with the code. It is in F#. I posted pseudo code here because C#-ish lang are more popular. I want more a review of the concept more than the code itself. Thats why I was asking if it would be better suited for SE. @Malachiany any ideas?"
}
] |
[
{
"body": "<p>You may need to have a class for each card type, and an abstract class that would be shared between them.</p>\n<p>from the Wikipedia page, I can see each card can have <code>Name</code>, <code>IIN Range</code> , <code>Active</code>, <code>Length</code> and <code>Validation</code>. Now, from there we can get the common values for each card (what are the common things that most cards shared ?) to have a base line to start from. I can see that card number is mostly between 12 and 19 digits. Which give us a base values for <code>CardNumberMaxLength</code> and <code>CardNumberMinLength</code>. Now, the Validation for each card can vary, but from the Wikipedia page it shows that most cards uses <code>Luhn algorithm</code> validation. This means, we can use it as a base validation process in our abstract class. In which, would make things much easier for us.</p>\n<p>We can now construct these into an abstract class something like this :</p>\n<pre><code>public abstract class PaymentCard\n{\n private static readonly Random _random = new Random(); \n \n public virtual int CardNumberMaxLength { get; } = 19;\n \n public virtual int CardNumberMinLength { get; } = 12;\n \n public virtual string Name { get; }\n \n public virtual string Number { get; set; }\n \n public virtual bool IsActive { get; } = true;\n \n private int[] InternalGenerateCardNumber(int length, string prefix = null)\n {\n var startIndex = 0; \n \n var cardNumbers = new int[length];\n\n if(!string.IsNullOrWhiteSpace(prefix))\n {\n startIndex += prefix.Length; \n \n for(var x = 0; x < prefix.Length; x++)\n {\n cardNumbers[x] = prefix[x] - '0';\n }\n }\n \n while(startIndex < length)\n {\n cardNumbers[startIndex] = _random.Next(0, 10);\n startIndex++;\n }\n\n return cardNumbers;\n }\n \n protected virtual string GenerateNewCardNumber(int length, string prefix = null)\n {\n \n string str = null; \n \n do \n {\n var cardNumbers = InternalGenerateCardNumber(length);\n str = string.Concat(cardNumbers); \n }\n while(!Validate(str));\n \n return str;\n }\n\n /// <summary>\n /// Validate Credit Card Number using Luhn algorithm\n /// </summary>\n /// <param name="cardNumber"></param>\n /// <returns></returns>\n public virtual bool Validate(string cardNumber)\n {\n if(!string.IsNullOrWhiteSpace(cardNumber) && cardNumber.Length >= CardNumberMinLength && cardNumber.Length <= CardNumberMaxLength)\n {\n var digits = cardNumber.ToCharArray().Select(x=> Convert.ToInt16(x)).ToArray();\n\n var sum = 0;\n\n for(int x = 0; x < digits.Length; x++)\n {\n var digit = digits[x];\n\n if(x % 2 != 0)\n {\n sum += digit;\n }\n else\n {\n var doubled = digit * 2;\n sum += doubled < 10 ? doubled : ( doubled / 10 ) + ( doubled % 10 );\n }\n }\n\n return sum % 10 == 0;\n }\n\n return false;\n } \n\n public abstract string GenerateNewCardNumber();\n}\n</code></pre>\n<p>Now, we can use this abstract to implement each card something like this :</p>\n<pre><code>public class VisaCard : PaymentCard\n{\n public override string Name => "Visa"; \n \n public override int CardNumberMaxLength => 16; \n \n public override int CardNumberMinLength => 16; \n \n public override string GenerateNewCardNumber() {\n return base.GenerateNewCardNumber(16);\n }\n \n}\n\npublic class MaestroCard : PaymentCard\n{\n public override string Name => "Maestro"; \n\n public override string GenerateNewCardNumber() {\n return base.GenerateNewCardNumber(16, "5893");\n }\n}\n</code></pre>\n<p>this way, you'll have a full control on each card type. for instance, if you need a custom validate for any card, you just override the <code>Validation</code> method and do your own custom validation. The rest of work should be easy to handle.</p>\n<p>usage example :</p>\n<pre><code>public string GenerateCardNumber(PaymentCard card) {\n return card.GenerateNewCardNumber(); \n} \n</code></pre>\n<p>now we can create it this way :</p>\n<pre><code>var visa = new VisaCard(); \nvar cardNumber = GenerateCardNumber(visa); \n// this would return the VisaCard.GenerateNewCardNumber() result.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T12:52:17.043",
"Id": "515160",
"Score": "0",
"body": "Thank you for writing the whole code. I am not sure how OOP solve the issue. Now how would you create a Visa card with 13 number? Would you create a new constructor? What about a card with _n_ different available length? Would you create _n_ constructor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T15:49:04.917",
"Id": "515168",
"Score": "0",
"body": "@aloisdg, yes you'll need to define a new type for each card type. the example above `VisaCard` shows how to have a fixed length (exactly 16 digits) while `MaestroCard` shows a length range (taken from the base class default values)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T18:12:41.063",
"Id": "515191",
"Score": "0",
"body": "Yes I saw but in your code everything is random. This is not what I am looking for. I want to force a bunch of input (range or not) while sharing the information with the function caller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T19:35:51.853",
"Id": "515197",
"Score": "0",
"body": "@aloisdg the random part is just an example, which you need to change it to suit your needs. for instance, if a card has a range, then adjust the max and min length, and override the generate method to your custom range part, and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:28:49.930",
"Id": "515203",
"Score": "0",
"body": "As a function caller, how to I know if I can create a card with 16, 18 or only 19 numbers or any of those valid value? I would like to define a guard (akin to the guard pattern) at parameter level. I can achieve something similar with enums but it is quite cumbersome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:43:16.103",
"Id": "515204",
"Score": "0",
"body": "@aloisdg you just add `PaymentCard` as parameter, and then, pass `VisaCard` or `MaestroCard` to the method. I have updated my answer with usage example. Hope this would give you a clear thoughts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:44:50.603",
"Id": "515205",
"Score": "0",
"body": "@aloisdg all validations should be inside the class itself e.g. `VisaCard` and not outside it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:50:52.830",
"Id": "515206",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/124567/discussion-between-aloisdg-and-isr5)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T12:36:57.743",
"Id": "261064",
"ParentId": "261056",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T08:39:31.047",
"Id": "261056",
"Score": "-1",
"Tags": [
"c#",
"f#"
],
"Title": "What would be this best way to show that my function can accept some specific numbers as input?"
}
|
261056
|
<p>I have been working on porting my PowerShell 7 scripts to Python 3.9.5 lately, re-implementing the same logic in a different programming language, keeping what makes it work and removing unnecessary parts, improving the code, and this is one of the scripts that has been re-implemented.</p>
<p>The code is simple, and I know this has been implemented countless times, but it does get the job done without using the builtin <code>datetime</code> module, and it accepts two strings representing dates in nine date formats and returns the difference between the two dates:</p>
<pre class="lang-Python prettyprint-override"><code>'yyyy-MM-dd'
'yyyy/MM/dd'
'MM/dd/yyyy'
'MMM dd, yyyy'
'dd MMM, yyyy'
'MMMM dd, yyyy'
'dd MMMM, yyyy'
'yyyy, MMM dd'
'yyyy, MMMM dd'
</code></pre>
<p>And it is completely working.</p>
<p>So here is the code:</p>
<pre class="lang-Python prettyprint-override"><code>import re
import sys
Months = (
{'Month':'January', 'Days':31},
{'Month':'February', 'Days':28},
{'Month':'March', 'Days':31},
{'Month':'April', 'Days':30},
{'Month':'May', 'Days':31},
{'Month':'June', 'Days':30},
{'Month':'July', 'Days':31},
{'Month':'August', 'Days':31},
{'Month':'September', 'Days':30},
{'Month':'October', 'Days':31},
{'Month':'November', 'Days':30},
{'Month':'December', 'Days':31}
)
Culture = (
{'Format':'yyyy-MM-dd', 'Regex':'^\d{4}\-0?([2-9]|1[0-2]?)\-(0?(3[01]|[12][0-9]|[1-9]))$'},
{'Format':'yyyy/MM/dd', 'Regex':'^\d{4}\/0?([2-9]|1[0-2]?)\/(0?(3[01]|[12][0-9]|[1-9]))$'},
{'Format':'MM/dd/yyyy', 'Regex':'^0?([2-9]|1[0-2]?)\/(0?(3[01]|[12][0-9]|[1-9]))\/\d{4}$'},
{'Format':'MMM dd, yyyy', 'Regex':'^[A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9])), \d{4}$'},
{'Format':'dd MMM, yyyy', 'Regex':'^(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3}, \d{4}$'},
{'Format':'MMMM dd, yyyy', 'Regex':'^[A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9])), \d{4}$'},
{'Format':'dd MMMM, yyyy', 'Regex':'^(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3,9}, \d{4}$'},
{'Format':'yyyy, MMM dd', 'Regex':'^\d{4}, [A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9]))$'},
{'Format':'yyyy, MMMM dd', 'Regex':'^\d{4}, [A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9]))$'}
)
def splitter(date, x, y):
date = date.replace(',','').split(x)
y = list(map(int, y.split(',')))
year = int(date[y[0]])
month = date[y[1]]
if not re.match('^\d+$', month):
for i in Months:
if re.match(f'{month}',i['Month']): month = Months.index(i) + 1
month = int(month)
day = int(date[y[2]])
return {'Year': year, 'Month': month, 'Day': day}
def parsedate(date):
for a in range(len(Culture)):
if re.match('%s' % Culture[a]['Regex'], date): i = a; break
if i == 0: return splitter(date, '-', '0,1,2')
elif i == 1: return splitter(date, '/', '0,1,2')
elif i == 2: return splitter(date, '/', '2,0,1')
elif i == 3: return splitter(date, ' ', '2,0,1')
elif i == 4: return splitter(date, ' ', '2,1,0')
elif i == 5: return splitter(date, ' ', '2,0,1')
elif i == 6: return splitter(date, ' ', '2,1,0')
elif i == 7: return splitter(date, ' ', '0,1,2')
elif i == 8: return splitter(date, ' ', '0,1,2')
def totaldays(date):
ye = date['Year']
y = ye
mon = date['Month']
d = date['Day']
if mon <= 2: y -= 1
leaps = y // 4 - y // 100 + y // 400
m = 0
for b in range(mon - 1): m += int(Months[b].get('Days'))
days = (ye - 1) * 365 + m + d + leaps
return days
def diffdate(start, end):
date1 = totaldays(parsedate(start))
date2 = totaldays(parsedate(end))
ddate = date2 - date1
print(ddate)
start = sys.argv[1]
end = sys.argv[2]
diffdate(start, end)
</code></pre>
<p>As usual, I wonder how it can be improved, there may be multiple areas that can be improved but now I mostly care about the switch replacement and how to get parameters from command line, the 8 elif statements do the job but it makes the code look awful, I have tried to use a dictionary but it throws date is undefined error, and I don't want to import sys just to get the arguments from command line, I don't know if there is an automatic variable just like PowerShell's <code>$Args</code>.</p>
<p>Please help me improve my code, you can share whatever you think on my code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-08T05:03:54.303",
"Id": "518742",
"Score": "0",
"body": "Have you seen https://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result or https://youtu.be/-5wpm-gesOY? While useful for learning, dates can be notoriously difficult to get right. Therefore for any type of \"serious\" application, it is strongly recommended to use the `datetime` libraries =)"
}
] |
[
{
"body": "<p>This is a good approach you have done if you have to skip <code>datetime</code> module.</p>\n<p>There are many more cultures that you have not added but that's different topic.</p>\n<p>First, I will answer your question related to command line argument. NO there is <a href=\"https://stackoverflow.com/questions/27368283/in-python-command-line-args-without-import\">no clean/good solution</a> for that.</p>\n<p>Second, I will only review the main issue, replacing <code>if-else</code> ladder with <code>switch</code>.</p>\n<blockquote>\n<p>You have already done the ground work for me. :)</p>\n</blockquote>\n<pre><code>Decider = [\n ('-', '0,1,2'), ('/', '0,1,2'), ('/', '2,0,1'),\n (' ', '2,0,1'), (' ', '2,1,0'), (' ', '2,0,1'),\n (' ', '2,1,0'), (' ', '0,1,2'), (' ', '0,1,2')\n]\n\n# use like\nsplitter(date, *Decider[i])\n</code></pre>\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T10:48:05.237",
"Id": "261062",
"ParentId": "261059",
"Score": "2"
}
},
{
"body": "<p>Modern Python has so many conveniences for creating simple data objects\n(namedtuple, dataclass, and the excellent <a href=\"https://www.attrs.org/en/stable/index.html\" rel=\"nofollow noreferrer\">attrs</a> library), that it's usually a\nmistake to structure your internal data using ordinary dicts, lists, or tuples.\nThese simple data objects not only clean up the code from a readability\nperspective (as shown in multiple places below) but also encourage you to focus\nyour attention where it should be: defining the meaningful data entities to\nfacilitate and support the algorithmic needs of the program. Organize the data\nthe right way, and the algorithms will usually flow naturally.</p>\n<p>Case in point: you don't need an 8-way switch; you need richer data. The\n<code>splitter()</code> arguments belong in the realm of data (<code>Culture</code> instances in the\ncode below), not algorithm.</p>\n<p>Another case in point: don't drive your algorithm with data that requires\nparsing. For example, if you think you need a tuple of indexes like <code>(2, 0, 1)</code>, don't store it in a comma-delimited string and complicate your algorithmic\ncode with the unpacking logic. Just store the indexes directly as a tuple of\nintegers. The core problem in software writing is reducing and managing\ncomplexity, and the greatest complexity is always algorithmic.\nInvesting more in creating "smarter" or "richer" data will help you keep the\nalgorithmic parts of the code easier to understand and maintain.</p>\n<p>Python has a built-in <code>sum()</code> function.</p>\n<p>When possible (which means almost always) iterate directly\nover a collection (ie, list, tuple) rather than over the indexes.\nIf you need the indexes too, use <code>enumerate()</code>.</p>\n<p>Abandon your style of trying to cram extra logic on each line:</p>\n<pre><code>if foo > 1233: x = 12; y = 34\n</code></pre>\n<p>I went through that phase for a brief time early in my Python journey. It\ndoesn't scale well and it's harder to maintain over the long term on a project.\nAgain, complexity is the biggest foe in software engineering: one way to\nreducing complexity slightly (and increase readability) is to favor shorter\nlines of code over longer ones. Within reason, taller/skinnier texts are easier\non readers than shorter/wider texts (the publishing industry has understood\nthis for decades), so if you are cramming more code into single lines, you are\neconomizing on the wrong thing (ie, saving lines while spending readability).</p>\n<p>Similarly, abandon your aversion to importing parts of the Python standard\nlibrary. It's fine to avoid those things in the name of learning. But that's\nthe only good reason I know of. So get command-line arguments from <code>sys.argv</code>\nguilt-free. It's the way to go!</p>\n<p>After the simplification from those changes are made, the <code>splitter()</code> function\nseems unnecessary. Instead, I would suggest a different helper function just to\nparse the month. And that logic doesn't require regex: you can use simpler\nthings like <code>isdigit()</code> and <code>startswith()</code>. Also, a <code>Month</code> should know its\nnumber. Again, use richer data to simplify algorithm.</p>\n<p>Other improvements for you to consider:</p>\n<ul>\n<li><p>If you invest more in your regular expressions so that they use named\ncaptures, you can drop the tedious details in <code>Culture.separator</code> and\n<code>Culture.indexes</code>. Instead, you can grab the year, month, and day directly from\nthe <code>re.Match</code> object, by name. Yet again, <strong>smart data, simple code</strong>.</p>\n</li>\n<li><p>When given invalid input, your code just blows up. Give some thought to\nwhether you want to invest in better error handling/reporting.</p>\n</li>\n<li><p>Dates are notoriously complicated. There are probably weird edge-case\nbugs in your code. Are you sure you don't want to use <code>datetime</code>?</p>\n</li>\n</ul>\n<pre class=\"lang-python prettyprint-override\"><code>\nimport re\nimport sys\nfrom collections import namedtuple\n\n# Simple data objects are handy as hell. Use more of them.\n\nMonth = namedtuple('Month', 'name number days')\nCulture = namedtuple('Culture', 'format separator indexes regex')\nDate = namedtuple('Date', 'year month day')\n\nMonths = (\n Month('January', 1, 31),\n Month('February', 2, 28),\n Month('March', 3, 31),\n Month('April', 4, 30),\n Month('May', 5, 31),\n Month('June', 6, 30),\n Month('July', 7, 31),\n Month('August', 8, 31),\n Month('September', 9, 30),\n Month('October', 10, 31),\n Month('November', 11, 30),\n Month('December', 12, 31),\n)\n\nCultures = (\n Culture('yyyy-MM-dd', '-', (0,1,2), '^\\d{4}\\-0?([2-9]|1[0-2]?)\\-(0?(3[01]|[12][0-9]|[1-9]))$'),\n Culture('yyyy/MM/dd', '/', (0,1,2), '^\\d{4}\\/0?([2-9]|1[0-2]?)\\/(0?(3[01]|[12][0-9]|[1-9]))$'),\n Culture('MM/dd/yyyy', '/', (2,0,1), '^0?([2-9]|1[0-2]?)\\/(0?(3[01]|[12][0-9]|[1-9]))\\/\\d{4}$'),\n Culture('MMM dd, yyyy', ' ', (2,0,1), '^[A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9])), \\d{4}$'),\n Culture('dd MMM, yyyy', ' ', (2,1,0), '^(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3}, \\d{4}$'),\n Culture('MMMM dd, yyyy', ' ', (2,0,1), '^[A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9])), \\d{4}$'),\n Culture('dd MMMM, yyyy', ' ', (2,1,0), '^(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3,9}, \\d{4}$'),\n Culture('yyyy, MMM dd', ' ', (0,1,2), '^\\d{4}, [A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9]))$'),\n Culture('yyyy, MMMM dd', ' ', (0,1,2), '^\\d{4}, [A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9]))$'),\n)\n\n# A purely stylistic point: organize modules the way you want to read them.\n# Most humans like to read things top to bottom.\n\ndef main(args):\n start, end = args\n ddate = diffdate(start, end)\n print(ddate)\n\ndef diffdate(start, end):\n d1 = totaldays(parsedate(start))\n d2 = totaldays(parsedate(end))\n return d2 - d1\n\ndef totaldays(date):\n y = date.year\n if date.month <= 2:\n y -= 1\n leaps = y // 4 - y // 100 + y // 400\n m = sum(Months[b].days for b in range(date.month - 1))\n days = (date.year - 1) * 365 + m + date.day + leaps\n return days\n\ndef parsedate(date):\n for c in Cultures:\n if re.match(c.regex, date):\n parts = date.replace(',', '').split(c.separator)\n return Date(\n int(parts[c.indexes[0]]),\n parsemonth(parts[c.indexes[1]]),\n int(parts[c.indexes[2]]),\n )\n # Raise an error if we get here.\n\ndef parsemonth(month):\n if month.isdigit():\n return int(month)\n else:\n for m in Months:\n if m.name.lower().startswith(month.lower()):\n return m.number\n # Raise an error if we get here.\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:08:27.900",
"Id": "261080",
"ParentId": "261059",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "261080",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T09:41:33.833",
"Id": "261059",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"datetime"
],
"Title": "Python code to find difference between two dates"
}
|
261059
|
<p>I have a list of path I want to filter out. I want to keep only paths matching a specific pattern and remove all paths matching another specific pattern.</p>
<p>To achieve this I pattern matched on each pattern. Here is the code:</p>
<pre><code>let stringToSpan (s: string) =
System.ReadOnlySpan<char>(s.ToCharArray())
let matchWildcard pattern text =
System.IO.Enumeration.FileSystemName.MatchesSimpleExpression(stringToSpan pattern, stringToSpan text)
let filterByPattern (includePattern: string Option) (excludePattern: string Option) (paths: string seq) :string seq =
paths
|> Seq.filter
(fun path ->
let shouldKeep =
match includePattern with
| Some pattern -> matchWildcard pattern path
| None -> true
if not shouldKeep then
false
else
match excludePattern with
| Some pattern -> matchWildcard pattern path |> not
| None -> true)
</code></pre>
<p>You can try this snippet with:</p>
<pre><code>seq {"test"; "foo/bar"; "foo/toto"}
|> filterByPattern (Some "foo/*") (Some "*toto*")
|> printfn "%A"
// output: foo/bar
</code></pre>
<p>If it matters, this snippet is used inside a dotnet tool to clone multiple git repositories. You can find this tool on <a href="https://github.com/aloisdg/Kamino/blob/main/kamino/Program.fs" rel="nofollow noreferrer">GitHub</a>.</p>
<p>I think that we could improve this snippet a bit. Can we?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T13:46:42.173",
"Id": "515161",
"Score": "0",
"body": "Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T22:37:33.683",
"Id": "516110",
"Score": "1",
"body": "Don't call `.ToCharArray()` in your `stringToSpan` function. You're forcing it to allocate a character array on the heap when it's not needed. If there's nothing built into F# to support this, you should call `System.MemoryExtensions.AsSpan(s)` in this function instead."
}
] |
[
{
"body": "<p>Lets focus on <code>filterByPattern</code>.</p>\n<p>A Predicate is a function returning a boolean (<code>'T -> bool</code>). Since the predicate host most of the logic, lets start by spliting the Predicate from the filter to work on it.</p>\n<pre><code>let patternPredicate (includePattern: string Option) (excludePattern: string Option) (path: string) :bool =\n let shouldKeep =\n match includePattern with\n | Some pattern -> matchWildcard pattern path\n | None -> true\n\n if not shouldKeep then\n false\n else\n match excludePattern with\n | Some pattern -> matchWildcard pattern path |> not\n | None -> true\n\nlet filterByPattern (includePattern: string Option) (excludePattern: string Option) (paths: string seq) :string seq =\n Seq.filter (patternPredicate includePattern excludePattern) paths\n</code></pre>\n<p>Alright now we will stop modifying filterByPattern and focus on patternPredicate. Since we are only dealing with boolean maybe there is a refactoring to do here. Lets switch from pattern matching to basic boolean logic.</p>\n<pre><code>let patternPredicate (includePattern: string Option) (excludePattern: string Option) (path: string) :bool =\n let shouldKeep = includePattern.IsNone || (includePattern.IsSome && matchWildcard includePattern.Value path)\n if not shouldKeep then\n false\n else\n excludePattern.IsNone || (excludePattern.IsSome && (not (matchWildcard excludePattern.Value path))))\n</code></pre>\n<p><code>shouldKeep</code> can be seen as <code>(not a) or (a and b)</code> where <em>a</em> is the option state and <em>b</em> the result of the matching.</p>\n<p>Since we don't have to check twice the value of a, <code>(not a) or (a and b)</code> can be simplify to <code>(not a) or b</code>. If you want to verify this logic, you can use a Truth Table or rely on a tool like <a href=\"https://www.dcode.fr/boolean-expressions-calculator\" rel=\"nofollow noreferrer\">decode.fr's Boolean Expressions Calculator</a></p>\n<p><a href=\"https://i.stack.imgur.com/AwbXu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AwbXu.png\" alt=\"docde output\" /></a></p>\n<p>Lets apply this to our function!</p>\n<pre><code>let patternPredicate (includePattern: string Option) (excludePattern: string Option) (path: string) :bool =\n let shouldKeep = includePattern.IsNone || (matchWildcard includePattern.Value path)\n if not shouldKeep then\n false\n else\n excludePattern.IsNone || (not (matchWildcard excludePattern.Value path))\n</code></pre>\n<p>Thats better! Now lets get rid of this <code>if/else</code> clause and some parenthesis also.</p>\n<pre><code>let patternPredicate (includePattern: string Option) (excludePattern: string Option) (path: string) :bool =\n (includePattern.IsNone || matchWildcard includePattern.Value path) &&\n (excludePattern.IsNone || not (matchWildcard excludePattern.Value path))\n</code></pre>\n<p>So the complete snippet is now:</p>\n<pre><code>let stringToSpan (s: string) =\n System.ReadOnlySpan<char>(s.ToCharArray())\n\nlet matchWildcard pattern text =\n System.IO.Enumeration.FileSystemName.MatchesSimpleExpression(stringToSpan pattern, stringToSpan text)\n\nlet patternPredicate (includePattern: string Option) (excludePattern: string Option) path =\n (includePattern.IsNone || matchWildcard includePattern.Value path) &&\n (excludePattern.IsNone || not (matchWildcard excludePattern.Value path)) \n\nlet filterByPattern (includePattern: string Option) (excludePattern: string Option) (paths: string seq) :string seq =\n Seq.filter (patternPredicate includePattern excludePattern) paths\n\nseq {"test"; "foo/bar"; "foo/toto"}\n|> filterByPattern (Some "foo/*") (Some "*toto*")\n|> printfn "%A"\n\n// output: foo/bar\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T10:04:01.167",
"Id": "261061",
"ParentId": "261060",
"Score": "2"
}
},
{
"body": "<p>I would avoid using Option <code>.IsNone</code> and <code>.Value</code>, mainly because <code>.Value</code> will throw an exception if you made a mistake and called it at the wrong time. Almost all F# code will avoid that property and use pattern matching instead or some other function.</p>\n<p>Here's another way to write the <code>patternPredicate</code> function, which I renamed to <code>includePath</code> do describe what it actually does:</p>\n<pre><code>let includePath (includePattern: string option) (excludePattern: string option) path =\n let isIncluded =\n match includePattern with\n | Some includePattern -> matchWildcard includePattern path\n | None -> true\n let isExcluded =\n lazy\n match excludePattern with\n | Some excludePattern -> matchWildcard excludePattern path\n | None -> false\n isIncluded && not isExcluded.Value\n</code></pre>\n<p>My approach here was to first build up the values <code>isIncluded</code> and <code>isExcluded</code> so that we can write <code>isIncluded && not isExcluded.Value</code>. This breaks the problem down into understandable and explicit parts.</p>\n<p>Note the use of a lazy value for <code>isExcluded</code>. This means that it won't be evaluated unless <code>isIncluded</code> is true, so we don't need to call <code>matchWildcard</code> unnecessarily.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T14:02:52.557",
"Id": "515163",
"Score": "0",
"body": "I really like the use of `lazy` here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T13:37:33.717",
"Id": "261066",
"ParentId": "261060",
"Score": "2"
}
},
{
"body": "<p>This could be simplified by using straightforward composition:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let matches (x: string) (y: string) =\n System.IO.Enumeration.FileSystemName.MatchesSimpleExpression\n ( System.MemoryExtensions.AsSpan x\n , System.MemoryExtensions.AsSpan y\n )\n\nseq {"test"; "foo/bar"; "foo/toto"}\n|> Seq.filter (matches "foo/*")\n|> Seq.filter (matches "*toto*" >> not)\n|> printfn "%A"\n</code></pre>\n<p>And that's it! Just filter it twice.</p>\n<p>This way you don't need to figure out what each of the arguments to <code>filterByPattern</code> mean. If you really want to make a function out of it:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let includeThenExclude include' exclude =\n Seq.filter (matches include') >> Seq.filter (matches exclude >> not)\n</code></pre>\n<p>If you only sometimes need to include or exclude, instead of <code>Option</code>s:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let including x = matches x |> Seq.filter\nlet excluding x = matches x >> not |> Seq.filter\n\nlet includingFoo =\n seq {"test"; "foo/bar"; "foo/toto"}\n |> including "foo/*"\n\nlet includingFooExcludingToto =\n seq {"test"; "foo/bar"; "foo/toto"}\n |> including "foo/*"\n |> excluding "*toto*"\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T21:13:24.070",
"Id": "264294",
"ParentId": "261060",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T10:04:01.167",
"Id": "261060",
"Score": "2",
"Tags": [
"f#",
"pattern-matching"
],
"Title": "How to refactor the boolean logic of this F# function?"
}
|
261060
|
<p>If we apply outward curving, inward curving, and no curving at all, <strong>individually</strong> to each of the 4 corners of the rectangle, we get next 81 variations:</p>
<p><a href="https://i.stack.imgur.com/62Clz.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/62Clz.gif" alt="Rounded rectangles" /></a></p>
<p>The code implements next BASIC command:</p>
<pre><code>BOX X1%, Y1%, X2%, Y2% RADII Radii%
</code></pre>
<p><code>BOX</code> draws the rectangle between the opposite corners at (X1%, Y1%) and (X2%, Y2%).
The first byte of the 32-bit value in <em>Radii%</em> defines the first quadrant corner, the second byte of <em>Radii%</em> defines the second quadrant corner, and so on. These bytes, independent of each other, express a percentage of the half of the smallest dimension of the rectangle. A positive value rounds outwards (convex), a negative value rounds inwards (concave), a zero doesn't round at all.<br />
The arcs are drawn via an 8-point-symmetrical Bresenham code. This means that for each 90° arc, points are drawn simultaneously moving towards the bisector.</p>
<p>If the intent were to draw the whole rounded rectangle using some dotted linestyle, then it would be very desirable to draw all of these arcs entirely in an anti-clockwise fashion only. How can this be done, using either the Bresenham algorithm or a similar one ?<br />
Also, can the present code be optimized any further (codesize and/or execution speed) ?</p>
<pre class="lang-none prettyprint-override"><code>; Rounded Box (c) 2021 Sep Roland
; Assemble with FASM
ORG 256
mov ax, 0013h ; BIOS.SetVideoMode 320x200
int 10h
mov [Color], 4 ; Red
push dword 64643232h ; Q4=100% Q3=100% Q2=50% Q1=50%
push 89 189 10 130
call Box ; 'BOX 130,10,189,89 RADII Bytes(50,50,100,100)'
mov [Color], 14 ; Yellow
push dword 00006464h ; Q4=0% Q3=0% Q2=100% Q1=100%
push 189 189 110 130
call Box ; 'BOX 130,110,189,189 RADII Bytes(100,100,0,0)'
mov [Color], 1 ; Blue
push dword 9C00329Ch ; Q4=-100% Q3=0% Q2=50% Q1=-100%
push 129 149 70 10
call Box ; 'BOX 10,70,149,129 RADII Bytes(-100,50,0,-100)'
mov [Color], 2 ; Green
push dword 009C9C32h ; Q4=0% Q3=-100% Q2=-100% Q1=50%
push 129 309 70 170
call Box ; 'BOX 170,70,309,129 RADII Bytes(50,-100,-100,0)'
mov ah, 00h ; BIOS.WaitKey
int 16h ; -> AX
mov ax, 0003h ; BIOS.SetVideoMode 80x25
int 10h
mov ax, 4C00h ; DOS.Terminate
int 21h
; -----------------------------
; Plots single pixel on the 256-color screen
; IN (ax,bx,es) OUT ()
PT: push ax di ; AX=Y BX=X
mov di, ax
shl di, 6
xchg al, ah
add di, ax
mov al, [Color]
mov [es:di+bx], al
pop di ax
ret
; -----------------------------
; Draws rectangle with optional, individually outward or inward, curving corners
; IN () OUT ()
Box: push es
pushad
mov bp, sp ; Args start at BP+36
mov ax, 0A000h
mov es, ax
mov ecx, [bp+36+8] ; Radii
; SI = Min(Width,Height)-1
mov si, [bp+36+6] ; Y2
sub si, [bp+36+2] ; Y1 -> SI is DeltaY
mov ax, [bp+36+4] ; X2
sub ax, [bp+36+0] ; X1 -> AX is DeltaX
cmp si, ax
jbe .Q1
mov si, ax
; Q4 Q3 Q2 Q1
; | | | | <-- Convex --> <-- Concave -> |
; | " | " | " | Xc Yc Arc Xc Yc Arc R % |
; | | | | ---- ---- ---- ---- ---- ---- ---- ---- |
; ^ ^
; SP <-------------------- 4 * 8 words ---------------------> BP
.Q1: push cx
call .Radius ; -> AX ECX (BX DX)
push ax
mov dx, [bp+36+2] ; Y1
mov bx, [bp+36+4] ; X2
push .Q3Arc dx bx
add dx, ax
sub bx, ax
push .Q1Arc dx bx
.Q2: push cx
call .Radius ; -> AX ECX (BX DX)
push ax
mov dx, [bp+36+2] ; Y1
mov bx, [bp+36+0] ; X1
push .Q4Arc dx bx
add dx, ax
add bx, ax
push .Q2Arc dx bx
.Q3: push cx
call .Radius ; -> AX ECX (BX DX)
push ax
mov dx, [bp+36+6] ; Y2
mov bx, [bp+36+0] ; X1
push .Q1Arc dx bx
sub dx, ax
add bx, ax
push .Q3Arc dx bx
.Q4: push cx
call .Radius ; -> AX ECX (BX DX)
push ax
mov dx, [bp+36+6] ; Y2
mov bx, [bp+36+4] ; X2
push .Q2Arc dx bx
sub dx, ax
sub bx, ax
push .Q4Arc dx bx
mov si, sp ; DS=SS
add si, 4*16
.Arcs: sub si, 16
mov ax, [si+12] ; Current radius
test ax, ax ; No curving if radius=0
jz .f
push si ; (1)
xor bx, bx ; Start at (0,R)
cmp [si+14], bl ; BL=0
jg .a ; Convex
add si, 6 ; Concave
.a: mov di, 3 ; Decision variable D=3-2*R
sub di, ax
sub di, ax
jmp .c ; Skip all tops (belong to sides)
.b: push ax bx ; (2)
call word [si+4] ; Plot arc
pop bx ax ; (2)
.c: mov cx, bx
test di, di ; If D<0 then D=D+6+4*X
jns .d ; If D>=0 then D=D+10+4*(X-Y)
add di, 6 ; Y=Y-1
jmp .e
.d: sub cx, ax
add di, 10
dec ax ; Y=Y-1
.e: shl cx, 2
add di, cx
inc bx ; X=X+1
cmp bx, ax
jbe .b ; While X<=Y
pop si ; (1)
.f: cmp si, sp
jne .Arcs
.North: mov ax, [si+32+8] ; Y1, Going from East to West
mov bx, [si+48] ; Q1Xc
@@: call PT
dec bx
cmp bx, [si+32] ; Q2Xc
jge @b
.West: mov bx, [si+16+6] ; X1, going from North to South
mov ax, [si+32+2] ; Q2Yc
@@: call PT
inc ax
cmp ax, [si+16+2] ; Q3Yc
jle @b
.South: mov ax, [si+8] ; Y2, going from West to East
mov bx, [si+16] ; Q3Xc
@@: call PT
inc bx
cmp bx, [si] ; Q4Xc
jle @b
.East: mov bx, [si+6] ; X2, going from South to North
mov ax, [si+2] ; Q4Yc
@@: call PT
dec ax
cmp ax, [si+48+2] ; Q1Yc
jge @b
mov sp, bp
popad
pop es
ret 12
; - - - - - - - - - - - - - - -
; IN (ecx,si) OUT (ax,ecx) MOD (bx,dx)
.Radius:movsx ax, cl ; Inputted percentage [-128,+127]
; AX = Min(Abs(Percentage),100)
test ax, ax
jns @f
neg ax
@@: cmp ax, 100
jna @f
mov ax, 100
; AX = (SI/2)*AX/100
@@: mul si ; AX is percentage [0,100]
mov bx, 200
div bx ; -> AX is radius 0+
; Prepare for the next quadrant's percentage
shr ecx, 8
ret
; - - - - - - - - - - - - - - -
.Q1Arc: neg ax
jmp .PT___
; - - - - - - - - - - - - - - -
.Q2Arc: neg bx
neg ax
jmp .PT__
; - - - - - - - - - - - - - - -
.Q3Arc: neg bx
.PT___: call .PT
neg bx
neg ax
jmp .PT_
; - - - - - - - - - - - - - - -
.Q4Arc: xchg ax, bx
.PT__: call .PT
.PT_: xchg ax, bx
; --- --- --- --- ---
.PT: add bx, [si] ; X plus current Xc
add ax, [si+2] ; Y plus current Yc
call PT
sub bx, [si] ; Restore X
sub ax, [si+2] ; Restore Y
ret
; ------------------------------
Color rb 1
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T14:20:09.167",
"Id": "261067",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"assembly",
"graphics",
"x86"
],
"Title": "81 variations of the rounded rectangle"
}
|
261067
|
<p>I have recently come across a use case where I need to lump many maps into a single container. These maps can have different combinations of key/value types, but they all differ from one another.</p>
<p>For a certain set of key types <code>Key1, Key2, ...</code> and value types <code>Val1, Val2,...</code> the obvious implementation is</p>
<pre><code>class LumpedMap {
std::map<Key1, Val1> map1;
std::map<Key1, Val2> map2;
std::map<Key2, Val1> map3;
std::map<Key2, Val2> map4;
std::map<Key3, Val2> map4;
...
}
</code></pre>
<p>but this doesn't scale well for many maps, as if we want to maintain encapsulation we tend to create a vast number of accessors</p>
<pre><code>Val1& at(const Key1&) {...}
Val2& at(const Key1&) {...}
Val1& at(const Key2&) {...}
...
void insert(const Key1&, const Val1&) {...}
void insert(const Key1&, const Val2&) {...}
void insert(const Key2&, const Val1&) {...}
...
</code></pre>
<p>etc...</p>
<p>My goal is to have a class template that allows me to instantiate a particular type with a list of key/value types</p>
<pre><code>using MyMap = LumpedMap<std::pair<Key1, Val1>,
std::pair<Key1, Val2>,
std::pair<Key2, Val1>,
std::pair<Key2, Val3>>;
</code></pre>
<p>and that can generate automatically all standard methods for any type</p>
<pre><code>MyMap fm;
//...lookup
fm.at<Key2, Val3>();
//...insertion
fm.insert_or_assign(k2, v3);
//...etc
</code></pre>
<p>I have come up with the following variadic template implementation that uses fold expressions (for which reason, I will call it <code>FoldedMap</code> ;)):</p>
<pre><code>template<class K, class V>
class MapBase {
public:
using MapType = std::map<K, V>;
using MapPtr = std::shared_ptr<MapType>;
protected:
MapPtr _map{std::make_shared<MapType>()};
MapBase() = default;
MapBase(MapPtr map) : _map{std::move(map)} {
}
V& at(K& key) {
return _map->at(key);
}
auto insertOrAssign(const K& key, const V& val) {
return _map->insert_or_assign(key, val);
}
const auto& range() {
return *_map;
}
void merge(MapBase<K, V>& source) {
_map->merge(*source._map);
}
};
template<class ...Pair>
class FoldedMap : public MapBase<typename Pair::first_type, typename Pair::second_type>... {
public:
FoldedMap() = default;
FoldedMap(typename MapBase<typename Pair::first_type, typename Pair::second_type>::MapPtr& ...map)
: MapBase<typename Pair::first_type, typename Pair::second_type>(map)... {
}
template<class K, class V>
V& at(K& key) {
return MapBase<K, V>::at(key);
}
template<class K, class V>
auto insertOrAssign(const K& key, const V& val) {
return MapBase<K, V>::insertOrAssign(key, val);
}
template<class K, class V>
auto range() {
return MapBase<K, V>::range();
}
template<class ...P>
void merge(FoldedMap<P...>& other) {
(MapBase<typename P::first_type, typename P::second_type>::merge(other), ...);
}
template<class ...P>
FoldedMap<P...> extract() {
FoldedMap<P...> fm(MapBase<typename P::first_type, typename P::second_type>::_map...);
return fm;
}
template<class K, class V>
void _merge(std::map<K, V>& other) {
MapBase<K, V>::_merge(other);
}
};
</code></pre>
<p>A few remarks, mostly arbitrary choices I made that can be revised or fine tuned:</p>
<ul>
<li><p>The method <code>extract()</code> takes a slice of the object as a new FoldedMap with a subset of key/value types.</p>
</li>
<li><p>The choice of using shared pointers is motivated by the intention of supporting shallow-copy semantics in <code>extract()</code> (which maybe could be renamed to emphasize this, and is out of line with the semantics of the same method in std::map).</p>
</li>
</ul>
<p>This is an example test code, showing some usage.</p>
<pre><code>int main(int argc, const char * argv[]) {
Key1 k1 = "k1";
Key2 k2 = std::make_pair(2, "two");
Val1 val1 = 3.14;
Val2 val2 = "val2";
FoldedMap<std::pair<Key1, Val1>,
std::pair<Key1, Val2>,
std::pair<Key2, Val1>> fm;
FoldedMap<std::pair<Key2, Val1>> fm2;
// Insert elements
fm.insertOrAssign(k1, val2);
fm.insertOrAssign(k2, val1);
fm2.insertOrAssign<Key2, Val1>({3, "three"}, 6.28);
std::cout << fm.at<Key1, Val2>(k1) << "\n";
// Merge operation - follows std::map<T,T>::merge() semantics
fm.merge(fm2);
// Extract operation - leaves the original object unchanged
// by sharing data with target object
auto fm3 = fm.extract<std::pair<Key1, Val1>,std::pair<Key2, Val1>>();
for (auto& [k,v]: fm.range<Key1, Val1>())
std::cout << "Key1 - Val1 range: " << k << v << "\n";
for (auto& [k,v]: fm.range<Key1, Val2>())
std::cout << "Key1 - Val2 range: " << k << " " << v << " " << "\n";
for (auto& [k,v]: fm.range<Key2, Val1>())
std::cout << "Key2 - Val1 range: " << k.first << " " << k.second << " " << v << "\n";
for (auto& [k,v]: fm3.range<Key1, Val1>())
std::cout << "from view " << k << v << "\n";
for (auto& [k,v]: fm3.range<Key2, Val1>())
std::cout << "from view " << k.first << " " << k.second << " " << v << "\n";
std::cout <<
std::any_of(fm.range<Key2, Val1>().begin(),
fm.range<Key2, Val1>().end(),
[] (const auto& k2) { return k2.first.first == 3;}
)
<< "\n";
return 0;
}
</code></pre>
<p>Any feedback on the above implementation is welcome. Has someone seen something similar in any library?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:14:24.643",
"Id": "515172",
"Score": "0",
"body": "Can you add some test code that gives examples of how this is used? And include some details on why you're using (shared) pointers to maps internally, rather than just storing the maps directly in the class? (If I'm reading this right, the lack of rule-of-five here can cause some surprises, as code like `fm2 = fm1;` to copy the map followed by a change to `fm2` will result in unexpected changes to `fm1` as well.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:26:38.867",
"Id": "515173",
"Score": "0",
"body": "@1201ProgramAlarm Yes, will add some more explanation, you are right. The shared pointer, in particular, is used to implement the 'extract()' method with shallow-copy semantics. I need to make a few edits..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T14:56:29.460",
"Id": "515614",
"Score": "0",
"body": "Take a look at Boost's [MultiIndex](https://www.boost.org/doc/libs/1_76_0/libs/multi_index/doc/index.html), at least for inspiration."
}
] |
[
{
"body": "<p>This looks quite good already, and it's an interesting problem to solve. However, I'll first try to give some arguments why you perhaps shouldn't, and then mention some things that could be improved.</p>\n<h1>Encapsulation</h1>\n<blockquote>\n<p>but this doesn't scale well for many maps, as if we want to maintain encapsulation we tend to create a vast number of accessors</p>\n</blockquote>\n<p>I guess it depends on what you call "encapsulation", but I think that having multiple member variables grouped inside a <code>class</code> is also perfectly fine encapsulation. You don't need a vast number of accessors, since instead of writing:</p>\n<pre><code>fm.at<Key1, Val1>();\n</code></pre>\n<p>You can write:</p>\n<pre><code>fm.map1.at();\n</code></pre>\n<p>You have to provide information of which map you want to access anyway, so either it's via a member name, or via a template parameter. The only time I see the latter as being more desirable is if you have some other templated code that only knows about the pair <em>type</em> it needs to access, not the map <em>name</em>.</p>\n<h1>Consider using <code>std::tuple</code></h1>\n<p>Your <code>FoldedMap</code> basically looks like a <a href=\"https://en.cppreference.com/w/cpp/utility/tuple\" rel=\"nofollow noreferrer\"><code>std::tuple</code></a> over <code>std::maps</code>. Instead of:</p>\n<pre><code>FoldedMap<std::pair<Key1, Val1>, std::pair<Key2, Val2>> fm;\n</code></pre>\n<p>You could write:</p>\n<pre><code>std::tuple<std::map<Key1, Val1>, std::map<Key2, Val2>> fm;\n</code></pre>\n<p>The only drawback of this is that it doesn't have the convenience member function <code>insertOrAssign()</code> that can deduce the desired element type from its arguments. However, you could write an out-of-class function to do that:</p>\n<pre><code>template<typename FoldedMap, typename Key, typename Val>\ninsertOrAssign(FoldedMap &fm, const Key &key, const Val &val) {\n fm.get<std::map<Key, Val>>().insert_or_assign(key, val);\n}\n</code></pre>\n<p>The same goes for the other member functions.</p>\n<h1>Avoid starting identifiers with underscores</h1>\n<p>The standard has some <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">rules regarding identifiers starting with underscores</a>. While your use is safe, I would just avoid starting names with underscores completely, as it's too easy to make a mistake, as not everyone knows these rules by heart. I suggest you either use <code>m_</code> as a prefix for member variables, or use a single underscore as a suffix.</p>\n<h1>Use the standard library's naming conventions</h1>\n<p>You are trying to make the <code>FoldedMap</code> container look and feel the same as STL containers. However, while <code>at()</code> and <code>merge()</code> are spelled the same as the corresponding member functions of <code>std::map</code>, you used <code>insertOrAssign()</code> instead of <code>insert_or_assign()</code>. I recommend you use exactly the same naming conventions as the STL, so as to avoid surpises and make it easier to use it as a drop-in replacement for STL types.</p>\n<p>Also note that <code>extract()</code> also exists for <code>std::map</code>, but does something different from your <code>extract()</code>. Although I think that your <code>extract()</code> makes sense, consider that someone might want to extract a node from one of the <code>MapBase</code>s, and later <code>insert()</code> it again. You could overload <code>FoldedMap::extract()</code> to handle both these things, but it might be better if these things have clearly distinct names. Perhaps you could rename your current <code>extract()</code> to <code>get()</code>, as it does something similar to <a href=\"https://en.cppreference.com/w/cpp/utility/tuple/get\" rel=\"nofollow noreferrer\"><code>std::get()</code></a>.</p>\n<h1>Match the standard library's function signatures exactly</h1>\n<p>If you look at the documentation of <a href=\"https://en.cppreference.com/w/cpp/container/map/insert_or_assign\" rel=\"nofollow noreferrer\"><code>std::map<>::insert_or_assign()</code></a>, you'll notice that it takes the value not as a <code>const V&</code>, but as a <code>M&&</code>. This avoids unnecessary casting (for example, when passing a C string literal when <code>V</code> is <code>std::string</code>), and also allows efficient moving from temporaries. So your <code>MapBase::insert_or_assign()</code> should look like:</p>\n<pre><code>template<typename M>\nauto insert_or_assign(const K& key, M&& val) {\n return m_map->insert_or_assign(key, std::forward<M>(val));\n}\n</code></pre>\n<p>For <code>FoldedMap::insert_or_assign()</code> you can't do this of course, since it depends on the value having type <code>V</code> to correctly deduce which underlying <code>MapBase</code> to use. However, you should still take the <code>val</code> as a <a href=\"https://en.cppreference.com/w/cpp/language/reference#Forwarding_references\" rel=\"nofollow noreferrer\">forwarding reference</a>.</p>\n<p>Your <code>at()</code> is taking <code>key</code> as a non-<code>const</code> reference, this should be <code>const</code>. Also, <a href=\"https://en.cppreference.com/w/cpp/container/map/at\" rel=\"nofollow noreferrer\"><code>std::map<>::at()</code></a> has a <code>const</code> function overload, which you should probably also implement.</p>\n<h1>About <code>_merge()</code></h1>\n<p>Your <code>FoldedMap</code> has a member function <code>_merge()</code>, which doesn't work (there's no corresponding <code>_merge()</code> in <code>MapBase</code>), but also it should just be renamed to <code>merge()</code>; function overloading should work just fine.</p>\n<h1>Pass <code>Pair</code>s where possible</h1>\n<p>Instead of making <code>MapBase</code> be a template of two types, make it a template of just <code>Pair</code>:</p>\n<pre><code>template<typename Pair>\nclass MapBase {\n using K = typename Pair::first_type;\n using V = typename Pair::second_type;\n ...\n void merge(MapBase& source) {...}\n};\n</code></pre>\n<p>This simpifies most of <code>FoldedMap</code>, although some member functions do need to keep the <code>template<class K, class V></code> for type deduction to work, in which case you need to use <code>MapBase<std::pair<K, v>></code> to access the underlying map:</p>\n<pre><code>template<class ...Pair>\nclass FoldedMap : public MapBase<Pair>... {\n ...\n FoldedMap(typename MapBase<Pair>::MapPtr& ...map): MapBase<Pair>(map)... {}\n\n template<class K, class V>\n V& at(const K& key) {\n return MapBase<std::pair<K, V>>::at(key);\n }\n ...\n template<class ...P>\n void merge(FoldedMap<P...>& other) {\n (MapBase<P>::merge(other), ...);\n }\n ...\n};\n</code></pre>\n<h1>Use of <code>std::shared_ptr</code></h1>\n<p>I would avoid using <code>std::shared_ptr</code>, and instead store the underlying <code>std::map</code>s by value. Value semantics are always much easier to reason with. For example, if I would write:</p>\n<pre><code>FoldedMap<std::pair<std::string, std::string>> fm1;\nauto fm2 = fm1; // copy?\nfm1.insert_or_assign(std::string{"Hello,"}, std::string{"world!"});\nstd::cout << fm2.at<std::string, std::string>("Hello,") << "\\n";\n</code></pre>\n<p>If <code>fm1</code> were a regular <code>std::map<std::string, std::string></code>, then I expect the last line to throw an exception, because the copy was made when <code>fm1</code> was still empty. However, your class basically has reference semantics, and lets this code print "<code>world!</code>", which for most C++ programmers would be unexpected.</p>\n<p>If someone really needs shallow copy semantics, they could just create a <code>std::shared_ptr<FoldedMap<...>></code> themselves. If you want to make a shallow copy that restricts the number of underlying <code>MapBase</code>s that are accessible, perhaps you could create some kind of <code>FoldedMapView</code> type? Both of these solutions would make the shallow copy semantics explicit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T18:26:46.497",
"Id": "515349",
"Score": "0",
"body": "Many thanks for the detailed review, very appreciated. The shared_ptr use is really a half-baked idea I should have omitted, and not essential to make the main point. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T10:43:21.560",
"Id": "261098",
"ParentId": "261069",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261098",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T15:19:31.093",
"Id": "261069",
"Score": "1",
"Tags": [
"c++",
"c++17",
"collections",
"template-meta-programming"
],
"Title": "A multi key/value type \"folded\" map class template"
}
|
261069
|
<p>I have written a function that takes as input a list of 5 numbers, then the program's goal is to return the largest drop in the list. It is important to understand that [5, 3, ...] is a decrease of 2 and that [5, 20, .....] is a decrease of 0. In short, a decrease can only be from left to right and the largest decrease can for example also be the decrease from the 1st number to the 4th number, they do not necessarily have to be next to each other.</p>
<pre><code>def biggest_drop(temperature):
difference = 0
new_temperature = temperature.copy()
a = 0
for i in temperature:
del new_temperature[0]
for j in new_temperature:
if i <= j:
False
else:
a = i - j
if a > difference:
difference = a
return difference
</code></pre>
<p>The good news is the code works, the bad news is that because of the double for loop there is already a Big-O notation of O(n<sup>2</sup>). However, the program must have a Big-O notation of O(n<sup>1</sup>) and I don't know how to fix this and where the speed of the code is also high enough. For example, here I have made a fairly sloppy alternative, but it is too slow:</p>
<pre><code>def biggest_drop(temperature):
difference = 0
a = 0
b = temperature[1]
c = temperature[2]
d = temperature[3]
e = temperature[4]
for i in temperature:
if temperature[0] <= temperature[1] <= temperature[2] <= temperature[3] <= temperature[4]:
return 0
elif i > b:
a = i - b
if a > difference:
difference = a
elif i > c:
a = i - c
if a > difference:
difference = a
elif i > d:
a = i - d
if a > difference:
difference = a
elif i > e:
a = i - e
if a > difference:
difference = a
return difference
</code></pre>
<p>Do you have a better idea how my code complies with the big-O notation of O(n<sup>1</sup>) and is also fast enough for larger n, in other words lists with more than 5 integers?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:40:17.500",
"Id": "515174",
"Score": "2",
"body": "Welcome to Code Review! – The site standard is for the title to simply state the task accomplished by the code, not your concerns about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:40:52.883",
"Id": "515175",
"Score": "0",
"body": "Btw, what is n if the input is always a list of 5 numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:44:28.780",
"Id": "515176",
"Score": "0",
"body": "apologies, I only now understand from the command that the one larger n creates a larger list of integers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:47:32.617",
"Id": "515177",
"Score": "0",
"body": "Which a quick Google search I found this https://math.stackexchange.com/a/1172157/42969 and this https://stackoverflow.com/q/15019851/1187415, which might be what you are looking for."
}
] |
[
{
"body": "<p>This can be solved in a single pass, e.g., O(n).</p>\n<p>For each temperature, subtract it from the highest temperature seen so far to get the drop. Keep track of the largest drop. Also update the highest temperature.</p>\n<pre><code>def biggest_drop(temperatures):\n highest = temperatures[0]\n largest_drop = 0\n\n for temperature in temperatures:\n drop = highest - temperature\n largest_drop = max(largest_drop, drop)\n\n highest = max(temperature, highest)\n\n return largest_drop\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T21:01:27.540",
"Id": "261085",
"ParentId": "261070",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "261085",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T15:31:21.323",
"Id": "261070",
"Score": "3",
"Tags": [
"python",
"algorithm",
"comparative-review",
"complexity"
],
"Title": "Find the largest decrease in a sequence of numbers"
}
|
261070
|
<p>I work with a charity that does a number of jobs, more than 100, less than 1000 a year. Jobs are identified with a year, and an up to 3 digit serial number, so <code>2021#123</code> for instance.</p>
<p>I'm writing a Python report program to pull jobs out of our database, and I'd like be be able to specify ranges of jobs rather like a print dialogue can specify ranges of pages, so a dash separated range <code>2021#123-45</code>, or a comma separated list <code>2021#003,5,07,89,131</code> as well. I want to be able to parse all of these representations out of text strings.</p>
<p>I'm only interested in the syntax at the moment, the semantics of whether a range is valid is handled later. Even though I have very limited experience of regexes, I felt a one-liner would beat a whole bunch of python <code>if</code>s.</p>
<p>The valid strings I want to match are therefore of the form</p>
<ul>
<li><code>20y#n</code> OR</li>
<li><code>20y#n,q,p,r</code> OR</li>
<li><code>20y#n-m</code></li>
</ul>
<p>where y is any two digits, and m,n,p,q,r are 1 to 3 digits.</p>
<p>This is a question about the regex. The only python consideration is the use of <code>r'…'</code> for a raw string.</p>
<p>I struggled and failed to write a regex that captures any of these forms by trying to match the <code>year#ddd</code>, and then OR the different endings. I think I fell foul of the single job form not having an ending at all. I've therefore ended up with this rather agricultural effort, that works, but looks ugly. I didn't put the comments in just for this post; I put them in knowing that if I needed to change things next month, I'd need them.</p>
<pre><code>job_patt = r'((?:20\d\d#\d{1,3}-\d{1,3})|(?:20\d\d#\d{1,3}(?:,\d{1,3})+)|(?:20\d\d#\d{1,3}))'
# cap group ( )
# non-caps (?: ) (?: ) (?: )
# OR the non-caps, in this L->R order | |
# get year# 20\d\d# 20\d\d# 20\d\d#
# get 1 to 3 digits \d{1,3} \d{1,3} \d{1,3}
# get one instance of range -\d{1,3}
# get one or more repeats of list ',ddd' (?:,\d{1,3})+
</code></pre>
<p>What could be done to shorten or tidy up this regex?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T09:51:43.213",
"Id": "515589",
"Score": "0",
"body": "I changed the title so that it's a bit more specific. Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T09:56:36.787",
"Id": "515590",
"Score": "0",
"body": "@TobySpeight Yes, I'd changed it just a minute before you. Maybe yours matches my exact problem closely, but it could be more general without losing the flavour of the regex problem - matching several similar strings - as it refers to years and jobs, which aren't relevant to the issue. I'll try to revert it. The fundamental problem that remains unaddressed is that one of the options is null, which I need to think about more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T15:36:46.803",
"Id": "515619",
"Score": "0",
"body": "Yes, it was supposed to be specific. Did you intend to revert all my other fixes, too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T16:10:48.857",
"Id": "515623",
"Score": "0",
"body": "@TobySpeight No, didn't spot those, fixed. I prefer the title as more general."
}
] |
[
{
"body": "<p>This isn't so much a Python question as it is a RegEx question. The Python tag is almost irrelevant.</p>\n<h1>'+' -vs- '*'</h1>\n<p>You regex includes two alternates:</p>\n<ul>\n<li><code>(?:20\\d\\d#\\d{1,3}(?:,\\d{1,3})+)</code></li>\n<li><code>(?:20\\d\\d#\\d{1,3})</code></li>\n</ul>\n<p>The difference in these expressions is the first one include one or more repeats of <code>,\\d{1,3}</code>, where as the second does not include any repeats of that ...</p>\n<p>... in other words, you have <code>20\\d\\d#\\d{1,3}</code> followed by <strong>0 or more repeats</strong> of <code>,\\d{1,3}</code>.</p>\n<p>So we can replace the <code>+</code> modifier with the <code>*</code> modifier, and the pair of alternates becomes simply</p>\n<p><code>(?:20\\d\\d#\\d{1,3}(?:,\\d{1,3})*)</code></p>\n<h1>Common prefix</h1>\n<p>All three (or rather, both now that the last two have been combined into one) regex's start with <code>20\\d\\d#</code>. You can factor this out of both patterns.</p>\n<p><code>20\\d\\d#</code> <code>(?:</code> <code>(?:</code> <code>\\d{1,3}-\\d{1,3}</code> <code>|</code> <code>\\d{1,3}(?:,\\d{1,3})*</code> <code>)</code> <code>)</code></p>\n<h1>Capture Groups</h1>\n<p>There is no point creating a capture group for the entire regex expression. The entire match is always captured, as group 0.</p>\n<h1>Reworked Regex & Example</h1>\n<p>The regex can be rewritten as:</p>\n<p><code>r"20\\d\\d#(?:(?:\\d{1,3}-\\d{1,3}|\\d{1,3}(?:,\\d{1,3})*))"</code></p>\n<p>which is shorter, but is still quite unreadable. It is better for future programmers at the charity (as well as for yourself) to document the regex using the <code>re.VERBOSE</code> option. I find it clearer than comments below the regular expression that try to document the parts of the regular expression through vertically lined up notes.</p>\n<p><strong>Note</strong>: Since comments follow the octothorpe (<code>#</code>) character in <code>re.VERBOSE</code> mode, we need to escape it (<code>\\#</code>) to indicate that it is actually a character we want matched, and not the start of a comment.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\nJOB_PATTERN = re.compile(r"""\n 20\\d\\d # A 4-digit year\n \\# # followed by a hash mark\n (?: # followed by either ...\n (?:\\d{1,3}-\\d{1,3}) # a range of serial #'s\n | # or\n (?:\\d{1,3}(?:,\\d{1,3})*) # a list of serial #'s\n )""", re.VERBOSE)\n\n\ntest_cases = ["junk2021#123-45bar",\n "baz2021#003,5,07,89,131foo"]\n\nfor test_case in test_cases:\n m = JOB_PATTERN.search(test_case)\n if m:\n print("Found:", m[0])\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Found: 2021#123-45\nFound: 2021#003,5,07,89,131\n</code></pre>\n<h1><em>Update</em></h1>\n<p>Based on the OP's response to <a href=\"https://codereview.stackexchange.com/users/98633/roottwo\">RootTwo</a>'s comment, named capturing groups are actually desired. Here is an updated example with RootTwo's enhancement:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\nJOB_PATTERN = re.compile(\n r"""(?P<year> # Capturedas "year" ...\n 20\\d\\d # a 4-digit year\n )\n \\# # followed by a hash mark\n (?: # followed by either ...\n (?P<range> # captured as "range" ...\n \\d{1,3}-\\d{1,3} # a range of serial #'s\n )\n | # or\n (?P<list> # captured as "list" ...\n \\d{1,3} # a serial number\n (?:,\\d{1,3})* # or list of comma-seperated serial #'s\n )\n )\n """, re.VERBOSE)\n\ntest_cases = ["junk2021#123-45bar",\n "baz2021#003,5,07,89,131foo"]\n\nfor test_case in test_cases:\n m = JOB_PATTERN.search(test_case)\n if m:\n if m.lastgroup == "range":\n start, end = m['range'].split('-')\n print("Year:", m['year'], " from", start, "to", end)\n else:\n serial_numbers = m['list'].split(',')\n print("Year:", m['year'], " serial #':", serial_numbers)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Year: 2021 from 123 to 45\nYear: 2021 serial #': ['003', '5', '07', '89', '131']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T18:31:53.873",
"Id": "515192",
"Score": "2",
"body": "I came up with an identical pattern, except I used named capture groups so that one can use [`Match.lastgroup()`](https://docs.python.org/3.9/library/re.html#re.Match.lastgroup) to determine if it matched the range or list of jobs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T19:51:34.983",
"Id": "515198",
"Score": "0",
"body": "@RootTwo That would be a useful improvement. The OP was simply capturing the entire expression, and **explicitly** using non-capturing groups for the individual details, so I didn't change that in my regex reworkings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T05:38:14.293",
"Id": "515219",
"Score": "0",
"body": "@RootTwo could I trouble you to write an answer with named capture groups please. Just because I explicitly used non-capturing groups doesn't mean it's the best thing to do, and I don't like the what appears to be excessive (?: syntax anyway. Maybe it wouldn't shorten it, verbose certain doesn't, but it does make it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T06:55:59.837",
"Id": "515221",
"Score": "1",
"body": "@Neil_UK, it is literally the same as AJNeufeld's answer, except in the year part I used `(?P<year>20\\d\\d)`. in the range part I used `(?P<range>` instead of `(?:`, and in the list part I used `(?<list>` instead of the first `(?:`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T16:28:06.460",
"Id": "515248",
"Score": "0",
"body": "Note: @RootTwo obviously meant `(?P<list>`, not `(?<list>`. I've added an updated example with RootTwo's capture group and demonstration of the the `Match.lastgroup` property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T10:02:48.280",
"Id": "515591",
"Score": "0",
"body": "I was dubious about named groups as they don't appear to offer any advantage in this context. I can test for whether '-' in match as easily as I can test for lastgroup=='range'. The difference appears to be in readability, depending on what one is used to reading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T16:37:55.300",
"Id": "515625",
"Score": "0",
"body": "The readability benefits of named capture groups span the boundary between the regex and the Python program that uses it. I salvaged your question by framing it as a regex-only code review. The \"dubious\" value of named groups comes from a lack of understanding on how you want to use the results. You'd need to post your entire Python program as a follow-up question for review if you want a review of the benefits of capture groups -vs- named capture groups -vs- simply matching the entire text and splitting it again in Python."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T18:13:54.823",
"Id": "261073",
"ParentId": "261072",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "261073",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T16:01:42.407",
"Id": "261072",
"Score": "4",
"Tags": [
"python-3.x",
"regex"
],
"Title": "Regex to match several slightly different strings"
}
|
261072
|
<p>I've been creating a math engine in C++. I have decided now is a good time to ask for feedback from the community. Right now the main "good" things it has is complex numbers, calculus and a fraction class. I am planning to add set theory sometime in the future, although I don't know how useful it would be to programmers. Since my project is for brushing up my C++ skills, but I'm making it as if I was making it as a general-purpose library.</p>
<p>For <code>nsqrt</code> and <code>sqrt</code>; the parameter <code>precision</code> represent the number of steps of a Newton-Raphson approximation to be performed</p>
<p>Is there anything I should improve on, change, add, etc.?</p>
<pre><code>#include <iostream>
using namespace std;
namespace math{
const double mini = double (numeric_limits<double>::min());
const double e = 2.718281828459045;
const double pi = 3.141592653589793238462643383;
int def_prec = 16;
}
template <class t = double>
t exp(t base, int exponent){
if(exponent<0){
return 1/exp(base,-exponent);
} else if(exponent>0){
double output = 1;
for(int i=1;i<=exponent;i++){output *= base;}
return output;
} else {return 1;}
}
double nsqrt(double x, int precision = math::def_prec){
double sum = 1;
for (int i=1;i<=precision;i++){
sum -= ((sum*sum)-x)/(2*sum);
}
return sum;
}
double esqrt(double num, double precision = math::def_prec){
double h = num/precision;
double y = 1;
for (double x=1;x!=num;x+=h){
y += h*(1/(2*y));
}
return y;
}
double sqrt(double num, int precision = math::def_prec){
return nsqrt(num,precision);
}
double root(double num, int root, int precision = math::def_prec){
double sum = 1;
for (int i=1;i<=precision;i++){
sum -= ((exp(sum,root))-num)/(root*exp(sum,root-1));
}
return sum;
}
class complex{
private:
double r,i;
public:
complex(double r_in,double i_in): r(r_in), i(i_in) {};
double get_re() {return r;}
double get_im(){return i;}
double magnitude(int precision = math::def_prec){ return sqrt((r*r)+(i*i),precision);}
complex operator + (complex a){
r += a.get_re();
i += a.get_im();
return (*this);
}
complex operator + (double a){r += a;return (*this);}
complex operator - (complex a){
r -= a.get_re();
i -= a.get_im();
return (*this);
}
complex operator - (double a){r -= a;return (*this);}
complex operator * (complex a){
r = (r*a.get_re())-(i*a.get_im());
i = (r*a.get_im())+(i*a.get_re());
return (*this);
}
complex operator * (double a){r *=a;i *= a;return (*this);}
complex operator / (complex a){
r = (r/a.get_re())-(i/a.get_im());
i = (r/a.get_im())+(i/a.get_re());
return (*this);
}
complex operator / (double a){r /=a;i /= a;return (*this);}
void operator = (double a[2]){r=a[0];i=a[1];}
void operator = (complex a){r=a.get_re();i=a.get_im();}
bool operator == (complex a){return (r==a.get_re() && i==a.get_im());}
bool operator == (double a[2]){return (r==a[0] && i==a[1]);}
bool operator != (complex a){return (r!=a.get_re() || i!=a.get_im());}
bool operator != (double a[2]){return (r!=a[0] || i!=a[1]);}
void operator += (complex a){
r += a.get_re();
i += a.get_im();
}
bool operator > (complex a){return (r==a.get_re())? (i>a.get_im()) : (r>a.get_re());}
bool operator < (complex a){return (r==a.get_re())? (i<a.get_im()) : (r<a.get_re());}
bool operator <= (complex a){return (r==a.get_re())? (i<=a.get_im()) : (r<=a.get_re());}
bool operator >= (complex a){return (r==a.get_re())? (i>=a.get_im()) : (r>=a.get_re());}
void operator += (double a){r += a;}
void operator -= (complex a){
r -= a.get_re();
i -= a.get_im();
}
void operator -= (double a){r -= a;}
void operator *= (complex a){
r = (r*a.get_re())-(i*a.get_im());
i = (r*a.get_im())+(i*a.get_re());
}
void operator *= (double a){r *= a;i *= a;}
void operator /= (complex a){
r = (r/a.get_re())-(i/a.get_im());
i = (r/a.get_im())+(i/a.get_re());
}
void operator /= (double a){r /= a;i /= a;}
void operator ++ (){r++;}
void operator -- (){r--;}
ostream& operator<<(ostream& os)
{
os << r << "+" << i << "i";
return os;
}
void operator = (int a){r=a;}
};
complex exp(complex base, int exponent){
if(exponent<0){
complex one(1,0);
return one/exp(base,-exponent);
} else if(exponent>0){
complex output(1,0);
for(int i=1;i<=exponent;i++){output *= base;}
return output;
} else {return base/base;}
}
template <class t = int>
t gcd(t X, t Y) {
t pre = 0;
if (X%Y == 0) {return (X>Y)? Y : X;}
pre = X%Y;
X = Y;
Y = pre;
while (X%Y != 0) {
pre = X%Y;
X = Y;
Y = pre;
}
return pre;
}
int round(double x){return (x-int(x)>0.5)? int(x)+1 : int(x);}
class fraction{
private:
int n,d;
public:
fraction(int n_in,int d_in): n(n_in),d(d_in){};
void simplify(){n/=gcd(n,d);d/=gcd(n,d);}
double get_double(){return n/d;}
int get_num(){return n;}
int get_den(){return d;}
fraction operator + (fraction a){
n = (n*a.get_den())+(a.get_num()*d);
d *= a.get_den();
simplify();
return (*this);
}
fraction operator + (int a){n += a*d;return (*this);}
fraction operator - (fraction a){
n = (n*a.get_den())-(a.get_num()*d);
d *= a.get_den();
simplify();
return (*this);
}
fraction operator - (int a){n -= a*d;return (*this);}
fraction operator * (fraction a){
n *= a.get_num();
d *= a.get_den();
simplify();
return (*this);
}
fraction operator * (int a){n *= a;return (*this);}
fraction operator / (fraction a){
n /= a.get_num();
d /= a.get_den();
simplify();
return (*this);
}
fraction operator / (int a){n /= a;return (*this);}
void operator += (fraction a){
n = (n*a.get_den())+(a.get_num()*d);
d *= a.get_den();
simplify();
}
void operator += (int a){n += a*d;}
void operator -= (fraction a){
n = (n*a.get_den())-(a.get_num()*d);
d *= a.get_den();
simplify();
}
void operator -= (int a){n -= a*d;}
void operator *= (fraction a){
n *= a.get_num();
d *= a.get_den();
simplify();
}
void operator *= (int a){n*=a;}
void operator /= (fraction a){
n /= a.get_num();
d /= a.get_den();
simplify();
}
void operator /= (int a){n /= a;}
void operator = (fraction a){n = a.get_num();d=a.get_den();}
void operator = (int a){n=a;d=1;}
bool operator < (fraction a){return (n*a.get_den()<a.get_num()*d);}
bool operator > (fraction a){return (n*a.get_den()>a.get_num()*d);}
bool operator >= (fraction a){return (n*a.get_den()>=a.get_num()*d);}
bool operator <= (fraction a){return (n*a.get_den()<=a.get_num()*d);}
bool operator == (fraction a){return (n*a.get_den()==a.get_num()*d);}
bool operator != (fraction a){return (n*a.get_den()!=a.get_num()*d);}
bool operator < (int a){return (n<a*d);}
bool operator > (int a){return (n>a*d);}
bool operator >= (int a){return (n>=a*d);}
bool operator <= (int a){return (n<=a*d);}
bool operator == (int a){return (n==a*d);}
bool operator != (int a){return (n!=a*d);}
operator double () {return n/d;}
};
fraction tofrac(double x, int precision = 1000000000){
long gcd_ = gcd(round(x-int(x) * precision), precision);
fraction output(round(x-int(x)*precision)/gcd_,precision/gcd_);
return output;
}
template <class t = double>
t limit(double (*f)(t),t to) {
return (f(to+math::mini)+f(to-math::mini))/2;
}
template <class t = double>
t derivative(double (*f)(t),t x){
return ((f(x+math::mini)-f(x))/math::mini+(f(x-math::mini)-f(x))/(-math::mini))/2;
}
template <class t = double>
t sigma(double (*f)(t),int from, int to){
t out = 0;
for (int n=from;n<=to;n++){out += f(n);}
return out;
}
template <class t = double>
t pi(double (*f)(t),int from, int to){
t out = 1;
for (int n=from;n<=to;n++){out *= f(n);}
return out;
}
double factorial1(int x) {
double out = 1;
for(int n=x;n>0;n--){out*=n;}
return out;
}
template <class t = double>
t sin(t x, int precision = math::def_prec){
t output = 0;
for(int n=0;n<=precision;n++){
output += exp(-1,n)*(exp(x,(2*n)+1)/factorial1((2*n)+1));
}
return output;
}
template <class t = double>
t cos(t x, int precision = math::def_prec){
t output = 0;
for(int n=0;n<=precision;n++){
output += exp(-1,n)*(exp(x,2*n)/factorial1(2*n));
}
return output;
}
template <class t = double>
t tan(t x, int precision = math::def_prec){return sin(x,precision)/cos(x,precision);}
template <class t = double>
t ln(t x, int precision = math::def_prec){
t output = 0;
for(int n=1;n<=precision;n++){
output += (exp(x-2,n)*exp(-1,n-1))/n;
}
return output;
}
complex ln(complex x, int precision = math::def_prec){
complex output(0,0);
for(int n=1;n<=precision;n++){
output += (exp(x-1,n)*exp(-1,n-1))/n;
}
return output;
}
template <class t = double>
t log(t base, t x, int precision = math::def_prec){return ln(x,precision)/ln(base,precision);}
template <class t = double>
t derivative_fast(t (*f)(t),t x){return (f(x+1)-f(x-1))/2;}
double pi(int precision = math::def_prec){
double output = 0;
for(int i=0;i<=precision+(precision%2);i++){
output += exp(-1.0,i)/((2*i)+1);
}
return output*4;
}
//this pi algorithm isn't my work
double spigotpi(long digits){
long LEN = (digits / 4 + 1) * 14; //nec. array length
long array[LEN]; //array of 4-digit-decimals
long b; //nominator prev. base
long c = LEN; //index
long d; //accumulator and carry
long e = 0; //save previous 4 digits
long f = 10000; //new base, 4 decimal digits
long g; //denom previous base
long h = 0; //init switch
for (; (b = c -= 14) > 0;) { //outer loop: 4 digits per loop
for (; --b > 0;) { //inner loop: radix conv
d *= b; //acc *= nom prev base
if (h == 0)
d += 2000 * f; //first outer loop
else
d += array[b] * f; //non-first outer loop
g = b + b - 1; //denom prev base
array[b] = d % g;
d /= g; //save carry
}
h = (("%d"), e + d / f);//print prev 4 digits
std::cout << h;
d = e = d % f; //save currently 4 digits
//assure a small enough d
}
if (getchar())
{
return 0;
}
return 0;
}
double pi2(long precision){
double output = 1;
for (long k = precision;k>0;k--){
output *= 1.0+(k/((2.0*k)+1.0));
cout << output << endl;
}
return output;
}
double e(int precision = math::def_prec){
double output = 0;
for(int i=0;i<=precision;i++){
output += 1/factorial1(i);
}
return output;
}
double abs(complex x, int precision){return x.magnitude(precision);}
template <class t = double>
double abs(t x){return (x<0)? -x : x;}
complex sqrt(complex x, int precision = math::def_prec){
if (x.get_im()!=0){
complex output((1/sqrt(2,precision))*sqrt(x.magnitude()+x.get_re(),precision),((x.get_im()/abs(x.get_im()))/sqrt(2,precision))*sqrt(x.magnitude()-x.get_re(),precision));
return output;
} else {
complex output(sqrt(x.get_re()),0);
return output;
}
}
template <class t = double>
t quadratic(t a,t b, t c,t& otherroot, int precision = math::def_prec){
otherroot = (-b+sqrt((b*b)-4*a*c,precision))/(2*a);
return (-b-sqrt((b*b)-4*a*c,precision))/(2*a);
}
complex e_to_xi(double x, int precision = math::def_prec){
complex output(cos(x,precision),sin(x,precision));
return output;
}
template <class t>
t e_to_x(t x, int precision = math::def_prec){
t output = 0;
for(int i=0;i<=precision;i++){
output += exp(x,i)/factorial1(i);
}
return output;
}
complex e_to_x(complex x, int precision = math::def_prec){return e_to_xi(x.get_im(),precision)*e_to_x(x.get_re(),precision);}
complex exp(complex base, complex exponent, int precision = math::def_prec){return e_to_x(ln(base)*exponent);}
template <class t = double>
t exp(t base, double exponent, int precision = math::def_prec){
fraction asfrac(0,0);
asfrac = tofrac(exponent);
return exp(root(base,asfrac.get_den(),precision),asfrac.get_num());
}
template <class t = double>
t zeta(t s, int precision = math::def_prec){
t output(0,0);
for(int n=1.0;n<=precision;n++){output += 1/exp(n,s);}
return output;
}
template <class t = double>
t eta(t s, int precision = math::def_prec){
t output = 0;
for(int n=1;n<=precision;n++){output += exp(-1,(n-1)%2)/exp(n,s);}
return output;
}
template <class c=double>
c rsum(double (*f)(c), int n,c x[n],c t[n-1]){
c output = 0;
for(int i=0;i<=n-1;i++){
output += f(t[i])*(x[i+1]-x[i]);
}
return output;
}
template <class t=double>
t inf(t a, t b){return (a<b)? a:b;}
template <class t=double>
t sup(t a, t b){return (a>b)? a:b;}
template <class c=double>
c ldsum(double (*f)(c), int n,c x[n]){
c output = 0;
for(int i=0;i<=n-1;i++){
output += f(inf(x[i],x[i+1]))*(x[i+1]-x[i]);
}
return output;
}
template <class c=double>
c udsum(double (*f)(c), int n,c x[n]){
c output = 0;
for(int i=0;i<=n-1;i++){
output += f(sup(x[i],x[i+1]))*(x[i+1]-x[i]);
}
return output;
}
template <class c=double>
c rint(c a, c b, c (*f)(c), int precision=math::def_prec){
c partition[precision];
for(int i=0;i<=precision;i++){
partition[i] = a+(((b-a)/precision)*(i+1));
}
return rsum(f, precision, partition, partition); //use the lower bounds as tags
}
template <class c=double>
c udint(c a, c b, c (*f)(c), int precision = math::def_prec){
c P[precision];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T12:27:12.650",
"Id": "515232",
"Score": "1",
"body": "A comment, because it is really out of scope here. But you might want to look into things like [cln](https://www.ginac.de/CLN/), [ginac](https://www.ginac.de/), [singular](https://www.singular.uni-kl.de/), or [axiom](http://axiom-developer.org/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T22:28:20.147",
"Id": "515358",
"Score": "0",
"body": "Please post improvements to the code as answers, not as comments."
}
] |
[
{
"body": "<h1><code>using namespace std</code></h1>\n<p>Given that you're using <code>template</code> and declare your <code>class</code>, you're working in a header-only library. However, you should <em><strong>never</strong></em> use <code>using namespace</code> in header. Not only <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice?noredirect=1&lq=1\">is it bad practice</a>, but in this case you might conflict with <code>std::complex</code>.</p>\n<h1>Surprising <code>operator</code> semantics</h1>\n<p>Also, almost all operators don't follow the usual guidelines and are therefore either misleading or even plain wrong. Let's have a look at <code>operator-()</code>:</p>\n<pre><code> complex operator - (complex a){\n r -= a.get_re();\n i -= a.get_im();\n return (*this);\n}\n</code></pre>\n<p>Let's stop. This operator changes the value of the current item. That's completely unexpected. If I have</p>\n<pre><code>complex a = foo();\ncomplex b = bar();\ncomplex a_cp = a;\ncomplex b_cp = b;\ncomplex c = a - b;\n</code></pre>\n<p>then I expect <code>a == a_cp</code> and <code>b == b_cp</code>. However, this isn't true. This also prevents us from using <code>operator-()</code> on <code>cons</code>tant values.</p>\n<h1>Code duplication</h1>\n<p>Next, we see a lot of duplication. Let's stay at that operator and look at its compound assignment variant:</p>\n<pre><code> complex operator - (double a){r -= a;return (*this);}\n\n void operator -= (complex a){\n r -= a.get_re();\n i -= a.get_im();\n }\n void operator -= (double a){r -= a;}\n</code></pre>\n<p>We can immediately see that there is duplication between <code>-</code> and <code>-=</code>. It's almost the same code. Usually all compound assignment operations return <code>T&</code> instead of <code>void</code> or <code>T</code>, so let's fix that first:</p>\n<pre><code> complex& operator -= (complex a){\n r -= a.get_re();\n i -= a.get_im();\n return *this;\n }\n</code></pre>\n<h1>Scott Meyers: prefer non-member, non-friend functions</h1>\n<p>Now <code>operator-</code> can be rewritten using <code>operator-=</code>, which is also an item in Scott Meyers' book:</p>\n<pre><code>complex operator-(const complex &a, const complex &b) {\n complex tmp = a;\n tmp -= b;\n return tmp;\n}\n</code></pre>\n<p>Note that the operator above is free-standing. It's not a member function. This allows us to use it with types that can be converted into <code>complex</code>.</p>\n<h1>Provide conversion constructors</h1>\n<p>The code above is missing a <code>double</code> or even <code>double[2]</code> variant. However, that's not a problem if we have a fitting constructor at hand, e.g.</p>\n<pre><code>class complex {\n...\npublic:\n complex(double r) : r(r), i(0) {}\n complex(double c[2]) : r(c[0]), i(c[1]) {}\n\n complex(const complex&) = default;\n complex(complex&&) = default;\n complex& operator=(const complex&) = default;\n complex& operator=(complex&&) = default;\n}\n</code></pre>\n<p>While we're at it, we should also add the usual copy and move constructors resp. assignments.</p>\n<h1>Use <code>const&</code> where possible</h1>\n<p>Almost all functions in <code>complex</code> copy their argument. That's not necessary for them.</p>\n<h1>Use <code>const</code> for functions that may not change the class internals</h1>\n<p>The <code>get_re()</code> and <code>get_im()</code> functions don't change the <code>complex</code> among others, so mark them as <code>const</code>:</p>\n<pre><code>class complex {\n...\n double get_re() const {\n return r;\n }\n double get_im() const {\n return i;\n }\n...\n</code></pre>\n<h1>Use a code formatter</h1>\n<p>The code formatting and style changes all too much. Stick to a <em>readable</em> style and enforce it, either manually (which takes time) or with a tool like <code>clang-format</code>. Your IDE/editor might have a built-in feature.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T23:39:34.147",
"Id": "515210",
"Score": "2",
"body": "Thank you. This means a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T04:11:31.857",
"Id": "515217",
"Score": "8",
"body": "@NYcan You're welcome. I hope that this answer doesn't seem too harsh. There's a lot of great stuff in your implementation, but I believe you need to read a recent C++ book with best practices to make your code shine. Don't worry, though, we all went through that stage in our C++ careers :)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T12:12:43.327",
"Id": "515231",
"Score": "2",
"body": "While const& is usually preferred, with types this small const& is often slower, but in any case this should all get inlined and thus make no difference in the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T15:47:44.947",
"Id": "515245",
"Score": "0",
"body": "Would Bjarne Stroustrup's Programming Principles and Practice Using C++ (second edition) count? It was published in 2014."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T16:59:54.443",
"Id": "515251",
"Score": "0",
"body": "When I tried to provide conversion constructors for my fraction class, it says that it is ambiguous when I assign one fraction to another."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:06:53.120",
"Id": "515323",
"Score": "0",
"body": "Re \"prefer non-member non friend...\" is that out of date, or does it depend on the operator and its usage? Current advice is to use \"hidden friends\" for better compile speed and reduced overloading ambiguity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:09:05.330",
"Id": "515324",
"Score": "1",
"body": "@NYcan anything written before 2011 is obsolete, as C++11 is a significant update. I don't know if that book covers up-to-date C++ or not. The publication date suggests it is new enough, but 2nd edition is a rather low number, and completely reworking the order of presentation and all the examples does not sound like a revision of an existing book."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:58:27.183",
"Id": "261084",
"ParentId": "261078",
"Score": "26"
}
},
{
"body": "<p>In addition to the other answer,</p>\n<ol>\n<li>Put all your code inside a namespace. Why are only constants inside a <code>math</code> namespace? Also, <code>math</code> might be too common a name to use as namespace.</li>\n</ol>\n<p>A good idea would something like this:</p>\n<pre><code>namespace my_math_library\n{\n namespace constants\n {\n // put constants here\n }\n\n // rest of the stuff here\n} \n</code></pre>\n<hr />\n<ol start=\"2\">\n<li>You can declare all constants, functions and classes as <code>constexpr</code>.</li>\n</ol>\n<hr />\n<ol start=\"3\">\n<li><code>template<class t = double></code>. You don't need to actually provide a default template argument, since the template argument will just get deduced from the function argument.</li>\n</ol>\n<hr />\n<ol start=\"4\">\n<li>Why are some of your functions templated and others are not? (<code>nsqrt</code>, <code>esqrt</code>)</li>\n</ol>\n<hr />\n<ol start=\"5\">\n<li><code>for(double x = 1; x != num; x += h)</code>. Comparing two floating point numbers using <code>==</code> or <code>!=</code> is a recipe for disaster. Compare it against a tolerance (epsilon) e.g. <code>std::numeric_limits<double>::epsilon()</code></li>\n</ol>\n<hr />\n<ol start=\"6\">\n<li><code>x-int(x) * precision</code>. Be careful of operator precedence. <code>int(x) * precision</code> is evaluated first. For any value of x >= ~4, you are invoking undefined behavior since the value doesn't fit inside an <code>int</code>.</li>\n</ol>\n<hr />\n<ol start=\"7\">\n<li><code>t derivate(double (*f)(t), t x)</code>. Instead of passing a function pointer, pass a templated argument:</li>\n</ol>\n<pre><code>template<typename Func, typename T>\nT derivate(Func&& func, T x)\n</code></pre>\n<p>That way, you can also pass in lambdas and functors.</p>\n<hr />\n<ol start=\"8\">\n<li><code>rsum(double (*f)(c), int n,c x[n],c t[n-1]</code> is not valid. Also, use consistent notation when using templates.</li>\n</ol>\n<hr />\n<ol start=\"9\">\n<li></li>\n</ol>\n<pre><code>template <class c=double>\nc udint(c a, c b, c (*f)(c), int precision = math::def_prec){\n c P[precision];\n}\n</code></pre>\n<p>Variable length arrays are illegal in C++. Also, function isn't doing anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T01:48:59.337",
"Id": "515213",
"Score": "0",
"body": "When I try to make my complex exp function a constexpr it gives me the error \"Constexpr function's return type 'math_lib::complex' is not a literal type\" (math_lib is the new namespace I made.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T02:18:49.840",
"Id": "515214",
"Score": "0",
"body": "Your `complex` constructor should be marked `constexpr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T02:51:06.903",
"Id": "515215",
"Score": "0",
"body": "When I change it to constexpr class complex, it says that a class cannot be marked as constexpr."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T03:22:30.760",
"Id": "515216",
"Score": "0",
"body": "Mark the constructor as `constexpr`. Like this: https://godbolt.org/z/hrG9WPGxP"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T19:46:40.357",
"Id": "515264",
"Score": "0",
"body": "oh, whoops, I didn't finish the udint function yet. That's why it isn't doing anything."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T01:17:27.443",
"Id": "261086",
"ParentId": "261078",
"Score": "7"
}
},
{
"body": "<p><em>Note: This isn't comprehensive, I'm adding to the previous reviews as well.</em></p>\n<h1>Numeric Constants</h1>\n<p>Take a look at <a href=\"https://en.cppreference.com/w/cpp/numeric/constants\" rel=\"noreferrer\">numeric constants</a> in C++. There's no need for you to define them yourself.</p>\n<h1>Dangerous Iteration</h1>\n<pre><code> double h = num/precision;\n double y = 1;\n for (double x=1;x!=num;x+=h){\n y += h*(1/(2*y));\n }\n</code></pre>\n<p>It's not guaranteed that <code>x</code> will ever reach the value of <code>num</code>. Here, you could use the iteration style <code>for (double x=1; x<=num; x+=h)</code>. However, this seems like the nth approximation to the sqare root, so why not use an integer counter? After all, you're not using <code>x</code> at all inside the loop!</p>\n<h1>Unusual Iteration</h1>\n<pre><code> for (int i=1;i<=precision;i++){\n</code></pre>\n<p>The idiomatic way to write that is to start with zero and then to compare for equality:</p>\n<pre><code> for (int i=0; i!=precision; ++i) {\n</code></pre>\n<h1>Unit Tests</h1>\n<p>This isn't strictly part of reviewing your code. Still, for libraries like this, using Test-Driven Development (TDD) is probably the standard. I believe that some of the faults in your code would have become obvious.</p>\n<h1>Documentation</h1>\n<p>What are <code>nsqrt()</code>, <code>esqrt()</code> and <code>sqrt()</code>? Why add another <code>sqrt()</code> overload at all? Why not use the one provided by the standard library? These three are just examples of things you need to put into a suitable context so that others can use your code.</p>\n<p>In addition, putting down a few of your thoughts will make the code easier to maintain for your "now +6months" future self. Also, sometimes you will find that an initial thought is actually a stupid idea when you explain it to someone else. The same thing happens if you write it down as comment (which should be for someone else as well).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T07:00:28.753",
"Id": "261091",
"ParentId": "261078",
"Score": "8"
}
},
{
"body": "<p>As a complement to the other answers, here are a few brief comments on the math part.</p>\n<p>Disclaimer: I'm no numerical analyst, so there are probably more substantial efficiencies than the ones I suggest. I would say that efficiencies are important, since usually math code will be the backbone of a numerical application.</p>\n<p>First a few general principles:</p>\n<ul>\n<li><p>As a general principle, you want to try and minimize the number of operations you make, to minimize errors.</p>\n</li>\n<li><p>Errors do exist. A compiled C program stores its numbers in binary (or hex if you prefer). This has some unexpected consequences. A typical example is that the number 1/10 (one over ten) is periodic in base 2. The consequence of this is that it only stored as an approximation, and that any computation involving this number will carry errors over. This happens left and right with any usual floating point implementation. Very often it does not generate problems; but in a library you want to minimize computations, as mentioned above.</p>\n</li>\n<li><p>Any function implemented in your library is likely to be used repeatedly by a program. This makes efficiency fairly important.</p>\n</li>\n</ul>\n<p>Now to a (very) non-exhaustive list of concrete manifestations of the above:</p>\n<ul>\n<li><p>You exp function simply multiplies the <code>base</code>, <code>exponent</code> times. This can be streamlined a little (timewise) by keeping products, and this can be achieved by using the binary representation of the exponent. For instance, if you want to do <code>exp(base, 20)</code>, you notice that 20 is 2^4 + 2^2. So you can do <code>(base^2)^4 + (base^2)^2</code>. This makes you calculate three products and one sum instead of 20 products.</p>\n</li>\n<li><p>You definitely want to do complex multiplication in polar form, where the products turn to sums.</p>\n</li>\n<li><p>The limit and the derivative are calculated as <code>(f(x+h)+f(x-h))/2</code> and <code>((f(x+h)-f(x))/h+(f(x-h)-f(x))/(-h))/2</code>. This is bad numerically. In numerical calculuations, you want to avoid very small denominators, as this augments your errors greatly.</p>\n</li>\n<li><p>In the sine and the cosine, you are re-calculating the factorial for each term of the series, instead of calculating it as you go: in the term n+1, the divisor is <code>d_{n+1} = d_n * (n+1)</code>. Same with the power of X and the sign.</p>\n</li>\n<li><p>The tangent function would be better served by using its own Taylor series than by calculating both the sine's and cosine's and dividing. In any case, you need to use reduction to the first quadrant and even to the first half of the first quadrant.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T18:36:14.253",
"Id": "515256",
"Score": "1",
"body": "Commenting on the structure of the OP's code may be useful, but pretty much all of the numerical methods used are worthless for any real-world application, and addressing that issue is way off-topic here IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T10:48:06.287",
"Id": "515292",
"Score": "1",
"body": "Welcome to CodeReview. About the numerical errors: feel free to point to https://floating-point-gui.de/ or https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. The former one is more light, the latter usually *the* reference for handling IEEE floating pointer numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:58:35.730",
"Id": "515331",
"Score": "0",
"body": "The advantage of calculating tangent as the quotient is that the Taylor series converge everywhere, whereas tagnent's Taylor series only converges on `(-π/2,π/2)`, and slowly at that. But I'm sure that numerical analysts have even better approaches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T18:04:40.737",
"Id": "515348",
"Score": "0",
"body": "@Teepeemm: good point. With either method one should reduce to numbers close to 0 to accelerate convergence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T06:22:06.927",
"Id": "521247",
"Score": "0",
"body": "In practice, you probably wouldn't use a Taylor series for any of the trigonometric functions—the relative errors blow up at boundary values, and the number of terms required to compensate for this gets ridiculous. Taylor series also don't converge _that_ quickly—compare it to, say, the continued fraction approximation for the equivalent trig function, which converges quicker and with a tighter fit. Chebyshev polynomials can be used to approximate trig functions, with rapid convergence and an error function that's distributed evenly throughout the range without blowing up."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T17:00:24.013",
"Id": "261106",
"ParentId": "261078",
"Score": "8"
}
},
{
"body": "<p>Coming from a math background and with no C++ experience, here's what I notice:</p>\n<p>You jump between <code>if (condition) { body inline }</code> and</p>\n<pre><code>if (condition) {\n body by itself\n}\n</code></pre>\n<p>Stick with the second.</p>\n<p>Your function and parameter names need to be more descriptive. Failing that, you should comment why you're doing what you're doing.</p>\n<p><code>precision</code> should be <code>iterations</code>. Even better would be to leave it as <code>precision</code> (or <code>tolerance</code>), and calculate enough iterations until you are within <code>precision</code> of the answer (or at least your current answer changes by at most <code>precision</code>).</p>\n<p>Generally, <code>exp</code> means <code>e^x</code>. It would be better to name yours <code>power</code>.</p>\n<p>What is the difference between <code>nsqrt</code> and <code>esqrt</code>? I see that <code>nsqrt</code> is the Newton-Rahpsom method. I don't understand <code>esqrt</code>. Others have remarked about the problem of <code>x!=num</code>. I'll point out that (1) you should have started with <code>x=0</code>, and (2) this is a convoluted way to have <code>precision</code> iterations, so you would have wanted <code>for (int i=1;i<=precision;i++)</code> and dispensed with <code>h</code>.</p>\n<p>I'm pretty sure that you can remove the <code>if</code> portion of <code>gcd</code> and it will still work.</p>\n<p>Shouldn't <code>class frac</code> have some sort of method to return a string representation?</p>\n<p><code>tofrac</code> should make use of <code>simplify</code>. Others have noticed that it's broken, eg, anything from 0 to .5 will return 0. I think you wanted <code>numerator=round(x*precision); return fraction(numerator, precision).simplify();</code>. Now <code>precision</code> doesn't mean iterations, it means "my guess for a denominator". But this approach will not work well for denominators that don't divide <code>precision</code>. It would be better to return the fraction with the smallest denominator that is within <code>precision</code> of <code>x</code>. This can be done in <code>O(denominator)</code> time.</p>\n<p><code>limit</code> should document its limitations. It will work ok for a removable discontinuity. It won't work for other types of limits.</p>\n<p><code>sigma</code> should be named <code>sum</code> or <code>summation</code>. <code>pi</code> should definitely be named <code>prod</code> or <code>product</code>.</p>\n<p>Several of your Taylor polynomial loops use <code>exp(-1,n)</code> to calculate a sign. It will be faster to just have <code>sign *= -1</code> in the loop, although that won't be too big of a deal if you're only running a loop 16 times (the default).</p>\n<p>You have a constant <code>pi</code> and a function <code>pi</code> that returns an approximation of the constant (in addition to the <code>pi</code> that should be <code>prod</code>). Why do you have a function to approximate a constant you already have stored? Similarly, you have a function <code>e</code> to approximate your constant <code>e</code>.</p>\n<p>What is <code>spigotpi</code> supposed to do? Print <code>pi</code>? Or something else? A math engine shouldn't be printing things; that should be the calling program's decision.</p>\n<p>What is <code>pi2</code>? Again with printing.</p>\n<p><code>complex sqrt</code> should also return a complex number if <code>x.get_re()<0</code> (actually, does this even get called in that case? It should). You need an intermediate value somewhere in there; I can't follow what you're doing. And I'm suspicious that you have sqrt(2).</p>\n<p><code>inf</code> and <code>sup</code> should be <code>min</code> and <code>max</code>. <code>inf</code> and <code>sup</code> would only make sense if you can have an infinite array in the input, and I don't know of a programming language that could handle that. (Or maybe it could return a lower bound within <code>tolerance</code> of the true <code>inf</code>, but you'd need a lot more code to pull that off.)</p>\n<p>In <code>rsum</code>, you're assuming that <code>x[i]<=t[i]<=x[i+1]</code>. You should document that, and possibly assert it as well. If <code>rsum</code> stands for Riemann sum, then <code>ldsum</code> must be lower Reimann sum and <code>udsum</code> must be upper Riemann sum. What's the <code>d</code> stand for?</p>\n<p>Does <code>rint</code> mean "Riemann sum with equally spaced partitions"? You should document that. In your comment, I would say "left hand endpoint" instead of "lower bound" (I would assume "lower bound" to be <code>ldsum</code>).</p>\n<p>Off topic:</p>\n<p>Series with denominators that are <code>O(n)</code> converge horribly slowly (in <code>ln</code> and <code>pi</code>). You should find better algorithms. <code>zeta</code> and <code>eta</code> will also converge slowly, but there's not much you can do with those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:56:42.600",
"Id": "261144",
"ParentId": "261078",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T19:45:02.007",
"Id": "261078",
"Score": "8",
"Tags": [
"c++",
"mathematics"
],
"Title": "A math engine with support for complex numbers, calculus, and fractions"
}
|
261078
|
<p>I have a bash script that fixes or creates, and syncs the asciidoc attributes and yaml header for blog posts. It does what it is supposed to. But notice I have put <code>sleep</code> commands in between the <code>sed -i</code> insert commands. This is because I was getting unusual error messages such as:</p>
<pre><code>sed: -e expression #1, char 40: unknown command: `Y'
</code></pre>
<p>But there is no command or any expression containing a <code>Y</code> in the file. I figured it was perhaps some kind of race condition, and wanted to 'slow' <code>sed</code> down. This sees to solve the problem but is there a better way to do this?</p>
<pre><code>#!/usr/bin/bash
#Before runing this script ensure the doc has a valid asciidoctor title
#then set the type lang and author defaults
export sectnumlevels=2
export toc="true"
export includedir="include"
[[ -z "$1" ]] && { echo "need a file" ; exit 1 ; }
sed -n '/^=\s/q1' "$1" && { echo "this looks like it doesn't have a title" ; exit 1 ; }
export file=$1
#delete blank lines
sed -i '10,19{/^[[:space:]]*$/d}' "$1"-
export title=`sed -n /^\=\ .*/p "$1"`-
export author=`awk /author:/{'first = $1; $1=""; print $0'} "$1" |sed 's/^ //g'`
export categories=`awk /categories:/{'first = $1; $1=""; print $0'} "$1" |sed 's/^ //g'`
export tags=`awk /tags:/{'first = $1; $1=""; print $0'} "$1" |sed 's/^ //g'`
[[ -z $author ]] && author="Name AUTHOR"
export date=`awk '/date:/{print $2}' "$1" | uniq`-
[[ -z "$date" ]] && date=`date -Im`
export type="post"
export lang="fr"
export draft="true"
[[ -z $categories ]] && categories="[]"
[[ -z $tags ]] && tags="[]"
function yaml {
sed -i '1 i ---' "$file"
sed -i "/^---/a title: $title" "$file"
sed -i "/^title:/a author: $author" "$file"
sed -i "/^author:/a date: $date" "$file"
sed -i "/^date:/a type: $type" "$file"
sed -i "/^type:/a draft: $draft" "$file"
sed -i "/^draft:/a categories: $categories" "$file"
sed -i "/^categories:/a tags: $tags" "$file"
sed -i '/^tags:/a ---' "$file"
#this is the weirdest hack
sed -i '9 a #;' "$file" && sed -i 's/^#;//g' "$file"
}
#call yaml function if no yaml header
sed -r -n '/^---(\s|$)/q1' "$1" && yaml-
#but if there is already a header it may be missing stuff
#needs to take care of when the key exists but no value...
sed -n '/^title:\s/q1' "$1" && sed -i "/^---/a title: $title" "$file"
sed -n '/^author:\s/q1' "$1" && sed -i "/^title:/a author: $author" "$file"
[[ ! $(awk '/^date:/{print $2}' "$1") ]] && sed -i "/^author:/a date: $date" "$file"
sed -n '/^type:\s/q1' "$1" && sed -i "/^date:/a type: $post" "$file"
#start the asciidoctor attributes
sed -i '/^:author:.*/d' "$1" && sed -i "/^=\s/a :author: $author" "$1"
#[[ ! $(awk '/^:date:/{print $2}' "$1") ]] && sed -i "/^:author:/a :date: $date" "$1"
sleep 0.25-
sed -i '/^:date:.*/d' "$1" && sed -i "/^:author:/a :date: $date" "$1"
sleep 0.25-
sed -i '/^:type:.*/d' "$1" && sed -i "/^:date:/a :type: $type" "$1"
sleep 0.25-
sed -i '/^:toc:.*/d' "$1" && sed -i "/^:type:/a :toc: $toc" "$1"-
sleep 0.25-
sed -i '/^:experimental:.*/d' "$1" && sed -i '/^:toc:/a :experimental:' "$1"-
sleep 0.25-
sed -i '/^:sectnums:.*/d' "$1" && sed -i '/^:experimental:/a :sectnums:' "$1"
sleep 0.25-
sed -i '/^:sectnumlevels:.*/d' "$1" && sed -i "/^:sectnums:/a :sectnumlevels: $sectnumlevels" "$1"-
if [ ! $lang = "en" ]; then
sed -n '/^:lang:\s/q1' "$1" && sed -i "/^:sectnumlevels:/a :lang: $lang" "$1"-
sleep 0.25-
sed -i '/:includedir:.*/d' "$1" && sed -i "/^:lang:/i :includedir: content/$lang/$includedir" "$1"
sleep 0.25-
sed -i '/include::locale/d' "$1" && sed -i '/^:lang:/a include::locale/attributes.adoc[]' "$1"-
sleep 0.25-
sed -i "/^include::locale/a #;" "$1" && sed -i 's/^#;//g' "$1"
fi
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T07:13:00.880",
"Id": "515281",
"Score": "1",
"body": "This question could be improved by showing a simple set of inputs and outputs, so we can replicate your results. It looks like your code has been mis-copied somehow - a lot of lines seem to have had `-` added at the end. I assume they are not in your actual script? Could you [edit] to fix them?"
}
] |
[
{
"body": "<blockquote>\n<pre><code>export sectnumlevels=2 \nexport toc="true" \nexport includedir="include"\n</code></pre>\n</blockquote>\n<p>It's not clear why any of these need to be exported</p>\n<blockquote>\n<pre><code>[[ -z "$1" ]] && { echo "need a file" ; exit 1 ; }\n</code></pre>\n</blockquote>\n<p>Error messages should go to stderr, not stdout: <code>echo >&2</code>. And we could use portable shell <code>[</code> instead of <code>[[</code>, rather than making the script Bash-specific.</p>\n<blockquote>\n<pre><code> sed -i '1 i ---' "$file"\n sed -i "/^---/a title: $title" "$file"\n sed -i "/^title:/a author: $author" "$file"\n sed -i "/^author:/a date: $date" "$file" \n sed -i "/^date:/a type: $type" "$file" \n sed -i "/^type:/a draft: $draft" "$file" \n sed -i "/^draft:/a categories: $categories" "$file"\n sed -i "/^categories:/a tags: $tags" "$file"\n sed -i '/^tags:/a ---' "$file"\n</code></pre>\n</blockquote>\n<p>It's inefficient to repeatedly open and write <code>$file</code>. Replace all this with a single <code>sed</code> program that inserts all of the required lines before line 1.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T22:54:47.327",
"Id": "515463",
"Score": "0",
"body": "Ah but the point is there are old posts that may or may not have some or any of those lines. So the script searches for what exists already and inserts what is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T07:16:46.730",
"Id": "515483",
"Score": "0",
"body": "And your test cases verify that it does that correctly? As I commented on the question, you'll get better reviews if you can show some inputs and expected outputs (or better still, your complete test harness)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T07:14:45.813",
"Id": "261126",
"ParentId": "261083",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-22T20:46:22.037",
"Id": "261083",
"Score": "1",
"Tags": [
"bash",
"sed"
],
"Title": "Bash script syncronizing yaml and asciidoc headers using sed"
}
|
261083
|
<p>This Program is a simple phonebook, user is given 3 choice, add a number to the phone book, dial a number or exit the program. Are there Any Improvements that i can make, either efficient or cleaning the code or something useful i can add?</p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class PhoneBookV2 {
public static void main(String[] args){
final ArrayList<String> numbers = new ArrayList<>();
print(numbers);
task(numbers);
}
public static void task(ArrayList<String> numbers){
Scanner scan = new Scanner(System.in);
System.out.println("Please Pick A Task: \n 1:Add A Number to Speed Dial \n 2:Speed Dial A Number \n 3:Exit");
String choice = scan.nextLine();
switch(choice){
case "1":
AddNumber(numbers);
break;
case "2":
CallNumber(numbers);
break;
case "3":
System.out.println("Goodbye!");
System.exit(0);
break;
}
}
private static void CallNumber(ArrayList<String> numbers) {
Scanner scan = new Scanner(System.in);
try {
String[][] keys = {
{" ", "1", " ", "2", " ", "3"},
{" ", "4", " ", "5", " ", "6"},
{" ", "7", " ", "8", " ", "9"},
{" ", " ", " ", "0", " ", " "}
};
printPhoneBook(keys);
System.out.println("Pick A Speed Dial Number");
int choice = Integer.parseInt(scan.nextLine());
String phoneNum = "";
switch (choice) {
case 1 -> phoneNum = numbers.get(0);
case 2 -> phoneNum = numbers.get(1);
case 3 -> phoneNum = numbers.get(2);
case 4 -> phoneNum = numbers.get(3);
case 5 -> phoneNum = numbers.get(4);
case 6 -> phoneNum = numbers.get(5);
case 7 -> phoneNum = numbers.get(6);
case 8 -> phoneNum = numbers.get(7);
case 9 -> phoneNum = numbers.get(8);
case 0 -> phoneNum = numbers.get(9);
default -> System.out.println("No Number Saved At " + choice);
}
if (phoneNum != null) System.out.println("Dialing " + phoneNum + "....");
else System.out.println("There is No Number At This Location");
PhoneBookV2.task(numbers);
} catch(IndexOutOfBoundsException e) {
System.out.println("There is No Number At This Location");
PhoneBookV2.task(numbers);
}
}
private static ArrayList<String> AddNumber(ArrayList<String> numbers) {
Scanner scanner = new Scanner(System.in);
boolean cont = false;
do {
System.out.print("Please Enter The Number You Wish To Save Under Speed Dial: ");
// Add the next number to the ArrayList
numbers.add(scanner.nextLine());
System.out.print("Would you like to add another? Yes or No: ");
String answer = scanner.nextLine().toLowerCase();
if (answer.equals("yes")) continue;
if (answer.equals("no")) {
print(numbers);
cont = true;
}
} while (!cont);
PhoneBookV2.task(numbers);
return numbers;
}
public static void printPhoneBook(String[][] keys){
for(String[] row : keys){
for(String s : row){
System.out.print(s);
}
System.out.println();
}
}
public static void print(ArrayList<String> numbers){
for(int i = 0; i< numbers.size(); i++){
System.out.println((i+1) + ") " + numbers.get(i));
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:33:15.423",
"Id": "515454",
"Score": "1",
"body": "I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>These are my suggestions:</p>\n<ol>\n<li>No need to invoke <code>print</code> before <code>task</code> in main. At that point, the numbers would be empty anyway.</li>\n<li>Better to declare numbers as : <code>List<String> numbers = new ArrayList<>();</code> (interface name on the left side) and make all parameters as <code>List<String> numbers</code> instead of <code>ArrayList<String> numbers</code>. This would minimize the code changes if you plan to use a different implementation of <code>List</code> instead of <code>ArrayList</code> in future.</li>\n<li>You are currently not closing the <code>Scanner</code> objects. It would be good to use try with resources : <code>try(Scanner s = new Scanner(System.in)) { //code}</code></li>\n<li>Better to follow naming conventions : method names follow camel-case convention.</li>\n<li>In <code>CallNumber</code> instead of the big <code>switch-case</code>, simple <code>if-else</code> is required. (Also it would be nice if speed dial 1 is <code>numbers.get(1)</code> instead of <code>numbers.get(0)</code>, so that you could just use <code>numbers.get(choice)</code>)</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>String phoneNum = null; // should not be initialized as "", otherwise dialing message would be displayed even if choice is invalid.\nif(choice >= 0 && choice <= 9) {\n phoneNum = numbers.get((choice + 9) % 10);\n} else {\n // error message\n}\n</code></pre>\n<ol start=\"6\">\n<li>I believe <code>cont</code> in <code>AddNumber</code> is used to indicate continue adding numbers. But the loop executes when this is <code>false</code>. So the naming and the actual use do not match. You could have initialized it to <code>true</code>, then use a <code>while(cont)</code> instead of <code>do-while(!cont)</code> and for choice <code>no</code> you could have set <code>cont = false</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T09:37:30.973",
"Id": "261095",
"ParentId": "261089",
"Score": "2"
}
},
{
"body": "<p>It's hard to know where to begin here.</p>\n<ul>\n<li>If you only allow 10 numbers, why bother with an arraylist, an array would do</li>\n<li>If you allow a choice of 0 - 9, why do you have to change the chosen values for indexing in such an ugly way? If you want to use 1-based numbering for the phone numbers, just do that by simple arithmetic</li>\n<li>You use far too many Scanners, none of which you close - you only need one</li>\n<li>You use recursion - calling the "choose a task" method at the end of each task method - for a process which is naturally iterative. You've written loops elsewhere, so why not for the main process?</li>\n<li>You have no object-orientation - this is procedural code, just written in Java</li>\n<li>You don't validate input phone numbers - the user could enter -1 or "my dog has fleas" and the program would accept them</li>\n<li>As Gautham mentions (he makes a number of good points), the use of "cont" seems unintuitive</li>\n<li>The "if...else" in callNumber is non-standard format</li>\n</ul>\n<p>Some basic ideas</p>\n<ul>\n<li>Split your code between the data and the user interaction - have a PhoneBook class with simple operations, like add, delete, retrieve and use that from your user interaction code</li>\n<li>Your main flow should then be a simple loop that asks for a choice of task, performs that task, then loops round again</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T08:34:30.240",
"Id": "261129",
"ParentId": "261089",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T05:18:01.423",
"Id": "261089",
"Score": "2",
"Tags": [
"java",
"array"
],
"Title": "Java Simple Phonebook"
}
|
261089
|
<p>There is a personal program of mine which logs in, scrape links and then download them. The downloader part is based on <code>Youtube-dl</code> and I think it's a smell code. Is there any way to improve this code?</p>
<pre><code>import requests
import subprocess
import getpass
import time
from bs4 import BeautifulSoup as bs
import argparse
def Login(url, login_route, username, password):
URL = url
LOGIN_ROUTE = login_route
headers = {
'User-Agent': '',
'origin': URL,
'referer': URL + LOGIN_ROUTE,
}
request_session = requests.session()
csrf_token = request_session.get(URL).cookies['csrftoken']
login_payload = {
'hidden_username': username,
'password': password,
'csrfmiddlewaretoken': csrf_token
}
login_request = request_session.post(
URL + LOGIN_ROUTE, headers=headers, data=login_payload)
# !
msg = (
f'You have logged in successfully {login_request.status_code}' if login_request.status_code == 200 else
f'Error {login_request.status_code}'
)
print(msg)
def get_user_input():
url = 'https://maktabkhooneh.org/signin/?next=/dashboard/'
username = getpass.getpass('Username: ')
password = getpass.getpass('Password: ')
login_route = '/auth/login-authentication'
return(Login(url, login_route, username, password))
def Scraper(page_url):
Page_URL = page_url
headers = {
'User-Agent': ''
}
page = requests.get(
Page_URL,
headers=headers,
)
soup = bs(page.text, "html.parser")
URL_List = []
link_count = 0
for a_tag in soup.select('a[href^="/course/"]'):
links = "https://maktabkhooneh.org" + a_tag["href"]
URL_List.append(links)
link_count += 1
return URL_List
def Downloader(url_list):
URL_List = Scraper(url_list)
download_count = 0
for links in URL_List:
command = f"youtube-dl {links}"
result = subprocess.call(command, shell=True)
# !
if result == 0:
download_count += 1
return('\nReturned Value', result)
return(f'\n{download_count} file(s) have been downloaded')
page_url = 'https://maktabkhooneh.org/course/%D8%A2%D9%85%D9%88%D8%B2%D8%B4-%D8%B1%D8%A7%DB%8C%DA%AF%D8%A7%D9%86-%DB%8C%D8%A7%D8%AF%DA%AF%DB%8C%D8%B1%DB%8C-%D9%85%D8%A7%D8%B4%DB%8C%D9%86-Andrew-NG-mk1085/%D9%81%D8%B5%D9%84-%D8%A7%D9%88%D9%84-%D9%85%D9%82%D8%AF%D9%85%D9%87-ch3364/%D9%88%DB%8C%D8%AF%DB%8C%D9%88-%D8%AE%D9%88%D8%B4%D8%A2%D9%85%D8%AF%DB%8C%D8%AF-%DB%8C%D8%A7%D8%AF%DA%AF%DB%8C%D8%B1%DB%8C-%D9%85%D8%A7%D8%B4%DB%8C%D9%86/'
Login_ = input('Login required Website [Y], [N]? ')
# !
if Login_ == 'y' or 'Y':
get_user_input()
list_len = len(Scraper(page_url))
# !
Download_Permission = input(
f'\n{list_len} link(s) have been extracted. Do you want to DOWNLOAD them [Y], [N]? ')
# !
if Download_Permission == 'y' or 'Y':
Downloader(page_url)
</code></pre>
<p>Any help would be highly appreciated.</p>
|
[] |
[
{
"body": "<h1>Issues</h1>\n<p>The first one is the use of the <code>or</code> operator. If you wish to compare a variable with two values, you will have to write the comparison operator twice.\nFor instance,</p>\n<pre class=\"lang-py prettyprint-override\"><code>if Login_ == 'y' or 'Y':\n ...\n</code></pre>\n<p>should be write as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if Login_ == 'y' or Login_ == 'Y':\n</code></pre>\n<p>Also, it seems you are returning from the <code>Downloader</code> function before iterating though all links (whenever the first process finishes correcly):</p>\n<pre class=\"lang-py prettyprint-override\"><code>...\nif result == 0:\n download_count += 1\n # This will return after one commad executes successfully\n return('\\nReturned Value', result)\n</code></pre>\n<h1>Code style</h1>\n<p>Now, regarding code smells and style, in python there is <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8</a>, a general guide for code style.</p>\n<p>For example, functions/methods and variable names should start with lowecase (<code>Login</code> should be called <code>login</code>).</p>\n<p>Also, in the <code>Login</code> function, you are assigning the values of the <code>url</code> and <code>login_route</code> parameters to <code>URL</code> and <code>LOGIN_ROUTE</code> but they do not seem to serve for anything special. You could just use the function's parameters directly:</p>\n<pre class=\"lang-py prettyprint-override\"><code>...\nheaders = {\n 'User-Agent': '',\n 'origin': url,\n 'referer': url + login_route,\n}\n...\ncsrf_token = request_session.get(url).cookies['csrftoken']\n</code></pre>\n<p>Same goes for <code>Page_URL</code> in <code>Scraper</code>.</p>\n<p>Moreover, <code>return</code> should be used as a statement, rather than with function notation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def myFunction():\n return 0\n</code></pre>\n<p>Is better than:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def myFunction():\n return(0)\n</code></pre>\n<h1>Readability</h1>\n<p>Lastly, I would say this assignment in <code>Login</code> is not quite readable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>msg = (\n f'You have logged in successfully {login_request.status_code}' if login_request.status_code == 200 else\n f'Error {login_request.status_code}' \n )\n</code></pre>\n<p>Language features are there for when they are useful, but readability is key and should be kept in mind. I would write that assignment as a simple <code>if-else</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if login_request.status_code == 200:\n msg = f'You have logged in successfully {login_request.status_code}'\nelse:\n msg = f'Error {login_request.status_code}' \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T19:25:37.013",
"Id": "261114",
"ParentId": "261096",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "261114",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T09:49:26.080",
"Id": "261096",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"web-scraping"
],
"Title": "Simple download manager based on Youtube-dl"
}
|
261096
|
<p>I have a contact model, on change I set the state of the <code>contact</code> object, how can I make the below function more readable?</p>
<p>The <code>address</code> field is different because it's an object: <code>['address', 'city', 'state', 'zip']</code></p>
<pre><code> const onFieldChange = (
key,
index = 0,
isMulti = false,
isAddress = false
) => event => {
const value = event.target.value
const updatedContact = {...contact}
if (!isMulti) {
updatedContact[key] = value
if (
key === 'type' &&
value === 'Individual' &&
contact.entityFormationDate
) {
delete updatedContact.entityFormationDate
}
} else {
const keyInternal = isAddress ? key : 'value'
key = isAddress ? 'addresses' : key
updatedContact[key][index][keyInternal] = value
}
setContact(updatedContact)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T16:49:33.003",
"Id": "515250",
"Score": "2",
"body": "I don't see anything that can be improved in your code. In particular I don't see any repetition or any other boring code. Splitting the code into several smaller functions would not help either since that would mean way more code to read. So I guess it's already perfect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T07:02:47.550",
"Id": "515279",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T17:06:58.317",
"Id": "515981",
"Score": "0",
"body": "@TobySpeight Done"
}
] |
[
{
"body": "<p>You can do :</p>\n<pre><code> const onFieldChange = (\n key,\n index = 0,\n isMulti = false,\n isAddress = false\n ) => event => {\n const value = event.target.value\n const updatedContact = {...contact}\n if (!isMulti) {\n updatedContact[key] = value\n }\n if (!isMulti && // see this\n key === 'type' &&\n value === 'Individual' &&\n contact.entityFormationDate\n ) {\n delete updatedContact.entityFormationDate\n }\n if (isMulti) {\n const keyInternal = isAddress ? key : 'value'\n key = isAddress ? 'addresses' : key\n updatedContact[key][index][keyInternal] = value\n }\n setContact(updatedContact)\n }\n</code></pre>\n<p>That way you lose a level of nestedness, and it doesn't really change any of the logic</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T18:59:54.567",
"Id": "515260",
"Score": "3",
"body": "If you can do the check of `key=='type' && value ...` before the `updatedContact`, then you can switch those two statements and create an if/else, rather than `if(!isMulti)` and an `if(isMulti)` but tbh, this is still okay."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T20:22:43.180",
"Id": "515266",
"Score": "1",
"body": "The body of the second `if` statement is indented too far to the right."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T18:58:14.973",
"Id": "261113",
"ParentId": "261097",
"Score": "1"
}
},
{
"body": "<p>Code readability is a subjective quantity, however it is still considered as on-topic here at Code-Review.</p>\n<h2>General readability points</h2>\n<p>Note that code in isolation is must rely on presumptions. The scope, naming, and missing defines may force some of the following points to change if known.</p>\n<ul>\n<li><p>Use simplest statements possible. For example the statement <code>if (!isMulti) {</code> can be simplified to <code>if (isMulti) {</code> and swapping the code blocks.</p>\n</li>\n<li><p>Avoid breaking lines unless they extend past the right of screen.</p>\n<p>Some people use 80 columns (a little last century in my book (word warp is standard in IDE's these days)), 120 or even 160 will be readable in all but the smallest of devices.</p>\n</li>\n<li><p>Avoid repetition. You test <code>isAddress</code> twice within the listener. This can be done once outside the returned function. See rewrite.</p>\n<p>This may not be considered a readability issue, but part of good code readability is clearly showing intent.</p>\n<p>To read the two lines testing <code>isAddress</code> I immediately questioned why in the event? This is already known? I had to check as your intent was muddied.</p>\n</li>\n<li><p>The function <code>onFieldChange</code> is not an event listener, it returns a listener. The the prefixed <code>on</code> obfuscates its usage.</p>\n<p>The name would be better as just <code>createFieldChangeEvent</code>, <code>fieldChangeListener</code>, or <code>fieldChange</code> depending on the functions scope.</p>\n</li>\n<li><p>Semicolons go a long way to improve readability, especially for coders that are swapping between C like languages.</p>\n</li>\n<li><p>The string literals should be constants, however without the full scope and usage of these strings it is hard to define where and how to declare. So I leave them as is (apart from changing to double quotes)</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Two rewrites to contrast the subjective nature of readability.</p>\n<h3>General rewrite</h3>\n<p>Using the above points the code can be rewritten as</p>\n<pre><code>const fieldChangeListener = (key, index = 0, isMulti = false, isAddress = false) => {\n const [field, internalKey] = isAddress ? [key, "addresses"] : ["value", key];\n const isTypeKey = key === "type";\n return event => {\n const value = event.target.value;\n const updated = {...contact};\n if (isMulti) {\n updated[field][index][internalKey] = value;\n } else {\n updated[key] = value;\n const isTypeIndividual = value === "Individual" && isTypeKey;\n if (isTypeIndividual && contact.entityFormationDate) {\n delete updated.entityFormationDate;\n }\n }\n setContact(updated);\n }\n}\n</code></pre>\n<p>Is it more readable. We that depends on the readers level of experience and skill.</p>\n<h3>Compact rewrite</h3>\n<p>Personally I would have compacted the code further as its the total quantity (lines of code) that make code navigation the crucial readability factor. Code is seldom read in isolation.</p>\n<pre><code>const fieldChange = (name, idx = 0, isMulti = false, isAddress = false) => {\n const [internal, fieldName] = isAddress ? ["addresses", name] : [name, "value"];\n const isType = name === "type";\n return event => {\n const [updated, value] = [{...contact}, event.target.value];\n if (isMulti) {\n updated[fieldName][idx][internal] = value;\n } else {\n const canDelete = (updated[name] = value) === "Individual" && isType;\n canDelete && contact.entityFormationDate && (delete updated.entityFormationDate);\n }\n setContact(updated);\n }\n}\n</code></pre>\n<h2>Defined readability</h2>\n<p>Code readability is very dependent on code standards used in projects. Standards must be defined in writing.</p>\n<p>This is a document that all project coders should be thoroughly versed in and defines the styles, naming, layout, language features, etc... used and not to use in each project.</p>\n<p>It can be argued that a comprehensive code standards document makes it impossible to write unreadable code.</p>\n<p>To start a project without a standards document has already failed the first rule of readability. <em>"Subjectivity is unreliable"</em>.</p>\n<p>Example standards (as un-categorized points) I used for <em>"Compact rewrite"</em></p>\n<ul>\n<li>Fields to have <code>names</code> not <code>keys</code>.</li>\n<li><code>index</code> is always written <code>idx</code>.</li>\n<li>Short circuited end clauses must be grouped.</li>\n<li>Single line expression with multiple assignments must group each assignment.</li>\n<li>Use semicolons.</li>\n<li>Prefer declarations using destructuring assignments over multi-line declarations.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T06:16:30.770",
"Id": "515376",
"Score": "0",
"body": "Thank you very much for your detailed answer, I read it a few times and feel like I learned a lot from it, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T05:18:44.077",
"Id": "515476",
"Score": "0",
"body": "Would it be okay to drop the curly brackets from `if (isMulti)`? I know it's possible, but I dont know if there is a standard against it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T10:22:58.340",
"Id": "515503",
"Score": "0",
"body": "@TomJenkins There is no rule against it but I always delimit all code blocks as forgetting to add the curlies in latter modifications is an very difficult to spot and seemingly random behavioral bug that is 100% avoidable if you always delimit code blocks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T12:45:47.250",
"Id": "261136",
"ParentId": "261097",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261113",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T09:56:56.253",
"Id": "261097",
"Score": "0",
"Tags": [
"javascript",
"react.js"
],
"Title": "Set state on field change"
}
|
261097
|
<p>I'm very new to programming and I decided to start my journey with Python. It's my fifth day of learning and decided to try myself out and make a very simple slot machine. I was stuck for hours because I had issues with the balance counter but finally managed to make it work.</p>
<p>Would you please rate it or give your opinion on where the code could have been simpler? Many thanks!</p>
<pre><code>import random
global a
a = [1000]
global bet
bet = 20
# This is the user's wallet, the list "a" contains the balance
def win1():
# I did different wins, the win1,2,3 function contains them
print("WIN!WIN!WIN! \n You won " , bet * 2 , "credits! ")
a.append(a[-1] + (bet * 2))
print("Actual balance : ", a[-1])
def win2():
print("WIN!WIN!WIN! \n You won " , bet * 4 , "credits! ")
a.append(a[-1] + (bet * 4))
print("Actual balance : ", a[-1])
def win3():
print("WIN!WIN!WIN! \n You won " , bet * 6 , "credits! ")
a.append(a[-1] + (bet * 6))
print("Actual balance : ", a[-1])
def reels():
# Here is the random number calculation.As you can see, theres a pretty good chance to win so it
# would not be a good casino game for the house :)
reel_1 = random.randint(1,3)
reel_2 = random.randint(1,3)
reel_3 = random.randint(1,3)
if reel_1 + reel_2 + reel_3 == 9 :
print("Jackpot!!!!!!!!!!")
a.append(a[-1] + bet * 100)
print ("Actual balance : " , a[-1])
elif reel_1 + reel_2 + reel_3 == 8:
win3()
elif reel_1 + reel_2 + reel_3 == 7:
win2()
elif reel_1 + reel_2 + reel_3 == 6:
win1()
else :
print("No win this time")
def spin() :
# And this is the main function, the spin
spin1 = input("Balance : "+ str(a[-1])+ " Press enter to spin the wheel ")
if spin1 == (""):
print("****************************THE WHEEL IS SPINNING**************************** \n "
"")
else :
print("You can only spin the wheel with enter")
spin()
a.append(a[-1] - bet)
print("Balance : " , (a[-1]))
reels() , spin()
spin()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T06:56:53.930",
"Id": "515278",
"Score": "0",
"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."
}
] |
[
{
"body": "<p>All your <code>win1</code>, <code>win2</code> and <code>win3</code> functions are essentially the same. When you have multiple functions/pieces of code that are nearly identical, look at what parts of them are the same, and what parts are different. Make the identical parts the body of a function, and the differing parts parameters of the function.</p>\n<p>In the case of those three functions, they're all the same; except for the bonus factor. Simply make that a parameter:</p>\n<pre><code>def win(bonus_factor):\n amount_won = bet * bonus_factor\n # I did different wins, the win1,2,3 function contains them\n print("WIN!WIN!WIN! \\n You won " , amount_won, "credits! ")\n a.append(a[-1] + amount_won)\n print("Actual balance : ", a[-1])\n</code></pre>\n<p>Then change the callsite to use the same function:</p>\n<pre><code>elif reel_1 + reel_2 + reel_3 == 8:\n win(6)\n\nelif reel_1 + reel_2 + reel_3 == 7:\n win(4)\n\nelif reel_1 + reel_2 + reel_3 == 6:\n win(2)\n</code></pre>\n<p>And better yet, the <code>6</code>, <code>4</code> and <code>2</code> should be extracted out into constants at the top of the file so they're named and easily modifiable.</p>\n<p>That reduced the duplication of those three functions, but there's multiple things that need to be said about <code>a</code>:</p>\n<ul>\n<li><p>It's a terrible name. The name you associate with an object should be descriptive and let readers know its purpose. Which makes more sense to you?:</p>\n<pre><code>a.append(a[-1] + (bet * 4))\nbalance_history.append(balance_history[-1] + (bet * 4))\n</code></pre>\n<p>You'll find that overwhelmingly, the latter will be easier to understand. Not only is <code>a</code> completely non-descript, but it's also so simple that you can't search for usages of it using simple "find" tools, since <code>a</code> is such a common letter.</p>\n</li>\n<li><p>It's not necessary. If you do a search for usages of <code>a</code>, you'll see that it's only used for two things: <code>a[-1]</code>, and <code>a.append</code>. While there's something to be said about anticipating future needs, you're currently accumulating a history of balances that you never use. This not only uses up more memory than is needed, but it also convolutes the logic. If you're maintaining a history, that suggests that the history is used somewhere. It never is though. You could safely change <code>a</code> to <code>balance = 1000</code>, then just do simple math on it directly. That would make a lot of this code cleaner and more sensical.</p>\n</li>\n</ul>\n<hr />\n<p>Speaking of memory usage, you're using recursion for basic looping, which is not a good thing. Your <code>spin</code> function is essentially:</p>\n<pre><code>def spin():\n # Logic\n reels(), spin()\n</code></pre>\n<p>Every single time your player takes another turn, <code>spin</code> is allocating another stack frame, and taking up more memory. If your player were to take ~1000 turns, your program would crash due to the stack being exhausted. Change that function to a basic <code>while</code> loop:</p>\n<pre><code>def spin():\n global balance\n while True:\n # And this is the main function, the spin\n spin1 = input("Balance : " + str(balance) + " Press enter to spin the wheel ")\n\n if spin1 == "":\n print("****************************THE WHEEL IS SPINNING**************************** \\n")\n balance -= bet\n print("Balance : ", balance)\n reels()\n else:\n print("You can only spin the wheel with enter") \n</code></pre>\n<p>A few changes I made:</p>\n<ul>\n<li>I changes <code>balance</code> to be a simple integer and discussed above (notice how much more sense <code>balance -= bet</code> makes).</li>\n<li>It's using a <code>while</code> loop. This does not eat up memory as the program is used. Recursion should be reserved for the very specific cases where it's the proper choice, like when iterating a recursive structure. Especially in a language like Python, recursion should be avoided unless you're very familiar with it and know about its strengths/weaknesses.</li>\n<li>I rearranged the <code>if</code> branches. You originally had it so if <code>if spin1 == "":</code> was true, all it would do is <code>print</code>; then the actual functionality happened at the bottom of the function. I think it makes much more sense as I have it here; where everything is grouped.</li>\n<li>I did a lot of small touchups (more on that below).</li>\n</ul>\n<hr />\n<p>You're making heavy use of global variables. This is quite common when starting out, but it's a habit you should work to fix quickly. General rules of thumb to follow unless you have good reason to do otherwise:</p>\n<ul>\n<li>All the changing data that a function requires to operate (<code>balance</code>, for example) should be explicitly passed to the function as arguments. This means you can test the function by simply passing it data, and you don't need to alter global state. This isn't a big deal now, but needing to alter mutable globals to test a function will become a disaster once your function is larger.</li>\n<li>All data that the function produces should be returned from the function. Again, this means you can test the function all you want without affecting any other code.</li>\n</ul>\n<p>As an alternative, you may also find that creating a class to maintain a state is a cleaner choice as well. That's getting a little more advanced though.</p>\n<hr />\n<p>I'm going to show the full final code below, but I needed to make many small fixes to make it clean. Please be aware of formatting. Yes, it is very important. You have many places in your code where care was not taken to make it consistent and readable:</p>\n<pre><code>elif reel_1 + reel_2 + reel_3 == 8:\n win3()\n\nelif reel_1 + reel_2 + reel_3 == 7: # Too many spaces after the elif\n win2()\n\n\n"Balance : "+ str(a[-1])+ " Press enter to spin the wheel " # Inconsistent spacing around +\n\n\ndef spin() : # There shouldn't be a space before the colon\n</code></pre>\n<p>If you're going to write Python, you should spend an afternoon to read over <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> <em>at least</em> once. The look of your code reflects strongly on that care that was taken while writing it. You want you code to look sharp, and clean. You may have your own stylistic preferences, but be consistent when applying them, and when in doubt, stick to PEP8.</p>\n<hr />\n<p>The final code:</p>\n<pre><code>import random\n\nbalance = 1000\nbet = 20\n\n\ndef win(bonus_factor):\n global balance\n amount_won = bet * bonus_factor\n # I did different wins, the win1,2,3 function contains them\n print("WIN!WIN!WIN! \\n You won ", amount_won, "credits! ")\n balance += amount_won\n print("Actual balance : ", balance)\n\n\ndef reels():\n global balance\n # Here is the random number calculation.As you can see, theres a pretty good chance to win so it\n # would not be a good casino game for the house :)\n reel_1 = random.randint(1, 3)\n reel_2 = random.randint(1, 3)\n reel_3 = random.randint(1, 3)\n\n if reel_1 + reel_2 + reel_3 == 9:\n print("Jackpot!!!!!!!!!!")\n balance += bet * 100\n print("Actual balance : ", balance)\n\n elif reel_1 + reel_2 + reel_3 == 8:\n win(6)\n\n elif reel_1 + reel_2 + reel_3 == 7:\n win(4)\n\n elif reel_1 + reel_2 + reel_3 == 6:\n win(2)\n else:\n print("No win this time")\n\n\ndef spin():\n global balance\n while True:\n # And this is the main function, the spin\n spin1 = input("Balance : " + str(balance) + " Press enter to spin the wheel ")\n\n if spin1 == "":\n print("****************************THE WHEEL IS SPINNING**************************** \\n")\n balance -= bet\n print("Balance : ", balance)\n reels()\n else:\n print("You can only spin the wheel with enter")\n\n\nspin()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T17:33:46.167",
"Id": "515254",
"Score": "1",
"body": "I really appreciate your comment and i'm pretty sure that along the way i'm on , your advices will help me a lot. It was already helpful and it made me help to think in a different way which will be more effective and time saving in the future. As i mentioned i'm new to this world, have a lot of work to put in, a lot of things to learn. Thank you for your time you put in this comment! God Bless"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T14:32:42.743",
"Id": "261103",
"ParentId": "261101",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "261103",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T13:37:04.433",
"Id": "261101",
"Score": "3",
"Tags": [
"python",
"beginner"
],
"Title": "Slot-machine balance counter"
}
|
261101
|
<p>This is my attempt at simulating an eco system.
Basically this thing is suppost to simulate how an eco system works.
Its not the most accurate thing but it's something.
Let me know what you think about it.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace Ecosystemsimulation
{
class Rabbit
{
public bool Haseaten // property
{
get; set;
}
public Rabbit(bool hasalreadyeaten)
{
Haseaten = hasalreadyeaten;
}
}
class Program
{
public static bool GenerateRandombool(int precentage)
{
var rand = new Random();
if (rand.Next(1000) < precentage * 10)
{
return true;
}
return false;
}
static void Main(string[] args)
{
Console.WriteLine("Ecosystem Simulation");
Console.WriteLine("---Enter the amount of prey---");
int RabbitsAmount = Int32.Parse(Console.ReadLine());
List<Rabbit> rabbits = new List<Rabbit>();
for (int i = 0; i < RabbitsAmount; i++)
{
rabbits.Add(new Rabbit(false));
}
Console.WriteLine("---Enter the amount of avialable crops per day---");
int Foodavailable = Int32.Parse(Console.ReadLine());
Console.WriteLine("---Write the amount of days to siumlate---");
int Daysamount = Int32.Parse(Console.ReadLine());
//Console.WriteLine("---Write the amount of predetors ---");
//int predator = Int32.Parse(Console.ReadLine());
Console.WriteLine("---Write the probabilty of repuduction---");
int reproductionperc = Int32.Parse(Console.ReadLine());
int dead = 0;
Console.WriteLine("------------------Starting Simulation------------------");
int Foodavailablefortheday = Foodavailable;
int deathstoday = 0;
for (int i = 0; i < Daysamount; i++)
{
foreach (Rabbit obj in rabbits.ToList())
{
if (!obj.Haseaten)
{
if (Foodavailablefortheday > 0)
{
obj.Haseaten = true;
Foodavailablefortheday = Foodavailablefortheday - 1;
}
}
}
/*if (GenerateRandombool(reproductionperc))
{
rabbits.Add(new Rabbit(true));
}*/
foreach (Rabbit obj in rabbits.ToList())
{
if (!obj.Haseaten)
{
dead = dead + 1;
deathstoday = deathstoday + 1;
rabbits.Remove(obj);
}
}
if (rabbits.Count % 2 == 0 && rabbits.Count != 0 && rabbits.Count != 1)
{
int Rabbitcountrepu = rabbits.Count / 2;
for (int u = 0; u != Rabbitcountrepu; u++)
{
rabbits.Add(new Rabbit(true));
}
}
else if(rabbits.Count >= 3)
{
int Rabbitcountrepu = rabbits.Count - 1;
Rabbitcountrepu = reproductionperc / 2;
for (int u = 0; u != Rabbitcountrepu; u++)
{
rabbits.Add(new Rabbit(true));
}
}
foreach (Rabbit obj in rabbits.ToList())
{
obj.Haseaten = false;
}
Console.WriteLine($"Deaths total day {i}:{deathstoday}" );
Console.WriteLine($"Alive total day {i}:{rabbits.Count}");
Console.WriteLine("------------------");
Foodavailablefortheday = Foodavailable;
deathstoday = 0;
}
int alive = 0;
foreach (Rabbit obj in rabbits.ToList())
{
alive = alive + 1;
}
Console.WriteLine("------------------Simulation over------------------");
Console.WriteLine("We ended up with " + dead + " casualt(ies)(y)");
Console.WriteLine("We ended up with " +alive+ " Still alive");
Console.WriteLine($"Amount of creatures who lived once { alive + dead}");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T18:52:45.223",
"Id": "515258",
"Score": "2",
"body": "One quick tip: be consistent with your casing. Should have \"HasEaten\", \"GenerateRandomBool\", \"hasAlreadyEaten\" and there are others that seem a bit haphazard. Read https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions for guidelines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T21:22:05.897",
"Id": "515271",
"Score": "0",
"body": "Thanks for your feedback"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T08:19:00.563",
"Id": "515391",
"Score": "0",
"body": "Sorry to say but this has nothing to do with OOP."
}
] |
[
{
"body": "<p>The biggest code smell I see is repeated enumeration of the same collection multiple times in a row, except you are actually creating copies for no good reason (more on this later).</p>\n<p>Try to find a way to change your design to require enumerating a collection the least amount of times possible. This will improve performance and should also make it more clear to read and edit. Especially important as you scale up (enumerating a huge collection multiple times is not fast).</p>\n<p>First one simple suggestion:</p>\n<pre><code>//Explicitly mark the accessibility of the class here. Just good practice.\n//Private, protected, public, internal, etc..\npublic class Rabbit\n{\n //...SNIP...\n}\n</code></pre>\n<p>I also agree with the comment about picking a consistent naming convention. Otherwise a variable like <code>Haseatencarrotstoday</code> is very hard to read.</p>\n<p>Which casing is really opinion based, however I think the consensus is pick a naming convention and stick with it throughout.</p>\n<p>Now to the worst part of the code:</p>\n<pre><code>foreach (Rabbit obj in rabbits.ToList())\n</code></pre>\n<p>Why <code>ToList</code>? <code>rabbits</code> is already a list... I would wager that's a workaround for modifying a collection during enumeration.</p>\n<p>What's really happening is you're copying an array (lists are backed by an array) repeatedly simply due to bad design. That's what I'd call a hack. And really bad for performance, especially because it's entirely unnecessary.</p>\n<p>Here's a better way (without modifying your <code>Rabbit</code> class, because I prefer a <code>HashSet<T></code> here, but I digress):</p>\n<pre><code>var removeThese = new List<Rabbit>();\nforeach (Rabbit obj in rabbits)\n{\n if(<cwhatever condition to check for removal>)\n {\n removeThese.Add(obj);\n //Going to remove this, let's continue\n continue;\n }\n //Other stuff here\n}\nforeach(var remove in removeThese)\n rabbits.Remove(remove);\n</code></pre>\n<p>While that can be improved upon I think it demonstrates the problem and possible solutions.</p>\n<p>Lastly, conditionals are evaluated left to right. So you want the fastest conditionals to be on the left, and more expensive on the right.</p>\n<p>For example, changing</p>\n<pre><code>if (rabbits.Count % 2 == 0 && rabbits.Count != 0 && rabbits.Count != 1)\n</code></pre>\n<p>To</p>\n<pre><code>if (rabbits.Count > 1 && rabbits.Count % 2 == 0)\n</code></pre>\n<p>Nets better performance because checking <code>Count > 1</code> is faster than using the mod operator <code>%</code>.</p>\n<p>Sure, not a big difference in this case, but this can have tremendous impact if you can short circuit the condition as fast as possible. It's vital to understand this concept when writing complex conditionals.</p>\n<p>It's extremely common to see things like null and count checks at the beginning of conditionals for this reason.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T00:28:27.003",
"Id": "261168",
"ParentId": "261107",
"Score": "1"
}
},
{
"body": "<p>There quite a few problems with your code, here's a few of the worst ones:</p>\n<ul>\n<li><p>You're instantiating a new <code>Random</code> object every time you create a new number. That is bad because the random object gets seeded on construction, and calling this thing multiple times quickly in a row will most likely give you the same value repeated. Plus it's expensive.</p>\n</li>\n<li><p>Repeated <code>ToList()</code> calls when iterating objects. That is terribly inefficient and absolutely unneeded.</p>\n</li>\n<li><p>Imagine someone gave you the piece of code <code>new Rabbit(false)</code> and nothing else. What does it mean? What do you mean you don't know, the code can't be so badly written that <strong>an object construction isn't immediately obvious what it does</strong>! There is nothing more important than knowing exactly why you are filling up your memory and with exactly what.</p>\n</li>\n<li><p><code>// property</code> -- there are memes about people who write "comments" like those. Refer to the previous point to give you an idea of where you should be spending your efforts.</p>\n</li>\n<li><p><code>Haseaten</code> is not how properties should be named in .Net, it should be <code>HasEaten</code>. There are very clear guidelines on naming: <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines</a></p>\n</li>\n<li><p>And lastly, if you reference the C# static analysis package, most of your code will light up green (or ghost out of existence) because it's using improper names (<code>Int32</code>), repeated names (<code>new List<Rabbit>()</code>), wasteful casts (<code>Rabbit</code>), wasteful Linq operations (<code>ToList()</code>), wrong operators (<code>dead = dead + 1;</code>), unnecessary assignments (<code>int Rabbitcountrepu = rabbits.Count - 1</code>) etc.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:56:50.480",
"Id": "261203",
"ParentId": "261107",
"Score": "0"
}
},
{
"body": "<p>If the program simulates an ecosystem, I'd probably have an Ecosystem class.</p>\n<p>Since weather may be a factor, for crops I might have a min and max that can be available each day.</p>\n<p>My high level approach might be something like this:</p>\n<pre><code>var prey = new Rabbits(50);\nvar predators = new Predators(5);\nvar crops = new Crops(5, 10);\nvar days = 200;\nvar system = new Ecosystem(prey, predators, crops, days);\nsystem.Evolve();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-10T21:15:32.747",
"Id": "262901",
"ParentId": "261107",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T17:06:38.520",
"Id": "261107",
"Score": "-1",
"Tags": [
"c#",
"object-oriented"
],
"Title": "C# oop eco system simulation"
}
|
261107
|
<p>I made a 52 standard deck generator for practicing my C#. Just to let you know I am using the unity editor.</p>
<p>I would your feedback as to whether my code is good/bad or whatever you may desire.</p>
<pre><code>using System;
using System.Collections.Generic;
using UnityEngine;
public class Standard52Deck {
List<Card> deck = new List<Card>();
enum Ranks {
Ace,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King
}
enum Suits {
Hearts,
Spades,
Clubs,
Diamonds,
}
class Card {
readonly Ranks rank;
readonly Suits suit;
public Card(Ranks rank, Suits suit) {
this.rank = rank;
this.suit = suit;
}
public override string ToString() {
return $"{rank} of {suit}";
}
}
IEnumerable<Card> GetSortedCardsBySuits() {
var rankCount = Enum.GetValues(typeof(Ranks));
var suitCount = Enum.GetValues(typeof(Suits));
var deckCount = rankCount.Length * suitCount.Length;
var index = 0;
var rankIteration = 0;
while (index < deckCount) {
var rank = (Ranks)(index % 13);
if (rank == 0 && index != 0) {
rankIteration++;
}
var suit = (Suits)(rankIteration);
index++;
yield return new Card(rank, suit);
}
}
void CreateSortedCards() {
foreach (var card in GetSortedCardsBySuits()) {
deck.Add(card);
}
}
void Start() {
CreateSortedCards();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T18:29:17.413",
"Id": "515555",
"Score": "0",
"body": "Comments are not for extended discussion; the conversation has been [moved to chat](https://chat.stackexchange.com/rooms/124723/discussion-on-question-by-mr-banks-c-standard-52-card-deck)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-10T21:05:00.367",
"Id": "518954",
"Score": "0",
"body": "My [Blackjack example](https://codereview.stackexchange.com/questions/214390/my-blackjack-game-in-c-console/215625#215625) includes Deck, Suit, and Card classes which you might want to check out."
}
] |
[
{
"body": "<p>You have nicely read the rank count into the variable <code>rankCount</code>, but later, you are writing <code>index % 13</code>. It is not immediately clear where this number comes from. Use the variable there too.</p>\n<p>Since these numbers never change and are well known for a 52-card deck, you could also simply define them as constants.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>const int RankCount = 13;\nconst int SuitCount = 4;\nconst int DeckCount = RankCount * SuitCount; \n</code></pre>\n<hr />\n<p>I usually do not use <code>var</code> for built in types. You do not save a lot of typing by writing <code>int</code> or <code>string</code> instead of <code>var</code> and it is easier to read.</p>\n<hr />\n<p>The two integer operators <code>%</code> and <code>/</code> are complementary and play well together.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var rank = (Ranks)(index % RankCount);\nvar suit = (Suits)(index / RankCount);\n</code></pre>\n<p>Note that the integer division truncates the result.\nThis makes the <code>rankIteration</code> variable superfluous.</p>\n<p>Alternatively, you could also use two nested loops, looping over suits and ranks. Using <code>foreach</code> makes all the indexes and suit and rank index calculations as well as the related constants superfluous. Additionally, <code>foreach</code> automatically casts the values to match the type of the loop variable:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>IEnumerable<Card> GetSortedCardsBySuits()\n{\n foreach (Suits suit in Enum.GetValues(typeof(Suits))) {\n foreach (Ranks rank in Enum.GetValues(typeof(Ranks))) {\n yield return new Card(rank, suit);\n }\n }\n}\n</code></pre>\n<hr />\n<p>Using <code>List<T>.AddRange()</code> makes the explicit loop superfluous</p>\n<pre class=\"lang-cs prettyprint-override\"><code>void CreateSortedCards()\n{\n deck.AddRange(GetSortedCardsBySuits());\n}\n</code></pre>\n<p>There is a minor naming problem here. The deck list is created elsewhere. Here it is only initialized. Since the list has a constructor overload <code>List<T>(IEnumerable<T>)</code>, we could create and initialize the deck in the class constructor instead (or, if we make <code>CreateSortedCards</code> static, also in an initializer)</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private readonly List<Card> deck;\n\npublic Standard52Deck()\n{\n deck = new List<Card>(GetSortedCardsBySuits());\n}\n</code></pre>\n<p>read-only fields can be initialized in an initializer or in a constructor. This also ensures that there is always an initialized card deck.</p>\n<hr />\n<p>The canonical way of looping a number range is (instead of the while-loop)</p>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int index = 0; index < DeckCount; index++)\n{\n ...\n}\n</code></pre>\n<p>It unifies and standardizes the declaration and initialization of the loop variable, the loop condition and incrementing the loop variable. Also, it scopes the loop variable locally to the loop. However, I prefer the <code>foreach</code> approach mentioned earlier.</p>\n<hr />\n<p>Note that these are only suggestions. There are always different ways to approach a problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T17:50:10.570",
"Id": "261110",
"ParentId": "261108",
"Score": "19"
}
},
{
"body": "<pre class=\"lang-cs prettyprint-override\"><code>class Card {\n readonly Ranks rank;\n readonly Suits suit;\n // ...\n}\n</code></pre>\n<p>In this type definition, there is a grammatical mismatch: <code>Ranks rank</code> has a plural type name but a singular variable name.</p>\n<p>The types <code>Ranks</code> and <code>Suits</code> should be renamed to <code>Rank</code> and <code>Suit</code>, to make the code more consistent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T20:29:37.223",
"Id": "261117",
"ParentId": "261108",
"Score": "20"
}
},
{
"body": "<p>Note: The traditional order of suits is (highest to lowest) Spades, Hearts, Diamonds, Clubs.</p>\n<p>While this order does not matter for many games, there are also many games for which it does matter. However, even in games where the order does not matter, it is still understood to be the traditional implicit order in almost all of them (the game of Hearts may be an exception).</p>\n<p>Therefore, I would suggest changing the order in your suits <code>enum Suits</code> to fit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T15:30:12.117",
"Id": "515332",
"Score": "0",
"body": "By the same token, I'd also consider putting Ace after King. I mean, it depends on the game, but *most* card games I know have aces high. Might have to make different versions of the class to support either ordering. Aces will probably require special handling in many games no matter what."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T15:59:16.333",
"Id": "515335",
"Score": "3",
"body": "@DarrelHoffman Ace is a particular problem because in many card games it's value is dynamic: it can change from high to low depending on circumstances. However it's *denomination* is 1 and the traditional *ordering* is numerical which makes it first (i.e., before two). In most card game programs I've seen, the Ace is enumerated first with a value of one. Sometimes, if the Ace is always high, then then the two is enumerated first with an explicit value of 2 and the Ace is last (with an implict value of 14). Since this appears to be intended for use in multiple games, Ace=1 seems right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T19:54:19.757",
"Id": "515650",
"Score": "0",
"body": "I find your answer interesting but a deck of playing cards should be oblivious to ranking of suits. That should be left to a Game object, which is not defined here. Consider different games like Poker, Blackjack, FreeCell, or Crazy Eights all treat the suits differently. A Game object would define the rules of a particular game. Suits alphabetically would be C-D-H-S. Microsoft Charmap has them as ♠♣♥♦, or S-C-H-D. And this site has them as H-C-D-S from top to bottom: https://ambitiouswithcards.com/new-deck-order/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:04:05.093",
"Id": "261142",
"ParentId": "261108",
"Score": "5"
}
},
{
"body": "<p>It always seems odd in code to see a constant whose name is a number and for it to have a value different to that number.</p>\n<p>You can set a value on an enum and the later ones automatically increment thereafter, so writing:</p>\n<pre><code>enum Ranks {\n Ace = 1,\n Two,\n Three,\n Four,\n Five,\n Six,\n Seven,\n Eight,\n Nine,\n Ten,\n Jack,\n Queen,\n King\n}\n</code></pre>\n<p>means that <code>9 == (int) Nine</code> is true, which is less weird than <code>Nine</code> being eight.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:13:39.367",
"Id": "261150",
"ParentId": "261108",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "261110",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T17:10:09.387",
"Id": "261108",
"Score": "11",
"Tags": [
"c#",
"unity3d"
],
"Title": "C# - Standard 52 card deck"
}
|
261108
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/260576/231235">Android APP connect to FTP server in Java</a>. I am attempting to create a tiny FTP host manager with <code>FTPHostProfile</code> class and <code>FTPHostProfiles</code> class.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p>Project name: FTPHostManagement</p>
</li>
<li><p><code>FTPHostProfile</code> class implementation:</p>
<pre><code>package com.example.ftphostmanagement;
public class FTPHostProfile {
private String ProfileName = "";
private String FTPHostName = "";
private int FTPPort = 21;
private String FTPUsername = "";
private String FTPPassword = "";
public FTPHostProfile(String hostnameInput, int portInput, String usernameInput, String passwordInput)
{
this.ProfileName = FTPHostName;
this.FTPHostName = hostnameInput;
this.FTPPort = portInput;
this.FTPUsername = usernameInput;
this.FTPPassword = passwordInput;
}
public FTPHostProfile(String profileNameInput, String hostnameInput, int portInput, String usernameInput, String passwordInput)
{
this.ProfileName = profileNameInput;
this.FTPHostName = hostnameInput;
this.FTPPort = portInput;
this.FTPUsername = usernameInput;
this.FTPPassword = passwordInput;
}
public String GetProfilename()
{
return this.ProfileName;
}
public String GetHostname()
{
return this.FTPHostName;
}
public int GetPort()
{
return this.FTPPort;
}
public String GetUsername()
{
return this.FTPUsername;
}
public String GetPassword()
{
return this.FTPPassword;
}
}
</code></pre>
</li>
<li><p><code>FTPHostProfiles</code> class implementation:</p>
<pre><code>package com.example.ftphostmanagement;
import android.util.Log;
import org.apache.commons.net.ftp.FTP;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class FTPHostProfiles {
private ArrayList<FTPHostProfile> Collection = new ArrayList<>();
/// Empty constructor
public FTPHostProfiles()
{
}
/// Single FTPHostProfile handler
public FTPHostProfiles(FTPHostProfile input)
{
this.Collection.add(input);
}
/// Multiple FTPHostProfiles handler
public FTPHostProfiles(ArrayList<FTPHostProfile> input)
{
this.Collection = input;
}
public FTPHostProfiles(FTPHostProfiles input)
{
this.Collection.addAll(input.Collection);
}
public FTPHostProfiles AddProfile(FTPHostProfile input)
{
this.Collection.add(input);
return this;
}
public FTPHostProfiles AddProfiles(ArrayList<FTPHostProfile> input)
{
this.Collection.addAll(input);
return this;
}
public FTPHostProfiles AddProfiles(FTPHostProfiles input)
{
this.Collection.addAll(input.Collection);
return this;
}
public FTPHostProfile GetProfile(String profileNameInput)
{
var filteredResult = this.Collection.stream().filter(element -> (element.GetProfilename().equals(profileNameInput))).collect(Collectors.toList());
if (filteredResult.stream().count() >= 1)
{
return filteredResult.get(0);
}
else
{
Log.d("GetProfile", "no such item in stored profiles");
throw new IllegalStateException("no such item in stored profiles");
}
}
}
</code></pre>
</li>
<li><p><code>FTPconnection</code> class implementation:</p>
<pre><code>package com.example.ftphostmanagement;
import android.util.Log;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.SocketClient;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPconnection {
FTPHostProfiles mFTPHostProfiles = new FTPHostProfiles();
public FTPconnection(FTPHostProfiles input)
{
this.mFTPHostProfiles = input;
}
public FTPClient connectftp(String profilename)
{
// Reference: https://stackoverflow.com/a/8761268/6667035
FTPClient ftp = new FTPClient();
try {
var FTPHostProfile = mFTPHostProfiles.GetProfile(profilename);
// Reference: https://stackoverflow.com/a/55950845/6667035
// The argument of `FTPClient.connect` method is hostname, not URL.
ftp.connect(FTPHostProfile.GetHostname(), FTPHostProfile.GetPort());
boolean status = ftp.login(FTPHostProfile.GetUsername(), FTPHostProfile.GetPassword());
if (status)
{
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.sendCommand("OPTS UTF8 ON");
}
System.out.println("status : " + ftp.getStatus());
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (SocketException en) {
en.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
}
</code></pre>
</li>
<li><p>User permission setting</p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</code></pre>
</li>
<li><p><code>AndroidManifest.xml</code></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ftphostmanagement">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FTPHostManagement">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
</code></pre>
</li>
<li><p><code>build.gradle</code></p>
<pre><code>plugins {
id 'com.android.application'
}
android {
compileSdk 30
defaultConfig {
applicationId "com.example.ftphostmanagement"
minSdk 26
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
// https://mvnrepository.com/artifact/commons-net/commons-net
implementation group: 'commons-net', name: 'commons-net', version: '20030805.205232'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
</code></pre>
</li>
</ul>
<p><strong>Full Testing Code</strong></p>
<ul>
<li><p><code>MainActivity.java</code> implementation:</p>
<pre><code>package com.example.ftphostmanagement;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTPClient;
public class MainActivity extends AppCompatActivity {
private FTPClient ftpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FtpTask().execute();
}
void ShowToast(String Text, int Duration)
{
Context context = getApplicationContext();
CharSequence text = Text;
int duration = Duration;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// AsyncTask must be subclassed to be used. The subclass will override at least one method
// `doInBackground(Params...)`, and most often will override a second one `onPostExecute(Result)`
// Reference: https://developer.android.com/reference/android/os/AsyncTask?authuser=4
// Reference: https://stackoverflow.com/a/12447497/6667035
private class FtpTask extends AsyncTask<Void, Void, FTPClient> {
// `doInBackground` invoked on the background thread immediately after `onPreExecute()`
// finishes executing. This step is used to perform background computation
// that can take a long time. The parameters of the asynchronous task are
// passed to this step. The result of the computation must be returned by
// this step and will be passed back to the last step. This step can also use
// `publishProgress(Progress...)` to publish one or more units of progress.
// These values are published on the UI thread, in the `onProgressUpdate(Progress...)`
// step.
protected FTPClient doInBackground(Void... args) {
FTPHostProfiles ftpHostProfiles = new FTPHostProfiles();
ftpHostProfiles.AddProfile(new FTPHostProfile( "Profile1",
"Hostname1",
21,
"Username1",
"Password1"));
ftpHostProfiles.AddProfile(new FTPHostProfile( "Profile2",
"Hostname2",
21,
"Username2",
"Password2"));
FTPconnection ftpConnect = new FTPconnection(ftpHostProfiles);
FTPClient ftp = ftpConnect.connectftp("Profile1");
return ftp;
}
// `onPostExecute` invoked on the UI thread after the background computation finishes.
// The result of the background computation is passed to this step as
// a parameter.
protected void onPostExecute(FTPClient result) {
Log.v("FTPTask","FTP connection complete");
ftpClient = result;
//Where ftpClient is a instance variable in the main activity
Log.v("Boolean.toString(ftpClient.isConnected())", Boolean.toString(ftpClient.isConnected()));
ShowToast(Boolean.toString(ftpClient.isConnected()), Toast.LENGTH_SHORT);
}
}
}
</code></pre>
</li>
</ul>
<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/260576/231235">Android APP connect to FTP server in Java</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The <code>FTPHostProfile</code> class and <code>FTPHostProfiles</code> class implementation is the key part in this post.</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>
|
[] |
[
{
"body": "<p>Important caveat: I know nothing about the Special Android coding conventions that are different from vanilla java.</p>\n<h2>General</h2>\nIt's preferable to use lowercase letters for acronyms in class names. `FtpHostProfile` is easier to read than `FTPHostProfile`.\n<p>Classes which have not been carefully designed for extension should be final.</p>\n<p>It's idiomatic for variable names to start with a lowercase letter. <code>profileName</code>, etc.</p>\n<p>Variables which do not change after the object is constructed should all be marked <code>final</code>. This reduces cognitive load on the reader as they can be confident they will not be reassigned after construction.</p>\n<p>It's idiomatic for method names to start with a lowercase letter.</p>\n<p>It's idiomatic for curly braces to be on the same line as the method declaration, not a line by themselves.</p>\n<p>Prefer using the most generally applicable type on the left hand side of assignments. <code>List</code> instead of <code>ArrayList</code>, etc.</p>\n<p>It's unnecessary to assign variables a value when they will get immediately overwritten in the constructor.</p>\n<h2>FTPHostProfile</h2>\nThere's no point in assigning the variables to be `\"\"` if you're just going to overwrite them in both constructors.\n<p>In the first constructor, why is profile name getting set to <code>""</code> by setting it to the value of <code>FTPHostName</code>? If you want it to be blank, make it blank. This is especially confusing because FTPHostName is reassigned on the next line.</p>\n<p>Lines longer than a hundred characters or so are hard to read. Consider breaking up the declaration of the second constructor over multiple lines, or at least starting the variable declarations on their own line.</p>\n<p><code>username</code> and <code>hostname</code> are sometimes written as one word. <code>Profilename</code> is not an English word, so it should be broken up as <code>ProfileName</code>. The variable names are also inconsistent with the method names.</p>\n<h2>FTPHostProfiles</h2>\nWhy does constructor number 3 require that multiple profiles be submitted in an `ArrayList`? What's wrong with a `LinkedList`, or (gasp!) a `Set` of some kind? This constructor should take a `Collection`. Likewise for `addProfiles`.\n<p>Directly assigning the <code>input</code> of that constructor to <code>Collection</code> is a bad idea. You've now lost control of your internals - whoever passed in <code>input</code> still has a pointer to it, and can change its contents without the knowledge or consent of this class. Just call <code>addAll</code> on your collection - you get the values stored in <code>input</code>, and nobody can muck with your collection.</p>\n<p><code>Collection</code> is not a great variable name. It's not descriptive, and it collides with a class name. Consider <code>profiles</code> or <code>ftpHostProfiles</code> as variable names.</p>\n<p>Do you actually need both constructors and methods which add profiles? That seems like overkill.</p>\n<p>Having the <code>addProfile</code> methods <code>return this</code> is convenient for chaining, but consider if you need to return something else instead, such as whether the addition was successful or not.</p>\n<p><code>getProfile</code> makes it clear that that <code>profiles</code> should be a <code>Map</code>, not a <code>List</code>.</p>\n<h2>FTPconnection</h2>\nThe `c` should be capitalized.\n<p><code>mFtpHostProfiles</code> should probably be <code>private final</code>.</p>\n<p>This class has several unused imports.</p>\n<p>You can probably call the variable <code>profile</code> I think there's enough context that the <code>FTPHost</code> is redundant.</p>\n<p>Perhaps <code>loggedIn</code> would be more descriptive than <code>status</code>?</p>\n<p>If you made all these changes, your code might look more like:</p>\n<p>FtpConnection:</p>\n<pre><code>public final class FtpConnection {\n\n private final FtpHostProfiles mFtpHostProfiles = new FtpHostProfiles();\n\n public FtpConnection(FtpHostProfiles input) {\n this.mFtpHostProfiles.addProfiles(input);\n }\n\n public FTPClient connectftp(String profileName) {\n // Reference: https://stackoverflow.com/a/8761268/6667035\n FTPClient ftp = new FTPClient();\n try {\n FtpHostProfile profile = mFtpHostProfiles.getProfile(profileName);\n\n // Reference: https://stackoverflow.com/a/55950845/6667035\n // The argument of `FtpClient.connect` method is hostname, not URL.\n ftp.connect(profile.getHostname(), profile.getPort());\n boolean loggedIn = ftp.login(profile.getUsername(), profile.getPassword());\n if (loggedIn) {\n ftp.enterLocalPassiveMode();\n ftp.setFileType(FTP.BINARY_FILE_TYPE);\n ftp.sendCommand("OPTS UTF8 ON");\n }\n System.out.println("status : " + ftp.getStatus());\n } catch (UnknownHostException ex) {\n ex.printStackTrace();\n } catch (SocketException en) {\n en.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return ftp;\n }\n}\n</code></pre>\n<p>FtpHostProfile:</p>\n<pre><code>public final class FtpHostProfile {\n private final String profileName;\n private final String ftpHostName;\n private final int ftpPort;\n private final String ftpUserName;\n private final String ftpPassword;\n\n public FtpHostProfile(String hostNameInput, int portInput, String userNameInput, String passwordInput) {\n this.profileName = "";\n this.ftpHostName = hostNameInput;\n this.ftpPort = portInput;\n this.ftpUserName = userNameInput;\n this.ftpPassword = passwordInput;\n }\n public FtpHostProfile(\n String profileNameInput,\n String hostnameInput,\n int portInput,\n String usernameInput,\n String passwordInput) {\n this.profileName = profileNameInput;\n this.ftpHostName = hostnameInput;\n this.ftpPort = portInput;\n this.ftpUserName = usernameInput;\n this.ftpPassword = passwordInput;\n }\n\n public String getProfileName() {\n return this.profileName;\n }\n\n public String getHostname() {\n return this.ftpHostName;\n }\n\n public int getPort() {\n return this.ftpPort;\n }\n\n public String getUsername() {\n return this.ftpUserName;\n }\n\n public String getPassword() {\n return this.ftpPassword;\n }\n}\n</code></pre>\n<p>FtpHostProfiles:</p>\n<pre><code>public final class FtpHostProfiles {\n private final Map<String, FtpHostProfile> profiles = new HashMap<>();\n\n public FtpHostProfiles() {\n // Empty constructor\n }\n\n public FtpHostProfiles addProfile(FtpHostProfile input) {\n this.profiles.put(input.getProfileName(), input);\n return this;\n }\n\n public FtpHostProfiles addProfiles(Collection<FtpHostProfile> input) {\n input.stream().forEach(profile -> profiles.put(profile.getProfileName(), profile));\n return this;\n }\n\n public FtpHostProfiles addProfiles(FtpHostProfiles input) {\n this.profiles.putAll(input.profiles);\n return this;\n }\n\n public FtpHostProfile getProfile(String profileNameInput) {\n FtpHostProfile profile = profiles.get(profileNameInput);\n if (profile == null) {\n Log.d("GetProfile", "No such item in stored profiles");\n throw new IllegalStateException("No such item in stored profiles");\n }\n return profile;\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T00:28:17.893",
"Id": "261120",
"ParentId": "261109",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261120",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T17:21:02.090",
"Id": "261109",
"Score": "1",
"Tags": [
"java",
"multithreading",
"android",
"networking",
"ftp"
],
"Title": "Android APP FTP host profile class implementation"
}
|
261109
|
<p>I'm constructing a homework from my Spring Boot Course and so far I did the JPA layer and want to have some feedback, before start the business rules, about if the I could improve something or change a type of relationship in my app. Any suggestions will be welcome.</p>
<p>Here is the exercise:</p>
<p>"Assume we have a big legacy system and one of the parts is withdrawal processing (the process that allows to transfer money from company to employee accounts). Now we have chance to completely rewrite the system, including API change (endpoints, DTOs etc). As a techical challenge we suggest you to take it. You can do whathever you want following the acceptance criteria:</p>
<ul>
<li>Use any architecture you are comfortable with</li>
<li>Use modern Java or Kotlin</li>
<li>Use Spring boot</li>
<li>Use any database SQL/NoSQL (please use embedded)</li>
<li>The code must be tested</li>
<li>The service should be easy to run (e.q. docker-compose)</li>
</ul>
<p>Here are some business rules of the processing:</p>
<ul>
<li>We have a list of users (/v1/users endpoint)</li>
<li>A user has several payment methods</li>
<li>A user can execute a withdrawal request using one of a payment
methods</li>
<li>A withdrawal can be executed as soon as possible or be scheduled to
execute later</li>
<li>After the service receives a request it stores a withdrawal object in
our DB and sends a request to a payment provider async. Note: for
this task we don't care about a transaction completion</li>
<li>We MUST 100% send notifications regarding any withdrawal status
(event, email etc)"</li>
</ul>
<p>That's my solution for the Models with JPA:</p>
<ul>
<li><p>USER</p>
<pre><code> @Entity(name = "User")
@Table(name = "user", uniqueConstraints = {@UniqueConstraint(name= "user_email_unique", columnNames = "email")})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id", updatable=false)
private Long id;
@OneToMany(mappedBy="user")
@Column(name = "payment_methods")
private List<PaymentMethod> paymentMethods;
@OneToOne(mappedBy = "user")
@JoinColumn(name = "account_id", nullable = false)
private Account account;
@Column(name = "first_name", nullable = false, columnDefinition = "TEXT")
private String firstName;
@Column(name = "last_name", nullable = false, columnDefinition = "TEXT")
private String lastName;
@Column(name = "email", nullable = false)
private String email;
@Column(name = "max_withdrawal_amount", nullable = false, columnDefinition = "DOUBLE")
private Double maxWithdrawalAmount;
}
</code></pre>
</li>
<li><p>ACCOUNT</p>
<pre><code> @Entity(name = "Account")
@Table(name = "account", uniqueConstraints = {
@UniqueConstraint(name = "account_account_number_unique", columnNames = "account_number") })
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "account_id")
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private User user;
@OneToMany(mappedBy = "account", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Transaction> transactionList = new ArrayList<>();
@Column(name = "account_number", nullable = false)
private Integer accountNumber;
@Column(name = "balance", nullable = false)
private double balance;
}
</code></pre>
</li>
<li><p>PAYMENT METHOD</p>
<pre><code> @Entity(name = "PaymentMethod")
@Table(name = "payment_methods")
public class PaymentMethod {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "payment_methods_id")
private Long id;
@ManyToOne
@JsonIgnore
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "payment_name", nullable = false, columnDefinition = "TEXT")
private String paymentName;
}
</code></pre>
</li>
<li><p>TRANSACTION</p>
<pre><code>@Entity(name = "Transaction")
@Table(name = "transaction")
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "transaction_id", updatable = false)
private Long id;
@Column(name = "comment", nullable = false, columnDefinition = "TEXT")
private String comment;
@ManyToOne
@JoinColumn(name = "accountNumber")
private Account account;
}
</code></pre>
</li>
<li><p>WITHDRAWAL</p>
<pre><code>@Entity(name = "Withdrawal")
@Table(name = "withdrawal")
public class Withdrawal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "withdrawals_id")
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Transaction transaction;
@ManyToOne
@JsonIgnore
@JoinColumn(name = "payment_methods_id", nullable = false)
private PaymentMethod paymentMethod;
@Column(name = "amount", nullable = false, columnDefinition = "DOUBLE")
private Double amount;
@Column(name = "created_at", nullable = false, columnDefinition = "DATE DEFAULT CURRENT_DATE")
private Instant createdAt;
@Column(name = "execute_at", nullable = false, columnDefinition = "DATE DEFAULT CURRENT_DATE")
private Instant executeAt;
@Enumerated(EnumType.STRING)
@Column(name = "withdrawal_status", nullable = false, columnDefinition = "TEXT")
private WithdrawalStatus status;
}
</code></pre>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T11:46:24.103",
"Id": "515300",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Welcome to code review! I have some comments about the data structure from banking point of view.</p>\n<ul>\n<li>Users usually have more than one account.</li>\n<li>E-mail is not a unique identifier.</li>\n<li>The assumption that <a href=\"https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/\" rel=\"nofollow noreferrer\">users have a first and last name</a> is wrong. :)</li>\n<li>Maximum withdrawal amount is usually a property of the account. Each account can have a different withdrawal limit. Usually there are even separate limits for internet payments and ATM withdrawals, but that may be beyond the scope of the exercise.</li>\n<li>Fetech type on account transactions should never be <code>eager</code>. There may be many thousands of transactions and loading the account would thus fetch them all. In fact, providing a list access to the complete transaction history is not feasible at all. Due to the volume, transaction history should be provided through a separate interface that supports paging and searching.</li>\n<li>Money should <a href=\"https://husobee.github.io/money/float/2016/09/23/never-use-floats-for-currency.html\" rel=\"nofollow noreferrer\">never be described as floting points</a>.</li>\n<li>What is the purpose of payment method in your system? Usually it means something like "debit card purchase", "ATM withdrawal", "online bank transfer" etc. All in all it probably should be an enumeration of values that is not associated to any specific user.</li>\n<li>A transaction involves two accounts: credit account for the recipient and debit account for the payer.</li>\n<li>Money withdrawal is a form of transaction. A transaction is identified as a money withdrawal by the transaction's type-attribute. The payment method may be related to this.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T11:30:03.567",
"Id": "515297",
"Score": "0",
"body": "Hi @TorbenPutkonen.\n\nMany thanks in advance for all the help you gave me here.\nI was refining my JPA Structure as you advised and so far I made some improvements. =)\n\nI'll go point by point:\n\n`code`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T05:00:15.163",
"Id": "261124",
"ParentId": "261115",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T19:43:15.347",
"Id": "261115",
"Score": "2",
"Tags": [
"java",
"spring",
"jpa"
],
"Title": "Bank exercise with Java Spring Boot and JPA"
}
|
261115
|
<p>I'm making a snake game for practicing the MVC pattern and also going out of my comfort zone (I'm in data processing / data science, mostly procedural coding)</p>
<p>The game is available in <a href="https://nabla-f.github.io/" rel="nofollow noreferrer">https://nabla-f.github.io/</a></p>
<p>This is a classical snake game, but with obstacles in the board (called blocks in the code)</p>
<p>This is my first time implementing MVC, so all comments are appreciated. Also, I'm having some trouble implementing the following things, cause I doesn't know where to put this functions (model, view or controller):</p>
<ul>
<li>A level class (to be able to create different stages)</li>
<li>UI messages doesn't related to game ("this works better in landscape mode", "welcome to the game", etc)</li>
<li>All things related to a future "app-alike" workflow (loading screens, auth screen, functions controlling this, etc)</li>
</ul>
<p>I'm ommiting implementation details because my question are centered about sw design rather than implementation of each function (e.g. I know that using canvas is better than render html elements in each cycle, etc). Here's the code:</p>
<h3>models.js</h3>
<pre><code>const DIRECTIONS = {
// an object representing directions (left, right, etc)
}
class Snake {
constructor() {
this.body = // Stores coordinates (an array) that represent snake position (i.e. an array of arrays)
this.len = this.body.length
this.head = this.body[0]
this.last = this.body[this.len-1]
this.direction = // Direction in which snake moves
this.toDigest = [] // Stores coordinates that snake should add in the following cycle
}
updateDirection(direction) {
this.direction = direction
}
updatePosition() {
// Updates snakes body to a new position according to his direction
}
updateData() {
this.len = this.body.length
this.head = this.body[0]
this.last = this.body[this.len-1]
}
eatFruit(fruitCoord) {
// Eats a fruit
}
checkToDigest() {
//
}
grow() {
this.body.push(Array.from(this.toDigest[0]))
this.toDigest.shift()
}
}
class Board {
constructor(width, height) {
this.width = width
this.height = height
this.fruits = new Fruits()
this.coords = // Stores coordinates of board. Each coordinate is an array
this.blocks = // Stores coordinates of blocking elements
}
generateFruits(forbiddenCoords) {
this.fruits.generateFruits()
}
removeFruits() {
this.fruits.removeFruits()
}
}
class Fruits {
constructor() {
this.fruits = [] // Stores a list of fruits
}
generateFruits(maxWidth, maxHeight, forbiddenCoords) {
// Generate a fruit coordinante that:
// - Isn't the same as a block coordinate
// - Isn't the same as a snake body coordinate
}
checkFruits() {
if (this.fruits) {return true}
else {return false}
}
removeFruits() {
// Remove a fruit for the list of fruits
}
}
export { Snake, Board, DIRECTIONS }
</code></pre>
<h3>views.js</h3>
<pre><code>
class BoardDrawer {
constructor(HTMLelem, snake, board) {
this.main = HTMLelem
this.board = board
this.snake = snake
}
drawCells() {
// draw cells of the board
}
drawSnake() {
// draws snake in board
}
drawBlocks() {
// draws blocks in board
}
drawFruits() {
// draws fruits in board
}
eraseSnake() {
// erase the snake in board
}
eraseFruits() {
// erase the fruits in board
}
}
export { BoardDrawer }
</code></pre>
<h3>controllers.js</h3>
<pre><code>import { DIRECTIONS } from './models.js'
class InputHandler {
constructor(deniedKey) {
this.deniedKey = deniedKey // last key pressed
}
userInput = (key) => {
// translates an arrow key into direction coordinate
}
}
class ObstaclesChecker {
constructor(snake, board) {
this.snake = snake.body
this.boundaries = {
left: -1,
right: board.width,
up: -1,
down: board.height,
}
this.snakeWithoutHead = []
this.blocks = board.blocks
this.fruits = board.fruits.fruits
}
checkBoundaryCollision(snakeHead) {
// Checks if snake collides with boundaries
}
checkSelfCollision(snakeHead) {
// Checks if snake collides with itself
}
checkBlockCollision(snakeHead) {
// Checks if snake collides with a block
}
checkFruitCollision(snakeHead) {
// Checks if snake collides with a fruit
}
}
export { InputHandler, ObstaclesChecker }
</code></pre>
<h3>app.js</h3>
<pre><code>import { Snake, Board } from './js/models.js'
import { BoardDrawer } from './js/views.js'
import { InputHandler, ObstaclesChecker } from './js/controllers.js'
// VARIABLE INIT
let boardHTMLelement = document.querySelector('#board');
let snake = new Snake()
let board = new Board(10, 10)
let obstacles = new ObstaclesChecker(snake, board)
let boardDrawer = new BoardDrawer(boardHTMLelement, snake, board)
let inputHandler = new InputHandler('ArrowLeft')
window.onload = () => {
// INITIALIZE GAME
boardDrawer.drawCells()
boardDrawer.drawBlocks()
board.generateFruits()
boardDrawer.drawFruits()
boardDrawer.drawSnake()
startGame()
};
/// GAME LOOP
function gameLoop(timeStamp){
// SNAKE AND FRUITS LOGIC BLOCK
boardDrawer.eraseSnake()
boardDrawer.eraseFruits()
// check digestion
if (snake.checkToDigest()) {
console.log('The snake has a new block')
snake.updatePosition()
snake.grow()
snake.updateData()
} else {
snake.updatePosition()
snake.updateData()
}
// check new fruit
if (obstacles.checkFruitCollision(snake.head)) {
console.log('The snake found a fruit')
snake.eatFruit(snake.head)
board.removeFruits()
board.generateFruits([snake.toDigest, board.blocks])
}
// COLLISION CHECKING BLOCK
if (
obstacles.checkSelfCollision(snake.head) ||
obstacles.checkBoundaryCollision(snake.head) ||
obstacles.checkBlockCollision(snake.head)
)
{
console.log('u lose')
loserFunction()
}
// DRAWING BLOCK
boardDrawer.drawFruits()
boardDrawer.drawSnake()
// Keep requesting new frames
setTimeout(window.requestAnimationFrame, 250, gameLoop);
}
/// Things that I doesn't know where to put in :(
let startGame = (event) => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.key)) {
window.requestAnimationFrame(gameLoop)
document.removeEventListener('keydown', startGame)
}
};
let startGameListener = () => {
document.addEventListener('keydown', startGame)
}
const loserFunction = () => {
// Delete the screen when user loses, show "you lose" message and so on...
}
</code></pre>
<p>If helps, here's the repo: <a href="https://github.com/nabla-f/nabla-f.github.io" rel="nofollow noreferrer">https://github.com/nabla-f/nabla-f.github.io</a></p>
<p>Many thanks in advance</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T11:02:01.547",
"Id": "515293",
"Score": "1",
"body": "The code provided in question does nothing. Please provide a working copy of the code you wish reviewed in the question. (linking a repo does not count as reviewable code as it is subject to change)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:15:13.783",
"Id": "515404",
"Score": "1",
"body": "To add to @Blindman67, this otherwise excellent question will be closed without working code"
}
] |
[
{
"body": "<p>I do not pretend to be true like uncle Bob :)</p>\n<p>However, I think your case you have to separate your controllers on main and another different.</p>\n<p><strong>preparation</strong></p>\n<p>app.js</p>\n<pre><code>const boardDrawerController = BoardDrawer(new BoardModel(), new BoardDrawerView(width, height));\nconst cellsController = CellsController(new CellsModel(), new CellsView());\nconst snakeController = new SnakeController(new SnakeModel(), new SnakeView());\n...\n\nconst mainController = new MainController(\nboardDrawerController, \ncellsController,\nsnakeController\n//another controllers\n);\n\nwindow.onload = () => { \n mainController.run();\n startGame()\n};\n</code></pre>\n<p>//MainController</p>\n<pre><code> function run() {\n boardDrawerController.draw();\n cellsController.draw();\n snakeController.draw();\n....\n }\n</code></pre>\n<p><strong>Modal</strong></p>\n<p>Let's think what is modal? Modal has logic and view too. Back to app.js and create ModalController</p>\n<pre><code> const modalController = ModalController(new ModalModel(), new ModalView());\n</code></pre>\n<p>What is <strong>Level</strong>, in simple - is only number 1,2,3 in general it is some logic without view (you can't draw Level you can redraw boardDrawer, Snake, Fruit another)</p>\n<pre><code>const Level = LevelController(new levelModel()); //without view\n</code></pre>\n<p>In finished we have MainController with simple controllers.</p>\n<p><strong>How communicate between controllers?</strong></p>\n<p>There are different ways, but in this simple case we can use pattern Observer.</p>\n<p>//observer.js</p>\n<pre><code>class Observer {\n constructor () {\n this.observers = []\n }\n\n subscribe (fn) {\n this.observers.push(fn)\n }\n\n unsubscribe () {\n this.observers = [];\n \n }\n\n emit(data) {\n this.observers.forEach(subscriber => subscriber(data))\n }\n}\n</code></pre>\n<p>//observable-of-controllers.js.</p>\n<pre><code>class ObservableOfControllers {\n static modalShow$ = new Observer(); \n static levelChange$ = new Observer();\n \n\n constructor(modalController, levelController) {\n this.modalController = modalController;\n this.levelController = levelController;\n\n }\n \n subscribes() {\n ObservableOfControllers.modalShow$\n .subscribe(data => this.this.modalController.show(data));\n \n ObservableOfControllers.levelChange$\n .subscribe(data => this.this.levelController.change(data))\n }\n}\n</code></pre>\n<p>add to app.js</p>\n<pre><code>const observableOfControllers = new ObservableOfControllers(\n modalController,\n levelController\n);\n\n\nwindow.onload = () => { \n mainController.run();\n observableOfControllers.subscribes();\n startGame()\n};\n</code></pre>\n<p>Emit event like be</p>\n<pre><code>class BoardModel {\n\n onError(message) {\n ObservableOfControllers.modalShow$.emit({\n type: 'error',\n message: message\n });\n\n }\n}\n</code></pre>\n<p>I hope this simple example will help you understand MVC</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T15:11:00.477",
"Id": "261193",
"ParentId": "261121",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T01:05:13.810",
"Id": "261121",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"mvc",
"snake-game"
],
"Title": "Snake game MVC (Vanilla JS) - Help separating concerns"
}
|
261121
|
<p><strong>Question:</strong>
Write a function to find the longest common prefix string amongst an array of strings.</p>
<p>If there is no common prefix, return an empty string "".</p>
<p>Example :</p>
<pre><code>Input: strs = ["flower","flow","flight"]
Output: "fl"
</code></pre>
<p>Source: <a href="http://Source:%20https://leetcode.com/problems/longest-common-prefix/" rel="nofollow noreferrer">https://leetcode.com/problems/longest-common-prefix/</a></p>
<p><strong>My Code:</strong></p>
<pre><code>public String longestCommonPrefix(String[] strs) {
StringBuilder lcp = new StringBuilder();
//compute min length
int minLength = Integer.MAX_VALUE;
for(String str:strs){
if (str.length() < minLength) {
minLength = str.length();
}
}
for (int i = 0; i < minLength;i++){
char cmp = strs[0].charAt(i);
for(String str:strs){
if (str.charAt(i) != cmp) {
return lcp.toString();
}
}
lcp.append(cmp);
}
return lcp.toString();
}
</code></pre>
<p>Questions:</p>
<ol>
<li>Current time complexity is O(mn) where n is number of strings and m is the min string length.
Can it be faster?</li>
<li>How to improve code style in general.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T23:32:55.433",
"Id": "515360",
"Score": "0",
"body": "You should look into the Trie data structure and fine tune it to your needs. The Trie data structure is used in applications such as spell check and your cell phone’s text word suggesting algorithm."
}
] |
[
{
"body": "<h3>1. Don't think too much about performance.</h3>\n<p>Worst performance problems arise because the coder <em>thought</em> something could be faster but she didn't consider that the JVM does runtime optimizations for her code.</p>\n<p>So always prefer writing <strong>readable code that works</strong>. Only step into performance optimization if you actually faced a performance issue and you have <strong>proven by measurement</strong> that this particular piece of code is the problem <strong>and</strong> the alternative approach really solves the problem.</p>\n<h3>2. Why are you inventing the wheel a 4th time?</h3>\n<p>The JVM has methods to compare strings. There is even a <code>startsWith()</code> method that would perfectly fit.</p>\n<h3>3 Structure your code</h3>\n<p>Your code has 2 obvious parts. The first one you marked with an inline comment.</p>\n<p>Better use methods with good names for this kind of structuring.</p>\n<h3>An alternative solution could look like this:</h3>\n<p>My solution made some assumption on the behavior of the methods in the <code>String</code> class which I verified with <em>spikes</em> coded as <em>JUnit</em> Tests along with the acceptance test using your given example.</p>\n<pre><code>import static org.junit.jupiter.api.Assertions.*;\n\nimport org.junit.jupiter.api.Test;\n\nclass LongestCommonPrefixTest {\n\n @Test\n void spike__does_StartsWith_returnTrueForTheEmptyString() {\n assertTrue("someWord".startsWith(""));\n }\n\n @Test\n void spike__does_substring_returnTheEmptyStringForEndIndexZero() {\n assertEquals("", "someWord".substring(0, 0));\n }\n\n @Test\n void spike__does_substring_returnShorterStringForLengthMinus1() {\n String someWord = "someWord";\n assertEquals("someWor", someWord.substring(0, someWord.length() - 1));\n }\n\n @Test\n void acceptanceTest() throws Exception {\n String[] strs = { "flower", "flow", "flight" };\n String longestCommonPrefix = //\n new LongestCommonPrefix().longestCommonPrefix(strs);\n assertEquals("fl", longestCommonPrefix);\n }\n\n}\n</code></pre>\n<p>And this is the solution I came up with:</p>\n<pre><code>public class LongestCommonPrefix {\n public String longestCommonPrefix(String[] strs) {\n String currentPrefix = selectFirstWordOrEmptyString(strs);\n for (String currentWord : strs) {\n currentPrefix = findCommonPrefixIn(currentPrefix, currentWord);\n }\n return currentPrefix;\n }\n\n private String selectFirstWordOrEmptyString(String[] strs) {\n return 0 == strs.length ? "" : strs[0];\n }\n\n private String findCommonPrefixIn(String currentPrefix, String currentWord) {\n while (!currentWord.startsWith(currentPrefix)) {\n currentPrefix = currentPrefix.substring(0, currentPrefix.length() - 1);\n }\n return currentPrefix;\n }\n}\n</code></pre>\n<p>A performance improvement could be possible if you always pass the shorter of <code>currentPattern</code> and <code>currentWord</code> as first parameter to the private method and the longer one as second. But as I wrote you shouldn't do that unless necessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T09:35:19.243",
"Id": "261130",
"ParentId": "261125",
"Score": "5"
}
},
{
"body": "<blockquote>\n<ol>\n<li>Can it be faster?</li>\n</ol>\n</blockquote>\n<p>I don't think there is an approach with a better complexity, but the runtime can be improved.</p>\n<p>Finding the shortest string can be avoided by adding one more condition in the for-loop:</p>\n<pre><code>public String longestCommonPrefix(String[] strs) {\n StringBuilder lcp = new StringBuilder();\n for (int i = 0; i < strs[0].length(); i++){\n char cmp = strs[0].charAt(i);\n for(String str: strs){\n if (i == str.length() || str.charAt(i) != cmp) {\n return lcp.toString();\n }\n }\n lcp.append(cmp);\n }\n return lcp.toString(); \n}\n</code></pre>\n<p>The condition <code>i == str.length()</code> returns as soon as the shortest string is consumed.</p>\n<p>I doubt that Leetcode is able to spot the difference in runtime but in theory, it should be faster. As @TimothyTruckle points out in the comments, better to measure it and see whether there is an actual improvement.</p>\n<hr />\n<blockquote>\n<ol start=\"2\">\n<li>How to improve code style in general.</li>\n</ol>\n</blockquote>\n<p>My suggestion is to format the code properly. There are some problems (medium and hard) that take more than few lines of code and can get quite messy without properly formatting the code.</p>\n<p>Unfortunately, Leetcode does not provide a built-in auto-formatting (as far as I know), but there are <a href=\"https://codebeautify.org/javaviewer\" rel=\"nofollow noreferrer\">websites</a> to help with it.</p>\n<h2>Finding the length of the shortest string</h2>\n<pre><code>int minLength = Integer.MAX_VALUE;\nfor(String str:strs){\n if (str.length() < minLength) {\n minLength = str.length();\n }\n}\n</code></pre>\n<p>This is an alternative using Streams:</p>\n<pre><code>int minLength = Arrays.stream(strs)\n .min(Comparator.comparingInt(String::length))\n .get().length();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T16:39:00.230",
"Id": "515339",
"Score": "1",
"body": "*\"but in theory, it should be faster.\"* **--** This sentence usually is as harmful as \"hold my beer\" ;o) **Never** choose a certain \"optimization\" because you *think* it might me faster. You always have to prove that by **measurement** in the real applications context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T16:41:10.613",
"Id": "515340",
"Score": "2",
"body": "*\"Finding the shortest string\"* **--** your suggestion does not find the shortest string, only its length. Would you mind to rename that section?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T01:02:33.613",
"Id": "515370",
"Score": "0",
"body": "@TimothyTruckle thanks for the suggestions, updated the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T15:58:54.503",
"Id": "261147",
"ParentId": "261125",
"Score": "3"
}
},
{
"body": "<h3>Is it fast enough?</h3>\n<p>Then don't worry about it.</p>\n<p>If you don't truly know, measure.</p>\n<p>Otherwise, remember that locality counts, so finish processing each string in one go, if you can.</p>\n<p>Finding the minimal length can reduce the worst case. But does it really matter for you?</p>\n<h3>Extract functions</h3>\n<p>Suddenly, you no longer need comments. And the result is more flexible, and solves more problems.</p>\n<pre><code>public int minLength(String[] strs) {\n int r = Integer.MAX_VALUE;\n for (String s : strs)\n r = Math.min(r, s.length());\n return r;\n}\n\npublic String maxPrefixCapped(String[] strs, int n) {\n if (strs.length == 0) return "";\n String x = strs[strs.length - 1];\n for (String s : strs) {\n int m = n;\n for (n = 0; n < m && s.charAt(n) == x.charAt(n); ++n)\n /* */;\n }\n return x.substring(0, n);\n}\n\npublic String maxPrefix(String[] strs) {\n return maxPrefixCapped(strs, minLength(strs));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T20:49:29.493",
"Id": "261160",
"ParentId": "261125",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261130",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T07:03:51.490",
"Id": "261125",
"Score": "3",
"Tags": [
"java",
"strings"
],
"Title": "Longest common prefix for set of strings"
}
|
261125
|
<h2>Description</h2>
<p>This is my attempt at writing a wrapper around Microsoft's research API (<em>evaluate</em> endoint).</p>
<p>My goals were:</p>
<ol>
<li>learn how to write classes</li>
</ol>
<ul>
<li>does it look ok overall?</li>
<li>should all methods except for <code>download_publications</code> and <code>save</code> be <em>private</em> (start with underscore)?</li>
</ul>
<ol start="2">
<li>make it easier to download entities from the API (use one method to get raw json data & processed tabular data; and another method to easily write either format to a file)</li>
</ol>
<p>I'm not a software engineer and never use classes for my tasks, but I guess it could be useful in cases like this - when I'm downloading and processing data?</p>
<p><em>how the code could be improved / do you see a better approach overall?</em></p>
<h2>Structure</h2>
<p><strong>logging.py</strong></p>
<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
import logging
def create_logger(name: str):
"""Create logger with DEBUG level & stream handler."""
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s [%(levelname)s]: %(message)s")
sh.setFormatter(formatter)
logger.addHandler(sh)
return logger
logger = create_logger("mag-api-wrapper")
</code></pre>
<p><strong>mag.py</strong></p>
<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
import json
import requests
import pandas as pd
from time import sleep
from .logger import logger
class MAG:
"""Papers retrieved from Microsoft Academic API."""
ENDPOINT = "https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate"
ENTITIES = {
"Id": "mag_ID",
"DN": "original_paper_title",
"Ti": "normalized_title",
"W": "normalized_words_in_title",
"AW": "normalized_words_in_abstract",
"RA": "restored_abstract",
"IA": "inverted_abstract",
"AA": "authors",
"AuId": "author_id",
"DAuN": "author_name",
"Y": "year_published",
"D": "isodate_published",
"DOI": "DOI",
"J": "journals",
"JN": "journal_name",
"PB": "publisher",
"ECC": "estimated_citation_count",
"F": "fields",
"DFN": "field_of_study",
"FN": "normalized_field_of_study",
}
def __init__(
self,
expr: str,
key: str,
count: int = 1_000,
offset: int = 0,
model: str = "latest",
attr: str = "DN,Ti,W,AW,IA,AA.AuId,AA.DAuN,Y,D,DOI,J.JN,PB,ECC,F.FN",
):
self.expr = expr
self.key = key
self.count = count
self.offset = offset
self.model = model
self.attr = attr
self.json_data = None
self.table_data = None
def download_publications(self):
"""Download entities."""
logger.info(f"Calling Microsoft Academic API with the query: {self.expr}")
records = list(self.yield_records())
self.json_data = [item["raw"] for item in records]
self.table_data = (
pd.DataFrame([item["processed"] for item in records])
.drop(["prob", "logprob"], axis=1)
.rename(columns=MAG.ENTITIES)
)
logger.info(f"Downloaded {self.table_data.shape[0]} entries in total.")
def save(self, tocsv=None, tojson=None):
"""Write fetched data to files."""
if tocsv is not None and self.table_data is not None:
self.table_data.to_csv(tocsv, index=False)
if tojson is not None and self.json_data is not None:
with open(tojson, "w", encoding="utf-8") as f:
json.dump(self.json_data, f, ensure_ascii=False, indent=4)
def fetch(self, url, params):
"""Make a remote call to Microsoft Academic API."""
return requests.get(url, params).json()
def restore_abstract(self, abstract):
"""Restore inverted abstract to its original form."""
words = abstract["InvertedIndex"]
total_words = abstract["IndexLength"]
text = []
for position in range(0, total_words):
for word, positions in words.items():
if position in positions:
text.append(word)
return " ".join(text)
def process(self, entities):
"""Process entities, including unnesting JSON and restoring
inverted abstracts to their raw form."""
for item in entities:
entity = item.copy()
if "IA" in entity.keys():
entity["RA"] = self.restore_abstract(entity["IA"])
del entity["IA"]
if "AA" in entity.keys():
entity["DAuN"] = ";".join(item["DAuN"] for item in entity["AA"])
entity["AuId"] = ";".join(str(item["AuId"]) for item in entity["AA"])
del entity["AA"]
if "F" in entity.keys():
entity["FN"] = ";".join(item["FN"] for item in entity["F"])
del entity["F"]
if "J" in entity.keys():
if isinstance(entity["J"], dict):
entity["JN"] = entity["J"]["JN"]
elif isinstance(entity["J"], list):
entity["JN"] = ";".join(item["JN"] for item in entity["J"])
else:
entity["JN"] = entity["J"]
del entity["J"]
yield {"raw": item, "processed": entity}
def yield_records(self):
"""Fetch all entities for a given query expression."""
params = {
"expr": self.expr,
"offset": self.offset,
"count": self.count,
"attributes": self.attr,
"model": self.model,
"subscription-key": self.key,
}
downloaded = 0
while True:
data = self.fetch(MAG.ENDPOINT, params)
if data["entities"] == []:
break
yield from self.process(data["entities"])
params["offset"] += self.count
downloaded += len(data["entities"])
logger.info(f"fetched {downloaded} entries.")
sleep(3.1)
</code></pre>
<p><strong>__init__.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from .mag import MAG
__version__ = "0.1.0"
</code></pre>
<h2>Usage</h2>
<pre class="lang-py prettyprint-override"><code>>>> from mag import MAG
>>> pubs = MAG(
expr="And(And(AW='organized', AW='crime', Y=[2000, 2020]), Composite(F.FN='political science'))",
key="2q3b955bfa210f9aa1a4eq35fa63378c" #dummy key
)
>>> pubs.download_publications()
>>> pubs.save(tocsv="data.csv")
>>> pubs.save(tojson="data.json")
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T07:49:44.813",
"Id": "261127",
"Score": "0",
"Tags": [
"python",
"object-oriented",
"api"
],
"Title": "Microsoft Academic API wrapper"
}
|
261127
|
<p>I understand there is <a href="https://codereview.stackexchange.com/questions/222292/character-picture-grid-exercise-automatetheboringstuff">another question</a> on this already, however this is what I coded and wanted to know if this would raise any red flags?</p>
<p>Regarding the Character picture exercise located at the end the following page:
<a href="https://automatetheboringstuff.com/chapter4/" rel="nofollow noreferrer">https://automatetheboringstuff.com/chapter4/</a></p>
<blockquote>
<p>Say you have a list of lists where each value in the inner lists is a
one-character string, like this:</p>
<pre><code>grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
</code></pre>
<p>You can think of <code>grid[x][y]</code> as being the character at the x- and
y-coordinates of a “picture” drawn with text characters. The <code>(0, 0)</code>
origin will be in the upper-left corner, the x-coordinates increase
going right, and the y-coordinates increase going down.</p>
<p>Copy the previous grid value, and write code that uses it to print the
image.</p>
<pre><code>..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
</code></pre>
</blockquote>
<p>It's different in that it doesn't hard-code the length of the list.</p>
<pre><code>grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
x = 0
y = 0
for y in range(len(grid[x])):
for x in range(len(grid)):
print(grid[x][y],end='')
print()
</code></pre>
<p>Thanks for the help and let me know if this is not appropriate to post!</p>
|
[] |
[
{
"body": "<p>It's wasteful to use <code>range()</code> and then only use the result for indexing.</p>\n<p>Instead, just iterate directly over the values:</p>\n<pre><code>for col in range(len(grid[0])):\n for row in grid:\n print(row[col],end='')\n print()\n</code></pre>\n<p>We can simplify, though - use the <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> function to transpose the array:</p>\n<pre><code>transposed = zip(*grid)\n\nfor row in transposed:\n for col in row:\n print(col,end='')\n print()\n</code></pre>\n<p>The next simplification is instead of printing one character at a time, we can use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join</code></a> to form strings for printing:</p>\n<pre><code>for row in zip(*grid):\n print(''.join(row))\n</code></pre>\n<p>And we can join all the rows using <code>'\\n'.join()</code>, giving this final version:</p>\n<pre><code>print('\\n'.join(''.join(x) for x in zip(*grid)))\n</code></pre>\n<p>Equivalently, using <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a>:</p>\n<pre><code>print('\\n'.join(map(''.join, zip(*grid))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T05:20:33.180",
"Id": "515375",
"Score": "0",
"body": "This is great, thanks @toby. \n\nCan I ask why using range here is wasteful? the idea was to build a code that can work with any number of rows/columns.\n\nI got to learn a lot here, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T07:02:49.390",
"Id": "515381",
"Score": "1",
"body": "Perhaps \"wasteful\" isn't exactly the right word. My point is that we don't need to count the columns and create indexes when it's simpler to iterate the columns directly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T12:05:00.837",
"Id": "261134",
"ParentId": "261128",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T08:22:45.130",
"Id": "261128",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Automate The Boring Stuff - Character Picture Grid"
}
|
261128
|
<p>I and Abishek Joshi forked a repo, and improved a lot of code in it and published it, we did that because that original repo was last commited on 2020 december.
For more info on history you can visit the <a href="https://github.com/Readme-Workflows/recent-activity#history" rel="nofollow noreferrer">repo readme's history section</a></p>
<p>Anyway this action gets the recent activity of a user or org and adds a ordered list to the readme.
The code has a lot of files, so I will share the main files code here. For other code you can see the <a href="https://github.com/Readme-Workflows/recent-activity/tree/main/src" rel="nofollow noreferrer">repo</a></p>
<p><code>index.js</code>:</p>
<pre><code>/**
* Copyright (c) 2020 James George
* Copyright (c) 2021 The Readme-Workflows organisation and Contributors
*/
const fs = require("fs");
const { Toolkit } = require("actions-toolkit");
// configuration
const { username, readme_file, max_lines } = require("./config");
// functions
const appendDate = require("./functions/appendDate");
const commitFile = require("./functions/commitFile");
const filterContent = require("./functions/filterContent");
// accepted events
const serializers = require("./serializers");
Toolkit.run(
async (tools) => {
// Get the user's public events
tools.log.debug(`Getting activity for ${username}`);
const events = await tools.github.activity.listPublicEventsForUser({
username: username,
per_page: 100,
});
tools.log.debug(`${events.data.length} events found for ${username}.`);
let eventData = events.data
// Filter out any boring activity
.filter((event) => serializers.hasOwnProperty(event.type));
let content = filterContent(eventData);
let readmeContent;
try {
readmeContent = fs.readFileSync(readme_file, "utf-8").split("\n");
} catch (err) {
return tools.exit.failure(`Couldn't find the file named ${readme_file}`);
}
// Find the index corresponding to <!--RECENT_ACTIVITY:start--> comment
let startIdx = readmeContent.findIndex(
(content) => content.trim() === "<!--RECENT_ACTIVITY:start-->"
);
// Early return in case the <!--RECENT_ACTIVITY:start--> comment was not found
if (startIdx === -1) {
return tools.exit.failure(
"Couldn't find the <!--RECENT_ACTIVITY:start--> comment. Exiting!"
);
}
// Find the index corresponding to <!--RECENT_ACTIVITY:end--> comment
const endIdx = readmeContent.findIndex(
(content) => content.trim() === "<!--RECENT_ACTIVITY:end-->"
);
if (!content.length) {
tools.exit.success("No events found. Leaving readme unchanged.");
}
if (content.length < max_lines) {
tools.log.info(`Found less than ${max_lines} activities`);
}
if (startIdx !== -1 && endIdx === -1) {
// Add one since the content needs to be inserted just after the initial comment
startIdx++;
content.forEach((line, idx) =>
readmeContent.splice(startIdx + idx, 0, `${idx + 1}. ${line}`)
);
// Append <!--RECENT_ACTIVITY:end--> comment
readmeContent.splice(
startIdx + content.length,
0,
"<!--RECENT_ACTIVITY:end-->"
);
readmeContent = appendDate(readmeContent);
// Update README
fs.writeFileSync(readme_file, readmeContent.join("\n"));
// Commit to the remote repository
try {
await commitFile();
} catch (err) {
tools.log.debug("Something went wrong");
return tools.exit.failure(err);
}
tools.exit.success("Wrote to README");
}
// const oldContent = readmeContent.slice(startIdx + 1, endIdx).join("\n");
// const newContent = content
// .map((line, idx) => `${idx + 1}. ${line}`)
// .join("\n");
// // if (oldContent.trim() === newContent.trim())
// // tools.exit.success("No changes detected.");
startIdx++;
// Recent GitHub Activity content between the comments
const readmeActivitySection = readmeContent.slice(startIdx, endIdx);
if (!readmeActivitySection.length) {
content.some((line, idx) => {
// User doesn't have 5 public events
if (!line) {
return true;
}
readmeContent.splice(startIdx + idx, 0, `${idx + 1}. ${line}`);
});
tools.log.success("Wrote to README");
} else {
// It is likely that a newline is inserted after the <!--RECENT_ACTIVITY:start--> comment (code formatter)
let count = 0;
readmeActivitySection.some((line, idx) => {
// User doesn't have 5 public events
if (!content[count]) {
return true;
}
if (line !== "") {
readmeContent[startIdx + idx] = `${count + 1}. ${content[count]}`;
count++;
}
});
tools.log.success("Updated README with the recent activity");
}
readmeContent = appendDate(readmeContent);
// Update README
fs.writeFileSync(readme_file, readmeContent.join("\n"));
// Commit to the remote repository
try {
await commitFile();
} catch (err) {
tools.log.debug("Something went wrong");
return tools.exit.failure(err);
}
tools.exit.success("Pushed to remote repository");
},
{
event: ["schedule", "workflow_dispatch"],
secrets: ["GITHUB_TOKEN"],
}
);
</code></pre>
<p><code>config.js</code>:</p>
<pre><code>/**
* Copyright (c) 2020 James George
* Copyright (c) 2021 The Readme-Workflows organisation and Contributors
*/
const core = require("@actions/core");
const parseYaml = require("./functions/parseYaml.js");
const defaultVals = {
username: core.getInput("GH_USERNAME"),
commit_msg: "⚡ Update README with the recent activity",
max_lines: 5,
readme_file: "./README.md",
disabled_events: ["comments"],
url_text: "{REPO}{ID}",
date: {
timezone: "0",
text: "Last Updated: {DATE}",
format: "dddd, mmmm dS, yyyy, h:MM:ss TT",
},
comments: " Commented on {ID} in {REPO}",
issue_opened: "❗️ Opened issue {ID} in {REPO}",
issue_closed: "✔️ Closed issue {ID} in {REPO}",
pr_opened: " Opened PR {ID} in {REPO}",
pr_closed: "❌ Closed PR {ID} in {REPO}",
pr_merged: " Merged PR {ID} in {REPO}",
create_repo: " Created new repository {REPO}",
fork_repo: " Forked {FORK} from {REPO}",
wiki_create: " Created new wiki page {WIKI} in {REPO}",
added_member: " Became collaborator on {REPO}",
changes_approved: " Approved {ID} in {REPO}",
changes_requested: " Requested changes in {ID} in {REPO}",
new_release: "✌️ Released {ID} in {REPO}",
new_star: "⭐ Starred {REPO}",
};
const userVals = parseYaml(core.getInput("CONFIG_FILE"));
if (userVals.settings) {
userVals.settings.date = { ...defaultVals.date, ...userVals.settings.date };
}
let conf = {
...defaultVals,
...userVals.settings,
...userVals.messages,
};
let disabled = [];
conf.disabled_events.forEach((event) => {
disabled.push(event.trim().toLowerCase());
});
conf.disabled_events = disabled;
const urlPrefix = "https://github.com";
module.exports = {
...conf,
urlPrefix,
};
</code></pre>
<p><code>serializers.js</code>:</p>
<pre><code>/**
* Copyright (c) 2020 James George
* Copyright (c) 2021 The Readme-Workflows organisation and Contributors
*/
const { disabled_events } = require("./config");
// Events
const IssueCommentEvent = require("./events/IssueCommentEvent");
const CommitCommentEvent = require("./events/CommitCommentEvent");
const PullRequestReviewCommentEvent = require("./events/PullRequestReviewCommentEvent");
const IssuesEvent = require("./events/IssuesEvent");
const PullRequestEvent = require("./events/PullRequestEvent");
const CreateEvent = require("./events/CreateEvent");
const ForkEvent = require("./events/ForkEvent");
const GollumEvent = require("./events/GollumEvent");
const MemberEvent = require("./events/MemberEvent");
const PullRequestReviewEvent = require("./events/PullRequestReviewEvent");
const ReleaseEvent = require("./events/ReleaseEvent");
const WatchEvent = require("./events/WatchEvent");
const serializers = {};
if (!disabled_events.includes("comments")) {
serializers.IssueCommentEvent = IssueCommentEvent;
serializers.CommitCommentEvent = CommitCommentEvent;
serializers.PullRequestReviewCommentEvent = PullRequestReviewCommentEvent;
}
if (!disabled_events.includes("issues")) {
serializers.IssuesEvent = IssuesEvent;
}
if (!disabled_events.includes("pr")) {
serializers.PullRequestEvent = PullRequestEvent;
}
if (!disabled_events.includes("create_repo")) {
serializers.CreateEvent = CreateEvent;
}
if (!disabled_events.includes("fork")) {
serializers.ForkEvent = ForkEvent;
}
if (!disabled_events.includes("wiki")) {
serializers.GollumEvent = GollumEvent;
}
if (!disabled_events.includes("member")) {
serializers.MemberEvent = MemberEvent;
}
if (!disabled_events.includes("review")) {
serializers.PullRequestReviewEvent = PullRequestReviewEvent;
}
if (!disabled_events.includes("release")) {
serializers.ReleaseEvent = ReleaseEvent;
}
if (!disabled_events.includes("star")) {
serializers.WatchEvent = WatchEvent;
}
module.exports = serializers;
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T11:28:40.193",
"Id": "261131",
"Score": "0",
"Tags": [
"node.js"
],
"Title": "A recent activity github action written in node.js"
}
|
261131
|
<p>I'm testing here ways to find prime number. But it looks weird because of repeating parts. Are there any options to make it prettier. Probably I should use cycle or wrap it in an interface.</p>
<pre><code> start = System.nanoTime();
res = PoKrestyanski.letsUseit(numbers);
duration = (System.nanoTime() - start) / 1_000_000;
System.out.println(res);
System.out.println("Time spent: " + duration + " ms" + "\n\n");
//using threads
int nthreads = 4;
PrimeThreads<Integer> threadsHandler = new PrimeThreads<>(nthreads);
start = System.nanoTime();
PrimeThreads.Answer<Integer> answer = threadsHandler.runThreads(numbers, nthreads, pred);
duration = (System.nanoTime() - start) / 1_000_000;
res = answer.isAnswerFound();
System.out.println(res);
System.out.println("Time spent: " + duration + " ms" + "\n\n");
//using Parallel Stream
//System.out.println("parallelStream");
start = System.nanoTime();
Stream<Integer> parStream = numbers.parallelStream();
res = parStream.anyMatch(pred);
duration = (System.nanoTime() - start) / 1_000_000;
System.out.println(res);
System.out.println("Time spent: " + duration + " ms");
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T18:48:11.327",
"Id": "515556",
"Score": "0",
"body": "You're not measuring execution time. You're measuring setup time and JVM warmup time. Take a look at this [Stack Overflow question and answers](https://stackoverflow.com/questions/8423789/benchmarking-inside-java-code) for more information about benchmarking code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T11:52:56.067",
"Id": "261132",
"Score": "1",
"Tags": [
"java"
],
"Title": "I'm testing here ways to find prime number. But it looks weird because of repeating parts"
}
|
261132
|
<p>I am trying to implement a cache which can be persisted. Also, some of the functions that I am trying to cache takes arguments that are not python objects (external library objects). But they seem to have a <code>hash</code> value. My first try was to use <code>lru_cache</code> but it didn't have an option to persist across sessions. Then I stumbled upon <a href="https://stackoverflow.com/a/15587418/3679377">this</a> answer which explained a way to create a custom decorator to cache the function results. I made some minor changes to it and came up with this decorator (which can take arguments) now.</p>
<pre class="lang-py prettyprint-override"><code>def cached(maxsize=None, hashkey=True, persist=False):
"""Decorator method to cache an expensive function
Args:
maxsize (int): The maximum number of cached results to store
if None, the size is indefinite.
hashkey (bool): If the arguments of the function are objects
which cannot be pickled, use the hashkey option which will
hash the arguments.
persist (bool): Write the cached results to the disk so that
it can be read in even after the session has ended.
Returns:
Decorator function
"""
def outer(func):
func.cache = {}
func.cache_file = f"{func.__name__}.cache"
@wraps(func)
def wrapper(*args):
if hashkey:
key = hash(args)
else:
key = args
try:
return func.cache[key]
except KeyError:
try:
if persist:
with open(func.cache_file, "rb") as cachefile:
func.cache = pickle.load(cachefile)
return func.cache[key]
except (KeyError, FileNotFound):
func.cache[key] = result = func(*args)
if maxsize and len(func.cache) > maxsize:
func.cache.pop(next(iter(func.cache))) # removes the first item
if persist:
with open(func.cache_file, "wb") as cachefile:
pickle.dump(func.cache, cachefile)
return result
return wrapper
return outer
</code></pre>
<p>The functions that I am planning to cache may be called at most 10000 times with a given cache file.</p>
<p>Here are my questions:</p>
<ol>
<li>Is there anything obviously wrong with this code?</li>
<li>Is hashing the arguments a bad idea?</li>
<li>Are there any obvious places where I can store the cache file?</li>
</ol>
|
[] |
[
{
"body": "<p>It seems rather inefficient to reload the cache file on every cache miss. The last part of <code>wrapper()</code> saves the file whenever the cache is updated, so the cache and file should always be in synch. Loading the file could be moved into <code>outer()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T19:34:05.290",
"Id": "261156",
"ParentId": "261133",
"Score": "1"
}
},
{
"body": "<h1>Explanation</h1>\n<p>As @RootTwo mentioned, there are two things that can be improved:</p>\n<ul>\n<li><p>Loading the file could be done whenever the decorator is being applied. There is no need to read from the cache file whenever a key is not found (unless you plan modifying contents from elsewhere in the code)</p>\n</li>\n<li><p>Updating the cached file every miss is very inefficient</p>\n</li>\n</ul>\n<p>I would also argue that storing the cache file in the working directory is probably not the best idea: if you run your code from a different directory, cached data will not be available</p>\n<p>That's regarding the code itself. Now, regarding code style, I would personally swith to the <code>pathlib</code> library, rather than using the raw <code>open</code> function.</p>\n<h1>Solution</h1>\n<p>Now, the solution I propose is as follows:</p>\n<ul>\n<li><p>Read the cache file when applying the decorator</p>\n</li>\n<li><p>Write the cache file on exit (using module <code>atexit</code>)</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import atexit\nimport pickle\nfrom pathlib import Path\nfrom functools import wraps\n\n\ndef cached(maxsize=None, hashkey=True, persist=False):\n """Decorator method to cache an expensive function\n\n Args:\n maxsize (int): The maximum number of cached results to store\n if None, the size is indefinite.\n hashkey (bool): If the arguments of the function are objects\n which cannot be pickled, use the hashkey option which will\n hash the arguments.\n persist (bool): Write the cached results to the disk so that\n it can be read in even after the session has ended.\n\n Returns:\n Decorator function\n """\n def outer(func):\n func.cache = {}\n func.cache_file_path = Path(f"{func.__name__}.cache")\n\n if persist:\n if func.cache_file_path.exists():\n with func.cache_file_path.open("rb") as cachefile:\n func.cache = pickle.load(cachefile)\n\n def persits_cache_on_exit():\n with func.cache_file_path.open("wb") as cachefile:\n pickle.dump(func.cache, cachefile)\n atexit.register(persits_cache_on_exit)\n\n @wraps(func)\n def wrapper(*args):\n if hashkey:\n key = hash(args)\n else:\n key = args\n\n try:\n return func.cache[key]\n except KeyError:\n func.cache[key] = result = func(*args)\n\n if maxsize and len(func.cache) > maxsize:\n # removes the first item\n func.cache.pop(next(iter(func.cache)))\n\n return result\n return wrapper\n return outer\n</code></pre>\n<p>Regarding where to store the cache files, if you intend to use this decorator in just one project, you could probably store cache files relative to the project files (If you do not know how to do this, I'd be happy to point you in the right direction). If you intend to use it elsewhere, you could maybe store it in a temporary directory such as <code>/temp/</code> in *nix.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T06:36:20.563",
"Id": "515378",
"Score": "0",
"body": "Thanks. I think this will help. Any comments on hashing the arguments?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T20:21:58.253",
"Id": "261158",
"ParentId": "261133",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261158",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T12:04:39.460",
"Id": "261133",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"cache"
],
"Title": "Python persistant cache for non-pythonic objects"
}
|
261133
|
<p>I am attaching the code here. I am very new to VBA and trying to do a complex calculation using Macro. Please help me improve the speed of the attached code. The code works fine and produces the end output. The program is intended to do the following. I am calling the below two subs after data is filled in the sheet.
Copy and paste two sets of variable in two specified cell
Excel does a complex calculation using FILTER command & other INDEX and MATCH Formulas
Copy and paste the output to a location
This is required to done 1500 times for two sets of data. Present execution time is 10 minutes.</p>
<pre><code>Sub CF_Amb_Pr_NG()
Dim intX As Integer
Dim copyRng As String
X = 43
For X = 40 To 1539
Sheets("CC_NG_APr").Select
Range("C2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R" & X & "C2"
Range("C3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R" & X & "C3"
Range("E2").Select
Selection.Copy
Let copyRng = "D" & X
Range(copyRng).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next X
End Sub
Sub CF_RH_NG()
Dim intX As Integer
Dim copyRng As String
X = 33
For X = 32 To 1531
Sheets("CC_NG_RH").Select
Range("C2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R" & X & "C2"
Range("C3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R" & X & "C3"
Range("E2").Select
Selection.Copy
Let copyRng = "D" & X
Range(copyRng).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next X
End Sub
</code></pre>
<p><a href="https://i.stack.imgur.com/6YHnQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6YHnQ.png" alt="Calculations used in for determining E2' using values for C2&C3`" /></a></p>
<p>Attached screenshot of sheet in formula mode to explain what exactly is going on in <code>E2</code> based on the values fed in <code>C2</code> & <code>C3</code>. Basis the value entered in <code>C2</code> & <code>C3</code>, formula to be chosen to calculate <code>E2</code> is chosen and final value is shown. I need to get value in <code>E2</code> for 3000 sets of data in <code>C2</code> & <code>C3</code></p>
<p>Thanks a lot for helping !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:24:55.407",
"Id": "515305",
"Score": "0",
"body": "Did you post the whole code, or did you post too much ? I don't see where CF_RH_NG is actually used in this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:27:11.560",
"Id": "515306",
"Score": "0",
"body": "The first procedure is missing the signature and possibly some additional lines of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:32:41.883",
"Id": "515307",
"Score": "0",
"body": "@Anonymous - I am calling these two subs in the excel to perform calculation after data entry is completed. The calculations are done in two different sheets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:33:56.950",
"Id": "515308",
"Score": "0",
"body": "@FreeMan - Please help here. I am getting the result i need but it takes forever."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:36:38.663",
"Id": "515309",
"Score": "0",
"body": "COM and Excel Automation is known to be slow. Writing cell-by-cell is VERY slow. Is there any way you can write to an entire range once rather than individual rows?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:39:32.017",
"Id": "515311",
"Score": "0",
"body": "@RickDavin - Thanks Rick. I have tried to copy range in one go but couldn't manage as this would require the calculation excel is doing as a code, which I am unable to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:42:01.263",
"Id": "515312",
"Score": "0",
"body": "One thing that will definitely help is to [avoid using `.Select`](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:58:43.757",
"Id": "515317",
"Score": "0",
"body": "@FreeMan - Thanks ! Can you suggest an edit in the code in question to avoid using `.select`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:05:30.673",
"Id": "515320",
"Score": "0",
"body": "That's a good question and answers for you to study and understand for yourself so you can recognize when you're falling into that path in the future. TBH, it looks like your code was generated by the Macro Recorder. There's nothing whatsoever wrong with that - it'll help teach you how things work. The other, _critical_ thing it will teach you is how to write _very crappy_ code. The MR is _not_ known for generating efficient code, it simply records each UI thing that you do - turn the MR on and hit `<down arrow>` a few times and see what it gives you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:14:14.867",
"Id": "515328",
"Score": "0",
"body": "@FreeMan - appreciate the advice. Will try to break my head around it."
}
] |
[
{
"body": "<p>As best I can tell, <code>Sub CF_Amb_Pr_NG()</code> sets cells <code>C2</code> and <code>C3</code> to formulas that changes with each iteration through the loop, then ends with them set to <code>"=R1539C2"</code>.</p>\n<p>You then copy cell <code>E2</code> to each row in column <code>D</code> from 40 to 1539.</p>\n<p>Unless there's something going on with the value in <code>C2</code> and <code>C3</code> that somehow impact <code>E2</code>, if you <em>really</em> want to stick with the <code>.Select</code> and <code>.PasteSpecial</code> this should do the trick:</p>\n<pre><code>Sub test()\n\n With ThisWorkbook.Worksheets("Sheet1")\n .Range("E2").Select\n Selection.Copy\n .Range("D40:D1539").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False\n .Range("C2").FormulaR1C1 = "=R1539C2"\n .Range("C3").FormulaR1C1 = "=R1539C3"\n End With\n\nEnd Sub\n</code></pre>\n<p>Otherwise, I'd suggest this which is even easier:</p>\n<pre><code>Sub test()\n\n With ThisWorkbook.Worksheets("Sheet1")\n .Range("d40:d1539").Value2 = .Range("e2").Value2\n .Range("C2").FormulaR1C1 = "=R1539C2"\n .Range("C3").FormulaR1C1 = "=R1539C3"\n End With\n\nEnd Sub\n</code></pre>\n<p>It copies <code>E2</code> to <code>D40</code> through <code>D1539</code>, then it sets <code>C2</code> and <code>C3</code> to the final values they have in your loop.</p>\n<p>Make a similar change to <code>Sub CF_RH_NG()</code>.</p>\n<hr>\n<p><em>If</em> the value in <code>E2</code> changes with the values as determined in <code>C2</code> and <code>C3</code> for each iteration through the loop, I'd <em>strongly</em> suggest that you add a helper column (out in column <code>Z</code> or <code>LLL</code> or someplace) that calculates <code>E2</code> for the <em>current</em> row, then simply make the formula in <code>D40</code> read <code>=LLL40</code> (manually copy that formula down to <code>D1539</code> <em>one</em> time), and be done with it - no need for code at all.</p>\n<hr> \n<p>These simple assignments should execute in a second or two (Excel is notably slow in copying in my recent experience), but significantly less than the 10 minutes you're currently experiencing.</p>\n<hr>\n<p>Based on the update, a loop <em>is</em> required, avoiding <code>.Select</code> will still help performance:</p>\n<pre><code>Sub test()\n\n On Error GoTo CleanExit\n' Application.ScreenUpdating = False\n Dim row As Long\n For row = 40 To 1539\n With Sheet1\n .Range("C2").FormulaR1C1 = "=R" & CStr(row) & "C2"\n .Range("C3").FormulaR1C1 = "=R" & CStr(row) & "C3"\n .Range.Cells.Item(4, row).Value2 = .Range("e2").Value2\n End With\n Next\n \nCleanExit:\n Application.ScreenUpdating = True\n \nEnd Sub\n</code></pre>\n<p>Note in this case the <code>With Sheet1</code> - you can use the worksheet's <code>(Name)</code> property as a direct reference to it (you'll have to modify this for <em>your</em> <code>Workbook</code>):</p>\n<p><a href=\"https://i.stack.imgur.com/NEDky.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NEDky.png\" alt=\"enter image description here\" /></a></p>\n<p>Note that this is <em>not</em> the same as the <code>.Name</code> of the worksheet as displayed on the "tab":<a href=\"https://i.stack.imgur.com/NMkZZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NMkZZ.png\" alt=\"enter image description here\" /></a></p>\n<p>Additionally, I've added <code>Application.ScreenUpdating = False</code>, but left it commented out for now. Make sure your new code is working properly before enabling this. This will prevent Excel from refreshing the screen with each step it takes. Removing all the UI activity reduces the amount of execution time (it's not a panacea, though). Note the addition of the <code>On Error Goto...</code> to ensure that if anything were to go wrong during execution, it will reenable <code>ScreenUpdating</code>. If you don't weird and confusing things happen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:06:45.310",
"Id": "515322",
"Score": "0",
"body": "For info on `.Value` vs `.Value2`, see [this good SO Q&A](https://stackoverflow.com/questions/17359835/what-is-the-difference-between-text-value-and-value2)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:11:50.993",
"Id": "515325",
"Score": "0",
"body": "I don't think this would work. See the thing is the formula to be used to calculate `E2` is dependent on the values fed into `C2` & `C3`. Based on the data in `C2` & `C3`, Formula to be used in `E2` is chosen and subsequently `E2` is calculated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:14:11.487",
"Id": "515327",
"Score": "0",
"body": "Then use the suggestion between the two lines - instead of calculating them in a function, have hard-coded calculations set off to the side somewhere in a hidden/locked column and let Excel just do its thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T14:29:29.527",
"Id": "515330",
"Score": "0",
"body": "Added an image of the excel to explain what actually is going on in `C2` & `C3` to generate `E2`. I have tried using a helper column but could not make it work."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:59:21.257",
"Id": "261141",
"ParentId": "261135",
"Score": "0"
}
},
{
"body": "<p>Thanks a lot @freeman & the community !! Implemented solution by @freeman with the below with a single line change. Could not get to work the <code>.Range.Cells.Item(4, row).Value2 = .Range("e2").Value2</code> changed this to <code>.Range(pst_row).Value2 = .Range("e2").Value2</code> added one more variable <code>pst_row</code> rest it works like charm. Runtime < 10 seconds. Also disabled screen update.</p>\n<pre><code>Dim row As Long\n Dim pst_row As String\n For row = 42 To 1541\n With Sheet3\n Let pst_row = "D" & row\n .Range("C2").FormulaR1C1 = "=R" & CStr(row) & "C2"\n .Range("C3").FormulaR1C1 = "=R" & CStr(row) & "C3"\n .Range(pst_row).Value2 = .Range("e2").Value2\n End With\n Next\nEnd Sub\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T06:42:27.707",
"Id": "261175",
"ParentId": "261135",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "261141",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T12:35:26.487",
"Id": "261135",
"Score": "0",
"Tags": [
"performance",
"beginner",
"vba",
"excel",
"macros"
],
"Title": "Improving Speed of VBA Code - Copy/paste two sets of variable, Excel does a calculation, returns a value then copy/paste the output value"
}
|
261135
|
<p>Time ago I had a header implemented with a Bootstrap carousel: You know, something like this:</p>
<pre><code><div class="carousel">
<div class="item"><img src="pic1.jpg"></div>
<div class="item"><a href="example.com"><img src="pic2.jpg"></a></div>
</div>
</code></pre>
<p>Pay attention to that link on "pic2.jpg", this will be fun...</p>
<p>Recently, I have been asked to use <code><picture></code> elements, so now it is posible to display images for mobile devices:</p>
<pre><code><div class="item">
<picture>
<source media="(max-width: 576px)" srcset="pic1-small.jpg">
<img src="pic1.jpg">
</picture>
</div>
<div class="item">
<picture>
<source media="(max-width: 576px)" srcset="pic2-small.jpg">
<img src="pic2.jpg">
</picture>
</div>
</code></pre>
<p>And here is the tricky question: I need to add a link only in the mobile image (pic2-small.jpg).</p>
<p>(Well, in fact could be links on every image, or none at all, only in the mobile image, only in the desktop image... This is managed by the administrator user)</p>
<p>So, I can't do this because the link should be only for pic2-small, not pic2:</p>
<pre><code><div class="item">
<a href="example.com">
<picture>
<source media="(max-width: 576px)" srcset="pic2-small.jpg">
<img src="pic2.jpg">
</picture>
</a>
</div>
</code></pre>
<p>What I did is this:</p>
<pre><code><div class="item" onclick="header_onclick(this)">
<picture>
<source media="(max-width: 576px)" srcset="pic2-small.jpg?target=pic2-small-link">
<img src="pic2.jpg">
</picture>
<a id="pic2-small-link" href="example.com" style="display: none"></a>
</div>
<script>
function header_onclick(carousel_item)
{
var current_src = carousel_item.querySelector("img").currentSrc;
if (typeof current_src === "undefined") {
return;
}
var src_parts = current_src.split("?target=");
if (src_parts.length < 2) {
return;
}
var link = document.getElementById(src_parts[1]);
if (link) {
link.click();
}
}
</script>
</code></pre>
<ul>
<li>An <code>onclick</code> event in the carousel item and a javascript function.</li>
<li>A <code>target</code> value in the URL of the image.</li>
<li>A hidden <code><a></code> with the destination URL.</li>
</ul>
<p>The magic is in this line:</p>
<pre><code>var current_src = carousel_item.querySelector("img").currentSrc;
</code></pre>
<p><code>currentSrc</code> has the URL of the image that the browser is currently showing according to the screen size. So, from that URL I take the <code>target</code> parameter and use it to get the corresponding link and then execute it.</p>
<p>All this is working, but I feel it too hacky for my taste. I'm not very experienced with the <code><picture></code> element, so my question is: this could be resolved in a better way?</p>
|
[] |
[
{
"body": "<h2>Yes hacky!</h2>\n<p>This is very hacky as you are doing a media query the long way. Interpreting the resulting media aware DOM for a URL that you then manually parse.</p>\n<h3>Learn and use the API</h3>\n<p>There are many API's available to a modern browser environment. The general rule is if it can be done on the page via HTML/CSS there is an API that can do it in JavaScript.</p>\n<p>I never use media queries as I serve to interrogated devices so I am not 100% up on media querie API's, but for static pages you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window matchMedia\">matchMedia</a></p>\n<h3>Setting up media dependent links.</h3>\n<p>There are many ways to setup your page. But in code you can access media queries using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Window matchMedia\">matchMedia</a> which returns the result of a media query as <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList\" rel=\"nofollow noreferrer\" title=\"MDN Web API's MediaQueryList\">MediaQueryList</a></p>\n<p>You can access an elements media attribute by name. for example if an image is clicked in your example HTML <code>event.target.parentElement.querySelector("source").media</code></p>\n<p>You can store the different links as data attributes.</p>\n<p>I think the best approach is to pre-process the markup when it has loaded and just set the link references depending on the associated media query.</p>\n<h2>Example</h2>\n<p>The code checks each link (anchor element) for a source element and uses the source elements media attribute to do a media query.</p>\n<p>Depending on the result of the media query it gets the appropriate data set item and set the link <code>href</code> property.</p>\n<p>Each picture has a different media query. Hover to see link href (I have set title to show the link as example)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// do in page onload event\nfor (const link of linkedImages.querySelectorAll(\"a\")) {\n const source = link.querySelector(\"source\");\n if (source) {\n const isSmall = matchMedia(source.media).matches;\n link.href = isSmall ? link.dataset.linkSmall : link.dataset.linkNormal;\n link.title = link.href; // just for example \n }\n}\n \n\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"item\" id = \"linkedImages\">\n <a data-link-small=\"smallLink.com\" data-link-normal=\"normalLink.com\">\n <picture>\n <source media=\"(max-width: 1700px)\" srcset=\"https://i.stack.imgur.com/C7qq2.png?s=48&g=1\">\n <img class=\"images\" src=\"https://i.stack.imgur.com/C7qq2.png?s=328&g=1\">\n </picture>\n </a><br>\n <a data-link-small=\"smallLink.com\" data-link-normal=\"normalLink.com\">\n <picture>\n <source media=\"(max-width: 500px)\" srcset=\"https://i.stack.imgur.com/C7qq2.png?s=48&g=1\">\n <img class=\"images\" src=\"https://i.stack.imgur.com/C7qq2.png?s=328&g=1\" width=\"128\">\n </picture> \n </a>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T22:18:35.810",
"Id": "515357",
"Score": "0",
"body": "By _interrogated devices_ did you mean _integrated devices_? Apparently [_Device Interrogation_](https://www.acc.org/~/media/Non-Clinical/Files-PDFs-Excel-MS-Word-etc/Meetings/2016/Course%20PDFs/Core%20Curriculum/Fri%20Post/Fri%207%2030%20am%20Obias%20Manno.pdf?la=en) is a concept for devices like pacemakers..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T09:59:09.253",
"Id": "515393",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ I meant interrogated as a substitute for device discovery on a landing page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:52:57.933",
"Id": "515407",
"Score": "0",
"body": "This looks more like the kind of code I want! I wasn't aware of matchMedia(), I will investigate further and I will give it a try later, but at least now I have a path to follow. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:04:47.767",
"Id": "261149",
"ParentId": "261137",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261149",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T12:57:05.220",
"Id": "261137",
"Score": "3",
"Tags": [
"javascript",
"html"
],
"Title": "How to have <picture> elements with different links on each image?"
}
|
261137
|
<p>I am learning numpy, pandas, and sklearn for machine learning now. My teacher gives me code like below, but I guess it is ugly. This code is for splitting the data into training set and testing set, and later we could manipulate the entire data or just training/testing set by the <code>[True, False, True, False ... ]</code> <code>idx_train</code>/<code>idx_test</code> list later.</p>
<blockquote>
<pre><code>import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
m = 10
x1 = np.arange(m)
x2 = x1 * 2
x3 = x1 * 3
x4 = x1 * 4
x = np.c_[x1, x2, x3, x4]
x = pd.DataFrame(x)
x_train, x_test = train_test_split(x, train_size=0.7, random_state=666)
TRAIN, TEST = 'train', 'test'
TRAIN_TEST = TRAIN + TEST
pd.options.mode.chained_assignment = None
x_train[TRAIN_TEST] = TRAIN
x_test[TRAIN_TEST] = TEST
pd.options.mode.chained_assignment = 'warn'
x = pd.concat([x_train, x_test])
idx_train = x[TRAIN_TEST] == TRAIN
idx_test = np.invert(idx_train)
x_train = x[idx_train] # later
x_test = x[idx_test]
</code></pre>
</blockquote>
<p>And I get the below code by myself. I feel it is only a little better.</p>
<pre><code>offset_orig = np.arange(m)
rate = 0.7
offset_train, offset_test = train_test_split(offset_orig, train_size=rate, random_state=666)
if rate < 0.5:
offset_set_train = set(offset_train)
idx_train = [i in offset_set_train for i in offset_orig] # This may be slow. Is numpy broadcast or implicit cycling available here?
idx_test = np.invert(idx_train)
else:
offset_set_test = set(offset_test)
idx_test = [i in offset_set_test for i in offset_orig] # This may be slow. Is numpy broadcast or implicit cycling available here?
idx_train = np.invert(idx_test)
x_train = x[idx_train] # later
x_test = x[idx_test]
</code></pre>
<p>I want to get the <code>[True, False, True, False ... ]</code> list <code>idx_train</code> and <code>idx_test</code> for slicing usage later.</p>
<p>I believe that in the world of Python, there should be and will be only one appropriate way to achieve an objective. Could someone give me that very approach to get a "train or test" slicing? (Usage of the lib function <code>train_test_split</code> is required.)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T09:35:00.373",
"Id": "515392",
"Score": "0",
"body": "[Cross-posted at Stack Overflow](https://stackoverflow.com/q/67671132/1014587)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T12:38:03.377",
"Id": "515401",
"Score": "0",
"body": "Sorry, I am suggested to post my question here. The original post in StackOverflow has some information entered by other users, and I feel it should not be deleted."
}
] |
[
{
"body": "<p><strong>Inspired by Gulzar at Stackoverflow.</strong></p>\n<p>I do not realize it works until after a night's sleep.</p>\n<p><strong>So, below is enough:</strong></p>\n<pre class=\"lang-python prettyprint-override\"><code>offset_orig = range(m)\noffset_train, offset_test = train_test_split(offset_orig, train_size=0.7, random_state=666)\n\nx_train = x.iloc[offset_train] # later\nx_test = x.iloc[offset_test]\n</code></pre>\n<p><strong>The <code>offset_train</code> list (<code>[0, 2, ...]</code>) has the same feature in later programming against the <code>[True, False, True, False ...]</code> list for slicing I pursued at the beginning.</strong></p>\n<p>For example, I can use offset_train later as below:</p>\n<blockquote>\n<pre class=\"lang-python prettyprint-override\"><code>import matplotlib.pyplot as plt\nimport seaborn as sns\nfig, axes = plt.subplots(nrows=2, ncols=2)\nfig.set_size_inches(12, 10)\nsns.boxplot(data=df.iloc[offset_train], y='count', ax=axes[0][0])\nsns.boxplot(data=df.iloc[offset_train], y='count', x='season', ax=axes[0][1])\nsns.boxplot(data=df.iloc[offset_train], y='count', x='hour', ax=axes[1][0])\nsns.boxplot(data=df.iloc[offset_train], y='count', x='workingday', ax=axes[1][1])\n</code></pre>\n</blockquote>\n<p>And even as below:</p>\n<blockquote>\n<pre class=\"lang-python prettyprint-override\"><code># get noise index\nmu_count = df.loc[offset_train, 'count'].mean(axis=0)\nsigma_count = df.loc[offset_train, 'count'].std(axis=0)\nidx_bad_np = abs(df.loc[offset_train, 'count'] - mu_count) > 3 * sigma_count\nidx_good_np = np.invert(idx_bad_np)\n# remove noise index\nprint(f'Before removal: sum(idx good) = {sum(idx_good_np)}, sum(idx bad) = {sum(idx_bad_np)}, len(df[train]) = {len(df.iloc[offset_train])}')\noffset_train = list(set(offset_train) - set(np.array(offset_train)[idx_bad_np]))\nprint(f'After removal: sum(idx good) = {sum(idx_good_np)}, sum(idx bad) = {sum(idx_bad_np)}, len(df[train]) = {len(df.iloc[offset_train])}')\n# check again\nidx_bad_np = abs(df.loc[offset_train, 'count'] - mu_count) > 3 * sigma_count\nprint(f'Check sum(idx bad) after removal: {sum(idx_bad_np)}')\n</code></pre>\n</blockquote>\n<p>Thanks to the community. I feel I have so far to go on the path of Python.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T01:36:28.240",
"Id": "261170",
"ParentId": "261139",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:02:35.757",
"Id": "261139",
"Score": "0",
"Tags": [
"python",
"numpy",
"pandas"
],
"Title": "Get a \"train or test\" slicing elegantly after splitting"
}
|
261139
|
<p>I want to calculate the intersection point, in time, of 2 or 3 moving averages.</p>
<p>To solve this problem I decided to transform the moving average(ma) data into geometrical lines and calculate the intersection point via the formula for lines in the slope/intercept form.</p>
<p>X coordinate is the unix timestamp of the ma, the Y coordinate is the value of the ma.</p>
<p>Converting the intersection point to <code>datetime</code> format gives me the exact time of intersection.</p>
<p>The data is coming in from a websocket and it is based on a granularity setting.</p>
<p>In order to build the line representations of the moving averages a logic layer is needed to correctly set and update the X,Y coordinates of the lines.</p>
<p>Would like to know if the mutation operations on the line data can be written in a cleaner way.</p>
<p>Also any other improvement suggestions are welcome.</p>
<p><code>geometry.go</code></p>
<pre><code>package geometry
//Line represents a geometrical line
type Line struct {
PointA Point
PointB Point
slope float64
intercept float64
}
func NewLine(a Point, b Point) Line {
line := Line{
PointA: a,
PointB: b,
}
line.calculateSlope()
line.calculateIntercept()
return line
}
func (l *Line) calculateSlope() {
l.slope = (l.PointA.Y - l.PointB.Y) / (l.PointA.X - l.PointB.X)
}
func (l *Line) Slope() float64 {
return l.slope
}
func (l *Line) calculateIntercept() {
l.intercept = l.PointA.Y - (l.slope * l.PointA.X)
}
//Point represents a single Point on the x,y axis
type Point struct {
X,
Y float64
}
//IntersctionPoint return the intersection point of two lines.
//Calculation uses slope/intercept line form
func IntersectionPoint(l1, l2 Line) Point {
//line slope intercept form equation
//y - y coordinate, x - x coordinate
//m - slope, b intercept
//y = mx + b
//intersection equation for line definitions y = 3x-3 and y = 2.3x+4
//(3x-3 = 2.3x+4), (3x-2.3x = 4+3)
//0.7x = 7, (x = 7/0.7), x = 10
leftSide := l1.slope + (l2.slope * -1)
rightSide := l2.intercept + (l1.intercept * -1)
x := rightSide / leftSide
y := l1.slope*x + l1.intercept
return Point{X: x, Y: y}
}
</code></pre>
<p><code>intersector.go</code></p>
<pre><code>package intersector
import (
"fmt"
"intersector/geometry"
"time"
)
const (
up = 1
down = -1
)
type Average struct {
Value float64
Timestamp int
}
//intersector builds lines from the received moving average data
//and calculates their intersection point. max 3 lines
type intersector struct {
input chan []Average
}
func NewIntersector(input chan []Average) intersector {
return intersector{
input: input,
}
}
//point is a wrapper around geometry.Point
//adds timestamp field needed for tracking and placing
//moving average values as x,y coordinates
type point struct {
point geometry.Point
timestamp int
}
func newPoint(x, y float64, timestamp int) point {
return point{
point: geometry.Point{
X: x,
Y: y,
},
timestamp: timestamp,
}
}
//line is a wrapper around geometry.Line
//adds helper fields for capturing point data
//from data stream
type line struct {
geometry geometry.Line
pointA point
pointB point
direction int
}
func newLine(a, b point) *line {
return &line{
geometry: geometry.NewLine(a.point, b.point),
pointA: a,
pointB: b,
}
}
//update updates pointA or pointB of a line base on the timestamp of the average
func (line *line) update(average Average) bool {
//data refers to pointA of the line definition
//will not trigger once pointB is defined
if line.pointA.timestamp == average.Timestamp {
line.pointA.point.Y = average.Value
return true
}
//checks if pointB is defined yet, if not, inititialises pointB and creates the line
if line.pointB == (point{}) {
line.pointB = newPoint(float64(average.Timestamp), average.Value, average.Timestamp)
line.geometry = geometry.NewLine(line.pointA.point, line.pointB.point)
return true
}
if average.Timestamp == line.pointB.timestamp {
line.pointB.point.Y = average.Value
return true
}
//collecting data on pointB has finished. line is complete
//return false as there is nothing to update for this line
if average.Timestamp != line.pointB.timestamp {
return false
}
return true
}
func (l *line) setDirection(direction int) {
l.direction = direction
}
func getDirection(line geometry.Line) int {
horizon := 0.00
if line.Slope() <= horizon {
return down
}
return up
}
func (z intersector) Calculate() {
incompleteLines := make(map[int]*line)
completeLines := make(map[int]*line)
for {
if averages, ok := <-z.input; ok {
for index, average := range averages {
if line, ok := incompleteLines[index]; !ok {
pointA := newPoint(float64(average.Timestamp), average.Value, average.Timestamp)
pointB := point{}
incompleteLines[index] = newLine(pointA, pointB)
continue
} else {
if updated := line.update(average); !updated {
pointA := newPoint(float64(line.pointA.timestamp), line.pointA.point.Y, line.pointA.timestamp)
pointB := newPoint(float64(line.pointB.timestamp), line.pointB.point.Y, line.pointB.timestamp)
completeLines[index] = newLine(pointA, pointB)
incompleteLines[index] = newLine(line.pointB, point{})
}
}
}
//QUESTION::
//Can the same be done with a for loop avoiding the code duplication for lines A and B?
switch len(completeLines) {
case 2:
lineA := completeLines[0]
lineB := completeLines[1]
intersection := geometry.IntersectionPoint(lineA.geometry, lineB.geometry)
//check if the intersection point is within the origin coordinates of the lines
//intersections that occur outside of the lline definition are not important
if intersection.X >= lineA.geometry.PointA.X && intersection.X <= lineB.geometry.PointB.X {
//only print intersections that do not occur in the same direction. lines can intersect multiple times going upward or downward
if lineA.direction != getDirection(lineA.geometry) {
lineA.setDirection(getDirection(lineA.geometry))
fmt.Printf("Line1 interesects Line2 at: %v Y: %v X: %v Direction: %v\n", t(intersection.X), intersection.Y, intersection.X, getDirection(lineA.geometry))
}
}
case 3:
lineA := completeLines[0]
lineB := completeLines[1]
lineC := completeLines[2]
intersection1 := geometry.IntersectionPoint(lineA.geometry, lineB.geometry)
intersection2 := geometry.IntersectionPoint(lineA.geometry, lineC.geometry)
intersection3 := geometry.IntersectionPoint(lineB.geometry, lineC.geometry)
//check if the intersection point is within the origin coordinates of the lines
//intersections that occur outside of the lline definition are not important
if intersection1.X >= lineA.geometry.PointA.X && intersection1.X <= lineB.geometry.PointB.X {
//only print intersections that do not occur in the same direction. lines can intersect multiple times going upward or downward
if lineA.direction != getDirection(lineA.geometry) {
lineA.setDirection(getDirection(lineA.geometry))
fmt.Printf("Line1 interesects Line2 at: %v Y: %v X: %v Direction: %v\n", t(intersection1.X), intersection1.Y, intersection1.X, getDirection(lineA.geometry))
}
}
if intersection2.X >= lineA.geometry.PointA.X && intersection2.X <= lineC.geometry.PointB.X {
if lineC.direction != getDirection(lineC.geometry) {
lineC.setDirection(getDirection(lineC.geometry))
fmt.Printf("Line1 interesects Line3 at: %v Y: %v X: %v Direction: %v\n", t(intersection2.X), intersection2.Y, intersection2.X, getDirection(lineA.geometry))
}
}
if intersection3.X >= lineB.geometry.PointA.X && intersection3.X <= lineC.geometry.PointB.X {
if lineB.direction != getDirection(lineB.geometry) {
lineB.setDirection(getDirection(lineB.geometry))
fmt.Printf("Line2 interesects Line3 at: %v Y: %v X: %v Direction: %v\n", t(intersection3.X), intersection3.Y, intersection3.X, getDirection(lineB.geometry))
}
}
}
} else {
return
}
}
}
//converts unix time to string time
func t(timestamp float64) string {
t := int64(timestamp / 1000)
tm := time.Unix(t, 0)
return tm.Format(time.RFC3339)
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T13:05:27.530",
"Id": "261140",
"Score": "0",
"Tags": [
"go"
],
"Title": "Calculate intersection point of 2 or 3 moving averages"
}
|
261140
|
<p>Link to full problem description: <a href="https://www.codewars.com/kata/534e01fbbb17187c7e0000c6" rel="nofollow noreferrer">https://www.codewars.com/kata/534e01fbbb17187c7e0000c6</a></p>
<p>My code:</p>
<pre><code>def spiralize(size):
def get_change_values():
change_x = 0
change_y = 0
if direction == 'right':
change_x = 1
elif direction == 'left':
change_x = -1
elif direction == 'down':
change_y = 1
elif direction == 'up':
change_y = -1
return change_x, change_y
def check_collision():
if 0 <= y + change_y * 2 < size and 0 <= x + change_x * 2 < size:
if direction in ('right', 'left'):
if spiral[y][x + change_x * 2]:
return True
elif direction in ('down', 'up'):
if spiral[y + change_y * 2][x]:
return True
return False
spiral = [[0 for _ in range(size)] for _ in range(size)]
directions = ['right', 'down', 'left', 'up']
x = y = 0
change_directions = 0
while change_directions < size:
direction = directions[change_directions % 4]
change_x, change_y = get_change_values()
while 0 <= y + change_y < size and 0 <= x + change_x < size:
spiral[y][x] = 1
if check_collision():
break
y += change_y
x += change_x
change_directions += 1
return spiral
</code></pre>
<p>The basic idea of what my algortihm is trying to do here:</p>
<ul>
<li>Initialize a matrix of 0s of the given size</li>
<li>Starting from the top left and heading towards the right, go through each element and change it to '1' until it can no longer move in that direction</li>
<li>Once it can no longer move in a given direction, change the direction based on the order right -> down -> left -> up</li>
<li>Repeat until spiral is complete (until size-1 changes of direction have been made)</li>
</ul>
<p>The main advice I'm looking for here is how to better structure this code to make it more readable and understandable to the average viewer. Granted, if there are any glaring performance optimizations that can be made to improve this code, I'd be more than willing to hear those out as well. But again, I'm mostly looking for advice on how to make this code cleaner in general. I'm not exactly a new programmer per se, but the concept of 'clean code' is still something I very much struggle with.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T15:51:52.653",
"Id": "515334",
"Score": "6",
"body": "Please embed the problem description in the body of the question. Links can be broken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T12:51:22.210",
"Id": "515600",
"Score": "0",
"body": "Ahh I see, I'll keep that in mind next time I post. Thanks for letting me know!"
}
] |
[
{
"body": "<p>Without changing your algorithm we can make your code simpler in a few places. I'd say the algorithm is quite sensible, I would've chosen the same approach.</p>\n<hr />\n<p><strong>Comments and docstrings</strong></p>\n<p>Providing some comments here and there and explaining the general algorithmic approach in a docstring would be good start for increasing readability. In particular, it's not intuitively obvious why <code>while change_directions < size:</code>\nis the correct approach.</p>\n<hr />\n<p><strong>Nested functions</strong></p>\n<p>I find nested functions to be relatively hard to read. Especially when they start using variables from the outer scope (the outer function), thereby mixing namespaces. Personally, I generally try to avoid them. In the case of <code>check_collision</code> I'd say it might improve readability as it reduces the maximum indentation level. That's generally a good thing, since every indentation level is another layer of context to keep track of.</p>\n<hr />\n<p><strong>get_change_values()</strong></p>\n<p>We can easily get rid of this function by taking a closer look at the underlying logic. We don't actually need to pass around <code>direction</code> strings, since we always follow the same pattern <code>RIGHT -> DOWN -> LEFT -> UP -> RIGHT -> ...</code>. The <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module from the standard library provides <a href=\"https://docs.python.org/3/library/itertools.html#itertools.cycle\" rel=\"nofollow noreferrer\"><code>cycle</code></a>, which basically provides an endless iterator for a given iterable (example from the docs: <code>cycle('ABCD') --> A B C D A B C D A B C D ...</code>). So we might want to <code>cycle(['right', 'down', 'left', 'up'])</code>. But since we only need the strings to get the corresponding <code>change_x, change_y</code> values, we can replace them by those values directly:</p>\n<pre><code>directions = cycle(((1, 0), (0, 1), (-1, 0), (0, -1)))\n</code></pre>\n<p>We now replace</p>\n<pre><code>direction = directions[change_directions % 4]\nchange_x, change_y = get_change_values()\n</code></pre>\n<p>by</p>\n<pre><code>change_x, change_y = next(directions)\n</code></pre>\n<p>and get rid of <code>get_change_values()</code>.</p>\n<hr />\n<p><strong><code>0 <= variable < limit</code></strong></p>\n<p>Conditions that follow the pattern <code>0 <= variable < limit</code> <strong>can</strong> be replaced by <code>variable in range(limit)</code>. I personally find this to be more readable, but it's not always preferable and up to personal preference.</p>\n<hr />\n<p><strong>check_collision()</strong></p>\n<p>This function can be simplified to the point where we could directly put it into our nested <code>while</code> loop. This is a valid option here. But as mentioned above you might want to keep it in a seperate function to reduce the maximum indentation level.</p>\n<p>We don't actually need to check for the direction:</p>\n<pre><code>if direction in ('right', 'left'):\n if spiral[y][x + change_x * 2]:\n return True\nelif direction in ('down', 'up'):\n if spiral[y + change_y * 2][x]:\n return True\n</code></pre>\n<p>if we simply check</p>\n<pre><code>if spiral[y + change_y * 2][x + change_x * 2] == 1:\n return True\n</code></pre>\n<p>We can also directly <code>return</code>:</p>\n<pre><code>def check_collision() -> bool:\n if y + change_y * 2 in range(size) and x + change_x * 2 in range(size):\n return spiral[y + change_y * 2][x + change_x * 2] == 1\n \n return False\n</code></pre>\n<p>I find exit conditions to generally improve code readability as well. They're usually closer to the reader's thought process (<em>"If the step is out of bounds there's no collision, so we don't need to check anything else. Otherwise check if the step leads to a 1."</em>):</p>\n<pre><code>def check_collision() -> bool:\n if y + change_y * 2 not in range(size) or x + change_x * 2 not in range(size):\n return False\n \n return spiral[y + change_y * 2][x + change_x * 2] == 1\n</code></pre>\n<p>Both options are already pretty clean. I personally prefer this branchless approach:</p>\n<pre><code>def check_collision() -> bool:\n step_inside_bounds = y + change_y * 2 in range(size) and x + change_x * 2 in range(size)\n return step_inside_bounds and spiral[y + change_y * 2][x + change_x * 2] == 1\n</code></pre>\n<p>This works because <code>and</code> is evaluated lazily, so if <code>step_inside_bounds is False</code>, the rest of the condition is not evaluated.</p>\n<hr />\n<p><strong><code>spiral</code> initialization</strong></p>\n<p>Instead of</p>\n<pre><code>spiral = [[0 for _ in range(size)] for _ in range(size)]\n</code></pre>\n<p>we can initialize <code>spiral</code> like this</p>\n<pre><code>spiral = [[0] * size for _ in range(size)]\n</code></pre>\n<p>This again is just another way to do things, and I wouldn't say it's definitely better for multi-dimensional lists. For one-dimensional lists, I would prefer the suggested syntax. Compare these examples:</p>\n<pre><code>my_list = [0 for _ in range(my_length)]\nmy_list = [0] * my_length\n</code></pre>\n<hr />\n<p><strong>Complete code</strong></p>\n<p>I renamed <code>change_directions</code> to <code>direction_changes</code> and <code>check_collision</code> to <code>collision_in_two_steps</code>. I also added type hints (<a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a>).</p>\n<pre><code>from itertools import cycle\n\n\ndef spiralize(size: int) -> list[list[int]]:\n def collision_in_two_steps() -> bool:\n step_inside_bounds = y + change_y * 2 in range(size) and x + change_x * 2 in range(size)\n return step_inside_bounds and spiral[y + change_y * 2][x + change_x * 2] == 1\n\n directions = cycle(((1, 0), (0, 1), (-1, 0), (0, -1)))\n\n spiral = [[0] * size for _ in range(size)]\n x, y = 0, 0\n direction_changes = 0\n\n while direction_changes < size:\n change_x, change_y = next(directions)\n\n while y + change_y in range(size) and x + change_x in range(size):\n spiral[y][x] = 1\n\n if collision_in_two_steps():\n break\n\n y += change_y\n x += change_x\n\n direction_changes += 1\n\n return spiral\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T13:20:08.827",
"Id": "515601",
"Score": "1",
"body": "Thanks for the response! I think your answer more directly answered my original question, so I'm giving the accepted solution to you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T16:41:57.923",
"Id": "261148",
"ParentId": "261145",
"Score": "4"
}
},
{
"body": "<p>Your current implementation is not too hard to follow and you already have some\ngood suggestions in another review. Here I'll try to build on those ideas and\nspeak more directly to your deeper question: <strong>how does one get better at\nwriting cleaner, more readable, more intuitive code</strong>.</p>\n<p>One secret is to focus on the data. This principle has been famously\narticulated many times, by the likes of Fred Brooks, Eric Raymond, Linus\nTorvaldis, and Rob Pike. The latter, for example, lists the following in his <a href=\"https://users.ece.utexas.edu/%7Eadnan/pike.html\" rel=\"nofollow noreferrer\">5\nRules of Programming</a>:</p>\n<blockquote>\n<p>Rule 5. Data dominates. If you've chosen the right data structures and\norganized things well, the algorithms will almost always be\nself-evident. Data structures, not algorithms, are central to\nprogramming.</p>\n</blockquote>\n<p>Start with a simple example that has already been noted. The\n<code>get_change_values()</code> function is currently all algorithm. But it can be\nexpressed directly as data: for example, a collection of tuples expressing the\nrow/col shifts. Such data is immediately intuitive. In your specific case,\nwrapping that collection in <code>itertools.cycle()</code> is basically a super-powered\ntype of data. Even though there is code lurking behind the collection, you\ndon't need to think about the details. From your perspective, its just an\nendless collection.</p>\n<p>A second technique that I have found useful is to avoid the temptation to move\nto computer-sciencey implementation too early. I have learned this lesson the\nhard way many times. Indeed, I sort of learned it trying to write this review.\nI had an initial idea and jumped too soon to coding details. I struggled\nthrough some bugs and ended up with code similar in spirit to the review you\nalready have -- which is a good one! On my second attempt I ignored coding\ndetails and just tried to express the algorithm in intuitive terms.\nWhen doing this, don't fret too much over precise implementation details.\nHere's the sketch I started with. I didn't yet know what those wished-for\nfunctions would have to do, but at a high level this seemed both correct\nand directly understandable:</p>\n<pre class=\"lang-python prettyprint-override\"><code>grid = [... zeroes ...]\nloc = (0, 0)\n\nwhile True:\n mark_current_location(...)\n newloc = next_location(...)\n if not newloc:\n turn(...)\n newloc = next_location(...)\n if newloc:\n loc = newloc\n else:\n break\n\nreturn grid\n</code></pre>\n<p>As you convert the plan into actual code, sometimes adjustments\noccur (and sometimes you discover your plan has flaws). In this\ncase, the plan worked well in the sense that I was able to convert\nthe sketch into working code without any real hang-ups.</p>\n<p>Another technique for code readability is to keep top-level code simple by\ndelegating simple algorithmic details to one or more utility functions. These\ngrid problems are famous for annoyances regarding out-of-bounds checks. Never\nclutter up your main algorithm with tedium like that. From the outset, I expected\nto write a function that would take a grid, row, and column and return either\nthe cell value or <code>None</code>.</p>\n<p>Yet another technique is to invest more time in code comments. This does not\nnecessarily mean writing lots of comment text, and certainly the comments\nshouldn't repeat every detail of the code. Rather, they should play an\norganizational role, acting as major sign posts or dividers, and they should\ntry to express goals, intent, strategy, and so forth. Well done comments create\nan overarching narrative to help the reader (usually your future self) grasp\nthe details in the code more readily.</p>\n<p>Finally -- and this is more controversial -- use the shortest variable names\nyou can without sacrificing readability. That's inherently a balancing act:\nlonger names are more specific and more precise, but they can become visually\nheavy, weighing down the code and imposing a tax on the reader's attention.\nWithin local contexts, it's often possible to get away with very short names,\nprovided that those names have some intuition behind them and enough\nsurrounding information to make them clear. Consider the first few lines of the\nimplementation I ended up with. At interface points (e.g., a function signature),\none often wants more specific names, like <code>size</code>. But within the function, and\nfollowing a code comment that has the phrase "row/col location", the compact\nvariables of <code>r</code> and <code>c</code> work perfectly fine. And that naming convention\nbecomes the basis for other variable names used elsewhere in the code: <code>dr</code> and\n<code>dc</code> for movements (following the mathematical convention for change values)\nand <code>nr</code> and <code>nc</code> for new-row/new-col. In the abstract, those names might seem\ntoo cryptic. But in context, they are clear. For example, the latter two are\nfirst introduced as <code>nr, nc = next_location(...)</code>. Naming is always a difficult\nbalancing act, but readable code pays a lot of attention to names, naming\nconventions, and context.</p>\n<pre><code>def spiralize(size):\n # Setup empty grid and mark the current row/col location.\n grid = [[0] * size for _ in range(size)]\n r, c = (0, 0)\n</code></pre>\n<p>Note that this code gives different answers than yours (and the other review)\nfor grids sized 1, 2, and 3. The original problem excludes sizes below 5, but\nthat restriction seems unnecessary to me. At least the way I understand the\nessence of this problem, the small spirals generated by this code make more\nsense to me.</p>\n<pre class=\"lang-python prettyprint-override\"><code>\nfrom itertools import cycle\n\ndef spiralize(size):\n # Setup empty grid and mark the current row/col location.\n grid = [[0] * size for _ in range(size)]\n r, c = (0, 0)\n if not grid:\n return grid\n\n # Directions of travel (right, down, left, up).\n directions = ((0, 1), (1, 0), (0, -1), (-1, 0))\n moves = cycle(directions)\n move = next(moves)\n\n while True:\n # Mark current location.\n grid[r][c] = 1\n\n # Advance to the next row/col location.\n # If that fails, turn and try again.\n nr, nc = next_location(grid, r, c, move, directions)\n if nr is None:\n move = next(moves)\n nr, nc = next_location(grid, r, c, move, directions)\n\n # Halt or advance.\n if nr is None:\n break\n else:\n r, c = (nr, nc)\n\n return grid\n\ndef next_location(grid, r, c, move, directions):\n # Get new row/col from the move.\n dr, dc = move\n nr, nc = (r + dr, c + dc)\n\n # Generator expression to get cells surrounding\n # the new location, other than the current location.\n new_neighbors = (\n get(grid, nr + dr, nc + dc)\n for dr, dc in directions\n if not (nr + dr == r and nc + dc == c)\n )\n\n # Return:\n # - Fail: new location outside grid.\n # - Fail: new location touches existing part of snake.\n # - Success.\n return (\n (None, None) if get(grid, nr, nc) is None else\n (None, None) if any(new_neighbors) else\n (nr, nc)\n )\n\ndef get(grid, r, c):\n try:\n if r >= 0 and c >= 0:\n return grid[r][c]\n else:\n return None\n except IndexError:\n return None\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T12:02:50.267",
"Id": "515399",
"Score": "0",
"body": "+1 for comprehensively outlining your thought process, that's something I often struggle with. Is there a particular reason for checking `if r >= 0 and c >= 0` in `get(...)`? Wouldn't catching the `IndexError` suffice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:58:27.107",
"Id": "515410",
"Score": "0",
"body": "@riskypenguin In a generic `get()` one wouldn't want the checks. But in this specific problem, we want to disallow negative indexes (eg, when `r` is 0 and `dr` is -1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T14:02:20.490",
"Id": "515411",
"Score": "0",
"body": "Ah of course, for a moment I completely forgot that negative indexing is valid in Python and thought it would just throw an `IndexError`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T13:23:09.160",
"Id": "515602",
"Score": "1",
"body": "@FMc Thanks for the response! I appreciate the additional detail of your answer, it has definitely given me a lot to think about and consider. Though, I do wanna ask 1 thing out of curiosity. People have generally told me that having functions with many parameters (say 5 and up) is considered a bad thing, hence why I opted to use nested functions in my original solution. How valid do you think this rule of thumb is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T15:13:20.533",
"Id": "515616",
"Score": "0",
"body": "@dettolas It's not a bad rule of thumb, but it's not one I've ever spent much time worrying about. If the N of args for a function is so large that I find it a hassle to use, I don't conclude that I should stop using functions or that I should move them to inner functions (I rarely do the latter). Rather I consider whether my functions could be decomposed further, whether the arguments could be packaged up into useful data-bundles/objects, or whether the functions could be put into a meaningful class to reduce argument passing. But reducing function args is never a driving goal by itself."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T23:14:07.260",
"Id": "261167",
"ParentId": "261145",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261148",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T15:01:18.277",
"Id": "261145",
"Score": "4",
"Tags": [
"python",
"algorithm"
],
"Title": "Codewars: Make a spiral"
}
|
261145
|
<p>I have an enumerable source for which I do not know how big it is. I want to select a random element from it, without having to hold the whole collection in memory and with uniform distribution. I read about the reservoir sampling algorithm, and created a simple implementation for the very basic case where the reservoir size is 1, which is what I want.</p>
<p>Basically the idea is that if an item appears in position <code>n</code> starting by <code>1</code>, if a random roll returns less than <code>1/n</code> I pick that value as the current selected value.</p>
<pre><code>static T Random<T>(IEnumerable<T> source, Random random)
{
using var e = source.GetEnumerator();
if(!e.MoveNext())
return default;
var result = e.Current;
var count = 1;
while(e.MoveNext())
{
if(random.NextDouble() < 1.0 / ++count)
result = e.Current;
}
return result;
}
</code></pre>
<p>I created a demo project and the results seems to add up.</p>
<p><a href="https://dotnetfiddle.net/0iXEck" rel="nofollow noreferrer">https://dotnetfiddle.net/0iXEck</a></p>
<pre><code>public static void Main()
{
var size = 1000;
var tries = size * 100;
var random = new Random();
var array = Enumerable.Range(0, size).ToArray();
var histogram = array.ToDictionary(k => k, v => 0);
for(var i=0; i<tries; i++)
histogram[Random(array, random)]++;
foreach(var kv in histogram.OrderBy(kv => kv.Key))
Console.WriteLine($"{kv.Key,5}: {kv.Value}");
}
</code></pre>
<p>I wonder if am I missing anything because probability knowledge is not my strongest point. Is this still "reservoir sampling algorithm" or does it have another name?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T16:03:27.193",
"Id": "515336",
"Score": "2",
"body": "Welcome to the Code Review Community. Please include the code from entire class/program in the question since there is only one more function, this will help us understand what the program is doing."
}
] |
[
{
"body": "<p>Let me try another answer.</p>\n<p>Background info: <a href=\"https://en.wikipedia.org/wiki/Reservoir_sampling\" rel=\"nofollow noreferrer\">Wikipedia Reservoir Sampling</a>.</p>\n<p>The intro header to the Wikipedia link states:</p>\n<blockquote>\n<p>The size of the population <em><strong>n</strong></em> is not known to the algorithm and is\ntypically too large for all <em><strong>n</strong></em> items to fit into main memory.</p>\n</blockquote>\n<p>But consider you have a dictionary to hold the results for all <em><strong>n</strong></em> items in your main memory. And each example they provide has it returning a complete array, so it all has to fit into memory somehow.</p>\n<p>You could make your life easier if your method accepted an <code>IList<T></code> since that would return a known <code>Count</code>. Consider that each individual call to your method will enumerate over EACH element in the collection. Since you pass in a 1000 element array, all 1000 elements are enumerated for one call, and you make 100 calls. I am just saying after the first call has been made, the size of the collection is no longer unknown. Rather it is not remembered between invocations.</p>\n<p>But that is not what you asked for. My answer continues to with <code>IEnumerable<T></code> of unknown length.</p>\n<p>Typically, one does not pass in the <code>Random</code> instance, but rather relies upon the method to have one handy.</p>\n<p>The method name <code>Random<T></code> is a poor name producing much confusion with the <code>Random class</code>. I suggest it be <code>GetReservoirSample<T></code>.</p>\n<p>For C#, the CodeReview community strongly supports uses braces to avoid one-liners.</p>\n<p>There is no reason to <code>OrderBy</code> Key on <code>histogram</code> since it was created in Key order.</p>\n<p>A quick reworking of your method, which includes <code>Random</code> as an optional parameter, would become:</p>\n<pre><code>private static Random _random = new Random();\n\npublic static T GetReservoirSample1<T>(IEnumerable<T> source, Random random = null)\n{\n T result = default;\n int count = 0;\n if (random == null)\n {\n random = _random;\n }\n IEnumerator<T> e = source.GetEnumerator();\n // This enumerates over the entire collection!!!\n while (e.MoveNext())\n {\n if (random.NextDouble() < (1.0 / ++count))\n {\n result = e.Current;\n }\n }\n return result;\n}\n</code></pre>\n<p>But that can be simplified by getting rid of the Random parameter. And since you are iterating over all elements, there is no need for the enumerator. You may use an <code>foreach</code> instead yielding smaller code.</p>\n<pre><code>public static T GetReservoirSample2<T>(IEnumerable<T> source)\n{\n T result = default;\n int count = 0;\n // This enumerates over the entire collection!!!\n foreach (var element in source)\n {\n if (_random.NextDouble() < (1.0 / ++count))\n {\n result = element;\n }\n }\n return result;\n}\n</code></pre>\n<p><strong>IList versus IEnumerable</strong></p>\n<p>Finally, if you ever decide to change <code>source</code> to be an <code>IList<T></code>, there is this version:</p>\n<pre><code>static T GetReservoirSample3<T>(IList<T> source)\n{\n T result = source.Count > 0 ? source[0] : default;\n // This enumerates over the entire collection MINUS ONE!!!\n for (int i = 1; i < source.Count; i++)\n {\n if (_random.NextDouble() < (1.0 / (i + 1.0)))\n {\n result = source[i];\n }\n\n }\n return result;\n}\n</code></pre>\n<p><strong>UPDATED</strong></p>\n<p>In my original example using <code>IList<T></code>, there is no performance benefit. Each example must enumerate over the full collection. However, with a <code>IList</code> you can get a performance boost. Essentially, your method remembers the last element that satisfies the condition but it must continue to enumerate over the remainder of the collection.</p>\n<p>With a list, you can process the collection backwards and immediately return on the first item that satisfies the condition:</p>\n<pre><code>static T GetReservoirSample3B<T>(IList<T> source)\n{\n for (int i = source.Count - 1; i > 0; i--)\n {\n if (_random.NextDouble() < (1.0 / (i + 1.0)))\n {\n return source[i];\n }\n\n }\n return source[0];\n}\n</code></pre>\n<p>Also, I wanted to see the min and max values, so I altered <code>Main</code> for my own purposes. I share it here:</p>\n<pre><code>public static void Main()\n{\n var size = 1000;\n var tries = size * 100;\n var array = Enumerable.Range(0, size).ToArray();\n var histogram = array.ToDictionary(k => k, v => 0);\n var random = new Random();\n for (var i = 0; i < tries; i++)\n {\n histogram[GetReservoirSample3B(array)]++;\n }\n var min = int.MaxValue;\n var max = int.MinValue;\n foreach (var kv in histogram) \n {\n if (kv.Value < min)\n {\n min = kv.Value;\n }\n if (kv.Value > max)\n {\n max = kv.Value;\n }\n }\n foreach (var kv in histogram) \n {\n var extra = (kv.Value == min) ? "\\t** MININUM ** " : (kv.Value == max) ? "\\t** MAXIMUM **" : "";\n Console.WriteLine($"{kv.Key,5}: {kv.Value}{extra}");\n }\n}\n</code></pre>\n<p>All that said, I do not know if you are correctly implementing a reservoir sampling. From what I read, it expects you to return a sample subset of <code>k</code> elements where <code>k</code> is less than or equal to the source collection size of <code>n</code>. Since you are returning a single element, that is for <code>k == 1</code>, then this produces the same distribution as:</p>\n<pre><code>static T GetReservoirSample3C<T>(IList<T> source) => source[_random.Next(source.Count)];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:46:55.437",
"Id": "515456",
"Score": "0",
"body": "If you use IList, you can just do `list[random.Next(0,list.Count)]`, you do not need to iterate the list calculating randoms. But it is not practical to have a list with 100K results in memory just to pick one of them, that is the reason of why we are using this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T22:29:17.507",
"Id": "261164",
"ParentId": "261146",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261164",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T15:16:28.057",
"Id": "261146",
"Score": "3",
"Tags": [
"c#",
"random"
],
"Title": "Reservoir Sampling of an enumerable collection of unknown size"
}
|
261146
|
<p>How can this code be improved by "closuring" of functions here?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Your code here.
let countBs = countChar();
function countChar(str, letter = 'B') {
if (letter === 'B') return (str, letter = 'B') => String(str).split('').filter(ltr => ltr == letter).length;
return String(str).split('').filter(ltr => ltr == letter).length;
}
console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:35:50.827",
"Id": "515343",
"Score": "0",
"body": "Welcome to Code Review! Did you take this code from [the book](https://eloquentjavascript.net/2nd_edition/03_functions.html#h_3rsiDgC2do) or is this code that you wrote? If you wrote the code please explain that in the description above it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:26:48.203",
"Id": "515405",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ Thank you. I've wrote this code by myself. OK, I'll try to edit."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:15:06.290",
"Id": "261151",
"Score": "2",
"Tags": [
"closure"
],
"Title": "Make better solution for Bean counting example from \"Eloquent JavaScript\" book"
}
|
261151
|
<p>I have method that fetches all orders from Database and filtering, sorting that data(I know better to do It by specific query to Database but I dont know how).
I have Order entity that has following</p>
<pre><code>public class Order {
private int orderId;
private int userId;
private int carId;
private String userAddress;
private String userDestination;
private double orderCost;
@JsonSerialize(using = CustomLocalDateTimeJsonSerializer.class)
private LocalDateTime orderDate;
// getters/setters
}
public class OrdersProcessor {
private final MySQLOrderDao orderDao;
private final DateTimeFormatter formatter;
public OrdersProcessor(MySQLOrderDao orderDao){
this.orderDao=orderDao;
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
}
public List<Order> findFilSortOrders(Map<String,String> filters, String sortedColumn, boolean descending, int startRow, int rowsPerPage){
List<Order> fetchedOrders = orderDao.findAllOrders();
List<Order>orders = new LinkedList<>(fetchedOrders.subList(startRow, fetchedOrders.size()));
if(filters!=null){
filters.entrySet().iterator().forEachRemaining(element->{
switch (element.getKey()){
case "orderId":{
orders.removeIf(order -> order.getOrderId()!=Integer.parseInt(element.getValue()));
break;
}
case "userId":{
orders.removeIf(order -> order.getUserId()!=Integer.parseInt(element.getValue()));
break;
}
case "carId":{
orders.removeIf(order -> order.getCarId()!=Integer.parseInt(element.getValue()));
break;
}
case "userAddress":{
orders.removeIf(order -> !order.getUserAddress().equals(element.getValue()));
break;
}
case "userDestination":{
orders.removeIf(order -> !order.getUserDestination().equals(element.getValue()));
break;
}
case "orderCost":{
orders.removeIf(order -> order.getOrderCost()!=Double.parseDouble(element.getValue()));
break;
}
case "orderDate":{
orders.removeIf(order -> !order.getOrderDate().format(formatter).equals(element.getValue()));
break;
}
}
});
}
switch (sortedColumn){
case "orderId":{
if(descending){
orders.sort(Comparator.comparing(Order::getOrderId).reversed());
}else {
orders.sort(Comparator.comparing(Order::getOrderId));
}
break;
}
case "userId":{
if(descending){
orders.sort(Comparator.comparing(Order::getUserId).reversed());
}else {
orders.sort(Comparator.comparing(Order::getUserId));
}
break;
}
case "carId":{
if(descending){
orders.sort(Comparator.comparing(Order::getCarId).reversed());
}else {
orders.sort(Comparator.comparing(Order::getCarId));
}
break;
}
case "userAddress":{
if(descending){
orders.sort(Comparator.comparing(Order::getUserAddress).reversed());
}else {
orders.sort(Comparator.comparing(Order::getUserAddress));
}
break;
}
case "userDestination":{
if(descending){
orders.sort(Comparator.comparing(Order::getUserDestination).reversed());
}else {
orders.sort(Comparator.comparing(Order::getUserDestination));
}
break;
}
case "orderCost":{
if(descending){
orders.sort(Comparator.comparing(Order::getOrderCost).reversed());
}else {
orders.sort(Comparator.comparing(Order::getOrderCost));
}
break;
}
case "orderDate":{
if(descending){
orders.sort(Comparator.comparing(Order::getOrderDate).reversed());
}else {
orders.sort(Comparator.comparing(Order::getOrderDate));
}
break;
}
}
return orders.subList(0, Math.min(orders.size(), rowsPerPage));
}
}
</code></pre>
<p>And my question Is how can I do it at least more readable?Thanks for answering.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:56:10.423",
"Id": "515347",
"Score": "1",
"body": "Maybe you want to have a look at Javas [Streams-API](https://docs.oracle.com/javase/tutorial/collections/streams/). Also you might want to distinguish between foreward and reverse order before iterating over the entries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T07:00:53.243",
"Id": "515482",
"Score": "1",
"body": "Leeching the complete database into memory to filter and sort there is such a bad idea, that the resulting code should not even be reviewed. If you don't know how to do this via database queries, I recommend that you grab a tutorial and learn it, as this is basically the only serious approach to the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T08:29:10.090",
"Id": "515489",
"Score": "0",
"body": "@mtj I have Map that contains column name as key and column value as value. It all about order entity. I know how to work with jdbc but I dont know how to do it, If I have column name as variables. Can you help me with that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T09:22:49.233",
"Id": "515495",
"Score": "0",
"body": "Not really. As a starter, you might look into hibernate and the criteria API. This is a lot to tackle at a time, but definitely worthwile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T08:49:45.077",
"Id": "515680",
"Score": "0",
"body": "@mtj I have just done It by using Jdbc. Can you review my code and tell what should i improve?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T17:39:06.900",
"Id": "261152",
"Score": "3",
"Tags": [
"java",
"linked-list",
"database",
"stream"
],
"Title": "How can I filter and sort LinkedList faster and more effective?I have list of orders that should be processed"
}
|
261152
|
<p>Here is the code for the game :</p>
<pre><code>#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
using std::vector;
using std::cout;
using std::cin;
using std::endl;
using std::time;
using std::stringstream;
using std::string;
using std::to_string;
const string bot = "B";
void riftmaker(int coordx, int coordy , vector<vector<string>>& rboard);
void infinity_ikea(const vector<vector<string>>& rboard);
void introduction(const vector<vector<string>>& rboard);
bool legal(const vector<vector<string>>& rboard , int choice , string skin);
bool wincon(const vector<vector<string>>& rboard , int coordx , int coordy);
void COMMANDO(vector<vector<string>>& rboard, int choice, string skin, string command , string player);
void pepegaheadqurters(int coordx ,int coordy , vector<vector<string>>& rboard);
void error();
int skynet(vector<vector<string>>& rboard, string skin , int limit , int coordx , int coordy);
int main()
{
//elements
int coordx, coordy;
srand(static_cast<unsigned int>(time(0)));
//COORDS
cout << "enter horizntal size :";
cin >> coordx;
cout << "enter vertical size :";
cin >> coordy;
vector<vector<string>> board;
riftmaker(coordx, coordy, board);
//INTRODUCTIONS
introduction(board);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.get();
//main
pepegaheadqurters(coordx, coordy, board);
}
void riftmaker(int coordx , int coordy , vector<vector<string>>& rboard)//VECTOR ASSIGNER
{
int boardnumber = 1;
for (int i = 0; i < coordx; i++)
{
vector<string> row;
for (int j = 0; j < coordy; j++)
{
row.push_back(to_string(boardnumber));
boardnumber++;
}
rboard.push_back(row);
}
}
void infinity_ikea(const vector<vector<string>>& rboard) //PRINTER
{
int numberl;
for (vector<string> loop : rboard) {
for (string x : loop) {
stringstream geek(x);
geek >> numberl;
cout << x;
if (numberl < 10) {
cout << " | ";
}
else if (numberl < 100 || numberl > 9) {
cout << "| ";
}
else if (numberl == 0) {
cout << " | ";
}
else {
cout << " | ";
}
}
cout << "\n";
}
}
void introduction(const vector<vector<string>>& rboard) // INTRO
{
cout << "\t\t4-CONNECT\n\t-----------------------\n\n\n";
cout << "WELCOME TO 4-CONNECT U KNOW THE RULES AND THE SHT" << endl;
cout << "the board :" << endl;
infinity_ikea(rboard);
}
void pepegaheadqurters(int coordx, int coordy, vector<vector<string>>& rboard) //MAIN FUNCTION
{
//elements
int limit = coordx * coordy;
int blank = 0;
int boardnumber, loobyposition;
string skin, roboskin;
roboskin = 'B';
int robot;
int i = 0;
enum wincondition
{
win, lose, tie
};
wincondition w = win;
//main body
cout << "which letter will u use :";
cin >> skin;
cout << "\ndo u want to start first(0) or machine(1) :";
cin >> loobyposition;
error();
//game loop
while (blank != limit && wincon(rboard, coordx, coordy) != true)
{
if (loobyposition % 2 == 0) {
infinity_ikea(rboard);
cout << "enter number pls :";
cin >> boardnumber;
boardnumber -= 1;
COMMANDO(rboard, boardnumber, skin, "MOVE", "human");
wincon(rboard, coordx, coordy);
error();
infinity_ikea(rboard);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.get();
error();
blank++;
loobyposition++;
if (wincon(rboard , coordx , coordy)) {
w = win;
}
}
else if (loobyposition % 2 != 0 || wincon(rboard, coordx, coordy) != true) {
robot = skynet(rboard, skin, limit, coordx, coordy);
infinity_ikea(rboard);
cout << "my number is :" << robot << endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.get();
error();
loobyposition++;
blank++;
if (wincon(rboard , coordx , coordy)) {
w = lose;
}
}
}
infinity_ikea(rboard);
cout << "\n" << endl;
if (blank == limit && wincon(rboard, coordx, coordy) != true) {
w = tie;
}
if (w == win) {
cout << "congrats u won";
}
else if (w == lose) {
cout << "congreat u lose";
}
else {
cout << "TIE";
}
}
void error() // NEW PAGE
{
for (int i = 0; i < 1000; i++)
{
cout << "\n\n";
}
}
bool wincon(const vector<vector<string>>& rboard, int coordx, int coordy) //WIN CONDITIONS
{
bool check = true;
int equ1, equ2;
for (int x = 0; x < coordx; x++)
{
for (int y = 0; y < coordy; y++)
{
string startvalue = rboard[x][y];
int possiblex[4][2] = { {0 , 1} , {1 , 0} , {1 , -1} , {1 , 1} };
//checkloop
for (int j = 0; j < 4; j++)
{
check = true;
int i = 0;
for (int b = 1; b < 4; ++b) {
equ1 = (x + (b * possiblex[j][i]));
equ2 = (y + (b * possiblex[j][i + 1]));
if (equ1 < 0 || equ1 == coordx) {
check = false;
break;
}
else if (equ2 < 0 || equ2 == coordy) {
check = false;
break;
}
else
{
if (rboard[equ1][equ2] != startvalue) {
check = false;
}
}
}
if (check == true) {
return check;
}
}
}
}
return check;
}
void COMMANDO(vector<vector<string>>& rboard , int choice , string skin , string command , string player) //MOVE AND DELETE
{
int counter = 0;
int cols = 0;
vector<vector<string>>::iterator raw;
vector<string>::iterator col;
for (raw = rboard.begin(); raw != rboard.end(); raw++) {
for (col = raw->begin(); col != raw->end(); col++){
if (counter == choice) {
if (command == "MOVE") {
counter += raw->size();
while (raw != (rboard.end() - 1) && legal(rboard, counter, skin) == true)
{
raw++;
col = raw->begin() + cols;
counter += raw->size();
}
if (player == "human") {
*col = skin;
}
else
{
*col = bot;
}
}
else if (command == "DELETE") {
while (raw != (rboard.end() - 1) && legal(rboard, counter, skin) == true)
{
raw++;
col = raw->begin() + cols;
counter += raw->size();
}
if (*col == skin || *col == bot) {
*col = to_string(counter+1);
}
}
}
counter++;
cols++;
}
cols = 0;
}
}
bool legal(const vector<vector<string>>& rboard , int choice ,string skin ) //LEGAL OR NOT
{
int counter = 0;
for (vector<string> loop : rboard) {
for (string x : loop) {
if (choice == counter){
if (x == skin || x == bot) {
return false;
}
}
counter++;
}
}
return true;
}
int skynet(vector<vector<string>>& rboard, string skin, int limit, int coordx, int coordy) //AI
{
//checkwin and stop win
int counter = 0;
while (counter < limit) {
if (legal(rboard, counter, skin)) {
//check win
COMMANDO(rboard, counter, skin, "MOVE", "bot");
if (wincon(rboard, coordx, coordy) == true) {
return counter + 1;
}
COMMANDO(rboard, counter, skin, "DELETE", "bot");
//check enemy
COMMANDO(rboard, counter, skin, "MOVE", "human");
if (wincon(rboard, coordx, coordy) == true) {
COMMANDO(rboard, counter, skin, "DELETE", "human");
COMMANDO(rboard, counter, skin, "MOVE", "bot");
return counter + 1;
}
COMMANDO(rboard, counter, skin, "DELETE", "human");
}
counter++;
}
//random number generatror
for (int i = 0; i < 1000; i++)
{
counter = rand() % limit;
if (legal(rboard, counter, skin)) {
COMMANDO(rboard, counter, skin, "MOVE", "bot");
return counter + 1;
}
}
}
</code></pre>
<p>What could I have done better with this code, how could I make it shorter.</p>
<p>I know some functions have childish names, but I wrote their function near their definitions.</p>
<p>I overcomplicated stuff with the move and delete function and wincondition function, could I make it easier or not, or it's good.</p>
|
[] |
[
{
"body": "<p>I think there's quite a lot to improve, especially the first point I mention below. Consider updating your code according to the suggestions and then creating a new review question on Code Review.</p>\n<h1>Use proper names and spelling</h1>\n<blockquote>\n<p>I know some functions have childish names, but [...]</p>\n</blockquote>\n<p>The names are indeed childish. Sometimes it's fun to do this, but the consequence is that the code is now much harder to read. If you give a function or variable a name that clearly and concisely says what the function is supposed to do or represent, it is much easier to understand your source code. Not only is that important for others, but also for your future self! In half a year you will have forgotten the details, and then this code will look unreadable to you.</p>\n<p>I also recommend you use proper spelling, grammar and use consistent typography, and keep things professional. So instead of:</p>\n<pre><code>cout << "WELCOME TO 4-CONNECT U KNOW THE RULES AND THE SHT" << endl;\ncout << "the board :" << endl;\n</code></pre>\n<p>Write:</p>\n<pre><code>cout << "Welcome to Connect Four! The usual rules apply." << endl;\ncout << "The board:" << endl;\n</code></pre>\n<p>Write "you" instead of "u", <a href=\"https://english.stackexchange.com/questions/67394/spaces-around-a-colon\">don't add a space before a colon</a>, start sentences with a capital and end them with some kind of punctuation. Basically, write like you find text written in a book or on a professional website.</p>\n<p>Maybe this takes the fun out of things, but consider it good practice for your future career, and also be aware that what you post now on the Internet might stay there for a long time for everyone to see!</p>\n<h1>Avoid many <code>using std::</code>s</h1>\n<p>It's generally considered <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad practice to use <code>using namespace std</code></a>. You did not do that, but instead you have a whole list of <code>using std::something</code>s, in effect just being a more verbose form of <code>using namespace std</code>.</p>\n<h1>Use <code>\\n</code> instead of <code>std::endl</code></h1>\n<p>Prefer writing <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>\\n</code> instead of using <code>std::endl</code></a>, the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and just leads to worse performance.</p>\n<h1>Use C++11's random number generators</h1>\n<p>The <code>srand()</code> and <code>rand()</code> functions come from C, and are of low quality. Consider using the <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">C++11 random number functionality</a>. See <a href=\"https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c\">this StackOverflow post</a> for how to use it.</p>\n<h1>Create an <code>enum class</code> representing a cell on the board</h1>\n<p>Each cell on the board can be empty, have a piece of the human player, or that of the bot. Using a <code>std::string</code> for each cell is quite inefficient, and it's easy to make mistakes. Use an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\"><code>enum class</code></a> to define what the possible states of each cell are:</p>\n<pre><code>enum class Cell {\n EMPTY,\n HUMAN,\n BOT\n};\n</code></pre>\n<p>Then declare your board as:</p>\n<pre><code>std::vector<std::vector<Cell>> board;\n</code></pre>\n<p>Instead of writing <code>board[x][y] = skin</code>, you would now write <code>board[x][y] = Cell::HUMAN</code>. Apart from being more efficient, the benefit is also that the compiler will be able to catch certain mistakes. For example, if you assigned any other string to a cell besides <code>skin</code> or <code>roboskin</code>, you would only notice the mistake when the program was not behaving as expected. However, with an <code>enum class</code>, the compiler would complain about anything that wasn't defined earlier in <code>enum class Cell</code>.</p>\n<h1>Consider creating a <code>class</code> representing the board</h1>\n<p>You can encapsulate all the properties of a board in a <a href=\"https://en.cppreference.com/w/cpp/language/class\" rel=\"nofollow noreferrer\"><code>class</code></a>. You can start simple by just having it be a wrapper around the vector of vectors:</p>\n<pre><code>class Board {\npublic:\n std::vector<std::vector<Cell>> cells;\n};\n</code></pre>\n<p>And now in <code>main()</code>, you can write:</p>\n<pre><code>Board board;\n</code></pre>\n<p>And pass it around to all the other functions that want a board. This already avoids you having to write <code>std::vector<std::vector<std::string>> &rboard</code>, it can now just be <code>Board &rboard</code>.</p>\n<p>The next step is to make the functions manipulating the board member functions of <code>class Board</code>. This allows them easy access to the <code>cells</code>. For example:</p>\n<pre><code>class Board {\npublic:\n std::vector<std::vector<Cell>> cells;\n bool legal(int choice, Cell player) const;\n};\n\nbool Board::legal(int choice, Cell player) const {\n int counter = 0;\n for (vector<string> loop : cells) {\n ...\n }\n ...\n}\n</code></pre>\n<p>And then it can be called from "<code>skynet()</code>" as follows:</p>\n<pre><code>if (rboard.legal(counter, player)) {\n ...\n}\n</code></pre>\n<h1>Avoid using vectors of vectors</h1>\n<p>A <a href=\"https://stackoverflow.com/questions/38244435/what-are-the-issues-with-a-vector-of-vectors\">vector of vectors is an inefficient data structure</a>. Although for a simple game like connect four, it's not going to be an issue. Unfortunately, there's no nice 2D array type in the standard library, although there many external libraries that provide them. The standard trick however is to just use a single <code>std::vector</code>, give it as many elements in total as the original vector of vectors, and calculate the index into the one-dimensional vector. If you have a grid of <code>nrows</code> by <code>ncols</code> elements, then instead of writing:</p>\n<pre><code>std::vector<std::vector<...>> cells;\n...\ncells[x][y] = ...;\n</code></pre>\n<p>You would write:</p>\n<pre><code>std::vector<...> cells;\n...\ncells[x + y * ncols] = ...;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T00:14:56.553",
"Id": "515364",
"Score": "0",
"body": "Can u care to explain the last part in your answer, I can't seem to understand the equation at the end, and it the program, and I didn't use classes because my book didn't reach this part , but when the book reaches this part, I will be sure to use classes and post my code here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T00:23:18.393",
"Id": "515367",
"Score": "0",
"body": "here is the equation which I can't understand:`cells[x + y * ncols] = ...;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T00:27:47.153",
"Id": "515368",
"Score": "0",
"body": "I understood it now, u mean `cells[(x + ncols) + y] = ...;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T06:59:57.573",
"Id": "515379",
"Score": "0",
"body": "If you have a vector of length `nrows * ncols`, and `x` is representing the column and `y` the row, and assume first all the elements of the first row are stored in the vector, then all the elements of the second row and so on, then the start of each row in the vector is at offset `ncols * y` (because each row has `ncols` elements). Then we just add `x` to get to the right element within that row."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:42:23.077",
"Id": "515406",
"Score": "0",
"body": "ok, ty for your information @G. Sliepen"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T19:42:31.170",
"Id": "515439",
"Score": "0",
"body": "re \"in effect just being a more verbose form of using namespace std.\" I disagree. It specifically prevents the issues with `using namespace std;`, being that it drags in more than you actually wanted and may cause clashes in the future if more symbols are added to `std`. They are also properly declared in that scope rather than being a search path that works kind of differently from normal scope."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:01:30.720",
"Id": "515442",
"Score": "0",
"body": "@JDługosz True, but if it becomes a long list of `using std::*` statements then managing that list is going to be a source of problems. I think it's still better to be explicit with `std::`. Think for example of [`abs()`](https://en.cppreference.com/w/c/numeric/math/abs) vs [`std::abs()`](https://en.cppreference.com/w/cpp/numeric/math/abs), which behave differently when passing in a floating point number. Forgetting to use `using std::abs` is easy, won't result in a compile error, but might give unexpected results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:40:12.507",
"Id": "515448",
"Score": "0",
"body": "@G.Sliepen What does the C library's version of `abs` have to do with anything? In C++, all the overloads are in `std::` and _might_ be in the global namespace as well, depending on the implementation. I don't see anything about some of them being global and others not. If you include the C header's name instead, it's vice versa: they are put in global and _might_ also be in `std`. But again it's all the symbols, not just some selection of overloads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:58:24.417",
"Id": "515450",
"Score": "0",
"body": "@JDługosz For the math functions, there is only `<cmath>`, and this is the problem: https://godbolt.org/z/hbzxzeqef"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:42:18.447",
"Id": "515524",
"Score": "0",
"body": "@G.Sliepen how is that justified by the standard? I thought copying the symbols to global namespace was all or nothing, not just some of the overloads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-17T11:37:11.670",
"Id": "519478",
"Score": "0",
"body": "@JDługosz `using std::foo` does not copy `foo` into the global namespace, it merely makes it \"accessible for [unqualified lookup](https://en.cppreference.com/w/cpp/language/lookup) as if declared in the same class scope, block scope, or namespace as where this using-declaration appears\" according to [cppreference.com](https://en.cppreference.com/w/cpp/keyword/using)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-17T14:33:00.743",
"Id": "519504",
"Score": "0",
"body": "`using std::foo;` is a _using declaration_ which does declare `foo` in the current scope, like any **declaration**. `using namespace std;` is a _using directive_ which acts as a kind of search path for symbol lookup, as you are describing. I was referring to what I expect is a declaration `using std::abs;` in the global namespace. I see that it states \"as if\" now, which might be more of a technicality. It clashes with another symbol that's declared in that scope, etc. I suppose that's to match wording somewhere else that wants to refer to things _really_ declared in some scope."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T21:54:12.120",
"Id": "261161",
"ParentId": "261155",
"Score": "9"
}
},
{
"body": "<pre><code>wincon(rboard, coordx, coordy) != true\n</code></pre>\n<p>That's silly. Just write <code>!wincon(rboard, coordx, coordy)</code> for that term.</p>\n<pre><code> if (w == win) {\n cout << "congrats u won";\n }\n else if (w == lose) {\n cout << "congreat u lose";\n }\n else {\n cout << "TIE";\n }\n</code></pre>\n<p>Since you are checking the various values of an enumeration type, use a <code>switch</code> statement.</p>\n<p>And, I reiterate the point about <strong>spelling</strong> and the awful use of "u" for "you". When I read that I imagine <a href=\"https://en.wiktionary.org/wiki/Appendix:English_pronunciation\" rel=\"nofollow noreferrer\">/ʌ/</a> (like you started to say "up") rather than /ju/</p>\n<pre><code> for (vector<string> loop : rboard) {\n for (string x : loop) {\n</code></pre>\n<p>Do you realize that you are copying by value the vector of strings in the outer loop and the string in the inner loop? You should be using <code>const &</code> and best to use <code>auto</code> for the iteration variable because if it doesn't match the type exactly you can get extra conversions and copies without any error.</p>\n<hr />\n<p>Just what is it <em>doing</em>? It parses each string in the vector as a number... why not just store the numbers directly? And then it just prints spaces and pipe character depending on the range of the number (how many digits it has?). I have no idea what the point of this is, and the goofy names don't help.</p>\n<p>Edit: Ah, I see it prints the string first, then this adds trailing spaces plus the (unchanging) pipe and another space. You just want to print <code>x</code> justified to the full width. Look at the <code>ostream</code> features that do that automatically, such as the <code>setw</code> manipulator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:30:22.683",
"Id": "515445",
"Score": "1",
"body": "thank you for pointing things out, I will use them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T19:51:57.030",
"Id": "261209",
"ParentId": "261155",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T18:27:44.587",
"Id": "261155",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"game",
"vectors",
"connect-four"
],
"Title": "Improving C++ Connect-four game with little AI"
}
|
261155
|
<p>My .bash_aliases file contains several aliases.
In the beginning, when I wanted to see the aliases, I print the .bash_aliases file,</p>
<p>The output wasn't readable at all, so I created a python script to make it better.
To call my python script, I use the alias <code>print_aliases_manual</code></p>
<p>What is the most pythonic way to write the following script?</p>
<p>Here is my python script:</p>
<pre><code>
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
with open('/home/pi/.bash_aliases', 'r') as f:
lines = f.readlines()
for line in lines:
if r'##' in line:
print(f'{bcolors.HEADER}{bcolors.UNDERLINE}{bcolors.BOLD}{line}{bcolors.ENDC}')
elif r'#' in line:
print(f'{bcolors.WARNING}{line}{bcolors.ENDC}')
elif r'alias' in line:
drop_alias = line.replace('alias', '')
new_line = drop_alias.replace('=', ' ')
print(f'{bcolors.OKGREEN}{new_line}')
else:
print(f'{line}')
</code></pre>
<p>Here is my bash_aliases file:</p>
<pre><code>### Aliases list divided by category:
## General commands:
alias cdd="cd /home/pi/Desktop/speedboat/"
alias dc="sudo docker-compose"
alias pm2="sudo pm2"
## Cellular related commands:
alias pc="ping -I wwan0 www.google.com"
alias qmi="sudo qmicli -d /dev/cdc-wdm0 -p"
## AWS relaeted commands:
alias dlogs="sudo docker logs -f iot_service"
## Git commands:
alias gp="sudo git pull"
alias gc="sudo git checkout"
## scripts to run when deleting speedboat directory is needed:
# copying files to Desktop
alias stodtop="sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_to_desktop.sh"
# copying files from Desktop
alias sfromdtop="sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_from_desktop_to_speedboat.sh"
## verifications test and updates scripts
# run speedboat verifications tests
alias sinsta="sudo sh /home/pi/Desktop/speedboat/scripts/installation_verification.sh"
# run local unittests
alias slocalt="sudo sh /home/pi/Desktop/speedboat/scripts/run_local_unittest.sh"
# pull os updates from git and execute
alias supdate="sudo sh /home/pi/Desktop/speedboat/scripts/updates-speedboat.sh"
## speedboat start and stop scripts (dockers and PM2)
alias startr="sudo sh /home/pi/Desktop/speedboat/scripts/start_speedboat.sh"
alias stopr="sudo sh /home/pi/Desktop/speedboat/scripts/stop_speedboat.sh"
## AWS related scripts:
alias secrl="sudo sh /home/pi/Desktop/speedboat/scripts/ecr-login.sh"
alias slog="sudo sh /home/pi/Desktop/speedboat/scripts/log_register.sh"
## Command to run speedboat aliases manual:
alias print_aliases_manual="python3 /home/pi/Desktop/speedboat/verification/test_verification_speedboat/colored_aliases_manual.py"
</code></pre>
|
[] |
[
{
"body": "<p><strong><code>print</code></strong></p>\n<p>f-Strings are a great and convenient tool for including variables and calculations in strings. I'd say they're generally not needed when printing only variables. For example</p>\n<pre><code>print(f'{bcolors.WARNING}{line}{bcolors.ENDC}')\n</code></pre>\n<p>could become</p>\n<pre><code>print(bcolors.WARNING, line, bcolors.ENDC, sep='')\n</code></pre>\n<p>However I'm not sure which of the two is more pythonic, I personally prefer the latter for readability.</p>\n<p>You could also consider pulling out formatting into seperate variables to increase readability.</p>\n<pre><code>HEADER_FORMAT = "".join((bcolors.HEADER, bcolors.UNDERLINE, bcolors.BOLD, "{}", bcolors.ENDC))\n\nprint(HEADER_FORMAT.format(line))\n</code></pre>\n<hr />\n<p><strong><code>in</code> vs. <code>startswith</code></strong></p>\n<p>I'd recommend using <code>str.startswith</code> instead of <code>str in str</code> for checking prefixes.</p>\n<pre><code>if r'##' in line:\n</code></pre>\n<p>becomes</p>\n<pre><code>if line.startswith(r"##"):\n</code></pre>\n<p>This is less error-prone and conveys your intentions more explicitly, without the need to look at the source file. As there aren't any escape characters in your prefixes, you also don't need to make it a raw string. You can simply drop the <code>r</code>:</p>\n<pre><code>if line.startswith("##"):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T07:36:24.927",
"Id": "515386",
"Score": "2",
"body": "@Reinderien Maybe I‘m looking at the wrong line here, but the second print has its seperator set to an empty string via the sep argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:01:52.880",
"Id": "515403",
"Score": "1",
"body": "You're right, my apologies"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T23:09:27.483",
"Id": "261166",
"ParentId": "261163",
"Score": "10"
}
},
{
"body": "<p>First, a laundry list of things:</p>\n<ul>\n<li><code>bcolors</code> is not only colours; "underline" and "end code" are not colours. Call this perhaps <code>ANSICodes</code>, title-case to be PEP8-compliant.</li>\n<li><code>'r'</code> is the default file mode and can be omitted</li>\n<li>Do not hard-code your home directory</li>\n<li>You don't need <code>readlines</code>; iterate over the file object</li>\n<li>As @riskypenguin suggests, <code>in</code> is not the right tool here. Consider <code>startswith</code> for your header and comments, and a regex for the aliases.</li>\n<li>Pre-binding to format calls will clean things up a little</li>\n<li>Try piping your output through <code>less</code> and observe the fireworks. You need to be assured that your <code>stdout</code> is a real TTY.</li>\n<li>Consider making a fixed field width for your alias keys instead of four absolute spaces</li>\n</ul>\n<h2>Example</h2>\n<p>Note that I'm using a different file path from you.</p>\n<pre><code>import re\nfrom os import getenv\nfrom pathlib import Path\nfrom sys import stdout\nfrom typing import Callable\n\n# Terrible workaround for Pycharm\nDECORATE = stdout.isatty() or getenv('PYCHARM_HOSTED')\n\nRE_ALIAS = re.compile(r'^alias (.+)="(.+)"')\n\n\nclass ANSICodes:\n RED = '\\033[91m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n BLUE = '\\033[94m'\n PINK = '\\033[95m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n ENDC = '\\033[0m'\n\n @classmethod\n def decorate(cls, *codes: str) -> Callable[[str], str]:\n return ''.join((\n *codes, '{}', cls.ENDC,\n )).format\n\n\nheader1 = ANSICodes.decorate(ANSICodes.PINK, ANSICodes.UNDERLINE, ANSICodes.BOLD)\ncomment = ANSICodes.decorate(ANSICodes.YELLOW)\nalias = ANSICodes.decorate(ANSICodes.GREEN)\n\n\ndef transform(line: str) -> str:\n match = RE_ALIAS.match(line)\n if match:\n k, v = match.groups()\n line = f'{k:7} {v}'\n if DECORATE:\n return alias(line)\n return line\n\n if DECORATE:\n if line.startswith('##'):\n return header1(line)\n if line.startswith('#'):\n return comment(line)\n\n return line\n\n\ndef main():\n path = Path('.bash_aliases')\n # path = Path('~/.bash_aliases').expanduser()\n with path.open() as f:\n for line in f:\n print(transform(line.rstrip()))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T04:04:58.763",
"Id": "515372",
"Score": "1",
"body": "THX!!! That is genuinely beneficial. @Reinderien, can you please explain how to pipe the stdout throw less?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T12:44:28.050",
"Id": "515402",
"Score": "3",
"body": "@Monty_emma Instead of `print_aliases_manual`, you'd have `print_aliases_manual | less`. The `|` is a pipe."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T03:49:40.633",
"Id": "261173",
"ParentId": "261163",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T22:28:45.050",
"Id": "261163",
"Score": "7",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python script that make my .bash_aliases file MUCH more readable and clear"
}
|
261163
|
<p>I've made this script to automate blocking some deviant hosts on my router, and was curious if there's anything much else that can be done to make it quicker and more efficient.</p>
<p>Presently I'm restricted to using packages available on the <a href="https://bin.entware.net/armv7sf-k3.2/Packages.html" rel="nofollow noreferrer">Entware repository</a> and the latest Busybox/ash shell environment. So, for example, I can't use commands like <code>sort -S 25% --parallel=4 -u adblock.sources</code> (though awk/gawk is faster and more memory efficient anyway).</p>
<p><strong>update_the_blacklist.sh</strong></p>
<pre class="lang-bsh prettyprint-override"><code>curl -GOs https://raw.githubusercontent.com/T145/packages/master/net/adblock/files/adblock.sources
for key in $(jq -r 'keys[]' adblock.sources); do
case $key in
gaming | osid_basic )
# Ignore these lists
;;
* )
url=$(jq -r ".$key.url" adblock.sources)
rule=$(jq -r ".$key.rule" adblock.sources)
case $url in
*.tar.gz )
curl -s $url | \
tar -xOzf - | \
gawk "$rule" | \
sed "s/\r//g" | \
sed 's/^/0.0.0.0 /' >> the_blacklist.temp.txt
;;
* )
curl -s $url | \
gawk "$rule" | \
sed "s/\r//g" | \
sed 's/^/0.0.0.0 /' >> the_blacklist.temp.txt
esac
unset url
unset rule
esac
done
# Filter duplicate hosts
gawk '!a[$0]++' the_blacklist.temp.txt > the_blacklist.txt
rm the_blacklist.temp.txt
rm adblock.sources
</code></pre>
|
[] |
[
{
"body": "<p>We're missing a shebang line. The question is tagged <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged 'bash'\" rel=\"tag\">bash</a>, but that seems overkill, since there's nothing here that's not standard POSIX shell.</p>\n<pre><code>#!/bin/sh\n</code></pre>\n<p>We append to <code>the_blacklist.temp.txt</code>, but don't ensure that it starts off empty, or that it's even writeable. It's best to create temporary files using <code>mktemp</code>:</p>\n<pre><code>tmpfile=mktemp || exit $?\ntrap "rm $tmpfile" EXIT\n</code></pre>\n<p>Also, instead of directing final output to <code>the_blacklist.txt</code>, it would be more flexible to write to standard output, and let the user choose where to send it (perhaps pipe into another filter).</p>\n<p>But there seems to be no reason to use a file here - just pipe the <code>for</code> loop directly into <code>awk</code> (or into <code>sort -u</code> - that may be a better choice if you're memory-constrained, as it will perform an external merge-sort if it needs to).</p>\n<p>The duplicated <code>sed</code> pipe could be replaced with a single <code>sed</code> program of two commands:</p>\n<pre><code>for\n …\ndone |\n sed -e 's/\\r//g' -e 's/^/0.0.0.0 /' | gawk '!a[$0]++'\n</code></pre>\n<p>There's a security issue here:</p>\n<blockquote>\n<pre><code> gawk "$rule" | \\\n</code></pre>\n</blockquote>\n<p>We are executing downloaded content in <code>awk</code>. Because we can't be sure that the <code>adblock.sources</code> URL cannot be replaced with a more harmful version, we should run <code>awk</code> in its constrained "sandbox" mode, and use the <code>--</code> separator so we don't interpret the script as arguments.</p>\n<pre><code> gawk --sandbox -- "$rule" | \\\n</code></pre>\n<hr />\n<p>These changes give me</p>\n<pre><code>#!/bin/sh\n\nset -eu\n\nsources=$(mktemp)\ntrap 'rm "$sources"' EXIT\n\ncurl -s -o "$sources" https://raw.githubusercontent.com/T145/packages/master/net/adblock/files/adblock.sources\n\nfor key in $(jq -r 'keys[]' "$sources")\ndo\n case $key in\n gaming | osid_basic )\n # Ignore these lists\n ;;\n * )\n url=$(jq -r ".$key.url" "$sources")\n rule=$(jq -r ".$key.rule" "$sources")\n\n curl -s "$url" |\n case $url in\n *.tar.gz) tar -xOzf - ;;\n *) cat ;;\n esac |\n gawk --sandbox -- "$rule"\n esac\ndone |\n sed -e 's/\\r//g' -e 's/^/0.0.0.0 /' | sort -u\n</code></pre>\n<p>Somebody more expert with <code>jq</code> could probably avoid the remaining temporary file by making a single pass over the retrieved data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T08:54:46.443",
"Id": "261180",
"ParentId": "261165",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T22:53:21.837",
"Id": "261165",
"Score": "3",
"Tags": [
"bash",
"linux",
"shell",
"sh"
],
"Title": "The Blacklist: Blocking Malicious domains using Bash"
}
|
261165
|
<p>I am here to ask for some more experienced programmers to critique my first project. I wanted to see where I lack and what I can improve on. Thank you for taking time out of your day to help me better my skills as a programmer! I hope I did a good job for being a beginner but I know there is much more to learn!</p>
<pre><code>game_board = ['1','2','3','4','5','6','7','8','9']
original_board = ['1','2','3','4','5','6','7','8','9']
player1 = ''
player2 = ''
isFull = False
game_on = True
winner = False
def display_board(board):
print(board[0]+'|'+board[1]+'|'+board[2])
print(board[3]+'|'+board[4]+'|'+board[5])
print(board[6]+'|'+board[7]+'|'+board[8])
def player_input():
global player1
global player2
while player1 != 'X' or player1 != 'O':
player1 = input("Which do you want to be? (X or O): ")
player1 = player1.upper()
if player1 == 'X':
print("Player 1 has chosen X.")
player1 = 'X'
player2 = 'O'
break
elif player1 == 'O':
print("Player 1 has chosen O.")
player1 = 'O'
player2 = 'X'
break
return player1
def place_marker(board, player, position):
board[position-1] = player
return board[position-1]
def win_check(board):
global player1
global player2
global game_on
global winner
if board[0] == 'O' and board[1] == 'O' and board[2] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[0] == 'O' and board[4] == 'O' and board[8] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[2] == 'O' and board[4] == 'O' and board[6] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[0] == 'O' and board[3] == 'O' and board[6] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[1] == 'O' and board[4] == 'O' and board[7] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[2] == 'O' and board[5] == 'O' and board[8] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[3] == 'O' and board[4] == 'O' and board[5] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
elif board[6] == 'O' and board[7] == 'O' and board[8] == 'O':
if player1 == 'O':
print("Player 1 (O) has won!")
game_on = False
winner = True
else:
print("Player 2 (O) has won!")
game_on = False
winner = True
if board[0] == 'X' and board[1] == 'X' and board[2] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[0] == 'X' and board[4] == 'X' and board[8] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[2] == 'X' and board[4] == 'X' and board[6] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[0] == 'X' and board[3] == 'X' and board[6] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[1] == 'X' and board[4] == 'X' and board[7] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[2] == 'X' and board[5] == 'X' and board[8] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[3] == 'X' and board[4] == 'X' and board[5] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
elif board[6] == 'X' and board[7] == 'X' and board[8] == 'X':
if player1 == 'X':
print("Player 1 (X) has won!")
game_on = False
winner = True
else:
print("Player 2 (X) has won!")
game_on = False
winner = True
def space_check(board, position):
isTaken = False
if board[position - 1] == 'X' or board[position - 1] == 'O':
print("That position is already taken choose again.")
isTaken = True
else:
pass
return isTaken
def full_board_check(board):
global isFull
global original_board
for num in range(9):
if board[num] == original_board[num]:
return isFull
else:
isFull = True
return isFull
def player_choice(board):
good = False
while good == False:
choice = int(input("Choose a spot: "))
space_check(board, choice)
if space_check(board, choice) == False:
good = True
return choice
return choice
def replay():
global game_board
global player1
global player2
global isFull
global game_on
keep_playing = True
while keep_playing == True:
replay = input("Do you want to replay? (Y or N): ")
replay = replay.upper()
if replay == 'Y':
game_board = ['1','2','3','4','5','6','7','8','9']
player1 = ''
player2 = ''
game_on = True
isFull = False
elif replay == 'N':
keep_playing = False
print("Thanks for playing!")
print("Welcome to Tic Tac Toe!")
while isFull == False:
display_board(game_board)
player_input()
while game_on:
full_board_check(game_board)
if isFull == True and winner == False:
print("The game is a tie!")
game_on = False
break
if game_on:
print("Player 1's turn.")
place_marker(game_board, player1, player_choice(game_board))
display_board(game_board)
win_check(game_board)
full_board_check(game_board)
if isFull == True and winner == False:
print("The game is a tie!")
game_on = False
break
if game_on:
print("Player 2's turn.")
place_marker(game_board, player2, player_choice(game_board))
display_board(game_board)
win_check(game_board)
break
</code></pre>
|
[] |
[
{
"body": "<p>You need to add exception handling in player_choice. Currently, if I type in 'Y', the game crashes with error code:</p>\n<pre><code>Traceback (most recent call last):\n File "/Users/jake/Documents/TTRreview.py", line 299, in <module>\n place_marker(game_board, player2, player_choice(game_board))\n File "/Users/jake/Documents/TTRreview.py", line 246, in player_choice\n choice = int(input("Choose a spot: "))\nValueError: invalid literal for int() with base 10: 'y'\n</code></pre>\n<p>also, if I type an integer larger that 9 or smaller than one, the game behaves oddly, because python simply rolls over the array instead of giving an error. Change the code to read:</p>\n<pre><code>def player_choice(board):\n good = False\n while good == False:\n try:\n choice = int(input("Choose a spot: ")) \n except:\n continue #takes care of the game crashing with bad input\n if choice < 1 or choice > 9:\n continue #takes care of the game behaving oddly because of how python handles arrays\n space_check(board, choice)\n if space_check(board, choice) == False:\n good = True\n return choice\n return choice\n</code></pre>\n<p>Lastly, make sure you make comments on your code :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:20:28.750",
"Id": "515453",
"Score": "0",
"body": "Thank you for finding a flaw in my code. Thank you for showing me how to fix it and adding comments explaining what does what. I will start making a habit to adding comments in my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:57:38.003",
"Id": "515459",
"Score": "0",
"body": "Only add comments for \"business logic\" in the code, things that are unique to that program. Avoid obvious comments like \"converts this string to uppercase\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T22:25:37.903",
"Id": "515462",
"Score": "1",
"body": "Yes, but if you have to choose, err on the side of more comments rather than fewer. Anyone who works on from your code in the future will thank you"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T03:08:29.730",
"Id": "261171",
"ParentId": "261169",
"Score": "7"
}
},
{
"body": "<p>I'll point out some useful starting points for improving your code. I would additionally recommend looking at some other implementations, for some further inspiration regarding logic and code structure. There are a lot on this site alone, here's a starting point from recent memory: <a href=\"https://codereview.stackexchange.com/q/259809/239401\">Tic-tac-toe in python with OOP</a>.</p>\n<hr />\n<p><strong>Code structure</strong></p>\n<p>You rely on a few global variables (<code>game_board</code>, <code>original_board</code>, <code>player1</code>, <code>player2</code>, <code>isFull</code>, <code>game_on</code>, <code>winner</code>). This is generally not considered good practice for a variety of reasons and it can be avoided in most cases.</p>\n<hr />\n<p><strong>Naming</strong></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8</a>: <em>"Function names should be lowercase, with words separated by underscores as necessary to improve readability.\nVariable names follow the same convention as function names."</em></p>\n<hr />\n<p><strong>Unnecessary <code>return</code></strong></p>\n<p>Most of your functions return a value, but since they change the global variables the return value is never needed / used (e.g. <code>player_input</code>, <code>place_marker</code>, <code>full_board_check</code>). In your current implementation you could simply delete those return statements as they're never used. In an improved version I recommend using the return values instead of writing to global variables.</p>\n<hr />\n<p><strong><code>display_board</code></strong></p>\n<p>Very rarely in Python (and programming in general) should you hardcode indices as it makes code less readable, maintainable and scalable. Consider this approach using list slicing:</p>\n<pre><code>def display_board(board):\n row_length = 3\n for i in range(0, len(board), row_length):\n print('|'.join(board[i:i+row_length]))\n</code></pre>\n<p>Now if you ever want to change the board size / row length or the column separator, it will be a lot easier.</p>\n<hr />\n<p><strong><code>player_input</code></strong></p>\n<p>Consider this improved function:</p>\n<pre><code>def player_input():\n global player1\n global player2\n\n options = {'X', 'O'}\n\n while True:\n player1 = input(f"Which do you want to be? ({' or '.join(options)}): ").upper()\n\n if player1 in options:\n options.remove(player1)\n player2 = options.pop()\n break\n\n print(f"Player 1 has chosen {player1}.")\n print(f"Player 2 is {player2}.")\n</code></pre>\n<p>A few things to notice here:</p>\n<ul>\n<li>Your <code>while</code> loop had redundant logic: It checks if <code>player1 is not in {'X', 'O'}</code> each iteration, but once <code>player1</code> is either of those values it immediately <code>break</code>s. Meaning that the <code>while</code>-condition will never be relevant.</li>\n<li>The assignment <code>if player1 == 'X': ... player1 = 'X'</code> is redundant.</li>\n<li>We can pull out the <code>print</code> statement to the end of the function, as the text is the exact same, except for the value of <code>player1</code>. f-Strings provide a really convenient and redable way to include variables in a string.</li>\n<li>If we decide to change player symbols, this function only requires changes in a single place. The options for player symbols should probably be moved to a module constant to make changing them even easier.</li>\n</ul>\n<hr />\n<p><strong><code>win_check</code></strong></p>\n<p>This is probably the function you could and should save yourself the most work on. Manually writing out all the possible winning configurations is error-prone and hard to maintain. I'd recommend looking at some other implementations (and the corresponding reviews) to get an idea of how to make this easier for yourself.</p>\n<p>Everytime you find yourself copying or repeating code, you should stop to think if there's a pattern there. A naive implementation is often a good starting point to familiarize yourself with the problem. Once you have an understanding for the underlying logic you should start looking to improve your approach. For example: Even if you still manually check all the possible winning configurations, you should pull out the common part of the different conditions into a separate function. I'm talking about this part, which repeats 10+ times in this single function:</p>\n<pre><code>if player1 == 'O':\n print("Player 1 (O) has won!")\n game_on = False\n winner = True\nelse:\n print("Player 2 (O) has won!")\n game_on = False\n winner = True\n</code></pre>\n<p>This code snippet should also be simplified to something like</p>\n<pre><code>winner_number = 1 if player1 == 'O' else 2\nprint(f"Player {winner_number} (O) has won!")\n\ngame_on = False\nwinner = True\n</code></pre>\n<p>Another consideration for further improvements:</p>\n<p>These two conditions</p>\n<pre><code>if board[0] == 'O' and board[1] == 'O' and board[2] == 'O'\nif board[0] == 'X' and board[1] == 'X' and board[2] == 'X'\n</code></pre>\n<p>use the same logic. The only <strong>variable</strong> is the symbol that's checked. This should be an indication that a variable should be used instead of all the possible values. We only need to check if the spots contain the same symbol, not which one exactly it is:</p>\n<pre><code>if board[0] == board[1] == board[2]:\n\n winning_symbol = board[0]\n\n winning_number = 1 if player1 == winning_symbol else 2\n print(f"Player {winning_number} ({winning_symbol}) has won!")\n\n game_on = False\n winner = True\n</code></pre>\n<p>Again, the code inside the condition should be put into its own function to reduce code duplication.</p>\n<hr />\n<p>These suggestions are merely starting points for improvements, there are a lot more simplifications that can be done. You're always welcome to come back to CodeReview with an improved version to get another round of feedback. =)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:19:14.313",
"Id": "515452",
"Score": "1",
"body": "Thank you so much for the review! I am currently going through your suggestions and will keep them in mind for the next project I work on. Thank you again for taking time out of your day to help a newbie like myself."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T10:32:51.690",
"Id": "261184",
"ParentId": "261169",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T01:01:02.697",
"Id": "261169",
"Score": "9",
"Tags": [
"python",
"tic-tac-toe"
],
"Title": "Python: Tic Tac Toe Game"
}
|
261169
|
<p>Is there any room for improvement, in terms of simplicity and efficiency?</p>
<pre><code>from random import randint
class Dice():
def __init__(self):
"""Making a dice instance with 6 sides."""
self.sides = 6
class Roller(Dice):
def __init__(self,name,age):
"""Making a Dice Roller Instance"""
super().__init__()
#inhert sides attribute of a dice
self.name = name
self.age = str(age)
def describe_roller(self):
"""Describe the information of the roller"""
print('name: ' + self.name.title())
print('age: ' + self.age)
def roll_multiple(self,t):
"""Roll the dice multiple times and keep count in a dict"""
count = {}
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
for i in range(0,t):
key = randint(1, self.sides)
if key == 1:
one += 1
count["one"] = one
elif key == 2:
two += 1
count["two"] = two
elif key == 3:
three += 1
count["three"] = three
elif key == 4:
four += 1
count["four"] = four
elif key == 5:
five += 1
count["five"] = five
elif key == 6:
six += 1
count["six"] = six
print(count)
mike = Roller('mike',25)
mike.roll_multiple(6)
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><code>Roller</code> should not inherit from <code>Dice</code>, as <code>Roller</code> represents a human. Humans being a sub-class of <code>Dice</code> is pretty unintuitive. Rather, <code>Roller</code> should have an attribute: <code>self.dice = Dice()</code></li>\n<li>There's no particular reason <code>Roller.age</code> should be of type <code>str</code>. I'd keep it as an <code>int</code> and only convert to <code>str</code> if you need its string-represantation.</li>\n<li>f-Strings are a really convenient tool for creating strings containing variables / expressions. They also handle converting to <code>str</code> for you. Example: <code>print(f'age: {self.age}')</code></li>\n<li>You don't need the empty parantheses in <code>class Dice()</code></li>\n<li>You should put a space after the comma between arguments in a function call: <code>mike = Roller('mike',25)</code> becomes <code>mike = Roller('mike', 25)</code></li>\n<li><code>roll_multiple</code> should be a method of <code>Dice</code> that can be called by the <code>Roller</code>. This is part of an intuitive API. Users (including yourself) will probably expect to roll the dice, not the human. If you need <code>Roller.roll_multiple</code>, I'd only make it a wrapper for <code>Dice.roll_multiple</code>.</li>\n<li><code>roll_multiple(self, t)</code>: <code>t</code> is not a particularly expressive variable name, something like <code>times</code> would be better for readability.</li>\n<li>Adding type hints (<a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a>) increases the readability of your code.</li>\n<li>It's a convention in Python to name variables, whose values you don't actually use, <code>_</code>. So <code>for i in range(0,t):</code> becomes <code>for _ in range(t):</code>. Notice that you don't need to provide zero as the first argument as it's the default start for <code>range</code>.</li>\n<li>Passing <code>sides</code> as a default argument to the constructor of <code>Dice</code> makes the class a whole lot more versatile.</li>\n</ol>\n<hr />\n<p><strong>Algorithm</strong></p>\n<p>Hardcoding values like</p>\n<pre><code>one = 0\ntwo = 0\nthree = 0\n...\n</code></pre>\n<p>should always raise a red flag when writing code. This is neither necessary nor recommended in most situations. You already laid the groundwork by putting <code>Dice.sides</code> in an attribute, now we need to use it. You also don't need to keep a seperate count of the occured values outside of the <code>dict</code>. I implemented it to exactly mirror your functionality (i.e. using string-representations as keys for the dict and only counting numbers that actually occured), inside of <code>class Dice</code>:</p>\n<pre><code>from random import randint\nfrom collections import defaultdict\nfrom num2words import num2words\n\n...\n\ndef roll(self) -> int:\n return randint(1, self.sides)\n\ndef roll_multiple(self, times: int) -> dict:\n count = defaultdict(int)\n\n for _ in range(times):\n number = self.roll()\n key = num2words(number=number)\n count[key] += 1\n\n return dict(count)\n</code></pre>\n<p><a href=\"https://pypi.org/project/num2words/\" rel=\"nofollow noreferrer\"><code>num2words</code></a> is a third-party library, that needs to be installed first.</p>\n<p>If having keys of type <code>int</code> is fine for your use case, I would recommend using them as they're way more usable for further calculations. You also don't necessarily need to cast to <code>dict</code>, as a <code>defaultdict</code> provides all the same basic functionality. It does make a difference when printing though. Here is the adjusted implementation:</p>\n<pre><code>def roll_multiple(self, times: int) -> defaultdict:\n count = defaultdict(int)\n\n for _ in range(times):\n key = self.roll()\n count[key] += 1\n\n return count\n</code></pre>\n<hr />\n<p><strong>Suggested code</strong></p>\n<pre><code>from random import randint\nfrom collections import defaultdict\n\n\nclass Dice:\n def __init__(self, sides: int = 6):\n """Making a dice instance with a variable number of sides."""\n self.sides = sides\n\n def roll(self) -> int:\n """Returns the result of a single dice roll."""\n return randint(1, self.sides)\n\n def roll_multiple(self, times: int) -> defaultdict:\n """Provides the results of a variable number of dice rolls in a defaultdict."""\n count = defaultdict(int)\n\n for _ in range(times):\n key = self.roll()\n count[key] += 1\n\n return count\n\n\nclass Roller:\n def __init__(self, name: str, age: int) -> None:\n """Making a Dice Roller Instance"""\n self.name = name\n self.age = age\n\n self.dice = Dice()\n\n def describe_roller(self) -> None:\n """Describe the information of the roller"""\n print(f'name: {self.name.title()}')\n print(f'age: {self.age}')\n\n def roll_multiple(self, times: int) -> None:\n """Roll the dice multiple times and print the result"""\n print(self.dice.roll_multiple(times))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T18:32:02.390",
"Id": "515434",
"Score": "2",
"body": "Overall agree. Drop the `__init__ -> None`; refer https://stackoverflow.com/questions/64933298/why-should-we-use-in-def-init-self-n-none"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T18:34:03.060",
"Id": "515435",
"Score": "1",
"body": "...the above link actually argues in favour of an explicit `None`; https://github.com/python/mypy/issues/604 for more nuance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:08:29.553",
"Id": "515444",
"Score": "2",
"body": "Interesting, thanks for providing the discussion links. I've also found the return type annotation for `__init__` rather unnecessary but I usually go full type hint for reviews (when recommending type hints at least)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T03:12:26.317",
"Id": "515469",
"Score": "1",
"body": "Oh wow. This is the guidance and advice that I really needed. The result counting and storing part advice really hit the spot. Thank you for taking your time explaining and simplifying. I really really appreciate it. This really motivates me to code and learn more. Thank you so much."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:56:15.743",
"Id": "261201",
"ParentId": "261177",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261201",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T07:53:57.657",
"Id": "261177",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Dice rolling program which also counts and stores the result"
}
|
261177
|
<p>Hmm, I know this has been implemented countless times, and Python 3.9.5 <code>math</code> standard library has a built-in <code>gcd()</code> method that does exactly this, but this is how I do this, I think completing simple programming challenges using new ways will let gain experience that will help me find ingenious ways to overcome unprecedented practical programming challenges, so bear with me.</p>
<p>This implementation uses prime factorization method, it has three functions: <code>factors()</code>, <code>gcd()</code> and <code>main()</code>, the first function returns a dictionary object, the keys of the dictionary are the base prime factors of the inputted number, the values are the powers (how many times the factor should multiply by itself) of the keys, the dictionaries are created with one key<code>{'1': 1}</code>;</p>
<p>And the second function accepts two numbers, uses each number as inputs to the first function, the compares the resultant dictionaries, removes keys of the first dictionary not contained in the second dictionary, and reduces the values of keys of the first dictionary to their respective values in the second dictionary if their values in first dictionary is greater than the second dictionary.</p>
<p>Then the second function gets the product of all keys ^ values of the first dictionary.</p>
<p>The third function applies <code>gcd()</code> recursively to the list of numbers if there are more than two numbers.</p>
<p>This is the code, it is fully functional, and works properly if the inputs are valid:</p>
<pre class="lang-py prettyprint-override"><code>import math
import sys
def factors(n):
factors = {'1': 1}
f = 2
while f <= int(math.sqrt(n)):
while n % f == 0:
if f'{f}' in factors.keys():
factors.update({f'{f}': factors[f'{f}'] + 1})
else:
factors[f'{f}'] = 1
n = int(n / f)
f += 1
if n > 1: factors[f'{n}'] = 1
return factors
def gcd(x, y):
f1 = factors(x)
f2 = factors(y)
for f in f1.copy().keys():
if f not in f2.keys():
f1.pop(f)
elif f1[f] > f2[f]:
f1[f'{f}'] = f2[f]
cd = 1
for f in f1.keys():
cd *= int(f) ** f1[f]
return cd
def main(args):
args = list(map(int, args))
cd = gcd(args[0], args[1])
if len(args) > 2:
for i in args[2:]:
cd = gcd(cd, i)
print(cd)
args = sys.argv[1:]
main(args)
</code></pre>
<p>Currently I think two areas need be improved:</p>
<p>1, I need a better way than dictionaries to keep track of the divisors, so that I can easily find divisors not contained in the other number and find the lower power of the same divisor.</p>
<p>2, make the <code>gcd()</code> function do what <code>main()</code> function does internally so that the <code>main()</code> function isn't needed, currently I can't figure out a way to do this.</p>
<p>How can this script be improved?</p>
|
[] |
[
{
"body": "<p>It's more common to use <a href=\"https://en.wikipedia.org/wiki/Euler_method\" rel=\"nofollow noreferrer\">Euler's method</a> to find GCD, rather than factorising both numbers. However, I'll continue reviewing with the existing algorithm, as there's useful insights to be found.</p>\n<hr />\n<p>First, let's look at <code>factors()</code>.</p>\n<p>Our <code>factors</code> variable is being used as a counter or <em>multiset</em>, and Python provides us with a <a href=\"https://docs.python.org/3/library/collections.html#counter-objects\" rel=\"nofollow noreferrer\">collections.Counter</a> class for that.</p>\n<p>With <code>from collections import Counter</code>, we can replace</p>\n<blockquote>\n<pre><code> if f'{f}' in factors.keys():\n factors.update({f'{f}': factors[f'{f}'] + 1})\n else:\n factors[f'{f}'] = 1\n</code></pre>\n</blockquote>\n<p>with</p>\n<pre><code> factors[f] += 1\n</code></pre>\n<p>(I've also changed to using the numbers themselves as keys, instead of converting to string).</p>\n<p>The division <code>int(n / f)</code> can be rewritten using integer divide operator <code>n // f</code> (and we know the result will be exact, as we tested <code>n % f == 0</code>). Also, we should use <a href=\"https://docs.python.org/3/library/math.html#math.isqrt\" rel=\"nofollow noreferrer\"><code>math.isqrt()</code></a> rather than <code>int(math.sqrt())</code> when we want an integer.</p>\n<pre><code>from collections import Counter\n\ndef factors(n):\n factors = Counter({1: 1, n: 1})\n for f in range(2, 1 + math.sqrt(n)):\n while n % f == 0:\n factors[f] += 1\n n = n // f\n return factors\n</code></pre>\n<hr />\n<p>Now let's look at <code>gcd()</code>.</p>\n<p>We are computing the <em>intersection</em> of the two multisets. The operator <code>&</code> does exactly that for us:</p>\n<pre><code>common_factors = f1 & f2\ncd = 1\nfor f in common_factors.keys():\n cd *= f ** common_factors[f]\n</code></pre>\n<p>When we iterate over a dictionary, we don't need to get the keys and then index again. We can iterate over its <code>items()</code> instead, like this:</p>\n<pre><code>for f,count in common_factors.items():\n cd *= f ** count\n</code></pre>\n<p>Or we could expand the multiset using <code>elements()</code>:</p>\n<pre><code>for f in common_factors.elements():\n cd *= f\n</code></pre>\n<p>This allows us to then use <code>math.prod()</code> instead of our own loop:</p>\n<pre><code>return math.prod(common_factors.elements())\n</code></pre>\n<p>The whole lot then becomes a one-liner:</p>\n<pre><code>def gcd(x, y):\n return math.prod((factors(x) & factors(y)).elements())\n</code></pre>\n<hr />\n<p>Next, <code>main()</code>. The heart of this function is what a functional programmer would call <em>reduce</em>, and - you guessed it - Python provides a <a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>reduce()</code></a> function, in <code>functools</code>:</p>\n<pre><code>def main(args):\n args = map(int, args)\n print(reduce(gcd, args))\n</code></pre>\n<hr />\n<p>Finally, it's good practice to use a <code>main</code> guard, so the program can become a module:</p>\n<pre><code>if __name__ == "__main__":\n args = sys.argv[1:]\n main(args)\n</code></pre>\n<hr />\n<h1>Simplified code</h1>\n<pre><code>import math\nimport sys\nfrom collections import Counter\nfrom functools import reduce\n\ndef factors(n):\n factors = Counter({1: 1, n: 1})\n for f in range(2, int(math.sqrt(n))):\n while n % f == 0:\n factors[f] += 1\n n = n // f\n return factors\n\ndef gcd(x, y):\n return math.prod((factors(x) & factors(y)).elements())\n\nif __name__ == "__main__":\n print(reduce(gcd, map(int, sys.argv[1:])))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T10:15:33.873",
"Id": "261182",
"ParentId": "261179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T08:24:37.533",
"Id": "261179",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"mathematics"
],
"Title": "Python code to find greatest common divisor of multiple numbers"
}
|
261179
|
<p>Hi I was just asked by stackoverflow to move this question into this forum (<a href="https://stackoverflow.com/questions/67685433/how-to-design-the-react-component-properly">https://stackoverflow.com/questions/67685433/how-to-design-the-react-component-properly</a>).</p>
<p>Hi I am pretty new to react and I want to achieve something that turns out to be real pain for me and I am not sure what the best solution might be.</p>
<p>I got an application that handles a single keystore as application keystore and the admin is allowed to upload new keystores and merge the entries of these keystores into the application keystore. This results in the following class definition:</p>
<pre class="lang-javascript prettyprint-override"><code>export default class ApplicationKeystore extends React.Component
{
constructor(props)
{
super(props);
this.scimResourcePath = "/scim/v2/Keystore";
this.state = {};
this.setAliasSelectionResponse = this.setAliasSelectionResponse.bind(this);
this.onAliasSelectionSuccess = this.onAliasSelectionSuccess.bind(this);
}
setAliasSelectionResponse(resource)
{
let copiedResource = JSON.parse(JSON.stringify(resource));
this.setState({aliasSelectionResponse: copiedResource})
}
onAliasSelectionSuccess(resource)
{
this.setState({newAlias: resource[ScimConstants.CERT_URI].alias})
}
render()
{
return (
<React.Fragment>
<KeystoreUpload scimResourcePath={this.scimResourcePath}
setAliasSelectionResponse={this.setAliasSelectionResponse} />
<AliasSelection scimResourcePath={this.scimResourcePath}
aliasSelectionResponse={this.state.aliasSelectionResponse}
onCreateSuccess={this.onAliasSelectionSuccess} />
<KeystoreEntryList scimResourcePath={this.scimResourcePath}
newAlias={this.state.newAlias} />
</React.Fragment>
)
}
}
</code></pre>
<p>My problem now occurs on the last component <code>KeystoreEntryList</code>. The upload succeeds and the selection of entries to be merged works also correctly (just one at a time not several). But if I successfully merge an entry I get a response with the alias of the keystore entry that should now be added to the state of <code>KeystoreEntryList</code>. How do I do this in a clean way. I found several workarounds but all of them are dirty and make the code hard to read...</p>
<p>the important part of the <code>KeystoreEntryList</code>can be found here:</p>
<pre class="lang-javascript prettyprint-override"><code>class KeystoreEntryList extends React.Component
{
constructor(props)
{
super(props);
this.state = {aliases: []};
this.setState = this.setState.bind(this);
this.scimClient = new ScimClient(this.props.scimResourcePath, this.setState);
this.onDeleteSuccess = this.onDeleteSuccess.bind(this);
}
async componentDidMount()
{
let response = await this.scimClient.listResources();
if (response.success)
{
response.resource.then(listResponse =>
{
this.setState({
aliases: new Optional(listResponse.Resources[0]).map(val => val.aliases)
.orElse([])
})
})
}
}
componentDidUpdate(prevProps, prevState, snapshot)
{
// TODO if we delete an alias and add the same again the following if condition prevents adding it again
if (prevProps.newAlias !== this.props.newAlias && this.props.newAlias !== undefined)
{
let aliases = this.state.aliases;
aliases.push(this.props.newAlias);
aliases.sort();
this.setState({aliases: aliases, aliasDeleted: undefined});
}
}
...
}
</code></pre>
<p>my first idea was to do it on the <code>componentDidUpdate</code> method but this results in the problem stated out by the TODO. Is there any good way how I might be able to smoothly add the new alias into this component?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T10:17:25.183",
"Id": "515394",
"Score": "1",
"body": "Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:55:01.443",
"Id": "515409",
"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)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T10:00:10.090",
"Id": "261181",
"Score": "1",
"Tags": [
"react.js"
],
"Title": "What is the best way to pass an argument from one subcomponent to other subcomponent?"
}
|
261181
|
<p>I wrote a Pi Calculator using the BBP Algorithm in Cython. My specific goals are make the code more legible and more performant. This is a purely academic script in order to teach me how to implement complex algorithms with arbitrary precision (so no monetary gain, it's not homework, but is a personal goal). I have never used Cython before, much less the MPFR library (which is used for arbitrary precision).</p>
<p>My main concerns when it comes to performance is CPU time spent and RAM used. I would like to not have to duplicate the Pi result in RAM just to insert a decimal place. However, I do not know how to make MPFR return Pi with a decimal place. I believe the RAM issue also applies to the use of temporary variables for calculating Pi (in the base-16 or hex) portion of the calculation. As far as I can tell, I am unable to write the code in the format <code>8*i</code> in the Cython version due to the need for arbitrary precision. The Cython Code is not a huge fan of "implicit" math against variables of non-default types. I could be wrong and there could be a way to keep the accuracy while using what I call "implicit" math. I have not figured out how as I'm new to Cython (and have not used much C).</p>
<p>An example of what I view as unnecessary variables are the constants named "one", "two", etc... Attempting to perform the math operations with the raw numbers (e.g. 1 and 2) causes compilation to fail as MPFR does not accept integers, but instead accepts mpfr_t numbers. I believe I may have implemented this incorrectly due to what I believe to be unnecessarily complex. I could be wrong and this could be intended behavior.</p>
<p>Edit: I forgot to include the command to compile the Cython file. It is <code>python3 setup.py build_ext --inplace</code>. You then just run <code>python3 cpi-cli.py</code> to execute the script which calls the Cython binary.</p>
<p>The file called <code>cpi.pyx</code> is the main file in which the Cython implementation is held.</p>
<pre><code># Slimmed Down Version Of (For Code Review): https://github.com/alexis-evelyn/GeneralProjects/blob/0d59b7bcb78eb9a5ebc46b39d721c71a24a53b23/pi/cpi.pyx
from libc.stdio cimport printf
from gmpy2 cimport * # mpfr, import_gmpy2
import_gmpy2() # needed to initialize the C-API
# Modified From: https://github.com/aleaxit/gmpy/blob/879037f2bddccc44bff7ee2fb3ab6a2ff8710bc8/test_cython/test_cython.pyx#L23
# si means long, ui means unsigned long, sj means intmax, uj means unsigned int max, d means double, ld means long double
cdef extern from "mpfr.h":
# Management Functions
void mpfr_init2 (mpfr_t x, mpfr_prec_t prec)
void mpfr_clear (mpfr_t x)
# Convert Between MPFR and C
int mpfr_set_ld (mpfr_t rop, long double op, mpfr_rnd_t rnd)
long double mpfr_get_ld (mpfr_t op, mpfr_rnd_t rnd)
# Classic Math
int mpfr_mul (mpfr_t rop, mpfr_t op1, mpfr_t op2, mpfr_rnd_t rnd)
int mpfr_add (mpfr_t rop, mpfr_t op1, mpfr_t op2, mpfr_rnd_t rnd)
int mpfr_sub (mpfr_t rop, mpfr_t op1, mpfr_t op2, mpfr_rnd_t rnd)
int mpfr_div (mpfr_t rop, mpfr_t op1, mpfr_t op2, mpfr_rnd_t rnd)
# Exponent
int mpfr_exp (mpfr_t rop, long int op, mpfr_rnd_t rnd)
int mpfr_pow (mpfr_t rop, mpfr_t op1, mpfr_t op2, mpfr_rnd_t rnd)
mpfr_exp_t mpfr_get_exp (mpfr_t x)
# Convert MPFR To String
char * mpfr_get_str (char *str, mpfr_exp_t *expptr, int base, size_t n, mpfr_t op, mpfr_rnd_t rnd)
void mpfr_free_str (char *str) # Free String From Memory
# size_t mpfr_out_str (FILE *stream, int base, size_t n, mpfr_t op, mpfr_rnd_t rnd)
# Get Minimum Digits Needed To Hold Number
size_t mpfr_get_str_ndigits (int b, mpfr_prec_t p)
# Convert To cdef later and figure out how to set return type mpfr (or equivalent)
# Convert "steps: int" to "int steps" and figure out how to set default to 18
def bbp_formula(int steps):
# import_gmpy2()
# Define Variables
cdef long precision = steps*4
cdef mpfr_t i
cdef mpfr_t result
cdef mpfr_t eight_i
cdef mpfr_t base_sixteen_pi
cdef mpfr_t convert_base_ten
cdef char* pi = NULL # This is a pointer to a string (so no initialization has to be done here)
cdef mpfr_exp_t exponent = 2 # Should be 2
cdef mpfr ppi # Python Object To Hold Pi
cdef str ppis # Python Object To Hold String Pi
# Define TempVars
cdef mpfr_t denominator
cdef mpfr_t base_sixteen_pi_part_one
cdef mpfr_t base_sixteen_pi_part_two
cdef mpfr_t base_sixteen_pi_part_three
cdef mpfr_t base_sixteen_pi_part_four
# Define Constants
cdef mpfr_t eight
cdef mpfr_t six
cdef mpfr_t five
cdef mpfr_t four
cdef mpfr_t two
cdef mpfr_t one
# Initialize Variables
mpfr_init2(result, precision)
mpfr_init2(i, precision)
mpfr_init2(eight_i, precision)
mpfr_init2(base_sixteen_pi, precision)
mpfr_init2(convert_base_ten, precision)
# Initialize TempVars
mpfr_init2(denominator, precision)
mpfr_init2(base_sixteen_pi_part_one, precision)
mpfr_init2(base_sixteen_pi_part_two, precision)
mpfr_init2(base_sixteen_pi_part_three, precision)
mpfr_init2(base_sixteen_pi_part_four, precision)
# Initialize Constants
mpfr_init2(eight, precision)
mpfr_init2(six, precision)
mpfr_init2(five, precision)
mpfr_init2(four, precision)
mpfr_init2(two, precision)
mpfr_init2(one, precision)
# Set Variables
# The BBP Formula Summation (Sigma) Starts With 0
# MPFR_RNDN means Round Nearest - https://www.mpfr.org/mpfr-current/mpfr.html
mpfr_set_ld(result, 0, MPFR_RNDN)
mpfr_set_ld(i, 0, MPFR_RNDN)
# Set Constants
mpfr_set_ld(eight, 8, MPFR_RNDN)
mpfr_set_ld(six, 6, MPFR_RNDN)
mpfr_set_ld(five, 5, MPFR_RNDN)
mpfr_set_ld(four, 4, MPFR_RNDN)
mpfr_set_ld(two, 2, MPFR_RNDN)
mpfr_set_ld(one, 1, MPFR_RNDN)
for _ in range(0, steps):
# Calculate Pi To Base 16 (Hex)
# 8*i
mpfr_mul(eight_i, eight, i, MPFR_RNDN)
# printf("i: %Lf; 8*i: %Lf\n", mpfr_get_ld(i, MPFR_RNDN), mpfr_get_ld(eight_i, MPFR_RNDN))
# 4/(eight_i+1)
mpfr_add(denominator, eight_i, one, MPFR_RNDN)
mpfr_div(base_sixteen_pi_part_one, four, denominator, MPFR_RNDN)
# printf("Part 1 (4/8i+1): %Lf; Denominator: %Lf\n", mpfr_get_ld(base_sixteen_pi_part_one, MPFR_RNDN), mpfr_get_ld(denominator, MPFR_RNDN))
# 2/(eight_i+4)
mpfr_add(denominator, eight_i, four, MPFR_RNDN)
mpfr_div(base_sixteen_pi_part_two, two, denominator, MPFR_RNDN)
# printf("Part 2 (2/8i+4): %Lf; Denominator: %Lf\n", mpfr_get_ld(base_sixteen_pi_part_two, MPFR_RNDN), mpfr_get_ld(denominator, MPFR_RNDN))
# 1/(eight_i+5)
mpfr_add(denominator, eight_i, five, MPFR_RNDN)
mpfr_div(base_sixteen_pi_part_three, one, denominator, MPFR_RNDN)
# printf("Part 3 (1/8i+5): %Lf; Denominator: %Lf\n", mpfr_get_ld(base_sixteen_pi_part_three, MPFR_RNDN), mpfr_get_ld(denominator, MPFR_RNDN))
# 1/(eight_i+6)
mpfr_add(denominator, eight_i, six, MPFR_RNDN)
mpfr_div(base_sixteen_pi_part_four, one, denominator, MPFR_RNDN)
# printf("Part 4 (4/8i+6): %Lf; Denominator: %Lf\n", mpfr_get_ld(base_sixteen_pi_part_four, MPFR_RNDN), mpfr_get_ld(denominator, MPFR_RNDN))
# 4/(eight_i+1) - 2/(eight_i+4) - 1/(eight_i+5) - 1/(eight_i+6)
mpfr_sub(base_sixteen_pi, base_sixteen_pi_part_one, base_sixteen_pi_part_two, MPFR_RNDN)
mpfr_sub(base_sixteen_pi, base_sixteen_pi, base_sixteen_pi_part_three, MPFR_RNDN)
mpfr_sub(base_sixteen_pi, base_sixteen_pi, base_sixteen_pi_part_four, MPFR_RNDN)
# Convert Pi To Base 10
# 16**i (or 16^i)
mpfr_set_ld(denominator, 16, MPFR_RNDN)
mpfr_pow(denominator, denominator, i, MPFR_RNDN)
# 1/(16^i)
mpfr_div(convert_base_ten, one, denominator, MPFR_RNDN)
# (1/mpfr(16**i)) * base_sixteen_pi
mpfr_mul(convert_base_ten, convert_base_ten, base_sixteen_pi, MPFR_RNDN)
# Add Result To Previous Results (Summation)
# result = result + convert_base_ten
mpfr_add(result, result, convert_base_ten, MPFR_RNDN)
# Increment Step Counter
mpfr_add(i, i, one, MPFR_RNDN)
# Debug
# printf("%Lf\n", mpfr_get_ld(result, MPFR_RNDN))
# Convert To String To Import Into Python Object
exponent = mpfr_get_exp(result)
pi = mpfr_get_str(pi, &exponent, 10, mpfr_get_str_ndigits(10, precision), result, MPFR_RNDN)
ppis = str(pi, 'ASCII') # Convert Pi C String to Python String
corrected_pi: str = ppis[:1] + "." + ppis[1:]
# Import String To Python
ppi = mpfr(corrected_pi)
mpfr_free_str(pi) # Free C String
# Debug
# printf("Minimum Digits (Cython): %lu\n", mpfr_get_str_ndigits(10, precision))
# printf("Exponent (Cython): %lu\n", mpfr_get_exp(result))
# printf("Pi (Cython): %s", pi)
# print(f"Pi (Python): {corrected_pi}")
# print(f"Type PI: {type(pi)}")
# print(f"Type PPIs: {type(ppis)}")
return ppi # Pi in MPFR Python Object Format
</code></pre>
<p>This is the setup.py to compile the Cython script. You need to MPFR library in order to compile it.</p>
<pre><code># Not Slimmed Down Version (For Code Review) Of: https://github.com/alexis-evelyn/GeneralProjects/blob/0d59b7bcb78eb9a5ebc46b39d721c71a24a53b23/setup.py
#!/usr/bin/env python
# The order of these two imports matters greatly
from setuptools import Extension, setup
from Cython.Build import cythonize
import os
ext_modules = [
Extension("*", ['cpi.pyx'], libraries=["mpfr"])
]
ext_options = {"compiler_directives": {"profile": True}, "annotate": True}
setup(
ext_modules=cythonize(ext_modules, **ext_options)
)
</code></pre>
<p>This is the script to run the Cython binary. I call it cpi_cli.py.</p>
<pre><code># Slimmed Down Version Of (For Code Review): https://github.com/alexis-evelyn/GeneralProjects/blob/0d59b7bcb78eb9a5ebc46b39d721c71a24a53b23/cpi_cli.py
from cpi import bbp_formula
from gmpy2 import mpfr
import gmpy2
if __name__ == "__main__":
steps: int = 100
gmpy2.get_context().precision = steps*4
# Usually at least 2 digits are incorrect (at the end).
# The full script has a variable called "lost_digits" to adjust how many digits to toss.
print(str(bbp_formula(steps))[:-2])
</code></pre>
<p>This is the pure Python implementation of BBP that I wrote and then translated to Cython. This part is not for code review (although I won't complain if any suggestions are made). I included this for a short and legible version of the Cython implementation. I call it bbp.py.</p>
<pre><code># Slimmed Down Version Of (For Code Review): https://github.com/alexis-evelyn/GeneralProjects/blob/0d59b7bcb78eb9a5ebc46b39d721c71a24a53b23/pi/bbp.py
from gmpy2 import mpfr
import gmpy2
def bbp_formula(steps: int = 18) -> mpfr:
# The BBP Formula Summation (Sigma) Starts With 0
result: mpfr = mpfr(0)
for i in range(0, steps):
eight_i: mpfr = mpfr(8*i)
base_sixteen_pi: mpfr = 4/(eight_i+1) - 2/(eight_i+4) - 1/(eight_i+5) - 1/(eight_i+6)
convert_base_ten: mpfr = (1/mpfr(16**i)) * base_sixteen_pi
result: mpfr = result + convert_base_ten
return result
if __name__ == "__main__":
steps: int = 100
precision: int = steps*4
gmpy2.get_context().precision = precision
# Usually at least 2 digits are incorrect (at the end).
# The full script has a variable called "lost_digits" to adjust how many digits to toss.
print(str(bbp_formula(steps=steps))[:-2])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T12:59:26.747",
"Id": "515515",
"Score": "0",
"body": "I fixed my breaking gmpy2 by compiling gmp, mpfr, mpc, and gmpy2 from source. I should note that I had to ensure I used python3 and not python when performing the gmpy2 install. I may not have needed to compile gmp, mpfr, and mpc as it was available in homebrew, but I didn't notice that I was using the wrong version of Python (Python 2) until after I compiled and installed the libraries from source. It works now so I can continue development."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T10:24:46.297",
"Id": "261183",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"reinventing-the-wheel",
"cython"
],
"Title": "Pi Calculator Using BBP (Bailey–Borwein–Plouffe) - Written in Cython With MPFR"
}
|
261183
|
<h2>Please review this code</h2>
<p>I have written a function to find the successor of BST in c. It takes three arguments, i.e root pointer to the binary search tree, node value of which we have to find a successor and parent pointer (for first call it is also root pointer. It will return an integer that is the successor of the node value give.</p>
<pre><code>/**
* find Successor of BST, complex: o(h)
* @param rootPtr root pointer of BST
* @param parent_node parent node of the subtree (root node should be passed by default)
* @param nodeValue node val to find successor
* @return succsor
*/
int find_successor_h(BSTNode * rootPtr, int data, BSTNode * parent_node) {
if (rootPtr == NULL) return data;
int rt;
if (data < rootPtr -> data)
rt = find_successor_h(rootPtr -> left_child, data, rootPtr);
else if (data > rootPtr -> data)
rt = find_successor_h(rootPtr -> right_child, data, rootPtr);
else {
if (rootPtr -> right_child != NULL)
return minBST(rootPtr -> right_child);
else if (rootPtr != parent_node)
return INT_MIN;
else
return data;
}
if (rt == INT_MIN)
return INT_MAX;
if (rt == INT_MAX)
return parent_node -> data;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T11:54:20.563",
"Id": "515398",
"Score": "4",
"body": "Do you have a test program that drives this? It is easier to review if we can compile and run for ourselves, and for that we need a definition of `BSTNode`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T12:07:03.753",
"Id": "515400",
"Score": "4",
"body": "The `minBST` function is also missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:05:38.213",
"Id": "515451",
"Score": "1",
"body": "Abrar Ajaz Wani, Please post enough code so one may compile it. It is not necessary to link it - but that would even be better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T07:22:25.160",
"Id": "515484",
"Score": "0",
"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><strong>Missing return</strong></p>\n<p>Code may even fail the last <code>rt == INT_MAX</code> and then no return is specified.</p>\n<pre><code> if (rt == INT_MAX)\n return parent_node -> data;\n\n // Missing return.\n }\n</code></pre>\n<p><strong>Use <code>const</code></strong></p>\n<p>Using <code>const</code>, as able, provides more information as to what the code does and does not do. This also allows greater usage and potential optimization.</p>\n<pre><code>// int find_successor_h(BSTNode * rootPtr, int data, BSTNode * parent_node) {\nint find_successor_h(const BSTNode * rootPtr, int data, const BSTNode * parent_node) {\n</code></pre>\n<p><strong>Mis-matched comments</strong></p>\n<p>Comment does not match parameter names nor order: <code>node val</code> vs. <code>data</code>.</p>\n<pre><code>* @param rootPtr root pointer of BST\n* @param parent_node parent node of the subtree (root node should be passed by default)\n* @param nodeValue node val to find successor\n\nBSTNode * rootPtr, int data, BSTNode * parent_node\n</code></pre>\n<p><strong>Missing include</strong></p>\n<p><code>NULL</code> not defined.</p>\n<p><strong>Spelling</strong></p>\n<p><code>* @return succsor</code> vs. <code>* @return successor</code></p>\n<p><strong>Name error?</strong></p>\n<p>Why <code>h</code> in <code>int find_successor_h()</code>?</p>\n<p><strong><code>{ block }</code></strong></p>\n<p>Consider using <code>{}</code> even for simple blocks. Little need for <code>else</code></p>\n<pre><code>//if (rootPtr -> right_child != NULL)\n// return minBST(rootPtr -> right_child);\n//else if (rootPtr != parent_node)\n// return INT_MIN;\n//else\n// return data;\n\nif (rootPtr -> right_child != NULL) {\n return minBST(rootPtr -> right_child);\n}\nif (rootPtr != parent_node) {\n return INT_MIN;\n}\nreturn data;\n</code></pre>\n<hr />\n<p><strong>Deeper review</strong></p>\n<p>More support and test drive code needed for a deeper review.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:15:17.163",
"Id": "261210",
"ParentId": "261185",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T11:16:12.543",
"Id": "261185",
"Score": "0",
"Tags": [
"algorithm",
"c",
"binary-search",
"binary-search-tree"
],
"Title": "Finding inorder successor of a BST in C"
}
|
261185
|
<p>I have recently started to work with C++ and I do consider myself quite basic in C++ coding.</p>
<p>I have made the following two functions and I was wondering whether someone could give me some hints on how to improve and speed up this code.</p>
<p>Please, note that the second function is then used in <code>R</code> through <code>Rcpp R</code> package.</p>
<pre><code>#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
double sumAll(double i, double j, int a, int b, double coeff) {
double pi = 2 * acos(0.0);
double total = 0;
int half_a = a / 2;
int half_b = b / 2;
for (int k = 0; k <= half_a; ++k) {
for (int l = 0; l <= half_b; ++l) {
double fkl;
if (k == 0 && l == 0) {
fkl = 0;
} else {
fkl = pow((1 - (coeff * (1 - cos(2.0 * pi * k / a)))), 2.0) *
pow((1 - (coeff * (1 - cos(2.0 * pi * l / b)))), 2.0);
}
double a1 = 1 - (cos(2.0 * pi * i * k / a) * cos(2.0 * pi * j * l / b));
double deltaa;
if (k == 0) {
deltaa = 1;
} else {
deltaa = 0.5;
}
double deltab;
if (l == 0) {
deltab = 1;
} else {
deltab = 0.5;
}
if (k == 0 && l == 0) {
total = total + 0;
} else {
double res = (fkl * a1) / (deltaa * deltab * (1 - fkl));
total = total + res;
}
}
}
return total;
}
// [[Rcpp::export]]
NumericVector series_Sum(NumericVector xvec, NumericVector yvec, int a, int b,
double coeff) {
int size = xvec.length();
NumericVector series_res(size);
for (double i = 0; i < size; i++) {
series_res[i] = sumAll(xvec[i], yvec[i], a, b, coeff);
}
return series_res;
}
</code></pre>
<p>Consider that in <code>sumAll</code> :</p>
<ul>
<li>i and j: are integers, which can get values between 0 and a/2 or 0 and b/2, respectively.</li>
<li>coeff: can be a value between 0 and 1.0.</li>
<li>a and b: can be any integer values higher than 5 (arbitrary choice).</li>
</ul>
<p>In <code>series_Sum</code> :</p>
<ul>
<li>xvec and yvec: are vectors of i and j values.</li>
</ul>
<p>In other words, <code>series_Sum</code> use <code>sumAll</code> over several possible combinations of i and j.</p>
|
[] |
[
{
"body": "<p>Don't write <code>using namespace std;</code>.</p>\n<p>The constants including <code>pi</code> are provided in a standard header already. If you did need to define a constant, use <code>constexpr</code>.</p>\n<pre><code>double deltaa;\nif (k == 0) {\n deltaa = 1;\n } else {\n deltaa = 0.5;\n }\n</code></pre>\n<p>That is much clear to write as:</p>\n<pre><code>const double deltaa = k==0 ? 1 : 0.5;\n</code></pre>\n<p>which also allows you to initialize the value in the declaration and make it <code>const</code>.</p>\n<p>The block for <code>deltaa</code> and <code>deltab</code> are the same except for the parameter. You should make a small inline function for that.</p>\n<pre><code>total = total + 0;\n</code></pre>\n<p>Why?</p>\n<pre><code>total = total + res;\n</code></pre>\n<p>Better to write <code>total += res;</code></p>\n<hr />\n<p>Generally:</p>\n<p>Use <code>const</code> where you can. Initialize variables in the statement where you declare them.</p>\n<p>In addition to using <code>const</code>, which may allow the optimizer to better figure such things out on its own, consider hoisting subexpressions out of the loop. For example <code>pi * k</code> does not change inside the nested loop so compute it once in the outer loop only.</p>\n<p>Express your comments as preconditions (e.g. <code>assert</code> or <a href=\"https://stackoverflow.com/questions/54521085/how-to-use-c-expects-operator\"><code>Expect</code></a> statements).</p>\n<hr />\n<pre><code>for (double i = 0; i < size; i++) {\n series_res[i] = sumSij(half_a, half_b, xvec[i], yvec[i], a, b, coeff);\n }\n</code></pre>\n<p>Why is <code>i</code> of type <code>double</code>? It's an index into the <code>NumericArray</code>s.</p>\n<p>I see a call to <code>sumSij</code> but no call to <code>sumAll</code>. The code is not complete, and doesn't agree with your comment (unless the former calls the latter, but I don't know how).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T19:50:52.680",
"Id": "515441",
"Score": "0",
"body": "Yes, sorry. There was a typographical error when I copied my code here. The correct function is `sumAll`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:04:59.657",
"Id": "515443",
"Score": "2",
"body": "Technically the edit by OP invalidates part of your answer. I'll leave it up to you if you want to edit that part out, since the code wasn't working during your review. Non-working code is cause to close a question, not cause to answer it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:31:17.943",
"Id": "515446",
"Score": "0",
"body": "@Mast the two functions had different number of parameters, so I ruled out simply naming it wrong. Re \"non working\" I don't know what's in the Rcpp header file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T20:32:14.103",
"Id": "515447",
"Score": "0",
"body": "@CafféSospeso can't be: the number of parameters doesn't match. The function defined takes 5, the call at the bottom of the listing passes 7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T22:07:40.820",
"Id": "515461",
"Score": "0",
"body": "Once again, you were right. I just edited. Now it should be correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:21:13.990",
"Id": "515533",
"Score": "0",
"body": "I have a small comment/question. How `Expects` operator can be used, exactly? For instance, in my code. I looked around but it is not very clear to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:28:09.407",
"Id": "515535",
"Score": "1",
"body": "@CafféSospeso same as the old `assert`. Comment is _\"coeff: can be a value between 0 and 1.0.\"_ Expressed as code, `Expects(coeff>=0.0 && coeff<=1.0);`. Note that I had to decide whether you meant `>` or `>=` because the English was not rigorous. The code is more exact. (P.S. it's not an operator)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:50:36.373",
"Id": "515539",
"Score": "0",
"body": "Ok, then it is a rigorous way within the code to make sure that, for the example you made, coeff is higher or equal to 0 AND lower or equal to 1. Otherwise the code exits. Thanks for the clarification."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T19:24:39.837",
"Id": "261207",
"ParentId": "261186",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261207",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T13:39:17.420",
"Id": "261186",
"Score": "1",
"Tags": [
"c++",
"performance",
"rcpp"
],
"Title": "The average amount of time required to travel between two points in a torus-like space"
}
|
261186
|
<p>I am implementing a fixed point type, which mostly is used to be able store numbers as multiples of some base (power of 2). Apart from that, the type should be able to replace double/float values without the need of modifying some code. In its current implementation only basic arithmetic operations are possible but it should not be hard to extend the type.</p>
<p>I stripped away a lot of code which repeats other code - e.g. in the following only <code>operator<</code> is defined; all other comparison operators are defined in the same way.</p>
<p>The implementation trusts a lot that the compiler optimizes most of the code - e.g. instead of shift operations I wrote multiplications.</p>
<h2>Things I want from this type:</h2>
<ol>
<li>Header only</li>
<li>Modulo arithmetic for all operations</li>
<li>No undefined behaviour possible when this type is used (given that it is not abused)</li>
<li>Should be hard to use this type wrong</li>
<li>Operations are implemented efficient</li>
<li>no implicit conversion from <code>fixed</code> to built-in types</li>
<li>Radix point can be "outside" of the range of underlying bits - e.g. fixed<8,10>, which has range -2^17 to 2^17-1, with an ulp of 2^10 is possible.</li>
</ol>
<p>For points 1, 2, 4 and 7 I am quite sure I succeeded, for the other points I am nut sure.</p>
<h2>Target Version</h2>
<ul>
<li>C++14 Since this libarary must also be usable for CUDA and in the rest of the codebase there are problems with C++17 and Cuda.</li>
</ul>
<h2>Things I don't like currently</h2>
<p>I want most binary functions (<code>operator+</code>, etc...) to be compatible with two fixed objects, as well with one fixed object and one built-in arithmetic type - e.g. <code>fixed + fixed</code>, <code>fixed + int</code>, <code>int + fixed</code>. This currently leads to a lot of code duplication which I would like to get rid of.</p>
<h2>Unit Tests</h2>
<p>I wrote a lot of unit tests too, which I can always post if wanted. The unit tests use code from other parts of my projects too, thus I would have to rewrite them to a large extent in order to be able to post them here</p>
<pre><code>
#ifndef FIXED_HPP
#define FIXED_HPP
/**
* This is an implementation of a fixed point type
* Usage: fixed<TOTAL,SHIFT,SIGN> value
* TOTAL integer, number of total bits of underlying type, must be 8,16,32 or 64
* SHIFT integer, defines how much the radix point is shifted to the right. Can be negative.
* SIGN enum class signed_e, default=signed_e:signed, defines whether the type is signed or not.
* T (experimental) underlying type, default = determined by TOTAL
*
* Implemented operations:
* all casts to other basic types
* +, -, ~, !, >>, <<, as well as the operators +=, -=, ...
* ++ and -- operators are only defined when the number one can be represented
*
* Notes:
* In Debug mode, when a fixed object is created using a value, it is checked whether the value is in the proper range.
* All (subsequent) calculations are done using 2-complements unsigned integers, and thus, wrap around.
*/
#include <cassert>
#include <cmath>
#include <cstdint>
#include <limits>
#include <ostream>
#include <type_traits>
namespace detail { namespace fixed {
static inline constexpr double pow2_worker( double res, int n ) {
if ( n<0 ) {
return pow2_worker( res/2., n+1 );
} else if ( n>0 ) {
return pow2_worker( res*2., n-1 );
} else {
return res;
}
}
} }
static inline constexpr double pow2( int n ) {
return detail::fixed::pow2_worker( 1, n );
}
template<typename OUT,typename IN> static inline constexpr OUT safe_numeric_cast( IN in ) {
// taken from stackoverflow.com/questions/25857843
if ( std::isnan(in) ) {
return 0;
}
int exp;
std::frexp( in, &exp );
if( std::isfinite(in) && exp<= 63 ) {
return static_cast<int64_t>( in );
} else {
return std::signbit( in ) ? std::numeric_limits<int64_t>::min() : std::numeric_limits<int64_t>::max();
}
}
template<typename T>
static inline constexpr T rightshift( T value, int8_t shift ) {
static_assert( ((-4)>>1) == -2, "This library assumes sign-extending right shift" );
assert( sizeof(value)*8 >= (shift>0?shift:-shift) );
if ( shift>0 ) {
return value >> shift;
} else if ( shift<0 ) {
return value << -shift;
} else {
return value;
}
}
enum class signed_e {
signed_t, unsigned_t
};
template <int TOTAL, int SHIFT, signed_e SIGN, typename T> class fixed;
template<typename Number=long long> inline constexpr
void inrange( Number n, int TOTAL, int SHIFT, signed_e S ) noexcept {
auto I = TOTAL + SHIFT;
assert( ((void)"(Out of range) Given number not representable in target format",
S==signed_e::signed_t ?
n >= -pow2( I-1 ) && n <= pow2( I-1 ) - pow2( SHIFT ) :
n >= 0 && n <= pow2( I ) - pow2( SHIFT )
) );
}
namespace detail { namespace fixed {
struct NoScale {};
template <int T,signed_e S> struct type_from_size { // unspecialized type, compilation fails if this is chosen
};
template <> struct type_from_size<8,signed_e::signed_t> {
using value_type = uint8_t;
};
template <> struct type_from_size<8,signed_e::unsigned_t> {
using value_type = uint8_t;
};
template <> struct type_from_size<16,signed_e::signed_t> {
using value_type = uint16_t;
};
// etc...
} }
template<int TOTAL, int SHIFT=TOTAL/2, signed_e SIGN=signed_e::signed_t, typename T = typename detail::fixed::type_from_size<TOTAL,SIGN>::value_type>
class fixed {
public:
/// member variables
using base_type = T;
using compare_type = typename std::conditional< SIGN==signed_e::signed_t, typename std::make_signed<base_type>::type, base_type >::type;
base_type data_;
static_assert( -1 == ~0, "This library assumes 2-complement integers" );
/// constructors
fixed() noexcept = default;
fixed( const fixed & ) noexcept = default;
fixed& operator=( const fixed & ) noexcept = default;
template <class Number> inline constexpr
fixed( Number n, typename std::enable_if<std::is_arithmetic<Number>::value>::type* = nullptr ) noexcept :
data_( safe_numeric_cast<base_type>(n * pow2(-SHIFT)) ) {
inrange( n );
}
inline constexpr
fixed( base_type n, const detail::fixed::NoScale & ) noexcept : data_(n) {
}
inline constexpr static
fixed from_base( base_type n ) noexcept {
return fixed( n, detail::fixed::NoScale() );
}
/// helper functions
public:
template<typename Number> inline constexpr
void inrange( Number n ) const noexcept {
::inrange<Number>( n, TOTAL, SHIFT, SIGN );
}
/// comparison operators
inline constexpr
bool operator<( fixed rhs ) const noexcept {
return static_cast<compare_type>( data_ ) < static_cast<compare_type>( rhs.data_ );
}
// etc...
/// unary operators
inline constexpr
bool operator!() const noexcept {
return !data_;
}
// etc...
inline constexpr
fixed & operator++() noexcept {
static_assert( SHIFT<=0 && -SHIFT<=TOTAL, "++ operator not possible" );
data_ += pow2( -SHIFT );
return *this;
}
inline constexpr
const fixed operator++( int ) noexcept {
static_assert( SHIFT<=0 && -SHIFT<=TOTAL, "++ operator not possible" );
fixed tmp(*this);
data_ += pow2( -SHIFT );
return tmp;
}
//etc...
public: // basic math operators
inline constexpr
fixed& operator+=( fixed n ) noexcept {
data_ += n.data_;
return *this;
}
inline constexpr
fixed& operator-=( fixed n ) noexcept {
data_ -= n.data_;
return *this;
}
public:
/// binary math operators
inline constexpr
fixed& operator&=( fixed n ) noexcept {
data_ &= n.data_;
return *this;
}
//etc...
/// conversion to basic types
template<typename OUT, typename std::enable_if_t<std::is_integral<OUT>::value,bool> = false >
inline constexpr explicit
operator OUT () const noexcept {
return rightshift( static_cast<OUT>(data_), -SHIFT );
}
template<typename OUT, typename std::enable_if_t<std::is_floating_point<OUT>::value,bool> = false >
inline constexpr explicit
operator OUT () const noexcept {
return static_cast<OUT>( data_ ) * static_cast<OUT>( pow2(SHIFT) );
}
inline constexpr
base_type raw() const noexcept {
return data_;
}
public:
inline constexpr
void swap( fixed &rhs ) noexcept {
using std::swap;
swap( data_, rhs.data_ );
}
};
template <int T, int SH, signed_e SI>
std::ostream &operator<<( std::ostream &os, fixed<T,SH,SI> f ) {
os << static_cast<double>( f );
return os;
}
// basic math operators
template <int T, int SH, signed_e SI> inline constexpr
fixed<T,SH,SI> operator+( fixed<T,SH,SI> lhs, fixed<T,SH,SI> rhs ) noexcept {
lhs += rhs;
return lhs;
}
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
fixed<T,SH,SI> operator+( fixed<T,SH,SI> lhs, Number rhs ) noexcept {
lhs += fixed<T,SH,SI>( rhs );
return lhs;
}
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
fixed<T,SH,SI> operator+( Number lhs, fixed<T,SH,SI> rhs ) noexcept {
fixed<T,SH,SI> tmp(lhs);
tmp += rhs;
return tmp;
}
//etc...
// shift operators
template <int T, int SH, signed_e SI, class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> inline constexpr
fixed<T,SH,SI> operator<<( fixed<T,SH,SI> lhs, Integer rhs ) noexcept {
lhs <<= rhs;
return lhs;
}
template <int T, int SH, signed_e SI, class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> inline constexpr
fixed<T,SH,SI> operator>>( fixed<T,SH,SI> lhs, Integer rhs ) noexcept {
lhs >>= rhs;
return lhs;
}
// comparison operators
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
bool operator<( fixed<T,SH,SI> lhs, Number rhs ) noexcept {
return lhs < fixed<T,SH,SI>( rhs );
}
template <int T, int SH, signed_e SI, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> inline constexpr
bool operator<( Number lhs, fixed<T,SH,SI> rhs ) noexcept {
return fixed<T,SH,SI>(lhs) < rhs;
}
namespace std {
/// specialization of std::numeric_limits
template<int TOTAL,int SHIFT,signed_e SIGNED> struct numeric_limits<::fixed<TOTAL,SHIFT,SIGNED>> {
static constexpr bool is_specialized = true;
static constexpr double lowest() noexcept { return SIGNED==signed_e::signed_t ? -pow2( TOTAL + SHIFT - 1 ) : 0; }
static constexpr double max() noexcept { return SIGNED==signed_e::signed_t ? pow2( TOTAL + SHIFT - 1 ) - pow2( SHIFT ) : pow2( TOTAL + SHIFT ) - pow2( SHIFT ); }
// etc.
};
}
int main() {
fixed<16,-8> x = -10;
x+=-2;
auto r = x<-5;
auto y = x + 100;
return (int)x;
}
#endif //FIXED_HPP
</code></pre>
<h2>Credits</h2>
<p>This type is a heavily modified fixed point type written by Evan Teran.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T14:22:25.107",
"Id": "515413",
"Score": "0",
"body": "Do you know about the \"spaceship\" operator? Which C++ dialect is this targeting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T14:31:51.963",
"Id": "515414",
"Score": "0",
"body": "@JDługosz C++14, spaceship operator is no possibilty thus I fear."
}
] |
[
{
"body": "<blockquote>\n<p>I want most binary functions (operator+, etc...) to be compatible with two fixed objects, as well with one fixed object and one built-in arithmetic type - e.g. fixed + fixed, fixed + int, int + fixed. This currently leads to a lot of code duplication which I would like to get rid of.</p>\n</blockquote>\n<p>In my implementation (which is Decimal, not power-of-two, and has different design requirements for many of your points), I decided to provide <code>operator+</code> between identical types only. It would be confusing to have the result be a type that differs from either of the arguments and could lead to use of more distinct types than intended. On the other hand, <code>operator+=</code> does allow mixed types, as the result is implicitly the type of the left-hand operand, and it gives a compile-time error if the right-hand operand is larger in either size to the left of the decimal or size to the right of the decimal.</p>\n<p>As for code duplication, I rely on <code>operator=</code> (only) to do the heavy lifting of implicitly widening the type. The addition and subtraction operators call that to condition the right-hand argument.</p>\n<p>As for built-in integer type as one argument: are you doing size match checking? If you have, for example a 32-bit <code>int</code> with 5 implied fractional bits, then adding a regular 32-bit value will be too large to the left of the binary point. In my library, I disallow this, but <code>constexpr</code> constructors let me easily mark the regular <code>int</code> with a size that's smaller than the <code>int</code>. E.g. <code>d1 += decimal<3,0>(n);</code> tells it that <code>n</code> has (at most) three decimal digits (recall my library is decimal based) rather than 9 or 10 that would fit in a regular <code>int</code>. Thus, is passes the width checking and automatically widens to the declared type of <code>d1</code> which is, say, 5 digits to the left and 4 to the right of the decimal point and represented in a 32-bit value.</p>\n<hr />\n<p>Doing the underlying work as unsigned integers will be less efficient (less ability to optimize the inlined functions) as using signed values.</p>\n<hr />\n<p>Why are your functions <code>static inline</code> instead of just <code>inline</code>? That is not normal.</p>\n<hr />\n<p>You have namespaces nested as <code>detail::fixed</code> rather than the other way around? Also odd. Hmm, I see <code>fixed</code> is a class template that is not inside a namespace at all! You should put everything inside a namespace to prevent clashes.</p>\n<hr />\n<pre><code>template<typename OUT,typename IN> static inline constexpr OUT safe_numeric_cast( IN in ) {\n</code></pre>\n<p>It's hard to read with the <code>template</code> prefix and following declaration on one line like that. And again, it's quite odd to see <code>inline static</code>. Try:</p>\n<pre><code>template<typename OUT,typename IN>\nconstexpr OUT safe_numeric_cast ( IN in ) \n{\n</code></pre>\n<p>Furthermore, the use of <code>IN</code> and <code>OUT</code> may conflict with other libraries. I've seen those defined as <strong>macros</strong> that are used to mark parameters as with languages such as Ada or COM/CORBA marshalling.</p>\n<p>The <code>inline</code> is not needed here to allow use inside a header. A template is not a function, just like how a cookie-cutter is not a cookie. There is no code there; and the instantiation of the template, which <em>is</em> a function, understands being instantiated in multiple translation units. Note that <code>inline</code> is no longer a hint used to ask to compiler to inline the function — the compiler decides for itself what to inline or not. It is only used to allow definitions to appear in headers so that multiple copies are merged. On the other hand, <code>static</code> means that the instantiated function will <em>not</em> be shared among different translation units, which is the exact opposite in meaning. And why would you want to do that?</p>\n<hr />\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T19:49:18.430",
"Id": "515440",
"Score": "0",
"body": "1. signed/unsigned: Why are unsigned ints slower than signed ints? Can you give some reference? 2. inline: I saw in godbolt, that gcc inlines more when the inline keyword is present (not at this example, but on some others). Thats why I added tham."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T14:33:44.690",
"Id": "261189",
"ParentId": "261187",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261189",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T14:09:32.577",
"Id": "261187",
"Score": "3",
"Tags": [
"c++",
"c++14",
"fixed-point"
],
"Title": "Fixed Point Type"
}
|
261187
|
<p>I am new to python, and developing a moderate application for which I need to setup a logging mechanism.</p>
<p>The below program sets up log handling, which gives the user an option to specify whether log rotation is required or not.</p>
<p>The rest is my application. The code is mostly written in terms of functions (not using classes) which are irrelevant to the log setup and mostly contain printing log messages.</p>
<p>But before going ahead with the complete application, I would like to know from experts whether the following approach of using <code>RotatingFileHandler</code> and <code>basicConfig</code> is good enough.</p>
<p>I would like to know the comments for below:</p>
<ol>
<li>In case if I want to filter logs (either to stdout or file) based on log levels.</li>
<li>Adding any new handlers</li>
<li>Any other unforeseen problems (I am just a fresh learner)</li>
<li>In general is this the correct approach for supporting <code>RotatingFileHandler</code> and <code>basicConfig</code></li>
<li>Any other general comments</li>
</ol>
<pre><code>import logging
import logging.handlers
try:
import configparser
except ImportError:
# Python 2.x fallback
import ConfigParser as configparser
import argparse
LOG_FILENAME = 'debug.log'
LOG_PATH = "C:\\tool_temp\\"
# Set up a specific logger with our desired output level
logger = logging.getLogger('MYAPP')
def log_setup(dir_name, config_dict):
is_log_enabled = config_dict['logrotate_k']
if is_log_enabled == "enabled":
print "logrotation enabled"
# Add the log message rotate_handler to the logger
rotate_handler = logging.handlers.RotatingFileHandler(dir_name+LOG_FILENAME, maxBytes=512, backupCount=5)
#'%b %d %H:%M:%S' is to avoid printing 628 after 2021-05-25 16:30:30,628
formatter = logging.Formatter('%(asctime)s : %(levelname)s: %(filename)s::%(funcName)s:%(lineno)d %(message)s', '%d %b %d %H:%M:%S')
rotate_handler.setFormatter(formatter)
logger.addHandler(rotate_handler)
logger.setLevel(logging.DEBUG)
else:
print "logrotation is disabled"
date_strftime_format = "%d %b %y %H:%M:%S"
message_format='%(asctime)s : %(levelname)s %(filename)s:: %(funcName)s:%(lineno)d %(message)s'
#by default, the logging module logs the messages with a severity level of WARNING or above. so used level=logging.DEBUG
# to log everything from debug to critical
logging.basicConfig(filename = dir_name+LOG_FILENAME, format = message_format, datefmt = date_strftime_format,level=logging.DEBUG)
def is_file_exist(config_file_path):
if os.path.exists(config_file_path):
return True
else:
return False
#Reading config file through sections and keys
def read_config(cfg_path):
config_dict = {}
config = configparser.ConfigParser()
try:
config.read(cfg_path)
config_dict['logrotate_k'] = config.get('CONF_PARAMS', 'logrotate')
except Exception as e:
print("Error",str(e))
sys.exit()
return config_dict
# For parsing the command line arguments
# returns dictionary "config_dict" with the app build parameters
def parse_command_line_args():
config_dict = {}
parser = argparse.ArgumentParser(description='My Application')
parser.add_argument('-config_file', type = str)
parser.add_argument('-logrotate',type=str,help='logrotation enabled or not')
input_args = parser.parse_args()
config_file_path = input_args.config_file
if config_file_path != None:
if is_file_exist(config_file_path) == True:
print "Reading configs from config file: " + config_file_path
config_dict = read_config(config_file_path)
else:
print config_file_path + " does not exists"
sys.exit()
else:
print "reading configs from command line"
config_dict['logrotate_k'] = input_args.logrotate
return config_dict
if __name__ == "__main__":
config_dict = {}
config_dict = parse_command_line_args()
log_setup(LOG_PATH+LOG_FILENAME,config_dict)
logger.info('this info is from main')
logger.error('this is test error message from main')
print config_dict
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T15:12:56.227",
"Id": "515417",
"Score": "2",
"body": "Welcome to Code Review! When you state \"_Rest all is my application_\" does that mean it is all a [R.E.S.T.](https://en.wikipedia.org/wiki/Representational_state_transfer) application, or do you simply mean that _the rest_ of the application....?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T15:49:14.430",
"Id": "515420",
"Score": "0",
"body": ":) @SᴀᴍOnᴇᴌᴀ, it just remaining part of the application not R.E.S.T, sorry for confusion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T18:58:50.920",
"Id": "515437",
"Score": "0",
"body": "Why Python 2? Unless you have some deeply unfortunate restrictions about archaic technology, it's the wrong version to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T00:22:51.897",
"Id": "515465",
"Score": "0",
"body": "we are dealing with some legacy product which is running on Python 2, so cant do much about it."
}
] |
[
{
"body": "<p><strong><code>is_file_exist</code></strong></p>\n<p>This function basically follows the pattern</p>\n<pre><code>if condition:\n return True\nelse:\n return False\n</code></pre>\n<p>If <code>type(condition) == bool</code>, this pattern can always be simplified to</p>\n<pre><code>return condition\n</code></pre>\n<p>If <code>type(condition) != bool</code> (i.e. you're checking for <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"nofollow noreferrer\">truthy and falsy values</a>), it's still pretty simple:</p>\n<pre><code>return bool(condition)\n</code></pre>\n<p>So in your case:</p>\n<pre><code>def is_file_exist(config_file_path):\n return os.path.exists(config_file_path)\n</code></pre>\n<p>As you're now only wrapping <code>os.path.exists</code>, you should consider getting rid of the function as it serves no real purpose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T15:52:58.267",
"Id": "515421",
"Score": "0",
"body": "thanks , its really a good comment, pls comment on other part of the code if possible"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T15:12:37.143",
"Id": "261194",
"ParentId": "261188",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Don't use Python 2. Unless you're in legacy software hell, such as Jython, just don't do it.</li>\n<li><code>C:\\tool_temp</code> is not a good location for log files. Depending on intent, this might be better as <code>C:\\ProgramData\\my_app\\logs</code> for instance.</li>\n<li>Instead of initializing the logger in the global namespace and configuring it after the fact, consider instantiating the logger locally, configuring and then returning it to be set on the global namespace afterwards.</li>\n<li>Your configuration dict mechanism is unnecessary. Read about <a href=\"https://docs.python.org/3.8/library/argparse.html#fromfile-prefix-chars\" rel=\"nofollow noreferrer\">https://docs.python.org/3.8/library/argparse.html#fromfile-prefix-chars</a> which supports what - in another universe - is called a response file; basically a file with the exact same information that a list of command-line arguments would have.</li>\n<li>You call <code>basicConfig</code>, but only in the case where you don't want to rotate logs. This means that in the case where you <em>do</em> want to rotate logs, you're failing to set up a <code>StreamHandler</code>. That's probably an error.</li>\n<li><code>%d %b %d</code> is probably an error.</li>\n<li>You're using a non-sortable datetime format, which has grave consequences for some log file handling software. Just use a machine-readable ISO8601-style timestamp instead.</li>\n<li>Consider adding PEP484 type hints.</li>\n<li>Your arguments should follow the Unix convention of having a <code>--double-dashed</code> long form and a <code>-s</code> single-dashed short form.</li>\n</ul>\n<h2>Example code</h2>\n<pre><code>import logging\nfrom argparse import ArgumentParser, Namespace\nfrom logging import Formatter, Logger, getLogger, FileHandler, StreamHandler\nfrom logging.handlers import RotatingFileHandler\nfrom pathlib import Path\nfrom pprint import pformat\n\nLOG_FILENAME = 'debug.log'\n# Consider /var/log/my_app if in Unix, or something under C:\\ProgramData if in Windows\nLOG_PATH = Path('.') \n\n\ndef log_setup(dir_name: Path, filename: str, rotation_enabled: bool) -> Logger:\n\n # Avoid printing 628 after 2021-05-25 16:30:30,628\n formatter = Formatter(\n fmt='%(asctime)s : %(levelname)s: %(filename)s::%(funcName)s:%(lineno)d %(message)s',\n datefmt="%Y-%m-%d %H:%M:%S",\n )\n\n stream_handler = StreamHandler()\n stream_handler.setFormatter(formatter)\n\n if rotation_enabled:\n # Add the log message rotate_handler to the logger\n file_handler = RotatingFileHandler(dir_name / filename, maxBytes=512, backupCount=5)\n else:\n file_handler = FileHandler(dir_name / filename)\n file_handler.setFormatter(formatter)\n\n logger = getLogger('MYAPP')\n logger.addHandler(stream_handler)\n logger.addHandler(file_handler)\n # by default, the logging module logs the messages with a severity level of WARNING or above.\n # so used level=logging.DEBUG to log everything from debug to critical\n logger.setLevel(logging.DEBUG)\n\n return logger\n\n\ndef parse_command_line_args() -> Namespace:\n parser = ArgumentParser(\n description='My Application',\n fromfile_prefix_chars='@',\n )\n parser.add_argument(\n '-r', '--log-rotate', action='store_true',\n help='enable log rotation',\n )\n return parser.parse_args()\n\n\ndef test_levels() -> None:\n logger.debug('this debug is from our test')\n logger.info('this info is from our test')\n logger.error('this error is from our test')\n\n\nif __name__ == "__main__":\n config = parse_command_line_args()\n logger = log_setup(Path(LOG_PATH), LOG_FILENAME, config.log_rotate)\n logger.debug(f'Configuration: {pformat(config.__dict__)}')\n test_levels()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T00:49:40.920",
"Id": "515466",
"Score": "1",
"body": "Great, the comments are really nice ,you have covered all most all of my code, really got to know few new things and by the way I follow most of your answers on codereview site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T01:22:22.450",
"Id": "515467",
"Score": "0",
"body": "one question : How is the `logger` accessible without declaring it in global scope or passed as an argument to the function `test_levels`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T03:42:56.250",
"Id": "515470",
"Score": "1",
"body": "It is in the global scope. It's set within the main guard."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T19:47:26.833",
"Id": "261208",
"ParentId": "261188",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261208",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T14:25:36.083",
"Id": "261188",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-2.x"
],
"Title": "log setup using RotatingFileHandler and basicConfig"
}
|
261188
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/260989/231235">Android APP User class implementation</a>. I am attempting to create a password strength assessment class which is named <code>PasswordStrengthAssessment</code> in Java. Instead of adding "111111", "123123" or the other weak passwords one by one in program, the <a href="https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10k-most-common.txt" rel="nofollow noreferrer">10k-most-common.txt on Github</a> is used as the list of common passwords. After constructing <code>PasswordStrengthAssessment</code> class, this <code>10k-most-common.txt</code> is going to be downloaded and this design may make the matching operation for weak password detection be better. However, the network resource availability and the download time are need to be considered.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p>Project name: PasswordStrengthAssessment</p>
</li>
<li><p><code>PasswordStrengthAssessment</code> class implementation:</p>
<pre><code>package com.example.passwordstrengthassessment;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class PasswordStrengthAssessment extends AppCompatActivity {
private List<String> commonPasswords = new ArrayList<String>();
private final int minimumLengthRequired = 8;
public enum Level {
Weak,
Medium,
Strong // TODO: Implement the determination of strong level password
}
// Empty constructor
public PasswordStrengthAssessment() {
try {
createCommonPasswordsList();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Reference:
// 10k-most-common.txt: https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10k-most-common.txt
private void createCommonPasswordsList() throws InterruptedException {
Runnable downloadCommonPasswordsListRunnable = () -> {
final String mostCommonPasswordList = "https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10k-most-common.txt";
try {
// Create a URL for the desired page
URL url = new URL(mostCommonPasswordList);
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// Reference: https://stackoverflow.com/a/15949198/6667035
synchronized(this.commonPasswords) {
this.commonPasswords.add(str);
}
Log.d("downloadCommonPasswordsListRunnable", str);
}
in.close();
} catch (MalformedURLException e) {
Log.d("createCommonPasswordsList", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("createCommonPasswordsList", e.getMessage());
e.printStackTrace();
}
};
Thread thread = new Thread(downloadCommonPasswordsListRunnable);
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (this.commonPasswords.size() == 0) // Common Passwords List download fail
{
createCommonPasswordsListLocal();
}
return;
}
private void createCommonPasswordsListLocal()
{
this.commonPasswords.add(getResources().getString(R.string.common_password1));
this.commonPasswords.add(getResources().getString(R.string.common_password2));
this.commonPasswords.add(getResources().getString(R.string.common_password3));
this.commonPasswords.add(getResources().getString(R.string.common_password4));
this.commonPasswords.add(getResources().getString(R.string.common_password5));
this.commonPasswords.add(getResources().getString(R.string.common_password6));
this.commonPasswords.add(getResources().getString(R.string.common_password7));
this.commonPasswords.add(getResources().getString(R.string.common_password8));
this.commonPasswords.add(getResources().getString(R.string.common_password9));
this.commonPasswords.add(getResources().getString(R.string.common_password10));
this.commonPasswords.add(getResources().getString(R.string.common_password11));
this.commonPasswords.add(getResources().getString(R.string.common_password12));
return;
}
private boolean lengthCheck(final String input)
{
if (input.length() > minimumLengthRequired)
{
return true;
}
return false;
}
public boolean isPasswordWeak(final String passwordInput)
{
return determinePasswordStrength(passwordInput).equals(Level.Weak);
}
private Level determinePasswordStrength(final String passwordInput)
{
if (lengthCheck(passwordInput) == false)
{
return Level.Weak;
}
if (this.commonPasswords.contains(passwordInput))
{
return Level.Weak;
}
return Level.Medium;
}
}
</code></pre>
</li>
<li><p><code>strings.xml</code></p>
<pre><code><resources>
<string name="app_name">PasswordStrengthAssessment</string>
<string name="common_password1">111111</string>
<string name="common_password2">123123</string>
<string name="common_password3">12345</string>
<string name="common_password4">123456</string>
<string name="common_password5">12345678</string>
<string name="common_password6">123456789</string>
<string name="common_password7">1234567890</string>
<string name="common_password8">picture1</string>
<string name="common_password9">password</string>
<string name="common_password10">password123</string>
<string name="common_password11">Password</string>
<string name="common_password12">Password123</string>
</resources>
</code></pre>
</li>
<li><p>User permission setting</p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</code></pre>
</li>
<li><p><code>AndroidManifest.xml</code></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.passwordstrengthassessment">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.PasswordStrengthAssessment">
<activity
android:name=".MainActivity"
android:exported="true"
android:usesCleartextTraffic="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
</code></pre>
</li>
<li><p><code>build.gradle</code></p>
<pre><code>plugins {
id 'com.android.application'
}
android {
compileSdk 30
defaultConfig {
applicationId "com.example.passwordstrengthassessment"
minSdk 26
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation fileTree(include: ['*.jar'], dir: 'libs')
// https://mvnrepository.com/artifact/commons-net/commons-net
implementation group: 'commons-net', name: 'commons-net', version: '20030805.205232'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
</code></pre>
</li>
</ul>
<p><strong>Full Testing Code</strong></p>
<ul>
<li><p><code>MainActivity.java</code> implementation:</p>
<pre><code>package com.example.passwordstrengthassessment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final int READ_EXTERNAL_STORAGE_CODE = 1;
private static final int WRITE_EXTERNAL_STORAGE_CODE = 2;
private static final int ACCESS_NETWORK_STATE_CODE = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE_CODE);
checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE_CODE);
checkPermission(Manifest.permission.ACCESS_NETWORK_STATE, ACCESS_NETWORK_STATE_CODE);
PasswordStrengthAssessment passwordStrengthAssessment = new PasswordStrengthAssessment();
showToast("Is dogggg a weak password:" + String.valueOf(passwordStrengthAssessment.isPasswordWeak("dogggg")), Toast.LENGTH_SHORT);
}
// Function to check and request permission.
public void checkPermission(String permission, int requestCode)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode);
}
else {
Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
}
void showToast(String Text, int Duration)
{
Context context = getApplicationContext();
CharSequence text = Text;
int duration = Duration;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
</code></pre>
</li>
</ul>
<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/260989/231235">Android APP User class implementation</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Instead of adding "111111", "123123" or the other weak passwords one by one in program, the <a href="https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10k-most-common.txt" rel="nofollow noreferrer">10k-most-common.txt on Github</a> is used as the list of common passwords here.</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>
|
[] |
[
{
"body": "<h2>Test Harness</h2>\n<p>Your question presents a main activity that seems to act as a test harness for a particular case 'dogggg'. If the common password list has been downloaded then 'dogggg' is weak, if it hasn't then it's not. This is OK if you are just trialling something, however it makes review feedback less useful than it could otherwise be. We effectively have no real knowledge about how it is you're planning on using your <code>PasswordStregthAssessment</code> class. The use cases feel like they could frame future code improvements. You should consider actually using and presenting the class in a project to aid ours and your understanding of the requirements. Some of the below probably won't be relevant to your specific use cases...</p>\n<h2>Is it worth it?</h2>\n<p>The password file that you're downloading is about 70K (this doesn't seem like it's very big) and it hasn't been updated for 12 months and from what I can tell you don't own the project. If I'd decided that it was a useful list for evaluating passwords, I would consider just taking a cut of the file, either manually, or as part of your build process, so that the file is actually bundled with your application as a resource. If it does change, and you wanted the change, then you'd have the option of redeploying a new version of your app with the updated file. Obviously this adds an overhead to taking updates, particularly if you don't normally need to update your app, however it gives you more control and reduces uncertainty about behaviour.</p>\n<h2>What's the goal?</h2>\n<p>This comes back to my first point a bit, as the actual usage of the checker seems relevant. If you don't want to package the password file along with your application, then the next relevant question is how often are you going to check the strength of a password? Is it a one-shot evaluation that happens when the user registers your application, in which case downloading the list on-demand might make sense, or is the purpose of your application to let users try passwords and have them evaluated by your app, in which case many passwords are going to be checked. If this is the case, then it might make more sense to actually download the password file once and save it locally, then use the local version for future validations.</p>\n<h2>Consistency</h2>\n<p>You app's behaviour is inconsistent, it'll return different results if you're connected / not connected to the internet. As a user, this might be confusing. If you're using the password to connect to a remote system, does that have the same password validation rules or is that another inconsistency?</p>\n<h2>Variables</h2>\n<p>Naming for variables in Java is generally <code>camelCase</code>. I wouldn't expect to see <code>int Duration</code> for example. Adding extra variables isn't always necessary and creates extra noise that the reader has to work through. So, for example:</p>\n<pre><code>int duration = Duration;\n</code></pre>\n<p>Where <code>Duration</code> is already an <code>int</code> doesn't really add any value. You don't mutate either <code>duration</code> or <code>Duration</code>. Instead you could just pass <code>Duration</code> directly into the <code>makeText</code>.</p>\n<h2>So many strings...</h2>\n<p>Your backup list of passwords has a string resource for each password, which means you need to give each password a name, and add it to your list. A more efficient approach would be to create a single <code>string-array</code> resource which contained all of the passwords. You could then add passwords to the file without needing to change the code. There's a tutorial on how to create and use a <code>string-array</code> resource <a href=\"https://www.homeandlearn.co.uk/android/grid_view_array.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h2>Out of sync</h2>\n<p>You're synchronising if you add items to your <code>commonPasswords</code> during the runnable, however you're not synchronising if you perform the add of your backup items, or when you're reading from the list. This doesn't look guaranteed to work to me. Some discussion <a href=\"https://stackoverflow.com/q/55840034/592182\">here</a>.</p>\n<p>Something to consider is what happens if it takes 3 seconds to read the passwords from the remote file list (my phone will sometimes take longer than that just to make a connection, particularly if it decides it wants to switch from Wi-Fi to mobile data.</p>\n<h2>Threads are expensive</h2>\n<p>You're starting a brand new thread to go and do some work, then sleeping for 2 seconds whilst you wait for the thread to perform the fetch. If the fetch only takes 1 second, you still wait for 2. If it takes longer, then you give up waiting even though the thread keeps running (and may finish when you're no longer expecting it to). If you really want to take this approach, consider killing the thread at the point that you give up on it. But really this seems like a bad use of a thread. Kicking the work to a background thread (preferably from a thread pool) could make sense if you're going to return the main thread to so that it can continue to handle GUI interactions, however it can't do that if it's blocking in a sleep.</p>\n<p>Really, it feels like a better approach would be to add a time-out to your http request so that if it's unable to complete within a given period of time you can give up on the request and then continue processing with your alternative. Additional reading <a href=\"https://stackoverflow.com/q/693997/592182\">here</a> and <a href=\"https://stackoverflow.com/q/3000214/592182\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T23:14:51.210",
"Id": "261215",
"ParentId": "261195",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261215",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T16:02:53.553",
"Id": "261195",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"android",
"error-handling",
"classes"
],
"Title": "Android APP Password Strength Assessment class implementation"
}
|
261195
|
<p>I wanted to implement a short and functional brainfuck interpreter with minimal code repetition. It uses a little bit of macro magic, and does nested loops iteratively rather than using a cache, but it seems to do fine for most tasks I've given it.</p>
<p>One of my goals was to use the absolute minimum in external libraries, so I even made by own (length limited) strcpy.</p>
<p>Very open to style/functionality critiques, especially as it pertains to catching incorrect programs (eg <code>[[[</code>)</p>
<pre><code>/* brainfuck interpreter */
#include <stdio.h>
#define WORKSPACE_SIZE (65535)
void die(const char *msg)
{
puts(msg);
int x = *(int *)0;
}
/**
* dp is a pointer to the data pointer; that way we can manipulate the data
* pointer itself, and not just the data it points to. This allows us to
* easily implement both '>' and '+' instructions.
* pc is similar, it's a pointer to the program counter, which we use to index
* into the program text itself.
*/
void do_fsm(unsigned char **dp, const char **pc)
{
#define print_byte(b_) do {\
fprintf(stderr, #b_ ": '%c', %02x\n", b_, b_);\
} while(0)
/**
* starting at program counter, look in direction for matching
* branch character, accounting for nested loops.
* needs to have a check for overrunning past program text, in case of
* unmatched braces
* This is not quite as efficient as doing a single pass to note down
* locations of all open braces and their matching closing brace, but
* it's quick to write and this interpreter is meant to be simple, not fast.
*/
#define BRANCH_CASE(branch_char, matched_char, direction, dp_negation) \
case branch_char:\
if(dp_negation **dp) {\
loop_level++; \
while(loop_level) {\
(*pc) += direction;\
working_byte = **pc;\
if(working_byte == branch_char)\
loop_level++;\
if(working_byte == matched_char)\
loop_level--;\
}\
}\
break;
int loop_level = 0;
int working_byte = 0;
switch(**pc) {
case '>':
(*dp)++;
break;
case '<':
(*dp)--;
break;
case '+':
(**dp)++;
break;
case '-':
(**dp)--;
break;
case '.':
putchar(**dp);
break;
case ',':
**dp = getchar();
break;
BRANCH_CASE('[', ']', 1, !)
BRANCH_CASE(']', '[', -1, !!)
default:;
}
}
void cpy(unsigned char *dst, unsigned char *src, unsigned int len)
{
for(;len--; *dst++ = *src++);
}
#define OFST(p2, p1) ((unsigned long int) (p2) - (unsigned long int) (p1))
#define dbg(pc, dp, prgm) printf("pc %08x; dp %08x; *dp %02x '%c'\n", OFST(pc,prgm), OFST(dp,prgm), *dp, (char) 'x')
#undef dbg
#define dbg(...)
#define BOUNDED_BY(start, ptr, end) ((ptr >= start) && (ptr < end))
#define WARN_UNBOUNDED(start, ptr, end) do {\
if(!BOUNDED_BY(start, ptr, end)) puts("[WARNING] " #ptr " has stepped outside its allowed bounds!");\
} while(0)
void run(const char *prgm)
{
unsigned char data[WORKSPACE_SIZE] = {0};
unsigned char *dp = data;
const char *pc = prgm;
dbg(pc, dp, prgm);
while(BOUNDED_BY(prgm, pc, prgm + WORKSPACE_SIZE) && BOUNDED_BY(data, dp, data + WORKSPACE_SIZE) && *pc) {
do_fsm(&dp, &pc);
dbg(pc, dp, prgm);
pc++;
}
WARN_UNBOUNDED(prgm, pc, prgm+WORKSPACE_SIZE);
WARN_UNBOUNDED(data, dp, data+WORKSPACE_SIZE);
}
void xcpy(char *dest, const char *src)
{
unsigned int len = 0;
for(; len < WORKSPACE_SIZE && *src; *dest = *src, src++, dest++, len++);
// zero out the rest to prevent multiple programs from cluttering the program buffer
for(; len < WORKSPACE_SIZE; *dest = 0, dest++, len++);
}
int main(void)
{
char prgm [WORKSPACE_SIZE] = {0};
// Hello, World!
xcpy(prgm, ">++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<++.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>-]<+.");
// Game of Life
xcpy(prgm, ">>>->+>+++++>(++++++++++)[[>>>+<<<-]>+++++>+>>+[<<+>>>>>+<<<-]<-]>>>>[\n"
" [>>>+>+<<<<-]+++>>+[<+>>>+>+<<<-]>>[>[[>>>+<<<-]<]<<++>+>>>>>>-]<-\n"
"]+++>+>[[-]<+<[>+++++++++++++++++<-]<+]>>[\n"
" [+++++++++.-------->>>]+[-<<<]>>>[>>,----------[>]<]<<[\n"
" <<<[\n"
" >--[<->>+>-<<-]<[[>>>]+>-[+>>+>-]+[<<<]<-]>++>[<+>-]\n"
" >[[>>>]+[<<<]>>>-]+[->>>]<-[++>]>[------<]>+++[<<<]>\n"
" ]<\n"
" ]>[\n"
" -[+>>+>-]+>>+>>>+>[<<<]>->+>[\n"
" >[->+>+++>>++[>>>]+++<<<++<<<++[>>>]>>>]<<<[>[>>>]+>>>]\n"
" <<<<<<<[<<++<+[-<<<+]->++>>>++>>>++<<<<]<<<+[-<<<+]+>->>->>\n"
" ]<<+<<+<<<+<<-[+<+<<-]+<+[\n"
" ->+>[-<-<<[<<<]>[>>[>>>]<<+<[<<<]>-]]\n"
" <[<[<[<<<]>+>>[>>>]<<-]<[<<<]]>>>->>>[>>>]+>\n"
" ]>+[-<<[-]<]-[\n"
" [>>>]<[<<[<<<]>>>>>+>[>>>]<-]>>>[>[>>>]<<<<+>[<<<]>>-]>\n"
" ]<<<<<<[---<-----[-[-[<->>+++<+++++++[-]]]]<+<+]>\n"
" ]>>\n"
"]");
// Sierpinski
//xcpy(prgm, "++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<]>.>+[>>]>+]");
//xcpy(prgm, ">++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<++.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>-]<+.");
//run(prgm);
// For now, just run a simple "Hello, World!" program every time.
run(">++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<++.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>-]<+.");
run("[[["); // should segfault
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>One of my goals was to use the absolute minimum in external libraries</p>\n</blockquote>\n<p>Why? It's going to make your code slower in all likelihood, it's not helping you learn the standard libraries, and it's making your code longer, more complex and less legible. There is no win here.</p>\n<blockquote>\n<p>so I even made by own (length limited) <code>strcpy</code>.</p>\n</blockquote>\n<p>Your <code>cpy</code>? It's a slower and less-standard <code>memcpy</code>.</p>\n<p>Otherwise:</p>\n<ul>\n<li><code>die</code> attempts to abort the process by deliberately dereferencing a null pointer, but there are no guarantees that anything sane (such as clean program termination) will happen. <a href=\"https://stackoverflow.com/questions/7130878/at-what-point-does-dereferencing-the-null-pointer-become-undefined-behavior\">This is undefined behaviour</a>. Your C ABI is allowed to destroy the entire contents of the operating system's memory and force your computer to reboot - or do nothing - if it wants.</li>\n<li><code>print_byte</code> isn't used and can be deleted</li>\n<li><code>do / while 0</code> is a macro antipattern that I see floating around the web a lot. Bare brace-surrounded <code>{}</code> blocks are entirely legal and are a better fit.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T12:40:11.557",
"Id": "515514",
"Score": "1",
"body": "Regarding do-while-0 vs {} I beg to differ. `MACRO(args...);` should always be one single (compound if unavoidable) statement, not two. Though OP is overdoing it, as `MACRO(args...)` being a fully-braced single expression is superior to even that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T11:05:43.477",
"Id": "515592",
"Score": "1",
"body": "\"o / while 0 is a macro antipattern that I see floating around the web a lot. Bare brace-surrounded {} blocks are entirely legal and are a better fit.\" Hear, hear! I wrote a self-answered Q&A about the subject here: [What is do { } while(0) in macros and should we use it?](https://software.codidact.com/posts/279576). We also managed to convince the MISRA-C committee to drop this requirement in the latest version of their guidelines - using do while(0) used to be a required rule in that document but they removed it completely."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T22:48:05.643",
"Id": "261214",
"ParentId": "261197",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:17:36.350",
"Id": "261197",
"Score": "3",
"Tags": [
"c",
"brainfuck"
],
"Title": "Simple Brainfuck Interpreter Implementation in C"
}
|
261197
|
<p>I am new to python and I am trying to write a function with various actions based on the parameters sent. I am checking if the data has valid format then it publishes to /accepted otherwise to /rejected. If the data is fine then it does the function and then publishes to /success otherwise to /failure</p>
<p>Here is what i am doing now -</p>
<pre><code>def data_handler(event, context):
try:
input_topic = context.topic
input_message = event
response = f'Invoked on topic {input_topic} with message {input_message}'
logging.info(response)
client.publish(topic=input_topic + '/accepted', payload=json.dumps({'state': 'accepted'}))
except Exception as e:
logging.error(e)
client.publish(topic=input_topic + '/rejected', payload=json.dumps({'state': 'rejected'}))
try:
print('Perform the function based on input message')
client.publish(topic=input_topic + '/success', payload=json.dumps({'state': 'Execution succeeded'}))
except Exception as e:
logging.error(e)
client.publish(topic=input_topic + '/failure', payload=json.dumps({'state': 'Execution failed'}))
</code></pre>
<p>This works as of now but i think there should be a better way to implement this. Any idea?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:27:40.010",
"Id": "515430",
"Score": "1",
"body": "It would be nice to see this used in a `__main__` context where example input is given. There are a lot of questions around this, like \"What is `client`?\" If your entire program isn't proprietary code, it would be best to just post the whole thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:33:52.973",
"Id": "515432",
"Score": "0",
"body": "This is a big project for which this a small module i need to write. This is an AWS lambda function which is event triggered. The event parameter brings in the JSON payload. The client is the aws iot client which can publish to the specific topics based on MQTT"
}
] |
[
{
"body": "<p>Given that there isn't much here to analyse purely based on performance since we don't know what those other function calls do, here are some minor changes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def data_handler(message, topic):\n try:\n logging.debug(f'Invoked on topic {topic} with message {message}')\n client.publish(topic=topic + '/pass', payload=json.dumps({'state': 'pass'}))\n except Exception as e:\n logging.error(e)\n client.publish(topic=topic + '/fail', payload=json.dumps({'state': 'fail'}))\n</code></pre>\n<p>Both try/catch blocks in your code look identical, and you should have only one endpoint that needs to be communicated with. If you really <em>need</em> both, then there should be a separate function to have this code.</p>\n<p>It also seems pretty redundant that you're publishing to a <code>pass</code> and <code>fail</code> endpoint and have a payload that says whether or not it passed or failed. You should know that status based on the endpoint that receives the message.</p>\n<p>You can have the payload be more descriptive as well to remove multiple endpoints. Something like <code>{'formatted': true, 'error': ''}</code> is far more informative.</p>\n<p>Lastly, you can just pass your one-off variables into this function, like so: <code>data_handler(event, context.topic)</code>. If your <code>event</code> really is just a post message and not a posting event object, then that should be clarified somewhere in the code base.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:56:03.180",
"Id": "515458",
"Score": "0",
"body": "The different topics are used in order to convey different situations -\n`/accepted` - to publish a message when the payload is correctly formatted and can be parsed\n`/rejected` - incorrect formatting and cannot be parsed\n\nIf the publish on accepted is successful then try to publish to the `/success` topic to convey that the task was correctly performed (such as some OS configuration)\nIf the publish on `/success` is somehow not successful then publish on `/failure`.\n\nSeems like a separate function for the success / failure would work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:47:47.193",
"Id": "261200",
"ParentId": "261198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:18:51.110",
"Id": "261198",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Better way to structure and optimise try except statements"
}
|
261198
|
<blockquote>
<p>Follow-up from <a href="https://codereview.stackexchange.com/questions/261165/the-blacklist-blocking-malicious-domains-using-bash">this question</a> using @Toby Speight's answer:</p>
</blockquote>
<p>The primary concern is <code>jq</code> improvement/optimization, but please detail any others.</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
set -eu
sources=$(mktemp)
trap 'rm "$sources"' EXIT
curl -s -o "$sources" https://raw.githubusercontent.com/T145/packages/master/net/adblock/files/adblock.sources
for key in $(jq -r 'keys[]' "$sources")
do
case $key in
gaming | oisd_basic )
# Ignore these lists
;;
* )
url=$(jq -r ".$key.url" "$sources")
rule=$(jq -r ".$key.rule" "$sources")
curl -s "$url" |
case $url in
*.tar.gz) tar -xOzf - ;;
*) cat ;;
esac |
gawk --sandbox -- "$rule"
esac
done |
sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | sort -u > the_blacklist.txt
# use sort over gawk to merge sort multiple temp files instead of using up limited memory
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:44:16.213",
"Id": "515537",
"Score": "0",
"body": "Please refrain from modifying the code. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T16:27:57.020",
"Id": "515545",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I'm aware; the only change was a minor typo. Nothing about how the overall program works has been altered, and the change doesn't affect the chosen answer at all."
}
] |
[
{
"body": "<p>Don't use a <code>for</code> loop to iterate over program output. See <a href=\"http://mywiki.wooledge.org/BashFAQ/001\" rel=\"nofollow noreferrer\">http://mywiki.wooledge.org/BashFAQ/001</a></p>\n<p>Try this -- extract the keys, urls, rules all at once:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>jq -r 'keys[] as $k | [$k, .[$k].url, .[$k].rule] | @tsv' "$sources" |\nwhile IFS=$'\\t' read key url rule; do \n case $key in \n ...\n</code></pre>\n<p>If, for some reason, your shell does not understand <code>$'\\t'</code>, use</p>\n<pre class=\"lang-sh prettyprint-override\"><code>while IFS="$(printf '\\t')" read ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T18:40:22.600",
"Id": "261206",
"ParentId": "261199",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261206",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:19:25.877",
"Id": "261199",
"Score": "0",
"Tags": [
"linux",
"shell",
"sh"
],
"Title": "The Blacklist - follow-up"
}
|
261199
|
<p>I'm brushing up on Python, working my way through <a href="https://www.manning.com/books/python-workout" rel="noreferrer">Python Workout</a>. One of the exercises is to emulate the Python zip() function, assuming each iterable passed to the function is of the same length. Here's what I've come up with:</p>
<pre><code>def myzip(*args):
result = [[] for _ in range(len(args[0]))]
for i, v in enumerate(args):
for j, w in enumerate(v):
result[j].append(w)
for i, v in enumerate(result):
result[i] = tuple(v)
return result
</code></pre>
<p>While my function works, I have a hunch there must be a more succinct way of achieving the same thing (forgoing the nested loops). Is there? I'm running Python 3.9.</p>
|
[] |
[
{
"body": "<p>You should not apply <code>len</code>, because that requires that the first argument be at least as strong as a <code>Collection</code>, when <code>zip</code> should not need that guarantee and should only need <code>Iterable</code> which is a weaker type.</p>\n<p>Gathering results in memory can be inefficient and lead to memory starvation. It's worth noting that an in-memory approach might actually execute more quickly than a generator but you would want to test this.</p>\n<p>Attempt some type hinting. The amount of type-hinting you can do here is fairly limited, but you can do better than nothing.</p>\n<p>It's also worth noting that the <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\">official documentation has a reference implementation</a>.</p>\n<h2>Suggested</h2>\n<pre><code>from typing import Any, Iterable, Tuple\n\n\ndef myzip(*args: Iterable[Any]) -> Iterable[Tuple[Any, ...]]:\n first_iter, *other_iters = (iter(a) for a in args)\n\n for first in first_iter:\n yield (first, *(\n next(other) for other in other_iters\n ))\n\n\nfor a, b in myzip([1, 2, 3], [4, 5, 6]):\n print(a, b)\n</code></pre>\n<h2>Alternate</h2>\n<p>This version does not need to wrap the first argument in an iterator.</p>\n<pre><code>def myzip(first_iter: Iterable[Any], *args: Iterable[Any]) -> Iterable[Tuple[Any, ...]]:\n others = [iter(a) for a in args]\n\n for first in first_iter:\n yield (first, *(\n next(other) for other in others\n ))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T18:14:42.337",
"Id": "261205",
"ParentId": "261202",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:56:32.013",
"Id": "261202",
"Score": "6",
"Tags": [
"python",
"reinventing-the-wheel"
],
"Title": "Emulating Python zip() Function"
}
|
261202
|
<p>I am trying to implement a basic hash table using a list of tuples. The code produce the desired output. Please help me improve my code as I feel there are a lot of while loops.</p>
<pre><code>#global variables to keep track of the hash table
count = 0
size = 1000
def hash_table(size):
return [None] * size
def hash_item(key, value):
return (key,value)
def hash_func(key): #simple hash function
index = hash(key) % 1000
return index
def insert_hash(table,key,value):
index = hash_func(key)
item = hash_item(key,value)
global count
global size
if count == size:
raise Exception("Hash table limit reached")
if table[index] == None:
table[index] = item
else:
collision_handler(table, index, item)
count = count + 1
def print_hash(table,key):
index = hash_func(key)
while table[index][0] != key: #in case there is a collision:
index = index + 1
print(table[index])
def delete_hash(table,key):
index = hash_func(key)
while table[index][0] != key:
index = index + 1
table.pop(index)
def collision_handler(table,index,item): #handling collisions using open addressing
while table[index] != None:
index = index + 1
table[index] = item
a = hash_table(size)
b = hash_func('1')
insert_hash(a, '1','john')
print_hash(a,'1')
delete_hash(a,'1')
insert_hash(a,'1','edward')
print_hash(a,'1')
</code></pre>
|
[] |
[
{
"body": "<p>Despite the code produce the desired output in your simple test case, your implementation is quite flawed.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = hash_table(size)\n\ninsert_hash(a, 1, 'john')\ninsert_hash(a, 2, 'edward')\ndelete_hash(a, 1)\nprint_hash(a, 2)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File "C:/Code Review/hash_table.py", line 53, in <module>\n print_hash(a, 2)\n File "C:/Code Review/hash_table.py", line 30, in print_hash\n while table[index][0] != key: #in case there is a collision:\nTypeError: 'NoneType' object is not subscriptable\n>>> \n</code></pre>\n<p>The issue: <code>table.pop(index)</code> will move items after the one being delete forward by one position in the table. Given that they are indexed by the hash values, this would mean that they can't be found anymore.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = hash_table(size)\n\nfor _ in range(2000):\n insert_hash(a, 1, 'john')\n delete_hash(a, 1)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File "C:/Code Review/hash_table.py", line 51, in <module>\n insert_hash(a, 1, 'john')\n File "C:/Code Review/hash_table.py", line 22, in insert_hash\n if table[index] == None:\nIndexError: list index out of range\n>>> \n</code></pre>\n<p>After each insert/delete, the table size has shrunk by one item. After a thousand insert/deletes, the table can't hold any values!</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = hash_table(size)\n\ninsert_hash(a, 999, 'john')\ninsert_hash(a, 999, 'edward')\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File "C:/Code Review/hash_table.py", line 51, in <module>\n insert_hash(a, 999, 'edward')\n File "C:/Code Review/hash_table.py", line 25, in insert_hash\n collision_handler(table, index, item)\n File "C:/Code Review/hash_table.py", line 42, in collision_handler\n while table[index] != None:\nIndexError: list index out of range\n>>> \n</code></pre>\n<p>A collision at the last slot in the hash table doesn't have room to handle the collision, despite the table only having a 999 empty slots. You need to use circular addressing.</p>\n<p>You need to add more test cases, and rework the code to handle these issues. I generated these issues quickly by exploiting the fact that <code>hash(int) == int</code> for sufficiently small integers, but they would arise using strings for keys as well. It is just be harder to generate cases which deterministicly fail using string keys.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T22:40:56.277",
"Id": "261213",
"ParentId": "261204",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261213",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T17:59:28.057",
"Id": "261204",
"Score": "2",
"Tags": [
"python",
"reinventing-the-wheel",
"hash-map"
],
"Title": "Implementing hash table in Python using Tuples"
}
|
261204
|
<blockquote>
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/q/261089/120114">this phonebook code</a>.</p>
</blockquote>
<p>This Phone Book allows the user to Enter a value between 1-3.</p>
<p>Entering 1 lets the user Add a number to the phone book, when the process is finished, the user is asked again to pick 1 of the 3 tasks.</p>
<p>Entering 2 lets the user speed dial a number. If the number exists, it will be dialled, else an error statement will be printed. Again the user will pick from 1 of 3 options.</p>
<p>Entering 3 exits the program.</p>
<p>Question: How could I make this code easier to follow/understand. Can I make it more objected oriented and how? I've also been told using too many static methods is bad practice. I've passed the scanner and arraylist to the class to prevent this, and just want to make sure it was done correctly as I haven't done this before.</p>
<p><strong>PhoneBookV2.java</strong></p>
<pre><code>package com.java.phonebook;
import java.util.ArrayList; //Import ArrayList
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner; //Import Scanner
public class PhoneBookV2 {
public static void main(String[] args){
final List<String> numbers = new ArrayList<>(); //Initialize new ArrayList
Scanner scan = null;
try {
scan = new Scanner(System.in);
PhoneBook phoneBook = new PhoneBook(scan, numbers);
phoneBook.task();
}catch(InputMismatchException e){
System.out.println("Scanner Not Found");
}finally{
if(scan != null){
scan.close();
}
}
}
}
</code></pre>
<p><strong>PhoneBook.java</strong></p>
<pre><code>package com.java.phonebook;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PhoneBook {
Scanner scan;
List<String> numbers;
public PhoneBook(Scanner scan, List<String> numbers) {
this.scan = scan;
this.numbers = numbers;
}
public void task() {
boolean cont = true;
do {
//Ask user for input on which task they want to do
System.out.println("Please Pick A Task: \n 1:Add A Number to Speed Dial \n 2:Speed Dial A Number \n 3:Exit");
String choice = scan.nextLine(); //read input
//check user input and continue accordingly
switch (choice) {
case "1":
AddNumber(); //run AddNumber Method
cont = false;
break;
case "2":
CallNumber(); //Run CallNumber method
cont = false;
break;
case "3":
System.out.println("Goodbye!");
System.exit(0); //Terminate Program
cont = false;
break;
default:
System.err.println("Invalid");
}
}while(cont);
}
public void CallNumber() {
boolean cont = true;
//create Keypad
do try {
String[][] keys = {
{" ", "1", " ", "2", " ", "3"},
{" ", "4", " ", "5", " ", "6"},
{" ", "7", " ", "8", " ", "9"},
{" ", " ", " ", "0", " ", " "}
};
//print keypad
printPhoneBook(keys);
//ask user for key number
System.out.println("Pick A Speed Dial Number");
String phoneNum = null; // should not be initialized as "", otherwise dialing message would be displayed even if choice is invalid.
if (scan.hasNextInt()) {
int choice = Integer.parseInt(scan.nextLine()); //convert string to int
if (choice >= 0 && choice <= 9) {
phoneNum = numbers.get((choice + 9) % 10);
} else {
System.err.println("Does Not Exist");
continue;
}
}
//if number exists, Dial number
if (phoneNum != null) {
System.out.println("Dialing " + phoneNum + "....");
cont = false;
}
//or say no number exists
else {
System.out.println("There is No Number At This Location");
break;
}
//ask user tasks again
task();
} catch (IndexOutOfBoundsException e) { //catch possible errors
System.err.println("There is No Number At This Location");
//ask for tasks again
task();
}while(cont);
}
public void AddNumber() {
boolean cont = true; //initialize boolean for loop
do try{
System.out.print("Please Enter The Number You Wish To Save Under Speed Dial: ");
if(scan.hasNextLong()) {
long input = Long.parseLong((scan.nextLine().trim().strip()));
if ((input >= 100) && (input <= 999_999_999)) {
// Add the next number to the ArrayList
numbers.add(String.valueOf(input));
}else if((input < 1000) || (input > 999_999_999)){
System.out.println("Invalid Entry");
continue;
}
}else if (scan.hasNextLine()) {
scan.nextLine();
System.out.println("Invalid Entry");
continue;
}
System.out.print("Would you like to add another? Yes or No: ");
String answer = scan.nextLine().toLowerCase(); //take input and convert to lowercase
if (answer.equals("yes")){
continue; //if they want to continue, allow it
}else if (answer.equals("no")) { //if not, print arraylist and exit loop
print((ArrayList<String>) numbers);
cont = false;
}else if(answer.equals("")){
System.out.println("Invalid Entry");
}else{
System.out.println("Invalid");
}
}catch(NumberFormatException e){
}while(cont);
//ask user tasks again
task();
}
public static void printPhoneBook(String[][] keys){
// Loop to print array
for(String[] row : keys){
for(String s : row){
System.out.print(s);
}
System.out.println();
}
}
public void print(){
//loop to print array numbers
for(int i = 0; i< numbers.size(); i++){
System.out.println((i+1) + ") " + numbers.get(i));
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Conventions</h2>\n<p>Following language conventions can make your code more approachable to other people. Java methods follow <code>camelCase</code>, so <code>CallNumber</code> should be <code>callNumber</code> etc. More naming conventions <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html#:%7E:text=Interface%20names%20should%20be%20capitalized%20like%20class%20names.&text=Methods%20should%20be%20verbs%2C%20in,of%20each%20internal%20word%20capitalized.&text=Except%20for%20variables%2C%20all%20instance,with%20a%20lowercase%20first%20letter.\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h2>keys</h2>\n<p>I think you've done this so that it's easier to write the display code:</p>\n<pre><code>String[][] keys = {\n {" ", "1", " ", "2", " ", "3"},\n</code></pre>\n<p>However, it means that <code>keys</code> doesn't just contain keys. It also contains white space that is to be printed between keys. This can be a little confusion and may cause issues if you wanted change the way print the phone in the future.</p>\n<p>Since <code>keys</code> is only used by the private method <code>printPhoneBook</code>, it might make sense for it to be defined as a local variable in that method, rather than in the <code>CallNumber</code> method.</p>\n<h2>Public interface</h2>\n<p>The public methods on your class setup the expectation about how the class is to be used. All of the methods in your <code>PhoneBook</code> class are public, however it looks like <code>task</code> is the only one that you'd really expect a client to call. Some methods like <code>CallNumber</code> seem like they <em>could</em> be public methods, however they then call <code>task</code> which presents the user with a 'what do you want to do next decision'. This could be a little confusing.</p>\n<h2>It does what is says on the tin...</h2>\n<p>Naming is an important skill, which is surprisingly difficult get right. A good start is trying to make sure that names reflect what a variable/method/class represents/does/is responsible for. <code>printPhoneBook</code> doesn't look to me like it prints a phonebook. It looks like it prints they key pad (assuming the client passes in the correct structure).</p>\n<h2>Exit!</h2>\n<pre><code>System.out.println("Goodbye!");\nSystem.exit(0); //Terminate Program\ncont = false;\nbreak;\n</code></pre>\n<p>Nothing after the <code>exit</code> is run, because the process terminates. Having code after the <code>exit</code> is confusing. Generally you don't actually want to call <code>System.exit</code> other than in extreme circumstances. A better approach is to either throw an Exception, or in this case simply return from the <code>task</code> method so that the caller can decide what to do next.</p>\n<h2>Looping / Recursion.</h2>\n<p>Your <code>task</code> method has a loop in it that keeps going until a valid choice is selected. If a valid choice is selected though, each choice calls back to <code>task</code> to loop again. It seems like just having <code>task</code> keep looping until <code>exit</code> is selected may be more straightforward. It would also mean that <code>AddNumber</code> and <code>CallNumber</code> didn't have to call <code>task</code> to display the menu again. This in turn would mean that it was possible to call <code>AddNumber</code> from a different class, which goes some way towards making the class more reusable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T00:46:26.887",
"Id": "261218",
"ParentId": "261211",
"Score": "3"
}
},
{
"body": "<p>The main things you seem to have done is a) share the Scanner and b) move the processing into a class. You've also added some validation of your input. This is still not OOP.</p>\n<ul>\n<li>The first problem I find is that your PhoneBook class will not compile. At the very least, code you submit here should compile and pass some basic sanity tests.</li>\n<li>Your approach to indexing is odd, and unclear. Are you sure you understand how 0-based indexing works in Java?</li>\n<li>The fixed size list is enforced in some parts of your code - you only allow entries 0-9 to be chosen, but you allow an unlimited number of entries to be added. (Is this because you want to allow an unlimited number of entries, and speed-dial applies to the first 10? If so, you should document that design decision).</li>\n<li>Your input validation rejects invalid numbers (like "banana") without giving any feedback, and the try...catch block is bigger than it needs to be, making it harder to understand.</li>\n<li>Your range check on phone numbers is inconsistent (100 or 1000?) and if you were consistent, then the second "if" (in the "else") would be redundant.</li>\n<li>You still use recursion for your main "loop"</li>\n<li>You still have no distinction between the data and its external presentation. Nothing about your Phonebook could be reused sensibly if you, for example, moved to a GUI or a REST API approach. Read up on "Separation Of Concerns"...</li>\n<li>As already mentioned, you don't follow Java naming conventions, and your code formatting is also non-standard - I've never seen "do" and "try" on the same line before, and hope never to do so again. (Formatting is easily fixed by using a decent GUI, such as Eclipse or IntelliJ and getting it to format your code)</li>\n<li>Your commenting is frequently pointless - <code>import java.util.Scanner; //Import Scanner</code> has no value at all. Comments should add value, usually by explaining why the code is as it is.</li>\n</ul>\n<p>Here's a suggestion to get you started on an Object-Oriented approach.</p>\n<p>In this design I assume that your PhoneBook should store an unlimited number of phone numbers in the order in which they have been entered, and that the first 10 entries (indexes 0 to 9) should be available as speed-dial numbers.</p>\n<p>First, write a PhoneBook class <strong>which does no I/O</strong> - it should implement <code>Iterable<String></code> and provide the following:</p>\n<ol>\n<li>A constructor which takes no arguments.</li>\n<li>An addPhoneNumber() method which takes a phone number as a parameter and stores it in some internal store - an ArrayList seems a reasonable choice (create this in the constructor).</li>\n<li>A getPhoneNumber() method which takes an integer as a parameter and returns the appropriate phone number, returning null if no corresponding phone number exists.</li>\n<li>An iterator() method which returns an iterator over the internal list of phone numbers.</li>\n</ol>\n<p>Now write some unit tests for this class. Ideally use Junit, as that's the norm in Java and learning it will give you a valuable skill. Make sure your code compiles, and passes your unit tests. You should consider offering this class and the unit tests for review.</p>\n<p>Now write your interactive code to use this class, taking into account the feedback you've already been given, and following Java standards for naming and layout. Compile and test your program. Then raise a fresh request for review.</p>\n<p>Here's skeleton code for the PhoneBook class</p>\n<pre><code>import java.util.Iterator;\n\npublic class PhoneBook implements Iterable<String> {\n\n public PhoneBook() {\n // Add code to create the internal storage for phone numbers \n }\n \n public void addPhoneNumber(String phoneNumber) {\n // Add the phone number to the storage\n }\n \n public String getPhoneNumber(int index) {\n return null; // Change this to return the appropriate phone number, or null if none exists \n }\n \n public Iterator<String> iterator() {\n return null; // change this to return a suitable Iterator\n }\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T08:21:40.947",
"Id": "261234",
"ParentId": "261211",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:44:34.047",
"Id": "261211",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"static"
],
"Title": "PhoneBook in Java - follow-up"
}
|
261211
|
<p>I am really new to React and I worked on some challenges. I need to mention I did most of the stuff on my own without much dependence on the internet beside what functions do. I'd like to know if I did something wrong in regard to code structure and if there are better ways to achieve what I did.</p>
<p>The purpose of the code is a simple registration form with validation, step by step. At the end, it will complete and a heading will be displayed.</p>
<h3>App:</h3>
<pre><code>import "./App.css";
import Card from "./Card";
import React, { useState } from "react";
import UserInput from "./UserInput";
function App() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [step, setStep] = useState(1);
const [error, setError] = useState(true);
const onFirstNameChange = (event) => {
setFirstName(event.target.value);
};
const onLastNameChange = (event) => {
setLastName(event.target.value);
};
const onEmailChange = (event) => {
setEmail(event.target.value);
};
const onSubmitHandler = (event) => {
event.preventDefault();
if (step === 1 && firstName.trim().length === 0) {
setError(false);
return;
}
if (step === 2 && lastName.trim().length === 0) {
setError(false);
return;
}
if (step === 3 && email.trim().length === 0) {
setError(false);
return;
}
setStep((prevValue) => {
return prevValue + 1;
});
};
const stepBack = () => {
if (step === 2 && firstName.trim().length !== 0) {
setError(true);
setStep((prevValue) => {
return prevValue - 1;
});
}
if (step === 3 && lastName.trim().length !== 0) {
setError(true);
setStep((prevValue) => {
return prevValue - 1;
});
}
if (!error) return;
};
if(step===4){
return <h2>Registration Completed !</h2>
}
return (
<React.Fragment>
<Card>
<UserInput
submitHandler={onSubmitHandler}
onEmailChange={onEmailChange}
onFirstNameChange={onFirstNameChange}
onLastNameChange={onLastNameChange}
stepNum={step}
value={step === 1 ? firstName : step === 2 ? lastName : email}
></UserInput>
{step > 1 && <button onClick={stepBack}>Back</button>}
{!error && <label style={{ color: "red" }}> Required !</label>}
</Card>
<Card>
<p>{firstName}</p>
<p>{lastName}</p>
<p>{email}</p>
</Card>
</React.Fragment>
);
}
export default App;
</code></pre>
<h3>UserInput:</h3>
<pre><code>import React from "react";
const UserInput = (props) => {
const firstNameHolder = (
<React.Fragment>
<label>First Name</label>
<br />
<input
id="firstName"
type="text"
onChange={props.onFirstNameChange}
value={props.value}
></input>
</React.Fragment>
);
const lastNameHolder = (
<React.Fragment>
<label>Last Name</label>
<br />
<input
id="lastName"
type="text"
onChange={props.onLastNameChange}
value={props.value}
></input>
</React.Fragment>
);
const emailHolder = (
<React.Fragment>
<label>Email</label>
<br />
<input
id="email"
type="email"
onChange={props.onEmailChange}
value={props.value}
></input>
</React.Fragment>
);
return (
<React.Fragment>
<form onSubmit={props.submitHandler}>
{props.stepNum === 1 && firstNameHolder}
{props.stepNum === 2 && lastNameHolder}
{props.stepNum === 3 && emailHolder}
<button type="submit">Next</button>
</form>
</React.Fragment>
);
};
export default UserInput;
</code></pre>
<p><strong>Card</strong></p>
<pre><code>import React from "react";
import styles from './Card.module.css';
const Card = (props) => {
return <div className={`${styles.card} ${props.className}`}>{props.children}</div>;
};
export default Card;
</code></pre>
<p>Card.module.css</p>
<pre><code>.card{
position: center;
padding: 2em;
margin: 2em;
background: white;
box-shadow: 0 2px 8px black;
border-radius: 10px;
}
</code></pre>
|
[] |
[
{
"body": "<p>you can make this part of code a little bit shorter, before:</p>\n<pre><code>const [firstName, setFirstName] = useState("");\nconst [lastName, setLastName] = useState("");\nconst [email, setEmail] = useState("");\n\nconst onFirstNameChange = (event) => {\n setFirstName(event.target.value);\n };\n const onLastNameChange = (event) => {\n setLastName(event.target.value);\n };\n const onEmailChange = (event) => {\n \n setEmail(event.target.value);\n \n };\n</code></pre>\n<p>after:</p>\n<pre><code>const initialForm = {\n firstName: '',\n lastName: '',\n email: ''\n}\n...\nconst [form, setForm] = useState(initialForm );\n\n// allways wrap your components functions inside useCallback, to save it's value after rerender\nconst formChangeHandler = useCallback((event) => {\n // use "prev" param, to make dependences array empty\n setForm((prev) => (\n [event.target.name]: event.target.value\n ));\n}, [])\n</code></pre>\n<p>better to use switch/case structure here, and rename numbers to some words, you will get some problems if you will need to add some inputs between 1 and 2</p>\n<pre><code>{props.stepNum === 1 && firstNameHolder}\n{props.stepNum === 2 && lastNameHolder}\n{props.stepNum === 3 && emailHolder}\n</code></pre>\n<p>for this functions is better to create custom inputField component.\nBefore:</p>\n<pre><code>const emailHolder = (\n <React.Fragment>\n <label>Email</label>\n <br />\n <input\n id="email"\n// by the way - don't use email type for input. It had some problems\n type="email"\n onChange={props.onEmailChange}\n value={props.value}\n ></input>\n </React.Fragment>\n );\n</code></pre>\n<p>after:</p>\n<pre><code>const InputFieldComponent = ({ label, name, type, onChange, value }) => (\n <React.Fragment>\n <label>{label}</label>\n <br />\n <input\n id={name}\n type={type}\n onChange={onChange}\n value={value}\n ></input>\n </React.Fragment>\n)\n\n// and inside ur render\n\nreturn (\n <InputFieldComponent\n label="Email"\n name="email"\n type="text"\n onChange={formChangeHandler}\n value={form.email}\n />\n <InputFieldComponent\n label="Email"\n name="email"\n type="text"\n onChange={formChangeHandler}\n value={form.email}\n />\n)\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-04T12:06:27.233",
"Id": "262612",
"ParentId": "261212",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T21:58:23.657",
"Id": "261212",
"Score": "3",
"Tags": [
"beginner",
"react.js",
"jsx"
],
"Title": "Simple registration form with validation"
}
|
261212
|
<p>This program will get data from a folder called Data which has txt files and will return the filename with a score but I don't think it's really good.</p>
<p>Can I get any kind of feedback on this program. Is there anyway this can be written in a better way or something that should be added to?</p>
<pre><code>import os, nltk, re
from nltk import word_tokenize
from nltk.corpus import stopwords
nltk.download('stopwords') # helps remove stop words such as "the", "and" etc
nltk.download('punkt') # Punkt sentence tokenizer, helps break down text
files = os.listdir("Data/")
f = open("words.txt","r")
contents = f.readlines()
vocab = []
for word in contents:
vocab.append(word[0:-1].lower())
word_set = set(vocab)
def process_files(dir, filenames):
file_to_terms = {}
for file in filenames:
pattern = re.compile('[\W_]+')
name = dir + file
file_to_terms[file] = open(name, 'r').read().lower();
file_to_terms[file] = pattern.sub(' ',file_to_terms[file])
re.sub(r'[\W_]+','', file_to_terms[file])
file_to_terms[file] = file_to_terms[file].split()
return file_to_terms
listdata = []
listdata = process_files("Data/",files)
print("storing keywords in dictionary done")
def index_one_file(termlist):
fileIndex = {}
for index, word in enumerate(termlist):
if word in fileIndex.keys():
fileIndex[word].append(index)
else:
fileIndex[word] = [index]
return fileIndex
def make_indices(termlists):
total = {}
for filename in termlists.keys():
total[filename] = index_one_file(termlists[filename])
return total
indexwordallfiles = make_indices(listdata)
print("constructing inverted index.")
def fullIndex(regdex):
total_index = {}
for filename in regdex.keys():
for word in regdex[filename].keys():
if word in total_index.keys():
if filename in total_index[word].keys():
total_index[word][filename].extend(regdex[filename][word][:])
else:
total_index[word][filename] = regdex[filename][word]
else:
total_index[word] = {filename: regdex[filename][word]}
return total_index
wordindex = fullIndex(indexwordallfiles)
print("now proceeding with the query part")
def one_word_query(word, invertedIndex):
pattern = re.compile('[\W_]+')
word = pattern.sub(' ',word)
if word in invertedIndex.keys():
return [filename for filename in invertedIndex[word].keys()]
else:
return []
def free_text_query(string):
pattern = re.compile('[\W_]+')
string = pattern.sub(' ',string.lower())
result = []
print(" returning intersection of files")
for word in string.split():
result.append(set(one_word_query(word,wordindex)))
A={}
A = result[0].intersection(result[1])
for i in range(1,len(result)-1):
A = A.intersection(result[i+1])
return list(A)
k = len(files)
dic = {}
for item in wordindex:
k = 0
for fil in wordindex[item]:
k += (len(wordindex[item][fil]))
dic[item] = k
print(len(dic))
def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
try:
v = list(d.values())
k = list(d.keys())
value = k[v.index(max(v))]
return value
except:
return
def startQuery(query):
pattern = re.compile('[\W_]+')
query = pattern.sub(' ',query.lower())
txtlist = word_tokenize(str(query))
txtlist = [word for word in txtlist if not word in stopwords.words('english')]
toreturn = {}
for f in files:
toreturn[f]=0
for item in txtlist:
listfilename = one_word_query(item,wordindex)
for t in listfilename:
toreturn[t] +=1
num_of_files = len([iq for iq in os.scandir('Data/')])
for i in range(0,num_of_files):
tx = keywithmaxval(toreturn)
print("filename ", tx ," score ", toreturn[tx])
return tx
if toreturn[tx] != 0:
del toreturn[tx]
</code></pre>
|
[] |
[
{
"body": "<p>For <code>nltk</code>, <code>default_download_dir</code> is <code>PYTHONHOME\\lib\\nltk</code> on Windows or <a href=\"https://www.nltk.org/api/nltk.html#nltk.downloader.Downloader.default_download_dir\" rel=\"nofollow noreferrer\">one of various</a> <code>/usr</code> directories, falling back to the home directory, for the rest of the world. In a production application you would want to separate the <code>download()</code> step into the setup code rather than the application code.</p>\n<p>Otherwise,</p>\n<ul>\n<li>Consider replacing <code>os.listdir</code> and related functions with equivalent but more sugar-y calls to <code>pathlib</code></li>\n<li>From your <code>open()</code> call onwards, that code belongs in one or more methods rather than the global namespace</li>\n<li>Don't call <code>re.compile</code> from the inside of a loop; pre-compile your expression at the beginning of the method. Also, after doing this (repeated) compilation, you throw away the results and call <code>re.sub</code>. Use <code>pattern.sub</code> instead.</li>\n<li>No need to semicolon-terminate your statements</li>\n<li>Use <code>with</code> on your file opens</li>\n<li>Consider adding PEP484 type hints</li>\n<li><code>listdata = []</code> is redundant and can be deleted because you trample right over it on the next line; same with <code>A={}</code></li>\n<li><code>fileIndex</code> would be <code>file_index</code> by PEP8</li>\n<li><code>[filename for filename in invertedIndex[word].keys()]</code> can be <code>list(inverted_index[word])</code></li>\n<li><code>dic</code> is a poor name for a variable; it says the type but not what's inside</li>\n<li><code>[word for word in txtlist if not word in stopwords.words('english')]</code> would be better-represented by set subtraction</li>\n<li><code>range(0,num_of_files)</code> can drop the <code>0</code> since that's default</li>\n</ul>\n<p>This block:</p>\n<pre><code> return tx\n if toreturn[tx] != 0:\n del toreturn[tx]\n</code></pre>\n<p>will never see the last two statements executed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T00:29:31.423",
"Id": "261217",
"ParentId": "261216",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-25T23:20:08.663",
"Id": "261216",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Simple Search Engine Program in Python"
}
|
261216
|
<p>I was doing the following exercise:</p>
<blockquote>
<p>Create an algorithm which asks the user a number from 1 to 7, and each number represents a day on the week. For example, 1 represents Sunday, 2 represents Monday and so on. The user will type this number and the program will show them the name of the day on the week and if it's a business day or a weekend.</p>
</blockquote>
<p>I tried to do it in a object-oriented way and using Python. Can someone please verify if my code is within the Python and object-oriented "standards"? Because I'm not sure whether it is, and I need a review.</p>
<p>Here's my code:</p>
<pre><code>class DayOnWeek:
ERROR_MESSAGE = 'Invalid weekday. Try again:'
NUMBER_NAME_ASSOCIATIONS = {
1: 'Sunday',
2: 'Monday',
3: 'Tuesday',
4: 'Wednesday',
5: 'Thursday',
6: 'Friday',
7: 'Saturday'
}
def __init__(self):
self._day_number = 0
self._day_name = None
self._category = None
@property
def day_name(self):
return self._day_name
@property
def category(self):
return self._category
@property
def day_number(self):
return self._day_number
@day_number.setter
def day_number(self, value):
if 1 <= value <= 7:
self._day_number = value
self._day_name = DayOnWeek.NUMBER_NAME_ASSOCIATIONS[self._day_number]
else:
raise ValueError(DayOnWeek.ERROR_MESSAGE)
if 2 <= value <= 6:
self._category = 'Business day'
else:
self._category = 'Weekend'
class DayOnWeekInterface:
def __init__(self):
self._day_on_week = DayOnWeek()
def request_day_number(self):
while True:
try:
day_num = input('Type the number of the day on the week (ex: 1 - Sunday):')
day_num = int(day_num)
self._day_on_week.day_number = day_num
break
except ValueError:
print(DayOnWeek.ERROR_MESSAGE)
self.show_day_on_week()
def show_day_on_week(self):
day_num = self._day_on_week.day_number
day_name = self._day_on_week.day_name
day_category = self._day_on_week.category
print(f'The day {day_num} is {day_name.lower()}')
print(f'{day_name} is a {day_category.lower()}')
DayOnWeekInterface().request_day_number()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:29:58.447",
"Id": "515536",
"Score": "1",
"body": "@gnasher729 You're welcome to add an answer saying so."
}
] |
[
{
"body": "<p>It's great that you're thinking about classes, but you've misapplied them. This is a very simple problem that does not call for object-oriented code. The <code>calendar</code> module already has the name sequence, so you really only need a validation loop and a small output routine:</p>\n<pre><code>from calendar import day_name\n\n\ndef request_day_number() -> int:\n while True:\n try:\n value = int(input(\n 'Type the number of the day on the week (ex: 1 - Sunday): '\n ))\n except ValueError:\n print('Invalid integer. Please try again.')\n continue\n\n if 1 <= value <= 7:\n return value\n print('Invalid weekday. Please try again.')\n\n\ndef main():\n day_no = request_day_number()\n name = day_name[day_no - 1]\n print(f'Day {day_no} is {name}')\n\n if 2 <= day_no <= 6:\n kind = 'business'\n else:\n kind = 'weekend'\n print(f'{name} is a {kind} day')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>If you were married to the idea of an object-oriented representation, here is one relatively sane (if somewhat overbuilt) way:</p>\n<pre><code>from calendar import day_name\n\n\nclass Weekday:\n def __init__(self, index: int):\n self.index = index\n if not (0 <= index < 7):\n raise ValueError(f'{self.one_based} is an invalid week day index')\n\n @property\n def one_based(self) -> int:\n return self.index + 1\n\n def __str__(self) -> str:\n return day_name[self.index]\n\n @property\n def category(self) -> str:\n if self.index in {0, 6}:\n return 'weekend'\n return 'business'\n\n @classmethod\n def from_stdin(cls) -> 'Weekday':\n while True:\n try:\n value = int(input(\n 'Type the number of the day on the week (ex: 1 - Sunday): '\n ))\n return cls(value - 1)\n except ValueError as e:\n print(f'Invalid input: {e}. Please try again.')\n\n @property\n def description(self) -> str:\n return (\n f'Day {self.one_based} is {self}\\n'\n f'{self} is a {self.category} day\\n'\n )\n\n\ndef main():\n day = Weekday.from_stdin()\n print(day.description)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T04:10:02.500",
"Id": "261225",
"ParentId": "261219",
"Score": "8"
}
},
{
"body": "<p>There's some issues:</p>\n<ul>\n<li>when a new instance of your class is initialised, it has a state that's not supported by the rest of the code (i.e. a <code>_day_number</code> of <code>0</code>, with no matching name)</li>\n<li>The name <code>DayOnWeek</code> isn't very descriptive, why not just <code>Weekday</code>?</li>\n<li>Why not implement the <code>category</code> property as a property that decides the category based on the value of <code>_day_number</code> instead of storing the category in a hidden variable? (which is initialised to <code>None</code> as well, causing further problems)</li>\n<li>Similarly, why set <code>_day_name</code> to the name from the internal constant dictionary, instead of just returning the name directly from that in the property?</li>\n<li>The error message in the <code>DayOnWeek</code> class is specific to functionality in the <code>DayOnWeekInterface</code>, it should live there, or it should be phrased correctly.</li>\n<li>"Saturday is a Weekend"?</li>\n<li>You've created <code>DayOnWeekInterface</code> to separate out the interaction with the user, that's OK, but not a very common way to go about it, what exactly is the idea here?</li>\n<li>You've implemented a bunch of stuff that's just duplicating what existing libraries can do; not a great idea, unless you're coding this as a homework assignment that explicitly asks you to do so.</li>\n<li>All the properties and attributes have <code>_day</code> in their names, while they really are all directly applying to a <code>Day</code> object anyway, better naming would be simpler.</li>\n</ul>\n<p>However, following the general design you chose, this would be a revised version without those issues:</p>\n<pre><code>class Weekday:\n ERROR_INVALID_NUMBER = 'Invalid day number.'\n\n DAY_NAMES = {\n 1: 'Sunday',\n 2: 'Monday',\n 3: 'Tuesday',\n 4: 'Wednesday',\n 5: 'Thursday',\n 6: 'Friday',\n 7: 'Saturday'\n }\n\n def __init__(self, number=1):\n self.number = number\n\n @property\n def name(self):\n return self.DAY_NAMES[self._number]\n\n @property\n def category(self):\n return 'business' if 2 <= self._number <= 6 else 'weekend'\n\n @property\n def number(self):\n return self._number\n\n @number.setter\n def number(self, value):\n if 1 <= value <= 7:\n self._number = value\n else:\n raise ValueError(self.ERROR_INVALID_NUMBER)\n\n\nclass WeekdayInterface:\n def __init__(self):\n self._weekday = Weekday()\n\n def request_value(self):\n while True:\n try:\n self._weekday = Weekday(int(input('Type the number of the day on the week (ex: 1 - Sunday):')))\n self.show()\n except ValueError as e:\n print(e)\n\n def show(self):\n print(f'The day {self._weekday.number} is {self._weekday.name.lower()}')\n print(f'{self._weekday.name} is a {self._weekday.category.lower()} day.')\n\n\nWeekdayInterface().request_value()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T21:07:23.763",
"Id": "515563",
"Score": "0",
"body": "I'm not in love with the \"Weekday\" name. I wouldn't normally call Saturday a weekday. It's a day of the week, but not a weekday."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T07:19:10.210",
"Id": "515578",
"Score": "0",
"body": "Agreed, `DayOfWeek` or just `Day` might have been better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T04:14:11.647",
"Id": "261226",
"ParentId": "261219",
"Score": "4"
}
},
{
"body": "<p>Your <code>DayOnWeek</code> object is mutable, allowing you to set the <code>.day_number</code> property. For such a simple object is not a good idea. An immutable object is better.</p>\n<p>There are exactly 7 days of the week. For a one-of-seven choice, the go-to data-storage structure is an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>Enum</code></a>. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass DayOfWeek(Enum):\n Sunday = 1\n Monday = 2\n Tuesday = 3\n Wednesday = 4\n Thursday = 5\n Friday = 6\n Saturday = 7\n\n @property\n def weekend(self):\n return self in {DayOfWeek.Saturday, DayOfWeek.Sunday}\n\n @property\n def category(self):\n return 'Weekend' if self.weekend else 'Business day'\n\n @property\n def number(self):\n return self.value\n</code></pre>\n<p>Borrowing Reideerien's <code>request_day_number()</code> function you'd use the <code>DayOfWeek</code> enum like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n day_no = request_day_number()\n day = DayOfWeek(day_no)\n\n print(f'Day {day.number} is {day.name}')\n print(f'{day.name} is a {day.category} day')\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-16T08:23:43.263",
"Id": "519375",
"Score": "0",
"body": "Hi AJNeufeld. You have provided an alternate solution. However, answers must make at least one [insightful observation](/help/how-to-answer), and must explain why the change is better than the OP's code. Failure to follow the IO rule can result in your answer being deleted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T04:47:57.737",
"Id": "261229",
"ParentId": "261219",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T00:57:30.057",
"Id": "261219",
"Score": "9",
"Tags": [
"python",
"beginner",
"datetime"
],
"Title": "Simple day-of-week program"
}
|
261219
|
<p>need some help or advice, HackerRank's <a href="https://www.hackerrank.com/challenges/frequency-queries" rel="nofollow noreferrer">frequency-queries</a> challenge,
the challenge of this Hackerrank problem is to check if the frequencies of number in your data structure matches the queries.</p>
<p>small integer values, that occupy the first 2 bytes of the integer datatype are fast and passes the test, but for values close to 1.000.000.000 that the occupy the second half of the integer data type are much slower.</p>
<p>the code i made passes 14 of the 15 test.</p>
<p>the code runs in "0.270603 seconds" seconds on my pc for case 8, with 100.000 lines, while reading them from the text file (input08.txt), but it takes "28.1141 seconds" for test eleven (input11.txt) as also contains 100.000 lines but with values up to 1 billion or 1 to the power of 9 sized values on witch it fails.</p>
<p>it seamed i have build a really lean & fast code, made a custom <code>main()</code> function, but ...</p>
<p>the bottleneck seams to be ...</p>
<pre><code>does_exist_map(Map &map, int frequency)
</code></pre>
<p>i tried various ways to loop the map.<br />
what can i do to make it faster?</p>
<pre><code>typedef std::map<int, int> Map;
void add_to_map(Map &map, int value){
/*
std::cout << "add" << endl;
if (map.find(value) == map.end()) {
map[value] = 1;
}
else {
map[value]++;
}
*/
if (map.count(value) > 0)
{
map[value]++;
}
else
{
map[value] = 1;
}
}
void delete_or_update_from_map(Map &map, int value){
if(map[value] > 1){
map[value]--;
//std::cout << "found in map and updated: " << value << " value:" << map[value] << endl;
}
else{
//std::cout << "found in map and deleleted: " << value << endl;
map.erase(value);
}
/*
if (map.find(value) != map.end()) {
//cout<<"Key (" << value << ") found. Value is: "<<map[value]<<endl;
if(map[value] > 1){
map[value]--;
//std::cout << "found in map and updated: " << value << " value:" << map[value] << endl;
}
else{
//std::cout << "found in map and deleleted: " << value << endl;
map.erase(value);
}
}
else {
//std::cout << "not found in map: " << value << endl;
}
*/
/*
if (map.count(value) > 0)
{
std::cout << "'hat' Found" << std::endl;
}
else
{
std::cout << "'hat' Not Found" << std::endl;
}
*/
}
bool does_exist_map(Map &map, int frequency){
//std::cout << "frequency: " << frequency << endl;
/*
or (auto& it : map) {
//cout << it.first << ' ' << it.second << '\n';
if(it.second == frequency){
return true;
}
}
*/
bool itexist = false;
int sizeMap = map.size();
auto it = map.begin();
for(int i = 0; i < sizeMap; i++){
if(it->second == frequency)
{
itexist = true;
break;
//return true;
}
it++;
}
/*
bool itexist = false;
auto it = map.begin();
while(it != map.end())
{
if(it->second == frequency)
{
itexist = true;
break;
//return true;
}
it++;
}
//return false;
*/
return itexist;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
ofstream fout(getenv("OUTPUT_PATH"));
string q_temp;
getline(cin, q_temp);
int q = stoi(ltrim(rtrim(q_temp)));
Map frequencies;
for (int i = 0; i < q; i++) {
int input[2] = {0,0};
for (int j = 0; j < 2; j++) {
cin >> input[j];
}
//std::cout << "task: " << input[0] << " value: " << input[1] << endl;
if(input[0] == 1){
add_to_map(frequencies, input[1]);
}
else if(input[0]== 2){
delete_or_update_from_map(frequencies, input[1]);
}
else if(input[0] == 3){
if(does_exist_map(frequencies, input[1])){
fout << "1\n";
}
else{
fout << "0\n";
}
}
}
fout.close();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T04:07:18.457",
"Id": "515473",
"Score": "5",
"body": "[Edit] the question to include a brief summary of the problem that the code solves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:36:04.793",
"Id": "515523",
"Score": "0",
"body": "Hi there, i have updated the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T16:22:09.297",
"Id": "515543",
"Score": "0",
"body": "Please do not edit the question after there has been an answer, especially don't change the code to the one suggested in the answer. See [here](https://codereview.stackexchange.com/help/someone-answers): \"Do not add an improved version of the code after receiving an answer. Including revised versions of the code makes the question confusing, especially if someone later reviews the newer code.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T06:27:12.577",
"Id": "515665",
"Score": "0",
"body": "@BlameTheBits Ordinarily I'd agree, but the question is still at risk of getting closed. If the question is closed, the answer arrived to early and determining whether it's answer-invalidation gets a lot more complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T06:27:39.827",
"Id": "515666",
"Score": "0",
"body": "ND, do you know why your code fails the 15th test? Is it because the output is wrong or because the time-limit is exceeded?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T07:12:35.010",
"Id": "515673",
"Score": "0",
"body": "@Mast, it fails on test 11 on time-limit, it's a so called corner case where most of the 100.000 values in the array occur only once, but you need to search for one the occurs 2 or more times and you have to iterate the whole map to find that one where the map[key] value is bigger than 1 and it takes to long to find it. for Test 8 that also contains 100.000 it passes the test, it passes 14 of 15 tests. the benefit of map, you can find a key almost instantly, map[...]. i need 2 maps and keep them in sync ... somehow."
}
] |
[
{
"body": "<h1>Performance of <code>std::map</code></h1>\n<p>Well, looking up in a map is a slow operation.</p>\n<pre><code>if(map[value] > 1){\n map[value]--;\n</code></pre>\n<p>is looking up the same thing twice. Don't do that with maps!</p>\n<p>You could write:</p>\n<pre><code>auto& v= map[value];\nif (v>1) --v;\n</code></pre>\n<p>Hmm, but you continue with:</p>\n<pre><code>\n else{\n //std::cout << "found in map and deleleted: " << value << endl;\n map.erase(value);\n }\n</code></pre>\n<p>So you call the form of <code>erase</code> that again looks it up from scratch, even though you already found it. Note that there is a form of <code>erase</code> that takes an iterator instead.</p>\n<p>But do you actually have to delete it from the map? Why not just leave it as zero? Would that be faster and simpler?</p>\n<hr />\n<p>I also see you wrote:</p>\n<pre><code>if (map.count(value) > 0)\n {\n map[value]++;\n }\n else\n {\n map[value] = 1;\n }\n</code></pre>\n<p>Same here: <code>count</code> looks it up. Then you look it up all over again just to increment it, or look up where it should be inserted in order to add it.</p>\n<p>Did you know that <code>map[value]</code> will automatically add the thing if it wasn't already there? And, it will initialize the newly created value the same as a static variable would be; that is, zero. So none of that is necessary. Just write <code>++map[value]</code> and be done with it.</p>\n<pre><code> for (auto& it : map) {\n //cout << it.first << ' ' << it.second << '\\n';\n if(it.second == frequency){\n return true;\n }\n }\n</code></pre>\n<p>OK, you are doing a reverse-lookup. That's not what maps are good at, and you do a full linear search for the value, using the (slow) pointer-based data structure. Your three variations of this code doesn't change this, and this first one is the best (other than your missing <code>const</code>). Of course, you are just implementing <code>std::find</code> that already exists in the library.</p>\n<p>You need a <em>second</em> map that indexes the reverse operation. Be sure to keep them updated in sync. There is a Boost multi-index map that you can use, too.</p>\n<p>Note that every time you update the frequency, you need to change the reverse index, and that can end up being expensive. If you do lots of adding before any lookups, then don't create the reverse index until you are done adding. I did something like that recently, and switched from "input mode" to "readout mode" by resorting how I kept the data.</p>\n<p>If you are only doing 1 lookup, then sorting/indexing it is more work than you need.</p>\n<p>You can instead try speeding up the search my using a Boost <code>flat_map</code>. This keeps everything in a sorted vector instead of a dynamic-memory tree, so traversing it in order will be <em>much</em> faster. The bottleneck is the memory access: trees of pointers hit cold (uncached) memory at every step, and it can't prefetch because it doesn't know where it's going. The vector is a contiguous range of memory which means several consecutive entries will be in the same cache row, and if you're scanning through it the CPU will catch on and start prefetching the next block! <strong>The speed difference on modern architectures is astounding.</strong> There is an essay on the opening doc page of Boost's flat map that explains in detail.</p>\n<p>In the similar task I mentioned earlier, I ended up just using a sorted <code>std::vector</code>, so I had full control over sorting, re-sorting, and searching. Note that you don't have to implement a lot, but can do it all using the supplied Algorithms library: Use <a href=\"https://en.cppreference.com/w/cpp/algorithm/lower_bound\" rel=\"nofollow noreferrer\"><code>std::lower_bound</code></a> to either find the element <em>or</em> the position where it should be inserted to maintain sort order.</p>\n<p>If lookup is clearly done after all addition/removal is performed, and you will have a lot of lookups, then you can re-sort based on the other field. But since sorting is <em>n log n</em> and a single unsorted <code>find</code> is order of <em>n</em>, if you have fewer than <em>log n</em> lookups (as a first approximation) it's faster to just do a linear search. You might also try using a hash table like <code>std::unordered_map</code> but these are also slow for the same reasons explained above, contrary to what is taught in CS classes (because <code>k</code> is so extremely large — memory access is the bottleneck).</p>\n<h1>other tips</h1>\n<p><code>typedef std::map<int, int> Map;</code><br />\nDon't use <code>typedef</code> anymore. Use <code>using</code> instead, which is more general and works with templates.</p>\n<pre><code> for (int j = 0; j < 2; j++) {\n cin >> input[j]; \n }\n</code></pre>\n<p>This could be:<br />\n<code>for (auto& x : input) cin>>x;</code></p>\n<pre><code> if(does_exist_map(frequencies, input[1])){\n fout << "1\\n";\n\n }\n else{\n fout << "0\\n";\n }\n</code></pre>\n<p>You're just printing the result of the function call as 0 or 1, but you're duplicating entire statements.</p>\n<pre><code>const bool b = does_exist_map(frequencies, input[1]);\nfout << b << '\\n';\n</code></pre>\n<p>You can control how <code>bool</code> values print via <a href=\"https://en.cppreference.com/w/cpp/io/manip/boolalpha\" rel=\"nofollow noreferrer\">formatting flags</a>. I think "no alpha" is the default though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:46:01.293",
"Id": "515538",
"Score": "1",
"body": "thanks a lot, i have learned quite a few things, i updated the code and it still works, but i cant use boost, my 8 years old dual 2.5 GHz Intel Celeron, is doing the job quite well, slightly of a quarter of second with 100.000 values, accept for test 11, \"You need a second map that indexes the reverse operation\", what do you mean with this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:55:18.270",
"Id": "515540",
"Score": "0",
"body": "i downloaded boost, but there is no way to isolate flat_Map on the fly. HackerRank max support = C14."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T22:46:49.410",
"Id": "515568",
"Score": "0",
"body": "@NaturalDemon I added some more to my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T13:43:13.483",
"Id": "515604",
"Score": "0",
"body": "@NaturalDemon _\"what do you mean by this?\"_ The `map` lets you look up a value based on `first`. That is, the collection is indexed, or you can consider this to be a key field. You need another index-like collection that lets you look up a desired value for `second`. Think about: `for(const auto& rec : map) map2[rec.second]=rec.first;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T15:22:28.747",
"Id": "515617",
"Score": "0",
"body": "thnx sofar, yeah, i found this \"https://www.codesynthesis.com/~boris/blog/2012/09/11/emulating-boost-multi-index-with-std-containers/\" last night and studying how this can be achieved.\nI'm struggling with the \"Key\" thing and temporary pointers. having both key van value as key and pointers as value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T14:15:02.890",
"Id": "515701",
"Score": "1",
"body": "@NaturalDemon his opening point about creating a dummy Person instead of just finding the email is obsolete; the std containers support that now. I think that blog code is hard to follow. Unless you have a great many lookups compared to the number of adds, you are better off just using a sorted vector for adding and unordered search for lookup on `second`. So don't worry about that blog's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T05:42:37.110",
"Id": "515778",
"Score": "0",
"body": "yeah, you're right about that blog code, but it gives a rough idea, I'm fingering out that temporary pointer stuff \"Key\" and how to replicate and apply it, i have his code in my compiler and it works, but it's pretty hard to follow on what is going on there. i'm thing about a map and a multimap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T04:29:29.570",
"Id": "515925",
"Score": "0",
"body": "https://pastebin.com/kG0biuut, on my computer i have the rights results, at least they where on my pc. but i changed 'does_exist_map(MultiMap &valuemap, const int frequency)' to find out why it fails on HackerRank, now i'm failing again, but now it does the job in less than a second with 100.000 values. the insertion method is triple checked 'add_to_map', works perfect, as does the 'delete_or_update_from_map' method. on my pc i print the results i na text file and compare them vs output files from HackerRank, it was spot on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T04:37:08.540",
"Id": "515926",
"Score": "0",
"body": "you just have to find any match on task 3, it doesn't matter if there are multiple. ' Check if any integer is present whose frequency is exactly . If yes, print 1 else 0. '"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T13:48:06.673",
"Id": "516082",
"Score": "0",
"body": "If the code works differently on your machine, you may have some \"undefined behavior\". Are you compiling with optimization flags?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T20:34:25.097",
"Id": "516106",
"Score": "0",
"body": "i use Qt creator, until now never used them. what are the benefits?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-02T13:41:20.977",
"Id": "516134",
"Score": "0",
"body": "@NaturalDemon what are you replying to? What is \"them\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-03T00:46:37.197",
"Id": "516171",
"Score": "0",
"body": "\"optimization flags\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-03T14:35:24.293",
"Id": "516213",
"Score": "0",
"body": "What are the benefits of turning on optimization? The code will be _much_ faster and might be smaller as well."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:57:09.930",
"Id": "261245",
"ParentId": "261223",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T02:34:24.120",
"Id": "261223",
"Score": "-2",
"Tags": [
"c++",
"performance",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "HackerRank frequency queries"
}
|
261223
|
<p>I am a newbie to JS and I am working on a FizzBuzz challenge. Below is what I have tried. Essentially when the function takes a value then it would iterate from 1 up to the value and an array would result.</p>
<p>I am seeking advice on adding conditional checking such as:</p>
<ol>
<li>If the value of <code>n</code> is less than 4, it will return the string: "Please insert a value greater than or equal to 4".</li>
<li>If the function is passed no value, it should return an empty array.</li>
</ol>
<p>I am not sure where to add and should I be using <code>if</code>...<code>else</code> or simply <code>if</code> for each conditional checking.</p>
<pre><code>var fizzBuzz = function(n, arr = []) {
for (let i = 1; i < n; i++) {
if (n === 1) {
arr.push('1');
return arr.reverse();
} else {
if (n % 4 === 0 && n % 5 === 0) {
arr.push('FIZZBUZZ');
} else if (n % 5 === 0) {
arr.push('Buzz');
} else if (n % 4 === 0) {
arr.push('Fizz');
} else {
arr.push('' + n);
}
return fizzBuzz(n - 1, arr);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T11:34:21.503",
"Id": "515506",
"Score": "1",
"body": "Welcome to CodeReview. I voted to close because this code does not work at all, `fizzBuzz(20)` returns `undefined`. Also Fizz is every 3, not every 4."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:46:16.883",
"Id": "515525",
"Score": "0",
"body": "Welcome to Code Review! Code Review isn't about helping you modify your code for new requirements, it is about helping you to see better logic. We Review code here, Code that is already written and fulfilling all requirements."
}
] |
[
{
"body": "<blockquote>\n<p>I am hoping to seek advice on adding conditional checking such as: 1) if the value n is less than 4, it will return the string: "Please insert a value greater than or equal to 4" and 2) if the function is passed no value, it should return an empty array. I am not sure where to add and should I be using if...else or simply if for each conditional checking.</p>\n</blockquote>\n<p>If we check for <code>n < 4</code> and returns a fixed string <code>"Please insert a value greater than or equal to 4"</code> anyway, do we really need to do anything before it? If we don't need to do anything before it, where should we put it?</p>\n<p>Same goes for <code>2) if the function is passed no value, it should return an empty array</code></p>\n<hr />\n<p>For the code itself, some points</p>\n<p><strong>1.</strong> Let's look at the loop</p>\n<pre class=\"lang-js prettyprint-override\"><code>for (let i = 1; i < n; i++) {\n if (n === 1) { \n // blah\n return arr.reverse();\n } else { \n // blah\n return fizzBuzz(n - 1, arr); \n }\n}\n</code></pre>\n<p>On every iteration this will return something. The <code>for</code> loop won't even need to go through the next iteration, it will always break and <code>return</code> on any iteration(!). You are doing recursion and loop at the same time.</p>\n<p><strong>2.</strong> <code>arr.push('' + n);</code></p>\n<p>Maybe use <code>toString()</code> method for numbers <code>arr.push(n.toString());</code></p>\n<p><strong>3.</strong> <code>if-else</code> and returns</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (n === 1) { \n arr.push('1');\n return arr.reverse();\n} else { \n // blah \n}\n</code></pre>\n<p>Since the <code>if</code> block will always return, we don't need the <code>else</code>. This can be rewritten as</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (n === 1) { \n arr.push('1');\n return arr.reverse();\n}\n \n// the else blah \n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T04:31:18.510",
"Id": "261227",
"ParentId": "261224",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T03:50:21.347",
"Id": "261224",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"fizzbuzz"
],
"Title": "Fizz Buzz function that returns an array"
}
|
261224
|
<p>I'm learning the file system library and thought nothing could be better than a project, so I thought of recreating the basic Linux commands such as <code>ls</code>, <code>cd</code> etc using C++ and <code><filesystem></code>.</p>
<p>As I said, I'm learning C++ and exploring libraries, so there could be weird code and all those things; could you review my code and say where I can improve the code?</p>
<h2>My Code:</h2>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <filesystem>
#include "command.h"
namespace fs = std::filesystem;
int main()
{
//Basic Linux Feel ;)
std::string CurPath = fs::current_path();
std::cout << "~";
color::color_blue(CurPath);
std::cout << "$ ";
//Main Loop
while (true)
{
std::string cmnd;
getline(std::cin, cmnd);
#if DEBUG
if (cmnd == "exit")
return 0;
#endif
DetermineCommand(cmnd);
}
}
</code></pre>
<p>command.h</p>
<pre><code>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <chrono>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
using namespace std::chrono_literals;
//DEBUG Mode :) I Used This For Exitting The Infinite Loop
#define DEBUG 1
//Used For Setting Color To Console According To OS
class color
{
public:
static void color_green(std::string path)
{
#ifndef __LINUX
//color code for green
std::cout << "\033[32m" << path << "\033[0m";
#else
//Green
system("Color 02");
std::cout << path;
//White
system("Color 07");
#endif
}
static void color_blue(std::string path)
{
//color code for blue
#ifndef __LINUX
std::cout << "\033[34m" << path << "\033[0m";
#else
//Blue
system("Color 01");
std::cout << path << " ";
//White
system("Color 07");
#endif
}
};
//Says The Current Path Color Encoded
void SayPath()
{
std::cout << std::endl;
std::string CurPath = fs::current_path();
std::cout << "~";
color::color_blue(CurPath);
std::cout << "$ ";
}
//cp Used For Copying Files
void cp(std::string p1, std::string p2)
{
fs::path ToCopy = p1, Target = p2;
if (!fs::exists(p2)|| !fs::exists(p1))
{
throw std::string("cp: cannot stat " + p1 + ": No such file or directory");
}
//Trying To Warn
fs::path CheckExist = p2 + "/" + p1;
if (exists(CheckExist))
{
std::cout << "The File Already Exist On The Given Path Replace Them [Y/N] ";
char ans;
std::cin >> ans;
if (ans != 'Y' || ans != 'y')
{
std::cout << "Aborted!";
return;
}
}
fs::copy(p1, p2, fs::copy_options::recursive);
}
//mkdir Used For Making Directories
void mkdir(std::string &s)
{
fs::create_directories(s);
}
//rm Used For Deleteing Files
void rm(std::string s)
{
std::error_code err;
//Handling The Case If Directory Doesn't Exsist
if (!fs::exists(s))
{
throw std::string("rm: cannot remove '" + s + "': No such file or directory");
}
if (fs::is_directory(s, err))
{
if (fs::exists(s))
{
throw std::string("rm: cannot remove '" + s + "': Is a directory");
}
}
fs::remove(s);
return;
}
//The “cd” Command Used For Navigating Over Directories
void cd(std::string &path)
{
//cd .. implementation - going to parent directory
if (path == "..")
{
fs::path Parent = fs::current_path().parent_path();
fs::current_path(Parent);
return;
}
//If The User Entered A Blank Path Or Just The "cd" command
else if (path == "")
{
fs::current_path(fs::current_path().root_directory());
return;
}
//If Path Doesn't Exist
else if (!fs::exists(path))
{
throw std::string("cd: " + path + " No such file or directory");
}
else
{
fs::current_path(path);
}
}
//The “ls” Command Is Used For Printing All The Files And Directories In The Cirrent Folder
void ls()
{
fs::path CurPath = fs::current_path();
//f_name will be used for storing paths and names
std::string f_name;
for (auto &Name : fs::directory_iterator(CurPath))
{
//If It's A File
std::error_code err;
if (fs::is_regular_file((Name).path(), err))
{
f_name = Name.path().filename();
color::color_green(f_name);
std::cout << " ";
}
//If It's A Folder
else
{
f_name = Name.path().filename();
color::color_blue(f_name);
std::cout << " ";
}
}
}
//mv move command
void mv(std::string From, std::string To, bool IsRename)
{
fs::path p1 = From, p2 = To;
//Checking If It's For Renaming
if (!IsRename)
{
fs::path CheckExist = To + "/" + From;
if (exists(CheckExist))
{
std::cout << "The File Already Exist On The Given Path Replace Them [Y/N] ";
char ans;
std::cin >> ans;
if (ans != 'Y' || ans != 'y')
{
std::cout << "Aborted!";
return;
}
}
}
fs::copy(From, To);
fs::remove(From);
}
void rmdir(std::string Path){
if(!fs::exists(Path)){
throw std::string("rmdir: failed to remove "+Path+": No such file or directory");
}
if(!fs::is_directory(Path)){
throw std::string("rmdir: failed to remove "+Path+": Not a directory");
}
fs::remove(Path);
}
//Related To File Information
std::streampos GetSize(std::string PathName){
std::streampos FullSize=0;
fs::path Path=PathName;
if(fs::is_directory(Path)){
for (auto& Name:fs::recursive_directory_iterator(Path)){
if(fs::is_regular_file(Name.path())){
std::ifstream Open(Name.path(),std::ios_base::binary);
std::streampos ThisSize=Open.tellg();
Open.seekg(0,std::ios::end);
FullSize+=ThisSize-Open.tellg();
Open.close();
}
}
return FullSize;
}
else{
std::ifstream Open(Path);
std::streampos ThisSize=Open.tellg();
Open.seekg(0,std::ios::end);
ThisSize=ThisSize-Open.tellg();
Open.close();
return ThisSize;
}
}
void PrintTime(std::string Path){
//Copied From Runebook.dev ;)
auto ftime=fs::last_write_time(Path);
std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime);
std::cout <<std::asctime(std::localtime(&cftime));
}
void GetInfo(std::string Path){
if(!fs::exists(Path)){
throw std::string("--info: "+Path+" No such file or directory");
}
std::streampos Size=GetSize(Path);
std::cout<<"SIZE : "<<Size<<std::endl;
std::cout<<"PATH : "<<Path<<std::endl;
std::cout<<"LAST MODIFIED : ";
PrintTime(Path);
if(fs::is_directory(Path)){
std::cout<<"TYPE : Directory";
}
else{
std::cout<<"TYPE : File";
}
}
void cat(std::string Path){
if(!fs::exists(Path)){
throw std::string("cat: "+Path+": No such file or directory");
}
else if(fs::is_directory(Path)){
throw std::string("cat: "+Path+": Is a directory");
}
std::string Temp;
std::ifstream Reader(Path);
while(getline(Reader,Temp)){
std::cout<<Temp<<std::endl;
}
}
void help(){
std::cout<<"•cd\n•ls\n•mkdir\n•rmdir\n•rm\n•pwd\n•echo\n•clear\n•cp\n•mv\n•rename\n•--info\n•cat";
SayPath();
}
//This Function Is Used For Determining The Type Of Command
void DetermineCommand(std::string &s)
{
std::stringstream Extractor(s);
std::string Type;
Extractor >> Type;
if (Type == "cd")
{
if (s.length() == 2 || s[3] == ' ')
{
std::string Empty = "";
cd(Empty);
SayPath();
return;
}
//I'm Reusing The Type Variable To Store The Path As The Next Would Be The Path
Extractor >> Type;
try
{
cd(Type);
SayPath();
}
catch (std::string Error)
{
std::cout << Error;
SayPath();
return;
}
}
else if (Type == "ls")
{
ls();
SayPath();
}
else if (Type == "mkdir")
{
std::string Path;
Extractor >> Path;
mkdir(Path);
SayPath();
}
else if (Type == "rm")
{
std::string Parms;
Extractor >> Parms;
try
{
rm(Parms);
std::cout << "\b";
}
catch (std::string Error)
{
std::cout << Error;
}
SayPath();
}
else if (Type == "pwd")
{
std::cout << fs::current_path();
SayPath();
}
else if (Type == "echo")
{
std::string s;
std::string a;
Extractor>>s;
while(Extractor>>a){
s+=a+' ';
}
if(s[0]=='"' && s[s.length()-1]=='"'){
s.erase(s.begin());
s.erase(s.end());
}
std::cout << s;
SayPath();
}
else if (Type == "clear")
{
system("clear");
SayPath();
}
else if (Type == "cp")
{
std::string p1, p2;
Extractor >> p1 >> p2;
try
{
cp(p1, p2);
}
catch (std::string Err)
{
std::cout << Err;
}
SayPath();
}
else if (Type == "mv")
{
std::string p1, p2;
Extractor >> p1 >> p2;
try{
mv(p1, p2, false);
}
catch(...){
std::cout<<"Some Error Occured\n";
}
std::cout<<'\b';
SayPath();
}
else if (Type == "rename")
{
std::string p1, p2;
Extractor >> p1 >> p2;
mv(p1, p2, true);
std::cout<<'\b';
SayPath();
}
else if(Type=="--info"){
try{
std::string Path;
Extractor>>Path;
GetInfo(Path);
//Flushing \n
std::cout<<'\b';
SayPath();
}
catch(std::string err){
std::cout<<err;
SayPath();
}
}
else if(Type == "cat"){
std::string FName;
Extractor>>FName;
try{
cat(FName);
}
catch(std::string err){
std::cout<<err<<std::endl;
}
std::cout<<'\b';
SayPath();
}
else if(Type=="--help"){
help();
}
else if(Type == "rmdir"){
std::string Path;
Extractor>>Path;
rmdir(Path);
SayPath();
}
else{
std::cout<<"No such command found use --help to get a list of all command";
SayPath();
}
}
</code></pre>
<p>I have uploaded it on GitHub Too - <a href="https://github.com/DevAgent-A/Linux-Commands" rel="nofollow noreferrer">Repo</a>.</p>
<p>Note - I didn't implement all options of every command; for example, I just implemented <code>ls</code> but not <code>ls -a</code> etc.</p>
<p>Thanks for checking this out!!</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> std::cout << "\\033[32m" << path << "\\033[0m";\n</code></pre>\n</blockquote>\n<p>Please don't do that - not all the world is an ANSI terminal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T08:12:57.090",
"Id": "515487",
"Score": "0",
"body": "Actually i wrote more than half of the code and this came in my made so in order to use curses I'll have to rewrite it completely that's the reason i did that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T08:28:20.007",
"Id": "515488",
"Score": "0",
"body": "Eh? Just produce ordinary text output and it will work everywhere. If you don't implement `-a`, there's really no reason to force `--color`..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T07:57:46.650",
"Id": "261232",
"ParentId": "261228",
"Score": "2"
}
},
{
"body": "<h1>Command Loop</h1>\n<pre><code> std::cout << "$ ";\n //Main Loop\n while (true)\n {\n std::string cmnd;\n getline(std::cin, cmnd);\n #if DEBUG\n if (cmnd == "exit")\n return 0;\n #endif\n</code></pre>\n<p>A few comments here:</p>\n<ul>\n<li>You output a prompt, <code>"$ "</code>, but you only do that once. The other times, that is done in <code>SayPath()</code>. This isn't very transparent.</li>\n<li>If you pipe input from a file into this program, <code>getline()</code> will fail after reading the last line. You never check for success. Use <code>while (getline(cin, cmnd))</code> instead.</li>\n<li>Why does this behave differently when <code>DEBUG</code> is defined?</li>\n<li>Consider not using a command loop, because it doesn't lend itself to reuse in scripts, only for interactive use. Instead, take the (single!) command via commandline. You would then call your program like <code>./youprog ls /etc</code> to list the contents of the <code>/etc</code> dir.</li>\n</ul>\n<h1>Colours</h1>\n<p>You have code that creates coloured output, which you run conditionally using <code>#ifdef __LINUX</code>. However, that's the wrong approach! For one, you assume that when it runs on Linux, you want coloured output. However, what if you pipe the output of this program into another program. In that case, you'd have the escape sequences in your output which the other program receives as input.</p>\n<p>Another thing is that this is not a Linux specialty! Instead, it depends on the shell and the terminal. Since you can't know either when compiling the program, you need a solution that makes the decision at runtime instead.</p>\n<h1>Class vs. Namespace</h1>\n<p>You have a class <code>color</code>, but you never create an instance of that class. Instead, you use the static functions that this class provides. This should be a simple namespace instead.</p>\n<h1>Header vs. Implementation</h1>\n<p>Your approach to move some code to a separate file is not uncommon. However, you typically have a header file (typically *.h or *.hpp) and an implementation file (typically *.cpp). The header file also has so-called include guards. This is a wide topic but keep your eyes open, you will find lots of examples for it.</p>\n<h1>Else After Return</h1>\n<p>You have lots of code like</p>\n<pre><code>if (...)\n{\n ...\n return;\n}\nelse\n{\n ...\n}\n</code></pre>\n<p>You can save yourself the <code>else</code> completely. As a rule of thumb, use if-else only when the paths converge after the else branch. If you return, the path ends and it will never converge with the other path. Another example is your big command dispatch function, where you have this structure:</p>\n<pre><code>if (Type == "cd")\n{\n ...\n}\nelse if (Type == "ls")\n{\n ...\n}\nelse if (Type == "rm")\n{\n ...\n}\nelse if (Type == "cd")\n{\n ...\n}\nelse\n{\n throw ...\n}\n</code></pre>\n<p>Here, the paths actually converge, but the converging part is empty. So, if you want to understand what the "cd" does, you will have to scroll down past all other handlers and you will find that nothing else happens! This would be immediately obvious if you returned instead.</p>\n<p>Note that not just <code>return</code> ends the path you can take through a function. Other such flow control statements are</p>\n<ul>\n<li><code>throw</code></li>\n<li><code>break</code></li>\n<li><code>continue</code></li>\n<li><code>goto</code></li>\n<li><code>exit()</code></li>\n<li><code>abort()</code></li>\n<li><code>longjmp()</code></li>\n</ul>\n<p>These all make any <code>else</code> branch redundant.</p>\n<h1>Throwing Strings</h1>\n<p>Firstly, apart from one or two places, you approach of using exceptions to signal errors looks good. Don't waste your time with returncodes unless you have a good reason. However, don't throw <code>std::string</code> instances. Instead, use <code>std::runtime_error</code>, which takes a string in its constructor. Of course, you have to adjust any <code>catch</code> clauses as well accordingly:</p>\n<pre><code> try\n {\n ...\n }\n catch (std::exception const& e)\n {\n std::cout << e.what() << std::endl;\n ...\n }\n</code></pre>\n<p>Note that you catch the exception using a const reference (not by value) to the baseclass. If you have specific exceptions for specific errors that need different processing, you can use those specific types instead. For output of the error message, you retrieve the error string using <code>e.what()</code>.</p>\n<h1>Linebreaks</h1>\n<p>The default output stream <code>std::cout</code> is buffered. If you write to it using <code>cout << "foo"</code>, nothing is actually displayed! Only when the output is flushed, it is actually printed (e.g. on screen). It is implicitly flushed when you retrieve input from <code>std::cin</code>, so this might not be immediately obvious. Another way to flush the stream is to write <code>std::endl</code> to it, which also finishes the line. I'd suggest you use that by default.</p>\n<h1>Parameter Passing</h1>\n<p>You have a bunch of handler functions. Some of them take a string as parameter, but you're not consistent there. In some cases, you pass the string by value (<code>std::string p</code>), in other cases, you pass a reference (<code>std::string& p</code>). The third variant of passing a reference to a constant (<code>std::string const& p</code>) is unused. The differences should be explained in your C++ tutorial.</p>\n<p>One thing which might not be explained in every tutorial: When you pass a reference to a non-constant, the implicitation is that the function is supposed to modify the value. Don't use this if the function doesn't modify the value. Also, if you use that, document in what way the value is modified. This is important for others to use the function correctly, but it also helps you structure your thoughts when writing it, like every documentation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:29:07.167",
"Id": "515521",
"Score": "1",
"body": "Thanks man for taking your time I'll keep those things in mind :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:34:43.543",
"Id": "515522",
"Score": "1",
"body": "If you refactor to perform a single operation per process, then `cd` won't be any use (because the process with the changed working directory exits before you can do anything with it). `cd` really is a shell operation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T15:10:23.817",
"Id": "515530",
"Score": "0",
"body": "`cd` is one such thing. Also, shell variables and environment variables. In e.g. Bash, call `command -V cd` to find out where something comes from. Another thing done by the shell instead of the called program is globbing. If you type `ls *` in the shell, the shell substitutes `*` with your directory content and then invokes `ls` with these arguments. Also handled by the shell are quotes (`\"` and `'`)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:17:40.690",
"Id": "261243",
"ParentId": "261228",
"Score": "6"
}
},
{
"body": "<p>When you use conditional code make it functional so the code you read looks normal. i.e. don't mess up the code by putting conditional compilation in. Use conditional compilation to generate alternative versions of appropriate functions.</p>\n<pre><code> static void color_green(std::string path)\n {\n#ifndef __LINUX\n //color code for green\n std::cout << "\\033[32m" << path << "\\033[0m";\n#else\n //Green\n system("Color 02");\n std::cout << path;\n //White\n system("Color 07");\n#endif\n }\n static void color_blue(std::string path)\n {\n//color code for blue\n#ifndef __LINUX\n std::cout << "\\033[34m" << path << "\\033[0m";\n#else\n //Blue\n system("Color 01");\n std::cout << path << " ";\n //White\n system("Color 07");\n#endif\n }\n</code></pre>\n<p>This is hard to read because each block contains a lot of conditional code.</p>\n<pre><code>#ifndef __LINUX\n static const_expr char COLOR_GREEN[] = "32m";\n static const_expr char COLOR_WHITE[] = "0";\n // Now when you get comments from "Toby" you only have\n // fix the code in a single place and not modify the code\n // in multiple locations through the code base.\n void set_ink(char const[] color) {std::cout << "\\033[" << color << "m";}\n#else\n static const_expr char COLOR_GREEN = "color 3";\n static const_expr char COLOR_GREEN = "color 7";\n void set_ink(char const[] color) {system(color);}\n#endif\n\nstatic void color_green(std::string path)\n{\n set_ink(COLOR_GREEN);\n std::cout << path;\n set_ink(COLOR_WHITE);\n}\nstatic void color_blue(std::string path)\n{\n set_ink(COLOR_BLUE);\n std::cout << path;\n set_ink(COLOR_WHITE);\n}\n</code></pre>\n<p>Now do it properly to make sure the color is reset even with exceptions:</p>\n<pre><code>class Ink\n{\n Ink(char const[] color) {\n set_ink(color);\n }\n ~Ink() {\n set_ink(COLOR_WHITE);\n }\n};\nstatic void color_green(std::string path)\n{\n Ink ink(COLOR_GREEN);\n std::cout << path;\n}\nstatic void color_blue(std::string path)\n{\n Ink ink(COLOR_BLUE);\n std::cout << path;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T23:03:00.527",
"Id": "515658",
"Score": "0",
"body": "Thanks I'll try writing neat and readable code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T22:42:31.143",
"Id": "261313",
"ParentId": "261228",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T04:35:59.947",
"Id": "261228",
"Score": "1",
"Tags": [
"c++",
"beginner",
"file-system"
],
"Title": "Basic Linux filesystem commands"
}
|
261228
|
<p>I have a data frame that has several columns, one of which contains html objects (containing tables). I want a column of table arrays.</p>
<p>My problem is that this piece of code takes a long time to run. Is there any way I can optimize this? I tried list comprehension, which doesn't significantly improve run time.</p>
<p>Some suggested that I restructure the logic. Any suggestions how?</p>
<pre><code> df = htmldf
countries = dict(countries_for_language('en'))
countrylist = list(countries.values())
arrayoftableswithcountry = []
arrayofhtmltables = []
for idx, row in df.iterrows():
#print("We are now at row ", idx+1, "of", len(df),".")
inner_html = tostring(row['html'])
soup = bs(inner_html,'lxml')
tableswithcountry = []
outputr = []
for idex,item in enumerate(soup.select('table')):
#print("Extracting", idex+1, "of", len(soup.select('table')),".")
table = soup.select('table')[idex]
rows = table.find_all('tr')
output = []
outputrows = []
for row in rows:
cols = row.find_all('td')
cols = [item.text.strip() for item in cols]
output.append([item for item in cols if item])
if methodsname == 'revseg_geo':
if '$' in str(output):
for country in countrylist:
if country in str(output):
tableswithcountry.append(output)
outputr.append(table)
arrayoftableswithcountry.append(tableswithcountry)
arrayofhtmltables.append(outputr)
df['arrayoftables'] = arrayoftableswithcountry
df['arrayofhtmltables'] = arrayofhtmltables
print('Made array of tables.')
df.drop(columns=['html'])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T06:34:21.183",
"Id": "515478",
"Score": "4",
"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-05-26T21:09:04.837",
"Id": "515564",
"Score": "0",
"body": "Please show an example of the data you're processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T21:14:46.337",
"Id": "515565",
"Score": "0",
"body": "Your question as posted is borderline off-topic. (For our \"unclear what you're asking\" reason.) Questions on Code Review must contain a description (in English) of what your code is doing. I wanted to edit your title to resolve BCdotWEB's comment, however you've not provided me with the information to do so."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T06:00:06.063",
"Id": "261230",
"Score": "0",
"Tags": [
"python",
"performance",
"html",
"pandas",
"iteration"
],
"Title": "How do I make my html object-to-table array script run faster? (Pandas)"
}
|
261230
|
<p>Looking a way to reduce the below code to get comma separated values from the list of arrays
By using ECMA or plain old vanilla JS. How should we achieve this?</p>
<p><strong>Actual Array Data:</strong></p>
<pre><code>[{
ansBook: "046H",
ansPersonId: "2044000102",
bookNbr: "046H",
dns: "0",
examCode: "20717010",
examShortTitle: "QA-ATAG-Director of Applications",
nar: "0",
personId: "2044000102",
pull: "0",
wn: "0",
corrCd: 1
},
{
ansBook: "046I",
ansPersonId: "2044000102",
bookNbr: "046I",
dns: "0",
examCode: "20721010",
examShortTitle: "QA-ATAG-Plans Examinier",
nar: "0",
personId: "2044000102",
pull: "0",
wn: "0",
corrCd: 1
}
];
</code></pre>
<p><strong>Expected Result:</strong></p>
<pre><code>{
"PersonIds": "2044000102, 2044000102",
"BookLetCodes": "046H, 046I",
"ExamNumbers": "20717010, 20721010",
"ExamTitles": "QA-ATAG-Director of Applications, QA-ATAG-Plans Examinier"
}
</code></pre>
<p>As I am getting the expected result. But I need to reduce and improvise the performance performed on it..</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>let seriesDataSet = [{
ansBook: "046H",
ansPersonId: "2044000102",
bookNbr: "046H",
dns: "0",
examCode: "20717010",
examShortTitle: "QA-ATAG-Director of Applications",
nar: "0",
personId: "2044000102",
pull: "0",
wn: "0",
corrCd: 1
},
{
ansBook: "046I",
ansPersonId: "2044000102",
bookNbr: "046I",
dns: "0",
examCode: "20721010",
examShortTitle: "QA-ATAG-Plans Examinier",
nar: "0",
personId: "2044000102",
pull: "0",
wn: "0",
corrCd: 1
}
];
let auditingInfo = {};
auditingInfo = (seriesDataSet).filter(w => (w.dns == '0' && w.pull == '0') && w.corrCd == 1)
.map(e => ({
PersonIds: e.personId,
BookLetCodes: e.ansBook,
ExamNumbers: e.examCode,
ExamTitles: e.examShortTitle
}))
console.log(auditingInfo)
let auditingDetails = {
PersonIds: auditingInfo.map(x => x.PersonIds).join(', '),
BookLetCodes: auditingInfo.map(x => x.BookLetCodes).join(', '),
ExamNumbers: auditingInfo.map(x => x.ExamNumbers).join(', '),
ExamTitles: auditingInfo.map(x => x.ExamTitles).join(', ')
}
console.log('______________________________________________')
console.log('Expected Result:')
console.log(auditingDetails)</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
max-height: 100% !important;
top: 0;
}</code></pre>
</div>
</div>
</p>
<p><strong>OR</strong></p>
<pre><code>let ScoringApprove: Array<number> = [];
ScoringApprove = new List<SeriesReportsDataset>(this.tempSeriesDataSet)
.Where(w => (w.dns == '0' && w.pull == '0') && w.corrCd == 1)
.Select(s => s.scannedResponseID).ToArray();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T06:45:37.323",
"Id": "515931",
"Score": "0",
"body": "Consider one single `reduce` instead of the 5 `map` calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T13:56:51.353",
"Id": "515970",
"Score": "0",
"body": "@Blindman67, Anything you could add apart from these answers. I saw your post went deleted, before I could read... I am supporting larger audience bringing up their own approaches whether it's right or wrong"
}
] |
[
{
"body": "<p>Honestly, structure-wise, your code seems pretty good. I've just got a handful of minor code-cleanup suggestions:</p>\n<ul>\n<li>Use <code>===</code> instead of <code>==</code>, <code>==</code> does some magical type coercion, and can create unexpected results.</li>\n<li>You've got some unenesary parentheses here: <code>auditingInfo = (seriesDataSet).filter(w => (w.dns === '0' && w.pull === '0') && w.corrCd === 1)</code> - you can take out the parentheses around <code>(seriesDataSet)</code> and <code>(w.dns === '0' && w.pull === '0')</code></li>\n<li>What's the reason for initializing <code>auditingInfo</code> to <code>{}</code>, then immediately setting it to a different value? Just do it in one go. For example:</li>\n</ul>\n<pre><code>// instead of\nlet auditingInfo = {};\nauditingInfo = ...\n// just do\nlet auditingInfo = ...;\n</code></pre>\n<p>You're using a <code>.map()</code> to extract and rename values from your data set, then the next thing you do is some <code>.map()</code>s again to extract out specific values. Why not take out the first <code>.map()</code> entirely?</p>\n<p>After applying these suggestions, you'll be left with this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let auditingInfo = seriesDataSet.filter(w => w.dns === "0" && w.pull === "0" && w.corrCd === 1);\n\nlet auditingDetails = {\n PersonIds: auditingInfo.map(x => x.personId).join(", "),\n BookLetCodes: auditingInfo.map(x => x.ansBook).join(", "),\n ExamNumbers: auditingInfo.map(x => x.examCode).join(", "),\n ExamTitles: auditingInfo.map(x => x.examShortTitle).join(", ")\n};\n</code></pre>\n<p>Finally, you had also asked about improving performance. You're not doing anything slow algorithm-wise, so there's not a whole lot of performance gains you can squeeze out of this. I wouldn't bother unless you <em>really</em> need it, in which case, you can try out different micro-optimizations and run performance tests on your target platforms to see which optimizations help the most. (some optimizations could speed things up on one platform and slow them down on another). Any of these types of optimizations will reduce the readability of your code, so only apply them if they make a significant enough impact.</p>\n<p>A couple of optimization ideas you can try out that may help out, or may make things worse:</p>\n<ul>\n<li>Use a single for loop instead of using .filter() and multiple .map() calls.</li>\n<li>Instead of array.join(), gradually build the string.</li>\n<li>If you have a large dataset, see if you can gradually consume a stream of data, instead of loading the whole thing into memory, all at once.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T04:15:29.600",
"Id": "261320",
"ParentId": "261231",
"Score": "1"
}
},
{
"body": "<p>To reduce the array loops you could use one single <code>reduce</code> function instead of several <code>map</code> calls. The example below uses <a href=\"https://www.typescriptlang.org/docs/handbook/variable-declarations.html#object-destructuring\" rel=\"nofollow noreferrer\">Object destructuring</a> within the <code>reduce</code> callback, addition assignments and the ternary condition operator.</p>\n<pre><code>const auditingDetails2 = seriesDataSet\n .filter(w => w.dns === '0' && w.pull === '0' && w.corrCd === 1)\n .reduce((acc, {personId, ansBook, examCode, examShortTitle}) => {\n acc.PersonIds += acc.PersonIds ? `, ${personId}` : personId\n acc.BookLetCodes += acc.BookLetCodes ? `, ${ansBook}` : ansBook\n acc.ExamNumbers += acc.ExamNumbers ? `, ${examCode}` : examCode\n acc.ExamTitles += acc.ExamTitles ? `, ${examShortTitle}` : examShortTitle \n return acc;\n }, {PersonIds: '', BookLetCodes: '', ExamNumbers: '', ExamTitles: ''} )\n</code></pre>\n<p>Since the callback contains some redundancy, we can introduce a helper function, <code>appendValue</code>.</p>\n<pre><code>function appendValue(obj: Record<string, string>, property: string, value: string) {\n obj[property] += obj[property] ? `, ${value}` : value\n}\n\nconst auditingDetails3 = seriesDataSet\n .filter(w => w.dns === '0' && w.pull === '0' && w.corrCd === 1)\n .reduce((acc, { personId, ansBook, examCode, examShortTitle }) => {\n appendValue(acc, 'PersonIds', personId)\n appendValue(acc, 'BookLetCodes', ansBook)\n appendValue(acc, 'ExamNumbers', examCode)\n appendValue(acc, 'ExamTitles', examShortTitle)\n return acc;\n }, { PersonIds: '', BookLetCodes: '', ExamNumbers: '', ExamTitles: '' })\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T07:55:18.337",
"Id": "261452",
"ParentId": "261231",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T07:16:43.427",
"Id": "261231",
"Score": "0",
"Tags": [
"javascript",
"array",
"typescript",
"join"
],
"Title": "Simplifying the array of objects with comma separated values"
}
|
261231
|
<p>Here is a code I experimented with recently:</p>
<pre class="lang-hs prettyprint-override"><code>let br = [0]:[n:(concat $ take n br) | n <- [1..]] in concat br
</code></pre>
<p>This code produces the <a href="https://oeis.org/A007814" rel="nofollow noreferrer">binary rule</a> <code>0 1 0 2 0 1 0 3 ...</code></p>
<p>Here is the idea of how it works:</p>
<ul>
<li><p>create a list starting with [0]</p>
</li>
<li><p>each step, concatenate all the current elements in the list, put the next number at the begining and add at the end.</p>
</li>
</ul>
<pre><code>[[0] ...]
[[0], [1, 0] ...]
[[0], [1, 0], [2, 0, 1, 0]...]
[[0], [1, 0], [2, 0, 1, 0], [3, 0, 1, 0, 2, 0, 1, 0] ...]
...
</code></pre>
<p>My question now is: is there a shorter/smarter one-liner to get this infinite lazy binary-rule ?</p>
<h2>Edit:</h2>
<p>I found another way to do the same thing:</p>
<pre class="lang-hs prettyprint-override"><code>let f n = if n==0 then [0] else n:([0..n-1] >>= f) in [0..]>>= f
</code></pre>
<p>The extra question would be: wich one of the 2 version is more readable for an haskell programmer, and why ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T16:24:20.213",
"Id": "515624",
"Score": "0",
"body": "Re Edit 2: The python version should be `yield 0 \\n for b...: yield b+1 \\n yield 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T16:42:38.520",
"Id": "515628",
"Score": "0",
"body": "Re Edit 2: The haskell version: I confirm that it hangs, and I'm trying to figure out why. This works: `import Data.List (intersperse) \\n binaryRule = 0 : intersperse 0 ((+1) <$> binaryRule)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T16:47:13.730",
"Id": "515632",
"Score": "0",
"body": "Ok, I figured out the problem, but I think we've pissed off the mods enough with _troubleshooting_ on _Code Review_, and I want my fake internet points in the right place anyway :) . Open a thread on Stack Overflow and share the link here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T17:16:30.340",
"Id": "515638",
"Score": "0",
"body": "To be clear chameleon questions - questions where what is being asked changes over time - are not allowed on Code Review. If you'd like advice on _working_ code (which your Edit 2 is not) you can ask a follow-up question. Alternately you could take @ShapeOfMatter up on the offer to ask on Stack Overflow. Please do not undo my rollback or 'the mods' _may_ become pissed off ;)"
}
] |
[
{
"body": "<p>I would use an <code>interleave</code> helper:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>interleave :: [a] -> [a] -> [a]\ninterleave (x:xs) ys = x : interleave ys xs\n\nbinaryRule :: [Integer]\nbinaryRule = interleave [0,0..] (map (+ 1) binaryRule)\n</code></pre>\n<p>Or golfed: <code>let(a:b)#c=a:c#b;a=[0,0..]#map(+1)a in a</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T14:10:50.447",
"Id": "261242",
"ParentId": "261233",
"Score": "2"
}
},
{
"body": "<p>I'm a little out of practice with haskell, but I'm quite fond of it. I want to address your "extra" question first.</p>\n<blockquote>\n<p>wich one of the 2 version is more readable for an haskell programmer, and why ? [sic]</p>\n</blockquote>\n<p>Haskell programmers aren't a special magic kind of people. They tend to take the benefits of brevity more seriously than folks in love with python, but I think they'll still agree that golfed code is not readable/smarter/better. The basic rule of good (code) writing applies: <em>Write what you mean</em>.</p>\n<blockquote>\n<ul>\n<li>create a list starting with [0]</li>\n<li>each step, concatenate all the current elements in the list, put the next number at the beginning and add at the end.</li>\n</ul>\n</blockquote>\n<p>Neither of your proposed solutions is <em>obviously</em> doing that, although it only takes a minute to see that your first solution <em>is</em> doing that.</p>\n<p><a href=\"https://codereview.stackexchange.com/a/261242/200133\">Noughtmare's</a> suggestion is based on a different construction of the OEIS sequence, although the OEIS presents this as an <em>invariant</em>, not a construction, so the reader still needs to think the matter through (a little).</p>\n<p>Give-or-take efficiency, write code that <em>obviously</em> does what you're saying it does. Unfortunately, the OEIS entry doesn't describe the sequence in terms that translate directly to a lazy infinite list declaration, so you need to provide some documentation of your own.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>-- https://oeis.org/A007814\nrulerSequence :: [Integer]\nrulerSequence = concat halfs\n where seed = [0, 1]\n -- The sequence is built by concatenating with itself\n -- and incrementing the last index. `nextHalf` builds\n -- the right-hand-side of each such concatenation.\n nextHalf priorHalfs = let priors = concat priorHalfs\n in (init priors) ++ [(last priors) + 1]\n halfs = seed:[nextHalf (take iteration halfs) | iteration <- [1..]]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T16:00:55.230",
"Id": "261248",
"ParentId": "261233",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "261248",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T08:01:35.480",
"Id": "261233",
"Score": "2",
"Tags": [
"haskell",
"lazy"
],
"Title": "How can I make a shorter binary rule in haskell?"
}
|
261233
|
<p>I would like to transform my <code>dataframe</code> into an array of fixed-sized chunks from each unique segment. Specifically, I would like to transform the <code>df</code> to a list of <code>m</code> arrays each sized <code>(1,100,4)</code>. So at last, I would have an <code>(m,1,100,4)</code> array.</p>
<p>Since I require that the <code>chunks</code> be of fixed-size <code>(1,100,4)</code>, and on splitting it is unlikely that each segment produce perfectly this size, the last rows of a segment are usually less, so should be zero-padded.</p>
<p>For this, I start be creating an array of this size, and populate it with all zeros. Then gradually fill in these values with <code>df</code> rows. This way, what's left at end of a particular segment is therefore zero-padded.</p>
<p>To do this, I use the function:</p>
<pre><code>def transform(dataframe, chunk_size):
grouped = dataframe.groupby('id')
# initialize accumulators
X, y = np.zeros([0, 1, chunk_size, 4]), np.zeros([0,])
# loop over each group (df[df.id==1] and df[df.id==2])
for _, group in grouped:
inputs = group.loc[:, 'A':'D'].values
label = group.loc[:, 'class'].values[0]
# calculate number of splits
N = (len(inputs)-1) // chunk_size
if N > 0:
inputs = np.array_split(
inputs, [chunk_size + (chunk_size*i) for i in range(N)])
else:
inputs = [inputs]
# loop over splits
for inpt in inputs:
inpt = np.pad(
inpt, [(0, chunk_size-len(inpt)),(0, 0)],
mode='constant')
# add each inputs split to accumulators
X = np.concatenate([X, inpt[np.newaxis, np.newaxis]], axis=0)
y = np.concatenate([y, label[np.newaxis]], axis=0)
return X, y
</code></pre>
<p>This function does produce the intended <code>ndarray</code>. However, it is extremely slow. My <code>df</code> has over 21M rows, so the function takes more than 5hours to complete, this is crazy!</p>
<p>I am looking for a way to refactor this function for optimization.</p>
<p>Steps to reproduce the issue:</p>
<p>Generate a random large <code>df</code>:</p>
<pre><code>import pandas as pd
import numpy as np
import time
df = pd.DataFrame(np.random.randn(3_000_000,4), columns=list('ABCD'))
df['class'] = np.random.randint(0, 5, df.shape[0])
df.shape
(3000000, 5)
df['id'] = df.index // 650 +1
df.head()
A B C D class id
0 -0.696659 -0.724940 0.494385 1.469749 2 1
1 -0.440400 0.744680 -0.684663 -1.962713 4 1
2 -1.207888 -1.003556 -0.926677 -1.455632 3 1
3 1.575943 -0.453352 -0.106494 0.351674 3 1
4 0.888164 0.675754 0.254067 -0.454150 3 1
</code></pre>
<p>Transform <code>df</code> to the required <code>ndarray</code> per unique segment.</p>
<pre><code>start = time.time()
X,y = transform(df, 100)
end = time.time()
print(f"Execution time: {(end - start) / 60}")
Execution time: 6.169370893637339
</code></pre>
<p>For a 5M rows <code>df</code> this function takes more than 6mins to complete. In my case (>21M rows), it takes hours!!!</p>
<p>How do it write the function to improve speed? Maybe the notion of creating the accumulator is completely wrong.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T13:04:01.710",
"Id": "515516",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T13:30:30.377",
"Id": "515518",
"Score": "0",
"body": "@Mast this has been noted, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T09:41:29.983",
"Id": "515682",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T09:55:17.103",
"Id": "515683",
"Score": "0",
"body": "The question title still states your concerns about the code rather **the task accomplished by the code**. Please [edit] it to summarise the purpose - you might want to re-read [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-05-28T11:52:04.373",
"Id": "515688",
"Score": "0",
"body": "@TobySpeight My edit was because the answer slightly changes how the function works (return value)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T12:00:33.870",
"Id": "515689",
"Score": "1",
"body": "I again have rolled back your last edit. The reason is the same. Please stop changing the code in question which means adding code based on an answer as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T13:05:58.360",
"Id": "515695",
"Score": "0",
"body": "You still need to [edit] to state the purpose of the code (I'm guessing \"takes ages to complete\" is _not_ one of the requirements? And \"dataframe transformation\" is more a mechanism than a real-world mission)."
}
] |
[
{
"body": "<p>Your code appears to be quadratic in the number of groups. Each call to <code>np.concatenate()</code> allocates enough memory to hold the new array and then copies the data. The first group is copied the first time through the loop. Then the first and second groups on the second time. Then the first to third groups on the third time, etc.</p>\n<p>To speed this up, keep a list of the groups and then call <code>np.concatenate()</code> just once on the list of groups.</p>\n<p>Another observation is that the code splits a group into chunks only to reassemble them in the loop. The only differences are the group is padded to be a multiple of group_size and the shape of the array has changed. But those can be addressed without splitting and concatenating each group.</p>\n<p>The Pandas documentation says to use <code>DataFrame.to_numpy()</code> method rather than <code>.value</code>.</p>\n<p>Revised code:</p>\n<pre><code>def transform2(dataframe, chunk_size):\n \n parts_to_concat = []\n labels = []\n\n\n for _, id_group in dataframe.groupby('id'):\n\n group = id_group.loc[:, 'A':'D'].to_numpy()\n labels.append(id_group.loc[:, 'class'].iat[0])\n\n parts_to_concat.append(group)\n \n # add a zero-filled part to the list of parts to \n # effectively pad the group to be a multiple of chunk_size\n pad = chunk_size - len(group) % chunk_size\n if pad < chunk_size:\n parts_to_concat.append(np.zeros((pad, 4)))\n \n # reassemble the data and change it's shape to match \n # the output of the original code\n transformed_data = np.concatenate(parts_to_concat)\n transformed_data = .reshape(-1, 1, chunk_size, 4)\n\n labels = np.array(labels)\n \n return transformed_data, labels\n</code></pre>\n<p>On my laptop, the original code takes almost 12 minutes to run the sample dataframe. The new code takes less than one second--about a 700x speedup.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T17:58:11.847",
"Id": "515642",
"Score": "0",
"body": "Thank you, but this changes the required array shape from `(m, 1, 100, 4)` to `(m, 4)`. For example, in the question, `X[0].shape` is `(1, 100, 4)` (this is how it is required), in this answer, `X[0].shape` gives `(4,)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T19:15:38.903",
"Id": "515649",
"Score": "0",
"body": "@super_ask, Didn't return the reshaped array. Fixed. It now returns an array with shape (m, 1, chunk_size, 4)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T08:55:48.613",
"Id": "515681",
"Score": "0",
"body": "Great! This is really fast. One thing I just noticed is the function in your answer doesn't return chunk `labels`. I modified your answer but I am not able to get the correct labels, as described in the questio edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T14:21:19.650",
"Id": "515702",
"Score": "1",
"body": "@super_ask, I didn't do the labels because it didn't make sense--they were just random values in the sample data. Code added to duplicate what the original code was doing."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T14:51:14.733",
"Id": "261294",
"ParentId": "261239",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "261294",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T12:46:29.807",
"Id": "261239",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"array",
"numpy"
],
"Title": "Dataframe transformation to numpy ndarray takes ages to complete"
}
|
261239
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.