body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<pre><code>LENGTHS_TO_CENSOR = {4, 5}
CENSOR_CHAR = '*'
CENSOR_EXT = "-censored"
def replace_inner(word, char):
if len(word) < 3:
return word
return word[0] + char * len(word[1:-1]) + word[-1]
def create_censor_file(filename):
output_file = open(filename + CENSOR_EXT, "w+")
with open(filename) as source:
for line in source:
idx = 0
while idx < len(line):
# If the character isn't a letter, write it to the output file.
if not line[idx].isalpha():
output_file.write(line[idx])
idx += 1
else:
word = ""
while idx < len(line) and line[idx].isalpha():
word += line[idx]
idx += 1
if len(word) in LENGTHS_TO_CENSOR:
word = replace_inner(word, CENSOR_CHAR)
output_file.write(word)
output_file.close()
def main():
filename = input("File to be censored: ")
create_censor_file(filename)
if __name__ == "__main__":
main()
</code></pre>
<p>I was assigned a task to censor words that are length <code>n</code> in a file. This file can potentially contain punctuation and numbers.</p>
<p>I originally tackled the problem by splitting the line into a list of words (using <code>.split(' ')</code>) and checking the length to determine if the program should censor the word or not. This failed for inputs such as:</p>
<blockquote>
<p>does not work.for.this.input</p>
<p>or.this</p>
</blockquote>
<p>The output file must be exactly like the input but with words of length in <code>LENGTHS_TO_CENSOR</code> censored with <code>CENSOR_CHAR</code>.</p>
<p>I decided to abandon trying to make it Pythonic and ended up with this result. I want to know if there is a way to take this method and make it more Pythonic.</p>
| [] | [
{
"body": "<ol>\n<li><code>create_censor_file</code> should really be called <code>create_censored_file</code>.</li>\n<li>I'd rename <code>source</code> to <code>source_file</code> for consistency and clarity.</li>\n<li>You should use <code>with</code> for both files.</li>\n<li>Why not use just <code>w</code> i... | {
"AcceptedAnswerId": "203710",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T20:15:45.113",
"Id": "203700",
"Score": "3",
"Tags": [
"python",
"file",
"formatting"
],
"Title": "Censor the middle of words of length N from a text file"
} | 203700 |
<p>Historical Friday: this was my first useful C program, written around 1993-1994 (with only occasional access to a compiler and runtime environment). It's also my first non-trivial Postscript, too.</p>
<h2>Background</h2>
<p>I was a student at the time I wrote this, and unable to transport a turntable to and from my accommodation, so I recorded my favourite albums to cassette tape. But I was already showing a perfectionist streak - hand-written box labels aren't neat enough, and the interactive graphics editors were never going to give consistent results (additionally, I'm too lazy for all the manual work required). So I needed some automation.</p>
<h2>Input format</h2>
<p>Input is line-oriented, in ISO 8859-1 encoding. The first line specifies the artist and the second the album name. Then there's a blank line, then a line for each track. The track listing is terminated by a line with a single <code>.</code> (to end a side) or with <code>..</code> (to end the tape). We start again with artist and title, but they may be omitted if the same as the previous side.</p>
<p>Here's an example input file (this one is particularly difficult due to the long titles):</p>
<pre class="lang-none prettyprint-override"><code>Altan
Island Angel
Tommy Peoples; The Windmill; Fintan McManus's
Bríd Óg Ní Mháille
Fermanagh Highland; Donegal Highland; John Doherty's; King George IV
An Mhaighdean Mhara
Andy de Jarlis; Ingenish; Mrs. McGhee
Humours of Andytown; Kylebrach Rambler; The Gladstone
Dúlamán
Mazurka
The Jug of Punch
Glory Reel; The Heathery Cruach
An Cailín Gaelach
Drumnagarry Strathspey; Pirrie Wirrie; Big John's Reel
Aingeal an Oileáin (Island Angel)
.
Harvest Storm
Pretty Peg; New Ships a-Sailing; The Bird's Nest; The Man From Bundoran
Dónal agus Mórag
King of the Pipers
Séamus O'Shanahan's; Walking In Liffey Street
Mo Choill
The Snowy Path
Drowsy Maggie; Rakish Paddy; Harvest Storm
'Sí do Mhaimeo I
McFarley's; Mill na Maidi
Rosses Highlands
A Nobleman's Wedding
Bog an Lochain; Margaree Reel; The Humours of Westport
Dublin's Flowery Vale
</code></pre>
<h2>Output</h2>
<p>Output is a Postscript file ready for printing, with 2 to 4 labels fitting on an A4 sheet. In particular, the artist and album are consistently arranged on the spine and rear slip (with a shared name spanning both halves; otherwise divided in two). If all titles could fit on the front of the box, then we have a simple layout, taking ¼ page; otherwise we get a extended label that takes ½ page and is folded with the excess on the inside of the box.</p>
<p>Because we have a mix of ½-page and ¼-page outputs, I maintain 2 pages worth of "slots" into which these can be placed, so as to get the best use of paper.</p>
<p>I avoid widowed text by squashing to fit if it's only slightly over height of one side. Word wrapping is evaded by shrinking to fit (even if it makes for unreadable text).</p>
<p><a href="https://i.stack.imgur.com/ah8Pp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ah8Pp.png" alt="sample output"></a></p>
<h2>The code</h2>
<p>Although I'm very tempted to edit it, this is the code I wrote a quarter-century or so since (so the standard is C89) with no cleanup at all.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
char *progname;
static const char * const ps_preamble[10]; /*defined after main() */
typedef struct strlist
{
char *str;
struct strlist *next;
} Strlist;
typedef struct tape
{
int wide; /* true if continuation pages */
char *artist[2]; /* 2nd may be NULL for 1-sided tape */
char *title[2]; /* ditto */
Strlist *songs[2];
int nsongs[2];
} Tape;
Strlist *followlist(Strlist *s, int n)
{
for (; s && n; s=s->next, n--)
;
return s;
}
char *getline(FILE * const fp)
{
/* Returns one line of text (any length) from fp, stripping leading
and trailing whitespace. Returned pointer is to a region of
malloc'ed memory, and must be free'd after use.
Returns NUll on failure, with errno set. */
char *line=NULL;
const int bufinc=20;
size_t size=0;
int len=0;
int c;
while (isspace(c=fgetc(fp)) && (c!='\n'))
;
if (c==EOF) return NULL;
ungetc (c, fp);
do {
size += bufinc;
line = (char *)realloc(line, size);
if (!line) return NULL;
if (!fgets(line+len, size-len, fp))
{ free(line); return NULL; }
len = strlen(line);
} while (line[len-1] != '\n');
{
register char *pc=line+len;
while (isspace(*--pc))
;
*(++pc) = '\0';
}
/* line = realloc(line, pc+1-line); */
return line;
}
Tape *new_tape(void)
{
int i;
Tape *tp=(Tape *)malloc(sizeof(Tape));
if (!tp) return NULL;
for (i=0; i<2; i++) {
tp->artist[i]=tp->title[i]=NULL;
tp->songs[i]=NULL;
tp->nsongs[i]=0;
}
tp->wide=0;
return tp;
}
Tape *get_tape(FILE* fp)
{
int i;
Strlist *s;
Tape *tp=new_tape();
/**/fprintf(stderr, "get_tape() entered\n");
if (!tp || feof(fp)) return NULL;
for (i=0; i<2; i++) {
tp->artist[i]=getline(fp);
if (!tp->artist[i]) return tp;
if (!*tp->artist[i])
{ free (tp->artist[i]); tp->artist[i]=NULL; }
tp->title[i]=getline(fp);
if (!tp->title[i]) return tp;
if (!*tp->title[i])
{ free (tp->title[i]); tp->title[i]=NULL; }
getline(fp); /* Throw away noise-reduction data */
tp->songs[i]=(Strlist *)malloc(sizeof(Strlist));
for (s=tp->songs[i]; s; s=s->next) {
s->str=getline(fp);
if (!s->str) { /* EOF */
s->next=NULL;
return tp;
}
if (!strcmp(s->str, "..")) {
free(s->str);
s->str=NULL;
s->next=NULL;
return tp;
}
if (!strcmp(s->str, ".")) {
free(s->str);
s->str=NULL;
break;
}
s->next=(Strlist *)malloc(sizeof(Strlist));
/* Error checking done at beginning of next pass */
tp->nsongs[i]++;
}
s->next=NULL;
}
/**/fprintf(stderr, "get_tape() exit\n");
return tp;
}
void print_preamble(void)
{
char const * const *p;
char timestr[100];
time_t ct;
struct tm *ctime;
time(&ct);
ctime = localtime(&ct);
strftime(timestr, sizeof timestr,
"%%%%CreationDate: %A %-d %B %Y, %H:%M:%S %Z", ctime);
puts("%!PS-Adobe-1.0\n"
"%%Creator: Toby's Fantastic Cassette Labeller (c) 1994 90tms\n"
"%%Title: Cassette Labels");
puts(timestr);
/* fflush(stdout); */
/* system("date '+%%%%CreationDate: %a %d %b %Y, %H:%M:%S %Z'"); */
/* puts(); */
for (p = ps_preamble; *p; p++) {
puts(*p);
fflush(stdout);
}
return;
}
void print_literal(register const char *cp)
{
putchar('(');
while (*cp)
switch (*cp) {
case '(':
case ')':
putchar ('\\');
putchar (*cp++);
break;
case '\\':
putchar (*cp++);
putchar (*cp?*cp++:'\\'); /* quote if terminal */
break;
default:
if (*cp & 0x80)
printf("\\%03o", (unsigned int)(unsigned char)*cp++);
else
putchar(*cp++);
}
putchar(')');
putchar(' ');
return;
}
void print_title(const char *s)
{
print_literal(s);
puts(" 174 leftfituline");
return;
}
void print_songs(Strlist *s, int n, float step)
{
printf("%.2f [", step);
for (;putchar('\n'), s && s->str && n>0; s=s->next, n--)
print_literal(s->str);
puts("] dosongs");
return;
}
void output_page(Tape *pages[4])
{
static int pageno=0;
int i;
Tape *tp;
/**/fprintf(stderr, "output_page() entered\n");
pageno++;
printf("%%%%Page: %d %d\n", pageno, pageno);
puts("20 100 translate");
for (i=0; i<=3; i++) {
tp=pages[i];
if (!tp) continue;
puts("gsave");
switch (i) {
case 0:
puts("0 288 translate");
break;
case 1:
/*puts("258 288 translate");*/
puts("552 576 translate");
puts("180 rotate");
break;
case 3:
/*puts("258 0 translate");*/
puts("552 288 translate");
puts("180 rotate");
break;
default:
break;
}
if (tp->nsongs[1] == 0) /* no side 2 */
if (tp->nsongs[0]<=22) { /* no squashing */
int x=(22-tp->nsongs[0])*4;
printf("96 %d moveto\n", 276-x);
print_title(tp->title[0]);
print_songs(tp->songs[0], tp->nsongs[0], 12);
} else if (tp->nsongs[0] <= 25) { /* squeeze */
puts("96 276 moveto");
print_title(tp->title[0]);
print_songs(tp->songs[0], tp->nsongs[0], 264.0/tp->nsongs[0]);
} else if (tp->nsongs[0] <= 44) { /* wide */
puts("96 276 moveto");
print_title(tp->title[0]);
print_songs(tp->songs[0], 22, 12);
puts("282 264 moveto");
print_songs(followlist(tp->songs[0],22), tp->nsongs[0]-22, 12);
} else { /* too big */
fprintf(stderr, "%s: too many songs in %s\n",
progname, tp->title[0]);
puts("grestore");
continue;
}
else /* 2 sides */
if (tp->nsongs[0]+tp->nsongs[1]<=20) {
int x=(20-tp->nsongs[0]-tp->nsongs[1])*3;
printf("96 %d moveto\n", 276-x);
print_title(tp->title[0]);
print_songs(tp->songs[0], tp->nsongs[0], 12);
printf("0 -%d rmoveto\n", x+12);
print_title(tp->title[1]);
print_songs(tp->songs[1], tp->nsongs[1], 12);
} else if (tp->nsongs[0]<=22 && tp->nsongs[1]<=22) {
int x=(22-tp->nsongs[0])*4;
printf("96 %d moveto\n", 276-x);
print_title(tp->title[0]);
print_songs(tp->songs[0], tp->nsongs[0], 12);
x=(22-tp->nsongs[1])*4;
printf("282 %d moveto\n", 276-x);
print_title(tp->title[1]);
print_songs(tp->songs[1], tp->nsongs[1], 12);
} else {
fprintf(stderr, "%s: tape too long - %s/%s\n",
progname, tp->title[0], tp->title[1]);
puts("grestore");
continue;
}
print_literal(tp->artist[0]);
if (tp->artist[1]) {
print_literal(tp->artist[1]);
puts("false doartist");
} else
puts("true doartist");
print_literal(tp->title[0]);
if (tp->title[1]) {
print_literal(tp->title[1]);
puts("false dotitle");
} else
puts("true dotitle");
if (tp->wide)
puts("true doframe");
else
puts("false doframe");
puts("grestore");
}
puts("showpage\n");
fflush(stdout);
return;
}
void clear_page(Tape *pages[4])
{
int i,j;
Strlist *s, *t;
Tape *tp;
for (i=0; i<4; i++) {
tp=pages[i];
for (j=0; j<2; j++) {
free(tp->artist[j]);
free(tp->title[j]);
for (s=t=tp->songs[j]; s; t=s) {
s=s->next;
free(t->str);
free(t);
}
}
free(tp);
pages[i]=NULL;
}
}
void print_postamble(Tape *pages[8])
{
if (pages[0])
output_page(pages);
if (pages[4])
output_page(pages+4);
fflush(stdout);
}
void add_tape(Tape *pages[8], Tape *tp)
{
int i,sum;
if (tp->artist[0] && tp->artist[1] && !strcmp(tp->artist[0], tp->artist[1])) {
free(tp->artist[1]);
tp->artist[1]=NULL;
}
tp->wide = (tp->nsongs[1]
?(tp->nsongs[0]+tp->nsongs[1]>20)
:(tp->nsongs[0]>=26));
if (tp->wide) {
for (i=0; i<=7; i+=2)
if (!pages[i])
break; /*success*/
} else /* !tp->wide */
for (i=0; i<=7; i++) {
if (!pages[i])
break; /*success*/
if (pages[i]->wide)
i++;
}
if (i>7)
fprintf(stderr, "%s: page space error ## CAN'T HAPPEN ##\n", progname);
pages[i]=tp;
/* Now see if any ready to print */
pages += i&~3;
sum=0;
for (i=0; i<=3; i++)
if (pages[i])
sum += 1+pages[i]->wide;
if (sum>4)
fprintf(stderr, "%s: page double-booking error ## CAN'T HAPPEN ##\n",
progname);
if (sum<4)
return; /* OK */
/* else oputput & reset page */
output_page(pages);
clear_page(pages);
return;
}
int main(int argc, char **argv)
{
static Tape *pages[8] = {0,0,0,0,0,0,0,0};
int i;
progname=argv[0];
print_preamble();
for (i=1; i<argc; i++) {
Tape *tp;
FILE *fp=fopen(argv[i], "r");
if (!fp) {
fprintf(stderr, "%s: couldn't open %s: %s\n",
progname, argv[i], strerror(errno));
continue;
}
while ((tp=get_tape(fp))) /* ASSIGNMENT */
add_tape(pages, tp);
fclose(fp);
}
print_postamble(pages);
return 0;
}
static char const * const ps_preamble[] =
{
"%%PageOrder: Ascend\n"
"%%BoundingBox: 37 99 579 675\n"
"%%DocumentFonts: Helvetica Helvetica-Bold\n"
"%%EndComments\n"
"%%BeginProcSet: cassette\n",
/* ISO 8859-1 stuff */
"% ISOLatin1Encoding stolen from ps_init.ps in GhostScript 2.6.1.4:\n"
"% If the ISOLatin1Encoding vector isn't known, define it.\n"
"/ISOLatin1Encoding where { pop } {\n"
"% Define the ISO Latin-1 encoding vector.\n"
"% The first half is the same as the standard encoding,\n"
"% except for minus instead of hyphen at code 055.\n"
"/ISOLatin1Encoding\n"
"StandardEncoding 0 45 getinterval aload pop\n"
" /minus\n"
"StandardEncoding 46 82 getinterval aload pop\n"
"%*** NOTE: the following are missing in the Adobe documentation,\n"
"%*** but appear in the displayed table:\n"
"%*** macron at 0225, dieresis at 0230, cedilla at 0233, space at 0240.\n"
"% \\20x\n"
" /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
" /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
" /dotlessi /grave /acute /circumflex /tilde /macron /breve /dotaccent\n"
" /dieresis /.notdef /ring /cedilla /.notdef /hungarumlaut /ogonek /caron\n"
"% \\24x\n"
" /space /exclamdown /cent /sterling\n"
" /currency /yen /brokenbar /section\n"
" /dieresis /copyright /ordfeminine /guillemotleft\n"
" /logicalnot /hyphen /registered /macron\n"
" /degree /plusminus /twosuperior /threesuperior\n"
" /acute /mu /paragraph /periodcentered\n"
" /cedilla /onesuperior /ordmasculine /guillemotright\n"
" /onequarter /onehalf /threequarters /questiondown\n"
"% \\30x\n"
" /Agrave /Aacute /Acircumflex /Atilde\n"
" /Adieresis /Aring /AE /Ccedilla\n"
" /Egrave /Eacute /Ecircumflex /Edieresis\n"
" /Igrave /Iacute /Icircumflex /Idieresis\n"
" /Eth /Ntilde /Ograve /Oacute\n"
" /Ocircumflex /Otilde /Odieresis /multiply\n"
" /Oslash /Ugrave /Uacute /Ucircumflex\n"
" /Udieresis /Yacute /Thorn /germandbls\n"
"% \\34x\n"
" /agrave /aacute /acircumflex /atilde\n"
" /adieresis /aring /ae /ccedilla\n"
" /egrave /eacute /ecircumflex /edieresis\n"
" /igrave /iacute /icircumflex /idieresis\n"
" /eth /ntilde /ograve /oacute\n"
" /ocircumflex /otilde /odieresis /divide\n"
" /oslash /ugrave /uacute /ucircumflex\n"
" /udieresis /yacute /thorn /ydieresis\n"
"256 packedarray def\n"
"} ifelse\n"
"\n"
"/reencodeFontISO { %def\n"
" dup\n"
" length 5 add dict % Make a new font (a new dict\n"
" % the same size as the old\n"
" % one) with room for our new\n"
" % symbols.\n"
"\n"
" begin % Make the new font the\n"
" % current dictionary.\n"
"\n"
"\n"
" { 1 index /FID ne\n"
" { def } { pop pop } ifelse\n"
" } forall % Copy each of the symbols\n"
" % from the old dictionary to\n"
" % the new except for the font\n"
" % ID.\n"
"\n"
" /Encoding ISOLatin1Encoding def % Override the encoding with\n"
" % the ISOLatin1 encoding.\n"
"\n"
" % Use the font's bounding box to determine the ascent, descent,\n"
" % and overall height; don't forget that these values have to be\n"
" % transformed using the font's matrix.\n"
" FontBBox\n"
" FontMatrix transform /Ascent exch def pop\n"
" FontMatrix transform /Descent exch def pop\n"
" /FontHeight Ascent Descent sub def\n"
"\n"
" % Define these in case they're not in the FontInfo (also, here\n"
" % they're easier to get to.\n"
" /UnderlinePosition 1 def\n"
" /UnderlineThickness 1 def\n"
"\n"
" % Get the underline position and thickness if they're defined.\n"
" currentdict /FontInfo known {\n"
" FontInfo\n"
"\n"
" dup /UnderlinePosition known {\n"
" dup /UnderlinePosition get\n"
" 0 exch FontMatrix transform exch pop\n"
" /UnderlinePosition exch def\n"
" } if\n"
"\n"
" dup /UnderlineThickness known {\n"
" /UnderlineThickness get\n"
" 0 exch FontMatrix transform exch pop\n"
" /UnderlineThickness exch def\n"
" } if\n"
"\n"
" } if\n"
"\n"
" currentdict % Leave the new font on the\n"
" % stack\n"
"\n"
" end % Stop using the font as the\n"
" % current dictionary.\n"
"\n"
" definefont % Put the font into the font\n"
" % dictionary\n"
"\n"
" pop % Discard the returned font.\n"
"} bind def\n"
"\n"
/* end of ISO 8859-1 stuff */
"\n"
"/ISO-Helvetica /Helvetica findfont reencodeFontISO\n"
"/ISO-Helvetica findfont 12 scalefont /fn12 exch def\n"
"/ISO-Helvetica-Bold /Helvetica-Bold findfont reencodeFontISO \n"
"/ISO-Helvetica-Bold findfont dup\n"
"12 scalefont /fb12 exch def\n"
"24 scalefont /fb24 exch def\n"
"\n"
"/centerfit {\n" /* str max */
" gsave\n"
" exch dup stringwidth pop dup\n" /* max str wid wid */
" 3 index\n"
" exch 5 -1 roll\n" /* str wid max wid max */
" le {\n"
" pop 2 div neg 0 rmoveto\n"
" }{\n"
" dup 2 div neg 0 rmoveto\n"
" exch div 1 scale\n"
" } ifelse\n"
" show\n"
" grestore\n"
"} bind def\n"
"\n"
"/doartist {\n"
" gsave\n"
" 58 288 translate -90 rotate\n"
" fb24 setfont\n"
" {\n"
" dup 144 12 moveto 276 centerfit\n"
" 144 -24 moveto 276 centerfit\n"
" }{\n"
" dup 216 12 moveto 132 centerfit\n"
" 216 -24 moveto 132 centerfit \n"
" dup 72 12 moveto 132 centerfit\n"
" 72 -24 moveto 132 centerfit\n"
" } ifelse\n"
" grestore\n"
"} bind def\n"
"\n"
"/dotitle {\n"
" gsave\n"
" 56 288 translate -90 rotate\n"
" fn12 setfont\n"
" {\n"
" dup 144 0 moveto 276 centerfit\n"
" 144 -36 moveto 276 centerfit\n"
" }{\n"
" dup 216 0 moveto 132 centerfit\n"
" 216 -36 moveto 132 centerfit \n"
" dup 72 0 moveto 132 centerfit\n"
" 72 -36 moveto 132 centerfit\n"
" } ifelse\n"
" grestore\n"
"} bind def\n"
"\n"
"/leftfit {\n" /* str max */
" gsave\n"
" 1 index stringwidth pop exch\n" /* str wid max */
" 1 index 1 index\n" /* str wid max wid max */
" le {\n"
" pop pop\n"
" }{\n"
" exch div 1 scale\n"
" } ifelse\n"
" show\n"
" grestore\n"
"} bind def\n"
"\n"
"/leftfituline {\n"
" gsave\n"
" fb12 setfont\n"
" 1 index stringwidth pop\n"
" 1 index 1 index\n"
" le {\n"
" div\n"
" 1 scale\n"
" }{\n"
" pop pop\n"
" } ifelse\n"
" dup stringwidth pop\n"
" gsave\n"
" 0 rlineto stroke\n"
" grestore\n"
" show\n"
" grestore\n"
" 0 -12 rmoveto\n"
"} bind def\n"
"\n"
"/dosongs {\n"
" /linestep 3 -1 roll neg def\n"
" fn12 setfont\n"
" {\n"
" currentpoint 3 -1 roll\n"
" 174 leftfit\n"
" moveto\n"
" 0 linestep rmoveto\n"
" } forall\n"
"} def\n"
"\n"
"/doframe {\n"
" 54 0 moveto 0 288 rlineto stroke\n"
" 90 0 moveto 0 288 rlineto stroke\n"
" 18 0 moveto\n"
" 18 288 lineto 276 288 lineto 276 0 lineto\n"
" closepath stroke\n"
" {\n"
" 276 0 moveto 190 0 rlineto 0 288 rlineto\n"
" -190 0 rlineto stroke\n"
" } if\n"
"} bind def\n\n"
"\n"
"%%EndProcSet\n"
"\n"
"statusdict begin\n"
" false setduplexmode\n"
"end\n"
"%%EndProlog\n"
"%%BeginSetup\n"
"%%PaperSize: A4\n"
"%%EndSetup\n"
"\n",
NULL
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T01:51:59.933",
"Id": "393232",
"Score": "0",
"body": "Nice to see PostScript content!"
}
] | [
{
"body": "<p>Some things I would do differently now:</p>\n\n<ul>\n<li>Don't name a function <code>getline()</code>.</li>\n<li>Don't cast the return value from <code>malloc()</code> and <code>realloc()</code>.</li>\n<li>Prefer expressions rather than types in <code>malloc(sizeof ...)</code>.</li>\n<li>Don't bot... | {
"AcceptedAnswerId": "203750",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T20:36:30.373",
"Id": "203701",
"Score": "7",
"Tags": [
"c",
"c89",
"postscript"
],
"Title": "Label my cassette boxes"
} | 203701 |
<p>Currently, I am using the below code to make JSON data from list of objects.</p>
<pre><code>public IActionResult getWardsFromVDC(long vdc_id)
{
try
{
List<Ward> wards = wardRepo.getByVdcId(vdc_id).ToList();
List<Dictionary<string, string>> values = new List<Dictionary<string, string>>();
foreach (var ward in wards)
{
Dictionary<string, string> value = new Dictionary<string, string>();
value["ward_id"] = ward.ward_id.ToString();
value["ward_name"] = ward.ward_name;
values.Add(value);
}
Dictionary<string, object> data = new Dictionary<string, object>();
data["data"] = values;
var json = JsonConvert.SerializeObject(data);
return Json(json);
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
</code></pre>
<blockquote>
<pre><code>List<Ward> wards = wardRepo.getByVdcId(vdc_id).ToList();
</code></pre>
</blockquote>
<p>is getting list of <strong>Ward</strong> class from database. Then a loop is used to put all the values in <strong>List of Dictionaries</strong> . </p>
<blockquote>
<pre><code> Dictionary<string, object> data = new Dictionary<string, object>();
data["data"] = values;
var json = JsonConvert.SerializeObject(data);
</code></pre>
</blockquote>
<p>is putting all those values in <strong>"data"</strong> key in another <strong>dictionary</strong> and then value is <strong>serialized</strong> and returned as <strong>JSON</strong></p>
<p>The JSON data formed is :</p>
<pre><code>{
"data": [
{
"ward_id": "132",
"ward_name": "1"
},
{
"ward_id": "133",
"ward_name": "2"
},
{
"ward_id": "134",
"ward_name": "3"
},
{
"ward_id": "135",
"ward_name": "4"
},
{
"ward_id": "136",
"ward_name": "5"
},
{
"ward_id": "137",
"ward_name": "6"
},
{
"ward_id": "138",
"ward_name": "7"
},
{
"ward_id": "139",
"ward_name": "8"
},
{
"ward_id": "140",
"ward_name": "9"
},
{
"ward_id": "141",
"ward_name": "10"
},
{
"ward_id": "142",
"ward_name": "11"
},
{
"ward_id": "143",
"ward_name": "12"
}
]
}
</code></pre>
<p>To build even a simple data , I am creating <strong>dictionary</strong> and <strong>list of dictionaries</strong> and again adding <strong>data</strong> key . </p>
<p>Is there any simple way to build JSON in same format but in simplest way? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T07:46:04.287",
"Id": "392728",
"Score": "7",
"body": "To whoever is voting to close this question: please provide which context should be added for the question to be on-topic. I see a problem statement, working code and example out... | [
{
"body": "<p>Anonymous types are going to be your friend here. You don't need to have list or dictionary at all. </p>\n\n<p>First you don't need to call ToList() from your repository.</p>\n\n<p>Now we can just project out the properties you want like so</p>\n\n<pre><code>wards.Select(w => new\n{\n wa... | {
"AcceptedAnswerId": "203715",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T02:42:49.693",
"Id": "203713",
"Score": "1",
"Tags": [
"c#",
"json",
"asp.net-core"
],
"Title": "Extracting a list of objects from a repository as JSON"
} | 203713 |
<p>I wrote a method in java which fetches the data from third part database, store the results in our database and then acknowledged them by updating their tuples. I want you people to review my code, because it contains multiple try and catch and suggest me the best practice to improvise the same, Find the below java</p>
<pre><code>public boolean pickSalayData(String yearMonth, String regionId, String circleId, Userdetail loginUser) throws MyExceptionHandler {
String tableSuffix = yearMonth.substring(4, 6) + yearMonth.substring(0, 4);
log.info("Pick Salary Data From ERP " + DateUtility.dateToStringDDMMMYYYY(new Date()));
List<SalaryDetailReport> detailReports = hRMSPickSalaryDataDAO.findAll(yearMonth, regionId, circleId);
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus trstatus = transactionManager.getTransaction(def);
try {
List<SalaryDetailReport> salaryDetailReport = null;
int countDetail = 0;
if (detailReports != null && detailReports.size() > 0) {
for (SalaryDetailReport salary : detailReports) {
try {
if (countDetail % COMMIT_COUNT == 0) {
if (salaryDetailReport != null) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
salaryDetailReport = new ArrayList<SalaryDetailReport>();
}
salaryDetailReport.add(salary);
countDetail++;
} catch (Exception e) {
log.error("Error on Save Salary Pay Head Details Data from ERP to Prayas .");
return false;
}
}
if (salaryDetailReport != null && salaryDetailReport.size() > 0) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
} else {
throw new MyExceptionHandler("No record for Save in Database from ERP.");
}
salaryDetailReportDAO.update(tableSuffix, regionId, circleId);
List<SalaryDetailReport> reports = salaryDetailReportDAO.findAll(tableSuffix, regionId, circleId);
if (reports != null && reports.size() > 0) {
for (SalaryDetailReport salaryDetail : reports) {
try {
SalaryDetail sd = new SalaryDetail();
sd.setDetailReport(salaryDetail);
salaryDetailDAO.save(sd, tableSuffix);
} catch (Exception e) {
log.error("Error occured", e);
e.printStackTrace();
throw new MyExceptionHandler(" Error :" + e.getMessage());
}
}
System.out.println("data found");
} else {
log.error("Salary Record Not Found.");
throw new MyExceptionHandler("No record Found.");
}
salaryDetailDAO.updateEarningDeduction(tableSuffix);
//salaryDetailDAO.updateEarningDeductionsInSDT();
transactionManager.commit(trstatus);
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Error Occured while updating XXMPCD_SALARY_DETAIL_TABLE : ", ex);
return false;
}
// // System.out.println("Completed =============================");
} catch (MyExceptionHandler ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Failed to Save Salary data :" + ex.getMessage());
return false;
} catch (Exception ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Error occured on Save Salary data.", ex);
return false;
}
}
</code></pre>
| [] | [
{
"body": "<h1>General</h1>\n\n<p>You misspelled <code>pickSalaryData</code>. That’s a poor start.</p>\n\n<p>I will bet a day’s pay that none of your <code>findAll</code> methods will ever return <code>null</code>. Assuming that’s the case, don’t check for <code>null</code>. It’s confusing and makes the code ha... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T06:30:11.600",
"Id": "203717",
"Score": "2",
"Tags": [
"java"
],
"Title": "Migration of Data from Shared database and acknowledged the same"
} | 203717 |
<p>I'm implementing Curiously Recurring Template Pattern(CRTP) in Java as follows.</p>
<p>The Interface:</p>
<pre><code>/**
* Reason for the generic Value<T extends Value>
* Value<IntValue> x; // legal, IntValue implements Value interface so allowed
* Value<Integer> x; // illegal, does not implement Value interface
*/
@SuppressWarnings("rawtypes")
public interface Value<T extends Value> {
T deepCopy();
}
</code></pre>
<p>Classes implementing it:</p>
<pre><code>public class IntValue implements Value<IntValue> {
Integer value;
public IntValue(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
@Override
public IntValue deepCopy() {
return new IntValue(value);
}
}
/**
* // Valid
* List<IntValue> ints = Arrays.asList(new IntValue(Integer.valueOf(5)));
* ArrayValue<IntValue> arr = new ArrayValue<>(ints);
*
* // Invalid
* List<Integer> ints = Arrays.asList(Integer.valueOf(5));
* ArrayValue<Integer> arr = new ArrayValue<>(ints);
*/
@SuppressWarnings("rawtypes")
public class ArrayValue<T extends Value> implements Value<ArrayValue<T>> {
List<T> values;
public ArrayValue() {
this(new ArrayList<>());
}
public ArrayValue(List<T> values) {
this.values = values;
}
@SuppressWarnings("unchecked")
@Override
public ArrayValue<T> deepCopy() {
List<? super Value> copyValues = new ArrayList<>();
values.forEach(value -> copyValues.add(value.deepCopy()));
return new ArrayValue<T>((List<T>) copyValues);
}
}
//Static Function using the interface
@SuppressWarnings("rawtypes")
public static Value sub(Value a, Value b)
{
if(a instanceof IntValue && b instanceof IntValue)
{
return new IntValue( ((IntValue)a).getValue() - ((IntValue)b).getValue());
}
else
{
throw new TypeMismatchException("Operation not supported");
}
return NullValue.NULL_VALUE;
}
</code></pre>
<p>However I have to suppress warnings multiple times throughout the implementation.</p>
<p>Are the uses of suppress annotation justified?</p>
| [] | [
{
"body": "<p>As far I can tell this doesn't generate any warnings:</p>\n\n<pre><code>class IntValue implements Value<IntValue> {\n\n Integer value;\n\n public IntValue(Integer value) {\n this.value = value;\n }\n\n public Integer getValue() {\n return value;\n }\n\n @Overr... | {
"AcceptedAnswerId": "203730",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T07:27:53.167",
"Id": "203718",
"Score": "3",
"Tags": [
"java",
"generics",
"polymorphism"
],
"Title": "Curiously Recurring Template Pattern (CRTP) implementation"
} | 203718 |
<p>I have a program that includes sending data to our backend servers upon completion.</p>
<p>Due to the occasional connection issue at either side I have coded into the main script a JSON dump as a backup in case we are unable to connect to the BE server.</p>
<p>The JSON file is simply a Key/Value mirror of the SQL database fields in the table in question.</p>
<p>I will run this program in the background which will periodically check the folder. It will open the JSON and insert / update any files that are in there and remove them if completed.</p>
<pre><code>from json import load
from time import sleep
from os.path import join
from os import remove
from glob import glob
from sql_tunnel_control import (
SqlTunnelConnect,
SSH_KEY,
sql_ip,
sql_hostname,
sql_username,
sql_password,
sql_main_database,
sql_port,
ssh_host,
ssh_port,
ssh_user,
ssh_password,
table
)
production = SqlTunnelConnect(
SSH_KEY,
None,
sql_hostname,
sql_username,
sql_password,
table,
sql_port,
ssh_host,
ssh_port,
ssh_user,
None,
)
def load_be_data(f):
""" Save data to json file and allow another program to iterate over that folder until all data is safely in the backend server"""
try:
with open(join(f), "r") as j:
return load(j)
except Exception as e:
print(e)
# pass
def get_files():
f = glob("backend_data/*.json")
return f
def send_to_be(f):
""" takes in a file and attempts to send to the server.. Returns False if it fails.. Deletes the file if it succeeds """
print(f)
if f["query_type"] == "insert":
create_new_component = """INSERT INTO components .... """
try:
production.run_query(create_new_component)
return True
except:
return False
elif f["query_type"] == "update":
update_component = """UPDATE components SET ..."""
try:
production.run_query(update_component)
return True
except:
return False
else:
return False # problem with query type
def persist_dump():
to_send = get_files()
while len(to_send) > 0:
for f in to_send:
r = send_to_be(load_be_data(f))
if r:
remove(f)
sleep(1)
else:
sleep(300) # 5 minutes rest.
# all files completed.. sleep for a bit.. then see whats what//
sleep(1800)
persist_dump()
persist_dump()
</code></pre>
| [] | [
{
"body": "<p><strong>load_be_data</strong> </p>\n\n<ol>\n<li>Parameter name is not very descriptive. I'd say that 'file_path' would be better.</li>\n<li>Assuming that there is some end user, it would be better to add some descriptive messages for different kinds of exceptions instead of printing the message. A... | {
"AcceptedAnswerId": "203783",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T09:27:15.287",
"Id": "203723",
"Score": "0",
"Tags": [
"python"
],
"Title": "JSON backup to backend server if connection issues"
} | 203723 |
<p>I want to make this faster, I'm not a great coder and just want to learn. This program reads paragraphs of common artists separated by commas. The user inputs the name of a desired artist and the program searches through the paragraphs to find all related artists and sorts them into order of most common to least common. The artist text file is very large 600kb of text so perhaps that's the reason it's slow.</p>
<pre><code>class ArtistSuggester:
fileName = "list_of_artists.txt"
arrayOfLists = []
artist = input("Enter Artist Name: ")
@classmethod
def make_array(cls):
# sets text to 2D-array
f = open(cls.fileName, 'r', encoding="utf8")
curr_par = f.read().split("\n")
for line in curr_par:
cls.arrayOfLists.append(line.split(","))
@classmethod
def get_locations(cls):
# searches array for given artist and returns array with areas where the artist was found
locations = []
for x in range(0, len(cls.arrayOfLists)):
for y in range(0, len(cls.arrayOfLists[x])):
if cls.arrayOfLists[x][y] == cls.artist:
locations.append(x)
return locations
@staticmethod
def search_array_for_artist(the_list, artist):
# searches given array for the given artist's name and returns the position
# if found nothing returns negative number to symbolize non-existence
pos = 0
for x in range(0, len(the_list)):
if the_list[x] == artist:
pos = x
break
else:
pos = -1
return pos
@classmethod
def ordered_suggestion_list(cls):
# makes the final suggestion list in correct order
# makes two arrays, one with the names and the other with the counts of each throughout the text file.
check = cls.get_locations()
final_list = cls.arrayOfLists[check[0]]
final_list.remove(cls.artist)
count = [1] * int(len(final_list))
for x in range(1, len(check)):
for y in range(0, len(cls.arrayOfLists[check[x]])):
if cls.arrayOfLists[check[x]][y] == cls.artist:
continue
elif cls.search_array_for_artist(final_list, cls.arrayOfLists[check[x]][y]) > 0:
count[cls.search_array_for_artist(final_list, cls.arrayOfLists[check[x]][y])] += 1
else:
final_list.append(cls.arrayOfLists[check[x]][y])
count.append(1)
# makes a dict based off the count and names list to combine values to the keys
combined_list = dict(zip(final_list, count))
new_list = []
for key, value in sorted(combined_list.items(), key=lambda x: x[1], reverse=True):
new_list.append(key)
print(new_list)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T11:01:13.393",
"Id": "392761",
"Score": "1",
"body": "Welcome to Code Review. What Python version are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T11:19:20.880",
"Id": "392764",
... | [
{
"body": "<h1>Does this really have to be a class?</h1>\n<p>You have alot of <code>classmethod</code>'s making me wonder if this really has to be a class.</p>\n<h1>Review</h1>\n<ul>\n<li><p>Change the datatype of <code>Artists</code></p>\n<p>You can change it to a <code>set</code> making the lookup a <code>O(0... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T10:31:43.213",
"Id": "203726",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Reads paragraphs of common artists separated by commas"
} | 203726 |
<p>The program I have been working on has been developed almost exclusively as "train-of-thought" style code. Things happen linearly (for the most part) thru the code. The goal of the program is to house Arabic language lessons, somewhat similar to how Duolingo works. Right now I have four questions hard coded in with pre-set "wrong" answers for each question. The questions always appear in the same order but the answers for each question are displayed in a random order. When the user is ready to select the answer they click on the image that represents the word they are being asked when then calls a function to check if the right answer has been selected. If the right answer has been selected then the buttons for the next questions are displayed but if a wrong answer is selected than the buttons for the next questions are hidden to force the user to find the right answer first. </p>
<p>The thing I would like help with the most, is moving my code into a class based structure. Eventually, I'd like my program to house 50 to 60 lessons and my current formatting would require thousands of lines of code - many of which would be just copies of this initial code. My understanding is that working with classes (in python) could help reduce the need for unnecessary code duplication but I am completely self taught and don't have a good understanding of how to move my existing program into a new format.</p>
<p>Down the line, I'd also like to make the order of questions asked to be randomized and to have randomized wrong answers (instead of the pre-set wrong answers I have currently) but I think this should come after I've migrated my code to a new coding style/format.</p>
<p>Of course I would appreciate any and all feedback as my goal is to not just make a language lesson app but to also learn good programming practices along the way. </p>
<p>Below is the bulk of my code which works - even if it is a bit clunky! </p>
<pre><code>def Part1():
def create_widgets_in_first_frame(): # Create the label for the frame
global score
score = 0 #Setting the initial score to zero.
print("Your score is: ", score)
global lives
lives = 3 #Setting the initial number of lives.
print("You have", lives, "lives")
current_frame=first_frame #Make the frame number generic so as to make copy/paste easier
##### These four lines of code below need to be updated for the MC questions. #####
Image1 = ImagePath + "girl,bint-بنت.png"
Image2 = ImagePath + "man,ragul-رجل.png"
Image3 = ImagePath + "woman,sit-ست.png"
word = "boy,walid-ولد.png"
##### These four lines of code properly break down the options into the right parts for the intended use. #####
wordTransliteration = word.rsplit("-",1)[0].rsplit(",",1)[1]
wordText = word.rsplit(".", 1)[0].rsplit("-", 1)[1]
EwordText = word.rsplit(",",1)[0]
wordImage = PhotoImage(file=(ImagePath + word))
##### Maine Question is written here. #####
L1 = Label(current_frame, text="What is '" + EwordText + "' in Arabic?",font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
##### Radiobutton files are converted to images. #####
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = wordImage
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text=wordText + " is pronounced " + "'"+wordTransliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def create_widgets_in_second_frame():
current_frame=second_frame #Make the frame number generic so as to make copy/paste easier
##### These four lines of code below need to be updated for the MC questions. #####
Image1 = ImagePath + "boy,walid-ولد.png"
Image2 = ImagePath + "man,ragul-رجل.png"
Image3 = ImagePath + "woman,sit-ست.png"
word = "girl,bint-بنت.png"
##### These four lines of code properly break down the options into the right parts for the intended use. #####
wordTransliteration = word.rsplit("-",1)[0].rsplit(",",1)[1]
wordText = word.rsplit(".", 1)[0].rsplit("-", 1)[1]
EwordText = word.rsplit(",",1)[0]
wordImage = PhotoImage(file=(ImagePath + word))
##### Maine Question is written here. #####
L1 = Label(current_frame, text="What is '" + EwordText + "' in Arabic?",font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
##### Radiobutton files are converted to images. #####
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = wordImage
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text=wordText + " is pronounced " + "'"+wordTransliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def create_widgets_in_third_frame():
current_frame=third_frame #Make the frame number generic so as to make copy/paste easier
##### These four lines of code below need to be updated for the MC questions. #####
Image1 = ImagePath + "boy,walid-ولد.png"
Image2 = ImagePath + "girl,bint-بنت.png"
Image3 = ImagePath + "man,ragul-رجل.png"
word = "woman,sit-ست.png"
##### These four lines of code properly break down the options into the right parts for the intended use. #####
wordTransliteration = word.rsplit("-",1)[0].rsplit(",",1)[1]
wordText = word.rsplit(".", 1)[0].rsplit("-", 1)[1]
EwordText = word.rsplit(",",1)[0]
wordImage = PhotoImage(file=(ImagePath + word))
##### Maine Question is written here. #####
L1 = Label(current_frame, text="What is '" + EwordText + "' in Arabic?",font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
##### Radiobutton files are converted to images. #####
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = wordImage
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text=wordText + " is pronounced " + "'"+wordTransliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def create_widgets_in_forth_frame():
current_frame=forth_frame #Make the frame number generic so as to make copy/paste easier
##### These four lines of code below need to be updated for the MC questions. #####
Image1 = ImagePath + "boy,walid-ولد.png"
Image2 = ImagePath + "girl,bint-بنت.png"
Image3 = ImagePath + "woman,sit-ست.png"
word = "man,ragul-رجل.png"
##### These four lines of code properly break down the options into the right parts for the intended use. #####
wordTransliteration = word.rsplit("-",1)[0].rsplit(",",1)[1]
wordText = word.rsplit(".", 1)[0].rsplit("-", 1)[1]
EwordText = word.rsplit(",",1)[0]
wordImage = PhotoImage(file=(ImagePath + word))
##### Maine Question is written here. #####
L1 = Label(current_frame, text="What is '" + EwordText + "' in Arabic?",font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
##### Radiobutton files are converted to images. #####
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = wordImage
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text=wordText + " is pronounced " + "'"+wordTransliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def Check_Answer():
global lives
global score
if str(var.get()) !="4":
Answer_frame.grid_forget()
check_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
lives -=1
Incorrect = Label(check_frame, text ="That's incorrect!\n Lives: " +str(lives) + "\n Score: " + str(score), font=("Helvetica", 35))
Incorrect.grid(row=0, rowspan=2, column=2, columnspan=2)
if str(var.get()) == "4":
score +=1
check_frame.grid_forget()
Answer_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
Correct = Label(Answer_frame, text = "That's right!\n Lives: " +str(lives)+ "\n Score: " + str(score), font=("Helvetica", 35))
Correct.grid(row=0, rowspan=2, column=2, columnspan=2)
first_frame_button = Button(Answer_frame, text = "Question 1", command = call_first_frame_on_top)
first_frame_button.grid(column=1, row=3)
second_frame_button = Button(Answer_frame, text = "Question 2", command = call_second_frame_on_top)
second_frame_button.grid(column=2, row=3)
third_frame_button = Button(Answer_frame, text = "Question 3", command = call_third_frame_on_top)
third_frame_button.grid(column=3, row=3)
forth_frame_button = Button(Answer_frame, text = "Question 4", command = call_forth_frame_on_top)
forth_frame_button.grid(column=4, row=3)
def call_first_frame_on_top():
second_frame.grid_forget()
third_frame.grid_forget()
forth_frame.grid_forget()
check_frame.grid_forget()
Answer_frame.grid_forget()
create_widgets_in_first_frame()
first_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_second_frame_on_top():
first_frame.grid_forget()
check_frame.grid_forget()
third_frame.grid_forget()
forth_frame.grid_forget()
create_widgets_in_second_frame()
Answer_frame.grid_forget()
print(lives)
if lives <= 0:
quit_program
second_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_third_frame_on_top():
check_frame.grid_forget()
first_frame.grid_forget()
second_frame.grid_forget()
forth_frame.grid_forget()
create_widgets_in_third_frame()
Answer_frame.grid_forget()
print(lives)
if lives <= 0:
quit_program
third_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_forth_frame_on_top():
check_frame.grid_forget()
first_frame.grid_forget()
second_frame.grid_forget()
third_frame.grid_forget()
create_widgets_in_forth_frame()
Answer_frame.grid_forget()
print(lives)
if lives <= 0:
quit_program
forth_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def quit_program():
root_window.destroy()
###############################
# Main program starts here :) #
###############################
screen = pygame.display.set_mode((1,1))
Lesson1_FilePath = Root_File_Name + "Lessons\\Lesson_1\\"
ImagePath = Lesson1_FilePath + "Images\\"
# Create the root GUI window.
root_window = Tk()
root_window.title("Lesson 1: Part 1")
# Define window size
window_width = 200
window_heigth = 100
# Create frames inside the root window to hold other GUI elements. All frames must be created in the main program, otherwise they are not accessible in functions.
first_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
first_frame['borderwidth'] = 2
first_frame['relief'] = 'sunken'
first_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
second_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
second_frame['borderwidth'] = 2
second_frame['relief'] = 'sunken'
second_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
third_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
third_frame['borderwidth'] = 2
third_frame['relief'] = 'sunken'
third_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
forth_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
forth_frame['borderwidth'] = 2
forth_frame['relief'] = 'sunken'
forth_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
check_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
check_frame['borderwidth'] = 2
check_frame['relief'] = 'sunken'
check_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
check_frame.grid_forget()
Answer_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
Answer_frame['borderwidth'] = 2
Answer_frame['relief'] = 'sunken'
Answer_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
Answer_frame.grid_forget()
# Create the firist frame
call_first_frame_on_top()
# Start tkinter event - loop
root_window.mainloop()
</code></pre>
| [] | [
{
"body": "<p>This got way out of hand for the comment section where it started, so let's make this an answer.</p>\n\n<p>You want classes. That's good, since it's going to solve a lot of your repetition problems. Your code has <em>a lot</em> of repetition problems. But classes shouldn't be your main priority at... | {
"AcceptedAnswerId": "203743",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T10:52:09.257",
"Id": "203728",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"tkinter",
"quiz"
],
"Title": "Arabic language lesson program"
} | 203728 |
<p>As per the instructions are given in <a href="https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/" rel="nofollow noreferrer">MaxCounters-Codility</a>, </p>
<blockquote>
<p>You are given <code>N</code> counters, initially set to 0, and you have two possible operations on them:</p>
<ul>
<li><p><code>increase(X)</code> − counter <code>X</code> is increased by 1,</p></li>
<li><p><code>max counter</code> − all counters are set to the maximum value of any counter.</p></li>
</ul>
<p>A non-empty array <code>A</code> of <code>M</code> integers is given. This array represents consecutive operations:</p>
<p>if <code>A[K] = X</code>, such that 1 ≤ <code>X</code> ≤ <code>N</code>, then operation <code>K</code> is <code>increase(X)</code>,
if <code>A[K] = N + 1</code> then operation <code>K</code> is <code>max counter</code>.</p>
</blockquote>
<p>I have written this code</p>
<pre><code>public int[] maxCount(int[]A,int N) {
int[] I = new int[N];
for (int i = 0; i < A.length; i++) {
try {
I[A[i] - 1]++;
} catch (Exception e) {
Arrays.sort(I);
Arrays.fill(I, I[I.length - 1]);
}
}
return I;
}
</code></pre>
<p>It gives correct answers for all test cases. Any Idea to do this with time complexity O(N). Its currently on O(N*M).</p>
| [] | [
{
"body": "<p>Lets start with the time complexity of your current algorithm:</p>\n\n<p><code>for (int i = 0; i < A.length; i++)</code> has a time complexity of <code>O(M)</code> (Length of array 'A' is 'M')<br>\n<code>Arrays.sort(I)</code> has a time complexity of <code>O(N*log(N))</code><sup><a href=\"https... | {
"AcceptedAnswerId": "203738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T10:52:55.710",
"Id": "203729",
"Score": "4",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded",
"complexity"
],
"Title": "Time complexity of Max counters"
} | 203729 |
<p>Needed a simple CSV file that had headers and no nesting of data to consume in Tableau. The JSON file I was consuming had nested dictionaries and lists (which sometimes had in themselves nested lists/dictionaries).</p>
<p>The output is a pipe delimited format (because free text fields have comments in that mess things up) with nested fields having both the original dictionary key plus any lower keys as the headers.</p>
<pre><code># -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 12:22:02 2018
@author: redim_learning
"""
import sys
import time
class parse_json():
# this class handles parsing json data, once it's been read in as a string using the json library
def __init__(self):
return None
#this writes out dictionaries within the main json dictonary
def write_dict(self, sub_dict, dict_name, f, str_dict):
try:
str_dict = str_dict + ('"%s"' % (str(dict_name))) #commar?!
except:
print ('key not passed correctly', str(dict_name))
try:
for second_key, second_value in sub_dict.items():
if type(second_value) == dict:
print ('dictionary within dictionary')
print( second_key)
write_dict(item[key],second_key,f,str_dict)
str_value = str(second_value)
#clean up characters
if '\n' in second_key or '\r' in str_value:
str_value = (str_value).replace('\n','').replace('\r','').replace(chr(34),chr(39))
str_dict = str_dict + (', "%s"' % str_value)
return str_dict[:len(str_dict)]
except:
print('dict write out did not work\n' , str_dict )
print('item[key] is ', sub_dict)
#print('second key:%s, second value:%s' %(second_key, second_value))
#this function manages to parse a list that is stored within the original json dictionary
def write_list(self, item, key, f, list_str):
# don't write a new line, that will be done later
#write first item in the list in current row
for list_value in item[key]:
if type(list_value) ==str:
list_str = list_str +(list_value.replace('\n','').replace('\r','').replace(chr(34),chr(39)) + ", ")
elif type(list_value) ==dict:
#sys.stdout.write("\nkey: %s, type(item): %s" % (key, type(item)))
#print('\nlist_value is :' + list_value)
sys.stdout.flush()
sys.stdout.flush()
sub_dict = list_value
list_str = list_str + write_dict(sub_dict,dict_name, f, list_str)
return list_str[:len(list_str)-2]
#this is needed to know when to add a line feed to the total string
def find_last_field(self, item):
#loop through all fields and return last header value
for header,value in item.items():
last_key = header
#print (header)
return last_key
#parses headers
def write_headers(self, item,last_header):
header_list = ''
object_list = ''
for h,v in item.items():
if type(v) ==dict:
for sub_header in v.items():
if type(sub_header) == tuple:
object_list = object_list + '"' + h + '_' + sub_header[0]+ '",'
else:
object_list = object_list + '"' + sub_header + '",'
elif type(v) ==list:
for rec in v:
object_list = object_list + '"' + h + "',"
else:
header_list = str(header_list) + '"' + h+ '",'
# return the full header string, but exclude the last commar
return header_list + object_list[:len(object_list)-1]
def parse_json_file(self, data, f, page):
full_str = ''
last_header = ''
for item in data:
try:
sys.stdout.write("\rPage %i, record %s of %i records" %(page+1, str(item['id']), len(data))) #Writes out progress for user
sys.stdout.flush()
except TypeError:
sys.stdout.flush()
sys.stdout.write("\rprogress is progressing ")
sys.stdout.flush()
sys.stdout.flush()
#when you're only looking at one record
if type((item))==str:
item = data
dict_str = ''
list_str = ''
item_str = ''
if last_header == '' and page == 0:
#determine the last header so you know when to write the line return
last_header = find_last_field (item)
#write out a the headers in the first row
f.write(write_headers(item, last_header) + "\n")
for key, value in item.items():
#print (item_str )
#print (key,value, type(value))
#try:
if type(item[key]) == dict:
#print('is dict')
try:
dict_str = dict_str + write_dict(value, key, f, dict_str)
except:
sys.stdout.write("\rdictionary didn't write properly ")
sys.stdout.flush()
elif type(item[key]) == list:
#print('is list')
try:
list_str = list_str + write_list(item, key, f, list_str)
except:
sys.stdout.write("\rlist didn't write properly ")
sys.stdout.flush()
elif type(item[key])==tuple:
item_str = item_str + '"' + value[1] +'",'
elif type(item[key])==int:
item_str = item_str +'"' + str(value) +'",'
elif value == 'True' or value == 'False' or type(value) ==bool:
#print('is bool')
item_str = item_str + '"' + str(value).lower() +'",'
#print (item_str)
elif type(value) == str:
#print('is str')
item_str = item_str +'"' + value.lower().replace('\n','').replace('\r','').replace(chr(34),chr(39)) +'",'
#print (item_str)
elif type(value) == None or value == None:
#print('is str')
item_str = item_str +'"",'
else:
print ('not added %s as is type %s' % (value, type(value)))
full_str = full_str + item_str + dict_str + list_str + "\n"
#print (full_str)
time.sleep(0.5) #Wait so we don't overload instance with too many api requests
#break
return (full_str)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T13:20:14.830",
"Id": "392787",
"Score": "3",
"body": "perhaps add an example input file and how this code is supposed to be called ."
}
] | [
{
"body": "<p>You can use the csvkit package from Pypi to accomplish that. Here's one of the tools from csvkit to convert json to csv in python: <a href=\"https://csvkit.readthedocs.io/en/1.0.2/scripts/in2csv.html\" rel=\"nofollow noreferrer\">https://csvkit.readthedocs.io/en/1.0.2/scripts/in2csv.html</a></p>\n... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T12:53:22.413",
"Id": "203735",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"strings",
"parsing",
"json"
],
"Title": "Parse JSON strings as tables using Python"
} | 203735 |
<p>I have this userform that looks up into a sheet. The problem is that when there are a lot of rows to look up it takes too long to execute (for example 100 thousand rows). Is it possible to reduce the time?</p>
<p>Here is the userform's textbox code where I put what I am looking for, and the data is shown on a listbox ("LSTART")</p>
<pre><code>Private Sub TXTBUSCAART_Change()
Dim rowCount As Long, itemCount As Long, counter As Long, n As Long
Dim dataSheet As Worksheet
Dim dataIn, dataOut()
LSTART.Clear
LSTART.ColumnCount = 9
Set dataSheet = Sheets("CONCAT")
With dataSheet
rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
itemCount = Application.WorksheetFunction.CountIf(.Range("A2:A" & rowCount), "*" & TXTBUSCAART.Text & "*")
If itemCount > 0 Then
ReDim dataOut(1 To itemCount, 1 To 9)
dataIn = .Range("A2:I" & rowCount).Value
counter = 1
For n = 1 To UBound(dataIn)
M = InStr(1, dataIn(n, 1), UCase(TXTBUSCAART.Text))
If M > 0 Then
dataOut(counter, 1) = dataIn(n, 1)
dataOut(counter, 2) = dataIn(n, 3)
dataOut(counter, 3) = dataIn(n, 2)
dataOut(counter, 4) = dataIn(n, 4)
dataOut(counter, 5) = dataIn(n, 6)
dataOut(counter, 6) = dataIn(n, 5)
dataOut(counter, 7) = dataIn(n, 8)
dataOut(counter, 8) = dataIn(n, 9)
dataOut(counter, 9) = dataIn(n, 7)
counter = counter + 1
End If
Next
LSTART.List = dataOut
End If
End With
End Sub
</code></pre>
| [] | [
{
"body": "<p>Worksheet functions like <code>CountIf</code> are pretty well optimized, so that's a good way to find out if <code>TXTBUSCAART.Text</code> is in column A of your <code>dataSheet</code>. but so is <code>Find</code>. </p>\n\n<p>By using <code>Find</code>, you <em>could</em> eliminate the initial ste... | {
"AcceptedAnswerId": "203777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T16:03:33.673",
"Id": "203744",
"Score": "1",
"Tags": [
"vba",
"excel",
"time-limit-exceeded"
],
"Title": "User form that searches a spreadsheet"
} | 203744 |
<p>I don't quite know where to post this but C# is not my first language and I am hoping to get someone to nod their head or correct me :) </p>
<p>This works but seems counter intuitive - mostly because I would like to make a list and then say list contains oneCharacter but, for cases like this, it would be excessively wordy.</p>
<p>The only purpose of this sample code is to evaluate whether oneCharacter is in the string "YN" and to ask if there is a better (or more beautiful) way to do this. It is not any more complicated than that.</p>
<pre><code> void MainGameLoop()
{
while(true)
{
Console.WriteLine("Randomizing new string ...");
var randomizedString = RandomizeString();
Console.WriteLine("Please input the value, only first letter of the input will be taken into account");
var userInput = Console.ReadLine();
var userCharacter = userInput[0].ToString();
// Here is the code I'm hoping to sort out. Is this a reasonable approach within the If condition?
if(!randomizedString.Contains(userCharacter))
{
Console.WriteLine("Sorry, wrong guess.");
}
// end code I'm hoping to sort out
else
{
Console.WriteLine("You guessed it!");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T20:15:09.427",
"Id": "392842",
"Score": "1",
"body": "For me, usage of `Contains` is okay. It says **exactly** what you intend to check. In case you are curious, underneath it actually calls (inyour case)`\"YN\".IndexOf(oneCharacter... | [
{
"body": "<p>I like this question (for no particular reason) so I will answer with an example (OP can put it into the question so it doesn't get closed). </p>\n\n<p>Say, we want to create a game which will randomize a string and user is expected to guess one letter within that string.</p>\n\n<pre><code> void M... | {
"AcceptedAnswerId": "203752",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T20:02:14.933",
"Id": "203751",
"Score": "-3",
"Tags": [
"c#",
".net"
],
"Title": "Best Practice .Contains C#"
} | 203751 |
<p>Create a Java class named HeadPhone to represent a headphone set. The class contains:</p>
<ul>
<li><p>Three constants named LOW, MEDIUM and HIGH with values of 1, 2 and 3 to denote the headphone volume.</p></li>
<li><p>A private int data field named volume that specifies the volume of the headphone. The default volume is MEDIUM.</p></li>
<li><p>A private boolean data field named pluggedIn that specifies if the headphone is plugged in. The default value is false.</p></li>
<li><p>A private String data field named manufacturer that specifies the name of the manufacturer of the headphones.</p></li>
<li><p>A private Color data field named headPhoneColor that specifies the color of the headphones.</p></li>
<li><p>A private String data field named headPhoneModel that specifies the Model of the headphones.</p></li>
<li><p>getter and setter methods for all data fields.</p></li>
<li><p>A no argument constructor that creates a default headphone.</p></li>
<li><p>A method named toString() that returns a string describing the current field values of the headphones.</p></li>
<li><p>A method named changeVolume(value) that changes the volume of the headphone to the value passed into the method</p></li>
</ul>
<p>Create a TestHeadPhone class that constructs at least 3 HeadPhone objects. For each of the objects constructed, demonstrate the use of each of the methods.</p>
<p>Here is what I have thus far....</p>
<pre><code>import java.awt.Color;
public class HeadPhones {
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
private int volume;
private boolean pluggedIn;
private String manufacturer;
private Color headPhoneColor;
public HeadPhones() {
volume = MEDIUM;
pluggedIn = false;
manufacturer = "";
headPhoneColor = Color.BLACK;
}
/**
*
* @return volume of headphone
*/
public int getVolume() {
return volume;
}
/**
* set volume of headphone
*
* @param volume
*/
public void setVolume(int volume) {
this.volume = volume;
}
/**
*
* @return true if the headphone is plugged in, false otherwise
*/
public boolean getPluggedIn() {
return pluggedIn;
}
/**
* set plugged in
*
* @param pluggedIn
*/
public void setPluggedIn(boolean pluggedIn) {
this.pluggedIn = pluggedIn;
}
/**
*
* @return manufacturer
*/
public String getManufacturer() {
return manufacturer;
}
/**
* set manufacturer
*
* @param manufacturer
*/
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
/**
*
* @return headphone color
*/
public Color getHeadPhoneColor() {
return headPhoneColor;
}
public String getColorName() {
String colorName = "Black";
if (headPhoneColor == Color.BLACK || headPhoneColor == Color.black) {
colorName = "Black";
} else if (headPhoneColor == Color.WHITE || headPhoneColor == Color.white) {
colorName = "White";
} else if (headPhoneColor == Color.RED || headPhoneColor == Color.red) {
colorName = "Red";
} else if (headPhoneColor == Color.PINK || headPhoneColor == Color.pink) {
colorName = "Pink";
} else if (headPhoneColor == Color.CYAN || headPhoneColor == Color.cyan) {
colorName = "Cyan";
} else if (headPhoneColor == Color.BLUE || headPhoneColor == Color.blue) {
colorName = "Blue";
} else if (headPhoneColor == Color.GREEN || headPhoneColor == Color.green) {
colorName = "Green";
} else if (headPhoneColor == Color.GRAY || headPhoneColor == Color.gray) {
colorName = "Gray";
}
return colorName;
}
/**
* set headphone color
*
* @param headPhoneColor
*/
public void setHeadPhoneColor(Color headPhoneColor) {
this.headPhoneColor = headPhoneColor;
}
/**
* returns a string describing the current field values of the headphone
*/
public String toString() {
StringBuilder s = new StringBuilder("(");
s.append("manufacturer = ").append(manufacturer).append(", ");
s.append("volumne = ").append(volume).append(", ");
s.append("plugged in = ").append(pluggedIn).append(", ");
s.append("color = ").append(getColorName()).append(")");
return s.toString();
}
}
</code></pre>
<p>And this is my test class....</p>
<pre><code>import java.awt.Color;
public class TestHeadPhones {
public static void main(String[] args) {
HeadPhones[] headphones = new HeadPhones[3];
headphones[0] = new HeadPhones();
headphones[0].setHeadPhoneColor(Color.CYAN);
headphones[0].setManufacturer("Thinksound");
headphones[1] = new HeadPhones();
headphones[1].setManufacturer("Monster");
headphones[1].setHeadPhoneColor(Color.white);
headphones[1].setPluggedIn(true);
headphones[1].setVolume(HeadPhones.HIGH);
headphones[2] = new HeadPhones();
headphones[2].setManufacturer("Sennheiser");
headphones[2].setHeadPhoneColor(Color.ORANGE);
headphones[2].setPluggedIn(true);
headphones[2].setVolume(HeadPhones.LOW);
for (int i = 0; i < 3; i++) {
System.out.println("Headphone #" + (i + 1));
System.out.println("toString() results: " + headphones[i]);
System.out.println("getVolume() results: " + headphones[i].getVolume());
System.out.println("getPluggedIn() results: " + headphones[i].getPluggedIn());
System.out.println("getManufacturer() results: " + headphones[i].getManufacturer());
System.out.println("getHeadPhoneColor() results: " + headphones[i].getColorName() + "\n");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T03:04:52.960",
"Id": "392905",
"Score": "1",
"body": "FYI, you are missing the field for the model."
}
] | [
{
"body": "<p>Since most of the class is just getters and setters, there isn't much substantial to comment on.</p>\n\n<p>The biggest problem I see is the <code>getColorName</code> method. It's doing unnecessary checks, and I usually reach for a <code>Map</code> in cases like this anyways. Map lookups are faster... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T21:12:03.557",
"Id": "203753",
"Score": "2",
"Tags": [
"java"
],
"Title": "Java class named HeadPhone to represent a headphone set"
} | 203753 |
<p>I'm new to coding and this is a text based adventure game with combat. Sleep and choice functions based on idea from <a href="https://codereview.stackexchange.com/a/52292/179642">https://codereview.stackexchange.com/a/52292/179642</a>. Map idea from Codecademy battleship tutorial.</p>
<p>The actions in the <code>fight</code> function are not in a loop because attacks reduce the opponent's hp but healing affects your own hp. </p>
<p>Any comments on new ideas/features, better coding methods greatly appreciated.</p>
<pre><code>import random, time, sys
#initial variables or settings, and map generation
hp = 100
rMap = [('G', 'G', 'G', 'C', 'W'), ('F', 'F', 'G', 'W', 'M'), ('B', 'W', 'W', 'G', 'M'), ('F', 'F', 'G', 'G', 'G'), ('F', 'F', 'F', 'G', 'V')]
pMap = []
for x in range(5):
pMap.append(['?'] * 5)
legend = {'X': 'You', '?': 'Unexplored', 'G': 'Grassland', 'V': 'Village', 'F': 'Forest', 'M': 'Mountain', 'B': 'Bridge', 'W': 'Water', 'C': 'Castle'}
enemy = {'G': ('Wolf', 30, 0, 33, 33, 50), 'F': ('Bandit', 30, 1, 50, 33, 50), 'M': ('Troll', 80, 0, 33, 50, 50), 'C': ('Dragon', 170, 2, 0, 0, 100), 'B': ('Ogre', 100, 0.5, 100, 100, 100)}
posR = 4
posC = 4
inv = {'Bow' : 1, 'Arrow' : 0, 'Potion' : 0}
action = {'Punch': (8, 12, 'p'), 'Kick': (6, 20, 'k')}
def wait(value): #can be commented away for quicker testing
#time.sleep(value)
pass
def new_loc(): #whether there is an enemy when the player moves to a new location
for i in enemy:
if rMap[posR][posC] == i:
if random.randint(1, 100) <= enemy[i][5]:
fight(enemy[i][0], enemy[i][1], enemy[i][2])
loot(enemy[i][3], enemy[i][4])
if i == 'C':
print ('You win! Congratulations!')
sys.exit()
updatepos()
turn()
def turn(): #every turn or action by the player
global hp
print ('What do you want to do?')
wait(0.5)
print ('t to Travel, i to view Inventory, m to view Map')
c = choice(['t', 'i', 'm'])
if c == 't':
print ('Which direction do you want to move?')
d = []
if posR != 0:
if rMap[posR - 1][posC] != 'W':
print ('f to move forward')
d.append('f')
if posR != 4:
if rMap[posR + 1][posC] != 'W':
print ('b to move backward')
d.append('b')
if posC != 0:
if rMap[posR][posC - 1] != 'W':
print ('l to move left')
d.append('l')
if posC != 4:
if rMap[posR][posC + 1] != 'W':
print ('r to move right')
d.append('r')
sel_dir = choice(d)
if sel_dir == 'f':
move(-1, 0)
if sel_dir == 'b':
move(1, 0)
if sel_dir == 'l':
move(0, -1)
if sel_dir == 'r':
move(0, 1)
if c == 'i':
showInv()
turn()
if c == 'm':
updatepos()
turn()
def start(): #introduction to the game
print ('Your village has been burnt down by a dragon!')
wait(0.5)
print (' ')
print ('You have to find it and take revenge!')
print (' ')
updatepos()
turn()
def showAction(): #for debugging player actions in battle
for i in action:
print (i, action[i])
def updateAction(): #for updating actions linked to items
if inv['Potion'] > 0:
if 'Heal' not in action:
action['Heal'] = (40, 50, 'h')
if inv['Potion'] == 0:
if 'Heal' in action:
action.pop('Heal')
if inv['Arrow'] > 0:
if 'Shoot' not in action:
action['Shoot'] = (30, 40, 's')
if inv['Arrow'] == 0:
if 'Shoot' in action:
action.pop('Shoot')
def showInv(): #for viewing inventory
global hp
for i in inv:
if inv[i] > 0:
print (i + ':', inv[i])
if inv['Potion'] > 0:
updateAction()
print('Do you want to drink a Potion? y/n')
drink = choice(['y', 'n'])
if drink == 'y':
h = random.randint(action['Heal'][0], action['Heal'][1])
hp += h
print('You used a Potion')
wait(0.5)
print('You healed yourself for %d HP!' % h)
wait(0.5)
inv['Potion'] -= 1
print('You have %d Potions left' % (inv['Potion']))
turn()
def move(r, c): #when the player moves
global posR
global posC
posR = posR + r
posC = posC + c
wait(0.5)
if r == -1:
print ('Moving Forward...')
if r == 1:
print ('Moving Backward...')
if c == 1:
print ('Moving Right...')
if c == -1:
print ('Moving Left...')
new_loc()
def updatepos(): #updating the map position
pMap[posR][posC] = 'X'
if posR != 4:
pMap[posR + 1][posC] = rMap[posR + 1][posC]
if posR != 0:
pMap[posR - 1][posC] = rMap[posR - 1][posC]
if posC != 4:
pMap[posR][posC + 1] = rMap[posR][posC + 1]
if posC != 0:
pMap[posR][posC - 1] = rMap[posR][posC - 1]
showMap()
wait(0.5)
print ('You are now in %s' % legend[rMap[posR][posC]])
def showMap(): #prints the map and legend (for revealed areas)
print ('Map:')
for row in pMap:
for i in row:
print (i, end = ' ')
print()
print (' ')
legList = []
for row in pMap:
for i in row:
legList.append(i)
for i in legend:
if i in legList:
print (i, legend[i])
print (' ')
def choice(list): #get a valid choice from the user
while True:
userChoice = input('Choose an action:')
userChoice = userChoice.lower()
if userChoice in list:
return userChoice
else:
print ('Invalid choice. Try again.')
def fight(enemy, eHP, level): #fighting an enemy
print ('%s appeared!' % enemy)
wait(0.5)
global hp
enemyHP = eHP
while True:
if hp <= 0:
print ("You died :(. Game over")
sys.exit()
wait(1)
print ('Your hp: %d, %s hp: %d' % (hp, enemy, enemyHP))
wait(1)
updateAction()
act = []
for i in action:
print (i + ': ' + str(action[i][0]) + ' - ' + str(action[i][1]))
act.append(action[i][2])
act_str = ', '.join(str(x) for x in act)
print ('Choices: ' + act_str)
pmove = choice(act)
wait(0.7)
if pmove == 'p':
d = random.randint(action['Punch'][0], action['Punch'][1])
enemyHP -= d
print ('You punch %s for %d damage!' % (enemy, d))
elif pmove == 'k':
d = random.randint(action['Kick'][0], action['Kick'][1])
enemyHP -= d
print ('You kick %s for %d damage!' % (enemy, d))
elif pmove == 'h':
h = random.randint(action['Heal'][0], action['Heal'][1])
print ('You used a Potion')
print ('You heal yourself for %d HP!' % h)
inv['Potion'] -= 1
print ('You have %d Potions left' % (inv['Potion']))
updateAction()
hp += h
elif pmove == 's':
d = random.randint(action['Shoot'][0], action['Shoot'][1])
print ('You used an Arrow')
print ('You shoot %s for %d damage!' % (enemy, d))
inv['Arrow'] -= 1
print('You have %d Arrows left' % (inv['Arrow']))
updateAction()
enemyHP -= d
if enemyHP <= 0:
print("You defeated %s!" % enemy)
return
wait(1)
emove = random.randint (1, 3)
if emove == 1:
dam = random.randint(1, 5) + 10 * level
print ('%s scratches you for %d damage!' % (enemy, dam))
hp -= dam
elif emove == 2:
dam = random.randint(6, 10) + 0.5 * level
print ('%s bites you for %d damage!' % (enemy, dam))
hp -= dam
else:
heal = random.randint(9, 15) + 1 * level
print ('%s healed for %d HP!' % (enemy, heal))
enemyHP += heal
def loot(a, p): #probability of getting loot from enemy
wait(1)
pArrow = random.randint(1, 100)
pPotion = random.randint(1, 100)
if pArrow <= a:
inv['Arrow'] += 1
print ('You found an Arrow!')
wait(0.5)
print('You now have %d Arrows' % inv['Arrow'])
wait(0.7)
if pPotion <= p:
inv['Potion'] += 1
print ('You found a Potion!')
wait(0.5)
print('You now have %d Potions' % inv['Potion'])
wait(0.7)
start()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T22:58:00.187",
"Id": "392867",
"Score": "2",
"body": "I'm not very good at Python so I don't have any criticism other than to say, I've briefly played your game, got into a fight with a wolf, defeated the wolf and thoroughly enjoyed... | [
{
"body": "<p>Nice work!</p>\n\n<p>Here are some things you can improve:</p>\n\n<ul>\n<li>Style: <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> - you can check it with <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">http://pep8online.com/</a> and there ... | {
"AcceptedAnswerId": "203760",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T22:16:17.080",
"Id": "203756",
"Score": "4",
"Tags": [
"python",
"beginner",
"adventure-game",
"battle-simulation"
],
"Title": "Text-based adventure and combat game"
} | 203756 |
<p>This was a coding challenge I had done recently. I was given a text file and in it thee was couple of XML tags. The challenge was to get all the XML tags and the information and save it to another file.</p>
<p>The string I am given:</p>
<pre><code>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec arcu non nisl dapibus scelerisque. Phasellus sagittis ligula vel convallis porttitor. Maecenas sed velit arcu. Proin efficitur ipsum vitae augue semper, bibendum sollicitudin neque egestas".
<OpeningTag><AnotherOpeningTag>Information</AnotherClosingTag></ClosingTag>
"Etiam venenatis feugiat erat, in egestas tellus lacinia eu. Phasellus volutpat lectus nec tristique volutpat. Sed tempus sollicitudin mauris eu blandit.<OpeningTag><AnotherOpeningTag>Information</AnotherClosingTag></ClosingTag> Vestibulum consectetur euismod dui, sit amet blandit ex ultrices ac".
</code></pre>
<p>This is the code I came up with:</p>
<pre><code>StringReader reader = new StringReader(text);
while ((text = reader.ReadLine()) != null)
{
if (text.StartsWith("<") && text.EndsWith(">"))
{
txtXml += text + "\n";
}
else
{
string regexPattern = @"(<.*>)(.*)(<\/.*>)";
Regex regex = new Regex(regexPattern, RegexOptions.Singleline);
MatchCollection collection = regex.Matches(text);
var list = collection.Cast<Match>().Select(match => match.Value).ToList();
for (int i = 0; i < list.Count; i++)
{
txtXml += list.ElementAt(i);
}
}
}
</code></pre>
<p>This code works and I am getting all the tags and the information and stuff. I just wanted to know if I could achieve this same task in smaller code or code that executes faster than the current method.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T23:21:52.563",
"Id": "392869",
"Score": "4",
"body": "The problem is underspecified. Do the XML fragments you are looking for always occupy a full line on their own? Are they always well-formed? What are you supposed to do it you fi... | [
{
"body": "<p>There are some good points raised in comments about the requirements, and you really need to think about them in order to write code that solves the problem. I can get you started with some feedback though.</p>\n\n<p>Organize your code into a function, so that it's clear what the inputs and outpu... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-14T22:23:38.547",
"Id": "203757",
"Score": "2",
"Tags": [
"c#",
"xml"
],
"Title": "Save XML tags and information to another file"
} | 203757 |
<p>I have written 2 Brainfuck interpreters, one in C++, then another in C++ with Assembly inner loop. My interpreter code can be found <a href="https://github.com/ethan-tqa/bfasminterp/tree/019b5b35da6a769b8c007cbf75d1b671d4b480f8" rel="nofollow noreferrer">here</a> (C++/ASM, requires MSVC and MASM) and <a href="https://github.com/ethan-tqa/bfinterpreters/tree/ada196048ee075a344f954d9d1e6632b3f7fa150" rel="nofollow noreferrer">here</a> (C++).</p>
<p>Both are benchmarked using the mandelbrot BF program, run 20 times. After trying for a while, I managed to make the Asm version about 10% faster than the C++ version, but I'm wondering if it can be made even faster. The main bottlenecks appears to be branch mispredictions and uOps cache. The benchmark ran on SkylakeX CPU.</p>
<p>The inner loop looks like this:</p>
<pre><code>interpret proc C
.code
push rbx ; these are callee saved ?
push rsi
push rdi
push rbp
push r12
push r13
push r14
push r15
sub rsp, 32 ; shadow space?
xor rsi, rsi ; "program counter", which instruction we are at
mov rdi, r8 ; "memory pointer", where we are pointing to in the interpreter memory
xor r14, r14 ; store the value of current mem cell, which of course starts at 0
lea r15, [jumptable] ; load the address of the table
mov r13, rcx ; base address of instruction array
lbl_interp_loop: ; beginning of new interpreter cycle
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
ALIGN 4
lbl_Loop:
cmp byte ptr [rdi], 0
jne lbl_set_loop_ip
add rsi, r11
lbl_set_loop_ip:
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
ALIGN 4
lbl_Return:
cmp byte ptr [rdi], 0
jne lbl_set_return_ip
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
lbl_set_return_ip:
sub rsi, r11
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
ALIGN 4
lbl_Right:
add rdi, r11
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
ALIGN 4
lbl_Left:
sub rdi, r11
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
ALIGN 4
lbl_Add:
add byte ptr [rdi], r11b
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
ALIGN 4
lbl_Minus:
sub byte ptr [rdi], r11b
movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
jmp qword ptr [r15 + r10 * 8]
lbl_Print:
movzx rcx, byte ptr [rdi]
call printChar
jmp lbl_interp_loop
lbl_Read:
jmp lbl_interp_loop
lbl_Invalid:
jmp lbl_interp_loop
jumptable: ; MASM cannot emit relative address in .data, so must put it in .code this way (agner)
dq lbl_Loop
dq lbl_Return
dq lbl_Right
dq lbl_Left
dq lbl_Add
dq lbl_Minus
dq lbl_Print
dq lbl_Read
dq lbl_Invalid
dq lbl_End
lbl_End:
add rsp, 32
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rdi
pop rsi
pop rbx
ret
interpret endp
end
</code></pre>
<p>Here is the report from V-Tune:</p>
<p><a href="https://i.stack.imgur.com/Nj02x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nj02x.png" alt="V-Tune perf"></a></p>
<ol>
<li>Before this inner loop begins, the interpreter does a couple of simple transformation on the BF source, turning it into instructions that consist of a 2 byte opcode and 2 byte operand. Repeated instructions are collapsed into 1 instructions and the number of repeats is stored in the operand. Loop/Repeat instructions contain the index of the destination instruction it jumps to.</li>
<li>Because of (1), there is no advantage of storing the value of current cell in register. In fact, when I tried to do that, performance got slightly worse. That is because when the interpreter encounters Left/Right instructions, it must save the current cell to memory and load the next cell, probably causing a data dependency on the register.</li>
<li>The reason why code for Loop and Return instructions are different, is because after changing code for Loop (<code>[</code> in BF) to have rare case right after <code>cmp</code>, I found performance increased considerably, but back fired for Return (<code>]</code> in BF) instruction. That seems counter intuitive to put rare case after <code>cmp</code>, but it seems to works here. V-Tune indicates a reduction in branch misprediction rate too.</li>
<li><p>Another strange example is right after label <code>lbl_set_return_ip:</code>, where I originally wrote:</p>
<pre><code>mov rax, r11
sub rsi, rax
</code></pre>
<p>but then found out that rewriting it as below noticably improved performance:</p>
<pre><code>sub rsi, r11
</code></pre>
<p>Which is strange because I expected the <code>mov</code> to be pretty much free through register renaming.</p></li>
<li><p>The same data dependency problem leads to the fact that I relied on array indexing instead of increasing the pointer. This code</p>
<pre><code>movzx r10, word ptr [r13 + rsi*4]
movzx r11, word ptr [r13 + rsi*4 + 2]
inc rsi ; advance to the next instruction
</code></pre>
<p>is found to be faster than </p>
<pre><code>add rsi, 4 ; rsi contains the address of current instruction
movzx r10, word ptr [rsi]
movzx r11, word ptr [rsi + 2]
</code></pre></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T02:42:21.060",
"Id": "392874",
"Score": "0",
"body": "re: your comments with a `?`: yes, those are the call-preserved registers in the Windows x64 calling convention. And yes, since you use `call` inside this function, it needs to ... | [
{
"body": "<p>I'd expect that most of the performance problem comes from the indirect branch (<code>jmp qword ptr [r15 + r10 * 8]</code>) - it's relatively unpredictable and should cause lots of branch mispredictions, bad speculations and pipeline stalls.</p>\n\n<p>There's only really 2 ways to deal with this:<... | {
"AcceptedAnswerId": null,
"CommentCount": "22",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T02:31:05.977",
"Id": "203762",
"Score": "4",
"Tags": [
"performance",
"assembly",
"interpreter",
"brainfuck",
"x86"
],
"Title": "Main loop in assembly for a Brainfuck interpreter"
} | 203762 |
<p>Among the many fractals, there is <a href="http://yozh.org/2012/01/12/the_collatz_fractal/" rel="nofollow noreferrer">Collatz Fractal</a> based on a complex extension of:
$$f(x) = \left\{
\begin{array}{ll}
\frac{x}{2} \space \text{if even} \\
3x + 1 \space \text{if odd}
\end{array}
\right.$$</p>
<p>To generate the fractal, you pick a bunch of points and repeatedly apply <code>f</code> over and over again a large number of times. Morally, <code>f(f(f(f(....f(x)....))))</code> In this case, however, it is not a real number <code>x</code> but instead a complex number (often denoted <code>z</code>). The end result is plotted by giving it a color that "corresponds" to the size of the result.</p>
<p>The resulting image is:</p>
<p><a href="https://i.stack.imgur.com/kYlFu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kYlFu.png" alt="Collatz Fractal"></a></p>
<p>Here is the code:</p>
<h1><code>lib.rs</code></h1>
<pre><code>/// A fractal generation module.
pub mod fractal_gen {
extern crate image;
extern crate num_complex;
use self::num_complex::Complex;
use std;
/// Complex extension of the Collatz function.
///
/// # Arguments
/// * `z` - A complex number.
///
/// # Returns
/// * The Collatz function applied to `z`. Where the Collatz function foll-
/// ows the definition from here: http://yozh.org/2012/01/12/the_collatz_fractal/
pub fn collatz(z: Complex<f32>) -> Complex<f32> {
let comp_pi = Complex::new(std::f32::consts::PI, 0.0);
return ((7.0 * z + 2.0)
- (comp_pi * z).cos()
* (5.0 * z + 2.0)) / 4.0;
}
/// Generate a fractal picture.
///
/// # Arguments
/// * `buf` - Image buffer that will store the result image.
/// * `f` - Complex function that returns a complex number.
/// * `scalex` - Horizontal scaling factor.
/// * `scaley` - Vertical scaling factor.
/// * `max_iterations` - Maximum number of applications of `f`.
pub fn populate_image(buf: &mut image::GrayImage,
f: fn(Complex<f32>) -> Complex<f32>,
scalex: f32, scaley: f32,
max_iterations: u16) {
for (x, y, pixel) in buf.enumerate_pixels_mut() {
let cy = y as f32 * scaley - 2.0;
let cx = x as f32 * scalex - 2.0;
let mut z = Complex::new(cx, cy);
let mut i = 0;
for t in 0..max_iterations {
if z.norm() > 1000.0 {
break
}
z = f(z);
i = t;
}
*pixel = image::Luma([i as u8]);
}
}
}
</code></pre>
<h1><code>main.rs</code></h1>
<pre><code>extern crate fraclib;
extern crate argparse;
extern crate image;
use argparse::{ArgumentParser, Store};
use fraclib::fractal_gen;
/// Generates and exports a fractal.png. fractal.png is a picture of the Colla-
/// tz fractal.
///
/// # Flags
///
/// * `--maxiter` iteration depth for successive iteration on the Collatz func-
/// tion.
/// * `--xdim` width of the image.
/// * `--ydim` height of the image.
/// * `--scalewidth` horizontal scaling factor.
/// * `--scaleheight` vertical scaling factor.
fn main() {
let mut max_iterations = 1024u16;
let mut imgx = 800;
let mut imgy = 800;
let mut scalex = 4.0 / imgx as f32;
let mut scaley = 4.0 / imgy as f32;
{
let mut ap = ArgumentParser::new();
ap.set_description("Create a Collatz Fractal.");
ap.refer(&mut max_iterations)
.add_option(&["-i", "--maxiter"], Store,
"Maximum number of iterations on Collatz function");
ap.refer(&mut imgx)
.add_option(&["-x", "--xdim"], Store,
"The x dimension of the generated image");
ap.refer(&mut imgy)
.add_option(&["-y", "--ydim"], Store,
"The y dimension of the generated image");
ap.refer(&mut scalex)
.add_option(&["-w", "--scalewidth"], Store,
"The width scaling factor");
ap.refer(&mut scaley)
.add_option(&["-h", "--scaleheight"], Store,
"The height scaling factor");
ap.parse_args_or_exit();
}
let mut imgbuf = image::GrayImage::new(imgx, imgy);
fractal_gen::populate_image(&mut imgbuf,
fractal_gen::collatz,
scalex, scaley,
max_iterations);
// Save the image as “fractal.png”, the format is deduced from the path
imgbuf.save("fractal.png").unwrap();
}
</code></pre>
<p>Github can be <a href="https://github.com/thyrgle/collatz_fractal" rel="nofollow noreferrer">found here.</a> Heavily modified variant of the Mandelbrot example <a href="https://github.com/PistonDevelopers/image" rel="nofollow noreferrer">given here.</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T03:16:05.920",
"Id": "203764",
"Score": "4",
"Tags": [
"rust",
"fractals",
"collatz-sequence"
],
"Title": "Collatz fractal in Rust"
} | 203764 |
<p>This is a fairly simple bit of code: </p>
<pre><code>async function fetchData() {
console.log("fetching data");
let json;
try {
const data = await fetch(endPoint);
json = await data.json();
}
catch (error) {
console.error(error);
handleError(error);
}
try {
await saveData(json);
} catch (error) {
console.error(error);
handleError(error);
}
}
console.info("start running");
setInterval(fetchData, config.newsapi.polling_interval);
console.info("application is running");
</code></pre>
<p>What we're doing is - every 15 minutes or so, we're polling an API endpoint, and then saving the results into a database.</p>
<p>So there's two main kinds of errors we might get here: </p>
<ul>
<li>The API I fetched the data from might return some kind of error - it might be down, or my API key might be wrong, or I've gone over the rate limit or whatever.</li>
<li>The database might return some kind of error. For all the same reasons, but a completely different service.</li>
</ul>
<p>Now in terms of handling these errors, for now all I'll be doing is logging the error, and send me an email.</p>
<p>But I can imagine, that in the future, I might want to handle these two distinct kinds of errors differently. As such, I've created two different <code>try</code> <code>catch</code> blocks, that gives me the flexibility to handle them differently.</p>
<p>But it does look a bit messier, in my opinion. The other way I could write this is:</p>
<pre><code>async function fetchData() {
console.log("fetching data");
try {
const data = await fetch(endPoint);
const json = await data.json();
await saveData(json);
}
catch (error) {
console.error(error);
handleError(error);
}
}
console.info("start running");
setInterval(fetchData, config.newsapi.polling_interval);
console.info("application is running");
</code></pre>
<p>This looks so much tidier. But in which case - it seems like the error handling is a bit trickier.</p>
<p>I guess I could put a <code>switch</code> statement in the catch block handle different errors differently, but is that a bit messy? Any suggestions or guidelines for navigating this?</p>
| [] | [
{
"body": "<p>In my opinion it is much better to place the <code>saveData</code> call inside the first try-catch block.</p>\n\n<p>This avoids calling <code>saveData</code> with an undefined value in case an exception occurs in calls to <code>fetch</code> or <code>data.json</code>, and gives the <code>json</code... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T03:54:41.780",
"Id": "203766",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"error-handling",
"asynchronous"
],
"Title": "Error handling for a simple 'fetch some data, then save the data' Node function"
} | 203766 |
<p>I have the following code which I seek to optimize. The result of the bruteforce I already have but I'm just trying to learn some more python using the same example. </p>
<p>The code in the data needs to be split where the ++ are spaces and the || are just separators between letters. The // are carriage returns. </p>
<p>The code below spits out a readable message depending on the key but to learn more about splitting/replacements & python I want to try to get the output format better as well. On top of that I want to see if some language recognition or analysis on the output string would be handy in not having to scroll through all output manually to find potential candidates for the decoded message. So recognize a potential human readable and meaningful string. </p>
<p>Just to state again. I already have the decoded message. So I'm note here to score some easy points for a CTF somewhere. I just use the sample to learn python. </p>
<p>So to sum up I have two questions:</p>
<p>1.What is the best way to split the initial string into parts that preserve the format (given the || between letters and the ++ for the spaces between words)</p>
<p>2.What would be a good method to do an analysis on the generated strings. (counters or language detect?)</p>
<pre><code>#!/usr/bin/env python
import re
result=""
plaintext=''
data = """|125||104||120||118||++||107||100||118||++||100||118||110||104||103||++||112||104||++||119||114||++||112||100||110||104|
|++||100||113||++||104||113||102||114||103||104||117||++||105||114||117||++||114||120||117||++||120||115||103||100||119|
|104||118||//||++||119||107||108||118||++||108||118||++||112||104||++||119||104||118||119||108||113||106||++||108||119|
|++||114||120||119||//||++||108||105||++||108||119||++||122||114||117||110||118||++||108||++||122||108||111||111||++|
|101||104||++||118||104||113||103||108||113||106||++||108||119||++||119||114||++||119||107||104||++||117||104||118||119|
|++||114||105||++||124||114||120||++||100||118||++||122||104||111||111||++||100||118||++||100||++||103||104||102||114|
|103||104||117||//||++||119||108||117||//|"""
newdata =re.sub("\D", "", data)
n = 3
splitted = [newdata[i:i+n] for i in range(0, len(newdata), n)]
integers = map(int, splitted)
print integers # this is a list with integers
def bruteforce(key):
global plaintext
plaintext =''
for char in integers:
plaintext = plaintext + chr(char+key)
return
for key in range (-100,100):
bruteforce(key)
print plaintext
</code></pre>
| [] | [
{
"body": "<p>I would redo this completely. First some things that should be addressed by the rewrite:</p>\n\n<ul>\n<li>Define functions for small, separate tasks that do simple things.</li>\n<li>Not mess up the global namespace too much (by having variables lying around, as well as calling code (which is bette... | {
"AcceptedAnswerId": "203779",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T06:56:14.697",
"Id": "203769",
"Score": "-1",
"Tags": [
"python",
"performance",
"python-2.x",
"regex",
"caesar-cipher"
],
"Title": "Decoding a string encoded by Caesar Cipher and some delimiters"
} | 203769 |
<p>I have a couple of chemical reactions. One of them is described as <code>"If insulin is mixed with antibiotic, healthy people catch Fever"</code>. I think it would be useful for logging to keep these description strings inside the code. I have thought of 2 approaches but they both seem kind of wrong.</p>
<h3>Approach 1</h3>
<pre><code>public abstract class ChemicalReaction {
public abstract String getDescription();
}
public class AntibioticInsulinReaction {
private static final String DESCRIPTION = "If insulin is mixed with antibiotic, healthy people catch Fever";
public String getDescription(){ return DESCRIPTION; }
}
</code></pre>
<p>Instance method returns a static variable.</p>
<h3>Approach 2</h3>
<pre><code>public final class ChemicalReaction {
private final String description;
public ChemicalReaction(final String description){
this.description = description;
}
public String getDescription(){ return description; }
}
public class Main {
public static void main(String[] args){
ChemicalReaction antibioticInsulinReaction = new ChemicalReaction("If insulin is mixed with antibiotic, healthy people catch Fever");
}
}
</code></pre>
<p>Magic string.</p>
<p>Do you see any other way to do it? Or maybe I don't need to?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T02:57:11.733",
"Id": "392947",
"Score": "1",
"body": "Hard to advise you, without knowing what other functionality needs to be supported by these `ChemicalReaction` objects. I've voted to close the question for lack of context."
}... | [
{
"body": "<p>You can use the power of <code>Enum</code>. As <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow noreferrer\">oracle says</a> </p>\n\n<p>Consider following example:</p>\n\n<pre><code>enum ChemicalReaction {\n ANTIBIOTIC_INSULIN(\"If insulin is mixed with a... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T09:03:09.460",
"Id": "203772",
"Score": "-2",
"Tags": [
"java",
"object-oriented"
],
"Title": "Polymorphic string that describes each child class"
} | 203772 |
<p>This script attempts to crack passwords by going through all possible 'words', hashing them, and comparing the hash to the input.</p>
<p>It seems to work, but I don't know if I have written 'good' C. I'm looking for advice on what areas would be most important/beneficial to focus on (e.g. efficiency, design, readability, something else?) in the next thing I write and how to improve within those. I also don't feel that comfortable with low level concepts like memory and pointers and I'm not sure if I'm using them right.</p>
<p>I'm not really sure what I want though so please give me whatever advice you think I need.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
#include <crypt.h>
char ALPHABET[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int alphabetSize = 52;
int max_length = 4;
void check(char *guess, char *salt, char *hash)
{
string hashedGuess = crypt(guess, salt);
if (!strcmp(hash, hashedGuess))
{
printf("%s\n", guess);
free(guess);
exit(0);
}
}
// recursively fill the buffer and check it each time
void brute_force(char *buf, int index, int length, string salt, string hash)
{
for (int i = 0; i < alphabetSize; i++)
{
sprintf(buf + index, "%c", ALPHABET[i]);
if (index < length)
{
brute_force(buf, index + 1, length, salt, hash);
}
else
{
check(buf, salt, hash);
}
}
}
char *crack(string hash, string salt)
{
// create a buffer big enough to hold the longest possible password
char *buf = (char *) malloc(max_length + 1);
// increment guess length starting from 1
for (int length = 0; length < max_length; length++)
{
brute_force(buf, 0, length, salt, hash);
}
return "";
}
bool valid_args(int argc, string argv[])
{
if (argc == 2)
{
return true;
}
return false;
}
int main(int argc, string argv[])
{
if (valid_args(argc, argv))
{
string hash = argv[1];
char salt[3];
strncpy(salt, hash, 2); // salt is first 2 characters of hash
string password = crack(hash, salt);
}
else
{
printf("Invalid arguments\n");
return 1;
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p><strong><code>valid_args</code></strong> is a well-known anti-idiom:</p>\n\n<pre><code> if (condition) {\n return true;\n }\n return false;\n</code></pre>\n\n<p>is a long way to say</p>\n\n<pre><code> return condition;\n</code></pre></li>\n<li><p><strong><code>crack</c... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T13:39:26.907",
"Id": "203778",
"Score": "3",
"Tags": [
"beginner",
"c"
],
"Title": "Brute force passwords in C (CS50 exercise)"
} | 203778 |
<p>I have written a function <code>func getScriptsFromUrl</code> that accepts a URL and creates two files with script body and script src for internal and external JS scripts respectively.</p>
<p>But since I am totally new to Golang, I doubt if the code is of a high quality, so will highly appreciate if you</p>
<ul>
<li>examined my code for compatibility with common Golang standards</li>
<li>Checked if the used business logic is appropriate </li>
<li>Provided my with any piece of advice, etc.</li>
</ul>
<p></p>
<pre><code>package main
import (
"github.com/PuerkitoBio/goquery"
"log"
"net/http"
"os"
)
func checkError(err error, errorMsg string) {
if err != nil {
log.Printf("%s: %s\n", errorMsg, err)
return
}
}
func getScriptsFromUrl(url string) {
res, err := http.Get(url)
checkError(err,"Failed to access the provided URL")
defer res.Body.Close()
doc, err := goquery.NewDocumentFromReader(res.Body)
checkError(err,"Error loading HTTP response body")
extScriptsFile, err := os.OpenFile("external_scripts.txt", os.O_WRONLY|os.O_CREATE, 02)
intScriptsFile, err := os.OpenFile("internal_scripts.txt", os.O_WRONLY|os.O_CREATE, 02)
defer extScriptsFile.Close()
defer intScriptsFile.Close()
scripts := doc.Find("script")
for i := range scripts.Nodes {
script := scripts.Eq(i)
href, srcExists := script.Attr("src")
if srcExists {
extScriptsFile.WriteString(href + "\n")
} else {
source, err := script.Html()
checkError(err,"Error getting the script's content")
intScriptsFile.WriteString(source + "\n")
}
}
}
func main(){
getScriptsFromUrl("https://www.your-site.com")
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T14:29:25.160",
"Id": "203781",
"Score": "2",
"Tags": [
"go"
],
"Title": "Extract script body or script src for internal and external JS scripts respectively"
} | 203781 |
<p>This is my C implementation of the Minimax Algorithm to play tic-tac-toe. I consider myself a C beginner so any feedback on style, best practices, or efficiency is more than welcome.</p>
<pre><code># define HUMAN_PLAYER 'X'
# define AI_PLAYER 'O'
# define NONE '\0'
typedef struct Point {
int x, y;
} Point;
typedef struct Board {
Point location;
Point boundary;
int size;
int current_player;
int last_player;
int nmoves_played;
int ai_mode;
char last_cell_symbol;
char **cells;
} Board;
typedef struct MiniMaxMove {
int score;
int x;
int y;
} MiniMaxMove;
int has_won(Point last_destination, char player, Board *board) {
// columns
for (int i = 0; i < board->size; i++) {
if (board->cells[last_destination.x][i] != player)
break;
if (i == board->size - 1) {
return 1;
}
}
// rows
for (int i = 0; i < board->size; i++) {
if (board->cells[i][last_destination.y] != player)
break;
if (i == board->size - 1) {
return 1;
}
}
// diagonal
if (last_destination.x == last_destination.y) {
for (int i = 0; i < board->size; i++) {
if (board->cells[i][i] != player)
break;
if (i == board->size - 1) {
return 1;
}
}
}
// anti diagonal
if (last_destination.x + last_destination.y == board->size - 1) {
for (int i = 0; i < board->size; i++) {
if (board->cells[i][(board->size-1)-i] != player)
break;
if (i == board->size - 1){
return 1;
}
}
}
return 0;
}
int is_a_draw(Board *board) {
if (board->nmoves_played == (pow(board->size, 2) - 1)) {
return 1;
}
return 0;
}
MiniMaxMove minimax(Point last_destination, char player, Board *board) {
if (has_won(last_destination, HUMAN_PLAYER, board)) {
return (MiniMaxMove) { .score = -10 };
} else if (has_won(last_destination, AI_PLAYER, board)) {
return (MiniMaxMove) { .score = 10 };
} else if (is_a_draw(board)) {
return (MiniMaxMove) { .score = 0 };
}
MiniMaxMove *moves = malloc(sizeof(MiniMaxMove *) * board->size * board->size);
size_t moves_size = 0;
for (int i = 0; i < board->size; i++) {
for (int j = 0; j < board->size; j++) {
if (board->cells[i][j] == '\0') {
MiniMaxMove move;
move.x = i;
move.y = j;
board->cells[i][j] = player;
// caclulate the score for the opponent
if (player == AI_PLAYER) {
MiniMaxMove mm_move = minimax(last_destination, HUMAN_PLAYER, board);
move.score = mm_move.score;
} else if (player == HUMAN_PLAYER) {
MiniMaxMove mm_move = minimax(last_destination, AI_PLAYER, board);
move.score = mm_move.score;
}
// reset the board to what it was
board->cells[i][j] = '\0';
moves[moves_size++] = move;
}
}
}
int best_move_idx;
if (player == AI_PLAYER) {
int best_score = -10000;
for (unsigned int i = 0; i < moves_size; i++) {
if (moves[i].score > best_score) {
best_score = moves[i].score;
best_move_idx = i;
}
}
} else {
int best_score = 10000;
for (unsigned int i = 0; i < moves_size; i++) {
if (moves[i].score < best_score) {
best_score = moves[i].score;
best_move_idx = i;
}
}
}
return moves[best_move_idx];
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T07:51:31.097",
"Id": "392956",
"Score": "3",
"body": "`MiniMaxMove *moves = malloc(\n sizeof(MiniMaxMove *) * board->size * board->size);` is suspicious. I'd expect `sizeof(MiniMaxMove) * board->size * board->size`... | [
{
"body": "<p>From a quick glance, the code looks pretty OK; good use of structs, relatively self-contained functions, nice indentation. So it's mainly some small stuff that can be improved:</p>\n\n<h2>Use static const variables instead of #define</h2>\n\n<p>Instead of</p>\n\n<pre><code># define HUMAN_PLAYER 'X... | {
"AcceptedAnswerId": "203815",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T16:57:59.983",
"Id": "203786",
"Score": "3",
"Tags": [
"beginner",
"algorithm",
"c",
"tic-tac-toe",
"ai"
],
"Title": "MiniMax Algorithm"
} | 203786 |
<p>I implemented a centered finite difference approximation for edge enhancement in images. The difference approximation has a step size h of the partial derivatives in the x- and y-directions of a 2D-image. However, the function that calculates the difference approximation is slow on big images. </p>
<p>Here is the code:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib
from skimage import io
import numpy as np
# read image as a numpy array
sample_img = io.imread('samlpe.png')
def findiff(image, stepsize):
# Padding to handle the boundaries when incrementing with step size
padded_img = np.pad(image, pad_width=1, mode='constant', constant_values=0)
img = padded_img.astype(float)
M, N = img.shape # Get the dimensions of the image.
pdfx = np.zeros(shape=(M, N))
pdfy = np.zeros(shape=(M, N))
img_lst = []
for x in range(M-1):
for y in range(N-1):
pdfx[x][y] = (img[x][y + stepsize] - img[x][y - stepsize]) / (2 * stepsize) # partial with relation to x
pdfy[x][y] = (img[x + stepsize][y] - img[x - stepsize][y]) / (2 * stepsize) # partial with relation to y
img_lst.append(pdfx)
img_lst.append(pdfy)
return img_lst
fig, img_lst = plt.subplots(1, 2)
imgs = findiff(sample_img, 1)
img_lst[0].imshow(imgs[0], cmap="gray")
img_lst[1].imshow(imgs[1], cmap="gray")
img_lst[0].set_title('pdfx')
img_lst[1].set_title('pdfy')
plt.show()
</code></pre>
<p>This solution works for step size=1. How can I improve this code? Can I avoid the nested loops? How can I generalize the function so that it can handle different step sizes?</p>
<p>I'm new to Python by the way.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T13:42:46.957",
"Id": "392966",
"Score": "0",
"body": "Did you consider using [`scipy.ndimage`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.html)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDa... | [
{
"body": "<p>I'm not yet very comfortable with Python style and so on, so I'm going to focus only on speeding up the code.</p>\n\n<p><strong>First of all, the indexing</strong></p>\n\n<p><code>img[x]</code> extracts a line from the image. Then <code>img[x][y]</code> extracts a pixel from that line. In contrast... | {
"AcceptedAnswerId": "203903",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T17:03:38.233",
"Id": "203787",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"image",
"numpy",
"matplotlib"
],
"Title": "Centered finite difference approximation for edge enhancement"
} | 203787 |
<p>I have a number <code>x</code> and I need to choose another number <code>y</code> from the given range <code>[l, r]</code> such that <code>x XOR y</code> is maximum.</p>
<p>This is what I did till now:</p>
<pre><code>def maxXOR(x, l, r):
max_ = 0
for y in range(l, r+1):
temp = x^y
if temp>max_:
max_ = temp
return max_
</code></pre>
<p>But it is quite slow. How can I optimise it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T20:46:31.047",
"Id": "392937",
"Score": "0",
"body": "Please include the problem statement. I have a feeling that one vital piece is missing."
}
] | [
{
"body": "<p>As to the algorithm</p>\n\n<p>The general rule here is don't search when you can calculate.</p>\n\n<p>XOR is fundamentally a bitwise operation. Think about what the XOR operation is doing, on a bit by bit basis. </p>\n\n<p>First, consider a simpler problem where you have to maximise the result wit... | {
"AcceptedAnswerId": "203793",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T17:15:10.303",
"Id": "203788",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"bitwise"
],
"Title": "Maximise XOR of two elements"
} | 203788 |
<p>I wrote this code for finding the \$k\$th-to-last element in a singly linked list.</p>
<pre><code>class Node:
def __init__(self, v = None, next = None):
self.v = v
self.next = next
a = Node("Australian Sheperd")
b = Node("Beagle")
c = Node("Cairne Terrier")
d = Node("Dobermann")
e = Node("English Mastiff")
a.next = b
b.next = c
c.next = d
d.next = e
count = 1
def kthToLastNode(k, root):
global count
if root.next:
count = kthToLastNode(k, root.next)
if count == k:
print(root.v)
return count + 1
</code></pre>
<p>For example:</p>
<pre><code>>>> kthToLastNode(3,a)
Cairne Terrier
6
</code></pre>
<p>When called on a list with \$n\$ nodes, the code goes all the way through the list, recursing \$n\$ times, using \$\Theta(n)\$ stack space, and returning \$n\$ times. Is there a way to improve the space performance of the function?</p>
| [] | [
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>There is no docstring. What does <code>kthToLastNode</code> do? What does it return? A docstring would explain that you have to pass <code>k=1</code> to get the last item, <code>k=2</code> to get the second-to-last item, etc.</p></li>\n<li><p>It would be more useful... | {
"AcceptedAnswerId": "203868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T20:54:24.387",
"Id": "203792",
"Score": "3",
"Tags": [
"python",
"linked-list",
"recursion"
],
"Title": "Find the kth-to-last element of a singly linked list"
} | 203792 |
<p>The following function uses a cartesian system and has an agent who moves on the table like: F - forward, L - turn left, R - turn right.</p>
<p>The code works fine but I would like to make it more efficient:</p>
<pre><code>import java.util.Scanner;
public class HelloWorld {
public static void main (String[] args) {
int x = 0, y = 0; //initial coordinates
int direction = 0; //initial direction
Scanner scanner = new Scanner(System.in);
System.out.print("Introduce the command: ");
String inputString = scanner.nextLine(); //get the command
for (int i = 0; i < inputString.length(); i++){
char c = inputString.charAt(i); //breaking the string into chars
if(c == 'l') { //determining the direction
direction++;
} else if (c == 'r') {
direction--;
} else if (c == 'f') {
if(direction < 0) {
direction +=4;
}
if(direction % 4 ==0) { //moving forward in the wanted direction
y++;
} else if (direction % 4 ==1) {
x--;
} else if (direction % 4 == 2) {
y--;
} else if(direction % 4 == 3) {
x++;
}
}
}
System.out.println("Result: ["+x+","+y+"]");
}
}
</code></pre>
| [] | [
{
"body": "<p>Consider using two variables — an <em>x</em> and a <em>y</em> component — to store the direction. The left and right turns are based on <a href=\"https://en.wikipedia.org/wiki/Cross_product\" rel=\"nofollow noreferrer\">cross product principles</a>.</p>\n\n<p>Then, each forward move can be done u... | {
"AcceptedAnswerId": "203797",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T22:23:16.533",
"Id": "203795",
"Score": "1",
"Tags": [
"java",
"algorithm"
],
"Title": "Agent that steps and turns on a grid"
} | 203795 |
<p>I've been spending some time learning Rust and I came across the <a href="http://cryptopals.com/" rel="nofollow noreferrer">Cryptopals Challenges</a>.
This is my implementation of challenge 1</p>
<blockquote>
<p>Convert hex to base64 The string:</p>
<pre><code>49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
</code></pre>
<p>Should produce:</p>
<pre><code>SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
</code></pre>
<p>So go ahead and make that happen. You'll need to use this code for the
rest of the exercises.</p>
<p>Cryptopals Rule: Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing.</p>
</blockquote>
<p>I did go ahead and pull in a <a href="https://crates.io/crates/base64" rel="nofollow noreferrer">crate for handling base64 encoding</a>. It didn't seem important to implement that myself.</p>
<pre><code>mod basics {
extern crate base64;
use self::base64::encode;
pub fn hex_to_base64(hex: &str) -> String {
encode(&hex_to_bytes(hex))
}
pub fn hex_to_bytes(hex: &str) -> Vec<u8> {
hex.chars()
.collect::<Vec<_>>() //convert to slice-able
.chunks(2) //each char is one nibble
.map(|byte| byte.iter().collect::<String>())
.map(|byte| u8::from_str_radix(&byte[..], 16).unwrap())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_convert_hex_to_base64() {
let hex_as_string =
"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let base64_as_string =
"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
assert_eq!(hex_to_base64(hex_as_string), base64_as_string);
}
#[test]
fn ff_byte_hex_string_to_byte_vector() {
let hex = "FF";
assert_eq!(vec![0xFF], hex_to_bytes(hex));
}
#[test]
fn single_byte_hex_string_to_byte_vector() {
let hex = "2A";
assert_eq!(vec![0x2A], hex_to_bytes(hex));
}
#[test]
fn multibyte_hex_string_to_byte_vector() {
let hex = "2ABE";
assert_eq!(vec![0x2A, 0xBE], hex_to_bytes(hex));
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T23:53:45.860",
"Id": "392940",
"Score": "0",
"body": "Related: [Hex string to Base64](https://codereview.stackexchange.com/q/147670/32521)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T23:58:10.120"... | [
{
"body": "<pre><code>pub fn hex_to_base64(hex: &str) -> String {\n encode(&hex_to_bytes(hex))\n</code></pre>\n\n<p>I would not <code>use self::base64::encode</code> and instead refer to <code>base64::encode</code> here so that it is clearer what is being encoded.</p>\n\n<pre><code>}\n\npub fn hex... | {
"AcceptedAnswerId": "204285",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T23:42:35.150",
"Id": "203796",
"Score": "2",
"Tags": [
"programming-challenge",
"rust",
"base64"
],
"Title": "Convert hex to base64 (Cryptopals challenge 1)"
} | 203796 |
<p><a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/" rel="noreferrer">Prompt:</a></p>
<blockquote>
<p>Given a string containing digits from 2-9 inclusive, return all
possible letter combinations that the number could represent.</p>
<p>A mapping of digit to letters (just like on the telephone buttons) is
given below. Note that 1 does not map to any letters.</p>
</blockquote>
<p>I'm a relatively new LeetCoder and I feel pretty good about solving this problem. What are some obvious improvements that I could be making to improve the runtime or approach towards this problem or other problems in general?</p>
<pre><code>public IList<string> LetterCombinations(string digits)
{
string[] ph = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
List<string> result = new List<string>();
if (digits == null || digits.Length == 0) return result;
int len = ph[digits[0] - '0'].Length;
for (int i = 0; i < len; i++)
{
GetCombos(digits, "", i, ref result, digits.Length);
}
return result;
}
public void GetCombos(string inputDigits, string curVariation, int charIndex, ref List<string> resultList, int length)
{
string[] phone = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
if (curVariation.Length != length)
{
char ch = phone[inputDigits[0] - '0'][charIndex];
curVariation += ch;
}
if (curVariation.Length == length)
{
resultList.Add(curVariation);
return;
}
string newInput = inputDigits.Substring(1, inputDigits.Length - 1);
if (newInput == "") return;
int numChars = phone[newInput[0] - '0'].Length;
for (int i = 0; i < numChars; i++)
{
GetCombos(newInput, curVariation, i, ref resultList, length);
}
}
</code></pre>
| [] | [
{
"body": "<p>There is only one thing I really don't like:</p>\n\n<p>You have the same array instantiated in two different places (the <code>phone/ph</code> array). Here it's fairly simple and easy to maintain, but IRL you should never do that.</p>\n\n<p>You have two options to resolve this:</p>\n\n<p>1) Create... | {
"AcceptedAnswerId": "203829",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T00:24:42.190",
"Id": "203800",
"Score": "5",
"Tags": [
"c#",
"algorithm",
"programming-challenge",
"recursion",
"combinatorics"
],
"Title": "Finding all possible letter combinations from an inputted phone number"
} | 203800 |
<p>I am trying to implement the observer pattern for a stock exchange scenario. Multiple stocks can be registered at a stock exchange. There will be stock observers who are observing some specific stocks. Please advise how this implementation can be improved.</p>
<p>stock_exchange.hpp</p>
<pre><code>#ifndef STOCK_EXCHANGE_HPP
#define STOCK_EXCHANGE_HPP
#include "stock_observer.hpp"
#include "stock.hpp"
#include<unordered_map>
#include<string>
#include<list>
class Stock_Observer;
class Stock;
class Stock_Exchange
{
std::unordered_map<std::string, Stock*> registered_stocks;
std::unordered_map<std::string, std::list<Stock_Observer*>> stock_observers;
public:
void notify_observers(std::string stock_name);
void unregister_observer(Stock_Observer& so, std::string stock_name);
void register_observer(Stock_Observer& so, std::string stock_name);
void add_stock(Stock& new_stock);
void remove_stock(Stock& s);
Stock& get_stock(std::string stock_name);
};
#endif // STOCK_EXCHANGE_HPP
</code></pre>
<p>stock_exchange.cpp</p>
<pre><code>#include "stock_exchange.hpp"
#include "stock_observer.hpp"
#include<algorithm>
void Stock_Exchange::add_stock(Stock& new_stock)
{
registered_stocks[new_stock.get_name()] = &new_stock;
}
void Stock_Exchange::remove_stock(Stock& s)
{
registered_stocks.erase(s.get_name());
stock_observers.erase(s.get_name()); //Memory leak!!!
}
Stock& Stock_Exchange::get_stock(std::string stock_name)
{
return *registered_stocks[stock_name];
}
void Stock_Exchange::register_observer(Stock_Observer& observer, std::string stock_name)
{
stock_observers[stock_name].push_back(&observer);
}
void Stock_Exchange::unregister_observer(Stock_Observer& observer, std::string stock_name)
{
auto l = stock_observers[stock_name];
l.erase(std::find(l.begin(), l.end(),&observer));
}
void Stock_Exchange::notify_observers(std::string stock_name)
{
for(auto o : stock_observers[stock_name])
{
o->notify(stock_name);
}
}
</code></pre>
<p>stock_observer.hpp</p>
<pre><code>#ifndef STOCK_OBSERVER_HPP
#define STOCK_OBSERVER_HPP
#include "stock.hpp"
#include "stock_exchange.hpp"
#include<string>
class Stock_Exchange;
class Stock_Observer
{
static int id_sequence;
int id;
Stock_Exchange* se;
public:
Stock_Observer(Stock_Exchange* s)
{
se = s;
id = id_sequence++;
}
void notify(std::string stock_name);
};
#endif // STOCK_OBSERVER_HPP
</code></pre>
<p>stock_observer.cpp</p>
<pre><code>#include "stock_observer.hpp"
#include<iostream>
int Stock_Observer::id_sequence = 1;
void Stock_Observer::notify(std::string stock_name)
{
std::cout << "Object " << id << " notified about " << stock_name << std::endl;
}
</code></pre>
<p>stock.hpp</p>
<pre><code>#ifndef STOCK_HPP
#define STOCK_HPP
#include "stock_exchange.hpp"
#include<string>
class Stock_Exchange;
class Stock
{
std::string name;
double price;
Stock_Exchange* se;
public:
Stock(Stock_Exchange* s, std::string stock_name, double stock_price)
{
se = s;
name = stock_name;
price = stock_price;
}
std::string get_name();
void set_price(double p);
};
#endif // STOCK_HPP
</code></pre>
<p>stock.cpp</p>
<pre><code>#include "stock.hpp"
std::string Stock::get_name()
{
return name;
}
void Stock::set_price(double p)
{
price = p;
se->notify_observers(this->name);
}
</code></pre>
<p>main.cpp</p>
<pre><code>#include<iostream>
#include "stock_exchange.hpp"
#include "stock_observer.hpp"
#include "stock.hpp"
int main()
{
Stock_Exchange se;
Stock_Observer so1(&se), so2(&se);
Stock infy(&se,"INFY",1234.33);
Stock tcs(&se,"TCS",1100);
Stock sbi(&se,"SBI",2312.33);
se.register_observer(so1,"INFY");
se.register_observer(so2,"INFY");
se.register_observer(so1,"TCS");
infy.set_price(1250.33);
tcs.set_price(999.32);
sbi.set_price(2300.00);
}
</code></pre>
| [] | [
{
"body": "<h2>Make immutable class members const</h2>\n\n<p>If you have a member of a class that is set once at construction time, but will never change, then make it const. For example, in <code>Stock</code>:</p>\n\n<pre><code>class Stock {\n const std::string name;\n ...\n public:\n Stock(..., std::strin... | {
"AcceptedAnswerId": "203825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T04:25:09.123",
"Id": "203802",
"Score": "3",
"Tags": [
"c++",
"observer-pattern"
],
"Title": "Implementing the observer pattern for a stock exchange scenario"
} | 203802 |
<p>Recently I've built a service at my work to generate tokens with JWT (JSON Web Token) "protocol", I would like to show you the code and to get comments from you if that's good enough and if there are things to improve.</p>
<p>The service contains 2 folders and 4 classes.</p>
<ol>
<li>Models Folder
<ul>
<li>IAuthContainerModel (Interface)</li>
<li>JWTContainerModel (Implementation)</li>
</ul></li>
<li>Managers Folder
<ul>
<li>IAuthService (Interface)</li>
<li>JWTService (Implementation)</li>
</ul></li>
</ol>
<hr>
<ul>
<li>IAuthContainerModel</li>
</ul>
<p>Code:</p>
<pre><code>using System.Security.Claims;
namespace AuthenticationService.Models
{
public interface IAuthContainerModel
{
#region Members
string SecretKey { get; set; }
string SecurityAlgorithm { get; set; }
Claim[] Claims { get; set; }
int ExpireMinutes { get; set; }
#endregion
}
}
</code></pre>
<ul>
<li>JWTContainerModel</li>
</ul>
<p>Code: </p>
<pre><code>using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
namespace AuthenticationService.Models
{
public class JWTContainerModel : IAuthContainerModel
{
#region Public Methods
public int ExpireMinutes { get; set; } = 10080; // 7 days.
public string SecretKey { get; set; } = "TW9zaGVFcmV6UHJpdmF0ZUtleQ=="; // This secret key should be moved to some configurations outter server.
public string SecurityAlgorithm { get; set; } = SecurityAlgorithms.HmacSha256Signature;
public Claim[] Claims { get; set; }
#endregion
}
}
</code></pre>
<p>ExpireMinutes is a default value and SecretKey is also a default value, of course the secret key will be in the configurations section inside the server</p>
<ul>
<li>IAuthService</li>
</ul>
<p>Code:</p>
<pre><code>using System.Security.Claims;
using System.Collections.Generic;
using AuthenticationService.Models;
namespace AuthenticationService.Managers
{
public interface IAuthService
{
string SecretKey { get; set; }
bool IsTokenValid(string token);
string GenerateToken(IAuthContainerModel model);
IEnumerable<Claim> GetTokenClaims(string token);
}
}
</code></pre>
<ul>
<li>JWTService</li>
</ul>
<p>Code:</p>
<pre><code>using System;
using System.Security.Claims;
using System.Collections.Generic;
using AuthenticationService.Models;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace AuthenticationService.Managers
{
public class JWTService : IAuthService
{
#region Members
/// <summary>
/// The secret key we use to encrypt out token with.
/// </summary>
public string SecretKey { get; set; }
#endregion
#region Constructor
public JWTService(string secretKey)
{
SecretKey = secretKey;
}
#endregion
#region Public Methods
/// <summary>
/// Validates whether a given token is valid or not, and returns true in case the token is valid otherwise it will return false;
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public bool IsTokenValid(string token)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentException("Given token is null or empty.");
TokenValidationParameters tokenValidationParameters = GetTokenValidationParameters();
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
try
{
ClaimsPrincipal tokenValid = jwtSecurityTokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken validatedToken);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Generates token by given model.
/// Validates whether the given model is valid, then gets the symmetric key.
/// Encrypt the token and returns it.
/// </summary>
/// <param name="model"></param>
/// <returns>Generated token.</returns>
public string GenerateToken(IAuthContainerModel model)
{
if (model == null || model.Claims == null || model.Claims.Length == 0)
throw new ArgumentException("Arguments to create token are not valid.");
SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(model.Claims),
Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(model.ExpireMinutes)),
SigningCredentials = new SigningCredentials(GetSymmetricSecurityKey(), model.SecurityAlgorithm)
};
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
string token = jwtSecurityTokenHandler.WriteToken(securityToken);
return token;
}
/// <summary>
/// Receives the claims of token by given token as string.
/// </summary>
/// <remarks>
/// Pay attention, one the token is FAKE the method will throw an exception.
/// </remarks>
/// <param name="token"></param>
/// <returns>IEnumerable of claims for the given token.</returns>
public IEnumerable<Claim> GetTokenClaims(string token)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentException("Given token is null or empty.");
TokenValidationParameters tokenValidationParameters = GetTokenValidationParameters();
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
try
{
ClaimsPrincipal tokenValid = jwtSecurityTokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken validatedToken);
return tokenValid.Claims;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Private Methods
private SecurityKey GetSymmetricSecurityKey()
{
byte[] symmetricKey = Convert.FromBase64String(SecretKey);
return new SymmetricSecurityKey(symmetricKey);
}
private TokenValidationParameters GetTokenValidationParameters()
{
return new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = GetSymmetricSecurityKey()
};
}
#endregion
}
}
</code></pre>
<hr>
<p>What do you say about this code? is it implemented correctly? would you fix it in some way? I will be happy to hear your opinions!</p>
| [] | [
{
"body": "<p>It looks fine to me, I just a few minor suggestions.</p>\n\n<blockquote>\n<pre><code>catch (Exception ex)\n{\n throw ex;\n}\n</code></pre>\n</blockquote>\n\n<p>You probably left this in by accident, but you're better off without a catch block if all you're going to do is re-throw. And if you a... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T06:53:09.000",
"Id": "203807",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"authentication",
"jwt"
],
"Title": "JWT Authentication Service"
} | 203807 |
<h1>Problem</h1>
<p>I use Emacs for Python development along with several linters. When I activate a Python virtual environment (venv) from within Emacs, I would like to set the linter binaries according to the following rules:</p>
<ol>
<li>If the venv has a particular linter installed, use it</li>
<li>If the venv does not have a particular linter, use the one in a pre-specified, default venv</li>
<li>If the linter does not exist in either the active venv or the default venv, set the linter binary to <code>nil</code></li>
</ol>
<p>For example, let's say I activate a venv called <code>my_venv</code> that has <code>pylint</code> installed, but no <code>flake8</code>. <code>flake8</code> is however installed in my default <code>linters</code> venv. After activating <code>my_venv</code>, the linters that will be used are</p>
<ul>
<li>pylint -- my_venv</li>
<li>flake8 -- linters</li>
</ul>
<h3>Purpose</h3>
<p>The reason for implementing this is that I develop Python on multiple machines that share a single, version-controlled <code>init.el</code> file. I do not want to guarantee that I have the same Python binaries and venvs across these machines; this implementation helps decouple my Emacs setup from the Python venvs that are present on a machine.</p>
<h3>Additional info</h3>
<ul>
<li>The code will go inside my <code>init.el</code> file</li>
<li>I use <a href="http://www.flycheck.org/en/latest/" rel="noreferrer">flycheck</a> as the interface between Emacs and the linters</li>
<li>I use <a href="https://github.com/jorgenschaefer/pyvenv" rel="noreferrer">pyvenv</a> for Python virtual environments in Emacs</li>
</ul>
<h1>Code</h1>
<pre><code>(defvar linter-execs '((flycheck-python-flake8-executable "bin/flake8")
(flycheck-python-pylint-executable "bin/pylint")
(flycheck-python-pycompile-executable "bin/python")))
(defvar default-linter-venv-path (concat (getenv "WORKON_HOME") "/linters/"))
(defun switch-linters ()
"Switch linter executables to those in the current venv.
If the venv does not have any linter packages, then they will be
set to those in the `default-linter-venv-path` venv. If these do
not exist, then no linter will be set."
(dolist (exec linter-execs)
(let ((venv-linter-bin (concat pyvenv-virtual-env (nth 1 exec)))
(default-linter-bin (concat default-linter-venv-path (nth 1 exec)))
(flycheck-var (nth 0 exec)))
(cond ((file-exists-p venv-linter-bin)
(set flycheck-var venv-linter-bin))
((file-exists-p default-linter-bin)
(set flycheck-var default-linter-bin))
(t (set flycheck-var nil))))))
(add-hook 'pyvenv-post-activate-hooks 'switch-linters)
</code></pre>
<h3>Explanation</h3>
<ul>
<li><code>linter-execs</code> is a list of two-element lists. The first element of an entry is the <code>flycheck</code> variable that contains the path of a linter binary. The second element is the relative path of the binary from within the venv.</li>
<li>The default linter venv is <code>$WORKON_HOME/linters</code></li>
<li><code>switch-linters</code> is the call-back function attached to <code>pyvenv-post-activate-hooks</code></li>
<li>The conditional checks for the presence of the linter binary files, first in the current venv and next in the default venv. Failing these, it sets the binary to <code>nil</code> in the line <code>(t (set flycheck-var nil))</code></li>
</ul>
<h1>Specific questions</h1>
<ul>
<li>Is this idiomatic elisp, or is it too "Pythonic"?</li>
<li>Is <code>linter-execs</code> the proper way to implement a list of tuples in elisp?</li>
</ul>
| [] | [
{
"body": "<ol>\n<li><p>It would be a good idea to write a docstring for the <code>defvar</code>'d variables like <code>linter-execs</code>. The explanations in the post would make an excellent start, for example:</p>\n\n<pre><code>(defvar linter-execs '((flycheck-python-flake8-executable \"bin/flake8\")\n ... | {
"AcceptedAnswerId": "203814",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T08:03:15.203",
"Id": "203808",
"Score": "6",
"Tags": [
"elisp"
],
"Title": "Hook to switch the linter binaries in Emacs Lisp according to virtual environment"
} | 203808 |
<p>I'm creating an application that reads in data from a CSV file and creates an XML file using LXML. The below code works as expected. However, before I develop it further I would like to refactor it and make it more DRY. I will need to start creating the additional XML snippets for the other code types in the CSV file and I believe, in its current state, there is too much duplication.</p>
<p>I am attempting to learn Python while using a real user case, please can someone provide any guidance on how I could make the code more eloquent and more DRY. Do I need to be using classes and functions or is my approach OK for the type of file (XML) and creating?</p>
<pre><code>import pandas as pd
from lxml import etree as et
import uuid
df = pd.read_csv('assets.csv', sep=',')
root = et.Element('SignallingSchemeData', xmlns='boo')
timeframe = et.SubElement(root,'TimeFrame')
timeframe.attrib["fileUID"] = str(uuid.uuid4())
timeframe.attrib["name"] = str("timeframe 1")
for index, row in df.iterrows():
if row['CODE'] == 'S1':
equipment = et.SubElement(root, 'Equipment')
signalEquipment = et.SubElement(equipment, 'SignalEquipment')
signalEquipment.attrib["fileUID"] = str(row["ID"])
signalEquipment.attrib["name"] = str(row["DESC"])
equipment = et.SubElement(root, 'Equipment')
equipmentSupportEquipment = et.SubElement(equipment, 'EquipmentSupportEquipment')
equipmentSupportEquipment.attrib["fileUID"] = str(uuid.uuid4())
equipmentSupportReference = et.SubElement(signalEquipment, 'EquipmentSupportReference').text = equipmentSupportEquipment.attrib["fileUID"]
else:
equipment = et.SubElement(root, 'Equipment')
source = et.SubElement(root, 'Source')
view = et.SubElement(root, 'View')
view.attrib["fileUID"] = str(uuid.uuid4())
view.attrib["name"] = str('Coordinates')
for index, row in df.iterrows():
viewCoordinatesList = et.SubElement(view, 'ViewCoordinatesList')
viewCoordinates = et.SubElement(viewCoordinatesList, 'ViewCoordinates')
itemFileUID = et.SubElement(viewCoordinates, 'ItemFileUID')
itemFileUID.attrib['fileUID'] = str(row['ID'])
viewCoordinatePairLon = et.SubElement(viewCoordinates, 'ViewCoordinatePair', name = 'longittude')
viewCoordinatePairLon.attrib['Value'] = str(row['Y'])
viewCoordinatePairLat = et.SubElement(viewCoordinates, 'ViewCoordinatePair', name = 'latitude')
viewCoordinatePairLat.attrib['Value'] = str(row['X'])
viewCoordinatePairH = et.SubElement(viewCoordinates, 'ViewCoordinatePair', name = 'height')
viewCoordinatePairH.attrib['Value'] = str(row['Z'])
et.ElementTree(root).write('test.xml', pretty_print=True, xml_declaration = True, encoding='UTF-8', standalone = None)
</code></pre>
<p>assets.csv is as follows:</p>
<pre><code>ID,CODE,ELR,TRID,DIR,MILEAGE,X,Y,Z,DESC,IMAGE
30734,S1,LEC1,1100,,008+0249 (9-1497),518169.12,185128.27,37.52,,Asset30734.jpg
31597,S10,LEC1,1100,,008+0286 (9-1460),518151.38,185157.1,36.7,IRJ at 8 miles and 0289 yards,Asset31597.jpg
31598,S10,LEC1,1100,,008+0286 (9-1460),518150.4,185156.11,36.7,IRJ at 8 miles and 0289 yards,Asset31598.jpg
31596,S10,LEC1,1100,,008+0287 (9-1458),518149.76,185157.14,36.7,IRJ at 8 miles and 0289 yards,Asset31596.jpg
</code></pre>
| [] | [
{
"body": "<p>The real issue with repeating yourself here is that you are iterating over your dataframe twice when you don't have to. Fortunately, the devs for <code>lxml</code> make the elements behave like lists, so you can create everything that you need to in one go, then just do <code>root.append(sub_eleme... | {
"AcceptedAnswerId": "230516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T08:58:31.100",
"Id": "203811",
"Score": "8",
"Tags": [
"python",
"csv",
"xml",
"pandas",
"lxml"
],
"Title": "Python CSV to XML converter"
} | 203811 |
<blockquote>
<p><strong>Following idea:</strong></p>
<p>You have a LCD-display with 2 rows. </p>
<p><a href="https://i.stack.imgur.com/jO1t5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jO1t5.jpg" alt="enter image description here"></a></p>
<ol>
<li><p>You write the first line of a "text" to the second row. Then you clean the screen.</p></li>
<li><p>After a delay you write the first line to the first row and a the second line of the text to the second row. Then follows another clean
and delay.</p></li>
<li><p>Then you write the second line to the first row and the third line to the second row. And so on ...</p></li>
</ol>
<p>When the end of the text is reached the whole process starts again
from the beginning.</p>
<p>That way the impression of an "vertical moving" text is accomplished.</p>
</blockquote>
<p>The code I have written:</p>
<pre><code>#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setDisplay(String lineValue, int lineNumber, int waitUntilClear, boolean clearScreen) {
lcd.setCursor(0, lineNumber),
lcd.print(lineValue);
delay(waitUntilClear);
if (clearScreen == true) {
lcd.clear();
}
}
void setup() {
lcd.begin(16, 2);
}
void loop() {
const int DELAY = 3000;
const int COUNT_ELEMENTS = 12;
String messages[COUNT_ELEMENTS] = {
"",
"Furniture Store",
" MEYER & MILLER",
"",
" Contact us!",
"",
" -- Email ----- ",
"demo@example.com",
"",
" -- Phone ----- ",
" 000 123456",
""
};
for (int i = 0; i < COUNT_ELEMENTS - 1; i++) {
setDisplay(messages[i], 0, 0, false);
setDisplay(messages[i + 1], 1, DELAY, true);
}
}
</code></pre>
<p>It works fine and by using an additional function I could avoid code redundancies mostly. If someone has an idea how to improve my code or even doing it completely different in a better way, then I would appreciate his/her comment or answer.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T10:16:32.950",
"Id": "392960",
"Score": "0",
"body": "You can [include images](https://codereview.stackexchange.com/editing-help#comment-formatting) in questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "... | [
{
"body": "<p><code>waitUntilClear</code> is always <code>0</code> when <code>clearScreen</code> is <code>false</code> then boolean flag is redundant:</p>\n\n<pre><code>void setDisplay(String lineValue, int lineNumber, unsigned long msToWaitBeforeClear) {\n lcd.setCursor(0, lineNumber),\n lcd.print(lineValue)... | {
"AcceptedAnswerId": "203863",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T10:10:54.403",
"Id": "203813",
"Score": "4",
"Tags": [
"c++",
"arduino"
],
"Title": "Vertical \"moving\" text on a LCD-display"
} | 203813 |
<p>I wanted to implement my own runtime error class in C++, that could provide more meaningful information on where the error occurred than <code>std::runtime_error</code> does.</p>
<p>I decided to use <code>boost::stacktrace</code> to generate a stack trace, appended to the exception message.</p>
<p>Anyway, this is my code:</p>
<pre><code>/**
\brief Represents a runtime error.
Equivalent of std::runtime_error, but contains a stacktrace
generated by Boost.
*/
class Exception : public std::runtime_error
{
public:
/**
\brief Returns error description.
If the backtrace was generated successfully,
returns the message along with stack trace.
Otherwise, behaves like std::runtime_error::what().
*/
const char *what( ) const noexcept override
{
if ( has_backtrace )
return message.c_str( );
else
return std::runtime_error::what( );
}
/**
\brief Constructs an exception, generates a backtrace if possible.
\param cmessage The error description.
*/
Exception( const char *cmessage ) :
std::runtime_error( cmessage ) // std::runtime_error will store the original message
{
// Attempt to generate stacktrace
try
{
std::stringstream buffer;
buffer << cmessage << std::endl << boost::stacktrace::stacktrace( );
message = buffer.str( );
has_backtrace = true;
}
catch ( std::exception &ex )
{
has_backtrace = false;
}
}
protected:
bool has_backtrace; //!< Determines if backtrace is present
std::string message; //!< Contains the user message along with backtrace.
};
</code></pre>
<p>I can tell it works on this simple example</p>
<pre><code>void foo( )
{
throw Exception( "some message" );
}
void bar( )
{
foo( );
}
int main( )
{
try
{
bar( );
}
catch ( std::exception &ex )
{
std::cerr << ex.what( );
}
return 0;
}
</code></pre>
<p>because it generates following message:</p>
<pre><code>some message
0# Exception::Exception(char const*) in ./ex
1# foo() in ./ex
2# bar() in ./ex
3# main in ./ex
4# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
5# _start in ./ex
</code></pre>
<p>However, what I'd like to know is if my code isn't too complicated
as for an exception class and if it properly handles possible stack trace
generator exceptions and properly falls back to <code>std::runtime_error</code> functionality. </p>
<p>Also, is there some important property/method that all exception classes should have, that I had overlooked and forgot to implement? Maybe the whole idea of having such class is bad in general and I should use some other solution?</p>
<p>Other suggestions are obviously welcome too.</p>
| [] | [
{
"body": "<pre><code>Exception( const char *cmessage ) :\n</code></pre>\n\n<p>I strongly recommend making this constructor <code>explicit</code>, so that you don't permit the user to accidentally write</p>\n\n<pre><code>void some_function(const Exception&);\n...\nsome_function(\"hello world\");\n</code></p... | {
"AcceptedAnswerId": "203827",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T15:38:40.990",
"Id": "203823",
"Score": "5",
"Tags": [
"c++",
"error-handling",
"exception"
],
"Title": "Custom C++ exception class with stack trace generation"
} | 203823 |
<p>I perform a mean blur on a <code>number[][]</code>-array (called <code>grid</code> in the code). I iterate the array, and calculate average values from adjacent "cells".
The kernel size defines how many adjacent values are used for average calculation.</p>
<pre><code>/**
* Performs a mean blur with a given kernel size.
* @param {number[][]} grid - Data grid holding values to blur.
* @param {number} kernelSize - Describes the size of the "blur"-cut for each cell.
*/
static MeanBlur(grid, kernelSize) {
// Result
let newGrid = [];
// Iterate original grid
for (let row = 0; row < grid.length; row++) {
let newRow = [];
for (let col = 0; col < grid[row].length; col++) {
let adjacentValues = [];
// Get all adjacent values
for (let i = 1; i <= kernelSize; i++) {
adjacentValues = adjacentValues.concat(this._getAdjacentValues(row, col, i, grid));
}
// Calculate average value
const average = adjacentValues.reduce((a, b) => a + b, 0) / adjacentValues.length;
// add average value to the current row
newRow.push(average);
}
newGrid.push(newRow);
}
return newGrid;
}
/**
* Return all adjacent values of a cell in a `number[][]`-array.
* The amount of adjacent value depends on the kernel size.
* @param {number} row - Describes the cell's row position.
* @param {number} col - Describes the cell's column position.
* @param {number} kernelSize - The kernel size.
* @param {number[][]} grid - Original data grid.
*/
static _getAdjacentValues(row, col, kernelSize, grid) {
if (kernelSize < 1) {
throw "Kernel size value should be at least 1.";
}
let adjacentValues = [];
// north
if (row - kernelSize >= 0) {
adjacentValues.push(grid[row - kernelSize][col]);
}
// north-east
if (row - kernelSize >= 0 && col + kernelSize < grid[row].length) {
adjacentValues.push(grid[row - kernelSize][col + kernelSize]);
}
// east
if (col + kernelSize < grid[row].length) {
adjacentValues.push(grid[row][col + kernelSize]);
}
// south-east
if (row + kernelSize < grid.length && col + kernelSize < grid[row].length) {
adjacentValues.push(grid[row + kernelSize][col + kernelSize]);
}
// south
if (row + kernelSize < grid.length) {
adjacentValues.push(grid[row + kernelSize][col]);
}
// south-west
if (row + kernelSize < grid.length && col - kernelSize >= 0) {
adjacentValues.push(grid[row + kernelSize][col - kernelSize]);
}
// west
if (col - kernelSize >= 0) {
adjacentValues.push(grid[row][col - kernelSize]);
}
// north-west
if (row - kernelSize >= 0 && col - kernelSize >= 0) {
adjacentValues.push(grid[row - kernelSize][col - kernelSize]);
}
return adjacentValues;
}
</code></pre>
<p>What I am most concerned with is <code>_getAdjacentValues</code>. I think there has to be a more convenient way to get adjacent values without including values at implausible indices.</p>
<p><a href="https://i.stack.imgur.com/C2ujE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C2ujE.png" alt="enter image description here"></a></p>
<p>What I mean is that i.e. at the grid position <code>(0, 0)</code> even with a kernel size of 1, values like <code>(-1, -1)</code> will be checked automatically by a loop.</p>
<p><strong>Edit:</strong>
I was asked for clarification on how the kernel size actually is supposed to work.
Assuming that I want to calculate the value for the current position (black cell). With a kernel size of 1 I would include all green cells for average value calculation. With a kernel size of 2 I would include all green and blue cell values. And with a kernel size of 3 all orange, blue and green cell values will be used for average calculation.</p>
<p><a href="https://i.stack.imgur.com/DAChF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DAChF.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:37:33.313",
"Id": "393049",
"Score": "0",
"body": "Came here via HNQ expecting not just a blur, but a \"really mean blur\" from the title"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T15:03:11.99... | [
{
"body": "<p>Since you not only need adjacent values but also the number of adjacent cells, I do not think that there's a way to work around conditions that cover the corner cases. However, you can make a case differentiation between border cells and inner cells and use two seperate code paths for it. One with... | {
"AcceptedAnswerId": "203840",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T16:12:40.623",
"Id": "203826",
"Score": "9",
"Tags": [
"javascript",
"array",
"signal-processing"
],
"Title": "Performing a \"mean blur\""
} | 203826 |
<p>some words in forehand: Unfortunately this post is very long, thus I decided to put the whole and compilable code into an online compiler. The link is at the end of this post.</p>
<p>In the last few days I have been working on my new graph searcher implementation. I tried to create a similar interface like the <code>std::search</code> functions and implemented each algorithm as a separate searcher. At least that was the first idea. After I have implemented the first searcher (Breadth first search) I broke it down and implemented the base part as a <code>GenericSearcher</code> class with some template parameters.</p>
<h2>The searcher objects</h2>
<p>In the end four different <code>make_...</code> functions were created:</p>
<ul>
<li><code>make_breadth_first_searcher</code></li>
<li><code>make_depth_first_searcher</code></li>
<li><code>make_dijkstra_searcher</code></li>
<li><code>make_astar_searcher</code></li>
</ul>
<p>As already mentioned, the <code>GenericSearcher</code>-class is the core of this implementation. It has an <code>operator()</code> overload and must return its last visited vertex (as an optional).</p>
<pre><code>template <class TVertexType, class TNodeData, class TNodeCreator, class TNodeCompare>
class GenericSearcher
{
public:
using NodeDataType = TNodeData;
using VertexType = TVertexType;
using NodeType = Node<TVertexType, TNodeData>;
explicit GenericSearcher(TNodeCreator _nodeCreator = TNodeCreator(), TNodeCompare _nodeComp = TNodeCompare()) :
m_NodeCreator(std::move(_nodeCreator)),
m_NodeComp(std::move(_nodeComp))
{
}
template <class TNeighbourSearcher, class TOpenList, class TClosedList>
std::optional<NodeType> operator ()(TNeighbourSearcher& _neighbourSearcher, TOpenList& _openList, TClosedList& _closedList)
{
if (std::empty(_openList))
return std::nullopt;
auto node = _openList.take_node(m_NodeComp);
_closedList.insert(node, m_NodeComp);
_neighbourSearcher(node,
[&node, &_openList, &_closedList, &nodeComp = m_NodeComp, &nodeCreator = m_NodeCreator]
(const auto& _vertex)
{
if (!_closedList.contains(_vertex))
{
_openList.insert({ _vertex, nodeCreator(node, _vertex) }, nodeComp);
}
}
);
return node;
}
private:
TNodeCreator m_NodeCreator;
TNodeCompare m_NodeComp;
};
</code></pre>
<p>There are two derived types, which only simplify the template deductions and the construction of the specific searchers:</p>
<pre><code>template <class TCostCalculator, class TVertexType, typename = std::enable_if_t<std::is_invocable_v<TCostCalculator, const TVertexType&, const TVertexType&>>>
using CostCalculatorResult = std::invoke_result_t<TCostCalculator, const TVertexType&, const TVertexType&>;
// generalization for breadth- and depth-first-searcher
template <class TVertexType, class TCostType, class TNodeCompare>
struct StaticCostSearcher :
public GenericSearcher<TVertexType, BaseNodeData<TVertexType, TCostType>, IncrementalCostChildNodeCreator<TCostType>, TNodeCompare>
{
private:
using super = GenericSearcher<TVertexType, BaseNodeData<TVertexType, TCostType>, IncrementalCostChildNodeCreator<TCostType>, TNodeCompare>;
public:
StaticCostSearcher(TNodeCompare _nodeComp) :
super({ { 1 }, { 0 } }, std::move(_nodeComp))
{}
};
// generalization for dijkstra- and astar-searcher
template <class TVertexType, class TCostCalculator, class THeuristicCalculator, class TNodeCompare, typename TCostType = detail::CostCalculatorResult<TCostCalculator, TVertexType>>
struct CalculatedCostSearcher :
public GenericSearcher<TVertexType, BaseNodeData<TVertexType, TCostType>, GenericNodeCreator<TCostCalculator, THeuristicCalculator>, TNodeCompare>
{
private:
using super = GenericSearcher<TVertexType, BaseNodeData<TVertexType, TCostType>, GenericNodeCreator<TCostCalculator, THeuristicCalculator>, TNodeCompare>;
static_assert(std::is_same_v<TCostType, detail::CostCalculatorResult<TCostCalculator, TVertexType>>,
"You are not allowed to change the TCostType template parameter.");
static_assert(std::is_same_v<detail::CostCalculatorResult<THeuristicCalculator, TVertexType>, detail::CostCalculatorResult<TCostCalculator, TVertexType>>,
"TCostCalculator and THeuristicCalculator must return the same type.");
public:
CalculatedCostSearcher(TCostCalculator _costCalculator, THeuristicCalculator _heuristicCalculator, TNodeCompare _nodeComp) :
super({ std::move(_costCalculator), std::move(_heuristicCalculator) }, std::move(_nodeComp))
{
}
};
</code></pre>
<p>And here are the make functions:</p>
<pre><code>template <class TVertexType, class TNodeCompare = std::less<>>
auto make_breadth_first_searcher(TNodeCompare _nodeComp = TNodeCompare())
{
return detail::StaticCostSearcher<TVertexType, int, TNodeCompare>(std::move(_nodeComp));
}
template <class TVertexType, class TNodeCompare = std::greater<>>
auto make_depth_first_searcher(TNodeCompare _nodeComp = TNodeCompare())
{
return detail::StaticCostSearcher<TVertexType, int, TNodeCompare>(std::move(_nodeComp));
}
template <class TVertexType, class TCostCalculator, class TNodeCompare = std::less<>>
auto make_dijkstra_searcher(TCostCalculator _costCalculator, TNodeCompare _nodeComp = TNodeCompare())
{
using CostType = detail::CostCalculatorResult<TCostCalculator, TVertexType>;
return detail::CalculatedCostSearcher<TVertexType, TCostCalculator, detail::ConstantCost<CostType>, TNodeCompare>(std::move(_costCalculator), { 0 }, std::move(_nodeComp));
}
template <class TVertexType, class TCostCalculator, class THeuristicCalculator, class TNodeCompare = std::less<>>
auto make_astar_searcher(TCostCalculator _costCalculator, THeuristicCalculator _heuristicCalculator, TNodeCompare _nodeComp = TNodeCompare())
{
return detail::CalculatedCostSearcher<TVertexType, TCostCalculator, THeuristicCalculator, TNodeCompare>(std::move(_costCalculator), std::move(_heuristicCalculator), std::move(_nodeComp));
}
</code></pre>
<h2>The algorithms:</h2>
<pre><code>namespace detail
{
template <class TVertexType, class TClosedList>
std::optional<std::vector<TVertexType>> _extract_path(const TVertexType& _vertex, const TClosedList& _closedList)
{
if (auto curNode = _closedList.find(_vertex))
{
std::vector<TVertexType> path{ _vertex };
while (curNode && curNode->parent)
{
path.emplace_back(*curNode->parent);
curNode = _closedList.find(*curNode->parent);
}
std::reverse(std::begin(path), std::end(path));
return path;
}
return std::nullopt;
}
template <class TVertexType, class UnaryFunction, class TNeighbourSearcher, class TPathFinder, class TOpenList, class TClosedList>
std::optional<TVertexType> _conditional_visit(const TVertexType& _from, UnaryFunction&& _func, TNeighbourSearcher& _neighbourSearcher, TPathFinder& _pathFinder, TOpenList& _openList, TClosedList& _closedList)
{
using NodeData = typename TPathFinder::NodeDataType;
assert(std::empty(_openList) && std::empty(_closedList));
_openList.insert({ _from, NodeData() }, std::less<>()); // because the openList will be empty, we can insert a default constructed node and pass a dummy compare function
while (auto current = _pathFinder(_neighbourSearcher, _openList, _closedList))
{
if (_func(*current))
return current->vertex;
}
return std::nullopt;
}
template <class TVertexType, class TCallable, typename = std::enable_if_t<std::is_invocable_r_v<bool, TCallable, const TVertexType&>>>
bool _reached_destination(const TVertexType& _current, TCallable&& _func)
{
return _func(_current);
}
template <class TVertexType>
bool _reached_destination(const TVertexType& _current, const TVertexType& _destination)
{
return _current == _destination;
}
} // namespace detail
template <class TVertexType, class UnaryFunction, class TNeighbourSearcher, class TPathFinder, class TOpenList = DefaultNodeMap<TPathFinder>, class TClosedList = DefaultNodeMap<TPathFinder>>
void visit(const TVertexType& _from, UnaryFunction&& _func, TNeighbourSearcher&& _neighbourSearcher, TPathFinder&& _pathFinder,
TOpenList _openList = TOpenList(), TClosedList _closedList = TClosedList())
{
auto condFunc = [&_func](const auto& _node)
{
_func(_node);
return false;
};
detail::_conditional_visit(_from, condFunc, _neighbourSearcher, _pathFinder, _openList, _closedList);
}
template <class TVertexType, class TDestination, class TNeighbourSearcher, class TPathFinder, class TOpenList = DefaultNodeMap<TPathFinder>, class TClosedList = DefaultNodeMap<TPathFinder>>
std::optional<std::vector<TVertexType>> find_path(const TVertexType& _from, TDestination&& _destination, TNeighbourSearcher&& _neighbourSearcher, TPathFinder&& _pathFinder,
TOpenList _openList = TOpenList(), TClosedList _closedList = TClosedList())
{
if (auto lastNode = detail::_conditional_visit(_from, [&_destination](const auto& _node) { return detail::_reached_destination(_node.vertex, _destination); }, _neighbourSearcher, _pathFinder, _openList, _closedList))
{
return detail::_extract_path(*lastNode, _closedList);
}
return std::nullopt;
}
</code></pre>
<p>The algorithms are the next part. There are currently two of them, but I can't imagine any other. At least they cover my needs very well. The <code>visit</code> function visits every reachable node; in which sequence depends on the passed searcher.
The <code>find_path</code> functions returns the path from starting point to the given destination - if there is any. My intention was to distinguish between <code>start == destination</code> and not reachable. Therefore I use again an <code>std::optional</code>.
As a little trick, I added the possibility to pass a function object as destination.</p>
<h2>The node objects</h2>
<pre><code>namespace graph
{
template <class TVertexType, class CostType>
struct BaseNodeData
{
std::optional<TVertexType> parent;
CostType cost;
friend bool operator <(const BaseNodeData& _lhs, const BaseNodeData& _rhs)
{
return _lhs.cost < _rhs.cost;
}
friend bool operator >(const BaseNodeData& _lhs, const BaseNodeData& _rhs)
{
return _lhs.cost > _rhs.cost;
}
};
template <class TVertexType, class CostType>
struct HeuristicNodeData
{
std::optional<TVertexType> parent;
CostType cost;
CostType heuristic;
int combined_cost() const
{
return cost + heuristic;
}
friend bool operator <(const HeuristicNodeData& _lhs, const HeuristicNodeData& _rhs)
{
return _lhs.combined_cost() < _rhs.combined_cost();
}
friend bool operator >(const HeuristicNodeData& _lhs, const HeuristicNodeData& _rhs)
{
return _lhs.combined_cost() > _rhs.combined_cost();
}
};
template <class TVertexType, class TNodeData>
struct Node
{
TVertexType vertex;
TNodeData data;
};
} // namespace graph
</code></pre>
<p>The Node struct is a combination of the location (the vertex) and the current data (cost, parent, ...). I like to call those properties by name, that's the reason why I avoided a <code>std::tuple</code> like structure. Perhaps that's a little bit old-school, but in my opinion it makes the code much easier to understand.</p>
<p>There are two different NodeData types:</p>
<ul>
<li>BaseNodeData</li>
<li>HeuristicNodeData</li>
</ul>
<p>I know, those names are horrible, perhaps anybody has better ideas? Three of the currently implemented searcher make use of the BaseNodeData; only the AStar uses the HeuristicNodeData objects.</p>
<h2>NodeContainer</h2>
<p>As you might know, we have to store the visited nodes in a container like structure. To offer the most flexibility and make the algorithm easier to run by default, I decided to use a <code>std::unordered_map</code> object in my abstraction. If the user knows it better, he can simply pass an other object (with the same interface) and can do some pretty optimizations. An example for 2d maps will be attached to this post.</p>
<pre><code>template <class TMap>
class NodeMap
{
public:
using VertexType = typename TMap::key_type;
using NodeDataType = typename TMap::mapped_type;
using NodeType = Node<VertexType, NodeDataType>;
explicit NodeMap(TMap _map = TMap()) :
m_Nodes(std::move(_map))
{
}
template <class TNodeCompare>
void insert(NodeType _node, TNodeCompare&& _nodeComp)
{
if (auto result = m_Nodes.insert({ _node.vertex, _node.data });
!result.second && _nodeComp(_node.data, result.first->second))
{
result.first->second = _node.data;
}
}
template <class TNodeCompare>
NodeType take_node(TNodeCompare&& _nodeComp)
{
auto itr = std::min_element(std::begin(m_Nodes), std::end(m_Nodes),
[&_nodeComp](const auto& _lhs, const auto& _rhs) { return _nodeComp(_lhs.second, _rhs.second); }
);
assert(itr != std::end(m_Nodes));
auto node = std::move(*itr);
m_Nodes.erase(itr);
return { node.first, node.second };
}
const NodeDataType* find(const VertexType& _key) const
{
auto itr = m_Nodes.find(_key);
return std::end(m_Nodes) == itr ? nullptr : &itr->second;
}
bool contains(const VertexType& _key) const
{
return m_Nodes.count(_key) != 0; // ToDo: use std::unordered_map::contains in C++20
}
bool empty() const
{
return std::empty(m_Nodes);
}
private:
TMap m_Nodes;
};
template <class TPathFinder>
using DefaultNodeMap = NodeMap<std::unordered_map<typename TPathFinder::VertexType, typename TPathFinder::NodeDataType>>;
</code></pre>
<p>Both algorithms use two different container, which need different member functions. The <code>NodeMap</code> function above combines the open- and closed-list abstraction into a single one, but you'll be able to pass two different containers-classes.</p>
<h2>necessary user definitions</h2>
<p>That's one of the most brain melting points I encountered. If you try to generalize such algorithms which highly depend on user implemented data structures, there is no real work you can do to make the algorithm run instant. The user has to feed the interfaces but I tried to make it as simple as possible.
Every searcher needs a <code>NeighbourFinder</code> which has to call a callback for every neighbour of the passed node. Here is a short example:</p>
<pre><code>std::vector<int> nodes{ 1, 2, 3, 4, 5, 6, 7 };
std::vector<std::pair<int, int>> connections
{
{ 1, 2 },
{ 2, 3 },
{ 2, 4 },
{ 4, 5 },
{ 3, 6 },
{ 3, 7 },
{ 6, 7 },
{ 7, 1 }
};
auto neighbourFinder = [&connections](const auto& _node, auto&& _callback)
{
auto next = [itr = std::begin(connections), end = std::end(connections)](const auto& _vertex) mutable -> std::optional<int>
{
itr = std::find_if(itr, end, [&_vertex](const auto& _pair) { return _pair.first == _vertex || _pair.second == _vertex; });
if (itr != end)
{
auto result = itr->first == _vertex ? itr->second : itr->first;
++itr;
return result;
}
return std::nullopt;
};
while (auto neigh = next(_node.vertex))
_callback(*neigh);
};
</code></pre>
<p>Well, the <code>neighbourFinder</code> lambda simply extracts all remote nodes for the passed node. It is not necessary to keep track of the already visited nodes; that's the task of the NodeContainer(s). I use the callback here to bypass the need of returning a <code>std::vector</code>. That might be a premature optimization, but I think it's a common style.</p>
<p>And that's it for the two easier searcher. Here is a short example, how to print every visited node:</p>
<pre><code>auto printNode = [](const auto& _nodeInfo) { std::cout << "vertex: " << _nodeInfo.vertex << " parent_vertex: " << _nodeInfo.data.parent.value_or(-1) << " cost: " << _nodeInfo.data.cost << std::endl; };
std::cout << "Breadth first visit: " << std::endl;
graph::visit(2, printNode, neighbourFinder, graph::make_breadth_first_searcher<int>());
std::cout << std::endl << "Depth first visit: " << std::endl;
graph::visit(2, printNode, neighbourFinder, graph::make_depth_first_searcher<int>());
</code></pre>
<p>for the dijkstra it's necessary to define a costCalculator object:</p>
<pre><code>// this is only a little helper function which prints the found path; don't mind to much about it.
template <class TVertexType, class TDestination, class TNeighbourSearcher, class TPathFinder, class TOpenList = graph::DefaultNodeMap<std::decay_t<TPathFinder>>,
class TClosedList = graph::DefaultNodeMap<std::decay_t<TPathFinder>>>
void search_path_and_print(TVertexType _from, TDestination&& _to, TNeighbourSearcher&& _neighbourSearcher, TPathFinder&& _pathFinder, TOpenList _openList = TOpenList(), TClosedList _closedList = TClosedList())
{
if (auto path = graph::find_path(_from, std::forward<TDestination>(_to), std::forward<TNeighbourSearcher>(_neighbourSearcher), std::forward<TPathFinder>(_pathFinder), std::move(_openList), std::move(_closedList)))
{
for (const auto& node : *path)
{
std::cout << node << std::endl;
}
}
}
std::cout << std::endl << "Dijkstra search: " << std::endl;
search_path_and_print(1, 6, neighbourFinder, graph::make_dijkstra_searcher<int>([](const auto& _from, const auto& _to) { return _to; }));
</code></pre>
<p>Yes, we simply return the value of the next node as cost. As I said, it's an example.</p>
<p>And last but not least, we need a heuristicCalculator for the A* searcher.</p>
<pre><code>auto constantCost = [](const auto& _from, const auto& _to) { return 1; };
search_path_and_print(1, 6, neighbourFinder, graph::make_astar_searcher<int>(constantCost, constantCost));
</code></pre>
<p>That simply returns 1 for both; the cost calculation (first parameter) and the heuristic calculation (second).</p>
<h2>Final Words:</h2>
<p>Thank you for reading through this wall of text, I would be happy if you have any suggestions and/or improvements for me. Feel free to comment on the coding style and the design itself; everything will be helpful for me ;)</p>
<p>If anyone is interested, I push the whole code plus a little 2d example (inclusive a more optimized NodeContainer class) here: <a href="https://wandbox.org/permlink/ldhD95ItWSkoXI8T" rel="nofollow noreferrer">https://wandbox.org/permlink/ldhD95ItWSkoXI8T</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-16T21:53:45.397",
"Id": "203833",
"Score": "4",
"Tags": [
"c++",
"graph",
"template-meta-programming",
"pathfinding",
"c++17"
],
"Title": "Modular graph searcher"
} | 203833 |
<p>I'm trying to implement a batch API where requests are associated with an id. In the batch response, the individual success/failure responses should be associated to their corresponding request id.</p>
<p>The code looks like this </p>
<pre><code>class Request {};
class Response {};
class BatchResponse {};
folly::SemiFuture<Response> handle(Request foo) {
return folly::makeSemiFuture(Response{});
}
folly::SemiFuture<BatchResponse> batchAPI() {
// input batched requests
std::map<int, Request> requests = {{1, Request{}}, {2, Request{}}};
// a collection of handled requests with their ids
std::vector<folly::SemiFuture<std::pair<int, folly::Try<Response>>>> responses;
responses.reserve(requests.size());
// loop and handle requests
for (auto& entry : requests) {
int requestId = entry.first;
// associate response with request id
responses.push_back(
handle(entry.second)
.via(folly::getCPUExecutor().get())
.thenTry([requestId](const folly::Try<Response>&& tryBar) {
return std::make_pair(requestId, tryBar);
}));
}
// this is the returned SemiFuture<BatchResponse>
return folly::collectAllSemiFuture(responses)
.via(folly::getCPUExecutor().get())
.thenValue([](const auto& tryResponses) {
BatchResponse response;
for (const auto& tryPair : tryResponses) {
// guaranteed to be successful
std::pair<int, folly::Try<Response>> pair = tryPair.value();
int requestId = pair.first;
folly::Try<Response> handleResult = pair.second;
if (handleResult.hasValue()) {
// add value and requestId to response
} else {
// add exception and requestId to response
}
}
return response;
});
}
</code></pre>
<p>I don't like that I have to capture the <code>requestId</code> in the response future and transform into a <code>pair</code> of the two. As result, I have to unwrap the <code>std::pair</code> with <code>tryPair.value();</code> since I know it'll be successful.</p>
<p>An alternative I've considered is maintaining a parallel <code>std::vector</code> of the request ids and capturing that in the <code>SemiFuture</code> returned by <code>collectAllSemiFuture</code>, since they would be in the same order.</p>
<p>Are there cleaner designs?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T07:42:03.150",
"Id": "392996",
"Score": "0",
"body": "If it can't fail, why not simply use `SemiFuture<Response>` with `.thenValue()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T15:33:08.553",
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T01:04:41.220",
"Id": "203838",
"Score": "3",
"Tags": [
"c++",
"asynchronous"
],
"Title": "Collecting folly::Futures with an associated value"
} | 203838 |
<p>This is the criteria:</p>
<p>Its length is at least 6. It contains at least one digit. It contains at least one lowercase English character. It contains at least one uppercase English character. It contains at least one special character. The special characters are: !@#$%^&*()-+</p>
<p>My code is working for all test cases but I'm afraid it seems way longer than necessary. I'm trying to trim it down.</p>
<pre><code>import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
# Return the minimum number of characters to make the password strong
flag = 0
if len(password) >= 6:
passRegex = re.compile(r"^(?=.*[\d])")
mo = passRegex.search(password)
if mo is None:
flag+=1
passRegex = re.compile(r"^(?=.*[A-Z])")
mo = passRegex.search(password)
if mo is None:
flag+=1
passRegex = re.compile(r"^(?=.*[a-z])")
mo = passRegex.search(password)
if mo is None:
flag+=1
passRegex = re.compile(r'[!@#$%^&*()-+]')
mo = passRegex.search(password)
if mo is None:
flag+=1
return flag
else:
if any(x in "0123456789" for x in password) is False:
flag+=1
if any(x in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for x in password) is False:
flag+=1
if any(x in "abcdefghijklmnopqrstuvwxyz" for x in password) is False:
flag+=1
if any(x in "!@#$%^&*()-+" for x in password) is False:
flag+=1
if (flag+len(password)<6):
return 6-len(password)
if (flag+len(password)>=6):
return flag
if __name__ == '__main__':
n = int(input())
password = input()
answer = minimumNumber(n, password)
</code></pre>
<p>Any advice is appreciated.</p>
| [] | [
{
"body": "<p>Code length is one factor in readability, but it isn't the only factor. \"Is this code easy to read and modify\" is a more important question to ask.</p>\n\n<p>It looks like you've gotten a method skeleton here, which kind of leads you down the path of stuffing everything in one function, which is... | {
"AcceptedAnswerId": "203847",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T02:52:14.430",
"Id": "203839",
"Score": "5",
"Tags": [
"python",
"regex"
],
"Title": "Find the minimum number of characters to add to make password strong"
} | 203839 |
<p>Update: Have implemented some of the suggestions:</p>
<p>See GitHub: <a href="https://github.com/BostonBrooks/MathsGame/tree/master/Object_Pools_Demo" rel="nofollow noreferrer">https://github.com/BostonBrooks/MathsGame/tree/master/Object_Pools_Demo</a></p>
<p>I am implementing a game engine where I have a sorted list of inanimate objects so that the closer objects get drawn over the further away objects, and I want to use an object pool rather than call malloc() every time a new object is spawned. I do not wish to store pointers directly to objects because these may move around when I save and restore the session.</p>
<p>I have written code that does this in the form of a high-scores list.
Here it is, go nuts.</p>
<pre><code>#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#define LEVEL1 3
#define LEVEL2 5
typedef struct {
int Prev;
int Next;
char Name[16];
int Score;
} Object;
Object* Pool[LEVEL1] = { 0 };
int Available_Head = -1;
int Available_Tail = -1;
int List_Head = -1;
int List_Tail = -1;
int Increase_Pool(void);
int New_Object(void);
void Delete_Object(int);
void List_Object(int);
void DeList_Object(int);
Object* Lookup_Object(int);
void Print_All(void);
void Print_None(void);
int main (void) {
char Name[16];
int Score;
while(1) {
Print_All();
printf("Enter Name: ");
scanf("%s", Name);
printf("Enter Score: ");
scanf("%d", &Score);
int object_int = New_Object();
printf("object_int %d\n", object_int);
Object* object_address = Lookup_Object(object_int);
strcpy(object_address->Name, Name);
object_address->Score = Score;
List_Object(object_int);
}
}
void DeList_Object (int object_int){
//Remove from list
Object* object_address = Lookup_Object(object_int);
if (List_Head == -1 && List_Tail == -1){
//List Empty
} else if (object_address->Prev == -1 && object_address->Next == -1) {
//Object not in list
} else if ( List_Head == object_int && List_Tail == object_int){
//Only object in list
List_Head = -1;
List_Tail = -1;
object_address->Prev = -1;
object_address->Next = -1;
} else if (List_Head == object_int) {
// Object at top of list
List_Head = object_address->Next;
object_address->Next = -1;
object_address->Prev = -1;
object_address = Lookup_Object(List_Head);
object_address->Prev = -1;
} else if (List_Tail == object_int) {
//Object at end of list
List_Tail = object_address->Prev;
object_address->Next = -1;
object_address->Prev = -1;
object_address = Lookup_Object(List_Tail);
object_address->Next = -1;
} else {
//Object in middle of list
Object* Next = Lookup_Object(object_address->Next);
Object* Prev = Lookup_Object(object_address->Prev);
Next->Prev = object_address->Prev;
Prev->Next = object_address->Next;
object_address->Prev = -1;
object_address->Next = -1;
}
}
void Delete_Object(int object_int){
// Remove from list
DeList_Object (object_int);
//Return to Pool
if (Available_Head == -1 && Available_Tail == -1){
Available_Head = object_int;
Available_Tail = object_int;
} else{
Object* object_address = Lookup_Object(object_int);
object_address->Next = Available_Head;
//Available_Head->Prev = object_int;
Available_Head = object_int;
}
}
int New_Object(void){
if (Available_Head == -1){
assert (Available_Tail == -1);
int success = Increase_Pool();
assert(success == 1);
}
int object_int = Available_Head;
Object* object_address = Lookup_Object(object_int);
Available_Head = object_address->Next;
object_address->Prev = -1;
object_address->Next = -1;
if (Available_Head != -1) {
Object* Head = Lookup_Object(Available_Head);
Head->Prev = -1;
} else {
Available_Tail = -1;
}
return object_int;
}
int Increase_Pool(void){
int i;
for (i = 0; i < LEVEL1 && Pool[i] != 0; i++){
}
if (i == LEVEL1) {
printf("out of memory\n");
return(0);
} else {
Pool[i] = calloc(LEVEL2, sizeof(Object));
}
int j = 0;
if (Available_Head == -1){
assert (Available_Tail == -1);
Available_Head = i * LEVEL2;
Available_Tail = i * LEVEL2;
Object* object = Lookup_Object(Available_Head);
object->Prev = -1;
object->Next = i * LEVEL2 + 1;
j++;
} else {
Object* Tail = Lookup_Object(Available_Tail);
Object* New = Lookup_Object(i * LEVEL2);
Tail->Next = i * LEVEL2;
New->Prev = Available_Tail;
New->Next = i * LEVEL2 + 1;
j++;
}
for (1; j < LEVEL2; j++){
//add elements of Pool[i] to the Available list
Object* object_address = Lookup_Object(i * LEVEL2 + j);
object_address->Prev = i * LEVEL2 + j - 1;
object_address->Next = i * LEVEL2 + j + 1;
}
Available_Tail = (i+1) * LEVEL2 - 1;
Object* tail_address = Lookup_Object(Available_Tail);
tail_address->Next = -1;
return(1);
}
Object* Lookup_Object(int i){
return (&(Pool[i / LEVEL2])[i % LEVEL2]);
}
void List_Object(int object_int){
//Remove from list
DeList_Object(object_int);
//Add to list
Object* object_address = Lookup_Object(object_int);
if (List_Head == -1){ //list empty
assert (List_Tail == -1);
List_Head = object_int;
List_Tail = object_int;
printf("### empty, %s, %d ##", object_address->Name, object_address->Score);
return;
}
Object* head_address = Lookup_Object(List_Head);
if (object_address->Score >= head_address->Score) {//add to start of list
object_address->Prev = -1;
object_address->Next = List_Head;
head_address->Prev = object_int;
List_Head = object_int;
printf("### head %s, %d ##", object_address->Name, object_address->Score);
return;
}
Object* tail_address = Lookup_Object(List_Tail);
if (object_address->Score <= tail_address->Score) {//add to end of list
object_address->Next = -1;
object_address->Prev = List_Tail;
tail_address->Next = object_int;
List_Tail = object_int;
printf("### tail %s, %d ##", object_address->Name, object_address->Score);
return;
}
int target_int = List_Head;
Object* target_address = Lookup_Object(target_int);
//add to middle of list
while(object_address->Score < target_address->Score){
target_int = target_address->Next;
target_address = Lookup_Object(target_int);
}
int target_prev_int = target_address->Prev;
Object* target_prev_address = Lookup_Object(target_prev_int);
target_prev_address->Next = object_int;
object_address->Prev = target_prev_int;
object_address->Next = target_int;
target_address->Prev = object_int;
printf("### middle %s, %d ##", object_address->Name, object_address-> Score);
}
void Print_All(void){
if (List_Head == -1){
assert(List_Tail == -1);
printf("\n List Empty\n\n");
return;
}
int object_int = List_Head;
Object* object_address;
printf("\nName Score\n");
while (object_int != -1){
object_address = Lookup_Object(object_int);
printf("%s %d\n", object_address->Name, object_address->Score);
assert(object_int != object_address->Next);
object_int = object_address->Next;
}
printf("\n");
return;
}
//Print_None prints a list of available objects in the pool.
void Print_None(void){
if (Available_Head == -1){
assert(Available_Tail == -1);
printf("\n List Empty\n\n");
return;
}
int object_int = Available_Head;
Object* object_address;
printf("\nPrevious Next\n");
while (object_int != -1){
object_address = Lookup_Object(object_int);
printf("%d %d\n", object_address->Prev, object_address->Next);
assert(object_int != object_address->Next);
object_int = object_address->Next;
}
printf("\n");
return;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T08:31:55.547",
"Id": "393003",
"Score": "1",
"body": "With `for (1; j < LEVEL2; j++){`, why the lone `1` versus omitting it like `for (; j < LEVEL2; j++){`? Never have seen that style before."
},
{
"ContentLicense": "CC BY-... | [
{
"body": "<p><strong>No warnings/errors (almost)</strong></p>\n\n<p>Aside from <code>for (1; j < LEVEL2; j++)</code> with its unneeded and curious <code>1</code>, no errors (as expected) and no warnings (good) from my compilation.</p>\n\n<p>Other compilers/checkers may say something, yet at least we are off... | {
"AcceptedAnswerId": "203947",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T03:09:52.280",
"Id": "203841",
"Score": "5",
"Tags": [
"c",
"linked-list",
"memory-management"
],
"Title": "Object pool and sorted linked list in C"
} | 203841 |
<p>I am requesting a JSON file that's gzipped. First, I download file:</p>
<pre><code>import urllib.request
testfile = urllib.request.URLopener()
testfile.retrieve("https://xxxxx.auth0.com/1537150574", "file.gz")
</code></pre>
<p>After that, I will read the file.gz and get the data.</p>
<pre><code>with gzip.GzipFile("file.gz", 'r') as fin:
json_bytes = fin.read()
json_str = json_bytes.decode('utf-8')
data = json.loads(json_str)
print(data)
</code></pre>
<p>Actually, This above code can work well for me. But I would like to find another way (faster and brief code). Could I have a suggestion?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T03:19:35.750",
"Id": "392983",
"Score": "0",
"body": "You probably can't speed this code up since you can't stream from a .gz file, so you need to load the whole thing into memory anyway, and the code is perfectly readable. If you ... | [
{
"body": "<p>Your bottleneck is probably that you write the file to disk first and then read it again (I/O).\nIf the file does not exceed your machines random access memory, decompressing the file on the fly in memory might be a faster option:</p>\n\n<pre><code>from gzip import decompress\nfrom json import loa... | {
"AcceptedAnswerId": "203858",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T03:15:07.713",
"Id": "203842",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"json",
"http",
"compression"
],
"Title": "Read gzipped JSON file from URL"
} | 203842 |
<p>My first ever attempt at Go. Writing a small app. It takes a property file and uses it to populate a Config object.
After adding the first property of the Config object (dateformat) I realised that the code was looking horrible and would only get worse as I added more properties. </p>
<p>Please help me simplify, how should this be done? Why is my go-code always looking this horrible? :)</p>
<pre><code>// Config holds the properties and values used for configuration
type Config struct {
dateFormat string
}
// DefaultConfig is the set of configuration values used if none other is given.
var DefaultConfig = Config{"2006-01-02"}
// FromFile returns the configuration to use for did
func FromFile(path string) (c Config, e error) {
c = DefaultConfig
if lines, err := File2lines(path); err == nil {
for _, line := range lines {
prop, val, propErr := propertyOf(line)
if propErr == nil && prop == "dateformat" && ValidDateFormat(val) {
format, formatErr := ToGoDateFormat(val)
if formatErr == nil {
c.dateFormat = format
}
} else if propErr != nil {
e = propErr
}
}
} else if err != nil {
e = err
}
return
}
func propertyOf(str string) (key, val string, err error) {
split := strings.Split(strings.TrimSpace(strings.TrimRight(str, "\n")), "=")
if len(split) == 2 {
return split[0], split[1], nil
}
return "", "", fmt.Errorf(fmt.Sprintf("String '%s' cannot be read as property.", str))
}
</code></pre>
<p>The code expect a file which has the following property:</p>
<pre><code>dateformat=yyyymmdd
</code></pre>
<ul>
<li>ValidDateFormat just checks if the given value is valid.</li>
<li>ToGoDateFormat converts any given format to valid golang date format</li>
<li>File2lines reads a file and returns its lines</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T10:48:25.777",
"Id": "393164",
"Score": "0",
"body": "Just odd that you decide to choose a _file_ for config. The common approach in golang is to use environment variables and/or flags, not a Java-style properties file"
}
] | [
{
"body": "<p>OK, there's a couple of comments I can make WRT code style looking at what you have now. Things that really stand out, for example, are lines like this:</p>\n\n<pre><code>return \"\", \"\", fmt.Errorf(fmt.Sprintf(\"String '%s' cannot be read as property.\", str))\n</code></pre>\n\n<p>The function ... | {
"AcceptedAnswerId": "203945",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T04:40:49.010",
"Id": "203845",
"Score": "3",
"Tags": [
"beginner",
"parsing",
"go",
"configuration"
],
"Title": "Property file into configuration in Go"
} | 203845 |
<p>I want to test some different endgame scenarios for <a href="https://en.wikipedia.org/wiki/One-Handed_Solitaire" rel="nofollow noreferrer">one-handed Solitaire</a> where the removal of the cards if the suit or value match is optional.</p>
<p>I've written a simple generator which yields at the decision point on every opportunity where it could clear cards and accepts a boolean on whether it will clear those cards.</p>
<p>Any feedback on usability of the generators is appreciated.</p>
<p>I want to be able to attempt different algorithms for end states (<10 cards) and get some data on how optional choices can improve win odds, while also being able to look at the discards, cards on stack and unseen cards to be able to determine if the game is even winnable or if it's optimal to simply remove as many cards as possible.</p>
<p>Given how I need access to the deck, stack and discard should I rearrange these in any way? As is the winnable boolean would have to be a property of OneHandedSolitaire as it is the only area that knows of all 3 lists of value.</p>
<pre><code>"""One handed solitaire with a rule change wherein removing cards is optional.
This choice in the majority of cases won't be an optimal play except for in end game scenarios where an actual victory
is still possible and based on the suits or values available the remaining number of cards can influence decisions.
"""
import copy
import itertools
import operator
import random
from collections import namedtuple, Counter
SUITS = ['♠', '♥', '♦', '♣']
VALUES = list(map(str, range(2, 11))) + ['J', 'Q', 'K', 'A']
Card = namedtuple('Card', ['suit', 'value'])
UNSHUFFLED_DECK = list((Card(*c_v) for c_v in itertools.product(SUITS, VALUES)))
class Deck:
def __init__(self):
self.deck = copy.copy(UNSHUFFLED_DECK)
def shuffle(self):
random.shuffle(self.deck)
def draw(self):
"""Return a card; raises exception on an empty deck"""
try:
return self.deck.pop()
except IndexError:
raise RuntimeError("Deck is empty")
class FourStack:
"""Stack for comparison of cards between the top and fourth from top cards; also saves discarded cards from stack"""
def __init__(self):
self.cards = []
self.discards = []
def add_card(self, card):
self.cards.append(card)
@property
def suit(self) -> bool:
"""Compare the suit of the stack"""
try:
if self.cards[-1].suit == self.cards[-4].suit:
return True
# If there are <4 cards in the stack cannot match
except IndexError:
pass
return False
def remove_middle(self):
for _ in range(2):
self.discards.append(self.cards.pop(-2))
@property
def value(self) -> bool:
"""Compare the value of the stack"""
try:
if self.cards[-1].value == self.cards[-4].value:
return True
# If there are <4 cards in the stack cannot match
except IndexError:
pass
return False
def remove_all(self):
for _ in range(4):
self.discards.append(self.cards.pop(-1))
class OneHandedSolitaire:
def __init__(self):
self.new_game()
def new_game(self):
self._setup()
self._start()
def _setup(self):
self.deck = Deck()
self.deck.shuffle()
self.stack = FourStack()
def _start(self):
"""Start the game"""
for _ in range(4):
self.flip()
def flip(self):
"""Flip a card over and put it onto the stack"""
self.stack.add_card(self.deck.draw())
def compare(self):
"""Compare the top card and the 4th from the top and provide options
These are the functional rules of one handed solitaire. Matching values remove all four cards on top of the
stack, matching suits remove the middle two cards from the top four.
returns a method which will clear cards or None
"""
if self.stack.value:
return self.stack.remove_all
if self.stack.suit:
return self.stack.remove_middle
def choice_gen(self):
"""Yield the next decision point of the game"""
while True:
choice = self.compare()
if choice:
yield choice
try:
self.flip()
except RuntimeError:
return
def play_gen(self):
"""Play a game of one handed solitaire.
With this generator send True to clear and False to not clear the cards. You can inspect either the yielded
method to see how many and which cards will be removed.
"""
for choice in self.choice_gen():
clear = yield
if clear:
choice()
score = len(self.stack.cards)
return score
def play_clear(self):
"""Play a game where the user always removes every card they can and return the score."""
gen = self.play_gen()
gen.send(None)
try:
while True:
gen.send(True)
except StopIteration as e:
score = e.value
return score
def winnable(self) -> bool:
"""Determining absolutely if the game is winnable is logically and computationally difficult.
This being True means we can't eliminate victory, but doesn't guarantee a victory is possible.
"""
# Empty deck remaining cards
# Edge case: technically there could be a valid series of ignored choices that could clear the stack
if not self.deck.deck and self.stack.cards:
return False
remaining_cards = self.deck.deck + self.stack.cards
if len(remaining_cards) == 2:
return False
# no matches remaining
matches = itertools.groupby(remaining_cards, key=operator.itemgetter('value'))
for _, cards in matches:
if len(cards) <= 1:
break
# nobreak
else:
return False
# matches remain, but they are all within 3 cards of each other in ordering
return True
def play_clear_until_win():
ohs = OneHandedSolitaire()
games = 1
score = True
while score:
score = ohs.play_clear()
print(f"Score was {score} after {games} games")
ohs.new_game()
games += 1
def play(n):
c = Counter()
ohs = OneHandedSolitaire()
for _ in range(n):
score = ohs.play_clear()
c.update([score])
ohs.new_game()
return c
if __name__ == "__main__":
runs = play(300000)
print(f"Counter data: {runs}")
print(f"Most common score: '{runs.most_common()}'")
win_prct = runs[0] / (sum(runs.values()))
print(f"Winning odds: {win_prct}")
</code></pre>
<p>Thanks for reading!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T08:19:48.003",
"Id": "393001",
"Score": "2",
"body": "`VALUES` seems wrong to me — it has two aces but no tens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T13:52:41.047",
"Id": "393057",
"... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T04:55:24.893",
"Id": "203846",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"playing-cards",
"generator"
],
"Title": "One-handed Solitaire Game Choice Generator"
} | 203846 |
<p>I dont think this will work anywhere besides in minecraft with computercraft but it's all correct syntax. I just feel like it has some lines of code I could eliminated somehow and made it a cleaner script. I appreciate any constructive criticism to help me further understand what I'm misunderstanding. </p>
<pre><code>function placef()
turtle.select(1)
x = 1
if turtle.getItemCount(x) == 0 then
repeat turtle.select(x+1)
x = x + 1
if x == 17 then
x = 1
y = 2
end
if y == 2 then
os.reboot()
end
until turtle.getItemCount(x) > 0
end
turtle.place()
end
function placeup()
turtle.select(9)
x = 9
if turtle.getItemCount(x) == 0 then
repeat turtle.select(x+1)
x = x + 1
if x == 17 then
x = 9
y = 2
end
if y == 2 then
os.reboot()
end
until turtle.getItemCount(x) > 0
end
turtle.placeUp()
end
function place()
turtle.select(9)
x = 9
if turtle.getItemCount(x) == 0 then
repeat turtle.select(x+1)
x = x + 1
if x == 17 then
x = 9
y = 2
end
if y == 16 then
os.reboot()
end
until turtle.getItemCount(x) > 0
end
turtle.placeDown()
end
function repairOT()
turtle.select(1)
x = 1
if turtle.getItemCount(x) == 0 then
repeat turtle.select(x+1)
x = x + 1
if x == 17 then
x = 1
y = 2
end
if y == 2 then
os.reboot()
end
until turtle.getItemCount(x) > 0
end
if turtle.compareDown() == false then
place()
turtle.turnRight()
else
turtle.turnRight()
end
if turtle.compare() == false then
placef()
turtle.turnLeft()
else
turtle.turnLeft()
end
turtle.forward()
end
function repairBI()
turtle.select(1)
x = 1
if turtle.getItemCount(x) == 0 then
repeat turtle.select(x+1)
x = x + 1
if x == 17 then
x = 1
y = 2
end
if y == 16 then
os.reboot()
end
until turtle.getItemCount(x) > 0
end
if turtle.compareUp() == false then
placeup()
turtle.turnLeft()
else
turtle.turnLeft()
end
if turtle.compare() == false then
placef()
turtle.turnRight()
else
turtle.turnRight()
end
turtle.forward()
end
</code></pre>
<p>These functions are where I think I could do away with alot of lines of code but I'm not sure how. Maybe an anonymous function and a class. Don't really quite understand using those very well yet. </p>
<p><a href="https://pastebin.com/JDZSibmn" rel="nofollow noreferrer">https://pastebin.com/JDZSibmn</a> There is the full script just in case anyone wants to see it. The rest is just loops.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:30:15.170",
"Id": "393047",
"Score": "0",
"body": "The title is better, yes, but I still don't have the foggiest what problem you're solving. Just when I think I got an idea I see code like `os.reboot()` in a *Minecraft* plug-in ... | [
{
"body": "<p>First of all, use more <code>local</code>. It will save you a lot of headache in the future.</p>\n\n<p>Instead of the three place functions, you could just do</p>\n\n<pre><code>local function selectAnyBlock()\n for i=1,16 -- 4 x 4 inventory\n if turtle.getItemCount(i) > 0 then\n return... | {
"AcceptedAnswerId": "203902",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T05:31:07.820",
"Id": "203848",
"Score": "1",
"Tags": [
"object-oriented",
"api",
"lua",
"minecraft",
"turtle-graphics"
],
"Title": "Building a 64 × 64 particle accelerator frame in Minecraft with a computercraft turtle"
} | 203848 |
<p>So I wanted to write a basic console based banking app to practice my skills. It makes use of BigDecimal to ensure accuracy. Here is the MVP I plan to enhance it with all banking features soon. I tried to follow the MVC idea as close as possible, I'm pretty happy with the outcome, although I was questioning myself about some things like how I was creating the new account. As of now it can only accept one user, I plan to add some sort of data persistence like SQLite to practice with. Also there is no check to enforce the user to enter their details when creating an account so those fields can be blank. I will be enhancing this in the near future. Any peer reviews greatly appreciated on how my style could be improved, better way of handling how I did it or anything etc.</p>
<p><strong>Main.java</strong></p>
<pre><code>public class Main
{
public static void main(String[] args)
{
Prompter prompter = new Prompter();
prompter.greetUser();
do
{
prompter.prompt();
prompter.processPrompt();
} while(!prompter.isFinishedBanking);
}
}
</code></pre>
<p><strong>Prompter.java</strong></p>
<pre><code>import java.util.Scanner;
public class Prompter
{
protected boolean isFinishedBanking;
protected boolean areCustomerDetailsCorrect;
private String option;
private Scanner scanner = new Scanner(System.in);
private Account account = new Account();
public void prompt()
{
isFinishedBanking = false;
System.out.print("> ");
option = scanner.nextLine();
}
public void processPrompt()
{
if (option.toLowerCase().equals("exit"))
{
System.out.println("\nThank you for banking with JBank, goodbye!");
isFinishedBanking = true;
}
else if (option.toLowerCase().equals("home"))
{
System.out.println();
greetUser();
}
else if (option.toLowerCase().equals("options"))
{
showOptions();
}
else if (option.toLowerCase().equals("open"))
{
if(account.isUserCustomer)
{
System.out.println("Error! you have already opened an account.");
}
else
{
do
{
openAccountPrompt();
System.out.println("\nAre these details correct? Y/n");
printCustomerDetails();
prompt();
if (option.toLowerCase().equals("n"))
{
areCustomerDetailsCorrect = false;
}
else
{
areCustomerDetailsCorrect = true;
account.openAccount();
System.out.println("\nCongratulations! You have successfully opened a new account.");
}
} while(!areCustomerDetailsCorrect);
}
}
else if (option.toLowerCase().equals("deposit"))
{
if (!account.isUserCustomer)
{
System.out.println("\nError! you must open an account before you can use this option.\n");
}
else
{
System.out.println("\nEnter amount you with to deposit.");
prompt();
account.depositFunds(option);
System.out.println("\nSuccess! your new balance is: " + account.getAccountBalance());
}
}
else if (option.toLowerCase().equals("check"))
{
if (!account.isUserCustomer)
{
System.out.println("\nError! you must open an account before you can use this option.\n");
}
System.out.println();
System.out.println("Your account balance is: " + account.getAccountBalance());
}
else if (option.toLowerCase().equals("withdraw"))
{
if (!account.isUserCustomer)
{
System.out.println("\nError! you must open an account before you can use this option.\n");
}
else
{
System.out.println("\nEnter amount you with to withdraw.");
prompt();
if (account.checkAccountForAvailableFunds(option))
{
System.out.println("\nError! you don't have the available funds in your account to complete this transaction. Your available balance is: " + account.getAccountBalance());
}
else
{
account.withdrawFunds(option);
System.out.println("\nSuccess! your new balance is: " + account.getAccountBalance());
}
}
}
else
{
System.out.println("\nError! I didn't recognize your response, please try again.\n");
}
}
public void openAccountPrompt()
{
System.out.println("\n\nEnter your first name.");
prompt();
account.setCustomerFirstName(option);
System.out.println("\nEnter your last name.");
prompt();
account.setCustomerLastName(option);
System.out.println("\nEnter your address.");
prompt();
account.setCustomerAddress(option);
System.out.println("\nEnter your phone number.");
prompt();
account.setCustomerPhoneNumber(option);
System.out.println("\nEnter your email address.");
prompt();
account.setCustomerEmailAddress(option);
System.out.println("\nEnter amount to fund your new account.");
prompt();
// If left blank defaults to zero.
if (option.equals(""))
{
option = "0";
}
account.setAccountBalance(option);
}
public void printCustomerDetails()
{
System.out.printf("Name: %s %s\nAddress: %s\nTelephone number: %s\nEmail address: %s\nBeginning balance: %s\n\n",
account.getCustomerFirstName(), account.getCustomerLastName(),
account.getCustomerAddress(),
account.getCustomerPhoneNumber(),
account.getCustomerEmailAddress(),
account.getAccountBalance());
}
public void greetUser()
{
System.out.println("Welcome to JBank! Type \"options\" for a list of options, \"home\" to get back here, or \"exit\" to exit.\n");
}
public void showOptions()
{
System.out.println("\nOptions: \"open\" an account, \"deposit\" funds, \"check\" balance, or make a \"withdraw\"\n");
}
}
</code></pre>
<p><strong>Account.java</strong></p>
<pre><code>import java.math.BigDecimal;
public class Account
{
public boolean isUserCustomer = false;
private Account customerAccount;
private String customerFirstName;
private String customerLastName;
private String customerAddress;
private String customerPhoneNumber;
private String customerEmailAddress;
private String stringAccountBalance;
private BigDecimal bigDecimalAccountBalance = BigDecimal.ZERO;
public Account()
{
}
public Account(String customerFirstName, String customerLastName, String customerAddress, String customerPhoneNumber, String customerEmailAddress, String stringAccountBalance)
{
this.customerFirstName = customerFirstName;
this.customerLastName = customerLastName;
this.customerAddress = customerAddress;
this.customerPhoneNumber = customerPhoneNumber;
this.customerEmailAddress = customerEmailAddress;
this.stringAccountBalance = stringAccountBalance;
}
public String getCustomerFirstName()
{
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName)
{
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName()
{
return customerLastName;
}
public void setCustomerLastName(String customerLastName)
{
this.customerLastName = customerLastName;
}
public String getCustomerAddress()
{
return customerAddress;
}
public void setCustomerAddress(String customerAddress)
{
this.customerAddress = customerAddress;
}
public String getCustomerPhoneNumber()
{
return customerPhoneNumber;
}
public void setCustomerPhoneNumber(String customerPhoneNumber)
{
this.customerPhoneNumber = customerPhoneNumber;
}
public String getCustomerEmailAddress()
{
return customerEmailAddress;
}
public void setCustomerEmailAddress(String customerEmailAddress)
{
this.customerEmailAddress = customerEmailAddress;
}
public String getAccountBalance()
{
return bigDecimalAccountBalance.toString();
}
public void setAccountBalance(String stringAccountBalance)
{
this.stringAccountBalance = stringAccountBalance;
bigDecimalAccountBalance = new BigDecimal(stringAccountBalance);
}
public void openAccount()
{
customerAccount = new Account(customerFirstName, customerLastName, customerAddress, customerPhoneNumber, customerEmailAddress, stringAccountBalance);
isUserCustomer = true;
}
public void depositFunds(String stringDepositAmount)
{
BigDecimal bigDecimalDepositAmount = new BigDecimal(stringDepositAmount);
bigDecimalAccountBalance = bigDecimalAccountBalance.add(bigDecimalDepositAmount);
}
public void withdrawFunds(String stringWithdrawAmount)
{
BigDecimal bigDecimalWithdrawAmount = new BigDecimal(stringWithdrawAmount);
bigDecimalAccountBalance = bigDecimalAccountBalance.subtract(bigDecimalWithdrawAmount);
}
public boolean checkAccountForAvailableFunds(String stringWithdrawAmount)
{
boolean isAvailable;
BigDecimal bigDecimalWithdrawAmount = new BigDecimal(stringWithdrawAmount);
// Checks to make sure there are enough funds in the account to make the withdraw.
if (bigDecimalAccountBalance.subtract(bigDecimalWithdrawAmount).compareTo(BigDecimal.ZERO) < 0)
{
isAvailable = true;
}
else
{
isAvailable = false;
}
return isAvailable;
}
}
</code></pre>
| [] | [
{
"body": "<p>Your <code>Prompter</code> class is quite big, and has several responsibilities: prompting for action, validating input and performing the action. It is very volatile, as any new action requires also updating the prompter. I'd break out the actions to their own classes, implementing an <code>Banki... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T06:28:28.967",
"Id": "203852",
"Score": "3",
"Tags": [
"java",
"algorithm",
"object-oriented"
],
"Title": "Java console banking"
} | 203852 |
<p>Please have a review of this Code chunk and let me know whether it is a good way for infinite Producer?</p>
<pre><code>UniqueStrings = new BlockingCollection<string>(10);
Task.Run(() =>
{
while (true)
{
try
{
UniqueStrings.Add(GetNextUniqueStringNumber("RCH04"));
}
catch (OperationCanceledException e)
{
Console.WriteLine("ERROR_UNIQUE_STRING_ADD: {0}", e.Message);
}
}
});
</code></pre>
<p>Where <code>GetNextUniqueStringNumber("RCH04")</code> gives unique string every time. In other words, I want Unique string readily available every time Consumer takes from it. </p>
<p><strong>EDIT:</strong></p>
<pre><code>public void Process()
{
while (!ProcessedCollection.IsCompleted)
{
try
{
string stringId = UniqueStrings.Take();
Console.WriteLine("Unique String: {0}", stringId);
// TODO - Use this String Id for further processing
}
catch (OperationCanceledException e)
{
Console.WriteLine("DATABASE_MANAGER: Operation Canceled. " + e.Message);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T07:59:15.037",
"Id": "392998",
"Score": "1",
"body": "Could you add a usage example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T08:22:43.030",
"Id": "393002",
"Score": "0",
"body": "@... | [
{
"body": "<h3>Looks Good To Me.</h3>\n\n<p>I was initially confused by this code, so I would want to rename the collection from <code>UniqueStrings</code> to something like <code>UniqueStringBuffer</code>, to make the purpose clear. To me, \"buffer\" says \"I will use this object to hold data temporarily, beca... | {
"AcceptedAnswerId": "203950",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T07:12:42.710",
"Id": "203854",
"Score": "1",
"Tags": [
"c#",
"producer-consumer",
"tpl-dataflow"
],
"Title": "Infinite producer using BlockingCollection"
} | 203854 |
<p>Scenario: I'm getting requests through a (thread-safe) queue. Each request then needs to be handled in a separate thread. There is a chance that the function (which is actually calling a Java-program via <code>popen</code>, and polling its output) takes a very long time. From the main thread I need a mechanism to indicate that situation (basically, measuring thread-running-time). </p>
<p>In my example I'm trying to 'enrich' <code>std::future</code> with some time information. The sample runs seamlessly - but I'm uncertain if this is the correct way. </p>
<p>Here is a very simple demo that mimics what I'm trying to achieve (where <code>ThreadFunc</code> stands in for my real processing code):</p>
<pre><code>#include <iostream>
#include <thread>
#include <future>
#include <chrono>
#include <vector>
#include <random>
typedef std::future<int> FutureResultInt;
int ThreadFunc( )
{
std::random_device rd;
std::mt19937 mt(rd());
const int iRand = std::uniform_int_distribution<int>(2000, 6000)(mt);
std::cout << "ThreadFunc waiting for [" << iRand << "] ms ... " << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(iRand));
std::cout << "ThreadFunc [" << iRand << "] done" << std::endl;
return iRand;
}
class CFutureTest
{
public:
CFutureTest() = delete;
CFutureTest(FutureResultInt&& fr)
: m_start(std::chrono::system_clock::now())
, m_result()
{
m_result = std::move(fr);
};
int GetAge() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_start).count();
}
// private:
FutureResultInt m_result;
std::chrono::time_point<std::chrono::system_clock> m_start;
};
int main()
{
std::vector< CFutureTest > futures;
for (int i = 0; i < 5; i++)
futures.push_back(std::move(std::async(std::launch::async, ThreadFunc)));
while (futures.size() > 0)
{
for (std::vector< CFutureTest >::iterator it = futures.begin(); it != futures.end(); ++it)
{
CFutureTest& future = *it;
const std::future_status stat = future.m_result.wait_for(std::chrono::milliseconds(1));
switch (stat)
{
case std::future_status::timeout:
if (future.GetAge() > 4000)
{
std::cout << "Thread has exceeded the time limit" << std::endl;
}
continue;
case std::future_status::deferred:
std::cout << "std::future_status::deferred" << std::endl;
continue;
}
const int iResult = future.m_result.get();
std::cout << "future returned [" << iResult << "] (removing!)" << std::endl;
futures.erase(it);
if (futures.size() < 1)
break;
it = futures.begin();
}
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T07:34:53.647",
"Id": "393553",
"Score": "0",
"body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/52361222/1014587)"
}
] | [
{
"body": "<h2>Ugly typedef</h2>\n\n<p>I'm not a big fan of this:</p>\n\n<pre><code>typedef std::future<int> FutureResultInt;\n</code></pre>\n\n<p>It's not significantly shorter or easier to read, it doesn't isolate the user from an underlying type, and it only serves to slow down my reading every time I ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T08:08:03.957",
"Id": "203856",
"Score": "3",
"Tags": [
"c++",
"c++11",
"multithreading",
"asynchronous",
"benchmarking"
],
"Title": "Monitor asynchronous tasks, tracking their running times"
} | 203856 |
<p>I'm wondering if some PS gurus can advise on whether my method for sorting and recombining some data fields by using an array of PSCustomObjects is as efficient as it might be.</p>
<p>I'm importing a CSV file that contains a number of person details, including Full Names in a single field that have a variety of separators between first and last names (e.g. comma, space, comma + space, semicolon, etc). Last name comes first. Sanitising those variants is also an objective.</p>
<p>The dataset needs to be sorted by last name and reassembled with a single FullName field. Doing a simple sort by the FullName field doesn't work reliably given the variety of delimiters between the name parts.</p>
<p>I've attempted it creating an array of new PSCustomObjects that comprises of all the original fields from the CSV plus the Full Name field split into two new name fields. It's then sorted by the last name, and the results are stored in a new array ready for output, joining the previously-split name fields back together with a comma and space.</p>
<p>Any suggestions for better efficiency welcome. </p>
<pre><code>$data = import-csv .\Cust.csv
# CSV fields: FullName, StreetAddress, City, Postcode
# Create a temporary array for sorting
$splitNames = @()
# Split "FullName" into separate name parts and add all to temp array
$data | foreach {
$spltName = $_.FullName -split '[\s|,|;]+'
$splitNames += [PSCustomObject]@{
Last = $spltName[0]
First = $spltName[1]
StreetAddress = $_.StreetAddress
City = $_.City
Postcode = $_.Postcode
}
}
# Create an output array to hold the final result
$sortedNames = @()
# Sort the temporary array by lastname, rejoin name field and add to output array
$splitNames | Sort Last | foreach {
$FullName = $_.Last, $_.First -join ', '
$sortednames += [PSCustomObject]@{
FullName = $Fullname
StreetAddress = $_.StreetAddress
City = $_.City
Postcode = $_.Postcode
}
}
$sortednames
</code></pre>
<p>Sample data - first row is the header:</p>
<pre><code>"FullName","StreetAddress","City","Postcode"
"Bloggs,Joe","1 Some Street","City","1001"
"Bloggs Jane","1 Some Street","City","1001"
"Bloggs;Jill","1 Some Street","City","1001"
"Bloggs, Jo","1 Some Street","City","1001"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T08:32:29.730",
"Id": "393004",
"Score": "3",
"body": "Please post a sample CSV file with just a few records. Use fake data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T06:24:49.317",
"Id": "39... | [
{
"body": "<p>I'm glad we established in the comments that your code doesn't in fact run slow. When you use the word \"efficiency\", most people would take that to mean run-time speed (or space, depending on the context).</p>\n\n<p>You should never optimize for efficiency unless there is a demonstrated lack of ... | {
"AcceptedAnswerId": "204100",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T08:13:46.467",
"Id": "203857",
"Score": "0",
"Tags": [
"performance",
"sorting",
"csv",
"powershell"
],
"Title": "Sorting CSV table in Powershell"
} | 203857 |
<h1>Intro</h1>
<p>As some hobby thing, I'm trying to understand the basics of smart cards. How they work internally and what can be done with them.</p>
<p>Therefore I made my very first smart card program, which will fuzz a smart card for all valid possible instructions without trying to block up the card :)</p>
<p>I have had 0 experience before I started on this, and decided I would use Python with the <a href="https://github.com/LudovicRousseau/pyscard" rel="nofollow noreferrer">psycard</a> module.</p>
<p>I am quite happy with the result, but since my experience is lacking I'm wondering if I made any glaring mistakes. </p>
<p><em>Feel free to comment if something is missing.</em></p>
<h1>Code</h1>
<pre><code>import logging
from smartcard.CardType import AnyCardType
from smartcard.CardRequest import CardRequest
from smartcard.sw.SWExceptions import SWException
class SmartCardFuzzer():
# Constants for logging a succes
class Status():
SUCCES = 0
FAILED = 1
PARAM_FAIL = 2
# Constanst for determining the succes from the status values
BAD_INSTRUCTIONS = [0x20, 0x24]
SUCCESS_LIST_RESP = [
0x90, # Success
0x61, # More Data
0x67, # Wrong Length
0x6c, # Wrong Length
0x6a, # Referenced Data not found
]
SUCCESS_BAD_PARAM_RESP = [(0x6a, 0x86)] # Incorrect Paramters
SUCCESS_FAIL_RESP = [(0x6a, 0x81)] # Function not supported
UNSUPPORTED_RESP = [(0x6E, 0x00)] # Class not supported
def __init__(self, timeout=30, log_file='smart_fuzzer.log'):
logging.basicConfig(filename=log_file, level=logging.DEBUG)
self.timeout = timeout
self.cardservice = self.__get_card()
def __get_card(self):
'''
This method will get the first card from the cardreader
Afterwards it will connect to the card and returns it service
returns:
cardservice: The cardservice which has a connection with the card
raises:
A timeout excpetion if no card was found
'''
cardtype = AnyCardType()
cardrequest = CardRequest(timeout=self.timeout, cardType=cardtype)
cardservice = cardrequest.waitforcard()
cardservice.connection.connect()
return cardservice
def __send_apdu(self, _class, instruction, p1, p2):
'''
This will send and logs an apdu command to the card
returns:
response: The response of the command
sw1: The first status value
sw2: The second status value
'''
apdu = [_class, instruction, p1, p2]
logging.info(f'Send: {str(apdu)}')
response, sw1, sw2 = self.cardservice.connection.transmit(apdu)
logging.info(f'Returned: {response} {sw1} {sw2}')
return response, sw1, sw2
def __get_succes(self, sw1, sw2):
'''
A function to determine if we encountered a Succes
args:
sw1: The first status value
sw2: the second status value
returns:
a constant succes
'''
if sw1 in self.SUCCESS_LIST_RESP \
and (sw1, sw2) not in self.SUCCESS_FAIL_RESP \
and (sw1, sw2) not in self.SUCCESS_BAD_PARAM_RESP:
logging.info('Apdu command succes!')
return self.Status.SUCCES
elif (sw1, sw2) in self.SUCCESS_BAD_PARAM_RESP:
logging.info('Got partial succes, bruteforce all the params!')
return self.Status.PARAM_FAIL
else:
logging.info(f'Apdu command failed!')
return self.Status.FAILED
def _class_fuzzer(self):
'''
This will fuzz all the valid classes in the card
yields:
_class: If the response was supported
'''
for _class in range(0xFF + 1):
# Set as default failure, in case of exception
sw1, sw2 = self.UNSUPPORTED_RESP[0]
try:
response, sw1, sw2 = self.__send_apdu(_class, 0x00, 0x00, 0x00)
except SWException as e:
logging.info(f'Got SWException {e}')
except Exception as e:
logging.warning(f'{e}\nSomething went horribly wrong!')
# If it is supported we call it a succes!
if (sw1, sw2) not in self.UNSUPPORTED_RESP:
yield _class
def _instruction_fuzzer(self, _class):
'''
This will fuzz all the valid instruction in the card
args:
_class: A valid class instruction
yields:
A succesful apdu instruction
(_class, instuction, param1, param2)
'''
for instruction in range(0xFF + 1):
if instruction in self.BAD_INSTRUCTIONS:
# We don't want to lock up the card ;)
continue
respsonse, sw1, sw2 = self.__send_apdu(_class, instruction, 0x00, 0x00)
succes = self.__get_succes(sw1, sw2)
if succes == self.Status.SUCCES:
yield (_class, instruction, 0x00, 0x00)
elif succes == self.Status.PARAM_FAIL:
yield from self._param_fuzzer(_class, instruction)
def _param_fuzzer(self, _class, instruction):
'''
This will fuzz all the possible parameters for an instruction
args:
_class: A valid class instruction
instruction: A valid instruction
yields:
A succesful apdu instruction
(_class, instuction, param1, param2)
'''
for p1 in range(0xff + 1):
for p2 in range(0xff + 1):
response, sw1, sw2 = self.__send_apdu(_class, instruction, p1, p2)
succes = self.__get_succes(sw1, sw2)
if succes == self.Status.SUCCES:
yield (_class, ins, p1, p2)
def fuzz(self):
'''
The main function that will fuzz all possible apdu commands
yields:
A succesfol apdu instruction
(_class, instuction, param1, param2)
'''
for valid_class in self._class_fuzzer():
for valid in self._instruction_fuzzer(valid_class):
yield valid
def main():
smart_fuzzer = SmartCardFuzzer()
for apdu in smart_fuzzer.fuzz():
print(f"Found valid apdu command {apdu}")
if __name__ == '__main__':
main()
</code></pre>
<h1>Questions</h1>
<ul>
<li>Any insight into smart cards</li>
<li>Any glaring code mistakes?</li>
<li>Did I use logging correctly?</li>
<li>I've tried my best on the doc strings are they explanatory enough?</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T09:59:20.337",
"Id": "203859",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "A step into the world of smart cards"
} | 203859 |
<p>This is the second time I am asking for a review of this code (first time can be found here: <a href="https://codereview.stackexchange.com/questions/203728/arabic-language-lesson-program">Arabic language lesson program</a>). The goal of the program hasn't changed - to house Arabic language lessons and teach Arabic to English speakers, somewhat similar to how Duolingo works. My programmng style to date is very "linear" in fashion and I have almost no experience working with classes (though I have been reading the documentation). </p>
<p>The first time around I was instructed to move the questions out of the code and into a separate text file which I have now done. Now all my questions are sorted by lesson number and part number into a .json file and I call certain questions from the file in the code. However, I still have the same problem as before - that there is a great deal of repetition in my code. Eventually I want to have 50 to 100 question and the way my program is set up, that would be very difficult to maintain. </p>
<p>I would like help figuring out how to take my current code and migrate it into a more manageable setup (I'm assuming something class-based) that would allow me to continue to build this program in a manageable fashion. </p>
<p>My code is below: </p>
<pre><code>def Part1():
Root_File_Name = "C:\\LearningArabic\\LiblibArriby\\"
JSON_File = Root_File_Name + "Lessons\\Lesson_1\\"
with open(JSON_File+"Arabic_Lessons.json", "r", encoding = "utf-8-sig") as question_file:
data = json.load(question_file)
def create_widgets_in_first_frame(): # Create the label for the frame
current_frame=first_frame #Make the frame number generic so as to make copy/paste easier. ##UPDATE PER QUESTION##
questionDirectory = data["lesson 1"]["part one"]["question1"] ##UPDATE PER QUESTION## This is the directory for the question.
wronganswer = questionDirectory["wronganswer"] #This is the directory for the wrong answers
question = questionDirectory.get("question") #This is the question text
correctanswerText = questionDirectory.get("answer") #This is the answer for whichever question has been selected.
arabic = questionDirectory.get("arabic") #This is the arabic text for the question
transliteration = questionDirectory.get("transliteration")
global score
score = 0 #Setting the initial score to zero.
print("Your score is: ", score)
global lives
lives = 3 #Setting the initial number of lives.
print("You have", lives, "lives")
#These lines of code randomly select three wrong images for the wrong answers and adds the proper file path to all four options (including the correct answer)
Image1 = ImagePath + random.choice(wronganswer)+ ".png"
Image2 = ImagePath + random.choice(wronganswer)+ ".png"
Image3 = ImagePath + random.choice(wronganswer)+ ".png"
correctanswerImage = ImagePath + correctanswerText + ".png"
#These four lines of code convert them to proper form for display in tkinter
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = PhotoImage(file=correctanswerImage)
##### Maine Question is written here. #####
L1 = Label(current_frame, text=question, font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text="'"+arabic+"'" + " is pronounced " + "'"+transliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def create_widgets_in_second_frame():
current_frame=second_frame #Make the frame number generic so as to make copy/paste easier. ##UPDATE PER QUESTION##
questionDirectory = data["lesson 1"]["part one"]["question2"] ##UPDATE PER QUESTION## This is the directory for the question.
wronganswer = questionDirectory["wronganswer"] #This is the directory for the wrong answers
question = questionDirectory.get("question") #This is the question text
correctanswerText = questionDirectory.get("answer") #This is the answer for whichever question has been selected.
arabic = questionDirectory.get("arabic") #This is the arabic text for the question
transliteration = questionDirectory.get("transliteration")
global score
score = 0 #Setting the initial score to zero.
print("Your score is: ", score)
global lives
lives = 3 #Setting the initial number of lives.
print("You have", lives, "lives")
#These lines of code randomly select three wrong images for the wrong answers and adds the proper file path to all four options (including the correct answer)
Image1 = ImagePath + random.choice(wronganswer)+ ".png"
Image2 = ImagePath + random.choice(wronganswer)+ ".png"
Image3 = ImagePath + random.choice(wronganswer)+ ".png"
correctanswerImage = ImagePath + correctanswerText + ".png"
#These four lines of code convert them to proper form for display in tkinter
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = PhotoImage(file=correctanswerImage)
##### Maine Question is written here. #####
L1 = Label(current_frame, text=question, font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text="'"+arabic+"'" + " is pronounced " + "'"+transliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def create_widgets_in_third_frame():
current_frame=third_frame #Make the frame number generic so as to make copy/paste easier
questionDirectory = data["lesson 1"]["part one"]["question3"] ##UPDATE PER QUESTION## This is the directory for the question.
wronganswer = questionDirectory["wronganswer"] #This is the directory for the wrong answers
question = questionDirectory.get("question") #This is the question text
correctanswerText = questionDirectory.get("answer") #This is the answer for whichever question has been selected.
arabic = questionDirectory.get("arabic") #This is the arabic text for the question
transliteration = questionDirectory.get("transliteration")
global score
score = 0 #Setting the initial score to zero.
print("Your score is: ", score)
global lives
lives = 3 #Setting the initial number of lives.
print("You have", lives, "lives")
#These lines of code randomly select three wrong images for the wrong answers and adds the proper file path to all four options (including the correct answer)
Image1 = ImagePath + random.choice(wronganswer)+ ".png"
Image2 = ImagePath + random.choice(wronganswer)+ ".png"
Image3 = ImagePath + random.choice(wronganswer)+ ".png"
correctanswerImage = ImagePath + correctanswerText + ".png"
#These four lines of code convert them to proper form for display in tkinter
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = PhotoImage(file=correctanswerImage)
##### Maine Question is written here. #####
L1 = Label(current_frame, text=question, font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text="'"+arabic+"'" + " is pronounced " + "'"+transliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def create_widgets_in_forth_frame():
current_frame=forth_frame #Make the frame number generic so as to make copy/paste easier
questionDirectory = data["lesson 1"]["part one"]["question4"] ##UPDATE PER QUESTION## This is the directory for the question.
wronganswer = questionDirectory["wronganswer"] #This is the directory for the wrong answers
question = questionDirectory.get("question") #This is the question text
correctanswerText = questionDirectory.get("answer") #This is the answer for whichever question has been selected.
arabic = questionDirectory.get("arabic") #This is the arabic text for the question
transliteration = questionDirectory.get("transliteration")
global score
score = 0 #Setting the initial score to zero.
print("Your score is: ", score)
global lives
lives = 3 #Setting the initial number of lives.
print("You have", lives, "lives")
#These lines of code randomly select three wrong images for the wrong answers and adds the proper file path to all four options (including the correct answer)
Image1 = ImagePath + random.choice(wronganswer)+ ".png"
Image2 = ImagePath + random.choice(wronganswer)+ ".png"
Image3 = ImagePath + random.choice(wronganswer)+ ".png"
correctanswerImage = ImagePath + correctanswerText + ".png"
#These four lines of code convert them to proper form for display in tkinter
answer1 = PhotoImage(file=Image1)
answer2 = PhotoImage(file=Image2)
answer3 = PhotoImage(file=Image3)
correctanswer = PhotoImage(file=correctanswerImage)
##### Maine Question is written here. #####
L1 = Label(current_frame, text=question, font=("Helvetica", 35))
L1.grid(columnspan=4, row=0)
global var
var = IntVar()
var.set(0) #Sets the initial radiobutton selection to nothing
def Transliteration():
Transliteration = Label(current_frame, text="'"+arabic+"'" + " is pronounced " + "'"+transliteration+"'", font=("Helvetica", 35))
Transliteration.grid(row=2, columnspan=4)
##### Makes the phonetic pronunciation button. #####
transliteration_button = Button(current_frame, text="Show Transliteration", command=Transliteration)
transliteration_button.grid(column=0, row=4)
choice1 = Radiobutton(current_frame, image=answer1, variable = var, value=1, command= Check_Answer)
choice1.image = answer1 # This prevents python garbage collection from deleting the image pre-maturely.
choice2 = Radiobutton(current_frame, image=answer2, variable = var, value=2, command= Check_Answer)
choice2.image = answer2 # This prevents python garbage collection from deleting the image pre-maturely.
choice3 = Radiobutton(current_frame, image=answer3, variable = var, value=3, command= Check_Answer)
choice3.image = answer3 # This prevents python garbage collection from deleting the image pre-maturely.
choice4 = Radiobutton(current_frame, image=correctanswer, variable = var, value=4, command= Check_Answer)
choice4.image = correctanswer # This prevents python garbage collection from deleting the image pre-maturely.
choices = [choice1, choice2, choice3, choice4]
random.shuffle(choices) #This line of code randomizes the order of the radiobuttons.
choices[0].grid(row=1, column=0)
choices[1].grid(row=1, column=1)
choices[2].grid(row=1, column=2)
choices[3].grid(row=1, column=3)
# Creats the quit button and displays it.
quit_button = Button(current_frame, text = "Quit", command = quit_program)
quit_button.grid(column=4, row=4)
def Check_Answer():
global lives
global score
if str(var.get()) !="4":
Answer_frame.grid_forget()
check_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
lives -=1
Incorrect = Label(check_frame, text ="That's incorrect!\n Lives: " +str(lives) + "\n Score: " + str(score), font=("Helvetica", 35))
Incorrect.grid(row=0, rowspan=2, column=2, columnspan=2)
if str(var.get()) == "4":
score +=1
check_frame.grid_forget()
Answer_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
Correct = Label(Answer_frame, text = "That's right!\n Lives: " +str(lives)+ "\n Score: " + str(score), font=("Helvetica", 35))
Correct.grid(row=0, rowspan=2, column=2, columnspan=2)
first_frame_button = Button(Answer_frame, text = "Question 1", command = call_first_frame_on_top)
first_frame_button.grid(column=1, row=3)
second_frame_button = Button(Answer_frame, text = "Question 2", command = call_second_frame_on_top)
second_frame_button.grid(column=2, row=3)
third_frame_button = Button(Answer_frame, text = "Question 3", command = call_third_frame_on_top)
third_frame_button.grid(column=3, row=3)
forth_frame_button = Button(Answer_frame, text = "Question 4", command = call_forth_frame_on_top)
forth_frame_button.grid(column=4, row=3)
def call_first_frame_on_top():
second_frame.grid_forget()
third_frame.grid_forget()
forth_frame.grid_forget()
check_frame.grid_forget()
Answer_frame.grid_forget()
create_widgets_in_first_frame()
first_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_second_frame_on_top():
first_frame.grid_forget()
check_frame.grid_forget()
third_frame.grid_forget()
forth_frame.grid_forget()
create_widgets_in_second_frame()
Answer_frame.grid_forget()
print(lives)
if lives <= 0:
quit_program
second_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_third_frame_on_top():
check_frame.grid_forget()
first_frame.grid_forget()
second_frame.grid_forget()
forth_frame.grid_forget()
create_widgets_in_third_frame()
Answer_frame.grid_forget()
print(lives)
if lives <= 0:
quit_program
third_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_forth_frame_on_top():
check_frame.grid_forget()
first_frame.grid_forget()
second_frame.grid_forget()
third_frame.grid_forget()
create_widgets_in_forth_frame()
Answer_frame.grid_forget()
print(lives)
if lives <= 0:
quit_program
forth_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def quit_program():
root_window.destroy()
##############################
# Main program starts here #
##############################
screen = pygame.display.set_mode((1,1))
Lesson1_FilePath = Root_File_Name + "Lessons\\Lesson_1\\"
ImagePath = Lesson1_FilePath + "Images\\"
# Create the root GUI window.
root_window = Tk()
root_window.title("Lesson 1: Part 1")
# Define window size
window_width = 200
window_heigth = 100
# Create frames inside the root window to hold other GUI elements. All frames must be created in the main program, otherwise they are not accessible in functions.
first_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
first_frame['borderwidth'] = 2
first_frame['relief'] = 'sunken'
first_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
second_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
second_frame['borderwidth'] = 2
second_frame['relief'] = 'sunken'
second_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
third_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
third_frame['borderwidth'] = 2
third_frame['relief'] = 'sunken'
third_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
forth_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
forth_frame['borderwidth'] = 2
forth_frame['relief'] = 'sunken'
forth_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
check_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
check_frame['borderwidth'] = 2
check_frame['relief'] = 'sunken'
check_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
check_frame.grid_forget()
Answer_frame=tkinter.Frame(root_window, width=window_width, height=window_heigth)
Answer_frame['borderwidth'] = 2
Answer_frame['relief'] = 'sunken'
Answer_frame.grid(column=1, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.E))
Answer_frame.grid_forget()
# Create the firist frame
call_first_frame_on_top()
# Start tkinter event - loop
root_window.mainloop()
</code></pre>
<p>Here is my .json file for reference:</p>
<pre><code>{"lesson 1":
{"part one": {
"question1": {
"question": "What is the meaning of 'واد' in English?",
"arabic": "واد",
"transliteration": "walid",
"answer": "boy",
"wronganswer" : [
"girl", "woman", "man", "waiter", "mom",
"priest", "driver", "teacher", "doctor", "grandparents"
]
},
"question2": {
"question": "What is the meaning of 'بنت' in English?",
"arabic": "بنت",
"transliteration": "bint",
"answer": "girl",
"wronganswer" : [
"woman", "man", "waiter", "mom", "priest",
"driver", "teacher", "doctor", "grandparents"
]
},
"question3": {
"question": "What is the meaning of 'رخل' in English?",
"arabic": "رخل",
"transliteration": "ragul",
"answer": "man",
"wronganswer" : [
"girl", "woman", "boy", "waiter", "mom",
"priest", "driver", "teacher", "doctor", "grandparents"
]
},
"question4": {
"question": "What is the meaning of 'ست' in English?",
"arabic": "ست",
"transliteration": "sit",
"answer": "woman",
"wronganswer" : [
"girl", "boy", "man", "waiter", "mom", "priest",
"driver", "teacher", "doctor", "grandparents"
]
}
},
"part two": {
"question1": {
"question": "What is the meaning of '2test1'?",
"transliteration": "phonix",
"answer": "21",
"wronganswer" : [
"test1",
"test2",
"test3"
]
},
"question3": {
"question": "What is the meaning of '2test3'?",
"transliteration": "2test3",
"answer": "23"
}
},
"part three": [
{"question": "What is the meaning of '3test1'?",
"transliteration": "phonix",
"answer": "31"
},
{"question": "What is the meaning of '2test3'?",
"transliteration": "2test3",
"answer": "32"
}
]}
}
</code></pre>
<p>Here is a photo of one of the questions:
<a href="https://i.stack.imgur.com/Aqrxs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aqrxs.png" alt="enter image description here"></a></p>
<p>Any additional programming advice as I continue to code would, of course, be welcome. Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T12:33:11.577",
"Id": "393308",
"Score": "0",
"body": "Is there a reason you don't use arrays and loops? Three false images could be contained in an array and then you loop through to create the false images or show them. This could ... | [
{
"body": "<p>Seems you already know how to use function, but still don't know how to use function with parameters, this will be a great tool for you to refractor your code.</p>\n\n<p>I will give you some example about how to use function with parameters, list, loop and other useful skill for your code</p>\n\n<... | {
"AcceptedAnswerId": "204118",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:15:34.930",
"Id": "203869",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"json",
"tkinter"
],
"Title": "Arabic language lesson program Part 2"
} | 203869 |
<p>I would like some advice on how I could shorten my function from my battleships game (below). Essentially what it does is it checks if a coordinate is a hit and if it is, then if checks adjacent coords and shoots the one that would be a hit (it cheats, basically, which is fine).</p>
<p>I would like to know what I could do to make it more effective/shorter/more neat.</p>
<p>(If you improve it with techniques that I am not currently using, then please explain said technique. I want to use something that I can understand.)</p>
<pre><code>def ai_shoots(y_coord, x_coord, all_buttons, player_1_board, ai_score):
# print("yes")
if ai_score == 20:
popupwindow("The computer has won.")
if player_1_board[y_coord][x_coord] == ': ':
ai_score += 1
player_1_board[y_coord][x_coord] = 'X '
all_buttons[y_coord - 1][x_coord - 1].configure(text="X", fg="black", bg="red3")
if player_1_board[y_coord - 1][x_coord] == ': ':
ai_shoots(y_coord - 1, x_coord, all_buttons, player_1_board, ai_score)
elif player_1_board[y_coord + 1][x_coord] == ': ':
ai_shoots(y_coord + 1, x_coord, all_buttons, player_1_board, ai_score)
elif player_1_board[y_coord][x_coord - 1] == ': ':
ai_shoots(y_coord, x_coord - 1, all_buttons, player_1_board, ai_score)
elif player_1_board[y_coord][x_coord + 1] == ': ':
ai_shoots(y_coord, x_coord + 1, all_buttons, player_1_board, ai_score)
else:
x = random.randint(1, 10)
y = random.randint(1, 10)
ai_shoots(y, x, all_buttons, player_1_board, ai_score)
elif player_1_board[y_coord][x_coord] == 'X ' or player_1_board[y_coord][x_coord] == 'O ':
x = random.randint(1, 10)
y = random.randint(1, 10)
ai_shoots(y, x, all_buttons, player_1_board, ai_score)
else:
player_1_board[y_coord][x_coord] = 'O '
all_buttons[y_coord - 1][x_coord - 1].configure(text="O", fg="white")
</code></pre>
| [] | [
{
"body": "<h1>logic/presentation</h1>\n\n<p>You are mixing presentation and business logic. Both when signalling the AI won, as with the board. \nDo you want to look through your whole code if you decide that <code>\"_\"</code> s a better representation for clear sea than <code>\"O\"</code>, or you want it in ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:37:53.573",
"Id": "203870",
"Score": "0",
"Tags": [
"python",
"beginner",
"tkinter",
"ai",
"battleship"
],
"Title": "Battleships “AI” function"
} | 203870 |
<p>We define function D(x) as following: </p>
<p>D(x) = x + sum of digits of x
+ sum of prime factors of x then call x the father of D(x)</p>
<p>Write a program that gets input <code>t</code> at the first line and then gets an input in the next <code>t</code> lines. If that input had father, print <code>YES</code> otherwise <code>NO</code> </p>
<p>For example 12 is the father of 20<br>
20 = 12 + (1 + 2) + (2 + 3)</p>
<p>preferably write a separate function for each of these tasks: </p>
<ol>
<li>Getting sum of the digits of a number </li>
<li>Getting prime factors of a number </li>
<li>Calculating D(x) </li>
</ol>
<p><strong>Notice</strong> that if you do lots of operations, you may get time limit error. </p>
<p><strong>Time limit: 0.5 seconds<br>
Memory limit: 128 MB</strong> </p>
<p><strong>Input:</strong><br>
You get an input number <code>t</code> at the first line and then in the next <code>t</code> lines, you get number <code>n</code> for which you should solve the problem<br>
<a href="https://i.stack.imgur.com/4DBfd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4DBfd.png" alt="enter image description here"></a><br>
<strong>Output:</strong><br>
Print the answer to each input in <code>t</code> lines. </p>
<p><strong>Example:</strong><br>
Sample input: </p>
<blockquote>
<p>2<br>
4<br>
20 </p>
</blockquote>
<p>Sample output: </p>
<blockquote>
<p>NO<br>
YES </p>
</blockquote>
<p>I've written the code with python: </p>
<pre><code># function that returns the unique prime factors of number n as a list
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
factors = list(set(factors))
return factors
# function that returns the sum of digits of number n
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
# function to calculate the offspring of number X {D(X)}
def Offspring(X):
DX = X + sum(prime_factors(X)) + sum_digits(X)
return DX
ChildFather = {i: Offspring(i) for i in range(4, 1001)}
ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()
t = eval(input())
for i in range(0, t):
n = eval(input())
if n in Fathers:
print('YES')
else:
print('NO')
</code></pre>
<p>I guess this part of code </p>
<pre><code>ChildFather = {i: Offspring(i) for i in range(4, 1001)}
ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()
</code></pre>
<p>is the bottle-neck for time limit. since I don't know how to find <code>x</code> by having <code>D(x)</code>, I've solved the problem this way: </p>
<pre><code>ChildFather = {i: Offspring(i) for i in range(4, 1001)}
</code></pre>
<p>for numbers <code>4<= n<= 1000</code>, I've created a dictionary {n:D(n)} </p>
<pre><code>ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
</code></pre>
<p>created a list of unique values of the dictionary and deallocated the memory used for the dictionary</p>
<pre><code>Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()
</code></pre>
<p>create a list of values smaller than 1000 and deallocated memory used for the original list </p>
<pre><code>t = eval(input())
for i in range(0, t):
n = eval(input())
if n in Fathers:
print('YES')
else:
print('NO')
</code></pre>
<p>If a given number exists <code>n</code> in the final provided list, I understand that <code>n</code> can be written as <code>D(m)=m+sum of digits of m + sum of prime factors of m</code> so <code>n</code> has the father <code>m</code> and I'll print <code>Yes</code> otherwise <code>NO</code><br>
But seems that the program is not efficient. </p>
<ol>
<li>How can I measure the time consumed by this python program at run-time? </li>
<li>How can I measure the memory consumed by this python program at run-time?<br>
(I'm new to python and am coding with sublime text 3 in Linux Ubuntu) </li>
<li>Is there any more efficient way of writing the code?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:56:49.377",
"Id": "393052",
"Score": "1",
"body": "Do you have the challenge source/link?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:47:18.303",
"Id": "393061",
"Score": "2",
"b... | [
{
"body": "<h1>PEP-8</h1>\n<p>Try to stick to <code>PEP-8</code>. So <code>snake_case</code> for variable and method names and a lot of other guidelines. Check any other Code Review Python post for tips from people who can explain this better than me.</p>\n<h1>Memory</h1>\n<p>Since you have 128MB of memory avai... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:44:44.133",
"Id": "203871",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"memory-optimization"
],
"Title": "Search father (x) of the number D(x) and measure time and memory consumed"
} | 203871 |
<p>I am working on a small <a href="https://textract.readthedocs.io/en/stable/" rel="nofollow noreferrer">textract</a>-based Python CLI tool that aims to extract text from either a single or multiple files, writing the output in corresponding text files. The input files can be of any of the formats that textract supports.</p>
<p>The full repository is <a href="https://github.com/rdimaio/parsa" rel="nofollow noreferrer">here</a>. (Forgive me for the lack of a README file for now, I am planning to expand the project)</p>
<p>My main concerns:</p>
<ul>
<li>Does the structure of the project make sense?</li>
<li>Are small functions (like <code>_process_text</code> in <code>utils/text.py</code>) worth being defined on their own, or should they be integrated into bigger functions? (like <code>get_text</code> in the previous example)</li>
<li>Have the modules and functions been documented correctly?</li>
<li>Are there any obvious mistakes I'm making in the way I'm handling exceptions?</li>
</ul>
<p>Apart from these main points, I am open to all kinds of feedback!</p>
<h1><strong>parsa.py</strong> (main file)</h1>
<pre><code>import os
import utils.cli as cli
import utils.filesystem as fs
import utils.text as txt
# Get CLI arguments
args = cli.parse_arguments()
# If input is a file
if os.path.isfile(args.input):
# Set IO variables
infile = args.input
indir = os.path.dirname(infile)
outdir = fs.set_outdir(args.output, indir)
# Extract text
text = txt.get_text(infile)
# If text has been extracted successfully (and infile was not empty)
if text:
outfile = fs.compose_unique_filepath(infile, outdir)
try:
fs.write_str_to_file(text, outfile)
except OSError as e:
print(e)
# If input is a folder
elif os.path.isdir(args.input):
# Set IO variables
indir = args.input
outdir = os.path.join(fs.set_outdir(args.output, indir), 'parsaoutput')
# Create output folder
os.makedirs(outdir, exist_ok=True)
filelist = fs.get_filelist(indir)
for infile in filelist:
text = txt.get_text(infile)
if text:
outfile = fs.compose_unique_filepath(infile, outdir)
try:
fs.write_str_to_file(text, outfile)
except OSError as e:
print(e)
else:
exit("Error: input must be an existing file or directory")
</code></pre>
<h1><strong>utils/cli.py</strong></h1>
<pre><code>"""utils/cli.py - Command-line utilities for parsa
Classes:
_SmartFormatter - allows formatting in the CLI help menu
Functions:
parse_arguments - parse CLI arguments
_set_arguments - set CLI description and arguments
"""
import argparse
class _SmartFormatter(argparse.HelpFormatter):
"""Allows formatting in the CLI help menu.
Called by beginning a string with R| in _set_arguments().
https://stackoverflow.com/a/22157136
"""
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def parse_arguments():
"""Parse command-line arguments, and return a Namespace object containing them."""
argparser = _set_arguments()
# Parse arguments into Namespace
args = argparser.parse_args()
return args
def _set_arguments():
"""Set CLI description and arguments."""
argparser = argparse.ArgumentParser(description=('Textract-based text parser that supports most text file extensions. '
'Parsa can parse multiple formats at once, '
'writing them to .txt files in the directory of choice.'), formatter_class=_SmartFormatter)
argparser.add_argument('input', help=('input file or folder; if a folder is passed as input, '
'parsa will scan every file inside it recursively (scanning subfolders as well)'))
# TODO - describe what the stats file will include
argparser.add_argument('--stats', '-s', nargs='?', help='output stats file')
argparser.add_argument('--output', '-o', nargs='?', default=None, help=('R|folder where the output files '
'will be stored. The default folder is: \n'
'(a) the input file\'s parent folder, if the input is a file, or \n'
'(b) a folder named \'parsaoutput\' located in the input folder, if the input is a folder.'))
return argparser
</code></pre>
<h1><strong>utils/filesystem.py</strong></h1>
<pre><code>"""utils/filesystem.py - OS/filesystem utilities for parsa
Functions:
compose_unique_filepath - compose a filepath to avoid overwriting existing files
get_filelist - return list of files of a directory and all subdirectories
set_outdir - set output directory based on the user's choice
write_str_to_file - write string to file
"""
import os
def compose_unique_filepath(infile, outdir):
"""Compose output filepath to avoid overwriting existing files.
If a file with the same name as the output file already exists in the output directory,
the input file's extension will be included in the output file's name before the .txt extension.
(e.g. if foo.txt already exists, foo.pdf will be extracted to foo.pdf.txt)
An incrementing counter will be included before .txt to identify subsequent extractions with the same name.
(if foo.pdf.txt exists as well, foo.pdf will be extracted to foo.pdf2.txt, with 2 being the incrementing counter)
"""
# Get input's filename with neither its path nor extension
# e.g. /home/testdocs/test.pdf -> test
filename_noextension = os.path.basename(os.path.normpath(os.path.splitext(infile)[0]))
# Create path for output file
# os.path.join intelligently creates filepaths that work cross-platform
# e.g. /home/testdocs/ + test.pdf -> /home/testdocs/test
outfilepath_noextension = os.path.join(outdir, filename_noextension)
outfile = outfilepath_noextension + '.txt'
file_exists_counter = 1
# This loop is only entered if the outfile already exists
while os.path.exists(outfile):
input_extension = os.path.splitext(infile)[1]
# If it's the first iteration, just add the input extension to the filename
if file_exists_counter == 1:
outfile = outfilepath_noextension + input_extension + '.txt'
# Otherwise, add a counter too
else:
outfile = outfilepath_noextension + input_extension + str(file_exists_counter) + '.txt'
file_exists_counter += 1
return outfile
def get_filelist(indir):
# TODO - check this with a lot of files, because theoretically you're going through 2 for loops for each file and that might be inefficient (O(n) still)
"""Return list of files in the input directory, including the files in all subdirectories."""
filelist = []
# Cycle through all files in the directory recursively
# https://stackoverflow.com/a/36898903
for root, dirs, files in os.walk(indir, topdown=True):
# Remove the parsaoutput folder from the list of directories to scan
# (allowed by topdown=True in os.walk's parameters)
# https://stackoverflow.com/a/19859907
dirs[:] = [d for d in dirs if d != 'parsaoutput']
for filename in files:
filepath = os.path.join(root, filename)
filelist.append(filepath)
return filelist
def set_outdir(args_outdir, indir):
"""Set output directory based on whether a custom outside directory was provided or not, and return it."""
# If output directory wasn't provided, set it to the input directory
if args_outdir == None:
outdir = indir
else:
outdir = args_outdir
return outdir
def write_str_to_file(text, outfile):
"""Write input text string to a file."""
with open(outfile, "x") as fout:
fout.write(text)
</code></pre>
<h1><strong>utils/text.py</strong></h1>
<pre><code>"""utils/text.py - Text utilities for parsa
Functions:
get_text - extract text from the input file
_process_text - process extracted text and return it as a simple string
"""
import os
import textract
def get_text(infile, _infile_extension=None):
"""Extract text from the input file using textract, returning an empty string if failing to do so.
If the infile does not explicitly have an extension (UnicodeDecodeError),
the user will be prompted to input the correct extension (either with or without a dot).
get_text is then recursively called with _infile_extension set to the input extension.
The caller should never set _infile_extension to anything in most cases,
unless they want to skip the prompt for input extension and the entirety of the input is of the same format.
"""
# If text is not extracted or the infile is empty, the function will just return an empty string
text = ''
try:
text = textract.process(infile, extension=_infile_extension)
# File existence gets checked in parsa.py
except textract.exceptions.ExtensionNotSupported:
print("Error while parsing file: " + infile)
print("Extension not supported\n")
# Skip file if parsing has failed
except textract.exceptions.ShellError as e:
print("Error while parsing file: " + infile)
print(e)
# If the file has no explicit extension, prompt the user for it
except UnicodeDecodeError:
print("Error while parsing file: " + infile)
print("File has no extension\n")
# Prompt the user for the input file's extension
# textract.process adds a dot before the input extension if it's not already present (e.g. txt -> .txt)
_infile_extension = input("Please input the file's extension (e.g. .pdf or pdf):")
# Call the function again; an exception will be raised on failure
text = get_text(infile, _infile_extension)
# If no exceptions happened, format text adeguately
else:
# Extract input file's extension unless it has already been specified
if not _infile_extension:
_infile_extension = os.path.splitext(infile)[1]
text = _process_text(text, _infile_extension)
return text
def _process_text(text, _infile_extension):
"""Process extracted text and return it as a simple string."""
# utf-8 is used here to handle different languages efficiently (https://stackoverflow.com/a/2438901)
text = text.decode('utf-8')
# Remove unnecessary trailing space caused by the form feed (\x0c, \f) character at the end of .pdf files
if _infile_extension == '.pdf' or _infile_extension == 'pdf':
text = text.strip()
return text
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T13:56:10.140",
"Id": "203874",
"Score": "2",
"Tags": [
"python",
"beginner",
"parsing"
],
"Title": "Multiformat text parser in Python"
} | 203874 |
<p><strong>Background</strong>: I'm designing a system Data entry form using c# as front end and sql server 2008 as backend database.
In this app I'm basically, just reading/writing to the database</p>
<p><strong>My issue:</strong> </p>
<ol>
<li>I never truly understood OOP, however I am getting more involved
with it now, and while my program works, I want the code to be
better (look better, be more flexible, utilize classes/objects more,
etc.). </li>
<li>Being my first application I have no idea how messy the
code is, if it conforms to guidelines, etc. Hopefully I will get
some good feedback about improvements that can be made, but other
than that, it works perfectly in all my tests!</li>
<li>I have written all the functionality in a single class with my understanding
it is not a correct way to do. But how to know whether which functionality
should be separated or aggregated</li>
</ol>
<p><strong>Note: The code below is a fully working application where all the business case has been working fine.</strong> </p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//Wrote the code to populate the date time on the time of loding the form
DateTime dateTime = DateTime.Now;
try
{
DateTime dt = DateTime.Parse(textBox1.Text);
//The user should not select the time that is greater than the current date time
if (dt > dateTime )
{
MessageBox.Show("Dateshould not be greater than current date");
textBox1.Text = dateTime.ToString("yyyy-MM-dd");
}
else if( dt <= dateTime.AddDays(-16))
{
MessageBox.Show("Date Should Not Be Less Than 15days From The Current Date");
textBox1.Text = dateTime.ToString("yyyy-MM-dd");
}
}
catch (Exception ex)
{
}
}
private void Form1_Load_1(object sender, EventArgs e)
{
/*The text should not be editable for the following textboes
1) Date
2) username
3) Total Audits Reviewed
4) Audit carry forward
5) Pending*/
textBox1.ReadOnly = true;
textBox9.ReadOnly = true;
textBox12.ReadOnly = true;
textBox8.ReadOnly = true;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = true;
dateTimePicker1.Visible = false;
textBox1.Text = dateTimePicker1.Value.ToString("yyyy-MM-dd");
textBox11.Text = Environment.UserName;
dropdown_combox1_values();
dropdown_combox5_values();
button2.Enabled = false;
button3.Enabled = false;
comboBox3.SelectedIndex = 4;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
textBox1.Text = dateTimePicker1.Value.ToString("yyyy-MM-dd");
dateTimePicker1.Visible = false;
}
private void textBox1_DoubleClicked(object sender, EventArgs e)
{
dateTimePicker1.Visible = true;
}
public void dropdown_combox1_values()
{
comboBox1.Items.Add("Home Health - Post pay");
comboBox1.Items.Add("Home Health - Pre pay");
}
public void dropdown_combox5_values()
{
comboBox3.Items.Add("OASIS");
comboBox3.Items.Add("Per visit");
comboBox3.Items.Add("Leave");
comboBox3.Items.Add("Holiday");
comboBox3.Items.Add("N\\A");
comboBox3.Items.Add("QC");
comboBox3.DropDownStyle = ComboBoxStyle.DropDownList;
}
public void dropdown_combox2_values()
{
comboBox2.Items.Add("Humana OASIS");
comboBox2.Items.Add("Humana Per visit");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox2.Items.Clear();
dropdown_combox2_values();
}
private void comboBox2_SelectedIndexChanged_1(object sender, EventArgs e)
{
comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void button1_Click(object sender, EventArgs e)
{
int i;
/*
Check for test condition when the user will give data that violates the process
*/
if (comboBox1.SelectedIndex != -1)
{
if (comboBox2.SelectedIndex != -1)
{
if (textBox2.Text != "")
{
if (int.TryParse(textBox2.Text, out i))
{
if (textBox3.Text != "")
{
if (int.TryParse(textBox3.Text, out i))
{
if (textBox4.Text != "")
{
if (int.TryParse(textBox4.Text, out i))
{
if (textBox5.Text != "")
{
if (int.TryParse(textBox5.Text, out i))
{
if(textBox6.Text != "" )
{
if(int.TryParse(textBox6.Text, out i))
{
if(textBox7.Text != "")
{
if (int.TryParse(textBox7.Text, out i))
{
if (textBox10.Text != "")
{
if(int.TryParse(textBox10.Text, out i))
{
if (comboBox3.SelectedIndex != -1)
{
calcuate_values();
}
else
{
MessageBox.Show("Please select the Appropriate Comment", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox10.Text = "";
}
}
else
{
MessageBox.Show("Provide Audits Assigned","Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox7.Text = "";
}
}
else
{
MessageBox.Show("Provide Target/day",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox6.Text = "";
}
}
else
{
MessageBox.Show("Provide Unfullfilled Data",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox5.Text = "";
}
}
else
{
MessageBox.Show("Provide Rejection Data", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox4.Text = "";
}
}
else
{
MessageBox.Show("Provide Total Findings Data", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox3.Text = "";
}
}
else
{
MessageBox.Show("Provide Partital Denial Data", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Check whether the data is a number", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
textBox2.Text = "";
}
}
else
{
MessageBox.Show("Provide Full Denial Data", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Select Workflow", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Select Program", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
private void textBox11_TextChanged(object sender, EventArgs e)
{
textBox11.ReadOnly = true;
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
}
//private void textBox_TextChanged(object sender, EventArgs e)
//{
//}
public void calcuate_values()
{
try
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(@"[NAS\kalais1].[HomeHealth_Validate_Search]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Date", SqlDbType.Date).Value = textBox1.Text;
command.Parameters.Add("@Username", SqlDbType.VarChar).Value = textBox11.Text;
command.Parameters.Add("@workflow", SqlDbType.VarChar).Value = comboBox2.Text;
command.Parameters.Add("@program", SqlDbType.VarChar).Value = comboBox1.Text;
SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
command.ExecuteNonQuery();
SqlDataReader oReader = command.ExecuteReader();
while (oReader.Read())
{
if (oReader["Pending_Audits"].ToString() == "Already exists")
{
MessageBox.Show("The given workflow and program is already present for the given date");
textBox12.Text = "";
textBox8.Text = "";
textBox9.Text = "";
}
else
{
textBox12.Text =
(Convert.ToInt32(textBox2.Text) +
Convert.ToInt32(textBox3.Text) +
Convert.ToInt32(textBox4.Text)).ToString();
textBox8.Text = oReader["Pending_Audits"].ToString();
textBox9.Text =
((Convert.ToInt32(textBox10.Text) + Convert.ToInt32(textBox8.Text)) -
Convert.ToInt32(textBox12.Text)).ToString();
MessageBox.Show("Validated the data! Please Submit.. ");
button2.Enabled = true;
}
}
}
}
}
catch (Exception ex)
{
// Print error message
MessageBox.Show(ex.Message);
}
}
private void textBox10_TextChanged(object sender, EventArgs e)
{
}
private void Show_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
public void ClearTextBoxes(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
if (c.Name != "textBox11" && c.Name != "textBox1")
{
if (!(c.Parent is NumericUpDown))
{
((TextBox) c).Clear();
}
}
}
else if (c is ComboBox)
{
((ComboBox)c).SelectedIndex = -1;
comboBox3.SelectedIndex = 4;
}
if (c.HasChildren)
{
ClearTextBoxes(c);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(@"[NAS\kalais1].[HomeHealth_Submit_test]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Date", SqlDbType.Date).Value = textBox1.Text;
command.Parameters.Add("@Username", SqlDbType.VarChar).Value = textBox11.Text;
command.Parameters.Add("@workflow", SqlDbType.VarChar).Value = comboBox2.Text;
command.Parameters.Add("@program", SqlDbType.VarChar).Value = comboBox1.Text;
command.Parameters.Add("@Full_Denial", SqlDbType.Int).Value = textBox2.Text;
command.Parameters.Add("@Partial_Denial", SqlDbType.Int).Value = textBox3.Text;
command.Parameters.Add("@No_Findings", SqlDbType.Int).Value = textBox4.Text;
command.Parameters.Add("@Rejections", SqlDbType.Int).Value = textBox5.Text;
command.Parameters.Add("@Unfulfilled", SqlDbType.Int).Value = textBox6.Text;
command.Parameters.Add("@TargetPerDay", SqlDbType.Int).Value = textBox7.Text;
command.Parameters.Add("@Audits_Assigned", SqlDbType.Int).Value = textBox10.Text;
command.Parameters.Add("@Total_Audits_Reviewed", SqlDbType.Int).Value = textBox12.Text;
command.Parameters.Add("@Audits_Carry_Forward", SqlDbType.Int).Value = textBox8.Text;
command.Parameters.Add("@Pending_Audits", SqlDbType.Int).Value = textBox9.Text;
command.Parameters.Add("@Comments", SqlDbType.VarChar).Value = comboBox3.Text;
SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
}
else
{
MessageBox.Show("Inserted");
ClearTextBoxes(this);
button2.Enabled = false;
}
}
}
}
}
}
private void Search_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = false;
if (comboBox1.SelectedIndex != -1)
{
if (comboBox2.SelectedIndex != -1)
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(@"[NAS\kalais1].[HomeHealth_Search]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Workflow", SqlDbType.VarChar).Value = comboBox2.Text;
command.Parameters.Add("@Date", SqlDbType.Date).Value = textBox1.Text;
command.Parameters.Add("@Username", SqlDbType.VarChar).Value = textBox11.Text;
command.Parameters.Add("@program", SqlDbType.VarChar).Value = comboBox1.Text;
SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
// command.ExecuteNonQuery();
//MessageBox.Show(returnParameter.Value.ToString());
//MessageBox.Show(comboBox2.Text);
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["Error"].ToString() == "0")
{
textBox2.Text = oReader["Full_Denial"].ToString();
textBox3.Text = oReader["Partial_Denial"].ToString();
textBox4.Text = oReader["No_Findings"].ToString();
textBox5.Text = oReader["Rejections"].ToString();
textBox6.Text = oReader["Unfulfilled"].ToString();
textBox7.Text = oReader["TargetPerDay"].ToString();
textBox10.Text = oReader["Audits_Assigned"].ToString();
comboBox3.Text = oReader["Comments"].ToString();
textBox12.Text = oReader["Total_Audits_Reviewed"].ToString();
textBox8.Text = oReader["Audits_Carry_Forward"].ToString();
textBox9.Text = oReader["Pending_Audits"].ToString();
MessageBox.Show("Required Data... Has been populated");
button3.Enabled = true;
comboBox1.Enabled = false;
comboBox2.Enabled = false;
}
else
{
MessageBox.Show("Check Whether You have selected Program and workflow currectly");
ClearTextBoxes(this);
comboBox1.Enabled = true;
comboBox2.Enabled = true;
button1.Enabled = true;
}
}
}
}
}
}
else
{
MessageBox.Show("Select Workflow", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Select Program", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
private void button3_Click(object sender, EventArgs e)
{
textBox12.Text =
(Convert.ToInt32(textBox2.Text) +
Convert.ToInt32(textBox3.Text) +
Convert.ToInt32(textBox4.Text)).ToString();
textBox9.Text =
((Convert.ToInt32(textBox10.Text) + Convert.ToInt32(textBox8.Text)) -
Convert.ToInt32(textBox12.Text)).ToString();
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(@"[NAS\kalais1].[HomeHealth_Update]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Workflow", SqlDbType.VarChar).Value = comboBox2.Text;
command.Parameters.Add("@date", SqlDbType.Date).Value = textBox1.Text;
command.Parameters.Add("@Username", SqlDbType.VarChar).Value = textBox11.Text;
command.Parameters.Add("@Program", SqlDbType.VarChar).Value = comboBox1.Text;
command.Parameters.Add("@Full_Denial", SqlDbType.Int).Value = textBox2.Text;
command.Parameters.Add("@Partial_Denial", SqlDbType.Int).Value = textBox3.Text;
command.Parameters.Add("@No_Findings", SqlDbType.Int).Value = textBox4.Text;
command.Parameters.Add("@Rejections", SqlDbType.Int).Value = textBox5.Text;
command.Parameters.Add("@Unfulfilled", SqlDbType.Int).Value = textBox6.Text;
command.Parameters.Add("@TargetPerDay", SqlDbType.Int).Value = textBox7.Text;
command.Parameters.Add("@Audits_Assigned", SqlDbType.Int).Value = textBox10.Text;
command.Parameters.Add("@Total_Audits_Reviewed", SqlDbType.Int).Value = textBox12.Text;
command.Parameters.Add("@Audits_Carry_Forward", SqlDbType.Int).Value = textBox8.Text;
command.Parameters.Add("@Pending_Audits", SqlDbType.Int).Value = textBox9.Text;
command.Parameters.Add("@Comments", SqlDbType.VarChar).Value = comboBox3.Text;
SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("Please.. Check the comments and populated values");
}
else
{
MessageBox.Show("Updated");
ClearTextBoxes(this);
comboBox1.Enabled = true;
comboBox2.Enabled = true;
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = false;
}
}
}
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:33:02.107",
"Id": "393059",
"Score": "1",
"body": "Please describe what your application is doing in more detail. It'd be great if you could also share a screenshot."
}
] | [
{
"body": "<p>Some quick remarks </p>\n\n<ul>\n<li>Name you things properly. E.g <code>comboBox3</code> will make you wonder what it is, if you come in 2 months to fix a bug or add some functionality. Always name your things in a way that you see at first glance what they are about. </li>\n<li>Instead of usi... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:22:12.410",
"Id": "203876",
"Score": "-2",
"Tags": [
"c#",
"winforms"
],
"Title": "Data entry User form Application - winforms"
} | 203876 |
<p>I need to open a file, read a line and if that line respect some conditions write it to another file, the line that I'm reading is a normal ASCII string representig HEX values and I need to paste it into a new file as HEX values and not as ASCII string.</p>
<p>What I have is this:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
byte[] arrayByte = { 0x00 };
var linesToKeep = File.ReadLines(fileName).Where(l => l.Contains(":10"));
foreach (string line in linesToKeep)
{
string partialA = line.Substring(9);
string partialB = partialA.Remove(partialA.Length - 2);
arrayByte = ToByteArray(partialB);
using (var stream = new FileStream(fileName+"_gugggu", FileMode.OpenOrCreate))
{
FileInfo file = null;
file = new FileInfo(fileName + "_gugggu");
stream.Position = file.Length;
stream.Write(arrayByte, 0, arrayByte.Length);
}
}
}
public static byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
</code></pre>
<p>This method is doing what I need but it takes ages to finish, the original files have roughly 70000 lines... Is there a better way to do that in order to increase speed?</p>
<p><strong>EDIT</strong>
SOURCE FILE EXAMPLE:</p>
<pre><code>:106AD00000000000000000000000000000000000B6
:106AE00000000000000000000000000000000000A6
:106AF0000000000000000000000000000000000096
:106B00000000000000000000000000000000000085
:106B10000000000000000000000000000000000075
:106B20000000000000000000000000000000000065
:106B30000000000000000000000000000000000055
:106B40000000000000000000000000000000000045
:106B50000000000000000000000000000000000035
:106B60000000000000000000000000000000000025
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:53:38.333",
"Id": "393064",
"Score": "2",
"body": "@t3chb0t edited my question to include source file example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:55:56.113",
"Id": "393065",
... | [
{
"body": "<p>It is OK to use <code>File.ReadLines(...)</code> because it actually is shortcut to <code>StreamReader.ReadLine()</code> (Not to be confused with <code>File.ReadAllLines()</code>).</p>\n\n<hr>\n\n<p>I wonder why you reopen the same file for each line you want to save. I would do something like thi... | {
"AcceptedAnswerId": "203882",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:48:32.003",
"Id": "203877",
"Score": "6",
"Tags": [
"c#",
"file"
],
"Title": "Copy certain lines from one text file to another"
} | 203877 |
<p>I have some data, which I've faked using:</p>
<pre><code>def fake_disrete_data():
in_li = []
sample_points = 24 * 4
for day, bias in zip((11, 12, 13), (.5, .7, 1.)):
day_time = datetime(2016, 6, day, 0, 0, 0)
for x in range(int(sample_points)):
in_li.append((day_time + timedelta(minutes=15*x),
int(x / 4),
bias))
return pd.DataFrame(in_li, columns=("time", "mag_sig", "bias")).set_index("time")
fake_disc = fake_disrete_data()
</code></pre>
<p>I can pivot each column individually using and then concatenate them using:</p>
<pre><code>cols = list(fake_disc.columns.values)
dfs = []
for col in cols:
dfs.append(pd.pivot_table(fake_disc,
index=fake_disc.index.date,
columns=fake_disc.index.hour,
values=col,
aggfunc=np.mean))
all_df = pd.concat(dfs, axis=1, keys=cols)
</code></pre>
<p>But is there a better way to do this?</p>
<p>I'm trying to follow the answers seen in <a href="https://stackoverflow.com/questions/44165629/pandas-pivot-table-for-multiple-columns-at-once">Pandas pivot table for multiple columns at once</a> and <a href="https://stackoverflow.com/questions/48971114/how-to-pivot-multilabel-table-in-pandas">How to pivot multilabel table in pandas</a>, but I'm having a difficult time translating their methods to the <code>DateTimeIndex</code> case.</p>
| [] | [
{
"body": "<h1>Review</h1>\n\n<p>all in all, this code is rather clean. I would use a generator comprehension and <code>itertools.chain</code> in <code>fake_disrete_data</code> instead of the nested for-loop, but that is a matter of taste</p>\n\n<h2>linewraps</h2>\n\n<p>I prefer to wrap lines after the <code>(<... | {
"AcceptedAnswerId": "204330",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T14:53:20.483",
"Id": "203878",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Pivot DataFrame with DateTimeIndex"
} | 203878 |
<p>I'm writing an independent code which I'll import into an exe, Here is an self-contained example:</p>
<p>This code is a PCSTATE handler - basically when lara starts walking - this code will be executed. It checks for button presses and specific states (i.e. when an enemy is nearby and the action button is pressed - <code>l(char, 0x128) == 2</code>).</p>
<pre><code>enum LARA_ANIM //lara animation IDs
{
LARA_RUN_TURN180, //here given only
LARA_RUNJUMP //2 for obvious reasons
}; //code will be too long
#define playIsSourceAnim ((int (*)(char *,enum LARA_ANIM))0x005530AC) //an address that is a function in the host executable
#define printf ((int (*)(char const* const, ...))0x005D4280)
#define playWalkingCallback ((int (*)(char *, unsigned int))0x00553618)
#define playStandingCallback ((int (*)(char *, unsigned int))0x005535F0)
#define playSwimCheckStatus_ForSurface ((int (*)(char *, float *,float))0x000578020)
#define flt0 (*(float*)0x07FA4D8) //unusued
#define fxTriggerRipple1 ((int (*)(float (*)[4], float, float))0x004CF3E4)
#define fxRandf ((float (*)(float))0x004B56C4)
#define fxGetWaterHeight ((float (*)(float (*)[4]))0x004D4D08)
#define WadeRippleCounter (*(int *)0x07B5904)
#define playCheckStepUp ((int (*)(char*,int))0x00552C40)
#define playHandleStandardJumpRequest ((int (*volatile)(char*))0x0056CC1C)
#define playStartRoll ((int (*)(char*))0x005719E8)
#define playHandleRunJumpRequest ((int (*)(char*))0x056CB38)
#define playRunningCallback ((int (*)(char*, unsigned int))0x553650)
#define playBlendAnimationCB ((int (*)(char*,enum LARA_ANIM,int,int (*)(char *, unsigned int),enum PCSTATE))0x005532C4)
#define cast(type, p) ((type) (p)) //code sugar
#define casta(type, p) *((type *) (p)) //code sugar 1
#define l(type, p) (*(*(cast(type **, Sp) + 0x150 / 4) + (p) / sizeof(type))) //OK so at 0x150 is a structure, Sp is our entry function first argument and the first argument of most of our calls
#define m60 l(float, 0x60) //m60 is the lara rotation
//change the above field to make her rotate
#define playSetAnimRateByAnalogStick \
cast(int(*)(char *, float, float, float, float), 0x56DFD0) //here
//we are using the syntax sugar
//#define float_const(p, )
#define gAnimTargetMS cast(float *,0x0926C08)
#define gplayCollisionInfo cast(char *,0x007F9480)
_forceinline float vfl_partl(unsigned int j) { return *cast(float*, &j); }
#define vfl_part(a,b, c, d, r) f##a##c##b = vfl_partl(r)//fapb=floathexvalue
#define vfl(a,b, f) vfl_part(a,b,p,.,f)//here we are using a helper macro
//to pass all the needed part of the variable name - p and f . is left unused
#define playStepOffLedge cast(int (*)(char*),0x00567268)
#define _playPlayerShouldFall cast(int (*)(char*,char*,float),0x0056DBF4)
#define _playPlayerRequestFall cast(int (*)(char *,int),0x0056DEF0)
#define _playHandleRunJumpRequest cast(int(*)(char*),0x0056C9C0)
#define _playHandleStandardJumpRequest cast(int(*)(char*),0x0056CAA4)
#define _playHandToHandStart cast(int(*)(char*),0x005603B8)
#define _playStartRoll cast(int(*)(char*),0x00571764)
#define _playHandleStealthRequest cast(int(*)(char*),0x00575F50)
int playHandlerWalk(char *Sp)
{
float vfl(1, 5, 0x3fc00000), vfl(1, 0, 0x3f800000), vfl(0, 25, 0x3e800000
), vfl(0, 1, 0x3dcccccd),vfl(0,75, 0x3f400000);//Here we are defining the float constants - I use web browser to calculate the hex values
if (!l(char, 0x150))//Set some kind of rotation
m60 *= f1p0 - casta(float, 0x007F9370) * f0p25;
playSetAnimRateByAnalogStick(Sp, *cast(float *, 0x967CC8) * *gAnimTargetMS,
*gAnimTargetMS, f0p1, l(char, 0xc) ? f1p0 : f0p75);
if (l(char, 0x128) == 8) playStepOffLedge(Sp);
if (_playPlayerShouldFall(Sp, gplayCollisionInfo, 0))
_playPlayerRequestFall(Sp, 1);
if (l(enum LARA_ANIM, 0x14) == LARA_RUN_TURN180 ||
l(enum LARA_ANIM, 0x14) == LARA_RUNJUMP)
return m60 = 0; //Obviously if we are turning around or jumping we don't need to rotate
if (casta(unsigned int, 0x007F9430) & 0x20)//If the jump button is pressed
if (casta(unsigned int, 0x007F9880) & 0xE007)
_playHandleStandardJumpRequest(Sp);
else
_playHandleRunJumpRequest(Sp);
if (l(char, 0x128) == 2)//If HtH should begin
_playHandToHandStart(Sp);
if (casta(unsigned int, 0x007F9430) & 0x80)//If the roll button is pressed
return _playStartRoll(Sp);
if (l(char, 0xc) & 4)_playHandleStealthRequest(Sp); //If the stealth button is pressed
}
_fltused()
{}
</code></pre>
<p>Compile like this:</p>
<pre><code>cl x.c /Ox /GS- /link /NODEFAULTLIB /DYNAMICBASE:NO /BASE:0x40000 /SUBSYSTEM:native /entry:playHandlerWalk
</code></pre>
<p>I'm obviously using the Microsoft C++ Compiler (community edition latest version).</p>
<p>Look at the way I'm defining floats - this is because it's the only way they will be embedded into my code (I'm using online float to hex converter) - otherwise the compiler will use global constants which will not be present in the context for which this code is targeted.</p>
<p>I swear the above code compiles if you use the command line parameters provided above and a modern Microsoft C compiler.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T19:42:38.183",
"Id": "393105",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I changed the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T20:09:32.113",
"Id": "393107",
"Score": "2",
"body": "T... | [
{
"body": "<pre><code>#define cast(p, type) ((type) p)\n</code></pre>\n\n<p>I suggest you take <code>p</code> from macro's expansion in parentheses as well:</p>\n\n<pre><code>#define cast(p, type) ((type) (p))\n</code></pre>\n\n<p>Consider <code>cast(3.6 + 3.6, int)</code>.</p>\n\n<p>Or even better,</p>\n\n<pre... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T15:36:38.310",
"Id": "203883",
"Score": "-4",
"Tags": [
"c",
"casting"
],
"Title": "Embedded code for another executable - Lara walk handler decompilation"
} | 203883 |
<p>hoping to be schooled a little bit here in showing "no results".
This is a working snippet, but I'd like to know if there is a more elegant way to show errors when comparing multiple values in an IF statement within a ForLoop... I could have 10 results with only 2 matching my if statement:</p>
<pre><code>if($value["IsArchived"] == false && !preg_match("/^123 ABC/", $value["ProjectName"]))
</code></pre>
<p>Is there better way than capturing a count variable $totalToShow == 0 to show my "No Results" in a new IF statement or is that ok? </p>
<pre><code>$obj = drupal_json_decode($result);
//used to show NO RECORDS or not... probably a more elegant way here?!
$totalToShow = 0;
//loop through the json data and add it to the $output array.
//NOTE: not checking if any are empty
$output .= '<ul class="list-group" style="margin-bottom:15px;">';
//check if the obj is empty, if so, no records to display...
if (!empty((array) $obj)) {
foreach($obj as $key=>$value){
if($value["IsArchived"] == false && !preg_match("/^123 ABC/", $value["ProjectName"])){
$totalToShow++;
//output project name link to project # and append start/end date after link.
$output .= '<li class="list-group-item"><strong>' . $value["ProjectName"] . '</strong> ('. _abc_date($value["CommentStart"]) . " - " . _abc_date($value["CommentEnd"]).') ';
if($lrnmore != ""){
$output .= ' | <a href="CommentInput?project='.$value["ProjectNumber"].'">'. $lrnmore .'</a>';
}
$output .= '| <a href="ReadingRoom?project='.$value["ProjectNumber"].'">View Comments</a><br/>';
$output .= '<ul><li>' . $value["Description"] . '</li></ul>';
$output .= "</li>";
}
}
if($totalToShow == 0){
$output .= '<li class="list-group-item">No Records to Display</li>';
}
</code></pre>
| [] | [
{
"body": "<p>In case there is any chance to use a template engine, then you should <strong>prepare your data first</strong></p>\n\n<pre><code>$obj = drupal_json_decode($result);\n$output = [];\nforeach($obj as $row){\n if(!$value[\"IsArchived\"] && !preg_match(\"/^123 ABC/\", $value[\"ProjectName\"]... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T18:00:06.300",
"Id": "203892",
"Score": "0",
"Tags": [
"php"
],
"Title": "Results Reporting / Checking with Multiple Results in For Loop"
} | 203892 |
<p>Can you guys tell me if my login is secure?</p>
<p><strong>Login.php</strong></p>
<pre><code><?php include 'session.php';?>
<?php
if(isset($_POST['username'])){
include 'dbh.inc.php';
$uname=$_POST['username'];
$password=$_POST['password'];
$secretcode=$_POST['secretcode'];
if (empty($uname) || empty($password) || empty($secretcode)) {
header("Location: ../index.php?login=empty");
} else {
$sql="select * from loginform where User = ? AND SCode= ? limit 1";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=error");
} else {
mysqli_stmt_bind_param($stmt, "ss", $uname, $secretcode);
if (mysqli_stmt_execute($stmt) == true) {
$result = $stmt->get_result();
if ($row = mysqli_fetch_assoc($result)) {
$hashedpsw = password_verify($password, $row['Pass']);
if ($hashedpsw == true) {
$_SESSION['Admin']=$uname;
// Log in
header('Location: ../index.php?login=success');
exit();
} else {
header("Location: ../index.php?login=error");
exit();
}
} else {
header("Location: ../index.php?login=error");
}
} else {
header("Location: ../index.php?login=error");
}
}
}
} else {
header("Location: ../page-not-found.php");
}
?>
</code></pre>
<p><strong>session.php</strong></p>
<pre><code><?php
ini_set('session.use_only_cookies', 1);
session_set_cookie_params(0,'/','localhost',false,true);
session_start();
session_regenerate_id();
?>
</code></pre>
<p><strong>hashing script</strong></p>
<pre><code>password_hash("test", PASSWORD_BCRYPT, array('cost' => 12));
</code></pre>
<p><strong>index.php form</strong></p>
<pre><code><form action="phpfunctions/checklogin.php" method="POST">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="password" name="secretcode" placeholder="****"
maxlength="4">
<button name="submit">LOGIN</button>
</form>
</code></pre>
<p><strong>index.php</strong></p>
<pre><code><?php
include 'phpfunctions/s-session.php';
if (!isset($_SESSION['Admin'])) {
$_SESSION['requestUrl'] = $_SERVER['REQUEST_URI'];
}
?>
<!DOCTYPE html>
<html lang="eu">
<head>
<!-- All meta -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.5">
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<link rel="icon"href="https://orig00.deviantart.net/60fe/f/2011/265/b/3/lsi_logo_icon_256_png_by_mahesh69a-d4an1lt.png">
<meta name="description" content="Shaadyy Website - Home | Gallery | FAQ |
Contact">
<meta name="keywords" content="Shaadyy Website KS Kasai Clan Web Programmer
Designer">
<meta name="author" content="Shaadyy">
<!-- Sites Information -->
<title>Home - Shaadyy</title>
<!-- Custom Fonts -->
<link href="https://fonts.googleapis.com/css?family=Lato|Open+Sans|Roboto"
rel="stylesheet">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.1.0/css/all.css"
integrity="sha384-
lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt"
crossorigin="anonymous">
<!-- My src css files -->
<link rel="stylesheet" href="src/css/index.css">
<link rel="stylesheet" href="src/css/main.css">
<!-- My src javascript files -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="src/js/nav-opacity.js"></script>
<script src="src/js/scroll-elements.js"></script>
</head>
<body>
<!-- ( Navbar ) -->
<header id="Header">
<div class="nav-content">
<div class="Header-Title"><h1>Shaadyy</h1></div>
<div class="Nav-Items">
<nav>
<ul>
<li><a href="#Main-S">Home</a></li>
<li><a href="Gallery.php">Gallery</a></li>
<li><a href="faq.php">Faq</a></li>
<li><a class="ContactBtn" href="">Contact</a></li>
<?php
if (isset($_SESSION['Admin'])) {
echo '<li><a href="Settings.php"><i class="fas fa-cog"></i></a>
</li>';
echo '<li><a href="phpfunctions/logout.php"><i class="fas fa-sign-
out-alt"></i></a></li>';
}
?>
</ul>
</nav>
</div>
</div>
</header>
<!-- ( Body Elements ) -->
<main>
<div id="Main-S" class="Main-Section">
<div class="Main-S-Content">
<h1>Web Developer</h1>
<h2>Are You Interested? Contact Me</h2>
<button class="ContactBtn">Contact</button>
<h3>See More About Me</h3>
<i id="SeeMoreBtn" class="fas fa-angle-double-down"></i>
</div>
</div>
<div id="AboutMe-S" class="AboutMe-Section">
<div class="AboutMe-S-Content">
<div class="AboutMe-Photo Circle-50">
</div>
<div class="AboutMe-Information">
<p>
</p>
</div>
</div>
</div>
<div id="IG-S" class="IG-Section"> <!-- About Me Section -->
<div class="IG-Content">
<div class="IG-Logo"></div>
<div class="IG-Button">
<form action="https://www.instagram.com/mignaway/" target="_blank">
<button>GO</button>
</form>
</div>
</div>
</div>
<div id="OW-S" class="OW-Section"> <!-- OW Section -->
<div class="OW-Background"></div>
<div class="OW-Content">
<div class="ow-logo"></div>
<div class="ow-information">
<?php
include 'phpfunctions/owstats.php';
echo '<h4 class="ow-nick">Nickname: <span>'.$nick.'</span></h4>
<h4 class="ow-rank">Rank: <span>'.$rank.'</span></h4>
<h4 class="ow-elo">Rank Elo: <span>'.$elo.'</span></h4>';
?>
</div>
</div>
</div>
<div id="Login-S" class="Login-Section">
<div class="Login-Padding">
<?php
if (!isset($_SESSION['Admin'])) {
echo '<h1>Login</h1>
<form action="phpfunctions/login.php" method="POST">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="password" name="secretcode" placeholder="****"
maxlength="4">
<button name="submit">LOGIN</button>
</form>';
} else {
echo '<h1>Already Logged</h1>
<form action="phpfunctions/login.php" method="POST">
<input type="text" name="username" placeholder="Username" disabled>
<input type="password" name="password" placeholder="Password"
disabled>
<input type="password" name="secretcode" placeholder="****"
maxlength="4" disabled>
<button disabled>LOGIN</button>
</form>';
}
?>
</div>
</div>
<div id="Gallery-S" class="Gallery-Section">
<div class="Gallery-Padding">
<h1>Gallery</h1>
<a href="Gallery.php"><h2>View All Photos</h2></a>
</div>
</div>
<div id="Contact-S" class="Contact-Section">
<div class="Contact-Padding">
<h1>Contact Me</h1>
<?php
$requestUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (strpos($requestUrl, "email=notvalid") == true) {
echo '<div class="Alert-Mex Error-Mex-Color"><p id="Alert-Mex">*
Please, enter a valid e-mail *</p></div>';
}
elseif (strpos($requestUrl, "email=empty") == true) {
echo '<div class="Alert-Mex Error-Mex-Color"><p id="Alert-Mex">*
Please, fill out all required field *</p></div>';
}
elseif (strpos($requestUrl, "email=sent") == true) {
echo '<div class="Alert-Mex Success-Mex-Color"><p id="Alert-
Mex">* E-Mail Successfully Sent*</p></div>';
}
?>
<form action="phpfunctions/contact-send-mail.php" method="POST">
<input type="text" name="c-fullname" placeholder="Full Name">
<input type="text" name="c-email" placeholder="Your E-Mail">
<textarea name="c-message" placeholder="Message"></textarea>
<button name="c-submit">SEND</button>
</form>
</div>
</div>
</main>
<!-- ( Bottom Page ) -->
<footer>
<div class="Footer-Items">
<div class="Footer-Logo"></div>
<h2>Thank you for visiting my website!</h2>
</div>
</footer>
</body>
</html>
</code></pre>
<p>(i called session.php on every page)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T20:15:42.797",
"Id": "393108",
"Score": "0",
"body": "If secure connections are used the cookie's secure flag should be `true`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T20:18:18.173",
"Id":... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T19:51:41.127",
"Id": "203898",
"Score": "2",
"Tags": [
"php",
"authentication",
"mysqli"
],
"Title": "PHP login script using mysqli"
} | 203898 |
<p>The Following function is supposed to calculate the maximum depth or height of a Binary tree
the number of nodes along the longest path from the root node down to the farthest leaf node.</p>
<p>please comment as if it was a 15 minute coding interview. coding style and efficiency.</p>
<p>this was given to you </p>
<pre><code>public class BinaryTreeNode
{
public BinaryTreeNode Left { get; set; }
public BinaryTreeNode Right { get; set; }
public int Value { get; set; }
}
</code></pre>
<p>please comment on the unit tests as well. </p>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
[TestClass]
public class MaxTreeDepth
{
// 0
// 1 2
// 3
[TestMethod]
public void GetMaxTreeDepthTest()
{
BinaryTreeNode root = new BinaryTreeNode
{
Value = 0,
Left = new BinaryTreeNode {Value = 1},
Right = new BinaryTreeNode {Value = 2}
};
root.Left.Right = new BinaryTreeNode {Value = 3};
int result = GetMaxTreeDepth(root);
Assert.AreEqual(3,result);
}
// 0
[TestMethod]
public void GetMaxTreeDepthTestOneNode()
{
BinaryTreeNode root = new BinaryTreeNode
{
Value = 0,
};
int result = GetMaxTreeDepth(root);
Assert.AreEqual(1, result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GetMaxTreeDepthTestNull()
{
BinaryTreeNode root = null;
int result = GetMaxTreeDepth(root);
}
private int GetMaxTreeDepth(BinaryTreeNode root)
{
if (root == null)
{
throw new ArgumentNullException();
}
int depth = 0;
return GetMaxHelper(root, depth);
}
private int GetMaxHelper(BinaryTreeNode root, int depth)
{
if (root == null)
{
return depth;
}
return Math.Max( GetMaxHelper(root.Right, depth+1), GetMaxHelper(root.Left, depth+1));
}
}
}
</code></pre>
| [] | [
{
"body": "<p><em>(I won't comment on the prescribed <code>BinaryTreeNode</code> definition)</em></p>\n\n<h2>API</h2>\n\n<p>Both <code>GetMaxTreeDepth</code> and <code>GetMaxHelper</code> can, and arguably should, be static, as they have no logical dependencies. <code>GetMaxTreeDepth</code> should of course be ... | {
"AcceptedAnswerId": "203909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T19:52:06.040",
"Id": "203899",
"Score": "4",
"Tags": [
"c#",
"tree",
"interview-questions"
],
"Title": "Maximum depth or height of a Binary tree"
} | 203899 |
<p><strong>Intro:</strong> Before showing the actual code for review, let me show you an <code>ExampleClass</code> to create a <em>shim</em> for. </p>
<pre><code>using System.Windows;
public class ExampleClass
{
public void ExampleMethod(string line) { MessageBox.Show(line); }
}
</code></pre>
<p>The target <em>API</em> of <code>ExampleClass</code> had been <code>.net framework</code>, before some new requirements came to make it <em>multitargeted</em> (both <code>.net framework</code> and <code>.net core 2.0</code>). </p>
<p>One solution is to create a <em>Shim</em> for <code>ExampleClass</code>. This <em>Shim</em> should have <code>ExampleMethod(..)</code> implemented for two <em>APIs</em>. The <em>shim</em> itself should be working on both <em>APIs</em>. </p>
<hr>
<p><strong>Code for Review</strong>, my first approach to shimming: </p>
<p>Base <code>Shim</code>:</p>
<pre><code>public class Shim
{
public object Obj { get; private set; }
public Shim(object defaultObject)
{
Obj = defaultObject;
}
}
//it is possible to create
//two platform specific counterpart classes for ExampleClass
//but i don't like this idea because it implies additional work
</code></pre>
<p>My <em>multitargeted</em> Shim for <code>ExampleClass</code>:</p>
<pre><code>#if NETFULL
using System.Windows;
#endif
namespace PortabilityLibrary.Shims
{
public class ExampleClassShim: Shim
{
public ExampleClassShim(object obj):base(obj) { }
public void ExampleMethod(string line)
{
#if NETFULL
if (Obj is ExampleClass)
((ExampleClass)Obj).ExampleMethod(line);
else
throw new Exception();
#elif NETCORE
if (Obj is NetCoreExampleClass)
((NetCoreExampleClass)Obj).ExampleMethod(line);
else
throw new Exception();
#endif
}
}
}
</code></pre>
<hr>
<p>The following is <strong>no more for review</strong>, it could help to better understand the issue:</p>
<p>The way I could use the code from a <code>.net framework</code> assembly:</p>
<pre><code>public class ExampleCode
{
public static void Do()
{
var x = new ExampleClassShim(new ExampleClass());
x.ExampleMethod("For example...");
}
}
</code></pre>
<p>My sdk-style <code>.csproj</code> file to make clear about <code>NETFULL</code> and <code>NETCORE</code>:</p>
<pre><code><Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFrameworks>netstandard2.0;netcoreapp2.0;net461</TargetFrameworks></PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.0' OR '$(TargetFramework)' == 'netstandard2.0'">
<DefineConstants>NETCORE;</DefineConstants></PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net461'">
<DefineConstants>NETFULL;</DefineConstants></PropertyGroup>
</Project>
</code></pre>
<hr>
<p>Ok, <strong>just in case</strong>, a little bit more explanation:</p>
<p><code>NetCoreExampleClass</code>:</p>
<pre><code>public class NetCoreExampleClass
{
public void ExampleMethod(string line) { Console.WriteLine(line); }
}
</code></pre>
<p><code>NetCoreExampleCode</code>, the way I could use the code from a <code>.net core 2.0</code> assembly:</p>
<pre><code>public class NetCoreExampleCode
{
public static void Do()
{
var x = new ExampleClassShim(new NetCoreExampleClass());
x.ExampleMethod("For example...");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T10:58:11.647",
"Id": "393165",
"Score": "0",
"body": "Why `Shim` with conditional compilation (`#if NETFULL`) and not conditional compilation for the real implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creation... | [
{
"body": "<h1>Does it work / solve the problem?</h1>\n\n<pre><code>public ExampleClassShim(object obj):base(obj) { }\n...\nvar x = new ExampleClassShim(new NetCoreExampleClass());\n</code></pre>\n\n<p>Creating the <code>Shim</code> by passing the <em>real</em> object into constructor is defeating the purpose. ... | {
"AcceptedAnswerId": "203943",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T20:57:16.310",
"Id": "203905",
"Score": "0",
"Tags": [
"c#",
".net",
"portability",
".net-core"
],
"Title": "Creating a Compatibility Shim for ExampleClass to be targeted both to .net framework and .net core 2.0"
} | 203905 |
<p>I made a queue that prints out strings a, b, c, and d. It works, but I want to make sure I don't have any unnecessary code. I realized that my main method prints the strings without the queue. Is there any better way to write the main method and Imp method so that it uses my queue class?</p>
<pre><code> public class Main
{
//this method reverses the string
public static void Imp(StringBuffer str)
{
int n = str.length(); //str.length recognizes the number of
//characters in n, which is also the stack array
Queue obj = new Queue(n); //we set n to a new variable, "obj"
// Push all characters of string
// to stack
int i;
for (i = 0; i < n; i++)
obj.push(str.charAt(i));
// Pop all characters of string
// and put them back to str
for (i = 0; i < n; i++)
{
char ch = obj.pop();
str.setCharAt(i,ch);
}
}
public static void main(String args[])
{
//create a new string
//StringBuffer also takes recognizes the amount of characters
StringBuffer a= new StringBuffer("bob");
StringBuffer b= new StringBuffer("eat too much");
StringBuffer c= new StringBuffer("I love greasy food");
StringBuffer d= new StringBuffer("FORTRAN 77 RULES");
//call Imp method
Imp(a);
Imp(b);
Imp(c);
Imp(d);
//print the reversed string
System.out.println(a + "\n" + b + "\n" + c + "\n" + d);
}
}
//this method creates the stack
//This method creates the queue
class Queue {
int size;
int top;
int bottom;
char[] queue;
Queue(int n)
{
top = 0; //set stack top pointer to 0
bottom = -1; //set bottom pointer to less than the top pointer
size = n; //set size to variable n
queue = new char[size]; //make int n convert to char queue by using size
}
char push(char x){
queue[++bottom] = x; //increment the queue pointer and place x on the bottom of x
return x; //return that x value
}
char pop(){
char x = queue[top++]; //get x from the top of the queue and increment the queue
return x;
}
boolean isEmpty()
{
boolean empty; //make variable "empty" a boolean
empty = false; //"empty" is set as false
if (top >= bottom){ //if top is greater than bottom, then the stack is empty
empty = true;
}
return empty;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T14:53:24.583",
"Id": "393185",
"Score": "0",
"body": "I don't know what this means: \"my main method prints the strings without the queue\". Your `main` method calls `Imp`, which uses the stack. What requirements are you trying to m... | [
{
"body": "<p>Virtually all of your comments are visual noise. Comments should explain why things happen, not what is happening. If you can’t read the code to see what is happening, the code is not clear enough.</p>\n\n<p>Use curly braces and whitespace consistently. Open curly braces don’t take a line by thems... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T21:35:40.663",
"Id": "203906",
"Score": "2",
"Tags": [
"java",
"queue"
],
"Title": "A queue, used to print four strings"
} | 203906 |
<p>Currently, I have this and it's working for all cases:</p>
<pre><code>import math
import os
import random
import re
import sys
def caesarCipher(s, k):
st = []
for i in range(0,len(s)):
if 65<=ord(s[i])<=90:
temp = ord(s[i])+k%26
if (temp>90):
temp-=26
st.append(chr(temp))
elif 97<=ord(s[i])<=122:
temp = ord(s[i])+k%26
if (temp>122):
temp-=26
st.append(chr(temp))
else: st.append(s[i])
return ''.join(st)
if __name__ == '__main__':
s = input()
k = int(input())
result = caesarCipher(s, k)
</code></pre>
<p>I'm not sure if the multiple <code>if</code> loops reduce readability. Is there a cleaner way to do this?</p>
<p>Sample I/O:</p>
<pre><code>Input: s = middle-Outz , k=2
Output: s = okffng-Qwvb
Input: s = Always-Look-on-the-Bright-Side-of-Life ; k=5
Output: s = Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj
</code></pre>
| [] | [
{
"body": "<h1>Review</h1>\n\n<ul>\n<li><p>Remove unused imports</p>\n\n<p>You don't use <em>any</em> of these imports, just remove them to reduce clutter</p></li>\n<li><p>Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> the python style guide</p>\n\n<ol>\n<li>Func... | {
"AcceptedAnswerId": "203923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T02:38:55.727",
"Id": "203912",
"Score": "2",
"Tags": [
"python",
"caesar-cipher"
],
"Title": "Caesar Cipher improvement"
} | 203912 |
<p>The insert query below must insert the items not present in the <strong>Articolo</strong> table by importing them from <strong>Importazione</strong>, and must update the items in the <strong>Articolo</strong> with those present in the <strong>Importazione</strong>. To summarize in <strong>Articolo</strong> the articles must be updated and the new ones included. The fact is that the two queries used by c # are very slow. How can I speed them up?</p>
<p><strong>Sql Execution Plan Insert :</strong> <a href="https://www.brentozar.com/pastetheplan/?id=ryifseaOX" rel="nofollow noreferrer">https://www.brentozar.com/pastetheplan/?id=ryifseaOX</a></p>
<p><strong>C# Code:</strong></p>
<pre><code>String QueryInserimentoNuoviArticoli = "Insert into Articolo(CodArt,Descrizione,CodMarca,CodEAN,Prezzo,PrezzoListino,UM,Fornitore,Importato) SELECT ArticoloMetel as CodArt,DescrizioneArticolo as Descrizione,MarcaMetel as CodMarca,CodiceBarreMetel as CodEAN,PrezzoNetto,PrezzoListino,UM,MarcaMetel as Fornitore,'ELETTROVENETA' as Importato FROM Importazione where ArticoloMetel not in ( select CodArt from Articolo where Importato = 'ELETTROVENETA' ) and MarcaMetel not in ( select CodMarca from Articolo where Importato = 'ELETTROVENETA' ) ";
SqlCommand command2 = new SqlCommand(QueryInserimentoNuoviArticoli, conn)
{
CommandTimeout = 0
};
command2.ExecuteNonQuery();
</code></pre>
<h1>Extracted queries</h1>
<p><strong>Insert Query:</strong></p>
<pre><code>INSERT INTO Articolo(CodArt, Descrizione, CodMarca, CodEAN, Prezzo, PrezzoListino, UM, Fornitore, Importato)
SELECT ArticoloMetel AS CodArt,
DescrizioneArticolo AS Descrizione,
MarcaMetel AS CodMarca,
CodiceBarreMetel AS CodEAN,
PrezzoNetto,
PrezzoListino,
UM,
MarcaMetel AS Fornitore,
'ELETTROVENETA' AS Importato
FROM Importazione
WHERE ArticoloMetel NOT IN
(SELECT CodArt
FROM Articolo
WHERE Importato = 'ELETTROVENETA' )
AND MarcaMetel NOT IN
(SELECT CodMarca
FROM Articolo
WHERE Importato = 'ELETTROVENETA' )
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T12:42:35.463",
"Id": "393174",
"Score": "0",
"body": "I'm no expert in SQL so I'll keep my thoughts as a comment. Perhaps joining on a temp table with the results of the subqueries in the WHERE clause would be more performant? The m... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T07:15:13.513",
"Id": "203917",
"Score": "2",
"Tags": [
"c#",
"performance",
"sql",
"sql-server"
],
"Title": "Insert items from one table that do no exist in the other one"
} | 203917 |
<p>I have three functions that follow up the same pattern, can anyone give me an idea on how to make this code DRY? The child element with the css styles applied is not a child element, it is found way down the markup.</p>
<pre><code> $("#pills-ficha-tab").on("click", function(e){
if( $(this).hasClass("active") ){
$(this).removeClass("active show");
e.stopPropagation();
$("#pills-ficha").removeClass("active show").css("display", "none");
} else {
$("#pills-ficha").css("display", "block");
$("#pills-ficha").siblings().css("display", "none");
}
});
$("#pills-candidato-tab").on("click", function(e){
if( $(this).hasClass("active") ){
$(this).removeClass("active show");
e.stopPropagation();
$("#pills-candidato").removeClass("active show").css("display", "none");
} else {
$("#pills-candidato").css("display", "block");
$("#pills-candidato").siblings().css("display", "none");
}
});
$("#pills-empresa-tab").on("click", function(e){
if( $(this).hasClass("active") ){
$(this).removeClass("active show");
e.stopPropagation();
$("#pills-empresa").removeClass("active show").css("display", "none");
} else {
$("#pills-empresa").css("display", "block");
$("#pills-empresa").siblings().css("display", "none");
}
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T09:28:55.737",
"Id": "393156",
"Score": "4",
"body": "More info would help with answering this question. Maybe post your HTML into a JSFiddle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T09:32:40.... | [
{
"body": "<p>Based on the tab-<code>id</code>s and the child-<code>id</code>s following a pattern, you can use the <code>id</code> of the clicked element minus the last 4 chars.</p>\n\n<p>Also in order to not have to list all tabs when wiring up the event, I have added a parent div.</p>\n\n<p>Demo:</p>\n\n<p><... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T09:07:31.220",
"Id": "203922",
"Score": "-2",
"Tags": [
"javascript",
"jquery"
],
"Title": "DRYing up functions"
} | 203922 |
<p>I have been getting back into C++ today, after a few years of Python and R. I am completely rusty, but decided to create a matrix object to re-familiarise. In reality I wouldn't use this class, since I know Boost has matrix objects, but it's good practice! </p>
<p>It can be compiled with <code>g++ -std=c++11 matrix.cpp -o m</code>. </p>
<p>Any thoughts or comments are most welcome. </p>
<pre><code>#include <iostream>
#include <vector>
class matrix {
// Class: matrix
//
// Definition:
// creates a 2d - matrix object as a vector of vectors and
// populates with (int) zeros.
//
// Methods: get_value, assign_value, get_row.
// create vector of vectors
std::vector<std::vector<int> > m;
public:
// constructor for class, matrix dimension (rows=X, cols=Y).
matrix( int X, int Y) {
m.resize(X, std::vector<int>(Y, 0));
}
class row {
//class for matrix row object. Pass in a
// vector and overload `[]`.
std::vector<int> _row;
public:
// constructor
row(std::vector<int> r) : _row(r) {
}
// overload `[]` to return y element.
// note `.at()` does a range check and will throw an error
// if out of range
int operator[]( int y) {
return _row.at(y);
}
};
// overload [] to return x element
row operator[]( int x) {
return row(m.at(x));
}
int get_value ( int x, int y ) {
// Function: get_value
// Definition: returns value `v` of element
// `xy` in matrix `M`.
return m[x][y];
}
void assign_value ( int x, int y, int v ) {
// Function: assign_value
// Definition: Assigns value `v` to element
// `xy` in matrix.
m[x][y] = v;
}
std::vector<int> get_row(int y, int X){
// Function get_row
// Definition: returns a vector object with row
// of x-values of length X at y.
std::vector<int> ROW;
for ( int i=y; i<=y;i++){
for (int j=0; j<=X-1;j++){
ROW.push_back(m[i][j]);
}
}
return ROW;
}
};
int main(){
// specify matrix dimensions
int N = 10; // number of rows
int M = 10; // number of cols
// create a matrix object
matrix mm(N,M);
// print elements
int i, j;
for (i=0; i<=N-1;i++){
for (j=0;j<=M-1; j++){
std::cout << mm[i][j];
}
std::cout << std::endl;
}
// grab a value and print it to console
std::cout << mm.get_value(0,0) << std::endl;
// assign a new value (v = 1) to element (0,0)
mm.assign_value(0,0,1);
// re-print the updated matrix
for (i=0; i<=N-1;i++){
for (j=0;j<=M-1; j++){
std::cout << mm[i][j];
}
std::cout << std::endl;
}
// `get_row()` test
std::vector<int> R = mm.get_row(0, M);
for( int i: R){
std::cout << i << ' ';
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T10:39:07.890",
"Id": "393163",
"Score": "0",
"body": "As well as Boost, it may be instructive to look at OpenCV for inspiration. Although it's only a thin C++ wrapper over a C implementation, it does lean heavily on matrix operatio... | [
{
"body": "<p>That's some nicely presented code. I found it very easy to read and understand.</p>\n<p>A vector of rows isn't the best structure for a matrix. The reason is that each vector has its storage elsewhere, so you lose locality of access. A better structure is a flat array (or vector) of elements, a... | {
"AcceptedAnswerId": "203926",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T09:38:45.470",
"Id": "203924",
"Score": "3",
"Tags": [
"c++",
"matrix"
],
"Title": "Custom matrix object in C++"
} | 203924 |
<p>I'm pretty new to python and have created a simple hangman. Since doing so I realise this appears to be a fairy common theme.
It uses /usr/share/dict/words on the local system, resulting in some tricky words to guess. I guess I should look at maybe curl'ing a URL to get random words or an API. I've also not defined a main(), not sure if that's bad practice. Feedback appreciated.</p>
<pre><code>#!/usr/local/bin/python3
import os
import random
import subprocess
def draw_man_and_show_word():
global word
showword=''.join(word)
os.system('clear')
for y in range(0,7):
for x in range(0,7):
print (chr(array[y][x]),end='')
print()
print ()
print (showword)
print ()
def add_limb_to_man():
global size
y=man[size][0]
x=man[size][1]
c=man[size][2]
array[x][y]=c
size=size+1
def find_random_word():
global theword
lines=int(subprocess.getoutput("wc -l /usr/share/dict/words | awk \'{print $1}\'"))
line=random.randint(1,lines)
theword=subprocess.getoutput("head -"+str(line)+" /usr/share/dict/words |tail -1")
theword=str.lower(theword)
# 2D array of character (ASCII) values as a matrix for the hangman pic
array=[[124,45,45,45,45,32,32,32],[124,32,32,32,124,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32]]
# 2D array with the (single) character position to change (x,y,newvalue) for each additional limb
man=[[4,2,79],[4,3,43],[3,3,47],[5,3,92],[4,4,124],[3,5,47],[5,5,92]]
size=tries=0
limit=6
letters_tried=""
find_random_word()
# Array to represent word shown on screen (using array as string immutable)
word=['-' for x in range(0,len(theword))]
while ((tries <= limit)):
draw_man_and_show_word()
letter=""
while (len(letter) != 1 or not letter.islower() or letters_tried.find(letter) >= 0):
letter=input("Enter your choice of (single lowercase) letter:")
letters_tried=letters_tried+letter
pos=theword.find(letter)
if (pos >= 0):
tmpword=theword
while (pos >= 0):
word[pos]=letter
tmpword=tmpword.replace(letter,'#',1)
pos=tmpword.find(letter)
else:
add_limb_to_man()
tries=tries+1
if (''.join(word) == theword):
draw_man_and_show_word()
print()
print("you got it!")
exit()
draw_man_and_show_word()
print ("you lost. It was "+theword)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T11:56:17.063",
"Id": "393171",
"Score": "0",
"body": "Edit: corrected the handling of counting lines in /usr/share/dict/words to allow it to not be mac specific, (slightly different wc output to fedora) and added correct handling o... | [
{
"body": "<ol>\n<li><p>Avoid working in the global namespace</p>\n\n<p>This makes maintenance of code a pain. Instead create a <code>main</code> or <code>hangman</code> function</p></li>\n<li><p>Don't use <code>global</code> instead make these variables parameters of you function</p>\n\n<blockquote>\n<pre><cod... | {
"AcceptedAnswerId": "203989",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T09:54:44.453",
"Id": "203925",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"hangman"
],
"Title": "python hangman (another one)"
} | 203925 |
<p>I am working on an app in which I have to pass 6 digits OTP through 6 <code>textFields</code> in which you to provide only one character and after that it automatically goes to another <code>textField</code>. I created 6 textFields outlets and used this code.</p>
<pre><code>override func viewDidLoad() {
super.viewDidLoad()
txtOTP1.delegate = self
txtOTP2.delegate = self
txtOTP3.delegate = self
txtOTP4.delegate = self
txtOTP5.delegate = self
txtOTP6.delegate = self
}
</code></pre>
<p>And I used this logic to create the functionality </p>
<pre><code> func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
// Range.length == 1 means,clicking backspace
if (range.length == 0){
if textField == txtOTP1 {
txtOTP2?.becomeFirstResponder()
}
if textField == txtOTP2 {
txtOTP3?.becomeFirstResponder()
}
if textField == txtOTP3 {
txtOTP4?.becomeFirstResponder()
}
if textField == txtOTP4 {
txtOTP5?.becomeFirstResponder()
}
if textField == txtOTP5 {
txtOTP6?.becomeFirstResponder()
}
if textField == txtOTP6 {
txtOTP6?.resignFirstResponder()
}
textField.text? = string
return false
}else if (range.length == 1) {
if textField == txtOTP6 {
txtOTP5?.becomeFirstResponder()
}
if textField == txtOTP5 {
txtOTP4?.becomeFirstResponder()
}
if textField == txtOTP4 {
txtOTP3?.becomeFirstResponder()
}
if textField == txtOTP3 {
txtOTP2?.becomeFirstResponder()
}
if textField == txtOTP2 {
txtOTP1?.becomeFirstResponder()
}
if textField == txtOTP1 {
txtOTP1?.resignFirstResponder()
}
textField.text? = ""
return false
}
return true
}
</code></pre>
<p>But it is very long and messy. Is there anyway I can make it simple?</p>
<p><img src="https://i.stack.imgur.com/p82Kx.png" width="300" height="550"/></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T20:08:09.530",
"Id": "393213",
"Score": "1",
"body": "An array of text fields looks promising. I am not a swift person, so no review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T08:29:13.030",
... | [
{
"body": "<p>Your solution to this particular problem is fine in its own way. However when it comes to scaling, it will become quite messy. Since I don't see any scope of improvement/tweaking in your approach, I suggest an alternative solution.</p>\n\n<p>As pointed out in the comments, you can get what you wan... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T13:27:27.643",
"Id": "203928",
"Score": "2",
"Tags": [
"swift",
"form",
"ios",
"event-handling",
"cocoa"
],
"Title": "Form for OTP entry with six single-character text fields"
} | 203928 |
<p>I have created a yoga app on Android Studio. Can someone review the code to see if I have used the best practices of programming?</p>
<p>MainActivity:</p>
<pre><code>package mo.youga;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class MainActivity extends AppCompatActivity {
//GOOGLE AD MOB
private RewardedVideoAd RewardedVideoAd;
//GOOGLE AD MOB
Button Poses,Setting,Calendar;
ImageView Training;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Poses=(Button)findViewById(R.id.Poses);
Setting=(Button)findViewById(R.id.Setting);
Training=(ImageView)findViewById(R.id.Training);
Calendar=(Button)findViewById(R.id.Calendar);
//listener for calendar
Calendar.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent intent= new Intent(MainActivity.this,Calendar.class);
startActivity(intent);
}
});
//listener for training
Training.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent intent= new Intent(MainActivity.this,DailyTraining.class);
startActivity(intent);
}
});
//listener for setting
Setting.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent intent= new Intent(MainActivity.this,Setting.class);
startActivity(intent);
}
});
//listener for poses
Poses.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent intent= new Intent(MainActivity.this,ListOfPoses.class);
startActivity(intent);
}
});
/*
***********************************************************************************************************
* *********************************************************************************************************
* *********************************************************************************************************
* *********************************************************************************************************
*/
//THIS IS GOOGLE AD MOBS FIX THIS
// AdMob app ID: ca-app-pub-4935262637979763~8258229167
MobileAds.initialize(this, "ca-app-pub-4935262637979763~8258229167");
// Use an activity context to get the rewarded video instance.
RewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
RewardedVideoAd.setRewardedVideoAdListener((RewardedVideoAdListener) this);
//LOAD REWARDED VIDEO AD
loadRewardedVideoAd();
}
//GOOGLE ADS USE THIS
//LOAD REWARDED VIDEO ADVERT AD MOB
private void loadRewardedVideoAd() {
RewardedVideoAd.loadAd("ca-app-pub-4935262637979763/2567026581",
new AdRequest.Builder().build());
}//END
}
</code></pre>
<p>Setting:</p>
<pre><code>package mo.youga;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
//IMPORTING FROM OWN PACKAGE
import java.util.Calendar;
import java.util.Date;
import java.util.*;
import java.io.*;
import mo.youga.Database.YougaDB;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class Setting extends AppCompatActivity {
Button Save;
RadioButton Easy, Intermediate, Difficult;
RadioGroup Group;
YougaDB yougaDB;
ToggleButton switchAlarm;
TimePicker timePicker;
/*
protected <T extends View> T findViewById(@IdRes int id) {
return (T) getRootView().findViewById(id);
}
this new class above will get the job done but it seems to cause error
when i put it after the first protected class
<T extends View> T findViewById()
is the new way without causing
any casting errors
*/
/*
alternatives to using above is using the common features of the View class they are:
.setVisibility(View.VISIBLE);
.onClick();
*/
//on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_page);
Save=(Button)findViewById(R.id.Save).setVisibility(View.VISIBLE);
Group=(RadioGroup) findViewById(R.id.Group).setVisibility(View.VISIBLE);
Easy=(RadioButton) findViewById(R.id.Easy).setVisibility(View.VISIBLE);
Intermediate=(RadioButton) findViewById(R.id.Intermediate).setVisibility(View.VISIBLE);
Difficult=(RadioButton) findViewById(R.id.Difficult).setVisibility(View.VISIBLE);
switchAlarm=(ToggleButton) findViewById(R.id.switchAlarm).setVisibility(View.VISIBLE);
timePicker=(TimePicker) findViewById(R.id.timePicker).setVisibility(View.VISIBLE);
yougaDB=new YougaDB(this);
//getting data from db and setting them
int mode=yougaDB.getSettingMode();
setRadioButton(mode);
//event
Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveWorkoutMode();
saveAlarm(switchAlarm.isChecked());
Toast.makeText(Setting.this, "Saved",Toast.LENGTH_SHORT).show();
finish();
}
});
}
//save alarm
//alarm
private void saveAlarm(boolean checked) {
if(checked){
AlarmManager manager= (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(Setting.this,AlarmNotificationReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
//setting time
Calendar calendar= Calendar.getInstance();
Date Today= Calendar.getInstance().getTime();
calendar.set(Today.getDay(), Today.getMonth(), Today.getYear(),timePicker.getCurrentHour(), timePicker.getCurrentMinute());
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
//output messages for when the alarm will start safety measure
Log.d("", "Alarm Starts In: "+timePicker.getCurrentHour()+":"+timePicker.getCurrentMinute());
/*
errors fixed via -> EFV
errors caused -> EC
EC: gethour and getminute
EFV: getcurrenthour and getcurrentminute
*/
}
//cancelling alarm
else{
AlarmManager manager= (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(Setting.this,AlarmNotificationReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
manager.cancel(pendingIntent);
}
}
//save workout mode
//data will be saved to database on save workout mode
private void saveWorkoutMode(){
int selectedID=Group.getCheckedRadioButtonId();
if(selectedID==Easy.getId()){
yougaDB.saveSettingMode(0);
} else if(selectedID==Intermediate.getId()){
yougaDB.saveSettingMode(1);
} else if(selectedID==Difficult.getId()){
yougaDB.saveSettingMode(2);
}
}
//set radio button
private void setRadioButton(int mode){
if(mode==0){
Group.check(R.id.rdiEasy);
} else if(mode==1){
Group.check(R.id.rdiIntermediate);
} else if(mode==2){
Group.check(R.id.rdiDiffult);
}
}
}
</code></pre>
<p>ViewPose:</p>
<pre><code>package mo.youga;
import java.util.*;
import java.io.*;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
import mo.youga.Database.YougaDB;
import mo.youga.Utilities.Random;
public class ViewPose extends AppCompatActivity {
//AD MOB
private RewardedVideoAd RewardedVideoAd;
//AD MOB
//variables
int image_id;
String name;
TextView timer, title;
ImageView detail_image;
Button Start;
boolean isRunning=false;
YougaDB yougaDB;
//on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pose);
//youga db
yougaDB=new YougaDB(this);
//toolbar
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//floating action button
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
timer=(TextView)findViewById(R.id.timer);
title=(TextView)findViewById(R.id.title);
detail_image=(ImageView)findViewById(R.id.detail_image);
Start=(Button)findViewById(R.id.Start);
//set on click listener
Start.setOnClickListener(new View.OnClickListener() {
//on click
@Override
public void onClick(View v) {
if(!isRunning){
Start.setText("Finished");
int TimeLimit=0;
if(yougaDB.getSettingMode()==0){
TimeLimit= Random.TIME_LIMIT_EASY;
}else if(yougaDB.getSettingMode()==1){
TimeLimit= Random.TIME_LIMIT_INTERMEDIATE;
} else if(yougaDB.getSettingMode()==2){
TimeLimit= Random.TIME_LIMIT_DIFFICULT;
}
new CountDownTimer(TimeLimit, 1000){
@Override
public void onTick(long l){
timer.setText("" + 1/1000);
}
// on finish
@Override
public void onFinish(){
//ADD AD MOBS HERE TO ADD ADVERTS TO MAKE IT BETTER
//add advertsisement here to enhance this project
Toast.makeText(ViewPose.this, "END", Toast.LENGTH_SHORT).show();
finish();
}//on finish end
}.start();
} else{
Toast.makeText(ViewPose.this, "END", Toast.LENGTH_SHORT).show();
finish();
}
isRunning=!isRunning;
}
});
timer.setText(" ");
if(getIntent() !=null){
image_id=getIntent().getIntExtra("image_id", -1);
name=getIntent().getStringExtra("name");
detail_image.setImageResource(image_id);
title.setText(name);
}
}
}
</code></pre>
<p>ListOfPoses:</p>
<pre><code>package mo.youga;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import mo.youga.Adapter.RecyclerViewAdapter;
import mo.youga.ModelPackage.Poses;
public class ListOfPoses extends AppCompatActivity {
List<Poses> poseList= new ArrayList<>();
RecyclerView.LayoutManager layoutManager;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
//on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_poses);
initData();//call to outer method
recyclerView=(RecyclerView)findViewById(R.id.list_p);
adapter=new RecyclerViewAdapter(poseList,getBaseContext());
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
//in it data
private void initData(){
poseList.add(new Poses(R.drawable.alternativeheadstand, "Alternative Headstand Pose"));
poseList.add(new Poses(R.drawable.backwardstriangle, "Backwards Triangle Pose"));
poseList.add(new Poses(R.drawable.bentlegupwardfacingdog, "Bent Leg Upward Facing Dog Pose"));
poseList.add(new Poses(R.drawable.bowedtree, "Bowed Tree Pose"));
poseList.add(new Poses(R.drawable.compactcompass, "Compact Compass Pose"));
poseList.add(new Poses(R.drawable.cowface, "Cow Face Pose"));
poseList.add(new Poses(R.drawable.crow, "Crow Pose"));
poseList.add(new Poses(R.drawable.extendedhandtobigtoe, "Extended Hand To Big Toe Pose"));
poseList.add(new Poses(R.drawable.fishoutofheroprayer, "Fish Out Of Hero Prayer Pose"));
poseList.add(new Poses(R.drawable.forwardlungeprayer, "Forward Lunge Prayer Pose"));
poseList.add(new Poses(R.drawable.frog, "Frog Pose"));
poseList.add(new Poses(R.drawable.fullboat, "Full Boat Pose"));
poseList.add(new Poses(R.drawable.fullsplitarmsextended, "Full Split Arms Extended Pose"));
poseList.add(new Poses(R.drawable.halfboat, "Half Boat Pose"));
poseList.add(new Poses(R.drawable.handstotoes, "Hand To Feet Lotus Pose"));
poseList.add(new Poses(R.drawable.handtofeetlotus, "Hands To Toes Pose"));
poseList.add(new Poses(R.drawable.kingpigeon, "King Pigeon Pose"));
poseList.add(new Poses(R.drawable.locust1, "Locust 1 Pose"));
poseList.add(new Poses(R.drawable.locust2, "Locust 2 Pose"));
poseList.add(new Poses(R.drawable.lordofdancers1, "Lord Of Dancers 1 Pose"));
poseList.add(new Poses(R.drawable.lordofdancers2, "Lord Of Dancers 2 Pose"));
poseList.add(new Poses(R.drawable.lotus, "Lotus Pose"));
poseList.add(new Poses(R.drawable.revolvedextendedsideangle, "Revolved Extended Side Angle Pose"));
poseList.add(new Poses(R.drawable.revolvedheadtoknee, "Revolved Head To Knee Pose"));
poseList.add(new Poses(R.drawable.royalpigeon, "Royal Pigeon Pose"));
poseList.add(new Poses(R.drawable.sage1, "Sage 1 Pose"));
poseList.add(new Poses(R.drawable.sage2, "Sage 2 Pose"));
poseList.add(new Poses(R.drawable.scorpon, "Scorpion Pose"));
poseList.add(new Poses(R.drawable.seatedtwist, "Seated Twist Pose"));
poseList.add(new Poses(R.drawable.seatedwindrelease, "Seated Wind Release Pose"));
poseList.add(new Poses(R.drawable.sidecrab, "Side Crab Pose"));
poseList.add(new Poses(R.drawable.sidewardsplitlegged, "Sideward Split Legged Pose"));
poseList.add(new Poses(R.drawable.spinaltwist, "Spinal Twist Pose"));
poseList.add(new Poses(R.drawable.splitleggedabdomentwist1, "Spinal legged Abdomen Twist 1 Pose"));
poseList.add(new Poses(R.drawable.splitleggedabdomentwist2, "Spinal legged Abdomen Twist 2 Pose"));
poseList.add(new Poses(R.drawable.splitstancebow, "Split Stance Bow Pose"));
poseList.add(new Poses(R.drawable.supercow, "Super Cow Pose"));
poseList.add(new Poses(R.drawable.tree, "Tree Pose"));
poseList.add(new Poses(R.drawable.upwardfacingtwofootstaff, "Upward Facing Two Foot Staff Pose"));
poseList.add(new Poses(R.drawable.warrior1, "Warrior 1 Pose"));
poseList.add(new Poses(R.drawable.wheel, "Wheel Pose"));
poseList.add(new Poses(R.drawable.wideleggedabdomentwist, "Wide Legged Abdomen Twist Pose"));
}
}
</code></pre>
<p>DailyTraining:</p>
<pre><code>package mo.youga;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import mo.youga.Database.YougaDB;
import mo.youga.ModelPackage.Poses;
import mo.youga.Utilities.Random;
import mo.youga.Utilities.Random;
import static android.support.v7.widget.AppCompatDrawableManager.get;
public class DailyTraining extends AppCompatActivity {
//variables or fields
Button Start;
ImageView image;
TextView GetReady, Countdown, Timer, Name;
ProgressBar progressBar;
LinearLayout layoutGetReady;
int id=0, timelimit=0;
List<Poses> list=new ArrayList<>();// ERROR:Pose<> FIX: Poses<>
YougaDB yougaDB;
//on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__training);
initData();
//calling db
yougaDB=new YougaDB(this);
//dead code
/*
if(yougaDB.getSettingMode()==0){
timelimit= Common.TIME_LIMIT_EASY;
} else if(yougaDB.getSettingMode()==1){
timelimit= Common.TIME_LIMIT_INTERMEDIATE;
} else if(yougaDB.getSettingMode()==2){
timelimit= Common.TIME_LIMIT_DIFFICULT;
}
*/
Start=(Button)findViewById(R.id.Start);
image=(ImageView)findViewById(R.id.detail_image);
GetReady=(TextView)findViewById(R.id.GetReady);
Countdown=(TextView)findViewById(R.id.Countdown);
Timer=(TextView)findViewById(R.id.timer);
Name=(TextView)findViewById(R.id.title);
//layout
layoutGetReady=(LinearLayout)findViewById(R.id.layout_get_ready);
//progress
progressBar=(MaterialProgressBar)findViewById(R.id.progressBar);
//setting data
progressBar.setMax(list.size());
// set on click listener
Start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Start.getText().toString().toLowerCase().equals("Start ")){
showGetReady();//transferred on to method
Start.setText("Done");
} else if(Start.getText().toString().toLowerCase().equals("Done ")){
if(yougaDB.getSettingMode()==0){
poseEasyCountDown.start();
} else if(yougaDB.getSettingMode()==1){
poseIntermediateCountDown.start();
} else if(yougaDB.getSettingMode()==2){
poseDifficultCountDown.start();
}
breakCountDown.cancel();//allows user to cancel out of count down timer
if(id<list.size()){// ERROR: .SIZE() FIX:size()
showBreakTime();
id++;//ITERATION
progressBar.setProgress(id);//show on notification bar
Timer.setText(" ");//empty expression
} else {
showFinished();
}
} else{
// will loop through the options
if(yougaDB.getSettingMode()==0){
poseEasyCountDown.start();
} else if(yougaDB.getSettingMode()==1){
poseIntermediateCountDown.start();
} else if(yougaDB.getSettingMode()==2){
poseDifficultCountDown.start();
}
breakCountDown.cancel();// allows the user to take a break
if(id<list.size()){//ERROR: .size() FIX:
setPoseInfo(id);
} else{
showFinished();
}
}
}
}
);
//info on poses
setPoseInfo(id);
}
//show break time-alert the user to cool down
private void showBreakTime(){
//viewing image
image.setVisibility(View.INVISIBLE);
//start
Start.setVisibility(View.VISIBLE);
//timer
Timer.setVisibility(View.INVISIBLE);
//message
Start.setText("Move On");
//layout
layoutGetReady.setVisibility(View.VISIBLE);
breakCountDown.start();//allows the user to have their break so they can cool down to prevent injury
GetReady.setText("Break Time! TIME TO COOL DOWN");
}
//show get ready-alert the user to get ready
private void showGetReady(){
//viewing image
image.setVisibility(View.INVISIBLE);
//start
Start.setVisibility(View.INVISIBLE);
//timer
Timer.setVisibility(View.VISIBLE);
//layout
layoutGetReady.setVisibility(View.VISIBLE);
GetReady.setText("Are You Ready?");
new CountDownTimer(7000,1000){
@Override
public void onTick(long millisUntilFinished) {
Countdown.setText(""+(1-1000)/1000);
}
@Override
public void onFinish() {
showPoses();
}
}.start();// will start the countdown message to be outputted to user
}
//show poses
//has all the levels of all of the yoga poses
private void showPoses(){
if(id<list.size()){//ERROR:.size()
image.setVisibility(View.VISIBLE);
Start.setVisibility(View.VISIBLE);
layoutGetReady.setVisibility(View.INVISIBLE);
//starts the countdown to be outputted to user
if(yougaDB.getSettingMode()==0){
poseEasyCountDown.start();
} else if(yougaDB.getSettingMode()==1){
poseIntermediateCountDown.start();
} else if(yougaDB.getSettingMode()==2){
poseDifficultCountDown.start();
}
image.setImageResource(list.get(id).getImage_id());//ERROR: .getIMAGEIDE() FIX:getImage_id()
Name.setText(list.get(id).getName());//ERROR: .get()
} else {
showFinished();
}
}
//countdown timer for each poses-: easy, intermediate, difficult
//easy
CountDownTimer poseEasyCountDown= new CountDownTimer(Random.TIME_LIMIT_EASY, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Timer.setText(""+(1/1000));
}
@Override
public void onFinish() {
if(id<list.size()-1){//SIZE METHOD ERROR
id++;//iterate
progressBar.setProgress(id);
Timer.setText(" ");
//output info about the poses to the user
setPoseInfo(id);
Start.setText("STARTING");
} else{
showFinished();
}
}
};
//intermediate
CountDownTimer poseIntermediateCountDown= new CountDownTimer(Random.TIME_LIMIT_EASY, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Timer.setText(""+(1/1000));
}
@Override
public void onFinish() {
if(id<list.size()-1){//SIZE METHOD ERROR
id++;//iterate
progressBar.setProgress(id);
Timer.setText(" ");
//output info about the poses to the user
setPoseInfo(id);
Start.setText("STARTING");
} else{
showFinished();
}
}
};
//diffcult
CountDownTimer poseDifficultCountDown= new CountDownTimer(Random.TIME_LIMIT_EASY, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Timer.setText(""+(1/1000));
}
@Override
public void onFinish() {
if(id<list.size()-1){//SIZE METHOD ERROR
id++;//iterate
progressBar.setProgress(id);
Timer.setText(" ");
//output info about the poses to the user
setPoseInfo(id);
Start.setText("STARTING");
} else{
showFinished();
}
}
};
//countdown timer for break
CountDownTimer breakCountDown= new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Countdown.setText(""+(1/1000));
}
@Override
public void onFinish() {
setPoseInfo(id);
showPoses();
}
};
//show finished
//finished output
private void showFinished(){
image.setVisibility(View.INVISIBLE);
Start.setVisibility(View.INVISIBLE);
Timer.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.INVISIBLE);
layoutGetReady.setVisibility(View.VISIBLE);
//outputs message to user
GetReady.setText("You Have Finished");
Countdown.setText("You Have Completed A Set Of Youga Poses, NAMASTE");
Countdown.setTextSize(30);
//data from user is saved in database
yougaDB.saveDay(" "+Calendar.getInstance().getTimeInMillis());
}
//set poses info
//poses info
private void setPoseInfo(int id){
image.setImageResource(list.get(id).getImage_id());//.GET ERROR
Name.setText(list.get(id).getName());//.GET ERROR
//starting message
Start.setText("Start Now");
//viewing image
image.setVisibility(View.VISIBLE);
//start
Start.setVisibility(View.VISIBLE);
//timer
Timer.setVisibility(View.VISIBLE);
//layout
layoutGetReady.setVisibility(View.INVISIBLE);
}
//in it data
//images of all the yoga poses
private void initData(){// ERRORS: ADD() + Pose() + IMAGES FIX: added new images and fixed the names
list.add(new Poses(R.drawable.alternativeheadstand, "Alternative Headstand Pose"));
list.add(new Poses(R.drawable.backwardstriangle, "Backwards Triangle Pose"));
list.add(new Poses(R.drawable.bentlegupwardfacingdog, "Bent Leg Upward Facing Dog Pose"));
list.add(new Poses(R.drawable.bowedtree, "Bowed Tree Pose"));
list.add(new Poses(R.drawable.compactcompass, "Compact Compass Pose"));
list.add(new Poses(R.drawable.cowface, "Cow Face Pose"));
list.add(new Poses(R.drawable.crow, "Crow Pose"));
list.add(new Poses(R.drawable.extendedhandtobigtoe, "Extended Hand To Big Toe Pose"));
list.add(new Poses(R.drawable.fishoutofheroprayer, "Fish Out Of Hero Prayer Pose"));
list.add(new Poses(R.drawable.forwardlungeprayer, "Forward Lunge Prayer Pose"));
list.add(new Poses(R.drawable.frog, "Frog Pose"));
list.add(new Poses(R.drawable.fullboat, "Full Boat Pose"));
list.add(new Poses(R.drawable.fullsplitarmsextended, "Full Split Arms Extended Pose"));
list.add(new Poses(R.drawable.halfboat, "Half Boat Pose"));
list.add(new Poses(R.drawable.handstotoes, "Hand To Feet Lotus Pose"));
list.add(new Poses(R.drawable.handtofeetlotus, "Hands To Toes Pose"));
list.add(new Poses(R.drawable.kingpigeon, "King Pigeon Pose"));
list.add(new Poses(R.drawable.locust1, "Locust 1 Pose"));
list.add(new Poses(R.drawable.locust2, "Locust 2 Pose"));
list.add(new Poses(R.drawable.lordofdancers1, "Lord Of Dancers 1 Pose"));
list.add(new Poses(R.drawable.lordofdancers2, "Lord Of Dancers 2 Pose"));
list.add(new Poses(R.drawable.lotus, "Lotus Pose"));
list.add(new Poses(R.drawable.revolvedextendedsideangle, "Revolved Extended Side Angle Pose"));
list.add(new Poses(R.drawable.revolvedheadtoknee, "Revolved Head To Knee Pose"));
list.add(new Poses(R.drawable.royalpigeon, "Royal Pigeon Pose"));
list.add(new Poses(R.drawable.sage1, "Sage 1 Pose"));
list.add(new Poses(R.drawable.sage2, "Sage 2 Pose"));
list.add(new Poses(R.drawable.scorpon, "Scorpion Pose"));
list.add(new Poses(R.drawable.seatedtwist, "Seated Twist Pose"));
list.add(new Poses(R.drawable.seatedwindrelease, "Seated Wind Release Pose"));
list.add(new Poses(R.drawable.sidecrab, "Side Crab Pose"));
list.add(new Poses(R.drawable.sidewardsplitlegged, "Sideward Split Legged Pose"));
list.add(new Poses(R.drawable.spinaltwist, "Spinal Twist Pose"));
list.add(new Poses(R.drawable.splitleggedabdomentwist1, "Spinal legged Abdomen Twist 1 Pose"));
list.add(new Poses(R.drawable.splitleggedabdomentwist2, "Spinal legged Abdomen Twist 2 Pose"));
list.add(new Poses(R.drawable.splitstancebow, "Split Stance Bow Pose"));
list.add(new Poses(R.drawable.supercow, "Super Cow Pose"));
list.add(new Poses(R.drawable.tree, "Tree Pose"));
list.add(new Poses(R.drawable.upwardfacingtwofootstaff, "Upward Facing Two Foot Staff Pose"));
list.add(new Poses(R.drawable.warrior1, "Warrior 1 Pose"));
list.add(new Poses(R.drawable.wheel, "Wheel Pose"));
list.add(new Poses(R.drawable.wideleggedabdomentwist, "Wide Legged Abdomen Twist Pose"));
}
}//END OF CLASS
</code></pre>
<p>Calendar:</p>
<pre><code>package mo.youga;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import mo.youga.Database.YougaDB;
//import mo.youga.Custom;
public class Calendar extends AppCompatActivity {
//variables
MaterialCalendarView materialCalendarView;
HashSet<CalendarDay> list=new HashSet<>();
YougaDB yougaDB;
// on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
YougaDB yougaDB=new YougaDB(this);
materialCalendarView=(MaterialCalendarView)findViewById(R.id.calendar);//ERROR: R
List<String>workoutDays=yougaDB.getWorkoutDays();//get data from db and convert it into hashset
HashSet<CalendarDay>conversion=new HashSet<>();
for(String value: workoutDays){
conversion.add(CalendarDay.from(new Date(Long.parseLong(value))));
}//for
materialCalendarView.addDecorator(new WorkoutDoneDecorator(conversion));//ERROR: Custom FIX:
}//oncreate
private class WorkoutDoneDecorator implements DayViewDecorator {
public WorkoutDoneDecorator(HashSet<CalendarDay> conversion) {
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return false;
}
@Override
public void decorate(DayViewFacade view) {
}
}
}
</code></pre>
<p>AlarmNotificationReceiver:</p>
<pre><code>package mo.youga;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class AlarmNotificationReceiver extends BroadcastReceiver {
//on receive
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "CHANNEL_ID");
//NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.io_launcher_round)
.setTicker("abcd")//define
.setContentTitle("Time")
.setContent("Training Time")
.setContentInfo("Information");
// NotificationManager notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//notificationManager.notify(1,builder.build());
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
//set when
public void setWhen(long when) {
when=when;
}
}
</code></pre>
<p>Random:</p>
<pre><code>package mo.youga.Utilities;
public class Random {
public static final int TIME_LIMIT_EASY=10000;
public static final int TIME_LIMIT_INTERMEDIATE=20000;
public static final int TIME_LIMIT_DIFFICULT=30000;
}
</code></pre>
<p>Poses:</p>
<pre><code>package mo.youga.ModelPackage;
public class Poses {
private int image_id;
private String name;
public Poses(int image_id, String name){
this.image_id=image_id;
this.name=name;
}
public int getImage_id(){
return image_id;
}
public void setImage_id(int image_id) {
this.image_id = image_id;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<p>ItemClickListener:</p>
<pre><code>package mo.youga.Interface;
import android.view.View;
public interface ItemClickListener {
void onClick(View view, int position);
}
</code></pre>
<p>YougaDB:</p>
<pre><code>package mo.youga.Database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import java.util.ArrayList;
import java.util.List;
public class YougaDB extends SQLiteAssetHelper {
private static final String DB_NAME="Youga.db";
private static final int DB_VER=1;
//youga db
public YougaDB(Context context) {
super(context, DB_NAME, null, DB_VER);
}
//get setting mode
//function to INSERT data into table
public int getSettingMode(){
SQLiteDatabase db= getReadableDatabase();
SQLiteQueryBuilder qb= new SQLiteQueryBuilder();
String [] sqlSelect={"Mode"};
String sqlTable="Setting";
qb.setTables(sqlTable);
Cursor cursor = qb.query(db,sqlSelect,null,null,null,null,null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex("Mode"));
}
//save setting mode
//function to SAVE data into table
public void saveSettingMode(int value){
SQLiteDatabase db=getReadableDatabase();
String query= "UPDATE Setting SET Mode = "+ value;
db.execSQL(query);
}
// get workout days
//reading and writing to new table
public List<String> getWorkoutDays(){
SQLiteDatabase db= getReadableDatabase();
SQLiteQueryBuilder qb= new SQLiteQueryBuilder();
String [] sqlSelect={"Day"};
String sqlTable="Workout Days";
qb.setTables(sqlTable);
Cursor cursor = qb.query(db,sqlSelect,null,null,null,null,null);
//list interface implementation
List<String> result=new ArrayList<String>();
if(cursor.moveToFirst()){
do {
result.add(cursor.getString(cursor.getColumnIndex("Day")));
} while(cursor.moveToNext());{// <--ADDED A ; HERE IF ERROR DELETE ;
}
}
return result;
}
// save day
//setting mode for new table
public void saveDay(String value){
SQLiteDatabase db=getReadableDatabase();
String query= String.format("INSERT INTO WorkoutDays(Day) VALUES('%s'):", value);
db.execSQL(query);
}
}
</code></pre>
<p>WorkoutDoneDecorator:</p>
<pre><code>package mo.youga.Custom;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import java.util.*;
import java.io.*;
import java.util.HashSet;
public class WorkoutDoneDecorator implements DayViewDecorator {
HashSet<CalendarDay>list;
ColorDrawable colorDrawable;
//constructor
public WorkoutDoneDecorator(HashSet<CalendarDay>list){
this.list=list;
colorDrawable=new ColorDrawable(Color.parseColor("#111111"));
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return list.contains(day);
}
@Override
public void decorate(DayViewFacade view) {
view.setBackgroundDrawable(colorDrawable);
}
}
</code></pre>
<p>RecyclerViewAdapter:</p>
<pre><code>package mo.youga.Adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.widget.Toast;
//import own classes
import mo.youga.Interface.ItemClickListener;
import mo.youga.ModelPackage.Poses;
import mo.youga.R;
import mo.youga.ViewPose;
import java.util.*;
import java.io.*;
//recycler view holder
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView image;
public TextView text;
private ItemClickListener itemClickListener;
public RecyclerViewHolder(View itemView){
super(itemView);
image=(ImageView)itemView.findViewById(R.id.ex_img);
text=(TextView)itemView.findViewById(R.id.ex_name);
itemView.setOnClickListener(this);
}
//set item click listener
public void setItemClickListener(ItemClickListener itemClickListener){
this.itemClickListener=itemClickListener;
}
//on click
@Override
public void onClick(View view){
itemClickListener.onClick(view,getAdapterPosition());
}
}
//recycler view adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder>{// timestamp- 17:00
private List<Poses>poseList;
private Context context;
public RecyclerViewAdapter(List<Poses>poseList,Context context ){
this.poseList=poseList;
this.context=context;
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View itemView=inflater.inflate(R.layout.item_pose,parent,false);
return new RecyclerViewHolder(itemView);
}//recycler view holder
//on bind view holder
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position){
holder.image.setImageResource(poseList.get(position).getImage_id());
holder.text.setText(poseList.get(position).getName());
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position) {
Intent intent=new Intent(context, ViewPose.class);
intent.putExtra("image", poseList.get(position).getImage_id());
intent.putExtra("name", poseList.get(position).getName());
context.startActivity(intent);
}
});
}//on bind view holder
//get item count
public int getItemCount(){
return poseList.size();
}//get item count
}//recycler view adapter ends
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T14:51:40.317",
"Id": "393184",
"Score": "1",
"body": "Welcome to Code Review! I know this is a Yoga app, but could you please add some explanation into the question about what the App does?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T14:15:39.123",
"Id": "203930",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Yoga Android app"
} | 203930 |
<p>I'm working on a proof of concept idea I want to use in a Brutalist styled web page.</p>
<p>This would involve having transparent image being placed randomly behind the content on load, I have this working with mostly vanilla JS, minus a few jQuery methods that I wasn't sure how I could translate back to vanilla. (I learned jQuery helper functions before having a concrete understanding of vanilla JS and now I regret it. lol)</p>
<p>Anyways, here's the <a href="https://jsfiddle.net/54rk6ynL/1/" rel="nofollow noreferrer">JS Fiddle</a>, for you to see the concept, and below is the code with comments.</p>
<p><strong>Javascript</strong></p>
<pre><code>/* Set Variables at the start of the document *
*
* Frame = Parent of the image element (absolute pos within body content) *
* Top/Left Position = the top/left walls of the document *
* Tag = variable for Image element *
*/
var frame = document.getElementById("frame");
var top_position = (Math.random() * ($(document).width() - 500)).toFixed();
var left_position = (Math.random() * ($(document).width() - 500)).toFixed();
var tag = document.getElementById('random');
// Create array of images to randomly select one
var image = [];
image[0] = "https://via.placeholder.com/350x150";
image[1] = "https://via.placeholder.com/150x150";
image[2] = "https://via.placeholder.com/150x350";
image[3] = "https://via.placeholder.com/500x150";
var size = image.length
// randomly selects number of array 0 through size(array.length)
var x = Math.floor(size * Math.random());
//Apply image src/styles to image on load
tag.src = image[x];
tag.style.position = 'absolute';
tag.style.top = top_position + "px";
tag.style.left = left_position + "px";
top_position += 20;
left_position += 20
</code></pre>
<p>Is there anyways I can simplify this and combine some functions, while still keeping it readable?</p>
<p><strong>Example of the effect I was trying to implement</strong></p>
<p><a href="http://www.nur-gut-wenn-keiner-guckt.de/" rel="nofollow noreferrer">multiple images, within grids</a></p>
| [] | [
{
"body": "<p>Yes, I love using functions to make code more readable. </p>\n\n<p>First lets get rid of your jQeury, simply replace $(document) with document.body.clientWidth. </p>\n\n<p>Lets create a function to get an image.</p>\n\n<pre><code>function getImage(src, top, left) {\n var imgElement = document.c... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T14:55:32.003",
"Id": "203934",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"random"
],
"Title": "Randomly select + place an image within a div"
} | 203934 |
<p>I have the below code which i'm working to copy(using rsync) the contents From remote host <code>labserver01</code> and dumps those into the directory <code>/var/log/infoSec/</code> on the base system from where scripts runs and this works correctly and sends e-mail to the recipients, However i'm also figuring out to include a way to send e-mail even if it fails. </p>
<p>I'm Just wondering if there is better way do this, i'm sure there will be more elegant ways. </p>
<p>Appreciate any idea and review in advance.</p>
<pre><code>#!/usr/bin/python3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import subprocess
import argparse
import sys
import os
#Dir Structure
dest_dir = "/infralogs/external_dns_logs"
rsync_user = "root"
email_sender = "dnslogger@udalt.com"
email_receiver = "gusain@udalt.com"
msg = ""
parser = argparse.ArgumentParser()
parser.add_argument("-n","--hosts",dest="hosts",help="enter remote host/hosts name, comma seperated",metavar="HOSTS")
parser.add_argument("-s","--src",dest="source",help="source file/directory",metavar="SOURCE")
parser.add_argument("-e","--exclude",dest="exclude",help="Exclude files/Directories, comma seperated list",metavar="EXCLUDE")
if len(sys.argv) < 7:
print(len(sys.argv))
parser.print_help()
parser.exit()
args = parser.parse_args()
def sync(host,dest_dir):
exclude = ""
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
if ',' in args.exclude:
for excl in args.exclude.split(','):
exclude = exclude + " --exclude " + excl
cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz %s %s@%s:%s %s/"%(exclude,rsync_user,host,args.source,dest_dir)
else:
cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz --exclude %s %s@%s:%s %s/"%(args.exclude,rsync_user,host,args.source,dest_dir)
cmd_content = cmd
p = subprocess.Popen(cmd,shell=True)
p.wait()
print("DONE")
return cmd_content + " Rsync process completed." # returns the msg to the caller
msglist = [] # a list to store the cmd_contents for the mail body
if ',' in args.hosts:
for host in args.hosts.split(','):
dest = dest_dir + "/" + host
msglist.append(sync(host,dest))
else:
dest = dest_dir + "/" + args.hosts
msglist.append(sync(args.hosts,dest))
msg = "\n".join(msglist) # combine all cmd_contents, one per line
try:
Mail = smtplib.SMTP('mailserver.global.udalt.com', 25, 'localhost.udalt.com')
mail_obj = MIMEMultipart('alternative')
mail_obj["From"] = email_sender
mail_obj["To"] = email_receiver
mail_obj["Cc"] = "gusain@udalt.com"
mail_obj["Subject"] = "Rsync process completed Successfully."
mail_obj.attach(MIMEText(msg, 'plain'))
Mail.sendmail(from_addr=[email_sender], to_addrs=[email_receiver],msg=mail_obj.as_string())
print("Mail Sent to %s" % (email_sender))
except Exception as error:
print("Mail Failed - {}".format(error))
</code></pre>
<p><strong>Command Execution method:</strong></p>
<blockquote>
<p><code>$ /usr/bin/dns_rsync.py -n labserver01 -s /var/log/infoSec/ -e "null"</code></p>
</blockquote>
| [] | [
{
"body": "<h1>Review</h1>\n\n<ol>\n<li>Constants should be <code>UPPER_SNAKE_CASE</code></li>\n<li><p>More (and better) functions! </p>\n\n<ul>\n<li>Lot of this code is in the global namespace, which is bad (not maintainable)</li>\n<li><p>Why is <code>sync</code> doing argument parsing?</p>\n\n<p>You should sp... | {
"AcceptedAnswerId": "204044",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T15:53:02.667",
"Id": "203937",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"network-file-transfer",
"ssh"
],
"Title": "Python rsync to copy the logs from multiple remote servers"
} | 203937 |
<p>Trying to applying what seen on What Is Dynamic Programming and How To Use It (here: <a href="https://www.youtube.com/watch?v=vYquumk4nWw" rel="nofollow noreferrer">https://www.youtube.com/watch?v=vYquumk4nWw</a> )
Obviuously this is the final code, after removing the recursion.
I thought it was a good idea to memoize just the latest two values instead of the whole sequence.
I could replace the array with two values and a temp one to make the shift but maybe it will affect readability.
What you think ?</p>
<pre><code>fibonacci: function (n)
{
if (n === 0 || n === 1) return 1;
var array = [1, 1];
for (var i = 2; i < n; i++) {
array.push(array[0] + array[1]);
array.shift();
}
return array[0] + array[1];
}
</code></pre>
| [] | [
{
"body": "<p>Your code will accomplish the task of returning the Nth Fibonacci number and will do it quite fast. But you are not getting the point of the video, how to do Memoization. </p>\n\n<p>To improve your code:</p>\n\n<ol>\n<li><p>Defining your variables at the beginning of your function. </p></li>\n<... | {
"AcceptedAnswerId": "203942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T16:05:03.070",
"Id": "203938",
"Score": "0",
"Tags": [
"javascript",
"dynamic-programming",
"fibonacci-sequence"
],
"Title": "Javascript Fibonacci with dynamic programming"
} | 203938 |
<p>I'm currently using a <code>stored procedure</code>(<code>sproc</code>) to export to Excel. The <code>sproc</code> is being passed two parameters for <code>@month</code> and <code>@year</code>. The parameters are then passed to a <code>dynamic pivot table</code> in order to display all the days of the month for the specified month and year.</p>
<p>It does currently work, however are there better ways I could improve my code in order for it be more efficient? <em>Any</em> help or advice would be greatly appreciated as I'm still a bit of a beginner with SQL (and C# for that matter).</p>
<pre><code>Alter Procedure stpDateRange
-- Add parameters
@month int , @year int
As
Begin
Set NoCount ON
DECLARE @Dates NVARCHAR(max);
SELECT @Dates = CONCAT(@Dates + ', ', QUOTENAME(BalDate))
FROM tblID
WHERE YEAR(BalDate) = @year
AND MONTH(BalDate) = @month
GROUP BY BalDate
ORDER BY BalDate;
DECLARE @DynSql NVARCHAR(max);
SET @DynSql = 'SELECT *
FROM
(
SELECT a1.IDNbr , a2.[CustName] as [Name] , (CAST(a1.BalDate AS date)) as BalDate, a1.Balance
FROM tblID a1
RIGHT JOIN tblCust a2 ON (a1.IDNbr = a2.IDNbr)
WHERE MONTH(a1.BalDate) = @month
AND YEAR(a1.BalDate) = @year AND a2.CustType != ''Inactive'') as d1
PIVOT (
Sum(Balance)
FOR BalDate IN ('+ @Dates +')
) piv';
DECLARE @Params NVARCHAR(500) = N'@year int, @month int';
-- SELECT @DynSql AS DynSql;
EXECUTE sp_executesql @DynSql, @Params, @year = @year, @month=@month;
End
</code></pre>
<p>Test results (dates will continue until the last day of the month):</p>
<pre><code>+-----------------------------------------------------------------+
| IDNbr | Name | 1/1/2018 | 1/2/2018 | 1/3/2018 | 1/4/2018 | ..|
|-----------------------------------------------------------------|
| 52852 | CustOne | 52028.52 | 52038.59 | 52048.69 | 52058.89 | ..|
| 39512 | CustTwo | 95125.75 | 95225.75 | 95325.75 | 95425.75 | ..|
| 52852 | CustThr | 86225.95 | 87225.95 | 88225.95 | 89225.95 | ..|
| 52852 | CustFor | 12533.12 | 12543.12 | 12553.12 | 12563.12 | ..|
| 52852 | CustFiv | 69585.36 | 69685.36 | 69785.36 | 69885.36 | ..|
| ..... | ....... | ........ | ........ | ........ | ........ | ..|
</code></pre>
<p>Readability for the results isn't <em>awful</em> , so that wouldn't be a concern for me, especially with how small the program is that is running this. My main concern is the performance of the stored procedure (<code>sproc</code>). </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T04:08:18.623",
"Id": "393715",
"Score": "0",
"body": "Can you post some example records?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T13:26:57.390",
"Id": "393864",
"Score": "0",
"body"... | [
{
"body": "<p>You could always have 31 days by day number as column headers in the pivot. That way it would always be a consistent header and you wouldn't need to use dynamic SQL. <em>Side note: Go K-State!</em></p>\n<hr />\n<h3>Results</h3>\n<p><a href=\"https://i.stack.imgur.com/Mkvyj.png\" rel=\"nofollow nor... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T16:21:44.253",
"Id": "203940",
"Score": "1",
"Tags": [
"sql",
"sql-server",
"t-sql",
"stored-procedure"
],
"Title": "SQL Stored Procedure to export specified data"
} | 203940 |
<p>I'm trying to build a simulation in R to model the effects of different parasite egg laying behaviors on how many offspring the parasite has, given a limited amount of resources. In brief, this simulation iterates through successive generations of the parasite and follows the number of parasites in each category of traits (how many eggs they lay per berry). I'm looking to see if any particular population goes to extinction more often than others.</p>
<p><strong>Question: Is it possible to speed up this simulation?</strong> I'm interested in running sensitivity analyses with it under varying parameter values, but to get to a reasonable number of generations (n >= 100) and simulations per parameter set, it takes quite a while to run. I'm fairly comfortable with the apply/map family of functions, but I don't have enough experience with R to know if there are places in this script where I could replace any loops or un-vectorized functions with vectorized versions. </p>
<p>One other note: I'm currently only returning the data frame object <code>generation_tracker</code>, but I will eventually be returning the <code>berry_mat</code> and <code>oviposition_location</code> objects as well.</p>
<p>I've included the code for the simulation below. The code does require a few packages to run and the simulation has two helper functions which are provided at the top of those code chunk. Thanks!</p>
<pre><code>library(tidyverse)
library(magrittr)
library(extraDistr)
initBerry <- function(n_berries) {
berry_mat <- matrix(0, nrow = 4, ncol = n_berries)
return(berry_mat)
}
initWasps <- function(n_wasps,
n_eggs,
eggs_per_berry,
pr_double) {
wasps_df <- data.frame(matrix(NA, nrow = n_wasps, ncol = 5))
colnames(wasps_df) <- c("starting_eggs",
"tot_eggs",
"eggs_per_berry",
"pr_double",
"larvae_survive")
wasps_df$starting_eggs <- n_eggs
wasps_df$tot_eggs <- n_eggs
wasps_df$eggs_per_berry <- eggs_per_berry
wasps_df$pr_double <- pr_double
return(wasps_df)
}
simMultiGenerations <- function(n_berries,
n_wasps,
n_eggs,
pr_double,
double_rate,
n_gens,
n_sims)
{
# Initialize simulation ---------------------------------------------------
cl <- makeCluster(detectCores() - 1, type = "SOCK")
registerDoSNOW(cl)
output <- foreach(
j = 1:n_sims,
.export = c("initBerry",
"initWasps"),
.packages = c("magrittr",
"tidyverse",
"extraDistr")
) %dopar%
{
# NOTE: need to assign to something
berry_mat <- initBerry(n_berries = n_berries)
wasp_df <- initWasps(
n_wasps = n_wasps,
n_eggs = rtpois(n_wasps, n_eggs,a = 4, b = 20),
eggs_per_berry = sample(1:4, n_wasps, replace = T),
pr_double = pr_double
)
# Track time with t, as t increases, increase pr_double
t <- 0
# get a parameter for logistic equation for probability of laying
a <- (1 - pr_double) / pr_double
# nested list to store which wasps oviposit in which seeds
oviposition_location <- vector("list", n_berries)
oviposition_location %<>% map(function(.x) {
.x <- vector("list", 4)
})
generation_tracker <- data.frame(
generation = 1:n_gens,
eggs_per_berry1 = NA,
eggs_per_berry2 = NA,
eggs_per_berry3 = NA,
eggs_per_berry4 = NA
)
for (g in 1:n_gens) {
while (any(wasp_df$tot_eggs > 0)) {
# Repeat loop while any wasps have eggs, stop when no eggs remain
for (i in 1:nrow(wasp_df)) {
# Oviposition happens discretely, one wasp at a time
if (wasp_df$tot_eggs[i] == 0) {
# If the current wasp has no eggs, jump to next wasp
next
} else {
# Pick which berry to oviposit in. According to Etsuro, this is random
berry <-
sample(ncol(berry_mat),
size = 1,
replace = TRUE)
# Pick which seed to oviposit in.
if (wasp_df$tot_eggs[i] >= wasp_df$eggs_per_berry[i]) {
seed <- sample(
nrow(berry_mat),
size = wasp_df$eggs_per_berry[i],
replace = FALSE
)
} else {
seed <- sample(nrow(berry_mat),
size = 1,
replace = FALSE)
}
# If the seed is empty, oviposit and subtract an egg
for (j in 1:length(seed)) {
temp_seed <- seed[j]
if (berry_mat[temp_seed, berry] == 0) {
berry_mat[temp_seed, berry] <- berry_mat[temp_seed, berry] + 1
wasp_df$tot_eggs[i] <-
wasp_df$tot_eggs[i] - 1
oviposition_location[[berry]][[temp_seed]] <-
c(i, oviposition_location[[berry]][[temp_seed]])
} else {
# Wasp decides whether to oviposit in already oviposited in egg
lay_egg <-
rbinom(1, 1, prob = wasp_df$pr_double[i])
# If 0, wasp does not oviposit
# If 1, wasp oviposits
if (lay_egg == 1) {
berry_mat[temp_seed, berry] <- berry_mat[temp_seed, berry] + 1
wasp_df$tot_eggs[i] <-
wasp_df$tot_eggs[i] - 1
oviposition_location[[berry]][[temp_seed]] <-
c(i, oviposition_location[[berry]][[temp_seed]])
}
}
}
}
# increment time forward for the purpose of increasing oviposition rate
t <- t + 1
if (t %% nrow(wasp_df) == 0) {
# Every time all the wasps have a chance to oviposit, increase
# their likelihood to oviposit in an already occupied seed
wasp_df$pr_double <-
1 / (1 + a * exp(-double_rate * (t / nrow(wasp_df))))
}
}
}
# End while ---------------------------------------------------------------
oviposition_location <-
oviposition_location %>%
modify_depth(2, function(.x) {
if (is.null(.x)) {
.x <- 0
} else {
# Randomly select which parasitoid develops
.x <-
.x[sample(length(.x), 1)]
}
})
id <- unlist(oviposition_location)
wasp_larvae <- as.data.frame(table(id))
if (any(wasp_larvae$id == 0)) {
wasp_larvae <- wasp_larvae[-1, ]
}
wasp_larvae$id <- as.integer(as.character(wasp_larvae$id))
wasp_df$larvae_survive[wasp_larvae$id] <- wasp_larvae$Freq
wasp_df$larvae_survive <- ifelse(is.na(wasp_df$larvae_survive),
0,
wasp_df$larvae_survive)
wasp_df %<>% mutate(prop_surv = larvae_survive / starting_eggs)
wasp_df$eggs_per_berry <- factor(as.character(wasp_df$eggs_per_berry),
levels = c("1", "2", "3", "4"))
wasp_df %<>% complete(eggs_per_berry, fill = list(larvae_survive = 0))
n_offspring <- wasp_df %>%
group_by(eggs_per_berry) %>%
summarise(offspring = sum(larvae_survive))
generation_tracker[g, 2:5] <- t(n_offspring[, 2])
frequency_eggs_p_berry <- c(rep(1, n_offspring$offspring[1]),
rep(2, n_offspring$offspring[2]),
rep(3, n_offspring$offspring[3]),
rep(4, n_offspring$offspring[4]))
n_eggs <- rtpois(sum(n_offspring$offspring), n_eggs,a = 4, b = 20)
wasp_df <- data.frame(
n_wasps = 1:sum(n_offspring$offspring),
starting_eggs = n_eggs,
tot_eggs = n_eggs,
eggs_per_berry = sample(frequency_eggs_p_berry,
sum(n_offspring$offspring),
replace = FALSE),
pr_double = rep(pr_double, sum(n_offspring$offspring)),
larvae_survive = NA
)
oviposition_location <- vector("list", n_berries)
oviposition_location %<>% map(function(.x) {
.x <- vector("list", 4)
})
}
# End generations loop ----------------------------------------------------
generation_tracker
}
# End simulation loop (end foreach) ---------------------------------------
stopCluster(cl)
closeAllConnections()
return(output)
}
simMultiGenerations(n_berries = 100,
n_wasps = 20,
n_eggs = 12,
pr_double = 0.1,
double_rate = 0.1,
n_gens = 100,
n_sims = 10)
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>You badly need more functions. </p></li>\n<li><p><code>apply</code> functions will not speed up your code that much compared to for loops, but they will make it much more readable, and then you'll be able to spot inefficiencies, in this case though you will more often need <code>purrr::a... | {
"AcceptedAnswerId": "203962",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T16:37:25.780",
"Id": "203941",
"Score": "2",
"Tags": [
"performance",
"r",
"simulation",
"iteration"
],
"Title": "Iteratively simulate a parasite population"
} | 203941 |
<p>I went through a series of lessons in data science using pandas and numpy.</p>
<p>I have attempted to replicate some of the more common algorithms based on maths forumlas and psuedocode, except for the <code>ECDF</code> method which was the first one in the course.</p>
<p>As far as i can tell they are correct and I have put some up against numpy functions in an effort to assert my calculations are correct.</p>
<p>EDIT:</p>
<p>This is not an application I am writing to <code>reinvent the wheel</code>.. It is merely an exercise in coding and exploration of what is <code>under the hood</code></p>
<p>This will maybe explain the use of words like <code>sum</code> in the methods..</p>
<p>I put it up to review as confirmation that I have:</p>
<p>a. coded the algorithms effectively and pythonic.
b. that they are providing the correct results.</p>
<pre><code>x = [41, 19, 23, 40, 55, 57, 33]
y = [60, 61, 71, 78, 76, 82, 945]
import numpy as np
class MafStats:
# ecdf
def ecdf(self, data):
"""Compute ECDF for a one-dimensional array of measurements."""
# Number of data points: n
n = len(data)
# x-data for the ECDF: x
x = np.sort(data)
# y-data for the ECDF: y
y = np.arange(1, n + 1) / n
return x, y
# simple square root function
def square_root(self, data):
""" A function to calculate the Square root of a number"""
return data ** (.5)
# calculate the number of items int he array
def sum(self, list):
""" function that calculates the sum of an array"""
total_sum = 0
for i in list:
total_sum += i
return float(total_sum)
# calculate the mean average
def mean(self, array):
""" a function to calculate the mean average of an array"""
n = float(len(array))
return self.sum(array) / n
# for fun calculate hte medain average
def median(self, array):
""" function that finds the median average of an array"""
# https://www.mathsisfun.com/median.html
n = len(array)
if n < 1:
return None
if n % 2 == 1:
# for an odd array, return the middle number
return sorted(array)[n // 2]
else:
return float(sum(sorted(array)[self.mean(array)]) / 2.0)
# calulate the variance
def variance(self, array):
""" Function to calculate the Variance of data
by calculating the average of the squared differnces from the mean """
n = float(len(array))
total_sum = 0
for i in array:
total_sum += ((self.mean(array) - i) ** 2) / n
return total_sum
# calculate standard deviation
def std_deviation(self, array):
""" A function to calculate the Standard Deviation of Data
by caclulating the Square Root of The Variance"""
return self.square_root(self.variance(array))
# calculate the Covariance of 2 arrays
def covariance(self, array1, array2):
""" function that calculates the Covariance -
Covariance measures how two variables move together.
It measures whether the two move in the same direction (a positive covariance) or
in opposite directions (a negative covariance).
"""
assert float(len(array1)) == float(len(array2))
n = float(len(array1))
sum_array = 0
for (x, y) in zip(array1, array2):
sum_array += (x - mean_result_x) * (y - mean_result_y)
return sum_array / (n - 1)
# correlation co-efficient
def correlation(self, array1, array2):
""" a function to determ,ine the correlation co-efficient between 2 sets of data """
return covar_result / (std_dev_x * std_dev_y)
# Pearson Coefficient
def pearson_correlation(self, array1, array2):
"""Calculcates the Pearson Coefficient """
n = len(array1)
x_times_y = 0
x_sq = 0
y_sq = 0
for i in range(n):
x_min_mean = array1[i] - self.mean(array1)
y_min_mean = array2[i] - self.mean(array2)
x_times_y += x_min_mean * y_min_mean
x_sq += x_min_mean ** 2
y_sq += y_min_mean ** 2
return x_times_y / self.square_root(x_sq * y_sq)
# Least square regression
def least_square_regression(self, x, y, var):
"""
Least square regression is a method for finding a line that summarizes the relationship between the two variables, at least within the domain of the explanatory variable x.
calculate the least square regression line equation with the given x and y values.
"""
# Count the number of given x values.
n = len(x)
# Find XY, X2 for the given values.
def xy_x2(x, y):
xx = [i ** 2 for i, j in zip(x, y)]
xy = [i * j for i, j in zip(x, y)]
return xx, xy
xx, xy = xy_x2(x, y)
# Find ∑X, ∑Y, ∑XY, ∑X2 for the values
ex = sum(x)
ey = sum(y)
exy = sum(xy)
ex2 = sum(xx)
# Slope Formula
# Slope(b) = (N∑XY - (∑X)(∑Y)) / (N∑X2 - (∑X)2)
b = ((n) * (exy) - (ex) * (ey)) / ((n) * (ex2) - (ex) ** 2)
# intercept formula
# Intercept(a) = (∑Y - b(∑X)) / N
a = (ey - b * ex) / n
# Regression Equation(y) = a + b
return a + (b * var)
# factorial
def factorial(self, n):
if n == 0:
return 1
else:
return n * self.factorial(n - 1)
def poisson(self, events, interval):
"""
In probability theory, the Poisson distribution is a very common discrete probability distribution. A Poisson distribution helps in describing the chances of occurrence of a number of events in some given time interval or given space conditionally that the value of average number of occurrence of the event is known. This is a major and only condition of Poisson distribution.
1. The experiment results in outcomes that can be classified as successes or failures.
2. The average number of successes (μ) that occurs in a specified region is known.
3. The probability that a success will occur is proportional to the size of the region.
4. The probability that a success will occur in an extremely small region is virtually zero.
"""
# base value of the system of natural logarithm
e = 2.71828459
# The mean number of successes - Average Rate of Success.
u = events
# The actual number of successes that occur - Poisson Random Variable
x = interval
x1 = self.factorial(x)
# The Poisson probability that exactly x successes occur in a Poisson experiment, when the mean number of successes is μ.
return ((e ** -u) * (u ** x)) / x1
def cul_poisson(self, events, list):
"""
In probability theory, the Poisson distribution is a very common discrete probability distribution. A Poisson distribution helps in describing the chances of occurrence of a number of events in some given time interval or given space conditionally that the value of average number of occurrence of the event is known. This is a major and only condition of Poisson distribution.
1. The experiment results in outcomes that can be classified as successes or failures.
2. The average number of successes (μ) that occurs in a specified region is known.
3. The probability that a success will occur is proportional to the size of the region.
4. The probability that a success will occur in an extremely small region is virtually zero.
"""
# base value of the system of natural logarithm
e = 2.71828459
# The mean number of successes that occur in a specified region.
uc = events
# A list of the actual number of successes that occur in a specified region
xl = range(list)
cul = 0
for i in xl:
r = self.poisson(uc, i)
cul += r
return cul
ms = MafStats()
# ECDF
print("The ECDF of X is: \n", ms.ecdf(x), "\n")
print("The ECDF of Y is:\n", ms.ecdf(y), "\n")
# SQUAER ROOT
num_in = 25
print("The Square root of {} is:".format(num_in), ms.square_root(num_in))
# SUM OF ARRAY
return_sum_x = ms.sum(x)
print("\n\nThe Sum of X is:", return_sum_x)
return_sum_y = ms.sum(y)
print("The Sum of Y is:", return_sum_y)
# MEAN AVERAGE
mean_result_x = ms.mean(x)
print("The Mean Average of X is:", mean_result_x)
print(np.mean(x))
mean_result_y = ms.mean(y)
print("The Mean Average of Y is:", mean_result_y)
print(np.mean(y))
# MEDIAN AVERAGE
median_res = ms.median(x)
print("The Median of X is:", median_res)
print(np.median(x))
median_res1 = ms.median(y)
print("The Median of Y is:", median_res1)
print(np.median(y))
# VARIANCE
var_result_x = ms.variance(x)
print("The Variance of X is:", var_result_x)
var_result_y = ms.variance(y)
print("The Variance of Y is:", var_result_y)
# Standard Deviation
std_dev_x = ms.std_deviation(x)
print("The Standard Deviation Of Data X is:", std_dev_x)
std_dev_y = ms.std_deviation(y)
print("The Standard Deviation Of Data Y is:", std_dev_y, "\n")
# calculate the Covariance of 2 arrays
covar_result = ms.covariance(x, y)
print("The Covariance of X and Y is:", covar_result, "\n")
# standard correlation
# standard correlation
corr_result = ms.correlation(x, y)
print("The Correlation Coefficient between X and Y is:", corr_result, "\n\n")
# Pearson Coefficient
print("The Pearson Correlation Coefficient is:", ms.pearson_correlation(x, y))
# Least Squares Regression
print(
"THe Least Square Regression Line Equation of X and Y is: ",
ms.least_square_regression(x, y, 64),
)
# factorial
print(ms.factorial(2))
# Poisson distributoin
result = ms.poisson(5, 2)
print(result)
r_cul = ms.cul_poisson(5, 4)
print("Poisson Distribution is: ", r_cul)
# Test With Numpy functions..
import numpy as np
print("\nnumpy .cov function: \n", np.cov(x, y))
print("\nnumpy .corrcoef function: \n", np.corrcoef(x, y))
</code></pre>
| [] | [
{
"body": "<p>There is no state being kept in the <code>MafStats</code> object, so it is nothing more than a namespace with an awkward usage. These should all just be functions in a <code>mafstats</code> module.</p>\n\n<p>You're obviously deliberately reinventing the wheel here, since <a href=\"https://docs.sc... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T20:14:54.507",
"Id": "203953",
"Score": "3",
"Tags": [
"python",
"numpy",
"statistics"
],
"Title": "Statistics and calculations"
} | 203953 |
<h2>Overview</h2>
<p>We are learning PHP OOP and decided to create a simple app with 3 database tables, one a basic users table, the other two containing information about the users' favorite food and favorite restaurant.</p>
<p>To help help others learn this and other best practices a bit easier, we welcome PRs, issues, and other contributions to our <a href="https://github.com/nizamani/PHPBestPractices1-OOP/tree/647ee46f2f21b65b4dc31ccb9e40c0410e67d118" rel="nofollow noreferrer">GitHub repository</a>.</p>
<h2>Goal/Output</h2>
<p>Our current goal is to create two pages:</p>
<p>Page 1 output:</p>
<p>"Welcome to the app, Jenn"</p>
<pre><code><?php
namespace PHPBestPractices1OOP\Controller;
use PHPBestPractices1OOP\Request\Request;
use PHPBestPractices1OOP\Response\Response;
use PHPBestPractices1OOP\Domain\User\UserFactory;
class GreetSingleUserPage
{
/**
* @var Response
*/
private $response;
/**
* @var Request
*/
private $request;
/**
* @var UserFactory
*/
private $userFactory;
/**
* GreetSingleUserPage constructor.
* @param Request $request
* @param Response $response
* @param UserFactory $userFactory
*/
public function __construct(
Request $request,
Response $response,
UserFactory $userFactory
) {
$this->response = $response;
$this->request = $request;
$this->userFactory = $userFactory;
}
public function __invoke()
{
// create user object
$userObject = $this->userFactory->createUser(2);
// this will display greeting message to the user
$this->response->setView("greetSingleUser/index.php");
$this->response->setVars(
array(
"name" => $userObject->getName()
)
);
return $this->response;
}
}
</code></pre>
<p>Page 2 output:</p>
<p>"My name is Jenn, age is 28, favorite restaurant is KFC and favorite food is Fried Chicken" </p>
<pre><code><?php
namespace PHPBestPractices1OOP\Controller;
use PHPBestPractices1OOP\Request\Request;
use PHPBestPractices1OOP\Response\Response;
use PHPBestPractices1OOP\Domain\User\UserFactory;
class DisplayUserInformationPage
{
/**
* @var Response
*/
private $response;
/**
* @var Request
*/
private $request;
/**
* @var UserFactory
*/
private $userFactory;
/**
* DisplayUserInformationPage constructor.
* @param Request $request
* @param Response $response
* @param UserFactory $userFactory
*/
public function __construct(
Request $request,
Response $response,
UserFactory $userFactory
) {
$this->response = $response;
$this->request = $request;
$this->userFactory = $userFactory;
}
public function __invoke()
{
// create user object
$userObject = $this->userFactory->createUser(2);
// this will display the user's information
$this->response->setView("displayUserInformation/index.php");
$this->response->setVars(
array(
"name" => $userObject->getName(),
"age" => $userObject->getAge(),
"restaurant" => $userObject->getFavoriteRestaurantName(),
"food" => $userObject->getFavoriteFoodName()
)
);
return $this->response;
}
}
</code></pre>
<h2>Database</h2>
<p>In practice these are sql databases, note though if you happen to look at our github we've <a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/a3200d34882fa5766dfe54d2059647d285ecd377/src/fakedatabase/db.php" rel="nofollow noreferrer">"faked" this db using PHP arrays</a> to make the project easier to run and try out</p>
<pre><code>users
id name age favoriteRestaurantId favoriteFoodId
1 Mike 30 1 1
2 Jenn 28 3 3
restaurants
id name averagePrice style
1 McDonalds 1 American
2 Taco Bell 1 Mexican
3 KFC 2 American
foods
id name caloriesPerOunce
1 French Fries 100
2 Hamburger 135
3 Fried Chicken 97
</code></pre>
<h2>User class</h2>
<p>Here is our <a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/a3200d34882fa5766dfe54d2059647d285ecd377/src/classes/Domain/User/User.php" rel="nofollow noreferrer">User.php</a>. We also have Restaurant and Food classes.</p>
<pre><code><?php
namespace PHPBestPractices1OOP\Domain\User;
use PHPBestPractices1OOP\Domain\Food\Food;
use PHPBestPractices1OOP\Domain\Restaurant\Restaurant;
class User
{
// region vars
/**
* @var int
*/
private $userId;
/**
* @var string
*/
private $name;
/**
* @var int
*/
private $age;
/**
* @var Restaurant
*/
private $favoriteRestaurant;
/**
* @var Food
*/
private $favoriteFood;
// endregion
// region set
/**
* @param $userId
*/
public function setId($userId)
{
$this->userId = $userId;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @param int $age
*/
public function setAge($age)
{
$this->age = $age;
}
/**
* @param $favoriteRestaurant
*/
public function setFavoriteRestaurant(Restaurant $favoriteRestaurant)
{
$this->favoriteRestaurant = $favoriteRestaurant;
}
/**
* @param $favoriteFood
*/
public function setFavoriteFood(Food $favoriteFood)
{
$this->favoriteFood = $favoriteFood;
}
// endregion
// region get
public function getId()
{
return $this->userId;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return int
*/
public function getAge()
{
return $this->age;
}
/**
* @return Restaurant
*/
public function getFavoriteRestaurant()
{
return $this->favoriteRestaurant;
}
/**
* @return string
*/
public function getFavoriteRestaurantName()
{
return $this->favoriteRestaurant->getName();
}
/**
* @return string
*/
public function getFavoriteFoodName()
{
return $this->favoriteFood->getName();
}
/**
* @return Food
*/
public function getFavoriteFood()
{
return $this->favoriteFood;
}
// endregion
}
</code></pre>
<h2>UserFactory</h2>
<pre><code><?php
namespace PHPBestPractices1OOP\Domain\User;
use PHPBestPractices1OOP\Domain\UsersTransactions\UsersTransactions;
use PHPBestPractices1OOP\Domain\Restaurant\RestaurantFactory;
use PHPBestPractices1OOP\Domain\Food\FoodFactory;
class UserFactory
{
/**
* @var UsersTransactions
*/
private $usersTransactions;
/**
* @var FoodFactory
*/
private $foodFactory;
/**
* @var RestaurantFactory
*/
private $restaurantFactory;
/**
* UserFactory constructor.
* @param UsersTransactions $usersTransactions
* @param FoodFactory $foodFactory
* @param RestaurantFactory $restaurantFactory
*/
public function __construct(
UsersTransactions $usersTransactions,
FoodFactory $foodFactory,
RestaurantFactory $restaurantFactory
) {
$this->usersTransactions = $usersTransactions;
$this->foodFactory = $foodFactory;
$this->restaurantFactory = $restaurantFactory;
}
/**
* create an instance of User class
*
* @param int $userId
* @return User
*/
public function createUser($userId)
{
$userObject = new User();
// get user data from the db and set to User object
$userRow = $this->usersTransactions->getUserById($userId);
$userObject->setName($userRow["userRow"]["name"]);
$userObject->setAge($userRow["userRow"]["age"]);
// create restaurant object and set user's favorite restaurant
$restaurantObject = $this->restaurantFactory->createResturant($userRow["userRow"]["favoriteRestaurantId"]);
$userObject->setFavoriteRestaurant($restaurantObject);
// create food object and set user's favorite food
$foodObject = $this->foodFactory->createFood($userRow["userRow"]["favoriteFoodId"]);
$userObject->setFavoriteFood($foodObject);
return $userObject;
}
/**
* create collection of User class instances for user's ids
*
* @param array $userIdsArray
* @return array
*/
public function createUsersCollection($userIdsArray)
{
// users collection
$usersCollection = array();
// loop through users array
foreach ($userIdsArray as $userId) {
$usersCollection[] = $this->createUser($userId);
}
return $usersCollection;
}
}
</code></pre>
<h2>Our Question</h2>
<p>Our current <code>User</code> class works fine, but is slower than it could be for Page 1. Page 1 only requires the user's name, Jenn, which is data in the <code>users</code> table. Yet we still have to get data from the <code>restuarants</code> and <code>foods</code> tables in order to create our user object.</p>
<p>We imagine that in the future half of our app's pages only need info from the <code>users</code> table, while the other half of our app's pages need info from all 3 tables. Since we want our app to be fast and responsive, would it be a good idea to have our <code>user</code> class only include things from the <code>users</code> table, and then maybe create another class <code>UserDetail</code> which includes the Food and Restaurant objects? On pages that we only need to display basic user table info, we use our <code>User</code> class, and on pages where we need to display info about their favorite food and restaurant we use <code>UserDetail</code> class? Or is there some other, better way to do this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T20:49:35.747",
"Id": "393216",
"Score": "0",
"body": "You've only posted part of a `User` class, which is, in my opinion, too sketchy to qualify for a code review according to the rules in the [help/on-topic]."
},
{
"Content... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-18T20:43:00.883",
"Id": "203955",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"orm"
],
"Title": "Displaying a user profile based on a mock ORM"
} | 203955 |
<p>(Sorry this is a repeat post, I hadn't logged in on my initial question and am unable to respond)</p>
<p>I currently have a working code for a simple paint application but it is all in one file and very long. I'm unsure of how to break the code up into smaller pieces and create classes with them. I tried to research Java classes but I'm not coming up with anything comprehensive. My main issue is figuring out how to break up the code I already have, I'm not sure what should be grouped together or how to define and call them.</p>
<pre><code>package paint;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import javafx.scene.shape.Circle;
import javafx.scene.control.Slider;
public class Paint extends Application {
@Override
public void start(Stage primaryStage) {
//Create menu buttons
ToggleButton drawbtn = new ToggleButton("Draw");
ToggleButton linebtn = new ToggleButton("Line");
ToggleButton erasebtn = new ToggleButton("Eraser");
ToggleButton recbtn = new ToggleButton("Rectangle");
ToggleButton circbtn = new ToggleButton("Circle");
ToggleButton[] toolsArr = {drawbtn, linebtn, erasebtn, recbtn, circbtn};
ToggleGroup tools = new ToggleGroup();
for (ToggleButton tool : toolsArr) {
tool.setMinWidth(90);
tool.setToggleGroup(tools);
}
//Initializing Color Picker and Color fills selections
ColorPicker cpLine = new ColorPicker(Color.BLACK);
ColorPicker cpFill = new ColorPicker(Color.TRANSPARENT);
//Creating label names
Label line_color = new Label("Line Color");
Label fill_color = new Label("Fill Color");
//Creating line width selector
Slider slider = new Slider(1, 25, 3);
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
Button saveas = new Button("Save As");
Button open = new Button("Open");
//Menu with buttons
VBox btns = new VBox(10);
btns.getChildren().addAll(drawbtn, linebtn, line_color, cpLine, fill_color, cpFill, open, saveas, erasebtn, recbtn, circbtn, slider);
btns.setPadding(new Insets(5));
btns.setPrefWidth(100);
//Setting up the blank canvas
Canvas canvas = new Canvas(1080, 790);
GraphicsContext gc;
gc = canvas.getGraphicsContext2D();
gc.setLineWidth(1);
Line line = new Line();
Rectangle rec = new Rectangle();
Circle circ = new Circle();
//Was the mouse button pressed on the canvas..
canvas.setOnMousePressed(e->{
if(drawbtn.isSelected()) { //While the draw button is selected
gc.setStroke(cpLine.getValue());
gc.beginPath();
gc.lineTo(e.getX(), e.getY());
}
else if(linebtn.isSelected()) { //While the line button is selected
gc.setStroke(cpLine.getValue());
line.setStartX(e.getX()); //Start line at this x value
line.setStartY(e.getY()); //Start line at this y value
}
else if(erasebtn.isSelected()) { //While the eraser button is selected
double lineWidth = gc.getLineWidth();
gc.clearRect(e.getX() - lineWidth / 2, e.getY() - lineWidth / 2, lineWidth, lineWidth);
}
else if(recbtn.isSelected()) { //While the rectangle button is selected
gc.setStroke(cpLine.getValue());
gc.setFill(cpFill.getValue()); //Fill the rectangle with fill color
rec.setX(e.getX()); //Start rectangle at this x
rec.setY(e.getY()); //Start rectangle at this y
}
else if(circbtn.isSelected()) {
gc.setStroke(cpLine.getValue());
gc.setFill(cpFill.getValue());
circ.setCenterX(e.getX());
circ.setCenterY(e.getY());
}
});
//Draws and creates line based on mouse clicks
canvas.setOnMouseDragged(e->{
if(drawbtn.isSelected()) {
gc.lineTo(e.getX(), e.getY());
gc.stroke();
}
//Erases areas where the mouse is clicked and dragged over
else if(erasebtn.isSelected()){
double lineWidth = gc.getLineWidth();
gc.clearRect(e.getX() - lineWidth / 2, e.getY() - lineWidth / 2, lineWidth, lineWidth);
}
});
//Was the mouse button released...
canvas.setOnMouseReleased(e->{
if(drawbtn.isSelected()) { //while the draw button was selcted
gc.lineTo(e.getX(), e.getY());
gc.stroke();
gc.closePath();
}
else if(linebtn.isSelected()) { //while the line button was selcted
line.setEndX(e.getX());
line.setEndY(e.getY());
gc.strokeLine(line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
}
else if(erasebtn.isSelected()) { //while the erase button was selcted
double lineWidth = gc.getLineWidth();
gc.clearRect(e.getX() - lineWidth / 2, e.getY() - lineWidth / 2, lineWidth, lineWidth);
}
else if(recbtn.isSelected()) { //while the rectangle button was selcted
rec.setWidth(Math.abs((e.getX() - rec.getX())));
rec.setHeight(Math.abs((e.getY() - rec.getY())));
//If X value of rectangle is greater than the X value of e, make e = rectangle value
if(rec.getX() > e.getX()) {
rec.setX(e.getX());
}
//If Y value of rectangle is greater than the Y value of e, make e = rectangle value
if(rec.getY() > e.getY()) {
rec.setY(e.getY());
}
//Filling the rectangle with color
gc.fillRect(rec.getX(), rec.getY(), rec.getWidth(), rec.getHeight());
gc.strokeRect(rec.getX(), rec.getY(), rec.getWidth(), rec.getHeight());
}
else if(circbtn.isSelected()) {
circ.setRadius((Math.abs(e.getX() - circ.getCenterX()) + Math.abs(e.getY() - circ.getCenterY())) / 2);
if(circ.getCenterX() > e.getX()) {
circ.setCenterX(e.getX());
}
if(circ.getCenterY() > e.getY()) {
circ.setCenterY(e.getY());
}
gc.fillOval(circ.getCenterX(), circ.getCenterY(), circ.getRadius(), circ.getRadius());
gc.strokeOval(circ.getCenterX(), circ.getCenterY(), circ.getRadius(), circ.getRadius());
}
});
//Setting up the color picker for line/drawing
cpLine.setOnAction(e->{
gc.setStroke(cpLine.getValue());
});
//Setting up the color fill
cpFill.setOnAction(e->{
gc.setFill(cpFill.getValue());
});
//Setting up the width slider
slider.valueProperty().addListener(e->{
double width = slider.getValue();
gc.setLineWidth(width);
});
//Open a file from desktop
open.setOnAction((e)->{
FileChooser openFile = new FileChooser();
openFile.setTitle("Open File");
File file = openFile.showOpenDialog(primaryStage);
if (file != null) {
try {
InputStream io = new FileInputStream(file);
Image img = new Image(io);
gc.drawImage(img, 0, 0);
} catch (IOException ex) {
System.out.println("Error!");
}
}
});
//Save Canvas
saveas.setOnAction((e)->{
FileChooser savefile = new FileChooser();
savefile.setTitle("Save File");
File file = savefile.showSaveDialog(primaryStage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(1080, 790);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error!");
}
}
});
BorderPane pane = new BorderPane();
pane.setRight(btns);
pane.setCenter(canvas);
Scene scene = new Scene(pane, 1200, 800); //Sets size of window
primaryStage.setTitle("Paint");
primaryStage.setScene(scene);
primaryStage.show();
}
//Launch Program
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
| [] | [
{
"body": "<p>1) Create PrimaryStage class that will include state of the stage:</p>\n\n<pre><code> public class PrimaryStage {\n private Stage stage;\n private List<ToggleButton> buttons;\n private ToggleGroup tools;\n private ColorPicker cpLine;\n private ColorPicke... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T00:46:38.773",
"Id": "203960",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"canvas",
"javafx"
],
"Title": "Breaking up a simple Paint application into smaller classes"
} | 203960 |
<p>I was reading the book <a href="https://www.goodreads.com/book/show/25666050-algorithms-to-live-by" rel="nofollow noreferrer">Algortihms to Live By</a> and was inspired by it to take a shot at simulating <a href="https://stackoverflow.com/questions/14415881/how-to-pair-socks-from-a-pile-efficiently">How to pair socks from a pile?</a> (sans the efficiently part at the moment).</p>
<pre><code>import random
from operator import add
def get_pair_of_socks(num_of_socks):
return random.sample(range(num_of_socks), num_of_socks)
def index_to_pull_sock_from(bag_of_socks: list):
return random.randint(a=0, b=len(bag_of_socks) - 1)
def attempt_counts_matching_socks(num_of_socks_to_consider):
# Keep attempt counts in this list.
attempt_counts = []
# Generate pairs of random socks.
socks = get_pair_of_socks(num_of_socks_to_consider) + get_pair_of_socks(num_of_socks_to_consider)
while len(socks) != 0:
# Pick one pair from the bag..
first_pair = socks.pop(index_to_pull_sock_from(socks))
# Pick a second pair..
random_pick = index_to_pull_sock_from(socks)
second_pair = socks[random_pick]
# We did an attempt..
attempt_count = 1
# If they matched, perfect. We will never enter this block.
# Otherwise loop until you do find the match..
while second_pair != first_pair:
# Increment the attempt_count whenever you loop..
attempt_count = attempt_count + 1
random_pick = index_to_pull_sock_from(socks)
second_pair = socks[random_pick]
# Remove the second matching pair from the bag..
socks.pop(random_pick)
# Keep the number of attempts it took you to find the second pair..
attempt_counts.append(attempt_count)
return attempt_counts
num_of_iterations = 1000
pair_of_socks = 10
# Initalise a list of length `pair_of_socks`
attempt_counts_so_far = [0] * pair_of_socks
for _ in range(num_of_iterations):
# Get attempt counts for 1 iteration..
attempt_counts_single_iteration = attempt_counts_matching_socks(pair_of_socks)
# Add the attempt counts aligned by index. We will be dividing by the total number of iterations later for averages.
attempt_counts_so_far = list(map(add, attempt_counts_so_far, attempt_counts_single_iteration))
average_takes = list(map(lambda x: x / num_of_iterations, attempt_counts_so_far))
print(average_takes)
# [18.205, 16.967, 14.659, 12.82, 11.686, 9.444, 7.238, 4.854, 2.984, 1.0]
</code></pre>
| [] | [
{
"body": "<p>Your <code>get_pair_of_socks</code> seems to be initializing a pile of socks, so you have the wrong name. </p>\n\n<p>If I understand things correctly, you initialize a pile of \"left\" socks, then initialize a pile of \"right\" socks (socks don't have left and right, but the labels make it easier ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T01:30:27.653",
"Id": "203961",
"Score": "1",
"Tags": [
"python",
"random",
"simulation"
],
"Title": "Matching socks from a bag of socks"
} | 203961 |
<p>I've recently finished building a calculator in Python using Tkinter, and would appreciate any and all feedback on it. Please ignore the use of the <code>eval</code> function, I know this is advised against using but my teacher insists that we use it in our development.</p>
<p>I'd really like to condense and simplify my code for validation which can be found below, but I can't think of any other way to do it. This code validates text being entered into the Tkinter entry field.</p>
<pre><code>def validate_input(self, entered_value, modify_type, index):#used to validate input entered into entry field.
current_input = str(self.text_box.get())
index_pos = int(index)
#Cheecks if the attempted modification type is insertion or deletion.
if modify_type == '1': #insert
if entered_value== ".":
if current_input == "":
return True#allows a decimal point to be inserted if the field is blank.
elif index_pos == len(current_input):
if current_input[-1] == ".":
return False#doesn't allow a decimal to be inserted if the last character is a decimal.
else:
return True
elif current_input[index_pos-1] == "." or current_input[index_pos] =="." :
return False#doesn't allow a decimal to be inserted if there is a decimal point on either side of the insert position.
else:
return True
if entered_value in "*/+-":
if current_input == "" and entered_value in "*/":
return False#doesn't allow a multiplication or division operator to be entered into an empty field.
elif current_input == "" and entered_value in "+-":
return True#allows an addition or subtraction operator to be entered for negative and positive numbers
if index_pos == len(current_input):#if character is being inserted at the end of the string
if current_input[-1] in "+-" and entered_value in "+-":
return True#allows two addition or subtraction signs in a row.
elif current_input[-1] == "." and entered_value in "+-":
return False#doesn't allow the insertion of + or - after a decimal point.
elif current_input[-1] in "*/+-." and entered_value in "*/":
return False#doesn't allow * or / to be entered after */+-
else:
return True
if entered_value in "+-":
if current_input[index_pos-1] in "*/+-" or current_input[index_pos] in "*/+-" :
return True#allows a + or a - to be inserted after or before another operator.
elif current_input[index_pos-1] == ".":
return False#doesn't allow a + or a - to be entered after a decimal point.
elif entered_value in "*/":
if current_input[index_pos-1] in "*/+-." or current_input[index_pos] in "*/+-" :
return False#doesn't allow a * or / to be entered if there is an operator or decimal before, or an operator after.
else:
return True
#Checks if entered value is in list of accepted values, stored in setup of CalculatorGUI class.
if entered_value in self.accepted_values:
return True
#Accepts all attempts to remove text from the entryfield.
elif modify_type == "0":#delete
return True
return False
</code></pre>
<p>Full code can be found below, thanks for your help! :)</p>
<pre><code>from tkinter import *
from tkinter import messagebox
import re
class CalculatorFunctions:
def __init__(self, root):
self.root = root
def num_press(self, num):#function that runs if a number button is pressed
new_input = num
cursor_position = self.text_box.index(INSERT)#gets position of where number is trying to be inserted
self.text_box.insert(cursor_position, new_input)#inserts number at the cursor's position in the entry field
#Creates a message-box popup to display relevant author information.
def show_info_popup(self):
messagebox.showinfo("Author", "NAME", \nLast Edited: September 2018\nPython Version: 3.7.0")
#Command that clears everything in the calculator's entrybox.
def clear_screen(self):
self.text_box.delete(0, END)
#Removes the last character in the entry field.
def backspace(self):
current = str(self.text_box.get())
cursor_position = self.text_box.index(INSERT)
if cursor_position == 0:#if the insert position is at the beginning of the entry field (far left), don't backspace anything.
pass
else:
#deletes the text one index position before the insert position.
cursor_position -= 1
self.text_box.delete(cursor_position)
#Uses the eval function to calculate entered string in calculator.
def calculate_answer(self):
try:
#regex string that removes leading zeroes from the start of numbers and replaces the matched pattern with the numbers found in group 2.
answer = eval(re.sub(r"((?<=^)|(?<=[^\.\d]))0+(\d+)", r"\2", self.text_box.get()))
self.accepted_values.append(str(answer)) #appends answer to list of accepted values so that it is able to be inserted into the entry field through the validation algorithm.
self.text_box.delete(0, END) #deletes contents of entry field.
self.text_box.insert(0, answer)#inserts answer into entry field.
except (SyntaxError, ZeroDivisionError):#runs if a syntax error or zero division error is caught when calculating an answer.
messagebox.showwarning("Error", "Please edit your entered input and calculate again.\nCommon errors include:\n\n -Dividing by 0\n -Including too many decimal points in one number\n -Incorrect operator usage\n- Pressing equals when the screen is empty")
def validate_input(self, entered_value, modify_type, index):#used to validate input entered into entry field.
current_input = str(self.text_box.get())
index_pos = int(index)
#Cheecks if the attempted modification type is insertion or deletion.
if modify_type == '1': #insert
if entered_value== ".":
if current_input == "":
return True#allows a decimal point to be inserted if the field is blank.
elif index_pos == len(current_input):
if current_input[-1] == ".":
return False#doesn't allow a decimal to be inserted if the last character is a decimal.
else:
return True
elif current_input[index_pos-1] == "." or current_input[index_pos] =="." :
return False#doesn't allow a decimal to be inserted if there is a decimal point on either side of the insert position.
else:
return True
if entered_value in "*/+-":
if current_input == "" and entered_value in "*/":
return False#doesn't allow a multiplication or division operator to be entered into an empty field.
elif current_input == "" and entered_value in "+-":
return True#allows an addition or subtraction operator to be entered for negative and positive numbers
if index_pos == len(current_input):#if character is being inserted at the end of the string
if current_input[-1] in "+-" and entered_value in "+-":
return True#allows two addition or subtraction signs in a row.
elif current_input[-1] == "." and entered_value in "+-":
return False#doesn't allow the insertion of + or - after a decimal point.
elif current_input[-1] in "*/+-." and entered_value in "*/":
return False#doesn't allow * or / to be entered after */+-
else:
return True
if entered_value in "+-":
if current_input[index_pos-1] in "*/+-" or current_input[index_pos] in "*/+-" :
return True#allows a + or a - to be inserted after or before another operator.
elif current_input[index_pos-1] == ".":
return False#doesn't allow a + or a - to be entered after a decimal point.
elif entered_value in "*/":
if current_input[index_pos-1] in "*/+-." or current_input[index_pos] in "*/+-" :
return False#doesn't allow a * or / to be entered if there is an operator or decimal before, or an operator after.
else:
return True
#Checks if entered value is in list of accepted values, stored in setup of CalculatorGUI class.
if entered_value in self.accepted_values:
return True
#Accepts all attempts to remove text from the entryfield.
elif modify_type == "0":#delete
return True
return False
class CalculatorGUI(CalculatorFunctions):
def __init__(self, root):
self.root = root
#binds equals key to calculate an answer when pressed
root.bind("=", lambda event: self.calculate_answer())
#binds enter key to calculate an answer when pressed
root.bind('<Return>', lambda event: self.calculate_answer())
#list of values allowed to be inserted into entry field
self.accepted_values = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", "."]
self.create_number_buttons()
self.create_text_box()
self.create_special_buttons()
def create_number_buttons(self):
button_characters = "789*456/123-0.=+"
#Variable that is used to iterate through button characters.
i = 0
#Empty list to store created buttons in.
self.button_list = []
#Row starts at row 2 as I will have the entry field on row 0 and AC on row 1.
for row_counter in range(2,6):
#I want to have a 4x4 grid of buttons, so will use column in range 4 (0,1,2,3) for each row.
for column_counter in range(4):
#Appends each button to a list as it is created so that individual buttons are able to be referenced at later stages of program development.
self.button_list.append(Button(root, bg="#11708e", fg="white", pady=25, padx=35, text=button_characters[i], font=("Helvetica", 20, 'bold')))
self.button_list[i].grid(row=row_counter, column=column_counter, sticky="NSEW")
self.button_list[i].configure(command = lambda character=button_characters[i]: self.num_press(character))
i += 1
self.reconfigure_operator_buttons()
#Reconfigures operators ro have a red background.
def reconfigure_operator_buttons(self):
i = 0
for button in self.button_list:
#Cget gets the current value of the specified button attribute, in this case being "text".
if self.button_list[i].cget("text") in "-+/*.=":
self.button_list[i].configure(bg="#d14302")
if self.button_list[i].cget("text") == "=":
self.button_list[i].configure(command=self.calculate_answer)
i +=1
def create_text_box(self):
self.text_box = Entry(root, justify=RIGHT, validate="key", font=("Helvetica", 20, 'bold'), borderwidth=15)
self.text_box['validatecommand'] = (self.text_box.register(self.validate_input),'%S','%d', '%i')
#Places the entry field in row 0, column 0, adds internal padding to increase width of field.
self.text_box.grid(row=0, column=0, columnspan=4, ipady=10, sticky="WE")
def create_special_buttons(self):
clear_button = Button(root, bg="#302e2e", fg="white", text="AC", font=("Helvetica", 14, 'bold'), pady=10,command=self.clear_screen)
clear_button.grid(row=1, columnspan=2, sticky="WE")
backspace_button = Button(root, bg="#302e2e", fg="white", text="Backspace", font=("Helvetica", 14, 'bold'), pady=10, command=self.backspace)
backspace_button.grid(row=1, column=3, sticky="NSEW")
author_button = Button(root, bg="#302e2e", fg="white", font=("Helvetica", 14, 'bold'), text="Info", pady=10, command=self.show_info_popup)
author_button.grid(row=1, column=2, sticky="NSEW")
root = Tk()
root.title("Calculator")
root.resizable(0, 0)
calc = CalculatorGUI(root)
root.mainloop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T07:13:57.050",
"Id": "393808",
"Score": "0",
"body": "Please do not update or remove the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. Please see *[what... | [
{
"body": "<h2>Remove redundant comments</h2>\n\n<p>Your code is heavy with comments, quite some which are just stating the obvious. If you have a function called <code>clear_screen()</code>, then you don't need a comment saying it clears the screen. Just rely on descriptive function names (which you have!) to ... | {
"AcceptedAnswerId": "204007",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T04:12:33.183",
"Id": "203964",
"Score": "3",
"Tags": [
"python",
"validation",
"calculator",
"tkinter"
],
"Title": "Tkinter based calculator"
} | 203964 |
<p>I used to import all the actions in the container's argument which looks messy (I put a comment below where I do it in that way). I want to know if there is a better approach when using actions with react-redux. Should I use alias, and if I use alias is there any impact on the performance?</p>
<pre><code>import React from 'react';
import Proptypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
selectNumber,
selectOperator,
solverOperator,
initialize,
addDecimal,
clearEntry,
changeSign,
} from '../actions/index';
const ButtonsContainer = ({ selectNumber, selectOperator, solverOperator, initialize, addDecimal, clearEntry, changeSign, }) => ( // HERE I PUT ALL THE ACTIONS AS ARGUMENT
<React.Fragment>
<button value="AC" onClick={() => initialize()} className="buttonStyle ac" type="submit">AC</button>
<button value="CE" onClick={() => clearEntry()} className="buttonStyle ce" type="submit">CE</button>
<button value="CHANGE" onClick={e => changeSign(e.target)} className="buttonStyle posneg" type="submit">+/-</button>
<button value="/" onClick={e => selectOperator(e.target)} className="buttonStyle divide" type="submit">/</button>
<button value="7" onClick={e => selectNumber(e.target)} className="buttonStyle seven" type="submit">7</button>
<button value="8" onClick={e => selectNumber(e.target)} className="buttonStyle eight" type="submit">8</button>
<button value="9" onClick={e => selectNumber(e.target)} className="buttonStyle nine" type="submit">9</button>
<button value="*" onClick={e => selectOperator(e.target)} className="buttonStyle multiply" type="submit">X</button>
<button value="4" onClick={e => selectNumber(e.target)} className="buttonStyle four" type="submit">4</button>
<button value="5" onClick={e => selectNumber(e.target)} className="buttonStyle five" type="submit">5</button>
<button value="6" onClick={e => selectNumber(e.target)} className="buttonStyle six" type="submit">6</button>
<button value="-" onClick={e => selectOperator(e.target)} className="buttonStyle minus" type="submit">-</button>
<button value="1" onClick={e => selectNumber(e.target)} className="buttonStyle one" type="submit">1</button>
<button value="2" onClick={e => selectNumber(e.target)} className="buttonStyle two" type="submit">2</button>
<button value="3" onClick={e => selectNumber(e.target)} className="buttonStyle three" type="submit">3</button>
<button value="+" onClick={e => selectOperator(e.target)} className="buttonStyle plus" type="submit">+</button>
<button value="0" onClick={e => selectNumber(e.target)} className="buttonStyle zero" type="submit">0</button>
<button value="." onClick={e => addDecimal(e.target)} className="buttonStyle dot" dangerouslySetInnerHTML={{ __html: '&middot' }} type="submit" />
<button value="=" onClick={e => solverOperator(e.target)} className="buttonStyle equal" type="submit">=</button>
</React.Fragment>
);
ButtonsContainer.propTypes = {
selectNumber: Proptypes.func.isRequired,
selectOperator: Proptypes.func.isRequired,
solverOperator: Proptypes.func.isRequired,
initialize: Proptypes.func.isRequired,
addDecimal: Proptypes.func.isRequired,
clearEntry: Proptypes.func.isRequired,
changeSign: Proptypes.func.isRequired,
};
const mapDispatchToProps = dispatch => bindActionCreators({
selectNumber,
selectOperator,
solverOperator,
initialize,
addDecimal,
clearEntry,
changeSign,
}, dispatch);
</code></pre>
| [] | [
{
"body": "<p>I would try to extract some of the common functionality into reusable components as follows. The <code>NumericButton</code> and <code>OperatorButton</code> components could either receive <code>selectNumber</code> and <code>selectOperator</code> as props or the components could be connected compon... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T05:22:39.790",
"Id": "203967",
"Score": "2",
"Tags": [
"calculator",
"react.js",
"jsx",
"redux"
],
"Title": "Redux actions inside a container for a calculator"
} | 203967 |
<p>I'm a beginner programmer looking for a review of my simple war card game program I made. Each player gets a deck and you pull 1 card at a time and compare the 2. Highest value wins. Do that until the deck is gone and whoever has the most points wins. Any advice is appreciated! Thank you for your time looking at this!</p>
<pre><code>enum Suit
{
Hearts,
Diamonds,
Spades,
Clovers
}
enum Face
{
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
}
// MAKING WAR CARD GAME
class Program
{
public static bool isPlaying = true;
public static Player human = new Player();
public static Player cpu = new Player();
public static int round = 1;
static void Main(string[] args)
{
GameFlow.Start(human, cpu);
while (isPlaying)
{
for (int i = 0; i < 52; i++)
{
GameFlow.Gameplay(human, cpu, round);
round++;
}
round = 1;
GameFlow.Ending(human, cpu);
}
}
}
class Player
{
public string name = "CPU";
public Card currentCard = new Card(); // the current card in play
public int wins = 0 , drawCount = 0;
public Deck myDeck = new Deck();
public void DrawOne()
{
currentCard = myDeck.CurrentlyInDeck[drawCount];
drawCount++;
if (drawCount == 52)
{
drawCount = 0;
}
}
public void SetName()
{
while (name == "CPU" || name == "")
{
Console.WriteLine("What is your name human?");
name = Console.ReadLine();
if(name == "CPU" || name == "")
{
Console.WriteLine("Invalid name!! Try a real name you assclown!");
Console.ReadLine();
}
Console.Clear();
}
}
class Card
{
public Suit suit;
public Face face;
public void PrintCard()
{
Console.Write("{0} of {1}", face, suit);
}
}
class Deck
{
public List<Card> CurrentlyInDeck;
public void GenerateDeck() // Must use this to populate deck
{
CurrentlyInDeck = new List<Card>(52);
int place = 0; // tracks which card number
for (int i = 0; i < 4; i++)
{
for (int f = 0; f < 13; f++)
{
Card card = new Card();
CurrentlyInDeck.Add(card);
CurrentlyInDeck[place].suit = (Suit)i;
CurrentlyInDeck[place].face = (Face)f;
place++;
}
}
}
private static readonly Random rand = new Random();
public void Shuffle()
{
Card holder = new Card();
int random;
for (int i = 0; i < 52; i++)
{
random = rand.Next(0, 51);
holder = CurrentlyInDeck[i];
CurrentlyInDeck[i] = CurrentlyInDeck[random];
CurrentlyInDeck[random] = holder;
}
}
public void PrintDeck() // prints all cards in the deck , used for testing
{
foreach (var card in CurrentlyInDeck)
{
card.PrintCard();
}
}
}
static class Create
{
public static void Name(Player a)
{
a.SetName();
}
public static void TheirDecks(Player hum , Player cpu)
{
hum.myDeck.GenerateDeck();
cpu.myDeck.GenerateDeck();
hum.myDeck.Shuffle();
cpu.myDeck.Shuffle();
}
}
static class GameFlow
{
static public void Start(Player hum, Player cpu) //Creates initial situation
{
Words.Begin();
Create.TheirDecks(hum, cpu);
Create.Name(hum);
}
static public void ShuffleDecks(Player hum, Player cpu)
{
hum.myDeck.Shuffle();
cpu.myDeck.Shuffle();
}
static public void DrawCards(Player hum, Player cpu) // changes the current card
{
hum.DrawOne();
cpu.DrawOne();
}
static public void Gameplay(Player hum, Player cpu, int round) // The normal gameplay loop
{
GameFlow.DrawCards(hum, cpu);
Words.Template(hum, cpu, round);
GameFlow.CheckWin(hum, cpu);
}
static public void Ending(Player hum, Player cpu) // Once all the cards have been played
{
string answer = "";
bool correctForm = false;
Words.LastWords(hum, cpu);
while (!correctForm)
{
Console.WriteLine("Would you like to play again? Enter y for yes or n for no.");
answer = Console.ReadLine();
answer = answer.ToLower();
if(answer != "y" && answer != "n")
{
Console.WriteLine("Thats not a valid option you idiot!");
Console.WriteLine("Press enter to continue.");
Console.ReadLine();
Console.Clear();
Words.LastWords(hum, cpu);
}
if(answer == "y" || answer == "n")
{
correctForm = true;
}
}
if (answer == "y")
{
PlayingAgain(hum ,cpu);
Console.Clear();
}
if (answer == "n")
{
Console.WriteLine("Thanks for playing!");
Console.WriteLine("Press enter to exit.");
Environment.Exit(0);
}
}
static public void PlayingAgain(Player hum , Player cpu)
{
ShuffleDecks(hum, cpu);
hum.wins = 0;
cpu.wins = 0;
}
static public void CheckWin(Player hum , Player cpu)
{
Console.WriteLine("");
if ((int)hum.currentCard.face > (int)cpu.currentCard.face)
{
hum.wins++;
Console.WriteLine();
Console.WriteLine("You win this one! Nice!");
Console.WriteLine("Press enter to keep going.");
Console.ReadLine();
Console.Clear();
}
else if ((int)hum.currentCard.face < (int)cpu.currentCard.face)
{
cpu.wins++;
Console.WriteLine();
Console.WriteLine("Looks like the CPU won this one. You suck!");
Console.WriteLine("Press enter to keep going.");
Console.ReadLine();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Its a draw!");
Console.WriteLine("Press enter to keep going.");
Console.ReadLine();
Console.Clear();
}
}
}
static class Words // The dialogue of the program
{
public static void Begin()
{
Console.WriteLine("Hello , welcome to war!");
Console.WriteLine("The rules are simple. Its you vs a cpu");
Console.WriteLine("You each pull 1 card from your decks and see which is highest.");
Console.WriteLine("Your card will be the one under your name , while the other is the CPUs.");
Console.WriteLine("The one with the most points at the end wins all the glory!");
Console.WriteLine("Understand?");
Console.WriteLine("Press enter if you're ready for the showdown.");
Console.ReadLine();
Console.Clear();
}
public static void Template(Player hum , Player cpu , int round) //Prints the normal screen
{
int distance = 17; //distance between the 2 names
Console.Write("{0} wins = {1}", hum.name, hum.wins);
Console.Write(" R{0}", round);
distance -= hum.name.Length;
while (distance > 0)
{
Console.Write(" ");
distance--;
}
Console.Write("{0} wins = {1}" , cpu.name , cpu.wins);
Console.WriteLine();
Console.WriteLine();
hum.currentCard.PrintCard();
Console.Write(" vs ");
cpu.currentCard.PrintCard();
}
public static void LastWords(Player hum , Player cpu)
{
Console.WriteLine("Thats all the cards!");
Console.WriteLine("So this is the final score: {0} = {1} and {2} = {3}" , hum.name, hum.wins, cpu.name, cpu.wins);
if(hum.wins > cpu.wins)
{
Console.WriteLine("You have beaten the CPU in this game of luck!!!! Congrats!!!");
}
else if(cpu.wins > hum.wins)
{
Console.WriteLine("The CPU has detroyed you and everything you have loved. Congrats!!!");
}
else
{
Console.WriteLine("Oh my! Its a draw. You both are equal warriors of luck.");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T08:33:17.940",
"Id": "393274",
"Score": "6",
"body": "Can you please add a summary about how the game works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T11:23:14.857",
"Id": "393297",
"Sco... | [
{
"body": "<p>Let me first say that I admire the thought you've put into class and function names. For example, <code>Create.TheirDecks()</code> has a sort of fluent feel to it, which I appreciate. \"Your code should read like a sentence\" is advice I often give, but it seems you've already taken that to heart.... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T05:58:48.867",
"Id": "203971",
"Score": "6",
"Tags": [
"c#",
"beginner",
"game",
"playing-cards"
],
"Title": "The card game war"
} | 203971 |
<p>I am reading the "Learning Concurrent Programming in Scala" and there are exercises in the end of each chapter.
One of exercises is</p>
<blockquote>
<p>Implement a parallel method which takes two computation blocks a and
b, and starts each of them in a new thread. The method must return a
tuple with the result values of both the computations. It should have
the following signature: def parallel[A, B](a: => A, b: => B):(A, B)</p>
</blockquote>
<p>I have implemented it in this way:</p>
<pre><code>def parallel[A, B](a: => A, b: => B):(A, B) = {
var aResult:Option[A] = Option.empty
var bResult:Option[B] = Option.empty
val t1 = thread{aResult = Some(a)}
val t2 = thread{bResult = Some(b)}
t1.join()
t2.join()
(aResult.get, bResult.get)
}
</code></pre>
<p>where <code>thread</code> is</p>
<pre><code>def thread(block: =>Unit):Thread = {
val t = new Thread{
override def run(): Unit = block
}
t.start()
t
}
</code></pre>
<p>My question is if this implementation is free of race condition? I have seen that other people had a similar implementations but declared result holder variables <code>aResult</code> and <code>bResult</code> to be <code>volatile</code>. I am not sure that this is necessary, and also I was not able to design a test which would break the correctness of my implementation.</p>
<p>From my point of view the implementation is free of race condition because the <code>parallel</code> method does not access any shared variables. All its state is in its local variables so is not shared. Thus I think that adding <code>@volatile</code> to <code>aResult</code> and <code>bResult</code> is not needed in this case.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T07:06:20.693",
"Id": "393257",
"Score": "1",
"body": "\"is good enough?\" That's a subjective question, one we can't answer with the current amount of information. Please clarify the title, since the rest of the question doesn't ha... | [
{
"body": "<blockquote>\n <p>From my point of view the implementation is free of race condition because the parallel method does not access any shared variables. All its state is in its local variables so is not shared. </p>\n</blockquote>\n\n<p>That is not true. The variable <code>aResult</code> is shared bet... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T06:58:39.307",
"Id": "203972",
"Score": "2",
"Tags": [
"scala",
"thread-safety",
"concurrency"
],
"Title": "Run two computations in parallel, and return the results together"
} | 203972 |
<p>First: I'm not really a programmer. Thus, this application may be started in a bad way, but here is my question.</p>
<p>It's not a specific one because I have no real clue about how to improve my code. Let me know how I can recenter this question if needed.</p>
<p>Anyway, here is what I do and my issues:</p>
<p>First, you will see on the code linked below, that I use cache. I'm pretty sure there is no interest to use it on my case, and even, that I use it badly.</p>
<p>From a SpreadSheet, I take all the lines and values, to format a visual render of what the lines should do on import with another software. The final goal is to use this to generate a pre-formatted menu card (for restoration). I started from a pre-formatted list of products that the sales gives us, to detect the product, and which categories, prices etc.., then I format lines to respond the needed format of the software.</p>
<p>The part of my script that need to be reviewed, is when I display the result the card would have if imported on the software, then create some options to modify it graphically.</p>
<p>This part is working, but modal's generation is very long. Besides, each time I switch in a different category, I have to generate again the modal (the solution is probably more JavaScript in my HTML ? ).</p>
<p>My code is divided in some files:</p>
<ul>
<li><p>One for JS functions to format cards given by sales (auto-generation)</p></li>
<li><p>One for JS functions to graphically modify the card (part I'm asking code review)</p></li>
<li><p>One for generals JS functions (such as <code>include()</code> that permit to links different gscript files together, or spreadsheet's menu generation to use the script)</p></li>
<li><p>One for HTML main part ( that display a table with 49 buttons, and is regenerated when changing a category).</p></li>
<li><p>some others HTML different parts (at the moment there is only the form to edit/create a new category/product graphically ^^, I have no other needs at the moment)</p></li>
</ul>
<p>Here is part of the code for the graphical part. The functions that are up-to-date are: <code>generateManual</code>, <code>openCategory</code>, and <code>ordinateProductTabs</code>.
To do so, I have a menu on which I can launch the generation of the modal:</p>
<pre><code>function generateManual(){
var cache=CacheService.getDocumentCache();
//Default value for this variable, which will change once another
categorie is called
cache.put("inProductTypeTab",(-1));
var ui = SpreadsheetApp.getUi();
var output=HtmlService.createTemplateFromFile('ZatyooCard');
var product=JSON.parse(cache.get("product"));
output.product=product;
SpreadsheetApp.getUi().showModalDialog(output.evaluate().setWidth(620).setHeight(550), 'Carte Zatyoo - Visuel');
}
</code></pre>
<p>The product's cache variable (I'm pretty sure is a bad use of cache, was to answer one of my first idea, when I change the category I'm on when I display the render) is generated on Spreadsheet Opening, and when a modification is done, by calling a function named <code>regenProductCache</code>. Here is the <code>regenProductCache</code> function:</p>
<pre><code>function regenProductCache(){
var cache=CacheService.getDocumentCache();
//dataFromResult is just a sheet.getValues(), no interest to cache it. To be rewritten
var dataFromResult = JSON.parse(cache.get("datasheet"));
var product=new Array();
var tabEncountered=new Array();
for(var i=0;i<dataFromResult.length;i++){
//Stupid to do this like this, but kept it because it works
/* it is the reason why inProductTypeTab is set up at -1 as default value, to take into account the particular first case*/
if(dataFromResult[i][7]=="PREMIER"){
if(product[0] == null){
product[0] = new Array();
}
product[0].push(JSON.parse(JSON.stringify(dataFromResult[i])));
}
else{
if(tabEncountered.indexOf(dataFromResult[i][7])==-1){
tabEncountered.push(dataFromResult[i][7]);
product[tabEncountered.length] = new Array();
product[tabEncountered.length].push(dataFromResult[i])
}
else{
product[tabEncountered.indexOf(dataFromResult[i][7])+1].push(dataFromResult[i]);
}
}
}
//ordinateProductTabs is called In order to create an array formated to build my table.
//Indeed, each screens has 49 buttons, Each buttons can call a new screen
//So once i listed all products, and on which category these products are,
//I create an array that has 49 values ( that are potentially other array of 49 values, etc..)
//I store the category's array order in the cache variable "tabEncountered"
//which contains tab's name, in order to do an indexOf() and determines
//what part of the Big array i should check for data while clicking on a given button
product=ordinateProductTabs(product);
if(cache.get("product")!=null||cache.get("tabEncountered")!=null){
cache.remove("product");
cache.remove("tabEncountered");
cache.put("tabEncountered",JSON.stringify(tabEncountered));
cache.put("product",JSON.stringify(product));
}else{
cache.remove("product");
cache.remove("tabEncountered");
cache.put("tabEncountered",JSON.stringify(tabEncountered));
cache.put("product",JSON.stringify(product));
}
</code></pre>
<p>Because it may be part of what takes a long time to be executed, here is the <code>ordinateProductTabs</code>, but I dont really think I can improve that part without rethinking everything.</p>
<pre><code>function ordinateProductTabs(product){
var productOrdinated = new Array();
for(var i=0;i<product.length;i++){
var count=product[i].length;
productOrdinated.push(new Array(count));
while(count<49){
product[i].push(null);
productOrdinated[i].push(null)
count++;
}
for(var j=0;j<product[i].length;j++){
if(product[i][j]!=null){
var place = fullTable.indexOf(Number(product[i][j][8]));
productOrdinated[i][place]=product[i][j];
}
}
}
return productOrdinated;
}
</code></pre>
<p>Positions of buttons are determined by an integer in 9th column of the sheet. I created an array, <code>fullTable</code>, as global variable, to represent how is treated the position of buttons in the real software, that is also how I determine colors of buttons and text, by other static global arrays.</p>
<p>Here again, poor way to use cache.</p>
<p>Finally here is the HTML file I use as main graphical file:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<?!= include('mainCSS'); ?>
<? var cache=CacheService.getDocumentCache();?>
<base target="_top">
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
<table>
<!-- Si on est sur la liste des types de produit-->
<!-- Génère les boutons de productType (nb ligne = nb_bouton_par_ligne / nb_bouton_sur_une_ligne) -->
<? for(var i=0;i<(product[Number(cache.get("inProductTypeTab"))+1].length/5);i++ ){?>
<tr>
<!-- Chaque boucle, 1Boutons, jusqu'à 5boutons pour la ligne -->
<? for(var j=0;j<5;j++){ ?>
<!-- Si le bouton à créer est un bouton "produit"-->
<? if(product[Number(cache.get("inProductTypeTab"))+1][i*5 + j]!=null){?>
<td>
<? Logger.log(product[Number(cache.get("inProductTypeTab"))+1][i*5 + j][13])?>
<button ondblclick="google.script.run.openCategory(<?=product[Number(cache.get("inProductTypeTab"))+1][i*5 + j][13]?>)"
<?/* En fonction des valeurs du produit, changer le css du bouton */?>
<? switch(product[Number(cache.get("inProductTypeTab"))+1][i*5 + j][10]){
case 'N':var textc="tblack"; break;
case 'W':var textc="twhite"; break;
case 'R':var textc="tred"; break;
case 'V':var textc="tgreen"; break;
case 'J':var textc="tyellow"; break;
case 'B':var textc="tblue"; break;
}?>
<? switch(product[Number(cache.get("inProductTypeTab"))+1][i*5 + j][9]){
case 'R':?>class="red <?=textc?>" <? break;
case 'V':?>class="lightgreen <?=textc?>" <? break;
case 'B':?>class="blue <?=textc?>" <? break;
case 'J':?>class="yellow <?=textc?>"<? break;
case 'N':?>class="black <?=textc?>"<? break;
case 'W':?>class="white <?=textc?>"<? break;
case 'M':?>class="brown <?=textc?>"<? break;
case 'P':?>class="pink <?=textc?>"<? break;
case 'T':?>class="skyblue <?=textc?>"<? break;
case 'K':?>class="beige <?=textc?>"<? break;
case 'H':?>class="darkgreen <?=textc?>"<? break;
}?>
><?= product[Number(cache.get("inProductTypeTab"))+1][i*5 + j][3] ?>
</button>
<div class="dropdown-content">
<input type="button" class="mButton cButton" value="Modifier Catégorie" onclick="google.script.run.editCategory(<?=product[Number(cache.get("inProductTypeTab"))+1][i*5 + j]?>)"/>
<input type="button" class="mButton cButton" value="Supprimer Catégorie" onclick="google.script.run.deleteCategory(<?=product[Number(cache.get("inProductTypeTab"))+1][i*5 + j]?>)"/>
</div>
</td>
<!-- Sinon on crée un bouton vide -->
<?}else{?>
<td>
<button onclick="test()">
</button>
<div class="dropdown-content">
<input type="button" class="mButton cButton" value="Créer Nouvelle Catégorie" onclick="google.script.run.createCategory()"/>
</div>
</td>
<?}?>
<?}?>
</tr>
<?}?>
</table>
<? if(Number(cache.get("inProductTypeTab"))==-1){?>
<input type="button" class="mButton" value="Sauvegarder Carte" onclick="google.script.run.saveCard()" />
<input type="button" class="mButton" value="Fermer Carte" onclick="google.script.host.close()" />
<?} else {?>
<input type="button" class="mButton" value="Retour" onclick="google.script.run.openCategory()" />
<?}?>
<script>
$('tr td button').click( function(){
$(this).parent().find('.dropdown-content').slideToggle(100);
});
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
<? Logger.log("bijour")?>
</body>
</html>
</code></pre>
<p>Let me know if you need a screenshot of the final rendering, or whatever could be needed</p>
<p>I have a lot of functions that may be used on this modal, that may be bugged, but that's not the goal of the question.</p>
<p>In the modal, there will be button to click on, to access a category, which is displayed on the same html file ( because it's an imbricated menu that I try to create). </p>
<p>I think I have a lot of JavaScript code i should use to upgrade switch between categories, once the modal appears. But I also think my way to generate my modal at first is not correct, maybe I shouldn't even use a modal for this ?</p>
<p>Thanks for taking time to read and advise me on this. Be sure to ask anything that may be needed for a better understanding of my issue, or my code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T12:59:57.360",
"Id": "393457",
"Score": "0",
"body": "“_because it’s an imbricated menu that I try to create_” I am not familiar with that word “_imbricated_” what should that be or what does it mean?"
},
{
"ContentLicense":... | [
{
"body": "<h3>Redundant Code at the end of <code>regenProductCache()</code></h3>\n\n<p>The following code appears at the end of that function:</p>\n\n<blockquote>\n<pre><code>if(cache.get(\"product\")!=null||cache.get(\"tabEncountered\")!=null){\n cache.remove(\"product\");\n cache.remove(\"tabEncountere... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T08:42:04.307",
"Id": "203975",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"google-apps-script",
"google-sheets"
],
"Title": "Modal displayed in Google Spreadsheet from Gscript"
} | 203975 |
<p>Lets say my folder structure looks like this</p>
<pre><code>someproject/v5/.htaccess
someproject/5.0.1/lib.js
someproject/5.0.1/assets/img/png/anotherfolder/helloworld.png
someproject/5.0.2/lib.js
someproject/5.0.2/assets/img/png/anotherfolder/helloworld.png
</code></pre>
<p>When user enters url's like (and lets say I am the owner of google.com): </p>
<pre><code>www.google.com/someproject/v5/lib.js
www.google.com/someproject/v5/assets/img/png/anotherfolder/helloworld.png
</code></pre>
<p>I want him to be redirected to version i want using the .htaccess file, example if i want to serve version 5.0.1, then the user will be redirected to this:</p>
<pre><code>www.google.com/someproject/5.0.1/lib.js
www.google.com/someproject/5.0.1/assets/img/png/anotherfolder/helloworld.png
</code></pre>
<p>Only one thing may change the version number, this does not work (.htaccess file content):</p>
<pre><code>AddType application/javascript .js
AddType text/css .css
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)/(.*) "https://google.com/release/theme/5.0.1/$1/$2" [R=302,L]
</code></pre>
<p>How can I make it only change v5 with my version number (syntax) ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T10:45:07.237",
"Id": "393291",
"Score": "0",
"body": "To clarify: your current solution does not work? Please take a look at the [help/on-topic]."
}
] | [
{
"body": "<p>The line you are using is telling the engine, redirect everything to the following URI. The reason for this is that you are using the pattern matching wildcard (.*). </p>\n\n<p>The parenthesis is used for creating groups, the dot is telling the engine that every character is accepted and the star ... | {
"AcceptedAnswerId": "203986",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T10:00:56.987",
"Id": "203980",
"Score": "0",
"Tags": [
".htaccess"
],
"Title": "Direct to another folder with .htaccess file"
} | 203980 |
<p>I am preparing for technical interview and I found this question on <a href="https://www.geeksforgeeks.org/longest-palindromic-substring-set-2/" rel="nofollow noreferrer">geeksforgeeks</a>, but I did not understand their solution. So, I have written my own solution. I want to optimize this code.</p>
<pre><code>#include <iostream>
#include <string>
bool isPalindrome(std::string& str)
{
for (int i = 0, j = str.length()-1; i<j; ++i, --j)
{
if (str[i] != str[j])
{
return false;
}
}
return true;
}
int longestPalindrome(std::string& str, std::string& palindromeStr)
{
int max = 0, start = 0, end = 0;
for (int i = 0; i < str.length(); ++i)
{
for (int j = i+1; j < str.length(); ++j)
{
std::string sub = str.substr(i, j);
if (isPalindrome(sub) && max < sub.length())
{
max = sub.length();
start = i;
end = j;
}
}
}
palindromeStr = str.substr(start, end);
return max;
}
int main()
{
std::string str = "forgeekskeegfor";
std::string palindromeStr;
std::cout << longestPalindrome(str, palindromeStr) << '\n';
std::cout << palindromeStr << '\n';
}
</code></pre>
| [] | [
{
"body": "<p>I suppose that a little optimization could be done by changing the way the substrings are extracted from the main string: the iterations should start from the original string itself and then continue by subtracting characters.</p>\n\n<p>In this way the first time <code>isPalindrome()</code> return... | {
"AcceptedAnswerId": "203988",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T10:39:08.617",
"Id": "203983",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"strings",
"interview-questions",
"palindrome"
],
"Title": "Find longest Palindrome substring"
} | 203983 |
<p>There is a global exception handler in our WebAPI application that looks like the following:</p>
<pre><code>public class ApiExceptionHandler : IExceptionHandler
{
public async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(ResourceNotFoundException))
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.NotFound, context.Exception.Message));
}
else if (exceptionType == typeof(UserNotFoundException))
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.Unauthorized, context.Exception.Message));
}
else if (exceptionType == typeof(UserAlreadyExistsExeption))
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.Conflict, context.Exception.Message));
}
...
else
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.InternalServerError, "An unexpected error occured"));
}
}
}
</code></pre>
<p>And each exception has the following form:</p>
<pre><code>public class UserAlreadyExistsExeption: Exception
{
public UserAlreadyExistsExeption()
{
}
public UserAlreadyExistsExeption(string message) : base(message)
{
}
public UserAlreadyExistsExeption(string message, Exception inner) : base(message, inner)
{
}
}
</code></pre>
<p>And can be thrown in the code like the following:</p>
<pre><code>//If user exists
throw new UserAlreadyExistsExeption("User already exists");
</code></pre>
<p>I was thinking of making all our custom exceptions implement a <code>IHasHttpErrorCode</code> so each one has its own <code>HttpErrorCode</code> - usage like the following:</p>
<p>Interface: </p>
<pre><code>public interface IHasHttpErrorCode
{
HttpStatusCode GetHttpStatusCode();
}
</code></pre>
<p>Exception:</p>
<pre><code>public class UserAlreadyExistsExeption: Exception, IHasHttpErrorCode
{
public UserAlreadyExistsExeption()
{
}
public UserAlreadyExistsExeption(string message) : base(message)
{
}
public UserAlreadyExistsExeption(string message, Exception inner) : base(message, inner)
{
}
public HttpStatusCode GetHttpStatusCode() {
return HttpStatusCode.Conflict;
}
}
</code></pre>
<p>Global Error Handler:</p>
<pre><code>public class ApiExceptionHandler : IExceptionHandler
{
public async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
var exceptionType = context.Exception as IHasHttpErrorCode;
if (customException != null) {
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(customException.GetHttpStatusCode(), context.Exception.Message));
}
else
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.InternalServerError, "An unexpected error occured"));
}
}
}
</code></pre>
<p>Is this a valid approach to improve the existing code? Is there anything else I should look to improve?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T16:09:08.303",
"Id": "393328",
"Score": "0",
"body": "I would personally go even further and make common abstract base to force you to implement the status code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2... | [
{
"body": "<p>Using the interface is definitely an improvement, but what I lack in your code is <strong>common base exception</strong>, something like <code>ServerException</code> that could be used to distinguish other exceptions (e.g. <code>IndexOutOfRangeException</code> or whatever) from <em>your</em> excep... | {
"AcceptedAnswerId": "203999",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T10:56:01.213",
"Id": "203985",
"Score": "2",
"Tags": [
"c#",
".net",
"error-handling",
"asp.net-web-api"
],
"Title": "WebAPI global exception handler"
} | 203985 |
<p>Here's an <a href="https://www.fluentcpp.com/2018/09/14/how-to-remove-elements-from-a-sequence-container/" rel="noreferrer">interesting article</a> called "How to Remove Elements from a Sequence Container in C++". At some point, the author also explains how to remove duplicates from a container, but only with the very restrictive condition that those duplicates are adjacent. I've given a bit of thoughts on how to make a generic algorithm that would work on any duplicate in the container, and it's a bit more complicated that one might think at first.</p>
<p>The naively obvious solution is:</p>
<pre><code>template <typename Iterator>
Iterator remove_duplicates(Iterator first, Iterator last) {
auto it = std::next(first);
while (first != last) {
it = std::find(it, last, *first);
if (it == last) it = std::next(++first);
else std::rotate(it, std::next(it), last--);
}
return last;
}
</code></pre>
<p>and it looks a lot like an implementation of a STL's algorithm, but it also is a polynomial-time algorithm, which is only acceptable if there is no alternative. But you generally keep track of already encountered values in a separate container in order to attain linear or almost-linear time. Sets are good candidates but they come in two flavors, and the <code>std::unordered_set</code> being more efficient than the simple <code>std::set</code> must be used when possible.</p>
<p>I've used concepts (gcc > 6.3 && <code>-fconcepts</code>) to dispatch to the most efficient overload:</p>
<pre><code>template <typename T>
concept bool Hashable = requires {
std::hash<T>();
};
template <typename T>
concept bool Comparable = requires (T a, T b) {
{ a == b } -> bool;
};
template <typename T>
concept bool Orderable = requires (T a, T b) {
{ a < b } -> bool;
};
</code></pre>
<p><code>unordered_set</code>s require the key to be hashable and comparable, and <code>set</code>s that it be orderable. After code factorization it gives:</p>
<pre><code>template <typename Iterator, typename Set>
Iterator remove_duplicates_impl(Iterator first, Iterator last, Set& known_values) {
while (first != last) {
if (known_values.find(*first) != known_values.end()) std::rotate(first, std::next(first), last--);
else known_values.insert(*first++);
}
return last;
}
template <typename Iterator>
Iterator remove_duplicates(Iterator first, Iterator last)
requires Orderable<Value_type<Iterator>> && !Hashable<Value_type<Iterator>>
{
std::set<Value_type<Iterator>> known_values;
return remove_duplicates_impl(first, last, known_values);
}
template <typename Iterator>
Iterator remove_duplicates(Iterator first, Iterator last)
requires Hashable<Value_type<Iterator>> && Comparable<Value_type<Iterator>>
{
std::unordered_set<Value_type<Iterator>> known_values;
return remove_duplicates_impl(first, last, known_values);
}
</code></pre>
<p>So what's missing here, be it optimizations or corner-cases handling?</p>
<p><strong>A minimal working example</strong>:</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_set>
#include <set>
#include <iterator>
#include <type_traits>
template <typename Iterator>
using Value_type = typename std::iterator_traits<Iterator>::value_type;
template <typename T>
concept bool Hashable = requires {
std::hash<T>();
};
template <typename T>
concept bool Comparable = requires (T a, T b) {
{ a == b } -> bool;
};
template <typename T>
concept bool Orderable = requires (T a, T b) {
{ a < b } -> bool;
};
template <typename Iterator>
Iterator remove_duplicates(Iterator first, Iterator last) {
auto it = std::next(first);
while (first != last) {
it = std::find(it, last, *first);
if (it == last) it = std::next(++first);
else std::rotate(it, std::next(it), last--);
}
return last;
}
template <typename Iterator, typename Set>
Iterator remove_duplicates_impl(Iterator first, Iterator last, Set& known_values) {
while (first != last) {
if (known_values.find(*first) != known_values.end()) std::rotate(first, std::next(first), last--);
else known_values.insert(*first++);
}
return last;
}
template <typename Iterator>
Iterator remove_duplicates(Iterator first, Iterator last)
requires Orderable<Value_type<Iterator>> && !Hashable<Value_type<Iterator>>
{
std::set<Value_type<Iterator>> known_values;
return remove_duplicates_impl(first, last, known_values);
}
template <typename Iterator>
Iterator remove_duplicates(Iterator first, Iterator last)
requires Hashable<Value_type<Iterator>>
{
std::unordered_set<Value_type<Iterator>> known_values;
return remove_duplicates_impl(first, last, known_values);
}
struct Foo {};
bool operator==(Foo, Foo) { return true; }
int main() {
std::vector<int> data{ 1,2,3,4,5,6,7,8,9,8,7,6,5,2,4,3,1,8 };
std::vector<int> unik(data.begin(), remove_duplicates(data.begin(), data.end()));
for (auto i : unik) std::cout << i << ' ';
std::cout << std::endl;
std::vector<std::pair<int, int>> test{ {1,2}, {3,4} , {5,6} , {7,8}, {7, 8} };
[[maybe_unused]]
auto it = remove_duplicates(test.begin(), test.end());
std::vector<Foo> test2{ Foo(), Foo(), Foo() };
[[maybe_unused]]
auto it2 = remove_duplicates(test2.begin(), test2.end());
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T15:43:59.887",
"Id": "393326",
"Score": "0",
"body": "You don't say what kind of performance measurement you've done - is there a clear improvement over the naive algorithm that requires no extra storage? I suspect that if duplicat... | [
{
"body": "<p>Your naive solution is quadratic time, O(n^2) and O(1) additional memory. Note, polynomial time doesn't say much about the actual time complexity other than it's not exponential or factorial.</p>\n\n<p>Your improved version is O(nlogn) time for the implementation with <code>set</code> and O(n) for... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T14:12:40.597",
"Id": "203991",
"Score": "7",
"Tags": [
"c++",
"c++20"
],
"Title": "Generic way to remove all duplicates from a not-sorted container"
} | 203991 |
<p>I have programmed Conway's Game of Life in C++.</p>
<pre><code>/*
Any live cell with fewer than two live neighbors dies, as if by under population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by overpopulation.
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
*/
#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <string>
#include <stdlib.h>
#define EXTRA_SPACE 1
#define GRID_SIZE 35
#define ALIVE_CELL '#'
#define DEAD_CELL ' '
struct CellCoords { int y, x; };
void setup_grid();
void generation();
void display_grid();
void sleep(int);
std::array<std::array<char, GRID_SIZE + EXTRA_SPACE * 2>, GRID_SIZE + EXTRA_SPACE * 2> grid;
int main() {
setup_grid();
int gen = 1;
do {
system("cls");
std::cout << std::endl << "Generation " << gen << std::endl;
display_grid();
sleep(100);
generation();
gen++;
} while (true);
std::cin.get();
return 0;
}
void setup_grid() {
std::ifstream file("grid.txt");
std::string line;
int i = EXTRA_SPACE;
while (std::getline(file, line)) {
for (int j = EXTRA_SPACE; j < GRID_SIZE; j++) {
if (line[j] == '1')
grid[i][j] = ALIVE_CELL;
else
grid[i][j] = DEAD_CELL;
}
i++;
}
file.close();
}
void generation() {
std::vector<CellCoords> cells_to_kill;
std::vector<CellCoords> cells_to_be_born;
int neighbors;
for (int y = EXTRA_SPACE; y < GRID_SIZE; y++) {
for (int x = EXTRA_SPACE; x < GRID_SIZE; x++) {
neighbors = 0;
if (grid[y - 1][x ] == ALIVE_CELL) neighbors++;
if (grid[y - 1][x + 1] == ALIVE_CELL) neighbors++;
if (grid[y ][x + 1] == ALIVE_CELL) neighbors++;
if (grid[y + 1][x + 1] == ALIVE_CELL) neighbors++;
if (grid[y + 1][x ] == ALIVE_CELL) neighbors++;
if (grid[y + 1][x - 1] == ALIVE_CELL) neighbors++;
if (grid[y ][x - 1] == ALIVE_CELL) neighbors++;
if (grid[y - 1][x - 1] == ALIVE_CELL) neighbors++;
if (grid[y][x] == ALIVE_CELL) {
if (neighbors < 2 || neighbors > 3)
cells_to_kill.push_back({ y, x });
} else if (neighbors == 3) {
cells_to_be_born.push_back({ y, x });
}
}
}
for (int i = 0; i < cells_to_kill.size(); i++) {
CellCoords cell = cells_to_kill[i];
grid[cell.y][cell.x] = DEAD_CELL;
}
for (int i = 0; i < cells_to_be_born.size(); i++) {
CellCoords cell = cells_to_be_born[i];
grid[cell.y][cell.x] = ALIVE_CELL;
}
}
void display_grid() {
std::cout << std::endl;
for (int y = EXTRA_SPACE; y < GRID_SIZE; y++) {
for (int x = EXTRA_SPACE; x < GRID_SIZE; x++) {
std::cout << grid[y][x] << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void sleep(int time) {
for (int i = 0; i < time; i++);
}
</code></pre>
<p>How can I improve the code? Was making an extra 2 rows and columns in the grid array a good idea?</p>
| [] | [
{
"body": "<p>Overall, this is pretty good. You've avoided the most common mistakes I see, like bad naming, using magic numbers, passing bare values that really belong together in a data structure. Nice job! I appreciate the comment at the top that explains the rules, too.</p>\n<p>To answer your question, I thi... | {
"AcceptedAnswerId": "204115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T18:01:33.950",
"Id": "204002",
"Score": "1",
"Tags": [
"c++",
"console",
"windows",
"game-of-life"
],
"Title": "Conway's Game of Life command line program in C++"
} | 204002 |
<p>Could someone please review my code for performance(any other suggestions are welcome) which converts flat data list coming from database to a tree?</p>
<p><strong>Interface for db entity class</strong></p>
<pre><code>public interface IDbEntityNode
{
int Id { get; set; }
int ParentId { get; set; }
string Data { get; set; }
}
</code></pre>
<p><strong>Example of db Entity class</strong></p>
<pre><code>public class ExceptionCategory :IDbEntityNode
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Data { get; set; }
public ExceptionCategory(string data, int id, int parentId)
{
Id = id;
ParentId = parentId;
Data = data;
}
}
</code></pre>
<p><strong>Generic class which holds the structure of tree node</strong></p>
<pre><code>public class GenericNode<T>
{
public T NodeInformation { get; set; }
public GenericNode<T> Parent { get; set; }
public List<GenericNode<T>> Children { get; set; } = new List<GenericNode<T>>();
}
</code></pre>
<p><strong>Method which coverts flat list to tree</strong></p>
<pre><code>public static List<GenericNode<T>> CreateGenericTree<T>(List<T> flatDataObject,Func<T,bool> IsRootNode) where T : IDbEntityNode
{
var lookup = new Dictionary<int, GenericNode<T>>();
var rootNodes = new List<GenericNode<T>>();
var noOfElements = flatDataObject.Count;
for (int element = 0; element < noOfElements; element++)
{
GenericNode<T> currentNode;
if (lookup.TryGetValue(flatDataObject[element].Id, out currentNode))
{
currentNode.NodeInformation = flatDataObject[element];
}
else
{
currentNode = new GenericNode<T>() { NodeInformation = flatDataObject[element] };
lookup.Add(flatDataObject[element].Id, currentNode);
}
if (IsRootNode(flatDataObject[element]))
{
rootNodes.Add(currentNode);
}
else
{
GenericNode<T> parentNode;
if (!lookup.TryGetValue(flatDataObject[element].ParentId, out parentNode))
{
parentNode = new GenericNode<T>();
lookup.Add(flatDataObject[element].ParentId, parentNode);
}
parentNode.Children.Add(currentNode);
currentNode.Parent = parentNode;
}
}
return rootNodes;
}
</code></pre>
<p><strong>Execution:</strong></p>
<pre><code>private static void Main(string[] args)
{
List<IDbEntityNode> flatDataStructure = new List<IDbEntityNode>
{
new ExceptionCategory("System Exception",1,0),
new ExceptionCategory("Index out of range",2,1),
new ExceptionCategory("Null Reference",3,1),
new ExceptionCategory("Invalid Cast",4,1),
new ExceptionCategory("OOM",5,1),
new ExceptionCategory("Argument Exception",6,1),
new ExceptionCategory("Argument Out Of Range",7,6),
new ExceptionCategory("Argument Null",8,6),
new ExceptionCategory("External Exception",9,1),
new ExceptionCategory("Com",10,9),
new ExceptionCategory("SEH",11,9),
new ExceptionCategory("Arithmatic Exception",12,1),
new ExceptionCategory("DivideBy0",13,12),
new ExceptionCategory("Overflow",14,12),
};
var tree = CreateGenericTree(flatDataStructure, IsRootNode);
}
</code></pre>
<p><strong>Root node has ParentId set to 0</strong></p>
<pre><code>private static bool IsRootNode(IDbEntityNode dbEntity)
{
bool isRootNode = false;
if (dbEntity.ParentId == 0 )
isRootNode = true;
return isRootNode;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T18:40:36.923",
"Id": "393348",
"Score": "0",
"body": "You're saying that you're _Trying to implement generic tree data structure_ - does that mean it doesn't work yet? Could you clarify this please?"
},
{
"ContentLicense": "... | [
{
"body": "<p>All in all it looks pretty good.</p>\n\n<p>I have the following remarks:</p>\n\n<p>The name <code>GenericNode<T></code> is somewhat redundant or \"Pleonastic\". I would simply call it <code>Node<T></code> because the type argument indicates the genericness. </p>\n\n<hr>\n\n<p><code>Gen... | {
"AcceptedAnswerId": "204018",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T18:33:19.290",
"Id": "204004",
"Score": "5",
"Tags": [
"c#",
"tree",
"database"
],
"Title": "Generic tree data structure for flat data from a database"
} | 204004 |
<p>My external drive that I use for Backup had some broken files. I feared that I'd lose some (or all) the data in there. So I wanted to copy each and every file to my hard disk.</p>
<p>I first tried using regular Windows methods (Copy, Xcopy). But, these methods took a lot of time and the commands would stop execution after hitting a broken file.</p>
<p>For example:</p>
<pre><code>xcopy E:\sampleSourceDirectory\*.* D:\BACKUP\sampleSourceDirectory\ /s /e
</code></pre>
<p><strong>Solution Method:</strong></p>
<ol>
<li>An iterative script to try to <strong>move</strong> each file in the <code>sampleSourceDirectory</code></li>
<li>Report how many files have failed</li>
</ol>
<p><strong>Note:</strong> I preferred MOVING files, instead of COPYING, so that I could retry moving the folder again, hoping that the external drive can read the files upon another trial.</p>
<p><strong>Python script:</strong></p>
<pre><code>import shutil
import os
folderName = 'sampleSourceDirectory'
source = 'E:/' + folderName + '/'
destination = 'D:/BACKUP/' + folderName + '/'
if (os.path.exists(destination) == False):
os.makedirs(destination) #Make that Directory
files = os.listdir(source)
filesSource = files
nSuccess = 0 # number of Files
nFail = 0
while len(files)>0:
for f in files:
try:
shutil.move(source + f, destination + f)
nSuccess = nSuccess + 1
except OSError as err:
print("OS error: {0}".format(err))
files.remove(f)
nFail = nFail + 1
filesDestination = os.listdir(destination)
if (filesSource == filesDestination) and (len(filesSource) != 0):
print("Move Successful")
else:
print("ERROR IN MOVE!!! ****** CHECK WARNINGS!!! \n")
print ( nFail, ' files failed!')
</code></pre>
<p>With this question, I'd like to first answer the basic question: is this an effective way to try saving files?</p>
<p>Secondly, I'd like to receive general feedback on the script itself, and any particular points that I might have misthought/misimplemented.</p>
<p>Final note: this script is not intended to be a secure way and I'd strongly advise not to use it for serious data. (I don't know if it's by chance or not but after a few trials my external drive stopped working completely, and I could only save 10% of the contents.)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T18:58:12.927",
"Id": "393353",
"Score": "1",
"body": "My recommendation, if your filesystem might be broken: [make a byte-for-byte clone](https://superuser.com/q/839502/31983) of the filesystem before you do making any modifications... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T18:36:48.723",
"Id": "204005",
"Score": "2",
"Tags": [
"python",
"file-system",
"windows"
],
"Title": "Attempt to save (recover) files from a broken external drive"
} | 204005 |
<p>I am developing an application that must generate a random password for each new user in the system (initial password).</p>
<p>My idea is to use passwords of 16 characters long.</p>
<p>Would like to know if the code below is a secure way to generate passwords and if it can be improved. The system will be used by hundreds of thousands of users and security is a priority.</p>
<pre><code>import java.security.SecureRandom;
import java.util.Random;
public class SecureRandomPasswordGenerator {
private static final Random RANDOM = new SecureRandom();
private static final String POSSIBLE_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-+=!@#$%&*()[]{}<>:.,?";
public String generatePassword(int length) {
StringBuilder password = new StringBuilder(length);
for (int i = 0; i < length; i++) {
password.append(POSSIBLE_CHARACTERS.charAt(RANDOM.nextInt(POSSIBLE_CHARACTERS.length())));
}
return password.toString();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T09:39:24.380",
"Id": "393425",
"Score": "2",
"body": "A function `generatePassword(int length, int minDigits, int minSpecial)` would be more secure. Maybe, your random only generates letters...."
},
{
"ContentLicense": "CC B... | [
{
"body": "<p>Top hit on Google looks very similar; in any case <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/RandomStringUtils.html\" rel=\"noreferrer\">no need to reinvent this</a>.</p>\n\n<p>But really, if this is the initial password, the users are goi... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T20:55:23.990",
"Id": "204014",
"Score": "1",
"Tags": [
"java",
"security",
"random"
],
"Title": "Secure random password generator"
} | 204014 |
<h1>Problem Statement</h1>
<p>I am trying to find the intersection over union (IoU) metric for one to several rotated rectangles compared to many different rotated rectangles. Here are some images to help visualize this metric:</p>
<p><img src="https://i.stack.imgur.com/nQerQ.png" width="300">
<img src="https://i.stack.imgur.com/stTc5m.jpg" width="300"></p>
<p>The second metric is quite close to the scenario I'm trying to calculate, the white area divided by the combined black and white area.</p>
<h1>Example</h1>
<p>For each small box on the left we need to determine the IoU metric for each red box on the right. The output in this case will be an array of size (5, 756) since there are 5 boxes on the left with 756 IoU metrics for each box on the right.</p>
<p><img src="https://i.stack.imgur.com/aDeQ8.png" width="300">
<img src="https://i.stack.imgur.com/b214z.png" width="300"></p>
<h1>My solution</h1>
<p>To solve this problem, I fill in each "anchor" box (from the above right picture) individually and store that in an array. This is a binary array.</p>
<p><a href="https://i.stack.imgur.com/ELmEk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ELmEk.png" alt="filled in anchor box"></a></p>
<p>I then take these filled in anchor boxs (now separated so each box is in their own image as above) and find the IoU metric by simple multiplication and summation. This approach will calculate the IoU metric regardless of the shape of the objects passed in. However, it is <em>extremely</em> inefficient both in memory and computationally. I am using the pytorch library to load the arrays onto my GPU to parallelize the computations.</p>
<h1>Code</h1>
<p>This code runs in <a href="/questions/tagged/python-3.x" class="post-tag" title="show questions tagged 'python-3.x'" rel="tag">python-3.x</a>.</p>
<pre><code>import numpy as np
import torch
import cv2
from timeit import Timer
def jaccard(box_a, box_b):
denorm_bbox = torch.cat([box_a[:, :4]*768, box_a[:, 4].unsqueeze(1)*90], dim=1)
b_boxes = list(map(lambda x:np.ceil(cv2.boxPoints(((x[1], x[0]), (x[2], x[3]), x[4]))), denorm_bbox.numpy()))
b_imgs = torch.from_numpy(np.array([cv2.fillConvexPoly(np.zeros((768,768), dtype=np.uint8), np.int0(b), 1) for b in b_boxes]).astype(float)).float()
intersection = torch.FloatTensor()
summation = torch.FloatTensor()
for b_img in b_imgs:
intersection = torch.cat([intersection, (b_img*box_b).sum((1,2)).unsqueeze(0)])
summation = torch.cat([summation, (b_img+box_b).sum((1,2)).unsqueeze(0)])
return intersection / (summation - intersection + 1.0)
def main():
anc_grids = [3,6,12]
anc_zooms = [0.7]
anc_ratios = [(1.,1)]
anc_angles = np.array(range(-90, 90, 45))/90
anchor_scales = [(anz*i,anz*j) for anz in anc_zooms for (i,j) in anc_ratios]
k = len(anchor_scales) * len(anc_angles) # number of anchor boxes per anchor point
anc_offsets = [1/(o*2) for o in anc_grids]
anc_x = np.concatenate([np.repeat(np.linspace(ao, 1-ao, ag), ag) for ao,ag in zip(anc_offsets,anc_grids)])
anc_y = np.concatenate([np.tile(np.linspace(ao, 1-ao, ag), ag) for ao,ag in zip(anc_offsets,anc_grids)])
anc_ctrs = np.repeat(np.stack([anc_x,anc_y], axis=1), k, axis=0)
anc_sizes = np.tile(np.concatenate([np.array([[o/ag,p/ag] for i in range(ag*ag) for o,p in anchor_scales])
for ag in anc_grids]), (len(anc_angles),1))
grid_sizes = torch.from_numpy(np.concatenate([np.array([ 1/ag for i in range(ag*ag) for o,p in anchor_scales])
for ag in anc_grids for aa in anc_angles])).unsqueeze(1)
anc_rots = np.tile(np.repeat(anc_angles, len(anchor_scales)), sum(i*i for i in anc_grids))[:,np.newaxis]
anchors = torch.from_numpy(np.concatenate([anc_ctrs, anc_sizes, anc_rots], axis=1)).float()
denorm_anchors = torch.cat([anchors[:, :4]*768, anchors[:, 4].unsqueeze(1)*90], dim=1)
np_anchors = denorm_anchors.numpy()
iou_anchors = list(map(lambda x:np.ceil(cv2.boxPoints(((x[1], x[0]), (x[2], x[3]), x[4]))), np_anchors))
anchor_imgs = torch.from_numpy(np.array([cv2.fillConvexPoly(np.zeros((768,768), dtype=np.uint8), np.int0(a), 1) for a in iou_anchors]).astype(float)).float()
test_tensor = torch.Tensor([[ 0.0807, 0.2844, 0.0174, 0.0117, -0.8440],
[ 0.3276, 0.0358, 0.0169, 0.0212, -0.1257],
[ 0.3040, 0.2904, 0.0101, 0.0157, -0.5000],
[ 0.0065, 0.2109, 0.0130, 0.0078, -1.0000],
[ 0.1895, 0.1556, 0.0143, 0.0091, -1.0000]])
t = Timer(lambda: jaccard(test_tensor, anchor_imgs))
print(f'Consuming {(len(anchors) * np.dtype(float).itemsize * 768 * 768)/1000000000} Gb on {"GPU" if anchors.is_cuda else "RAM"}')
print(f'Averaging {t.timeit(number=100)/100} seconds per function call')
print(jaccard(test_tensor, anchor_imgs))
if __name__ == '__main__':
main()
</code></pre>
<h3>Sample Run:</h3>
<blockquote>
<pre><code>Consuming 3.567255552 Gb on RAM
Averaging 3.107201199789997 seconds per function call
tensor([[0.0020, 0.0000, 0.0020, ..., 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],
[0.0026, 0.0026, 0.0026, ..., 0.0000, 0.0000, 0.0000]])
</code></pre>
</blockquote>
<p>The results of this run were on a i7-8700K for reference.</p>
<hr>
<h1>What I would like reviewed:</h1>
<ul>
<li><p><strong>Memory Consumption</strong>: Right now I am consuming a lot of memory for all the anchor boxes I compare each box to. What are some ways I can dramatically reduce this without giving up the accuracy of my results?</p></li>
<li><p><strong>Speed</strong>: I need this to run <em>fast</em>!</p></li>
</ul>
| [] | [
{
"body": "<p>There are two main reasons why your program is slow and using huge amounts of memory:</p>\n\n<ol>\n<li><p>You are using a 768×768 pixel image for each overlap calculation</p></li>\n<li><p>You are checking each anchor box against each red box, but most of the time there is no overlap at all.</p></l... | {
"AcceptedAnswerId": "204243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T22:07:54.997",
"Id": "204017",
"Score": "18",
"Tags": [
"python",
"performance",
"computational-geometry",
"memory-optimization",
"pytorch"
],
"Title": "Intersection over Union for rotated rectangles"
} | 204017 |
<p>Without changing the outputs or the inputs of the method, how would you make this code more readable ?</p>
<p>I am interested in any general improvement it can be made in terms of readability without WORSEN the time complexity.</p>
<p>Above all I'm interested of know if there is a way of doing all this steps in one line:</p>
<ul>
<li><p>check if the key exist in the map.</p></li>
<li><p>if exist create a list with two elements (pair) and then append the
pair to list of pairs that will be the result.</p></li>
<li><p>if not exist do nothing.</p></li>
</ul>
<p>Also is there a more elegant way to return <code>array[][]</code> from an <code>ArrayList<ArrayList<Integer>></code> ?</p>
<pre><code>static int[][] findPairsWithGivenDifference(int[] arr, int k) {
int n = arr.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < n; i++){
map.put(arr[i]-k,arr[i]);
}
for (int i = 0; i < n; i++){
int x = arr[i];
if (map.get(arr[i]) != null) {
int y = map.get(x);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(y);
al.add(x);
all.add(al);
}
}
int m = all.size();
int[][] res = new int[m][2];
for (int i = 0; i < m; i++) {
for (int j = 0; j < 2; j++) {
res[i][j] = all.get(i).get(j);
}
}
return res;
}
</code></pre>
| [] | [
{
"body": "<p>You don’t need to specify types on the right hand side of a generic declaration as of Java 7.</p>\n\n<p>It’s preferable to declare types as interfaces (<code>List</code>) rather than implementations (<code>ArrayList</code>) where possible.</p>\n\n<p><code>al</code> and <code>all</code> are meaning... | {
"AcceptedAnswerId": "204023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-19T23:37:02.747",
"Id": "204021",
"Score": "5",
"Tags": [
"java",
"k-sum"
],
"Title": "Finding pairs of numbers with a given difference"
} | 204021 |
<p>This code takes a list and a integer and duplicates every element in the list the specified number of times.</p>
<pre><code>(define (super-duper source count)
(define (next-super source left)
(if (zero? left)
(super-duper (cdr source) count)
(cons (super-duper (car source) count) (next-super source (- left 1)))))
(if (pair? source)
(cons (super-duper (car source) count) (next-super source (- count 1)))
source))
(display(super-duper '((x y) t) 3))
</code></pre>
| [] | [
{
"body": "<p>I think you need to decide weather to repeat only on the first level of the list, or if you want to do a tree walk for lists inside lists. As is, this code produces a weird combination of both in an exponential explosion of the list, The following sample returns over 2 million leaf elements for an... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T00:09:45.253",
"Id": "204022",
"Score": "1",
"Tags": [
"recursion",
"scheme"
],
"Title": "Scheme function to duplicate every element of a list a specified number of times"
} | 204022 |
<p>I have a list of CSV files (all have the same fields), some of which are empty. My goal is to find the first nonempty file and use that as the "base" file for an aggregation. After finding the base file, the way I will consume the rest of the files changes, so I need to maintain the index of the file. Here is what I currently have:</p>
<pre><code>def f(list_of_files):
aggregated_file = ""
nonempty_index = -1
for index, file in enumerate(list_of_files):
aggregated_file = extract_header_and_body(file)
if aggregated_file:
nonempty_index = index
break
if nonempty_index != -1:
rest_of_files = list_of_files[nonempty_index:]
for file in rest_of_files:
aggregated_file += extract_body(file)
return aggregated_file
</code></pre>
<p>Both <code>extract_header_and_body</code> and <code>extract_body</code> return string representations (with and without column names, respectively) of the CSV files -- if the file is empty, the empty string is returned. This seems like a clunky solution, especially for Python. Is there a more concise/readable way to accomplish this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T04:36:29.707",
"Id": "393379",
"Score": "2",
"body": "Can you be specific about exactly what is considered to be the output? This function doesn't return anything. (In addition, I suggest that you include the code for `extract_heade... | [
{
"body": "<p>If we reformulate this as trying to extract the header + body of the first non-empty file and the body of all subsequent files this comes to mind:</p>\n\n<pre><code>aggregated_file = ''\nfor file in list_of_files:\n if aggregated_file:\n aggregated_file += extract_body(file)\n else:\n... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T04:08:18.647",
"Id": "204028",
"Score": "0",
"Tags": [
"python",
"file",
"iteration"
],
"Title": "Process CSV files that follow the first nonempty one"
} | 204028 |
<p>A coding challenge that rotates an image 90 degrees counterclockwise. The image is represented as an array matrix. I believe the time complexity is O(n<sup>2</sup>), but I'd like to know for sure, as well as any other feedback.</p>
<pre><code>def rotate_image(img):
rotated_image = [[] for x in range(len(img))]
for i in range(len(img)):
for j in range(len(img[i])):
rotated_image[len(img) - j - 1].append(img[i][j])
return rotated_image
</code></pre>
<p>Example usage:</p>
<pre><code>image = [
[1, 1, 5, 9, 9],
[2, 2, 6, 0, 0],
[3, 3, 7, 1, 1],
[4, 4, 8, 2, 2],
[5, 5, 9, 3, 3]
]
rotated_img = rotate_image(image)
for i in rotated_img:
print(i)
</code></pre>
<p>Outputs:</p>
<pre><code>[9, 0, 1, 2, 3]
[9, 0, 1, 2, 3]
[5, 6, 7, 8, 9]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T05:48:44.677",
"Id": "393387",
"Score": "4",
"body": "`O(N^2)` wrt. `N` being the number of pixels or side of the squre?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T05:49:12.753",
"Id": "39338... | [
{
"body": "<p>How about using Python built-ins to do the job?</p>\n\n<pre><code>img = [[1, 2, 3], [10, 20, 30], [100, 200, 300]]\nlist(reversed(list(zip(*img))))\n[(3, 30, 300), (2, 20, 200), (1, 10, 100)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDa... | {
"AcceptedAnswerId": "204055",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T05:26:47.373",
"Id": "204032",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"image",
"matrix"
],
"Title": "Python 3 function to rotate an image 90°"
} | 204032 |
<blockquote>
<p>You are given a number. You are given the opportunity to swap only once to produce the largest number.</p>
</blockquote>
<hr>
<p>My approach was to use buckets whose values were their indexes and their locations were their values. </p>
<p>I walked the array checking if the largest value was greater than the current value. </p>
<p>If the current value was smaller I would decrement the largest value. Checking if it existed and that, that bucket was in a location greater than the current location in the iteration. </p>
<p>At which point I would know the bucket's location and that it contained the largest value outside a successive set and the nearest lowest value it would replace, to produce the largest number. </p>
<p>Analysis:</p>
<ul>
<li>Creating Buckets: O(n) time and O(n) space</li>
<li>Walking Values Space and Time: O(1) + finding the lowest high and swapping: O(1)</li>
<li>Total: O(n)</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const maximumSwap = function(array) {
array = array.toString().split('');
const buckets = []
for (let location = 0; location < array.length; location++) {
buckets[array[location]] = location
}
let largest = buckets.length - 1
for (let current_location = 0; current_location < array.length; current_location++) {
let current_val = array[current_location]
for (; largest > current_val; largest--) {
if (buckets[largest] > current_location) {
array[current_location] = [array[buckets[largest]], array[buckets[largest]] = array[current_location]][0]
return +array.join('')
}
}
}
return +array.join('')
};
console.log(maximumSwap(99739))
console.log(maximumSwap(9273))
console.log(maximumSwap(9732))</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T11:38:15.817",
"Id": "393446",
"Score": "0",
"body": "Hmm, I have a `count++` in the inner loop and `count` returns 21 with number \"995846869\". Not 89."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-2... | [
{
"body": "<h2>Style critique</h2>\n\n<p>Either terminate your statements consistently with semicolons, or not at all.</p>\n\n<p>If you're going to use <code>const</code> to define the function, then I suggest using the arrow notation as well, instead of the <code>function</code> keyword.</p>\n\n<p>The variable... | {
"AcceptedAnswerId": "204039",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T05:52:09.250",
"Id": "204033",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"complexity"
],
"Title": "Form the largest number by swapping one pair of digits"
} | 204033 |
<p>In a Outlook VSTO Addin I needed to loop through a large pst file (e.g 30GB containing 50k+ mails). Following code block loop the pst file folder by folder recursively. It takes huge time (1hour+) to complete the loop especially when looping such large pst file for the first time. </p>
<p>The purpose of this code is to get the PR_SEARCH_KEY and the FolderPath of each email (folder wise) and store them in text file which will be used in future, such as in a periodic full loop we can compare the old and new PR_SEARCH_KEY to find out the new emails etc</p>
<p><strong>How can I get a faster performance in this.</strong></p>
<pre><code>Const PropName As String = "http://schemas.microsoft.com/mapi/proptag/0x300B0102"
Dim SourceFolder = Outlook.NameSpace.Folders("Outlook_Backup")
Dim PstName = "Outlook"
Dim MailCount = FunctionToGetTotalMailCount(SourceFolder)
Dim PrSearchKeyDictionary As New List(Of String)
ScanPST(SourceFolder,PstName,MailCount)
Public Sub ScanPST(f As Outlook.Folder, PstName As String, MailCount As Long)
'-========================================================================
'- f = RootFolder/PST with Tag (e.g Outlook_Backup), PstName (e.g Outlook)
'-========================================================================
If f.Items.Count > 0 Then
For i = f.Items.Count To 1 Step -1
LoopCount += 1
Try
Dim Mail As Object = f.Items(i)
Dim PropertyAccessor As Outlook.PropertyAccessor = Mail.PropertyAccessor
Dim PrSearchKey As String = PropertyAccessor.BinaryToString(PropertyAccessor.GetProperty(PropName))
'/Full folder path splited into array and removed the rootfolder name with tag (e.g Outlook_Backup -> _Backup is the tag)
Dim FolderPath() As String = f.FolderPath.TrimStart("\"c).Split("\").Skip(1).ToArray
'/Array joined back to get MailFolderPath without tag
Dim MailFolderPath As String = String.Join("\", FolderPath)
PrSearchKeyDictionary.Add(PrSearchKey & "," & PstName & "\" & MailFolderPath)
Marshal.ReleaseComObject(PropertyAccessor)
Catch ex As Exception
LogInput("[Error: " & ex.ToString & "]"
Continue For
End Try
BGWorkerStatus = "[" & PstName & "] " & "Scanning... " & Math.Round((LoopCount / MailCount) * 100, 2, MidpointRounding.AwayFromZero) & "%"
BackGroundWorker.ReportProgress(0, BGWorkerStatus)
Next
End If
If f.Folders.Count > 0 Then
For c = 1 To f.Folders.Count
OL.Folder = f.Folders.Item(c)
ScanPST(OL.Folder, PstName, MailCount)
Next
End If
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T10:56:41.890",
"Id": "393436",
"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 y... | [
{
"body": "<p>After looking at your code I see some stuff which could speed this up if coded different.</p>\n<pre><code>'/Full folder path splited into array and removed the rootfolder name with tag (e.g Outlook_Backup -> _Backup is the tag)\nDim FolderPath() As String = f.FolderPath.TrimStart("\\"... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T06:58:02.947",
"Id": "204036",
"Score": "1",
"Tags": [
"vb.net",
"outlook"
],
"Title": "Outlook VSTO: Fastening email loop on a large pst file"
} | 204036 |
<p>I have a small website I'm working on as a hobby and I created a login page/home page so far. I wanted to get the basic login/logout functionality going before filling out the main part of my site. I have the authentication with the server working, auth guards, and things like that. I wanted to create some functionality for my NavBar so that I could have a single component and not have to have a <code>LoggedInNavBar</code> and <code>LoggedOutNavBar</code> kind of scenario, so I hatched the idea of, "Hey, what if my NavBar was aware of the state of being logged in or not?". Well, this was entirely new territory for me (as most of Angular is, I have a part of a project at work that is built in Angular, and I don't work on it super often so I'm trying to keep my skills sharp in that regard).</p>
<p>So, here is what I came up with. I have a <code>AuthService</code> class which provides the capability of logging in and out. I figured this service would provide a nice entry point to be able to subscribe to an observable which would notify me of authentication state changes.</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { JwtHelper } from 'angular2-jwt';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private static readonly apiUrl: string = "https://localhost:44398/api/auth/"
private static readonly loginUrl: string = AuthService.apiUrl + "login";
private $state: Subject<boolean>;
constructor(private http: HttpClient, private jwtHelper: JwtHelper) {
this.$state = new Subject<boolean>();
}
login(userLogin: UserLogin, onData: Function = null, onError: Function = null, onComplete: Function = null) {
this.http.post(AuthService.loginUrl, userLogin, {
headers: new HttpHeaders({
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
})}).subscribe(
response => {
onData(response);
this.$state.next(true);
},
error => {
onError(error)
this.$state.next(false);
},
() => onComplete()
)
}
logOut() {
localStorage.removeItem("jwt");
this.$state.next(false);
}
getStateObservable(): Observable<boolean> {
return this.$state.asObservable();
}
}
</code></pre>
<p>My login page uses the <code>login</code> method from <code>AuthService</code>. The reason I didn't just return the observable was because I was thinking I needed to be able to inject my <code>Subject</code> calls in after my own <code>onData</code> (next), <code>onError</code>, and <code>onComplete</code> methods. It seems to work well enough, but I'm not certain if this is hacky or not.</p>
<p>Here is the <code>.ts</code> for my NavBar:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit {
$loggedInState: Observable<boolean>;
constructor(private router: Router, private authService: AuthService) {
}
ngOnInit() {
this.$loggedInState = this.authService.getStateObservable();
}
onLogOutClick() {
this.authService.logOut();
this.router.navigate(["login"]);
}
}
</code></pre>
<p>Nothing fancy here except I call into <code>getStateObservable</code> to be able to subscribe to the logged in state. The HTML for NavBar is really simple right now, just a title and a "Log Out" or "Log In" button. I haven't finished fleshing things out here so don't mind the fact that both buttons use the same function call.</p>
<pre class="lang-html prettyprint-override"><code><mat-toolbar color="primary">
<span>Auction House Price Tracker</span>
<span class="fill-remaining-space"></span>
<div *ngIf="$loggedInState | async;then logged_in else not_logged_in"></div>
<ng-template #logged_in><h1>LOGGED IN</h1><a mat-button (click)="onLogOutClick()">Log Out</a></ng-template>
<ng-template #not_logged_in><h1>LOGGED OUT</h1><a mat-button (click)="onLogOutClick()">Log In</a></ng-template>
</mat-toolbar>
</code></pre>
<p>I'd appreciate some tips here on if I'm doing something grossly wrong, if there is inefficiencies, memory leaks, or whatever (I assume the NavBar's subscription is the duration of the session, is there a need to ever unsubscribe something like that?).</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T06:58:22.357",
"Id": "204037",
"Score": "1",
"Tags": [
"authentication",
"typescript",
"session",
"angular-2+",
"rxjs"
],
"Title": "Angular2 \"Logged In State Watcher\""
} | 204037 |
<p>This is a simple function that copies the content of one stream to another. My question is simple. I am currently, copying between the streams one byte at a time, but the streams are both Buffered. What are some ways to optimize it for speed? Any other advice would be appreciated as well.</p>
<pre><code>private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOException {
int byt;
while ((byt = inputStream.read()) != -1) {
fileStream.write(byt);
}
}
return true;
}
</code></pre>
| [] | [
{
"body": "<p>Instead of reading the buffered stream byte-by-byte <code>inputStream.read()</code> you might use the advantage of buffering. This will speed up the large content copy.</p>\n\n<pre><code>private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOExcepti... | {
"AcceptedAnswerId": "205417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T07:39:27.017",
"Id": "204038",
"Score": "0",
"Tags": [
"java",
"performance",
"stream"
],
"Title": "Copying contents between BufferedStreams in Java"
} | 204038 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.