body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>There is a remote Windows PC that has access to "landline" unmetered WiFi and there is a Verizon 4G LTE MiFi (metered WiFi) as backup. This script checks to see if the PC is connected to any WiFi, connected to metered WiFi, or has any internet connection. It will be called a few times a day by Task Scheduler. Everything seems to work OK while testing at home.</p> <pre><code>@echo off SETLOCAL enabledelayedexpansion rem get computer name set host=%COMPUTERNAME% set wifi= if "%host%"=="HOME" ( set landline=xxx set metered=Verizon-4GLTE-xxx-xxxx ) if "%host%"=="WORK" ( set landline="xxx spaces in name xxx" set metered=Verizon-4GLTE-xxx-xxxx ) echo. echo ************************************************** echo %host% echo landline wifi = !landline! echo metered wifi = !metered! echo ************************************************** echo. echo. echo ping test and if no response, connect to !metered! ... echo ************************************************************************************* ping 8.8.8.8 -n 1 || netsh wlan connect name=!metered! echo ************************************************************************************* timeout /t 10 echo. echo Attempting to connect to landline wifi %landline% ... netsh wlan connect name=%landline% timeout /t 10 echo. echo. echo Fail safe... echo ping test and if no response, connect to !metered! ... echo ************************************************************************************* ping 8.8.8.8 -n 1 || netsh wlan connect name=!metered! echo ************************************************************************************* </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T21:13:49.497", "Id": "475953", "Score": "1", "body": "You can check if you are connected to wifi by using `WMIC NICConfig where IPEnabled=\"True\" get DefaultIPGateway | findstr \"{\"` and then checking the error level since without `/value` switch `WMIC NICConfig where IPEnabled=\"True\" get DefaultIPGateway` wihtout wifi just prints `default gateway` and nothing else. Pinging is good too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T21:15:04.733", "Id": "475954", "Score": "0", "body": "Do you change your computer name depending if you are at work or at home?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T15:57:37.187", "Id": "476163", "Score": "0", "body": "@NekoMusume Thanks, I'll look at that command.\n\nI run the same script on different computers from a shared Google Drive folder, so any updates to the script propagate immediately." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-31T20:12:30.020", "Id": "210664", "Score": "2", "Tags": [ "networking", "batch", "status-monitoring" ], "Title": "Batch file that checks for wifi connection - reconnects if no internet" }
210664
<p>I am creating a machine learning tool set from scratch in python. I have never done something of this kind and I don't usually use python but I thought it would be good to expand my horizons. I am really looking for aspects of the code that would really hinder performance and things to consider since this will be used for a neural network implementation.</p> <pre><code>class vector: def __init__(self, size): self.elems = [0] * size self.size = size def __repr__(self): return repr(self.elems) def __mul__(self, other): if(self.size != other.size): raise ArithmeticError("vectors of two different lengths") a = 0 for i in range(self.size): a += self.elems[i] * other.elems[i] return a def set(self, array): for i in range(self.size): self.elems[i] = array[i] self.mag = sum([i**2 for i in self.elems])**.5 def normalize(self): a = vector(self.size) a.set([i/self.mag for i in self.elems]) return(a) class matrix: def __init__(self, r, c): self.coloums = [vector(c) for i in range(r)] self.r = r self.c = c def __repr__(self): return repr(self.coloums) def __mul__(self, other): if(type(other) != vector): raise TypeError("matrices can only be multiplied by vectors") if(self.c != other.size): raise ArithmeticError("rows and lengths do not match") a = vector(self.r) a.set([(other*self.coloums[i]) for i in range(self.r)]) return a def set(self, multiarray): for i in range(self.c): self.coloums[i].set(multiarray[i]) </code></pre> <p>I am aware this has no way of multiply by a scalar but I have no need for that just yet and it would be pretty trivial to implement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T05:58:28.513", "Id": "407273", "Score": "2", "body": "Is this something you are doing for learning? If not, just use numpy or one of pythons many machine learning frameworks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T06:31:45.347", "Id": "407275", "Score": "0", "body": "I think he's trying to make his own framework." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T06:38:56.657", "Id": "407277", "Score": "0", "body": "Yes the purpose is to do it on my own @Oscar I could use a library but that defeats the purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T08:17:30.317", "Id": "407279", "Score": "1", "body": "(Welcome to Code Review!) (Stick to standards such as [The Python Style Guide](https://www.python.org/dev/peps/pep-0008/#comments) and [Embedded Documentation Conventions](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring).)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T03:45:04.457", "Id": "210673", "Score": "1", "Tags": [ "python", "performance", "reinventing-the-wheel", "machine-learning", "neural-network" ], "Title": "Custom Vector and Matrix classes in python for machine learning" }
210673
<p>I wrote a small emulator for fun. Full code @ bottom of post, available on <a href="https://github.com/ianklatzco/lc3/blob/master/lc3.py" rel="nofollow noreferrer">GitHub here</a>.</p> <p>Design choices:</p> <ul> <li>modeling 16 bit little endian memory — opted for <code>ctypes</code> and array-like access via <code>__getitem__</code></li> <li><p><code>Enum</code> library</p> <ul> <li>Opcodes - convenient to access: the order of the opcodes in the enum matches the opcode's numeric value when interpreted as an integer</li> <li>Condition flags - convenient to access: named, so I can <code>self.registers.cond = condition_flags.z </code> where the right hand side is the enum.</li> </ul></li> <li><p>Some classes: </p> <ul> <li>CPU (<code>class lc3</code>) <ul> <li>Registers</li> <li>Memory </li> </ul></li> </ul></li> </ul> <hr> <p>Questions:</p> <ul> <li>How could I get started adding unit tests?</li> <li>Is there a better choice than using an <code>IntEnum</code> for the opcodes?</li> <li>How might I organize the code better? In particular, I dislike having <code>dump_state</code> (a diagnostic printing function), and all of my instruction implementations (eg <code>op_and_impl</code>) right next to each other in the <code>lc3</code> class.</li> <li>How else might I organize this mapping of opcodes to implementation functions?</li> </ul> <pre><code># first attempt if opcode == opcodes.op_add: self.op_add_impl(instruction) elif opcode == opcodes.op_and: self.op_and_impl(instruction) elif opcode == opcodes.op_not: self.op_not_impl(instruction) ... truncated https://github.com/ianklatzco/lc3/blob/7bace0a30353d4b1d4c720eddca07c1828f7c3e0/lc3.py#L303 # second attempt opcode_dict = { opcodes.op_add: self.op_add_impl, opcodes.op_and: self.op_and_impl, opcodes.op_not: self.op_not_impl, ... truncated https://github.com/ianklatzco/lc3/blob/67353ebb50367430a7d2921d701ea92aa2f0968e/lc3.py#L304 try: opcode_dict[opcode](instruction) except KeyError: raise UnimpError("invalid opcode") </code></pre> <ul> <li>How could I address this inconsistency between accessing GPRs (general purpose registers) and PC, <code>cond</code>ition register?</li> </ul> <pre><code>class registers(): def __init__(self): self.gprs = (c_int16 * 8)() self.pc = (c_uint16)() self.cond = (c_uint16)() # I instantiated the gprs as a ctypes "array" instead of a single c_uint16. # To access: # registers.gprs[0] # This is convenient when I need to access a particular register, and I have the index handy from a decoded instruction. # registers.pc.value # The .value is annoying. </code></pre> <hr> <h3>Full code</h3> <pre><code># usage: python3 lc3.py ./second.obj # This project inspired by https://justinmeiners.github.io/lc3-vm/ # There was a lot of copy-pasting lines of code for things like # pulling pcoffset9 out of an instruction. # https://justinmeiners.github.io/lc3-vm/#1:14 # ^ talks about a nice compact way to encode instructions using bitfields and # c++'s templates. # i am curious if you could do it with python decorators. # update: i tried this and it was mostly just an excuse to learn decorators, but it # isn't the right tool. i am curious how else you might do it. from ctypes import c_uint16, c_int16 from enum import IntEnum from struct import unpack from sys import exit, stdin, stdout, argv from signal import signal, SIGINT import lc3disas # in same dir DEBUG = False class UnimpError(Exception): pass def signal_handler(signal, frame): print("\nbye!") exit() signal(SIGINT, signal_handler) # https://stackoverflow.com/a/32031543/1234621 # you're modeling sign-extend behavior in python, since python has infinite # bit width. def sext(value, bits): sign_bit = 1 &lt;&lt; (bits - 1) return (value &amp; (sign_bit - 1)) - (value &amp; sign_bit) ''' iirc the arch is 16bit little endian. options: ctypes or just emulate it in pure python. chose: ctypes ''' class memory(): def __init__(self): # ctypes has an array type. this is one way to create instances of it. self.memory = (c_uint16 * 65536)() def __getitem__(self, arg): if (arg &gt; 65535) or (arg &lt; 0): raise MemoryError("Accessed out valid memory range.") return self.memory[arg] def __setitem__(self, location, thing_to_write): if (location &gt; 65536) or (location &lt; 0): raise MemoryError("Accessed out valid memory range.") self.memory[int(location)] = thing_to_write class registers(): def __init__(self): self.gprs = (c_int16 * 8)() self.pc = (c_uint16)() self.cond = (c_uint16)() # not actually a class but an enum. class opcodes(IntEnum): op_br = 0 op_add = 1 op_ld = 2 op_st = 3 op_jsr = 4 op_and = 5 op_ldr = 6 op_str = 7 op_rti = 8 op_not = 9 op_ldi = 10 op_sti = 11 op_jmp = 12 op_res = 13 op_lea = 14 op_trap = 15 class condition_flags(IntEnum): p = 0 z = 1 n = 2 class lc3(): def __init__(self, filename): self.memory = memory() self.registers = registers() self.registers.pc.value = 0x3000 # default program starting location self.read_program_from_file(filename) def read_program_from_file(self,filename): with open(filename, 'rb') as f: _ = f.read(2) # skip the first two byte which specify where code should be mapped c = f.read() # todo support arbitrary load locations for count in range(0,len(c), 2): self.memory[0x3000+count/2] = unpack( '&gt;H', c[count:count+2] )[0] def update_flags(self, reg): if self.registers.gprs[reg] == 0: self.registers.cond = condition_flags.z if self.registers.gprs[reg] &lt; 0: self.registers.cond = condition_flags.n if self.registers.gprs[reg] &gt; 0: self.registers.cond = condition_flags.p def dump_state(self): print("\npc: {:04x}".format(self.registers.pc.value)) print("r0: {:05} ".format(self.registers.gprs[0]), end='') print("r1: {:05} ".format(self.registers.gprs[1]), end='') print("r2: {:05} ".format(self.registers.gprs[2]), end='') print("r3: {:05} ".format(self.registers.gprs[3]), end='') print("r4: {:05} ".format(self.registers.gprs[4]), end='') print("r5: {:05} ".format(self.registers.gprs[5]), end='') print("r6: {:05} ".format(self.registers.gprs[6]), end='') print("r7: {:05} ".format(self.registers.gprs[7])) print("r0: {:04x} ".format(c_uint16(self.registers.gprs[0]).value), end='') print("r1: {:04x} ".format(c_uint16(self.registers.gprs[1]).value), end='') print("r2: {:04x} ".format(c_uint16(self.registers.gprs[2]).value), end='') print("r3: {:04x} ".format(c_uint16(self.registers.gprs[3]).value), end='') print("r4: {:04x} ".format(c_uint16(self.registers.gprs[4]).value), end='') print("r5: {:04x} ".format(c_uint16(self.registers.gprs[5]).value), end='') print("r6: {:04x} ".format(c_uint16(self.registers.gprs[6]).value), end='') print("r7: {:04x} ".format(c_uint16(self.registers.gprs[7]).value)) print("cond: {}".format(condition_flags(self.registers.cond.value).name)) def op_add_impl(self, instruction): sr1 = (instruction &gt;&gt; 6) &amp; 0b111 dr = (instruction &gt;&gt; 9) &amp; 0b111 if ((instruction &gt;&gt; 5) &amp; 0b1) == 0: # reg-reg sr2 = instruction &amp; 0b111 self.registers.gprs[dr] = self.registers.gprs[sr1] + self.registers.gprs[sr2] else: # immediate imm5 = instruction &amp; 0b11111 self.registers.gprs[dr] = self.registers.gprs[sr1] + sext(imm5, 5) self.update_flags(dr) def op_and_impl(self, instruction): sr1 = (instruction &gt;&gt; 6) &amp; 0b111 dr = (instruction &gt;&gt; 9) &amp; 0b111 if ((instruction &gt;&gt; 5) &amp; 0b1) == 0: # reg-reg sr2 = instruction &amp; 0b111 self.registers.gprs[dr] = self.registers.gprs[sr1] &amp; self.registers.gprs[sr2] else: # immediate imm5 = instruction &amp; 0b11111 self.registers.gprs[dr] = self.registers.gprs[sr1] &amp; sext(imm5, 5) self.update_flags(dr) def op_not_impl(self, instruction): sr = (instruction &gt;&gt; 6) &amp; 0b111 dr = (instruction &gt;&gt; 9) &amp; 0b111 self.registers.gprs[dr] = ~ (self.registers.gprs[sr]) self.update_flags(dr) def op_br_impl(self, instruction): n = (instruction &gt;&gt; 11) &amp; 1 z = (instruction &gt;&gt; 10) &amp; 1 p = (instruction &gt;&gt; 9) &amp; 1 pc_offset_9 = instruction &amp; 0x1ff if (n == 1 and self.registers.cond == condition_flags.n) or \ (z == 1 and self.registers.cond == condition_flags.z) or \ (p == 1 and self.registers.cond == condition_flags.p): self.registers.pc.value = self.registers.pc.value + sext(pc_offset_9, 9) # also ret def op_jmp_impl(self, instruction): baser = (instruction &gt;&gt; 6) &amp; 0b111 self.registers.pc.value = self.registers.gprs[baser] def op_jsr_impl(self, instruction): # no jsrr? if 0x0400 &amp; instruction == 1: raise UnimpError("JSRR is not implemented.") pc_offset_11 = instruction &amp; 0x7ff self.registers.gprs[7] = self.registers.pc.value self.registers.pc.value = self.registers.pc.value + sext(pc_offset_11, 11) def op_ld_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 pc_offset_9 = instruction &amp; 0x1ff addr = self.registers.pc.value + sext(pc_offset_9, 9) self.registers.gprs[dr] = self.memory[addr] self.update_flags(dr) def op_ldi_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 pc_offset_9 = instruction &amp; 0x1ff addr = self.registers.pc.value + sext(pc_offset_9, 9) self.registers.gprs[dr] = self.memory[ self.memory[addr] ] self.update_flags(dr) def op_ldr_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 baser = (instruction &gt;&gt; 6) &amp; 0b111 pc_offset_6 = instruction &amp; 0x3f addr = self.registers.gprs[baser] + sext(pc_offset_6, 6) self.registers.gprs[dr] = self.memory[addr] self.update_flags(dr) def op_lea_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 pc_offset_9 = instruction &amp; 0x1ff self.registers.gprs[dr] = self.registers.pc.value + sext(pc_offset_9, 9) self.update_flags(dr) def op_st_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 pc_offset_9 = instruction &amp; 0x1ff addr = self.registers.pc.value + sext(pc_offset_9, 9) self.memory[addr] = self.registers.gprs[dr] def op_sti_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 pc_offset_9 = instruction &amp; 0x1ff addr = self.registers.pc.value + sext(pc_offset_9, 9) self.memory[ self.memory[addr] ] = self.registers.gprs[dr] def op_str_impl(self, instruction): dr = (instruction &gt;&gt; 9) &amp; 0b111 baser = (instruction &gt;&gt; 6) &amp; 0b111 pc_offset_6 = instruction &amp; 0x3f addr = self.registers.gprs[baser] + sext(pc_offset_6, 6) self.memory[addr] = self.registers.gprs[dr] def op_trap_impl(self, instruction): trap_vector = instruction &amp; 0xff if trap_vector == 0x20: # getc c = stdin.buffer.read(1)[0] self.registers.gprs[0] = c return if trap_vector == 0x21: # out stdout.buffer.write( bytes( [(self.registers.gprs[0] &amp; 0xff)] ) ) stdout.buffer.flush() return if trap_vector == 0x22: # puts base_addr = self.registers.gprs[0] index = 0 while (self.memory[base_addr + index]) != 0x00: nextchar = self.memory[base_addr + index] stdout.buffer.write( bytes( [nextchar] ) ) index = index + 1 return if trap_vector == 0x25: self.dump_state() exit() raise ValueError("undefined trap vector {}".format(hex(trap_vector))) def op_res_impl(self, instruction): raise UnimpError("unimplemented opcode") def op_rti_impl(self, instruction): raise UnimpError("unimplemented opcode") def start(self): while True: # fetch instruction instruction = self.memory[self.registers.pc.value] # update PC self.registers.pc.value = self.registers.pc.value + 1 # decode opcode opcode = instruction &gt;&gt; 12 if DEBUG: print("instruction: {}".format(hex(instruction))) print("disassembly: {}".format(lc3disas.single_ins(self.registers.pc.value, instruction))) self.dump_state() input() opcode_dict = \ { opcodes.op_add: self.op_add_impl, opcodes.op_and: self.op_and_impl, opcodes.op_not: self.op_not_impl, opcodes.op_br: self.op_br_impl, opcodes.op_jmp: self.op_jmp_impl, opcodes.op_jsr: self.op_jsr_impl, opcodes.op_ld: self.op_ld_impl, opcodes.op_ldi: self.op_ldi_impl, opcodes.op_ldr: self.op_ldr_impl, opcodes.op_lea: self.op_lea_impl, opcodes.op_st: self.op_st_impl, opcodes.op_sti: self.op_sti_impl, opcodes.op_str: self.op_str_impl, opcodes.op_trap:self.op_trap_impl, opcodes.op_res: self.op_res_impl, opcodes.op_rti: self.op_rti_impl } try: opcode_dict[opcode](instruction) except KeyError: raise UnimpError("invalid opcode") ############################################################################## if len(argv) &lt; 2: print ("usage: python3 lc3.py code.obj") exit(255) l = lc3(argv[1]) l.start() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:19:07.570", "Id": "407460", "Score": "2", "body": "Bug: `if 0x0400 & instruction == 1:` — I don’t see how this could ever be `True`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:14:22.800", "Id": "407472", "Score": "0", "body": "@AJNeufeld alas, I am off-by-one. It's supposed to be 0x0800. Thanks for the catch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:33:26.037", "Id": "407523", "Score": "1", "body": "Then it is also supposed to be `== 0x0800`. In either case, `== 1` is not correct, which was the bug I thought I was bringing to your attention." } ]
[ { "body": "<p>I'm not really good at Python here, but I'm sharing my ideas.</p>\n\n<h3>Code style</h3>\n\n<p>Do you know there's a coding style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>? It provides a set of guidelines for code styling. I'd like to note some of them here:</p>\n\n<ul>\n<li>Use CapWords naming convention for your classes. Always begin your class name with a cap letter, so <code>class opcodes(IntEnum)</code> becomes <code>class OpCodes(IntEnum)</code> etc.</li>\n<li>Put two blank lines between class definitions and module-level function definitions</li>\n<li><p>Indentation: This is a bad indentation:</p>\n\n<pre><code>if (n == 1 and self.registers.cond == condition_flags.n) or \\\n (z == 1 and self.registers.cond == condition_flags.z) or \\\n (p == 1 and self.registers.cond == condition_flags.p):\n self.registers.pc.value = self.registers.pc.value + sext(pc_offset_9, 9)\n</code></pre>\n\n<p>This is the correct way to indent it:</p>\n\n<pre><code>if (n == 1 and self.registers.cond == condition_flags.n) or \\\n (z == 1 and self.registers.cond == condition_flags.z) or \\\n (p == 1 and self.registers.cond == condition_flags.p):\n self.registers.pc.value = self.registers.pc.value + sext(pc_offset_9, 9)\n</code></pre></li>\n</ul>\n\n<p>You can use a tool called <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a> to find out PEP 8 violations in your code. You may not want all of them - for example, I almost always ignore the line length limit, but this is up to you and it's recommended that you follow all the guidelines unless you have a good reason not to.</p>\n\n<h3>Repeated and similar code</h3>\n\n<p>I'm talking about lines like this:</p>\n\n<pre><code> print(\"r0: {:04x} \".format(c_uint16(self.registers.gprs[0]).value), end='')\n print(\"r1: {:04x} \".format(c_uint16(self.registers.gprs[1]).value), end='')\n print(\"r2: {:04x} \".format(c_uint16(self.registers.gprs[2]).value), end='')\n print(\"r3: {:04x} \".format(c_uint16(self.registers.gprs[3]).value), end='')\n print(\"r4: {:04x} \".format(c_uint16(self.registers.gprs[4]).value), end='')\n print(\"r5: {:04x} \".format(c_uint16(self.registers.gprs[5]).value), end='')\n print(\"r6: {:04x} \".format(c_uint16(self.registers.gprs[6]).value), end='')\n print(\"r7: {:04x} \".format(c_uint16(self.registers.gprs[7]).value))\n</code></pre>\n\n<p>This repetition is just unnecessary work. You can replace it with a nice loop:</p>\n\n<pre><code>for i in range(8):\n print(\"r{}: {:04x} \".format(i, c_uint16(self.registers.gprs[i]).value), end='')\nprint()\n</code></pre>\n\n<p>And the same for your other code where this pattern occurs</p>\n\n<h3>Conditional style</h3>\n\n<p>Use <code>elif</code> if your conditions are intended <em>not</em> to overlap:</p>\n\n<pre><code>def update_flags(self, reg):\n if self.registers.gprs[reg] == 0:\n self.registers.cond = condition_flags.z\n elif self.registers.gprs[reg] &lt; 0:\n self.registers.cond = condition_flags.n\n elif self.registers.gprs[reg] &gt; 0:\n self.registers.cond = condition_flags.p\n</code></pre>\n\n<h3>Using exceptions</h3>\n\n<p>I see you use <code>MemoryError</code> in your memory class for access violation. This is better replaced by <code>ValueError</code> or better, <code>IndexError</code>, because the one you're currently using is reserved for (host) memory issues, particularly memory allocation failures.</p>\n\n<p>There's also another built-in exception for unimplemented stuff, <code>NotImplementedError</code>. You should consider replacing your own <code>UnimpError</code> with the built-in one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:35:10.747", "Id": "407391", "Score": "1", "body": "PEP 8 doesn't say to use camelCase for classes: it says to use CapWords ([source](https://www.python.org/dev/peps/pep-0008/#class-names)); they're similar but distinct styles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:56:37.650", "Id": "407466", "Score": "0", "body": "thank you for the feedback! i appreciate it c:" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T09:36:46.317", "Id": "210729", "ParentId": "210676", "Score": "4" } }, { "body": "<h1>OpCodes</h1>\n\n<p>You are initializing your opcode dictionary inside the while loop for fetching instructions. It only needs to be initialized once; move it before the while loop. </p>\n\n<p>Your opcodes are a set of numbers between 0 &amp; 15. You index a dictionary based on these numbers to get the method to call. Why not use an array, instead of a dictionary; it would be faster and take less memory. </p>\n\n<p>Consider building the opcode array (or dictionary) programmatically:</p>\n\n<pre><code>OPCODES = [ 'br', 'add', 'ld', 'st', 'jsr', 'and', 'ldr', 'str',\n 'rti', 'not', 'ldi', 'sti', 'jmp', 'res', 'lea', 'trap' ]\n\nopcodes = [ getattr(self, f\"op_{op}_impl\") for op in OPCODES ]\n</code></pre>\n\n<p>Note: requires Python 3.6 for the <code>f\"strings\"</code>. Use <code>.format()</code> or <code>%</code> with earlier versions.</p>\n\n<p>Note: this eliminates the need for your <code>class opcodes(IntEnum)</code>. </p>\n\n<p>Since the <code>op_XXX_impl</code> functions are not meant to be called externally, they should named starting with an underscore.</p>\n\n<p>Even better: move initialization of the <code>opcodes</code> array into your <code>lc3</code> constructor, and store it in the object. It will help when it comes time to add in tests.</p>\n\n<pre><code>self._opcodes = [ getattr(self, f\"op_{op}_impl\") for op in OPCODES ]\n</code></pre>\n\n<hr>\n\n<h1>Memory</h1>\n\n<p>You could use the <code>array</code> class for your 16-bit memory; you don’t need to create your own <code>memory</code> class:</p>\n\n<pre><code>self.memory = array.array('H', [0]*65536)\n</code></pre>\n\n<p>The <code>'H'</code> is the type code for 16 bit unsigned values.</p>\n\n<p>Similarly, you code create your registers without a <code>registers</code> class. <code>'h'</code> is the type code for 16 bit signed values:</p>\n\n<pre><code>self.gprs = array.array('h', [0]*10)\n</code></pre>\n\n<p>This creates 10 register locations, 8 for the \"general purpose\" registers, and two additional registers: <code>pc</code> and <code>cond</code>, which you could access as <code>self.gprs[8]</code> and <code>self.gprs[9]</code>. We can improve on this, making them more accessible using <code>@property</code>:</p>\n\n<pre><code>@property\ndef pc(self):\n return self.gprs[8]\n\n@pc.setter\ndef pc(self, value):\n self.gprs[8] = value\n\n@property\ndef cond(self):\n return self.gprs[9]\n\n@cond.setter\ndef cond(self, value):\n self.gprs[9] = value\n</code></pre>\n\n<p>Then you can use and set <code>self.pc</code> and <code>self.cond</code> directly.</p>\n\n<hr>\n\n<h1>Instruction Decoding</h1>\n\n<p>You repeat a lot of code for decoding instructions. You should write helper functions to extract the required values. Then you could write like:</p>\n\n<pre><code>def op_add_impl(self, instruction):\n dr, src1, src2 = self.decode_dr_sr2imm(instruction)\n\n self.gprs[dr] = src1 + src2\n self.update_flags(dr)\n\ndef op_not_impl(self, instruction):\n dr, src1, _ = self.decode_dr_sr2imm(instruction)\n\n self.gprs[dr] = ~ src1\n self.update_flags(dr)\n</code></pre>\n\n<p>Since <code>not</code> doesn’t use <code>sr2</code> or an immediate value, the value returned for <code>src2</code> can be ignored by saving it to the <code>_</code> variable. </p>\n\n<hr>\n\n<h1>Debug output</h1>\n\n<p>Instead of printing to <code>sys.stdout</code>, you should learn and use the Python <code>logging</code> module, for adding (and removing) debug output from your program.</p>\n\n<pre><code>import logging\nLOG = logging.getLogger(__name__)\n\nLOG.debug(\"100 in hex is %x\", 100)\n</code></pre>\n\n<p>In the main program, to enable debug output, use:</p>\n\n<pre><code>logging.basicConfig()\nLOG.setLevel(logging.DEBUG)\n</code></pre>\n\n<hr>\n\n<h1>Testability</h1>\n\n<p>The <code>start()</code> method does a lot. Too much, in fact. It loops endlessly, reading instructions from memory, advancing the program counter, and dispatching instructions.</p>\n\n<p>Let's break this down a bit.</p>\n\n<h2>Dispatch</h2>\n\n<p>You want testability. How about executing just one instruction? In fact, you don't need to read the instruction from memory, either.</p>\n\n<pre><code>def _execute_instruction(self, instruction):\n opcode = instruction &gt;&gt; 12\n\n if LOG.isEnabledFor(logging.DEBUG):\n LOG.debug(\"instruction: %04x\", instruction)\n LOG.debug(\"disassembly: %s\", lc3disas.single_ins(self.pc, instruction))\n self.dump_state()\n\n try:\n self._opcode[opcode](instruction)\n except KeyError:\n raise NotImplementedError(\"Invalid opcode\")\n</code></pre>\n\n<p>Now you could write a test for an individual instruction.</p>\n\n<pre><code>def test_add():\n cpu = lc3()\n cpu.gprs[0] = 22\n cpu._execute_instruction(0x0000) # gprs[0] = gprs[0] + gprs[0]\n assert cpu.gprs[0] == 44\n assert cpu.cond == condition_flags.p\n</code></pre>\n\n<h2>Single Step</h2>\n\n<p>With dispatcher, above, we can now easily write a single stepper:</p>\n\n<pre><code>def single_step(self):\n instruction = self.memory[self.pc]\n self.pc += 1\n self._execute_instruction(instruction)\n</code></pre>\n\n<p>And again, you can write tests using single stepping:</p>\n\n<pre><code>def test_single_step_add(self):\n\n cpu = lc3()\n\n # Setup\n cpu.gprs[0] = -22\n cpu.pc = 0x1234\n cpu.memory[self.pc] = 0x0000\n\n cpu.single_step()\n\n assert cpu.gprs[0] == -44\n assert cpu.cond == condition_flags.n\n assert cpu.pc == 0x1235\n</code></pre>\n\n<h2>Running</h2>\n\n<p>Using <code>single_step()</code>, it becomes easy to write the <code>start()</code> method. But lets make it a little better.</p>\n\n<p>Trap #0x25 is a halt instruction, but it also exits the Python interpreter. That is a little too Draconian. If a program ever generates that trap, any test framework will come crashing down as the interpreter exits. Instead, you should use a flag to indicate whether the CPU is running normally, or if it has been halted.</p>\n\n<pre><code>def start(self):\n\n LOG.debug(\"Starting\")\n\n self._running = True\n while self._running:\n self.single_step()\n\n LOG.debug(\"Halted.\")\n</code></pre>\n\n<p>The <code>op_trap_impl()</code> function would set <code>self._running = False</code> when the Trap #0x25 is executed.</p>\n\n<p>You can now write a test program that runs, and halts, and check the state of memory when it has halted.</p>\n\n<h2>Input / Output</h2>\n\n<p>Your LC3 is tied to <code>sys.stdin</code> and <code>sys.stdout</code>. This makes it hard to test; you'd have to intercept the input and output streams when you write your tests. Or, you could have your LC3 cpu have custom <code>in</code> and <code>out</code> streams, which default to <code>sys.stdin</code> and <code>sys.stdout</code>, but can be replaced with <a href=\"https://docs.python.org/3/library/io.html?highlight=textio#io.StringIO\" rel=\"nofollow noreferrer\"><code>StringIO</code></a>, so your test can feed data to the program, and retrieve output for validation. The Trap #0x20, #0x21 and #0x22 would need to read/write to the requested io streams.</p>\n\n<pre><code>class LC3():\n\n def __init__(self, *, input=sys.stdin, output=sys.stdout):\n self._input = input\n self._output = output\n\ndef test_io():\n in = io.StringIO(\"7\\n\") # Input test data\n out = io.StringIO() # Capture output to string buffer\n\n lc3 = LC3(input=in, output=out)\n lc3.read_program_from_file(\"fibonnaci.obj\")\n lc3.start()\n\n assert out.getvalue() == \"13\\n\" # 13 is the 7th Fibonacci number\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:07:00.550", "Id": "407470", "Score": "0", "body": "i learned that names with a leading underscore aren't imported when you `from module import *`. https://shahriar.svbtle.com/underscores-in-python#single-underscore-before-a-name-eg-code-class_1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:58:56.847", "Id": "407525", "Score": "0", "body": "True, but misleading. If you `from module import *` this module, it would import the top level names like `signal_handler`, `memory`, `registers`, `opcodes`, and `lc3`. The entire `lc3` class is imported, not just a subset of the class. Please do mark non-public members with a leading underscore. If you are importing `lc3` into a file of test functions, the test functions will have access to all members of the class whether they start with a leading underscore or not. You shouldn’t access members with leading underscores from outside, but test functions are allowed to cheat a little." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:17:15.337", "Id": "210744", "ParentId": "210676", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T05:26:42.523", "Id": "210676", "Score": "6", "Tags": [ "python", "python-3.x", "lc-3" ], "Title": "Small CPU Emulator (LC3) in Python" }
210676
<p>This is my first code review question in here, so kindly guide me if I need to format the question in a better way.</p> <p><strong>Task Description</strong></p> <blockquote> <p>Aim of the task is to create a set of methods that would allow me to create random values for given primitive types. This would be used later in a method that would reflect on a class/struct and assign random values to each of the members (nested properties are also taken care of in the other method).</p> </blockquote> <p>The code attached set of methods for creating random values. I was wondering if this is the best way to create a random value for each of the primitive type.</p> <p><strong>Code</strong></p> <pre><code>private static bool RandomBoolean() { return Convert.ToBoolean(random.Next(0, 2)); } private static double RandomDouble(Int32 minValue=Int32.MinValue,Int32 maxValue= Int32.MaxValue) { return random.NextDouble() * (double)random.Next(minValue,maxValue); } private static char RandomChar(bool isLowerCase = true) { if (isLowerCase) return (char)random.Next((int)'a', ((int)'z')+1); else return (char)random.Next((int)'A', ((int)'Z')+1); } private static byte RandomByte() { var byteArray = new byte[1]; random.NextBytes(byteArray); return byteArray[0]; } private static sbyte RandomSByte(int minValue=sbyte.MinValue, int maxValue = sbyte.MaxValue) { return (sbyte)random.Next(minValue, maxValue); } private static float RandomFloat() { double mantissa = (random.NextDouble() * 2.0) - 1.0; double exponent = Math.Pow(2.0, random.Next(-126, 128)); return (float)(mantissa * exponent); } private static decimal RandomDecimal() { byte scale = (byte)random.Next(29); bool sign = random.Next(2) == 1; return new decimal(random.NextInt32(), random.NextInt32(), random.NextInt32(), sign, scale); } private static short RandomInt16(int minValue = Int16.MinValue, int maxValue = Int16.MaxValue) { return (short)random.Next(minValue, maxValue); } private static int RandomInt32(int minValue = Int32.MinValue, int maxValue = Int32.MaxValue) { return random.Next(minValue, maxValue); } private static long RandomInt64(long minValue = Int32.MinValue, long maxValue = Int32.MaxValue) { long result = random.Next((Int32)(minValue &gt;&gt; 32), (Int32)(maxValue &gt;&gt; 32)); result = (result &lt;&lt; 32); result = result | (long)random.Next((Int32)minValue, (Int32)maxValue); return result; } private static UInt16 RandomUInt16() { var byteArray = new byte[2]; random.NextBytes(byteArray); return BitConverter.ToUInt16(byteArray, 0); } private static UInt32 RandomUInt32() { var byteArray = new byte[4]; random.NextBytes(byteArray); return BitConverter.ToUInt32(byteArray,0); } private static UInt64 RandomUInt64() { var byteArray = new byte[8]; random.NextBytes(byteArray); return BitConverter.ToUInt64(byteArray, 0); } private static string RandomString(int length = 10) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s =&gt; s[random.Next(s.Length)]).ToArray()); } </code></pre> <p>Each of the methods are private and static by intention. I have a extension method <code>GetRandomValues(this Type source)</code> defined in the same class which has a return type <code>dynamic</code>.</p> <p>The given methods are part of a solution which aims to create/fill collections of any type <code>T</code>. The solution would reflect over the properties in <code>T</code> (nested properties as well), and assign random values to each of them. For example, if the user had a <code>Student</code> class with properties <code>Name</code> and <code>Age</code>, the utility method would create a collection objects, with random values assigned to each property of <code>Student</code> (for each instance in the collection).</p> <p>This becomes useful when testing (for example) a LINQ query on a collection, making it better than manually creating the collection.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T00:42:06.320", "Id": "407345", "Score": "1", "body": "What is the intented use-case for these random values? Fuzz-testing? And why would the return type of `GetRandomValues` need to be `dynamic` (instead of `object`)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T00:49:25.970", "Id": "407346", "Score": "0", "body": "@PieterWitvoet The intended use-case is to create a Collection Generator for any given Type. Say you have a class named XYZ, it should generate a collection of XYZ with random values assigned to members. Regarding dynamic/object => , any particular merits/demerits of either in above scenario ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T02:35:15.487", "Id": "407349", "Score": "1", "body": "And what's the use-case for those random-value collections? - Regarding `dynamic`, it involves late binding, which means more work at run-time and a loss of compile-time error detection, so I wouldn't use it unless I had a good reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:08:07.813", "Id": "407437", "Score": "0", "body": "@PieterWitvoet I have updated the Question with more description. Hope that is useful. I do understand that dynamic involves late binding, but in this scenario, am using reflection to parse through different properties of any given user defined type T and assign values to it.In such a scenario, would it make a difference ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:43:59.147", "Id": "407480", "Score": "2", "body": "Please post the entire class, without removing anything, we need the public method(s) becuase there is no point in reviewing private APIs that aren't used anywhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:45:11.213", "Id": "407557", "Score": "1", "body": "@AnuViswan: are you sure that 'totally' random values are useful, or do the tests require more specific randomized values? Something like `Enumerable.Range(0, 100).Select(i => new Student { Name = $\"NAME {i}\", Age = random.Next(20, 50) }).ToArray();` doesn't take too much effor, but gives you much more control over the actual values, how your solution compare to that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T21:09:09.090", "Id": "407602", "Score": "0", "body": "Do you use attributes to specify how to randomize a property value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T01:21:25.783", "Id": "407610", "Score": "0", "body": "Yes, i do have attributes which allows constrains on values. For example, MaxValue, MinValue" } ]
[ { "body": "<p>One problem with your code would be the distribution of values for some of the functions that might not match the expected distribution (usually linear) or might not even be inside the specified range.</p>\n\n<p>One example would be <code>RandomDouble</code> with arguments 10 and 20. You would multiply a number between 0.0 and 1.0 with a number between 10 and 20. In that case, most of the returned number would be below 10.0 and you would have an higher probability to get a number between 10 and 11 than a number between 19 and 20.</p>\n\n<p>For <code>RandomChar</code> often, you would probably want a mix of uppercase and lowercase with possibly numbers and punctuation (think a password) so as written, the function might often be almost useless.</p>\n\n<p><code>RandowInt64</code> will also not properly respect the specified range. Some values would never be returned and you probably also could have some out of range values. In particular, you cannot simply join two 32 bit numbers like that if the range can include negative values.</p>\n\n<p>Another thing that is strange is that for some types, you assume that you always want the whole range while for other types, you ask the user for the range.</p>\n\n<p>It is also weird that the default range for an <code>Int64</code> is the range of an <code>Int32</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T01:24:21.230", "Id": "407611", "Score": "0", "body": "Thank you for the feedback, I will take note of each point you mentioned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T21:08:02.343", "Id": "210841", "ParentId": "210677", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T05:30:43.253", "Id": "210677", "Score": "-1", "Tags": [ "c#" ], "Title": "Generating Random Values for Primitive Types" }
210677
<p>I wrote this to sort of gauge my understanding of the bare basics of C++.Could you guys give me any pointers? (Ha, get it?). I would happy to hear what you have to say about the code. Also is it neat (aesthetically as well as functionally)?</p> <pre><code>#include &lt;iostream&gt; bool end = false; int w_combinations[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}}; int pos[] = {1,2,3,4,5,6,7,8,9}; void check (int x) { if ( x == 10) { std::cout &lt;&lt; "X|"; } else if (x == 11) { std::cout &lt;&lt; "O|"; } else { std::cout &lt;&lt; x &lt;&lt; "|"; } } void printMatrix() { std::cout &lt;&lt; "|" ; check(pos[0]) ; check(pos[1]) ; check(pos[2]);std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "|" ; check(pos[3]);check(pos[4]) ; check(pos[5]);std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "|" ; check(pos[6]) ; check(pos[7]) ; check(pos[8]); std::cout &lt;&lt; "\n"; } void input(int z , int player) { if (player == 1 &amp;&amp; pos[z-1] != 10 &amp;&amp; pos[z-1] != 11) { pos[z-1] = 10; } else if (player == 2 &amp;&amp; pos[z-1] != 10 &amp;&amp; pos[z-1] != 11){ pos[z-1] = 11; } else { std::cout &lt;&lt; "\nInvalid! Try again: "; int y; std::cin &gt;&gt; y; input(y,player); } } //Winning mechanism: Simply cylce through all combos. bool win() { for (int i = 0 ; i &lt; 8 ; ++i) { if (pos[w_combinations[i][0]] == pos[w_combinations[i][1]] &amp;&amp; pos[w_combinations[i][0]] == pos[w_combinations[i][2]]) { return true; break; } } return false; } int main() { int count = 0; //Cycle through draws while (1) { int z; printMatrix(); std::cout &lt;&lt; "1[X]:"; std::cin &gt;&gt; z; input(z,1); if (win()) {std::cout &lt;&lt; "Player 1 wins!\n";break;} ++count; printMatrix(); if (count == 9) { std::cout &lt;&lt; "Draw!"; break; } std::cout &lt;&lt; "2[O]:"; std::cin &gt;&gt; z; input(z,2); if (win()) {std::cout &lt;&lt; "Player 2 wins!\n";break;} ++count; if (count == 9) { std::cout &lt;&lt; "Draw!"; break; } } std::cout &lt;&lt; "Play again[Yes = 1, No = 0]: "; int permission; std::cin &gt;&gt; permission; if (permission == 1) { std::cout &lt;&lt; "\n\n"; main(); } } </code></pre>
[]
[ { "body": "<p>I cannot check all because I use a phone at the moment, but here are some quick observations I saw skimming thru the code:</p>\n\n<p><strong>Never call main ()</strong></p>\n\n<p>-It is not defined in C++ what happens if you call main from another function. It is undefined behavior. </p>\n\n<p>You could instead put your while (1) loop in a function and call it instead of main.</p>\n\n<p><strong>Use of C++ Features</strong></p>\n\n<p>-Consider using std::array or std::vector instead of using plain C style arrays.</p>\n\n<p><strong>Formating</strong></p>\n\n<p>-Formatting seem to be off in some places. Add a space between functions and don’t put several instructions on one line.</p>\n\n<p>e.g. </p>\n\n<pre><code>if (win()) {std::cout &lt;&lt; \"Player 2 wins!\\n\";break;}\n ++count;\n</code></pre>\n\n<p>Should become:</p>\n\n<pre><code>if (win()) {\n std::cout &lt;&lt; \"Player 2 win\\n\";\n break;\n}\n++count;\n</code></pre>\n\n<p>Also you should avoid having to long lines. Get used to break the code after max 80 lines. It has the advantage that you can view two source codes next to each other.</p>\n\n<p>for example make this:</p>\n\n<pre><code>if (pos[w_combinations[i][0]] == pos[w_combinations[i][1]] &amp;&amp; pos[w_combinations[i][0]] == pos[w_combinations[i][2]]) \n{\n return true;\n break;\n}\n</code></pre>\n\n<p>Into this:</p>\n\n<pre><code>if (pos[w_combinations[i][0]] == pos[w_combinations[i][1]] \n &amp;&amp; pos[w_combinations[i][0]] == pos[w_combinations[i][2]]) \n{\n return true;\n break;\n}\n</code></pre>\n\n<p>or this</p>\n\n<pre><code>void printMatrix() {\nstd::cout &lt;&lt; \"|\" ; check(pos[0]) ; check(pos[1]) ; check(pos[2]);std::cout &lt;&lt; \"\\n\";\nstd::cout &lt;&lt; \"|\" ; check(pos[3]);check(pos[4]) ; check(pos[5]);std::cout &lt;&lt; \"\\n\";\nstd::cout &lt;&lt; \"|\" ; check(pos[6]) ; check(pos[7]) ; \n</code></pre>\n\n<p>It’s very important for code to be easy to read. You may be only write a program once but most of the time you read it while debugging or maintaining it. If the code is good formatted this task becomes a lot easier.</p>\n\n<p><strong>Avoid redundancy</strong></p>\n\n<p>In you’re while loop you use the same instructions except the messages for player 1 and 2.\nMake them a function with parameters for the messages. This way you make sure you handle both players the same.</p>\n\n<p><strong>Avoid global variables</strong></p>\n\n<p>Don’t use global variables they make the code hard to maintain. They can lead to obscure bugs. \nConsider passing them between you’re functions or even better check out OOP and work with a class who stores the state of the Board.</p>\n\n<p><strong>Functions should do one thing</strong></p>\n\n<p>You’re function check () should only return the string not also print it. It should become this:</p>\n\n<pre><code>std::string check (int x)\n{ \n if ( x == 10) {\n return \"X|\";\n }\n else if (x == 11) {\n return \"O|\";\n }\n return std::to_string (X)\n}\n</code></pre>\n\n<p>This function now gets called and the string is directly printed. No need to change anything in the call code.</p>\n\n<p>Also consider using switch instead of a long if else chain if there are many cases.</p>\n\n<p><strong>Calls to std::cout</strong></p>\n\n<p>No need to call std::cout several times. Just do this :</p>\n\n<p><code>std::cout &lt;&lt; '|' + check(pos[0]) + check(pos[1]) + check(pos[2]) + '\\n';</code></p>\n\n<p>Single chars should be quoted ' ' not \" \" to avoid getting a more expensive string use instead of a char.</p>\n\n<p><strong>Handle invalid input</strong></p>\n\n<p>Try to enter something which is not a the expected number. What happens? The program probably loops endless or crashes because you read no int.\nYou should handle this case.\nOne approach would be reading the in put as a std::string and check this string if it is a digit.\nIf it is not prompt an invalid input and let the user enter again.</p>\n\n<p>But wait. you can also break the program if it is an int but not in range. Handle also wrong range. for example when you input 1234 the program will crash currently as well. You could do all this in a function:</p>\n\n<p><code>int get_input();</code></p>\n\n<p>So you can write:</p>\n\n<p><code>int x = get_input();</code></p>\n\n<p><strong>Use descriptive names</strong></p>\n\n<p>Function names like <code>Check</code> or <code>Input</code> are very mysterious to me about what they are doing.</p>\n\n<p>The same goes for variable names like x, y or w_combinations.\nTry to self document youre code by using clear names which describe what the variable or function does.</p>\n\n<p>Ask yourself if you check this code in 1 or 2 months yourself if you still can get what the program does. With good naming’s and a clear structure it becomes a lot easier.</p>\n\n<p><strong>Use C++ Features like Classes</strong></p>\n\n<p>Youre code looks very C like. Make more use of C++ features like classes etc.\nI rewrote the program with classes to demonstrate a more C++ Style as an inspiration (maybe I should also post it for review?). \nDon't get overwhelmed it takes a lot of time and practice to get into C++...</p>\n\n<p><strong>tic_tac_toe.h</strong></p>\n\n<pre><code>#ifndef TIC_TAC_TOE_020120180815\n#define TIC_TAC_TOE_020120180815\n\n#include &lt;array&gt;\n#include &lt;string&gt;\n\nnamespace tic_tac_toe\n{\n class TicTacToe final{ \n public:\n TicTacToe() = default;\n ~TicTacToe() = default;\n\n // delete copy and move mechanism, we don't want to \n // copy a running game\n TicTacToe(const TicTacToe&amp;) = delete;\n TicTacToe(TicTacToe&amp;&amp; other) = delete;\n TicTacToe&amp; operator=(const TicTacToe&amp; other) = delete;\n TicTacToe&amp; operator=(TicTacToe&amp;&amp; other) = delete;\n\n void print_state_of_board() const;\n bool draw(int field);\n bool board_full() const;\n bool player1_win() const\n {\n return check_win_condition(FieldState::player1);\n }\n\n bool player2_win() const\n {\n return check_win_condition(FieldState::player2);\n }\n private:\n enum class FieldState {\n empty,\n player1, // X\n player2, // O\n };\n\n bool check_win_condition(FieldState state) const;\n char field_state_to_char(FieldState state) const;\n\n\n std::array&lt;FieldState, 9&gt; m_board{ FieldState::empty };\n bool m_player1_active{ true };\n\n static constexpr char m_player1_token{ 'X' };\n static constexpr char m_player2_token{ 'O' };\n };\n\n int get_user_input(const std::string&amp; user_message);\n\n void play_game(); // main routine to run the game logic;\n} // namespace tic_tac_toe\n#endif\n</code></pre>\n\n<p><strong>tic_tac_toe.cpp</strong></p>\n\n<pre><code>#include \"tic_tac_toe.h\"\n\n#include &lt;algorithm&gt; // std::find\n#include &lt;cctype&gt; // std::stoi\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nnamespace tic_tac_toe\n{\n void TicTacToe::print_state_of_board() const\n /*\n Print the board. e.g:\n |X| |O|\n | |X| |\n |O| | |\n */\n {\n for (auto i = 0; i &lt; m_board.size(); ++i) {\n if (i % 3 == 0 &amp;&amp; i != 0) {\n std::cout &lt;&lt; \"|\\n\";\n }\n auto token = field_state_to_char(m_board.at(i));\n std::cout &lt;&lt; '|' &lt;&lt; token;\n }\n std::cout &lt;&lt; \"|\\n\";\n }\n\n bool TicTacToe::draw(int field)\n /*\n Tries to draw the next symbol in the field.\n Each time the function is called the player is changed.\n The user input has to be done out side. This way also a bot\n could play the game.\n If the selected field can not be set because its already \n occupied by player1 or player2 or out of range the return\n value becomes false\n */\n {\n if (field &lt; 1 || field &gt; m_board.size() || \n m_board.at(field - 1) != FieldState::empty) {\n return false;\n }\n if (m_player1_active) {\n m_board.at(field - 1) = FieldState::player1;\n m_player1_active = false;\n }\n else { // player 2 active\n m_board.at(field - 1) = FieldState::player2;\n m_player1_active = true;\n }\n return true;\n }\n\n bool TicTacToe::board_full() const\n /*\n search for a empty field in the board\n indicating that board is full if no empty field available.\n */\n {\n auto it = std::find(\n m_board.begin(), m_board.end(), FieldState::empty);\n\n return it == m_board.end();\n }\n\n bool TicTacToe::check_win_condition(FieldState state) const\n {\n constexpr std::array&lt;std::array&lt;int, 3&gt;, 8&gt; combinations =\n { \n std::array&lt;int, 3&gt;{0,1,2},\n std::array&lt;int, 3&gt;{3,4,5},\n std::array&lt;int, 3&gt;{6,7,8},\n std::array&lt;int, 3&gt;{0,3,6},\n std::array&lt;int, 3&gt;{1,4,7},\n std::array&lt;int, 3&gt;{2,5,8},\n std::array&lt;int, 3&gt;{0,4,8},\n std::array&lt;int, 3&gt;{2,4,6}\n };\n\n for (const auto&amp; combination : combinations) {\n if (m_board.at(combination[0]) == state &amp;&amp;\n m_board.at(combination[1]) == state &amp;&amp;\n m_board.at(combination[2]) == state) {\n return true;\n }\n } \n return false;\n }\n\n char TicTacToe::field_state_to_char(FieldState state) const\n {\n\n if (state == FieldState::player1) {\n return m_player1_token;\n }\n if (state == FieldState::player2) {\n return m_player2_token;\n }\n return ' ';\n }\n\n int get_user_input(const std::string&amp; user_message)\n {\n while (true) {\n std::cout &lt;&lt; user_message;\n std::string input;\n std::cin &gt;&gt; input;\n /*\n If input is not an integer the stoi function will raise\n an exception. We use this to determine if the input was\n an int\n */\n try {\n return std::stoi(input);\n }\n catch (std::invalid_argument&amp;) {\n std::cout &lt;&lt; \"\\nInput is not a number. Try again:\";\n }\n }\n }\n\n void play_game()\n /*\n Main routine to play the game with 2 players\n */\n {\n while (true) {\n TicTacToe game;\n bool player1_active{ true };\n while (!game.board_full() &amp;&amp;\n !game.player1_win() &amp;&amp; !game.player2_win()) {\n\n game.print_state_of_board();\n\n std::string user_message;\n if (player1_active) {\n user_message = \"1[X]:\";\n }\n else { // player2 active\n user_message = \"2[O]:\";\n }\n if (!game.draw(get_user_input(user_message))) {\n std::cout &lt;&lt; \"\\nInvalid! Try again: \\n\";\n }\n else {\n player1_active = !player1_active;\n }\n }\n\n game.print_state_of_board();\n\n if (game.player1_win()) {\n std::cout &lt;&lt; \"Player 1 wins!\\n\";\n }\n else if (game.player2_win()) {\n std::cout &lt;&lt; \"Player 2 wins!\\n\";\n }\n else {\n std::cout &lt;&lt; \"Draw!\\n\";\n }\n\n int choice{};\n while (true) {\n choice = get_user_input(\n \"Play again[Yes = 1, No = 0]: \");\n\n if (choice == 0) {\n return;\n }\n if(choice == 1) {\n break;\n }\n }\n }\n }\n} // namespace tic_tac_toe\n</code></pre>\n\n<p><strong>main.cpp</strong></p>\n\n<pre><code>#include \"tic_tac_toe.h\"\n\n#include &lt;iostream&gt;\n\nint main()\ntry {\n tic_tac_toe::play_game();\n}\ncatch (std::runtime_error&amp; e) {\n std::cerr &lt;&lt; e.what() &lt;&lt; \"\\n\";\n std::getchar();\n}\ncatch (...) {\n std::cerr &lt;&lt; \"unknown error \" &lt;&lt; \"\\n\";\n std::getchar();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T10:04:35.080", "Id": "407284", "Score": "0", "body": "Really Helpful ! I wasnt able get how to handle invalid input though.For eg when the user inputs a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T12:05:21.293", "Id": "407290", "Score": "0", "body": "hey. As soon as i have the time i will post a solution using classes and also handle wrong user inputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T14:54:15.340", "Id": "407297", "Score": "1", "body": "I believe you want to put a space after dash, to make list with dots (markdown formatting)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T09:28:22.687", "Id": "407364", "Score": "0", "body": "as promised i added a alternative solution with classes" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T08:20:37.550", "Id": "210681", "ParentId": "210679", "Score": "3" } }, { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>The code declares and uses 3 global variables. Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult. It also makes the code harder to reuse. For all of these reasons, it's generally far preferable to eliminate global variables in favor of local variables and pass pointers to variables for functions needing them. For instance, the only function using <code>w_combinations</code> is <code>win()</code>, so I would declare it <code>static constexpr</code> and put it within the body of that function.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>Unused variables are a sign of poor code quality, so eliminating them should be a priority. In this code, <code>end</code> is initialized but never used. My compiler also tells me that. You compiler is probably also smart enough to tell you that, if you ask it to do so. </p>\n\n<h2>Eliminate spurious statements</h2>\n\n<p>Inside the <code>win()</code> function is this strange construction:</p>\n\n<pre><code>{\n return true;\n break;\n}\n</code></pre>\n\n<p>The <code>break</code> is never going to be executed, so it would be better to simply omit it.</p>\n\n<h2>Use more whitespace to enhance readability of the code</h2>\n\n<p>Instead of crowding things together like this:</p>\n\n<pre><code>if (game.win()) {std::cout &lt;&lt; \"Player 1 wins!\\n\";break;}\n</code></pre>\n\n<p>most people find it more easily readable if you use more space:</p>\n\n<pre><code>if (game.win()) {\n std::cout &lt;&lt; \"Player 1 wins!\\n\";\n break;\n}\n</code></pre>\n\n<h2>Don't call <code>main</code></h2>\n\n<p>The C++ standard specifically prohibits calling <code>main</code>, so doing so results in <em>undefined behavior</em>, meaning that the compiler could do anything. If you need to have the program loop, write a loop.</p>\n\n<h2>Prefer looping to unbounded recursion</h2>\n\n<p>Unlike <code>main</code>, it is legal C++ to call <code>input</code> from within the <code>input</code> function. However, in this case, it's not a good idea. The goal here is to keep trying to get input until we get a valid input. Here's a way to write that which uses a loop instead of recursion:</p>\n\n<pre><code>void input(int player) {\n const char *prompt[2] = { \"1[X]:\", \"2[O]:\" };\n const char token[2] = { 'X', 'O' };\n assert(player == 0 || player == 1);\n std::cout &lt;&lt; prompt[player];\n while (1) {\n int square;\n std::cin &gt;&gt; square;\n --square;\n if (square &gt;= 0 &amp;&amp; square &lt; 9 &amp;&amp; pos[square] == '1'+square) {\n pos[square] = token[player];\n return;\n }\n std::cout &lt;&lt; \"\\nInvalid! Try again: \";\n }\n}\n</code></pre>\n\n<p>Note that <code>player</code> is now 0 or 1 instead of 1 or 2 and that I've used characters for <code>pos</code> instead of <code>int</code>. More on that later.</p>\n\n<h2>Use objects</h2>\n\n<p>The game is written much more in the procedural style of C rather than in the object-oriented style of C++. The game itself could be an object, with most of the procedures as functions of that object. This would reduce coupling and make the program easier to understand. It would also easily eliminate the global variables that currently exist in the code.</p>\n\n<h2>Use better variable and function names</h2>\n\n<p>The variable name <code>w_combinations</code> is ok, but the name <code>check()</code> is not. The first name explains something about what the variable means within the context of the code, but the latter is only confusing. A better name might be <code>printSquare()</code>.</p>\n\n<h2>Rethink the interfaces</h2>\n\n<p>The <code>printMatrix()</code> code currently looks like this:</p>\n\n<pre><code>void printMatrix() {\n std::cout &lt;&lt; \"|\" ; check(pos[0]) ; check(pos[1]) ; check(pos[2]);std::cout &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \"|\" ; check(pos[3]);check(pos[4]) ; check(pos[5]);std::cout &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \"|\" ; check(pos[6]) ; check(pos[7]) ; check(pos[8]); std::cout &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>It relies on a function called <code>check</code>. </p>\n\n<pre><code>void check (int x) { \n if ( x == 10) {\n std::cout &lt;&lt; \"X|\";\n }\n else if (x == 11) {\n std::cout &lt;&lt; \"O|\";\n }\n else {\n std::cout &lt;&lt; x &lt;&lt; \"|\";\n }\n}\n</code></pre>\n\n<p>This could be made much less verbose by doing two things: first, use <code>char</code> instead of <code>int</code> for <code>pos</code> and second, use the values <code>X</code> and <code>O</code> instead of 10 and 11. Then it could be written like this:</p>\n\n<pre><code>void printMatrix() {\n std::cout \n &lt;&lt; '|' &lt;&lt; pos[0] &lt;&lt; '|' &lt;&lt; pos[1] &lt;&lt; '|' &lt;&lt; pos[2] &lt;&lt; '\\n'\n &lt;&lt; '|' &lt;&lt; pos[3] &lt;&lt; '|' &lt;&lt; pos[4] &lt;&lt; '|' &lt;&lt; pos[5] &lt;&lt; '\\n'\n &lt;&lt; '|' &lt;&lt; pos[6] &lt;&lt; '|' &lt;&lt; pos[7] &lt;&lt; '|' &lt;&lt; pos[8] &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p>Alternatively, one could write a loop.</p>\n\n<h2>Reduce redundant code</h2>\n\n<p>Each player's turn is essentially the same code, with only the prompt changing, so it would make sense to write it that way. Using all of the suggestions above, here's what my rewritten <code>main</code> looks like:</p>\n\n<pre><code>int main() {\n bool playing = true;\n while (playing) {\n TicTacToe game;\n game.play();\n std::cout &lt;&lt; \"Play again[Yes = 1, No = 0]: \";\n int permission;\n std::cin &gt;&gt; permission;\n playing = (permission == 1);\n std::cout &lt;&lt; \"\\n\\n\";\n }\n}\n</code></pre>\n\n<p>Notice that everything is wrapped up in a <code>TicTacToe</code> game object which has <code>play()</code> as its only public member function. There are, of course, other ways to do this, but I hope that whets your appetite for learning more C++.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T15:39:11.447", "Id": "210693", "ParentId": "210679", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T06:21:04.310", "Id": "210679", "Score": "5", "Tags": [ "c++", "beginner", "c++11", "tic-tac-toe" ], "Title": "Tic Tac Toe in C++11" }
210679
<p>I wanted to create a relatively universal way of serialising an object, by doing a <code>memcpy</code> and generating a unique type ID. Stored together they can be used, for example, by another thread to restore a copy of the object for further processing.</p> <p>This is used, for example, where one tread has a logging function requiring minimal overhead and converting the object to its logged state is considerably more expensive than making a raw copy.</p> <p>Some other requirements / design choices:</p> <ul> <li>IDs should be dense (no gaps)</li> <li>IDs should fit the smallest unsigned possible</li> <li>No RTTI allowed</li> <li>A slight convenience overhead at the runtime restoring side is acceptable (and present in the form of the generated 'if' tree to match an ID to a type)</li> <li>Both sides have access to the definition of the mapping</li> <li>Handling of constructors with side-effects is left up to the user</li> </ul> <p>Id'd love to hear any critiques or possible pitfalls! Below is the header pasted into a silly example to show the idea and interface:</p> <pre><code>// This keeps a variable in the final output: #define KEEP(x) volatile auto x __attribute__((unused)) #include &lt;type_traits&gt; #include &lt;cstdint&gt; #include &lt;cstddef&gt; namespace type_list { /** * @brief Extract the N-th type of a set of template arguments * * @tparam N Index of type to extract * @tparam Ts Arguments */ template &lt;std::size_t N, typename T, typename... Ts&gt; struct nth_type { using type = typename nth_type&lt;N-1, Ts...&gt;::type; }; template &lt;typename T, typename... Ts&gt; struct nth_type&lt;0, T, Ts...&gt; { using type = T; }; /** * @brief Extract the N-th type of a set of template arguments * * @tparam N Index of type to extract * @tparam Ts Arguments */ template &lt;std::size_t N, typename... Ts&gt; using nth_type_t = typename nth_type&lt;N, Ts...&gt;::type; /** * @brief Find the index of the first matching type `IN` in a set of types. * * @tparam IN Type to find * @tparam T First of type list * @tparam Ts Rest of type list */ template &lt;typename IN, typename T, typename... Ts&gt; struct index_of_type { static_assert(sizeof...(Ts) != 0 || std::is_same_v&lt;IN, T&gt;, "No index for type found"); static constexpr const std::size_t value { 1 + index_of_type&lt;IN, Ts...&gt;::value }; }; template &lt;typename IN, typename... Ts&gt; struct index_of_type&lt;IN, IN, Ts...&gt; { static constexpr const std::size_t value { 0 }; }; /** * @brief Find the index of the first matching type `IN` in a set of types. * * @tparam IN Type to find * @tparam Ts Type list */ template &lt;typename IN, typename... Ts&gt; static constexpr const auto index_of_type_v { index_of_type&lt;IN, Ts...&gt;::value }; namespace { static constexpr void noop(const std::size_t = 0) {} template &lt;size_t I, typename... Ts&gt; struct map_visit_impl { template &lt;typename F, typename E&gt; static constexpr decltype(auto) visit(const std::size_t id, const void *const ptr, F func, E on_error) { if (id == I - 1) { return func(*reinterpret_cast&lt;const nth_type_t&lt;I-1, Ts...&gt; *const&gt;(ptr)); } else { return map_visit_impl&lt;I - 1, Ts...&gt;::visit(id, ptr, func, on_error); } } template &lt;typename F, typename E&gt; static constexpr decltype(auto) visit(const std::size_t id, void *const ptr, F func, E on_error) { if (id == I - 1) { return func(*reinterpret_cast&lt;nth_type_t&lt;I-1, Ts...&gt; *const&gt;(ptr)); } else { return map_visit_impl&lt;I - 1, Ts...&gt;::visit(id, ptr, func, on_error); } } }; template &lt;typename... Ts&gt; struct map_visit_impl&lt;0, Ts...&gt; { template &lt;typename F, typename E&gt; static constexpr void visit(const std::size_t id, const void *const, F func, E on_error) { // If arrived here we have a invalid id on_error(id); } template &lt;typename F, typename E&gt; static constexpr void visit(const std::size_t id, void *const, F func, E on_error) { // If arrived here we have a invalid id on_error(id); } }; } /** * @brief Create an ID map of a set of types. * * @tparam Ts Type list */ template &lt;typename... Ts&gt; struct map { /** * @brief Get the type with index `N` * * @tparam N Index of type to get */ template &lt;std::size_t N&gt; using type = type_list::nth_type_t&lt;N, Ts...&gt;; /** * @brief The ID number (index) of a given type `T` * * @tparam T */ template &lt;typename T&gt; static constexpr const std::size_t id { type_list::index_of_type_v&lt;T, Ts...&gt; }; /** * @brief Number of types stored */ static constexpr const std::size_t size { sizeof...(Ts) }; /** * @brief Convert any given pointer to the type matching `id` and pass * it to a function `func` as only argument using a `reinterpret_cast`. * * @tparam F Function type * @param id id / index of type * @param ptr Storage location * @param func Handler function * @return Result of handler function */ template &lt;typename F, typename E = decltype(noop)&gt; static constexpr decltype(auto) parse(const std::size_t id, const void *const ptr, F func, E on_error = noop) { return map_visit_impl&lt;sizeof...(Ts), Ts...&gt;::visit(id, ptr, func, on_error); } /** * @brief Convert any given pointer to the type matching `id` and pass * it to a function `func` as only argument using a `reinterpret_cast`. * * @tparam F Function type * @param id id / index of type * @param ptr Storage location * @param func Handler function * @return Result of handler function */ template &lt;typename F, typename E = decltype(noop)&gt; static constexpr decltype(auto) parse(const std::size_t id, void *const ptr, F func, E on_error = noop) { return map_visit_impl&lt;sizeof...(Ts), Ts...&gt;::visit(id, ptr, func, on_error); } }; } // Generate unique types template &lt;size_t N&gt; struct c {}; // Demo set of types using map = type_list::map&lt; uint8_t, uint16_t, uint32_t, int8_t, int16_t, int32_t, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt;, c&lt;__COUNTER__&gt; &gt;; // Just a quick hack to initialise some test data: char bytes[] = "Test string, bla bla"; uint64_t counter = 0; void fn(const std::size_t n, const std::size_t i) { __asm volatile("# LLVM-MCA-BEGIN type_map_overhead"); map::parse(n, &amp;bytes[i], [&amp;](auto&amp; val) { __asm volatile("# LLVM-MCA-END"); // Needed because the handler needs to apply to any type in the map: if constexpr (std::is_integral_v&lt;decltype(val)&gt;) { counter += val; } }); } int main() { KEEP(k1) = map::id&lt;uint16_t&gt;; // size_t =&gt; 1 KEEP(k2) = std::is_same_v&lt;map::type&lt;1&gt;, uint16_t&gt;; // bool =&gt; true fn(0, 0); fn(1, 1); fn(2, 2); KEEP(k4) = counter; } </code></pre>
[]
[ { "body": "<p>It would be nice to pass a size with the buffer, so we can check the size of the type vs the size of the buffer. Also, a pointer to <code>unsigned char</code> or <a href=\"https://en.cppreference.com/w/cpp/types/byte\" rel=\"nofollow noreferrer\"><code>std::byte</code></a> would be better than a <code>void*</code>.</p>\n\n<p>I think using <a href=\"https://en.cppreference.com/w/cpp/language/reinterpret_cast\" rel=\"nofollow noreferrer\"><code>reinterpret_cast</code></a> like this is undefined behaviour. We can copy the object representation (by <code>reinterpret_cast</code>ing to <code>char</code> or <code>unsigned char</code> and copying manually, or using <code>std::memcpy</code>). However, the object may have alignment requirements or padding that aren't observable in this representation.</p>\n\n<p>Since the character array was created as a character array, it doesn't have the necessary alignment / padding, so using it directly as if it were the object is undefined behaviour. We have to use <code>std::memcpy</code> to copy the bytes back into memory that was actually allocated as the object in question.</p>\n\n<p>Note that <a href=\"https://en.cppreference.com/w/cpp/string/byte/memcpy\" rel=\"nofollow noreferrer\"><code>std::memcpy</code> has requirements of its own</a>. Specifically that types be <a href=\"https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable\" rel=\"nofollow noreferrer\"><code>TriviallyCopyable</code></a>, so constructors with side-effects will not work. It would be good to check this when serializing the object with a <code>static_assert(is_trivially_copyable_v&lt;T&gt;, \"...\")</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:59:21.677", "Id": "407450", "Score": "1", "body": "I disagree on `void*` versus `unsigned char*` or `byte*`. I think `void*` is absolutely the right type to semantically represent \"pointer to a thing I don't know what it is.\" In fact, if you use `void*` (as OP did), then you don't need the `reinterpret_cast`; you can just use a less-scary-looking `static_cast` (as OP didn't). If you pretend that your pointer points to `unsigned char`, or pretend that it points to `byte`, then you're lying to the compiler, and so you _would_ need the `reinterpret_cast` to undo the lie." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T08:02:12.667", "Id": "407481", "Score": "0", "body": "@Quuxplusone Hmm. I would agree, except that OP mentions using `memcpy` to serialise the object. So I think it actually is an array of bytes, not a pointer to an object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:27:56.413", "Id": "407570", "Score": "0", "body": "Yeah, as you mention, OP's code has alignment issues and also requires trivial copyability for `T`. But I think that's all kind of orthogonal. If the alignment issues were fixed, then I stand by my claim that `void*` would be more \"right\" than `unsigned char*`. If the alignment issues _aren't_ fixed, then it doesn't matter because nothing is right because the code doesn't even work. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T12:34:14.813", "Id": "210687", "ParentId": "210683", "Score": "1" } }, { "body": "<pre><code>// This keeps a variable in the final output:\n#define KEEP(x) volatile auto x __attribute__((unused))\n</code></pre>\n\n<p>Getting off to a controversial start here, aren't we? :) This macro is used <em>only</em> in your test harness <code>main()</code>, so it should be defined way down at the bottom of the file, right above <code>main()</code>. That way the reader doesn't get scared that your actual library functionality requires such a wacky macro.</p>\n\n<p>In general, you should make it clearer which part of your code is the library and which part is the test harness. Consider adding <code>#ifdef TESTING</code> around the harness code, which, IIUC, basically begins at the line</p>\n\n<pre><code>// Generate unique types\n</code></pre>\n\n<hr>\n\n<p>If <em>all</em> you're using <code>KEEP</code> for is to \"keep a variable in the final output,\" why don't you just make the variable global? That is, replace</p>\n\n<pre><code>int main() {\n KEEP(k1) = map::id&lt;uint16_t&gt;; // size_t =&gt; 1\n KEEP(k2) = std::is_same_v&lt;map::type&lt;1&gt;, uint16_t&gt;; // bool =&gt; true\n\n fn(0, 0);\n fn(1, 1);\n fn(2, 2);\n\n KEEP(k4) = counter;\n}\n</code></pre>\n\n<p>with simply</p>\n\n<pre><code>size_t k1 = map::id&lt;uint16_t&gt;; // should be 1\nbool k2 = std::is_same_v&lt;map::type&lt;1&gt;, uint16_t&gt;; // should be true\nsize_t k4 = 0;\n\nint main() {\n fn(0, 0);\n fn(1, 1);\n fn(2, 2);\n\n k4 = counter; // should be ???\n}\n</code></pre>\n\n<p>Since other translation units might access <code>k1</code>, <code>k2</code>, and <code>k4</code> by name, the compiler <em>has</em> to keep them around. No <code>volatile</code> or <code>__attribute__</code> needed!</p>\n\n<hr>\n\n<pre><code>void fn(const std::size_t n, const std::size_t i) {\n</code></pre>\n\n<p>Lose the meaningless <code>const</code>s. They just make your function prototype harder to read. (Personally, I would also lose the <code>std::</code>s; they aren't needed. But some people like them, and if you're such a person, I won't argue.)</p>\n\n<pre><code>void fn(size_t n, size_t i) {\n</code></pre>\n\n<p>So much cleaner! Now we even have room to give <code>n</code> and <code>i</code> real names, if we want to.</p>\n\n<hr>\n\n<p>FWIW, I don't understand the purpose of the <code>__asm volatile</code> comments.</p>\n\n<hr>\n\n<pre><code>map::parse(n, &amp;bytes[i], [&amp;](auto&amp; val) {\n __asm volatile(\"# LLVM-MCA-END\");\n // Needed because the handler needs to apply to any type in the map:\n if constexpr (std::is_integral_v&lt;decltype(val)&gt;) {\n counter += val;\n }\n});\n</code></pre>\n\n<p>It is highly unusual to write a generic lambda that takes a parameter of type <code>auto&amp;</code>. Pass-by-value <code>auto</code>, sure. Pass-by-forwarding-reference <code>auto&amp;&amp;</code>, sure. Pass-by-const-ref <code>const auto&amp;</code>, quite plausibly. But pass-by-nonconst-ref <code>auto&amp;</code>? That's a weird one. Are you sure that's what you want? In generic code you usually want <code>auto&amp;&amp;</code> for perfect forwarding.</p>\n\n<p>Since <code>decltype(val)</code> is <em>always</em> a reference type, it's <em>never</em> an integral type. Do you observe this <code>if constexpr</code> branch ever being taken? I don't think it is being taken. What was its purpose supposed to be?</p>\n\n<hr>\n\n<pre><code>static constexpr void noop(const std::size_t = 0) {}\n</code></pre>\n\n<p>What is the purpose of the default function argument here? I would prefer to see this as</p>\n\n<pre><code>static void noop(size_t) {}\n</code></pre>\n\n<p>or, even better if you care about inlining,</p>\n\n<pre><code>struct Noop { void operator()(size_t) const {} };\n</code></pre>\n\n<p>And then down where you use <code>noop</code>:</p>\n\n<pre><code>template &lt;typename F, typename E = decltype(noop)&gt;\nstatic constexpr decltype(auto) parse(const std::size_t id, const void *const ptr, F func, E on_error = noop) {\n return map_visit_impl&lt;sizeof...(Ts), Ts...&gt;::visit(id, ptr, func, on_error);\n}\n</code></pre>\n\n<p>this would be better optimizable if you wrote it as</p>\n\n<pre><code>template&lt;class F, class E = Noop&gt;\nstatic constexpr decltype(auto) parse(size_t id, const void *ptr, F func, E on_error = E()) {\n return map_visit_impl&lt;sizeof...(Ts), Ts...&gt;::visit(id, ptr, func, on_error);\n}\n</code></pre>\n\n<p>And if you <em>really</em> care about efficiency, and don't want to burden your end-user with wrapping their error handler in <code>std::ref()</code> all the time, then you'll break with STL tradition and either pass the error handler by reference, or move-out-of it (instead of copying it) when you pass it by value:</p>\n\n<pre><code>template&lt;class F, class E = Noop&gt;\nstatic constexpr decltype(auto) parse(size_t id, const void *ptr, const F&amp; func, const E&amp; on_error = E()) {\n return map_visit_impl&lt;sizeof...(Ts), Ts...&gt;::visit(id, ptr, func, on_error);\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>template&lt;class F, class E = Noop&gt;\nstatic constexpr decltype(auto) parse(size_t id, const void *ptr, F func, E on_error = E()) {\n return map_visit_impl&lt;sizeof...(Ts), Ts...&gt;::visit(id, ptr, std::move(func), std::move(on_error));\n}\n</code></pre>\n\n<hr>\n\n<pre><code>template &lt;typename IN, typename... Ts&gt;\nstatic constexpr const auto index_of_type_v { index_of_type&lt;IN, Ts...&gt;::value };\n</code></pre>\n\n<p>This is the weirdest way of writing</p>\n\n<pre><code>template&lt;class T, class... Ts&gt;\ninline constexpr size_t index_of_type_v = index_of_type&lt;T, Ts...&gt;::value;\n</code></pre>\n\n<p>that I've ever seen. :)</p>\n\n<hr>\n\n<pre><code> /*\n * @tparam F Function type\n * @param id id / index of type\n * @param ptr Storage location\n * @param func Handler function\n * @return Result of handler function\n</code></pre>\n\n<p>You know, if you renamed <code>ptr</code> to <code>storage</code> and renamed <code>func</code> to <code>handler</code>, then you could get rid of this comment. (Self-documenting code!)</p>\n\n<hr>\n\n<pre><code>return func(*reinterpret_cast&lt;const nth_type_t&lt;I-1, Ts...&gt; *const&gt;(ptr));\n</code></pre>\n\n<p>As I mentioned in a comment on <a href=\"https://codereview.stackexchange.com/a/210687/16369\">user673679's answer</a>, you should avoid <code>reinterpret_cast</code> whenever possible. It's a big red flag that makes the reader wonder what trickery you're doing. So, if you're not doing any trickery, you should avoid waving that red flag unnecessarily.</p>\n\n<p>Also, as usual, you've got useless <code>const</code>s that merely clutter the code.</p>\n\n<pre><code>return func(*static_cast&lt;const nth_type_t&lt;I-1, Ts...&gt; *&gt;(ptr));\n</code></pre>\n\n<hr>\n\n<p>Both <code>index_of_type</code> and <code>map_visit_impl</code> are done with recursive template instantiations. You should consider how to rewrite them as non-recursive templates using pack expansion and/or fold-expressions. Especially <code>map_visit_impl</code>, since function instantiation is basically the slowest thing you can ask a compiler to do. See <a href=\"https://quuxplusone.github.io/blog/2018/07/23/metafilter/\" rel=\"nofollow noreferrer\">this blog post</a> for inspiration if you need it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:35:03.463", "Id": "407461", "Score": "0", "body": "I feel like I need to review the answer, you bring up some very valid points, thanks for that, but also some things that are plain wrong. The macro is obviously just part of the test harness, by convention put on top to prevent changing the meaning of code halfway through the translation unit. Without the 'whacky' macro you have to rewrite everything as global, which is doable for a small main, but certainly not great if you want to selectively 'probe' a few variables in assembly. Only in testing, as you rightly point out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:38:23.177", "Id": "407462", "Score": "1", "body": "`size_t` is not standard C++, `std::size` is, you're proposing to make the code less portable. Interestingly, this is often pointed out in reviews here. Same for `const` correctness. Less is not more here and your advice would lead to worse code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:42:12.157", "Id": "407463", "Score": "0", "body": "The MCA comments are to allow `llvm-mca`, the [LLVM Machine Code Analyser](https://llvm.org/docs/CommandGuide/llvm-mca.html) to understand that this code section is to be analysed separately. It's a pretty neat tool, [Compiler Explorer](https://godbolt.org/) has it built-in these days." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:47:26.717", "Id": "407464", "Score": "0", "body": "Good point about the reference in the universal lambda, I will improve that. I was doubting about allowing write access at all. I added the `if constexpr` integral check for the specific test scenario (to filter out the classes), I'll verify its workings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:54:27.170", "Id": "407465", "Score": "0", "body": "About the restructuring of the way the error handler is attached. About the error function itself: What if I pass a const size_t to your proposed version? I wonder how much of your structural optimisation is needed to just compensate for your preference to not use `const` and `constexpr`. GCC certainly likes `constexpr` functions for inlining. I'll make a version as you proposed to see if it makes a difference in resulting assembly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:01:17.780", "Id": "407467", "Score": "1", "body": "_What if I pass a `const size_t`_ ... _`const` correctness. Less is not more here_ ... It sounds like you don't understand the notion of const-correctness in C++, or at least you have some misconception about the meaning of pass-by-`const`-value in a function signature. I want to say that googling \"const is a contract\" should clear up the misconception, but actually I'm not pleased with the top search results there. ([The Const Nazi](http://gamesfromwithin.com/the-const-nazi) is actually the best search result so far.) I guess I have another blog post to write soon... :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:03:25.337", "Id": "407468", "Score": "1", "body": "Let's go over `static constexpr const auto ... {}` vs `inline constexpr size_t ... =` : `static` in this case is to take a more prudent default: any translation unit using the template will not by default pollute the global namespace. `constexpr` implies `inline`, so it's not needed to add this. I prefer `auto` because it reduces information duplication, reducing issues with future code changes. For the difference between direct initialisation (`{}`) and assignment initialisation read up if you like, but in practice I've not seen differences in generated code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:37:43.017", "Id": "407580", "Score": "0", "body": "_`constexpr` implies `inline`_ — No it doesn't. [Wandbox example](https://wandbox.org/permlink/bhaYGS872vRVwh3h). When in doubt, do as the STL does: [`inline constexpr [type]`](https://en.cppreference.com/w/cpp/types/is_same#Helper_variable_template). They do have a reason for picking that exact sequence of keywords. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T04:53:29.940", "Id": "407620", "Score": "1", "body": "_I guess I have another blog post to write soon..._ [The blog post has now been written!](https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T01:15:54.047", "Id": "210777", "ParentId": "210683", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T08:52:50.720", "Id": "210683", "Score": "1", "Tags": [ "c++", "design-patterns", "template-meta-programming", "c++17", "rtti" ], "Title": "Map a set of types to unique IDs and runtime reinterpret back from ID and pointer in C++17" }
210683
<p>This is my first attempt to implement a crypto algorithm.</p> <p>I am using C and <a href="https://gmplib.org/" rel="nofollow noreferrer">gmp</a> to interact with big numbers.</p> <p>I am basing my implementation of the RSA algorithm on information in the book &quot;<a href="http://cacr.uwaterloo.ca/hac/" rel="nofollow noreferrer">A handbook of applied cryptography</a>&quot; (chapter 8.2) :</p> <ul> <li>Take two distinct, large primes <code>p</code> and <code>q</code> <ul> <li>Ideally these have a similar byte-length</li> </ul> </li> <li>Multiply <code>p</code> and <code>q</code> and store the result in <code>n</code></li> <li>Find the totient for <code>n</code> using the formula <span class="math-container">$$\varphi(n)=(p-1)(q-1)$$</span></li> <li>Take an <code>e</code> coprime that is greater, than 1 and less than <code>n</code></li> <li>Find <code>d</code> using the formula <span class="math-container">$$d\cdot e\equiv1\mod\varphi(n)$$</span></li> </ul> <p>At this point, the pair <code>(e, n)</code> is the public key and the private key <code>(d, n)</code> is the private key.</p> <p>Here is my code; you can run it after having linked with the <code>-lgmp</code> parameter:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;math.h&gt; #include &lt;sys/types.h&gt; #include &quot;gmp.h&quot; void generatePrimes(mpz_t* p, mpz_t* q); void computeNandF(mpz_t* q, mpz_t* p, mpz_t *phi, mpz_t* n); void generateE(mpz_t* phi, mpz_t* e); void enc(mpz_t* e, mpz_t* n, mpz_t* d, mpz_t* c, char[]); void dec(mpz_t* m, mpz_t* c, mpz_t* d, mpz_t* n); void makeKeys(mpz_t n, mpz_t e, mpz_t d, mpz_t p, mpz_t q); void encrFile(mpz_t e, mpz_t n, mpz_t d, mpz_t c); gmp_randstate_t stat; int main() { mpz_t p, q, phi, e, n, d, c, dc; char msg[40] = &quot;welcome to cryptoworld&quot;; int *mes; int len = strlen(msg); mpz_init(p); mpz_init(q); mpz_init(phi); mpz_init(e); mpz_init(n); mpz_init(d); mpz_init(c); mpz_init(dc); // RSA algorithm generatePrimes(&amp;p, &amp;q); computeNandF(&amp;q, &amp;p, &amp;phi, &amp;n); generateE(&amp;phi, &amp;e); // extended Euclidean mpz_invert(d, e, phi); printf(&quot;d = &quot;); mpz_out_str(stdout, 10, d); printf(&quot;\n------------------------------------------------------------------------------------------\n&quot;); enc(&amp;e, &amp;n, &amp;d, &amp;c, msg); dec(&amp;dc, &amp;c, &amp;d, &amp;n); printf(&quot;\n------------------------------------------------------------------------------------------\n&quot;); printf(&quot;encrypt message = &quot;); mpz_out_str(stdout, 10, c); printf(&quot;\n&quot;); printf(&quot;\n------------------------------------------------------------------------------------------\n&quot;); printf(&quot;message as int after decr = &quot;); mpz_out_str(stdout, 10, dc); printf(&quot;\n&quot;); mpz_export(mes, (size_t*) malloc(sizeof (size_t)), 1, sizeof (mes[0]), 0, 0, dc); char r[40]; printf(&quot;message as string after decr = &quot;); for (int i = 0; i &lt; len; i++) { r[i] = (char) mes[i]; printf(&quot;%c&quot;, r[i]); } printf(&quot;\n&quot;); encrFile(e, n, d, c); mpz_clear(p); mpz_clear(q); mpz_clear(phi); mpz_clear(n); mpz_clear(e); mpz_clear(c); mpz_clear(d); mpz_clear(dc); return 0; } void generatePrimes(mpz_t* p, mpz_t* q) { int primetest; long sd = 0; mpz_t seed; gmp_randinit(stat, GMP_RAND_ALG_LC, 120); mpz_init(seed); srand((unsigned) getpid()); sd = rand(); mpz_set_ui(seed, sd); gmp_randseed(stat, seed); mpz_urandomb(*p, stat, 512); primetest = mpz_probab_prime_p(*p, 10); if (primetest != 0) { printf(&quot;p is prime\n&quot;); } else { //printf(&quot;p wasnt prime,choose next prime\n&quot;); mpz_nextprime(*p, *p); } mpz_urandomb(*q, stat, 512); primetest = mpz_probab_prime_p(*q, 10); if (primetest != 0) { // printf(&quot;q is prime\n&quot;); } else { // printf(&quot;p wasnt prime,choose next prime\n&quot;); mpz_nextprime(*q, *q); } printf(&quot;p and q generated!!\n&quot;); printf(&quot;p = &quot;); mpz_out_str(stdout, 10, *p); printf(&quot;q = &quot;); mpz_out_str(stdout, 10, *q); printf(&quot;\n------------------------------------------------------------------------------------------\n&quot;); mpz_clear(seed); return; } void computeNandF(mpz_t* q, mpz_t* p, mpz_t *phi, mpz_t* n) { mpz_t temp1, temp2; mpz_init(temp1); mpz_init(temp2); //n=p*q mpz_mul(*n, *q, *p); mpz_sub_ui(temp1, *q, 1); //temp1=q-1 mpz_sub_ui(temp2, *p, 1); //temp2=p-1 //φ=(p-1)(q-1) mpz_mul(*phi, temp1, temp2); printf(&quot;phi and n generated!!\n&quot;); printf(&quot; n= &quot;); mpz_out_str(stdout, 10, *n); printf(&quot;phi = &quot;); mpz_out_str(stdout, 10, *phi); printf(&quot;\n------------------------------------------------------------------------------------------\n&quot;); } void generateE(mpz_t* phi, mpz_t* e) { mpz_t temp, seed; mpz_init(seed); mpz_init(temp); long sd = 0; gmp_randinit(stat, GMP_RAND_ALG_LC, 120); srand((unsigned) getpid()); sd = rand(); mpz_set_ui(seed, sd); gmp_randseed(stat, seed); do { mpz_urandomm(*e, stat, *phi + 1); mpz_gcd(temp, *phi, *e); //temp=gcd(e,φ) } while (mpz_cmp_ui(temp, 1) != 0); //while gcd!=1 printf(&quot;e generated \n e = &quot;); mpz_out_str(stdout, 10, *e); printf(&quot;\n------------------------------------------------------------------------------------------\n&quot;); } void enc(mpz_t* e, mpz_t* n, mpz_t* d, mpz_t* c, char msg[]) { int r[40]; for (int i = 0; i &lt; strlen(msg); i++) { r[i] = (int) msg[i]; } int *m = r; mpz_t M; mpz_init(M); mpz_import(M, strlen(msg), 1, sizeof (m[0]), 0, 0, m); printf(&quot;message as int before encryption = &quot;); mpz_out_str(stdout, 10, M); printf(&quot;\n&quot;); mpz_powm(*c, M, *e, *n); } void dec(mpz_t* m, mpz_t* c, mpz_t* d, mpz_t* n) { mpz_powm(*m, *c, *d, *n); } void encrFile(mpz_t e, mpz_t n, mpz_t d, mpz_t c) { char text[80]; FILE *file; file = fopen(&quot;text.txt&quot;, &quot;r&quot;); int i = 0; if (file) { while ((x = getc(file)) != EOF) { i++; putchar(x); text[i] = (char) x; } int r[40]; for (int i = 0; i &lt; strlen(text); i++) { r[i] = (int) text[i]; } int *m = r; mpz_t M; mpz_init(M); mpz_import(M, strlen(text), 1, sizeof (m[0]), 0, 0, m); printf(&quot;message as int before encryption = &quot;); mpz_out_str(stdout, 10, M); printf(&quot;\n&quot;); mpz_powm(c, M, e, n); printf(&quot;encrypt txt = &quot;); mpz_out_str(stdout, 10, c); printf(&quot;\n&quot;); fclose(file); file = fopen(&quot;text.txt&quot;, &quot;w&quot;); mpz_out_raw(file, c); fclose(file); } } </code></pre> <p>Any comments and improvements in my implementation will be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T13:38:35.370", "Id": "407292", "Score": "0", "body": "From what library is \"gmp.h\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T13:42:18.143", "Id": "407293", "Score": "0", "body": "Can you explain more about what this code is supposed to do and whether it does so in a satisfactory manner? There are a lot of variable names which could use an explanation, the initialization is odd at best and some of the definitions don't make much sense at first glance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T15:12:06.477", "Id": "407300", "Score": "2", "body": "@Mast https://gmplib.org/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T15:33:52.867", "Id": "407303", "Score": "0", "body": "@Mast the library is gmp. This code supposed to implement all the steps of RSA(https://amirshenouda.files.wordpress.com/2012/06/image3.png). I have the steps in the methods wich have names to understand the step. And all my variables have the proper names like the steps of the algorithm (ex. n is the n from the algo)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T20:01:37.617", "Id": "407334", "Score": "0", "body": "Much better already :-)" } ]
[ { "body": "<h2>Indicate your locals</h2>\n\n<p>Since all of your functions are in the same translation unit, make them <code>static</code>.</p>\n\n<h2>Passing by reference</h2>\n\n<p>Some of your <code>mpz_t</code> are explicitly passed by reference, i.e.</p>\n\n<pre><code>void generatePrimes(mpz_t* p, mpz_t* q);\n</code></pre>\n\n<p>and some appear initially to be passed by value:</p>\n\n<pre><code>void encrFile(mpz_t e, mpz_t n, mpz_t d, mpz_t c);\n</code></pre>\n\n<p>These structures are defined here:</p>\n\n<pre><code>typedef struct\n{\n int _mp_alloc; /* Number of *limbs* allocated and pointed\n to by the _mp_d field. */\n int _mp_size; /* abs(_mp_size) is the number of limbs the\n last field points to. If _mp_size is\n negative this is a negative number. */\n mp_limb_t *_mp_d; /* Pointer to the limbs. */\n} __mpz_struct;\n\ntypedef __mpz_struct mpz_t[1];\n</code></pre>\n\n<p>Confusingly, even if you don't add a <code>*</code>, you will be passing by reference, because <code>mpz_t</code> is defined as an array. As such, you should be dropping the pointer notation everywhere.</p>\n\n<p>You really do need to mark <code>const</code> the pointer arguments that you don't change, especially since everything is being passed by reference.</p>\n\n<h2>Naming arguments</h2>\n\n<p>Function prototypes aren't just to predeclare a function to sort out order dependency. They're also documentation for developers. As such, your unnamed <code>char[]</code> argument here:</p>\n\n<pre><code>void enc(mpz_t* e, mpz_t* n, mpz_t* d, mpz_t* c, char[]);\n</code></pre>\n\n<p>needs to be named.</p>\n\n<h2>Variable names</h2>\n\n<p>I realize that many of these variable names are defined by your book, but that doesn't help other developers (or you in the future). At the absolute least, write a comment beside every variable that you declare describing what it is and how it's used. If possible, upgrade variable names from cryptic single letters to actual words.</p>\n\n<h2>Error checking</h2>\n\n<p>All system calls, e.g. to <code>fopen</code>, might fail and need to be checked. This:</p>\n\n<pre><code>FILE *file;\nfile = fopen(\"text.txt\", \"r\");\nif (file) {\n</code></pre>\n\n<p>silently ignores failures to open the file, which is bad. You need to do something meaningful - in this case, perhaps <code>perror(\"Failed to open crypto file\"); exit(1);</code></p>\n\n<h2>Combine declaration and initialization</h2>\n\n<p>This:</p>\n\n<pre><code>FILE *file;\nfile = fopen(\"text.txt\", \"r\");\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>FILE *file = fopen(\"text.txt\", \"r\");\n</code></pre>\n\n<h2>Avoid overflows</h2>\n\n<p>This segment of code:</p>\n\n<pre><code>char text[80];\nFILE *file;\nfile = fopen(\"text.txt\", \"r\");\nint i = 0;\nif (file) {\n while ((x = getc(file)) != EOF) {\n i++;\n putchar(x);\n text[i] = (char) x;\n }\n\n int r[40];\n for (int i = 0; i &lt; strlen(text); i++) {\n r[i] = (int) text[i];\n }\n</code></pre>\n\n<p>is begging for an overflow error in a handful of ways. You have a fixed-length <code>text</code> array to which you write file contents with no length check other than EOF. You also have an <code>r</code> array whose initialization loop ignores its length and relies on <code>strlen</code> - but you haven't null-terminated your <code>text</code> string!</p>\n\n<p>Instead,</p>\n\n<ol>\n<li>Get the length of the file.</li>\n<li>Don't even bother with initializing a character array; skip to initializing your <code>int</code> array.</li>\n<li>Dynamically allocate the array with <code>malloc</code> based on the size of the file.</li>\n<li>Read into the array until it's full.</li>\n</ol>\n\n<h2>Don't use <code>printf</code> unless you have to</h2>\n\n<p>This:</p>\n\n<pre><code>printf(\"message as int before encryption = \");\n</code></pre>\n\n<p>doesn't do any formatting, so use <code>puts</code> instead, which is more efficient.</p>\n\n<h2>Make your file I/O functions more flexible</h2>\n\n<p>Don't hardcode the file name <code>text.txt</code>. Instead, accept that as an argument to the function. Get it from user input or a command-line argument.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:39:13.337", "Id": "407324", "Score": "3", "body": "Usually `printf()` with one argument (at least if not containing format specifiers) usually gets optimized into a `puts()` call, at least gcc+glibc does that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:23:08.980", "Id": "407329", "Score": "0", "body": "@larkey I'd offer that since both `printf` and `puts` are available to the user, and it's no extra effort to use `puts`, it's both useful and educational to use the latter. But that's good to know!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:46:21.460", "Id": "407333", "Score": "0", "body": "Sure! Often I end up using `printf()` even for simple things since I just edit something away and don't bother to change or have some logging macro, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:41:58.810", "Id": "407528", "Score": "1", "body": "Why show `typedef struct { ... } __mpz_struct;`? Type `mpz_t` is an array and `encrFile(mpz_t e, mpz_t n, mpz_t d, mpz_t c)` receives pointers (to the first element of `mpz_t`). Even if `__mpz_struct` was huge, `encrFile()` would still receive 4 pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:04:35.563", "Id": "407536", "Score": "0", "body": "@chux That's straight from the header file. Interesting - so `mpz_t` is an array? If so, the OP shouldn't be using pointers anywhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:15:54.853", "Id": "407541", "Score": "2", "body": "As I see it, using type `typedef __mpz_struct mpz_t[1];` allows _most_ `mpz_...()` to fake a call by reference as with `mpz_t p; ... mpz_init(p);`. Unfortunately it does not apply to `rop` in `mpz_export (void *rop, ...` and so [messes up](https://codereview.stackexchange.com/a/210824/29485) OP code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:14:39.767", "Id": "407587", "Score": "0", "body": "@chux OK, well valid points; I've updated the answer." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T17:53:55.643", "Id": "210697", "ParentId": "210685", "Score": "6" } }, { "body": "<p><strong>Invalid code</strong></p>\n\n<p>In <code>while ((x = getc(file)) != EOF)</code>, where is <code>x</code> defined? <sup>1</sup></p>\n\n<pre><code>error: 'x' undeclared (first use in this function)\n</code></pre>\n\n<p><strong>Use of uninitialized object</strong></p>\n\n<p>The pointer <code>mes</code> is passed to <code>mpz_export()</code> without initialization/assignment.</p>\n\n<pre><code>int *mes;\n...\n// Garbage value pass to `mpz_export(void *rop, ...)`\nmpz_export(mes, (size_t*) malloc(sizeof(size_t)), 1, sizeof(mes[0]), 0, 0,\n...\nr[i] = (char) mes[i];\n</code></pre>\n\n<p>The compiler warning hinted to this problem. This implies code is not using a good compiler will all warnings enabled. Save time. Enable then all.</p>\n\n<pre><code>warning: 'mes' may be used uninitialized in this function [-Wmaybe-uninitialized]\n</code></pre>\n\n<p>I suspect the following will fix</p>\n\n<pre><code>//int *mes;\n//int len = strlen(msg);\nint len = strlen(msg);\nint mes[len + !len]; // Insure VLA is at least size 1\n\n// Unsure about mpz_export() repair needs.\n// mpz_export(mes, (size_t*) malloc(sizeof(size_t)), 1, sizeof(mes[0]), 0, 0, dc);\nmpz_export( mes, malloc(sizeof(size_t)), 1, sizeof mes , 0, 0, dc);\n</code></pre>\n\n<p><strong>Passing by reference cheat</strong></p>\n\n<p>The <code>mpz</code> library <strong>cheats</strong>.</p>\n\n<p><code>typedef __mpz_struct mpz_t[1];</code> defines <code>mpz_t</code> as an array of 1. </p>\n\n<p>Consider the following:</p>\n\n<pre><code>extern void foo(mpz_t arg1);\nmpz_t a;\nfoo(a);\n</code></pre>\n\n<p>In common C, one would <strong>not</strong> expect <code>a</code> to be modified by <code>foo()</code> as C is <em>pass by value</em> . Yet since <code>a</code> is an array of <code>__mpz_struct</code>, <code>a</code> is converted from its value as an array to the addresses of <code>a[0]</code>. It is that address that is passed by value to <code>foo</code>. Now <code>foo()</code> can change the caller's <code>a</code>.</p>\n\n<p>To prevent/allow changing <code>mpz_t</code> augments, the <code>mpz</code> library uses <code>const</code>.</p>\n\n<pre><code>// can change, can't change, can't change, can't change\nmpz_powm (mpz_t rop, const mpz_t base, const mpz_t exp, const mpz_t mod)\n</code></pre>\n\n<p>But what should OP's function do? Take advantage of the hidden \"call-by-reference\"?</p>\n\n<p>Consider OP's <code>dec()</code></p>\n\n<pre><code>void dec(mpz_t* m, mpz_t* c, mpz_t* d, mpz_t* n) {\n mpz_powm(*m, *c, *d, *n);\n}\n</code></pre>\n\n<p>This should use <code>const</code> to indicate which may change.</p>\n\n<pre><code>void dec_alt1(mpz_t* m, const mpz_t* c, const mpz_t* d, const mpz_t* n) {\n mpz_powm(*m, *c, *d, *n);\n}\n</code></pre>\n\n<p>It is quite unnecessary to pass 4 <code>mpz_t*</code> pointers. Code could have been the following which is also passing 4 pointers.</p>\n\n<pre><code>void dec_alt2(mpz_t m, const mpz_t c, const mpz_t d, const mpz_t n) {\n mpz_powm(m, c, d, n);\n}\n</code></pre>\n\n<p>Alternatively, code could avoided the hidden \"pass-by-reference\":</p>\n\n<pre><code>void dec_alt3(mpz_t *m, const mpz_t c, const mpz_t d, const mpz_t n) {\n mpz_powm(*m, c, d, n);\n}\n</code></pre>\n\n<p><strong>Avoid casual sign changes</strong></p>\n\n<p>Code could have easily called <code>mpz_set_si (mpz_t rop, signed long int op)</code> rather than <code>mpz_set_ui (mpz_t rop, unsigned long int op)</code> and avoided a warning:</p>\n\n<pre><code>warning: \nconversion to 'long unsigned int' from 'long int' may change the sign of the result [-Wsign-conversion]\n</code></pre>\n\n<p>This implies the compilation was not done with <code>-Wsign-conversion</code> or its equivalent. </p>\n\n<p>Casual sign-ness changes are a source of bugs. Save time and enable the warning to help weed code of causal changes. There are at least 4 in OP's code.</p>\n\n<pre><code>long sd = 0;\nsd = rand();\n// mpz_set_ui(seed, sd);\nmpz_set_si(seed, sd);\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> This error make code not compilable, one of the reasons for closing the question. Let us count this as a copy/paste error. Still, better to be certain that the code <em>posted</em> compiles, not just the code on your computer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:09:46.230", "Id": "210824", "ParentId": "210685", "Score": "5" } } ]
{ "AcceptedAnswerId": "210697", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T09:36:35.357", "Id": "210685", "Score": "8", "Tags": [ "c", "reinventing-the-wheel", "cryptography", "gmp" ], "Title": "RSA c implementation" }
210685
<p>This program counts the number of the occurence of each character that is used in a file. </p> <p>I tried to use everything that Java offers to me properly. If you have tips which library functions would have been better, how to make the code more readable, than let me know. If you have a tip how to improve the performance I would be very thankful, also if the readability would decrease than.</p> <pre><code>import java.util.Map; import java.util.HashMap; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class Main { public static void main(String[] args) { if (args[0].contains("help")) { System.out.println("usage: java Main filename.txt"); } Map&lt;Character, Integer&gt; map = new HashMap&lt;&gt;(); char[] chars = fileToCharList(args[0]); for (int i = 0; i &lt; chars.length; i++) { if (map.containsKey(chars[i])) { Integer number = map.get(chars[i]); map.put(chars[i], ++number); } else { map.put(chars[i], 1); } } for (Map.Entry&lt;Character, Integer&gt; entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry. getValue()); } } private static char[] fileToCharList(String fileName) { File file = new File(fileName); StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader( file))) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString().toCharArray(); } } </code></pre>
[]
[ { "body": "<p>Your code is, in my opinion, well-written. It is readable and to the point. There a few things that I would like to point out that would fix a few bugs and help you improve your style:</p>\n\n<h2>1. Faulty Argument Checking</h2>\n\n<p>For your minimal argument checking, you simply detect if the first argument contains <code>\"help\"</code> anywhere. Therefore, it would not be able to process files like <code>helpme.txt</code>, <code>whelp.xyz</code>, <code>helpless</code>, or any file containing the characters of <code>\"help\"</code> in that order. </p>\n\n<p>I would suggest an alternative like checking for exactly the word <code>help</code> or counting the number of arguments (when an incorrect number of arguments is presented.</p>\n\n<p>In addition to that, the program should not continue if it detects that a filename was not presented. Or if it should continue, maybe prompt the user for input?</p>\n\n<h2>2. Simplification of Mapping Loop</h2>\n\n<p>You are extracting the value already present in the map against the given character to an <code>Integer</code> object. Then while reassigning the frequency, you are incrementing it with a prefix operator. I would discourage against that because you will only need the next integer in this instance and there is no need to reassign the variable.</p>\n\n<p>You are using a traditional indexed for-loop which </p>\n\n<p>There exists a method called <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-\" rel=\"nofollow noreferrer\"><code>getOrDefault</code></a> available for <code>Map</code>s, which we can use get rid of the <code>if</code> statement completely and use a single <code>put</code> statement.</p>\n\n<pre><code>for (char key : chars) {\n int frequency = map.getOrDefault(key, 0);\n map.put(key, frequency + 1);\n}\n</code></pre>\n\n<h2>3. Readable printing statement</h2>\n\n<p>If you are using Java 8 or above, use the functional programming features to make your code less verbose and more readable. I recommend using the <code>forEach</code> method.</p>\n\n<h2>4. Assign consistent names</h2>\n\n<p>When someone reads the method's name: <code>fileToCharList</code>, they will expect the return type to be a <code>java.util.List</code>, or one of its subclasses (like <code>ArrayList</code>, <code>LinkedList</code>, etc). If you want to return an array, rename the method <code>fileToCharArray</code> or simply <code>fileToChars</code>. This will help remove any possible ambiguity.</p>\n\n<h2>5. Simplifying the reading loop</h2>\n\n<p>Since all you do is read characters, there does not seem to be any special reason to proceed line-by-line. You will only skip over new lines with this approach. Instead, you could simply use a <code>FileReader</code> and keep on reading until <code>EOF</code> is reached (i.e. <code>-1</code> is returned).</p>\n\n<h2>The suggested update</h2>\n\n<p>Feel free to incorporate as much or as little of the changes I suggested. Here is the updated code for the complete picture:</p>\n\n<pre><code>import java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class Main {\n public static void main(String[] args) {\n if (args[0].contains(\"help\")) {\n System.out.println(\"usage: java Main filename.txt\");\n return; // No need to continue\n }\n\n Map&lt;Character, Integer&gt; map = new HashMap&lt;&gt;();\n char[] chars = fileToChars(args[0]);\n for (char key : chars) {\n int frequency = map.getOrDefault(key, 0);\n map.put(key, frequency + 1);\n }\n\n map.forEach((key, value) -&gt; System.out.println(key + \": \" + value));\n }\n\n private static char[] fileToChars(String fileName) {\n File file = new File(fileName);\n if (!file.exists()) {\n // Maybe do something here?\n }\n StringBuilder builder = new StringBuilder();\n try (FileReader reader = new FileReader(file)) {\n int input;\n while ((input = reader.read()) != -1) {\n // If you don't want to append certain characters\n // filter them out here.\n builder.append((char) input);\n }\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n return builder.toString().toCharArray();\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Update: Using ArrayList instead of StringBuilder</h2>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/33306/tinstaafl\">tinstaafl</a> pointed out, using an <code>ArrayList</code> would lead to simpler code and better performance for larger files, I decided to modify the code again:</p>\n\n<pre><code>// imports\n\npublic class Main {\n public static void main(String[] args) {\n // Same until this point\n\n Map&lt;Character, Integer&gt; map = new HashMap&lt;&gt;();\n List&lt;Character&gt; chars = fileToCharList(args[0]);\n for (char key : chars) {\n int frequency = map.getOrDefault(key, 0);\n map.put(key, frequency + 1);\n }\n\n map.forEach((key, value) -&gt; System.out.println(key + \": \" + value));\n }\n\n private static List&lt;Character&gt; fileToCharList(String fileName) {\n File file = new File(fileName);\n if (!file.exists()) {\n // Maybe do something here?\n }\n List&lt;Character&gt; list = new ArrayList&lt;&gt;();\n try (FileReader reader = new FileReader(file)) {\n int input;\n while ((input = reader.read()) != -1) {\n // If you don't want to append certain characters\n // filter them out here.\n list.add((char) input);\n }\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n return list;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T16:12:40.137", "Id": "407311", "Score": "0", "body": "Instead of returning a `char[]` in `fileToChars`, wouldn't it be better to use an arraylist, to store the characters directly, instead of converting the StringBuilder twice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T16:30:14.433", "Id": "407313", "Score": "0", "body": "@tinstaafl indeed. Using an `ArrayList` would simplify the code inside the method and retain the name that the OP originally used. I decided to stick to StringBuilder because it was in the original code. There shouldn't be any noticeable performance difference though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T16:53:52.767", "Id": "407315", "Score": "0", "body": "If the idea of your code is to show an improvement, it doesn't really make much sense to keep unimproved code there. the performance difference wouldn't be noticeable on relatively small files, but larger files wouldn't definitely show a difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:41:42.663", "Id": "407395", "Score": "1", "body": "Regarding point 2: `Map` has even more very practical methods. Using [`.merge()`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-) inside the loop would simplify it even more: `map.merge(key, 1, f -> f + 1);` This sets the value to `1` if no value has been assigned yet or adds one to the existing value." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T12:53:45.153", "Id": "210688", "ParentId": "210686", "Score": "0" } }, { "body": "<p>A couple of things I noticed:</p>\n\n<p>Using a TreeMap, instead of converting a StringBuilder to a char[] and creating the map, is much more efficient.</p>\n\n<p>You don't test for an empty argument list.</p>\n\n<p>Telling the user they have to use <code>.txt</code> in the filename is inaccurate as your code doesn't test for that.</p>\n\n<p>When you're printing multiple values on one line, it is more efficient and easier to maintain to use <code>printf</code>, rather than concatenating strings;</p>\n\n<p>Something like this will work:</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n if (args.length &lt; 1 || args[0].equals(\"help\")) {\n System.out.println(\"usage: java Main filename\");\n return;\n }\n fileToChars(args[0])\n .forEach((k, v) -&gt; System.out.printf(\"%1$s: %2$d\\n\", k, v));\n}\n\nprivate static TreeMap&lt;Character, Integer&gt; fileToChars(String fileName) throws IOException {\n final char EOF = (char) -1;\n File file = new File(fileName);\n TreeMap&lt;Character, Integer&gt; builder = new TreeMap&lt;&gt;();\n try (FileReader reader = new FileReader(file)) {\n Character input;\n while ((input = (char) reader.read()) != EOF) {\n Integer count = builder.getOrDefault(input, 0);\n builder.put(input, ++count);\n }\n } catch (IOException e) {\n throw new IOException(\"Problem reading file\");\n }\n return builder;\n}\n</code></pre>\n\n<p>This gives a sorted output of the mapped Characters. If an 'as is' output is wanted, change the <code>TreeMap</code> to a <code>HashMap</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:14:55.067", "Id": "210706", "ParentId": "210686", "Score": "1" } }, { "body": "<p>In addition to the other two answers, I would like to add this:</p>\n\n<h2>Prefer 'streaming' processing whenever possible.</h2>\n\n<p>Currently, you read the entire file to memory and even operate on it.</p>\n\n<p><code>builder.toString().toCharArray()</code> will even make the file be in memory <strong>twice</strong>, once as <code>String</code>, once as <code>char[]</code>.</p>\n\n<p>You could also process it line-by-line (or chunk-by-chunk, as you already use a <code>BufferedReader</code>. Have subresults returned and add it to the total result. That way you are far more memory-efficient.</p>\n\n<h2>Using as much standard Java functionality</h2>\n\n<p>Or, using the java 8 streams, for example:</p>\n\n<pre><code> Map&lt;Character, Long&gt; frequencyMap = \n Files.lines(Paths.get(filename)) //read the lines to a stream\n .flatMap(s-&gt; s.chars().mapToObj(c-&gt;(char)c)) //convert string stream to char stream\n .collect(\n Collectors.groupingBy( //collect to a map,\n Function.identity(), //key is the char\n Collectors.counting())); //value is the count\n</code></pre>\n\n<p>If you need a sorted end-result, sort after all the heavy lifting is done, this is better performance-wise:</p>\n\n<pre><code> SortedMap&lt;Characted, Long&gt; sortedFrequencyMap = \n new TreeMap&lt;Character, Long&gt;(frequencyMap);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T07:42:40.807", "Id": "210858", "ParentId": "210686", "Score": "0" } } ]
{ "AcceptedAnswerId": "210688", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T11:27:40.797", "Id": "210686", "Score": "3", "Tags": [ "java", "file" ], "Title": "Count characters of a text file" }
210686
<p>I wrote my own implementation of <strong>strlen</strong> and <strong>strcmp</strong> from C in x86 FASM and I would like to know is there anything that should be changed or improved.</p> <p><strong>strlen</strong> needs string in <strong>eax</strong> and is returning length of that string into <strong>ebx</strong>.</p> <pre><code>strlen: mov ebx,0 strlen_loop: cmp byte [eax+ebx],0 je strlen_end inc ebx jmp strlen_loop strlen_end: inc ebx ret </code></pre> <p><strong>strcmp</strong> needs two strings (one in <strong>eax</strong>, other in <strong>ebx</strong>) and returns into <strong>ecx</strong> <code>0</code> if strings are equal or <code>1</code>/<code>-1</code> if they are not.</p> <pre><code>strcmp: mov ecx,0 strcmp_loop: mov byte dl,[eax+ecx] mov byte dh,[ebx+ecx] inc ecx cmp dl,0 je strcmp_end_0 cmp byte dl,dh je strcmp_loop jl strcmp_end_1 jg strcmp_end_2 strcmp_end_0: cmp dh,0 jne strcmp_end_1 xor ecx,ecx ret strcmp_end_1: mov ecx,1 ret strcmp_end_2: mov ecx,-1 ret </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T13:43:52.177", "Id": "407295", "Score": "0", "body": "Welcome to Code Review! Does the current code work as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T13:47:42.343", "Id": "407296", "Score": "0", "body": "Its not full code that u can compile and run, but only code of my implementations of that functions. I checked both codes and I'm getting expected results, so I think it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:03:34.540", "Id": "407319", "Score": "0", "body": "Unless I am mistaken, strcmp does not return ecx=0 for identical strings. – strlen seems to include the trailing zero in the count, which is unconventional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:06:11.967", "Id": "407320", "Score": "0", "body": "I think that strcmp should return 0 for identical strings (https://www.quora.com/What-does-strcmp-mean-in-C++). In my implementation strlen includes trailing zero, so you don't need to add 1 to length everytime when you want to print this string" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:08:05.610", "Id": "407321", "Score": "1", "body": "@DeBos: What I meant is that *your implementation* does not return zero for identical strings, but the current value of ecx. Perhaps I am overlooking something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:13:59.197", "Id": "407322", "Score": "0", "body": "Yes you are right, I forgot this line." } ]
[ { "body": "<p><strong>Is the implementation complete?</strong></p>\n\n<p>From the manual pages of strcmp()</p>\n\n<blockquote>\n <p>The strcmp() and strncmp() functions return an integer less than,\n equal to, or greater than zero if s1 (or the first n bytes thereof)\n is found, respectively, to be less than, to match, or be greater\n than s2.</p>\n</blockquote>\n\n<p>Now if we take your strcmp function we have</p>\n\n<pre><code>strcmp:\n mov ecx,0\n strcmp_loop:\n mov byte dl,[eax+ecx]\n mov byte dh,[ebx+ecx]\n inc ecx\n cmp dl,0\n je strcmp_end_0\n cmp byte dl,dh\n je strcmp_loop\n jl strcmp_end_1\n jg strcmp_end_2\n strcmp_end_0:\n cmp dh,0\n jne strcmp_end_1\n xor ecx,ecx\n ret\n strcmp_end_1:\n mov ecx,1\n ret\n strcmp_end_2:\n mov ecx,-1\n ret\n</code></pre>\n\n<p>The first string goes to eax and the second to ebx. When eax is shorter than ebx, the null byte of eax is read first so. <code>cmp dl,0</code> is going to be true first. Therefore, it jumps to strcmp_end_0. At strcmp_end_0 if ebx has got any other byte than 0, the function returns 1. But if string in eax is smaller than ebx, it should return an integer less than 0.</p>\n\n<p>Also suppose the strings were:</p>\n\n<p><code>eax=[0x03,0x03,0x04,0x00]</code> \nand \n<code>ebx=[0x03,0x03,0x03,0x00]</code></p>\n\n<p><code>cmp byte dl,dh</code> at the third byte is +ve. Therefore,after <code>jg strcmp_end_2</code> the function returns -1. Shouldn't it return 1 since eax>ebx?</p>\n\n<p>A simple fix would be to move eax to dh and ebx to dl.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:11:34.240", "Id": "407327", "Score": "0", "body": "I think you are right. I'll just swap 1 and -1 and it should be good now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T19:17:04.853", "Id": "450619", "Score": "2", "body": "@DeBos99: After you find a stopping place (end or difference), you can sign-extend the chars and subtract one from the other to get a + / 0 / - result. That removes the need for 3-way branching. Even if you didn't do that, you only need two `jcc` along any given path if you lay out your branches carefully. This answer unfortunately doesn't say anything about simplifying the branching, or the inefficiency of writing DL and DH on CPUs other than mainstream Intel (false dependency if DH isn't renamed separately from DL or at least from the rest of EDX)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:07:17.457", "Id": "210704", "ParentId": "210689", "Score": "3" } }, { "body": "<p></p>\n\n<h2>strlen</h2>\n\n<ul>\n<li>We generally prefer smaller instructions. To zero the <code>EBX</code> register we normally use <code>xor ebx, ebx</code>. This is a 2-byte instruction where <code>mov ebx, 0</code> is a 5-byte instruction. </li>\n<li>Loops get faster if they include less jumping. Your <em>strlen_loop</em> has 2 jump-instructions per iteration. You can easily do this with a single conditional jump-instruction.</li>\n</ul>\n\n<p>Next code does exactly what your code does. Notice that by placing the <code>inc ebx</code> instruction early in the loop, you no longer need the separate <code>inc ebx</code> to include the terminating zero in the returned count.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; IN (eax) OUT (ebx=1+)\nstrlen:\n xor ebx, ebx\n strlen_loop:\n inc ebx\n cmp byte [eax+ebx-1], 0 ; Zero-terminator ?\n jne strlen_loop\n ret\n</code></pre>\n\n<p>Usually the returned count does not contain the terminating zero. Next code will deal with that situation:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; IN (eax) OUT (ebx=0+)\nstrlen:\n xor ebx, ebx\n dec ebx\n strlen_loop:\n inc ebx\n cmp byte [eax+ebx], 0 ; Zero-terminator ?\n jne strlen_loop\n ret\n</code></pre>\n\n<p>The 2 instructions <code>xor ebx, ebx</code> and <code>dec ebx</code> in a row are still shorter than <code>mov ebx, -1</code>.</p>\n\n<hr>\n\n<h2>strcmp</h2>\n\n<ul>\n<li>Characters in a string are to be considered as <strong>unsigned</strong> quantities. Therefore you should not use the <code>jl</code> (jump if less) nor the <code>jg</code> (jump if greater) instructions.<br>\nFor unsigned comparisons we use <code>jb</code> (jump if below) and <code>ja</code> (jump if above).</li>\n<li>To check if a register holds a zero you can <code>test</code> the register with itself. This produces smaller code.</li>\n<li>In a sequence like <code>je ...</code> <code>jl ...</code> <code>jg ...</code>, the 3rd conditional jump is redundant as it is always true. This is the perfect occasion to just fall through in the program.</li>\n</ul>\n\n<p>Next code applies these recommendations:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>; IN (eax,ebx) OUT (ecx={-1,0,1}) MOD (edx)\nstrcmp:\n xor ecx, ecx\n strcmp_loop:\n mov dl, [eax+ecx]\n mov dh, [ebx+ecx]\n inc ecx\n test dl, dl\n jz strcmp_end_s1\n cmp dl, dh\n je strcmp_loop\n jb strcmp_below\n strcmp_above:\n xor ecx, ecx ; s1 bigger than s2\n inc ecx\n ret ; ECX = 1\n strcmp_below:\n xor ecx, ecx ; s1 smaller than s2\n dec ecx\n ret ; ECX = -1\n strcmp_end_s1:\n test dh, dh\n jnz strcmp_below ; s1 shorter than s2\n xor ecx, ecx ; s1 same as s2\n ret ; ECX = 0\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov byte dl,[eax+ecx]\nmov byte dh,[ebx+ecx]\ncmp byte dl,dh\n</code></pre>\n</blockquote>\n\n<p>FASM, like most assemblers, does not require you to write these redundant size tags. The name of the register <code>DL</code>/<code>DH</code> already says that the size is <em>byte</em>.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mov dl, [eax+ecx]\nmov dh, [ebx+ecx]\ncmp dl, dh\n</code></pre>\n\n<hr>\n\n<p>It's always a good idea to write some comments in the program.<br>\nSee how describing the 3 possible exits on <em>strcmp</em> makes for a more readable code!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T19:45:28.177", "Id": "210990", "ParentId": "210689", "Score": "3" } }, { "body": "<h1>strlen</h1>\n\n<ol>\n<li><p><strong>Correctness (Return Value):</strong> You are violating the convention for the <code>strlen</code> function, which is documented as returning the number of characters between the beginning of the string and the terminating null character <em>without including the terminating NUL character</em>. Your code includes the terminating NUL, given the position of the <code>inc ebx</code> instruction.</p>\n\n<p>This may be fine if you control both the function's implementation and its usage, but it is confusing because it defies programmers' expectations and will be a recurring source of bugs. If you're going to return a length that includes the terminating NUL, you should consider calling your function something different than <code>strlen</code>.</p></li>\n<li><p><strong>Interface (ABI):</strong> All x86 calling conventions return a function's result in the <code>eax</code> register. Although you have documented your function as returning the result in <code>ebx</code>, this is utterly bizarre and is guaranteed to trip up every programmer who ever uses your code. When writing everything in assembly, you are of course free to define your own custom calling conventions, but you should only do so when there is a good reason (like an optimization possibility). I can't see a good reason here. It would be just as easy for you to arrange for your code to produce the result in <code>eax</code>, right where programmers will expect it to be.</p>\n\n<p>It is also somewhat unusual to pass an argument in the <code>eax</code> register, but calling conventions vary in which registers they use to pass arguments, so this isn't flying in the face of every convention ever and is therefore more excusable. However, when you're writing in assembly and you have the opportunity to make these types of decisions, you should consider your choices carefully: what makes the most sense? what will be the easiest to use? what will be the most flexible? what will be the most efficient? Have a good reason for your choice! In this case, passing a pointer in <code>eax</code> makes little sense, since <code>eax</code> is almost universally used for return values, and pointers are almost never going to be the return value of a function. By choosing <code>eax</code> as the input register, you've virtually guaranteed that every caller will need an extra <code>mov</code> instruction to shuffle the input parameter into the appropriate register. Why create this situation when you don't have to?</p></li>\n<li><p><strong>Style (Indentation):</strong> The way you've indented the code, with the labels at the same level as the instructions, makes it difficult to read because all of the instructions aren't lined up. Instead, consider outdenting the internal labels (branch targets) so that they match the function name (external symbols). That will allow all instructions in the function to be lined up at the same vertical column, and thus allow anyone reading the code to skim it easily.</p>\n\n<p>(The only drawback of this is that it makes it a bit harder to determine what is a function label and what is an internal label. Judicious use of whitespace is the most effective way to combat this. I also use a naming convention that allows me to recognize the difference at a glance.)</p>\n\n<p>Also, use variable numbers of spaces between the opcode and the operands to ensure that all operands line up in vertical columns.</p></li>\n<li><p><strong>Style (Documentation):</strong> Maybe you have extensive external documentation that accompanies these functions, but probably not. Even if you do, documentation <em>right in the code</em> is extremely useful, easier to maintain, and should not be forsaken without a very good reason.</p>\n\n<p>When writing functions in assembly, I use kind of a standard header containing a description, the inputs, the outputs, and the clobbers. If there are any assumptions made by the function, I will also call those out explicitly. So, in this case, following what you had documented in the question (even though I just called it into question), I'd write something like this:</p>\n\n<pre><code>; Determines the length of a C-style NUL-terminated string.\n; \n; Inputs: EAX = address of beginning of string buffer\n; Outputs: EBX = length of the string, including the NUL terminator\n; Clobbers: &lt;none&gt;\n</code></pre>\n\n<p>You should feel free to develop your own style. The important thing is having this information at the ready. <em>Especially</em> when programming in assembly where you can (and should) invent your own per-function custom calling conventions.</p></li>\n<li><p><strong>Optimization (Register Clearing):</strong> There is only one circumstance in which you should use <code>mov reg, 0</code>, and that's when you're trying to avoid clobbering the flags (<em>e.g.</em>, in a sequence that contains a <code>CMOVxx</code> or a <code>SETxx</code>). In all other cases, you should clear a register by XORing it with itself: <code>xor reg, reg</code>. Peter Cordes has written a comprehensive explanation of the reasons why <a href=\"https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and\">here</a>, but it's enough to just remember the rule. Basically, it's shorter (and thus faster) and it breaks dependencies (which is sometimes important, and never hurts).</p></li>\n<li><p><strong>Optimization (Reduce Branching):</strong> <a href=\"https://stackoverflow.com/questions/40991778/an-expensive-jump-with-gcc-5-4-0/40993519#40993519\">When you want performance, avoid branching</a>. That means that you should minimize branching as much as possible inside tight inner loops. <code>strlen</code> is the canonical example of a tight loop. You've got two branches inside of the loop, a conditional <code>je</code> and an unconditional <code>jmp</code>. Consider rearranging the code so that you only have one. This is almost always possible. Ideally, you want the common case to fall through and the unusual case to branch, but even if that's not possible, it's still better to have a single branch than several of 'em.</p></li>\n<li><p><strong>Optimization (Elide Repeated Instructions):</strong> You've repeated the <code>inc ebx</code> instruction. Consider how the code can be rearranged to avoid the need to do this. This isn't just the standard <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> advice, but a potential optimization opportunity. However, sometimes this trades off with the previous advice about reducing branching. Repeating a simple instruction in order to avoid a branch is virtually always worth it. As is arranging code so that you, say, speculatively increment inside of the loop, only to undo it by decrementing outside of the loop.</p></li>\n<li><p><strong>Optimization (Memory Access):</strong> In C terms, your code is maintaining an \"index\" into the string. That means you have to do a complex load-and-compare (<code>cmp byte [eax+ebx], 0</code>). You could instead maintain a \"pointer\" into the string, which would allow you to just do <code>cmp byte [eax], 0</code>. This is not only 1 byte shorter, but may execute more quickly.</p></li>\n</ol>\n\n<p>Consider:</p>\n\n<pre><code>; Determines the length of a C-style NUL-terminated string.\n; \n; Inputs: EBX = address of beginning of string buffer\n; Outputs: EAX = length of the string, including the NUL terminator\n; Clobbers: CL, flags\nstrlen:\n lea eax, [ebx + 1]\n\nstrlen_loop:\n mov cl, byte [eax]\n inc eax\n test cl, cl\n jnz strlen_loop\n\n sub eax, ebx\n ret\n</code></pre>\n\n<p>This is about the most efficient way of implementing a standard <code>strlen</code> function:</p>\n\n<ul>\n<li>The <code>lea</code> is used as a super-<code>mov</code>, allowing the value in <code>ebx</code> to be copied into <code>eax</code>, while simultaneously incrementing it by 1. (Although <code>mov</code>+<code>inc</code> would have been the same length in terms of bytes, <code>lea</code> might be slightly more efficient on certain processors.) <code>ebx</code> will remain a pointer to the <em>beginning</em> of the string, while <code>eax</code> will be a pointer to the <em>current location</em> in the string.</li>\n<li>Inside of the loop, the CISC-style <code>cmp</code> instruction that took a memory operand has been split up into separate RISC-style <code>mov</code>+<code>test</code> instructions for improved scheduling. In particular, this means we can do an <code>inc</code> of the pointer after loading the value that it pointed to. We couldn't do the <code>inc</code> after the <code>cmp</code>, because the <code>inc</code> would clobber the flags (in particular, the zero flag) that we were going to try and read. In this arrangement, the <code>test</code> can also macro-fuse with the <code>jnz</code> instruction.</li>\n<li>I've written <code>jnz</code> instead of <code>jne</code> even though they result in identical opcodes because I think it's a better mnemonic in this case. We are <code>test</code>ing the value, and then jumping if it is <em>n</em>ot <em>z</em>ero (<em>i.e.</em>, if the current character is not the NUL character).</li>\n<li>Outside of the loop, we do a final <code>sub</code>traction of the current pointer from the starting pointer, which gives us the length of the string, not including the terminating null.</li>\n</ul>\n\n<p>The biggest drawback is that we've introduced the use of an additional register (the 8-bit <code>cl</code>), which expands our \"Clobbers\" list in the documentation. See why documenting this is important? The only reason why this would be a drawback, of course, is if the caller/consumer of this function needed to preserve the value in <code>cl</code>, as that would require an extra instruction or two. However, those instructions would be outside of the loop, and thus off the critical path, so it's almost certainly worth it for the optimizations gained.</p>\n\n<p>Interestingly, this is basically the same code that Microsoft's C compiler will emit for a <code>strlen</code> operation when you have intrinsics enabled (otherwise, it'll generate a call to the <code>strlen</code> standard library function, which has essentially this same code inside of it).</p>\n\n<p>This is better than <a href=\"/a/210990\">Sep Roland's optimized implementation</a> because it avoids the <a href=\"https://www.phatcode.net/res/224/files/html/ch21/21-01.html\" rel=\"noreferrer\">AGI stall</a> introduced by this sequence of instructions in Sep's code:</p>\n\n<pre><code>inc ebx\ncmp byte [eax+ebx-1], 0\n</code></pre>\n\n<p>Sep is being similarly clever here, doing the <code>inc</code> first and then undoing it inside of the <code>cmp</code> to avoid clobbering flags, but modifying <code>ebx</code> immediately before you use it in the addressing operands list for <code>cmp</code> results in a potential stall. Reordering the instructions avoids the stall; even though we had to add one extra instruction, the performance improvement more than makes up for it (unless you're optimizing for size, which you aren't, unless you're code-golfing&mdash;it's only a 1-byte difference).</p>\n\n<p>So, this looks pretty good, right? Indeed, it is. As I said, it's about the best you're going to do for a straightforward, literal translation of <code>strlen</code> into assembly. But if you <a href=\"http://www.jagregory.com/abrash-zen-of-asm/\" rel=\"noreferrer\">stretch your mind a bit</a>, you can do better.</p>\n\n<p>The slowest part of this code is the <code>mov cl, byte [eax]</code> instruction that accesses memory at the beginning of every iteration of the loop. There's nothing we can do about the fact that we have to access memory, but notice that we're only reading 1 byte at a time here. Under the hood, the processor only does DWORD-sized reads, so it's actually reading 4 bytes and then throwing away all but the lowest-order byte. Why don't we just read 4 bytes at a time? Then, we can parallelize the code to actually deal with 4 bytes at a time, effectively unrolling the loop by a factor of 4.</p>\n\n<p>The trick to parallelizing the code is figuring out an efficient way of checking all 4 of the bytes that we load in each iteration of the loop for NUL characters.</p>\n\n<p>One possible attempt is the following (MASM syntax, sorry):</p>\n\n<pre><code>; Determines the length of a C-style NUL-terminated string.\n; \n; Inputs: EBX = address of beginning of string buffer\n; Outputs: EAX = length of the string, including the NUL terminator\n; Clobbers: ECX, flags\nstrlen:\n mov ecx, ebx\n\nALIGN 16\nCountChars:\n mov eax, DWORD PTR [ecx] \n\n test al, al \n jz SHORT ReturnLength \n inc ecx\n\n test ah, ah \n jz SHORT ReturnLength \n inc ecx\n\n test eax, 0x00FF0000 \n jz SHORT ReturnLength \n inc ecx\n\n test eax, 0xFF000000 \n jnz SHORT CountChars \n\nReturnLength:\n sub ecx, ebx \n mov eax, ecx \n ret \n</code></pre>\n\n<p>I've introduced an alignment of the branch target (<code>CountChars</code>) because aligned branch targets are more efficient, and it makes a measurable difference here because we're branching to that location a lot (each time we loop). When optimizing for code speed over size, this is a no-brainer.</p>\n\n<p>There are obvious variations on this theme, especially with regard to register assignment. You might ask, why not use <code>eax</code> for the pointer to the current location in the string buffer, as that would eliminate the need for the penultimate <code>mov</code> instruction. There is a good reason I didn't, though: using <code>eax</code> to hold the character being tested inside of the loop makes the latter two <code>test</code> instructions (the ones that use immediate operands) 1 byte shorter than if any other register had been used. (Certain x86 instructions have optimized encodings when <code>eax</code> is the destination register for legacy reasons.) This doesn't normally matter too much, but it can help to ensure that a loop fits entirely within the cache. A 2-byte <code>mov</code> outside of the loop is a small price to pay for a 2-byte size reduction of the code inside the loop.</p>\n\n<p>Details aside, this does get the job done with respect to testing 4 bytes at a time. But is it efficient? It feels like it might not be, because there's so much branching. Indeed, our \"avoid branches in inner loops\" intuition is right on, as this version is <em>not</em> significantly faster than the original. On modern architectures like Haswell, it's slightly faster; on older architectures, like Pentium 4 (where branch mispredictions are extremely expensive due to extremely long pipelines), it is slightly slower. In either case, the time delta is not even enough to matter. So this appears to be a dead-end. We bought ourselves a little bit of performance by reading a DWORD at a time, instead of a single byte, but any advantage gained is lost to all of the conditional branches that need to be executed each iteration of the loop.</p>\n\n<p>In order to gain a real performance improvement, we need to take a different tack. And it needs to be one that reduces the number of branches. If we can find a branchless way to test all 4 bytes of the DWORD at once to see if any of them are 0 (a NUL byte), then we can reduce the number of branches in all but one iteration of the loop by a factor of 4. As it turns out, there is a solution for this, as described on the <a href=\"https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord\" rel=\"noreferrer\">Bit Twiddling Hacks</a> page. </p>\n\n<p>Consider the following implementation (again in MASM syntax). It retrieves a DWORD and performs a series of bit manipulations on that value to determine if any of its byte are zero (i.e., contain NUL characters). If not, it branches back to the top and starts over with another DWORD-sized chunk of the string. If so, then it falls through and tests each of the four individual bytes (or, more accurately, three of the individual bytes, since if the low-order three bytes are non-zero, then we know the highest-order byte must be zero).</p>\n\n<pre><code>; Determines the length of a C-style NUL-terminated string.\n; \n; Inputs: EBX = address of beginning of string buffer\n; Outputs: EAX = length of the string, including the NUL terminator\n; Clobbers: ECX, flags\nstrlen:\n mov ecx, ebx ; save pointer to beginning of string for later\n\nALIGN 16\nCountChars:\n mov eax, DWORD PTR [ebx] ; load DWORD value from current offset\n add ebx, 4 ; increment offset by number of bytes processed\n and eax, 0x7F7F7F7F ; mask out highest bit of each byte\n sub eax, 0x01010101 \n test eax, 0x80808080 ; TEST to ensure macro-op fusion with JZ\n jz SHORT CountChars ; if none of these 4 bytes were 0, start again with 4 more\n\n mov eax, DWORD PTR [ebx-4] ; load previous 4 bytes (the ones we were just testing),\n ; using an immediate offset to compensate for eager\n ; increment in the loop while avoiding an AGI stall\n\n test al, al ; test low byte for NUL\n jz SHORT ReturnLength\n inc ebx ; wasn't the first byte, so increment byte count\n\n test ah, ah ; test the second byte for NUL\n jz SHORT ReturnLength\n inc ebx ; wasn't the second byte, so increment byte count\n\n test eax, 0x00FF0000 ; test the third byte for NUL\n jz SHORT ReturnLength\n inc ebx ; wasn't the third byte, so has to be the fourth (high) byte\n\nReturnLength:\n lea eax, [ebx - 4] ; undo the eager 4-byte increment; put result in EAX\n sub eax, ecx ; subtract starting pointer from current pointer\n ret\n</code></pre>\n\n<p>As it turns out, this is precisely the parallelization strategy taken by GLIBC (the C standard library implementation used by the GNU project, including the GCC compiler). The relevant code, including extensive descriptive comments, is available <a href=\"http://tsunanet.net/~tsuna/strlen.c.html\" rel=\"noreferrer\">here</a>; see also <a href=\"http://stackoverflow.com/q/20021066\">http://stackoverflow.com/q/20021066</a> and <a href=\"http://stackoverflow.com/q/11787810\">http://stackoverflow.com/q/11787810</a>. This parallelized implementation is <em>significantly</em> faster on all x86 architectures than our previous \"best\" code&mdash;you're looking at around a 2&times; speedup. </p>\n\n<p>I was pretty proud of this, until I thought some more and realized that there's no need to <em>retest</em> each of the 4 bytes. They were already tested in the initial bit-twiddling, and our answer about which of those 4 bytes contains the 0 is already available in the result of that bit-twiddling&mdash;we just need to extract it! This is great, because it eliminates three more branches, the three least likely to be correctly predicted (which of the 4 bytes actually contains the NUL is essentially random), and also the three most likely to enact a performance cost (since they are all back-to-back). It also saves us from having to reload the same 4 bytes again from memory.</p>\n\n<pre><code>; Determines the length of a C-style NUL-terminated string.\n; \n; Inputs: EBX = address of beginning of string buffer\n; Outputs: EAX = length of the string, including the NUL terminator\n; Clobbers: ECX, flags\nstrlen:\n mov ebx, DWORD PTR [psz]\n xor ecx, ecx\n\nALIGN 16\nCountChars:\n mov eax, DWORD PTR [ebx+ecx]\n add ecx, 4 \n and eax, 0x7F7F7F7F\n sub eax, 0x01010101\n and eax, 0x80808080 ; must be AND here b/c we need result (but may not fuse)\n jz SHORT CountChars\n\n ; At this point, EAX will contain one of the following values:\n ; - 0x80808080 (if the low byte---byte 0---contained the 0)\n ; - 0x80808000 (if byte 1 contained the 0)\n ; - 0x80800000 (if byte 2 contained the 0)\n ; - 0x80000000 (if the high byte, byte 3, contained the 0)\n bsf eax, eax ; find the first set bit, which gives either 7, 15, 23, or 31\n sub ecx, 4 ; undo the eager increment by 4 from the loop\n shr eax, 3 ; shift right by 3 (7 =&gt; 0, 15 =&gt; 1, 23 =&gt; 2, 31 =&gt; 3),\n ; thus giving the index of the NUL byte\n add eax, ecx ; add that byte index to the length, thus giving total length\n ret\n</code></pre>\n\n<p>This doesn't actually save a whole lot of time compared to the branching version, since the compare-and-branch sequence only gets executed once for each string. But, it does generally provide a minor performance boost, and it is never slower. This is true for all string lengths; there's no hidden overhead. Most of the cost comes from the relatively-expensive BSF operation. And, note that BSF is slower on AMD processors than Intel, so this code may be slightly less optimal on AMD, especially since AMD tends to use shorter pipelines and thus have less expensive branch mispredictions.</p>\n\n<p>Now, I won't say that this is the fastest possible implementation, because <a href=\"https://blog.codinghorror.com/there-aint-no-such-thing-as-the-fastest-code/\" rel=\"noreferrer\">there ain't no such thing as the fastest code</a>, but it's pretty respectable. I'd even say it's <em>about</em> as good as you're going to get with bog-standard x86 instructions.</p>\n\n<p>There is another frontier, and that is to use SIMD instructions (whether MMX, SSE 2, or SSE 4.2). This makes possible further substantial speed improvements, but my answer is much too long already, so I'll have to leave this stone unturned, since it is even more complicated to explain.</p>\n\n<p>[NOTE: There's a fair amount of hand-waving in this answer with regards to which optimizations are sensible and what the performance differences are. I've actually done <em>extensive</em> benchmarking of this exact code before, on a variety of different x86 family architectures (mostly Intel), but I've left those details out of this answer for brevity (hah!). You'll just have to take my word for it. Or ask a question about it on Stack Overflow.]</p>\n\n<hr>\n\n<h1>strcmp</h1>\n\n<p>Aren't you tired of reading yet?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T23:45:49.750", "Id": "413196", "Score": "0", "body": "Thanks for review @Cody Gray. I'm very thankful for this big piece of advice for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T22:44:06.213", "Id": "413922", "Score": "0", "body": "Already an impressive review but I found several problems with the presented code snippets. The **1st** snippet will not digest an empty string because the first byte of the buffer is never read. This could lead to memory access problems as well. The **2nd** snippet does not traverse the buffer in steps of 4 bytes because there're but 3 `inc ecx` 's. You'll want the extra `inc ecx` right before `test al, al`. The **3rd** and **4th** snippets don't return the length *including the terminating zero* as is stated under \"Outputs: ... \"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T19:43:01.273", "Id": "450623", "Score": "1", "body": "See [Is it safe to read past the end of a buffer within the same page on x86 and x64?](//stackoverflow.com/q/37800739) - only if you align your pointer first. You need to say that these functions are only safe for 4-byte aligned pointers, or add startup handling that reaches an alignment boundary (maybe just a scalar loop of `pointer & 3` iterations)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T19:50:50.270", "Id": "450624", "Score": "0", "body": "How does `tzcnt` compare to `bsf`? GCC optimizes a C-version of this code with `-O3` into a `tzcnt` instruction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T20:58:43.267", "Id": "450634", "Score": "1", "body": "@JL2210 `tzcnt` is encoded as `rep bsf`. It's a fully backwards-compatible encoding, and compilers often use `tzcnt` as a drop-in replacement for `bsf` (the `rep` prefix to `bsf` is just ignored on CPUs that don't support `tzcnt`). `tzcnt` and `bsf` produce the same results for all values where `bsf` is defined. The difference is that `bsf` has UB when the input operand is zero, whereas the result of `tzcnt` is well-defined for zero inputs as the maximum number of bits (based on the operand size). If you know input is non-zero, it's a drop-in replacement. If not, there are workarounds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T21:03:27.407", "Id": "450635", "Score": "1", "body": "Kinda too much detail for a comment, but…If you use `tzcnt` as the encoding, then it will execute as `tzcnt` on processors that support it. That means only on older processors will it execute as `bsf`, and you can test exactly what the semantics are of `bsf` on those older processors. You don't have to worry about forwards-compatibility (i.e., changes in behavior). You know that on AMD and Intel (AMD documents it; Intel leaves it formally undefined) that `bsf` on 0 inputs is not going to change the output reg. So, you can pre-set the output register to be the value that you want in the 0 case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-28T02:11:00.800", "Id": "451309", "Score": "0", "body": "@JL2210: `bsf` is slow on AMD, both are fast on Intel, so compilers usually spend the extra byte to make it run as `tzcnt` on CPUs where that's helpful. Also `tzcnt` has no output dependency on SKL and later. Note that `bsf` on zero inputs is not UB in the C sense of the word: it doesn't cause unpredictable behaviour for your whole program or the whole CPU. According to Intel's docs it produces an undefined output value, but is still guaranteed to set ZF according to the input. As Cody says, AMD documents the stronger behaviour that AMD and Intel both actually implement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-28T10:54:10.337", "Id": "451331", "Score": "0", "body": "@PeterCordes Ah, that explains why `tzcnt` is only used when compiling with -O2 and -O3, but not -Os." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:34:50.023", "Id": "452843", "Score": "0", "body": "This reacts oddly when it encounters `0x80` bytes. How do you circumvent that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:41:09.903", "Id": "452847", "Score": "1", "body": "Write better test cases, I guess? I don't remember coming across that. I thought I had tested over the entire range of `char`s. Perhaps I only tested over the entire range of *ASCII*, which wouldn't include a 0x80 byte. What do you mean by \"oddly\"? I suppose you're talking about the bit-twiddling hack to determine whether a DWORD contains any zero bytes. A 0x80 byte is a false-positive? That caveat is mentioned on the [Bit Twiddling Hacks](https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord) page, to which I referred. I forget now which approach I used. Could be refined. @JL2210" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:44:23.263", "Id": "452848", "Score": "0", "body": "False positive." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T05:55:18.897", "Id": "213558", "ParentId": "210689", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T13:11:28.500", "Id": "210689", "Score": "6", "Tags": [ "strings", "reinventing-the-wheel", "assembly", "x86" ], "Title": "strlen and strcmp implementation in x86 FASM assembly" }
210689
<p>I wrote an algorithm to transform mouse screen coordinates within an isometric map to corresponding coordinates of an underlying 2D-square grid. The algorithm works and I tested it successfully. I wanted to post it here so interested people could maybe check the algorithm and see if I can make any optimizations beyond of what I did already. My goal is to make the algorithm as compact as possible. There maybe are some smart mathematical solutions I didn't think of to save some lines of code or make it faster.</p> <p>The input data for the rendering of the map is a simple 2D-array like:</p> <pre><code>0,0,0,0 0,0,0,0 0,0,0,0 ... </code></pre> <p>Here is a screenshot of what the map looks like when rendered. It is not really a map right now but more of an outlining of the tiles I will render. The red coordinates are x and y values of the underlying source grid.</p> <p><a href="https://i.stack.imgur.com/ulJ8b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ulJ8b.png" alt="enter image description here"></a></p> <p>It is rendered with a zig-zag approach with an origin outside of the screen (top left). It is rendered row by row from left to right whereby every uneven row is inset by half a tiles width. This is a common approach to avoid having to fill the source 2D-grid with "zombie-data" if one would render it in a diamond approach.</p> <p>What the algorithm does is:</p> <ul> <li>the screen is logically divided into square rectangles with a width of my tile width and height of my tile height, i.e. 128px by 64px</li> <li>the mouse coordinates are scaled by tile width and tile height and then floored. This determines in which screen rectangle the user clicked</li> <li>then the mouse coordinates are compared against the center coordinates of this rectangle</li> <li>regarding this result, a right angled triangle is calculated to check if the user clicked within a certain area of the rectangle. I am using the cosine of this triangle to compare against my initial rotation angle of 26,565 (atan of 0.5). This is the angle in which the sides of the rendered rhombi are rotated to achieve a 2:1 ratio of width and height (classic isometric projection for video games).</li> <li>regarding on where the user clicked <ul> <li>the y value is determined from a lower and upper boundary</li> <li>the x value is determined based on y being even or uneven</li> </ul></li> </ul> <p>To run this code, you will need SDL2-2.0.9 and boost 1.67.0. to run. I am using MS Visual Studio Community 2017 as an IDE.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;SDL.h&gt; #include &lt;SDL_Image.h&gt; #include &lt;boost/cast.hpp&gt; struct Point { std::size_t x; std::size_t y; }; Point mouseToGrid(int pMouseXPos, int pMouseYPos, std::size_t pTileWidth, std::size_t pTileHeight, const double PI, const int SCREEN_WIDTH, const int SCREEN_HEIGHT) { double mouseXPos = boost::numeric_cast&lt;double&gt;(pMouseXPos); double mouseYPos = boost::numeric_cast&lt;double&gt;(pMouseYPos); double tileWidth = boost::numeric_cast&lt;double&gt;(pTileWidth); double tileHeight = boost::numeric_cast&lt;double&gt;(pTileHeight); double tileWidthHalf = tileWidth / 2; double tileHeightHalf = tileHeight / 2; double mouseTileYPos = mouseYPos / tileHeight; mouseTileYPos = std::floor(mouseTileYPos); int screenRectCenterX = ((std::floor((mouseXPos / tileWidth))) * tileWidth) + tileWidthHalf; int screenRectCenterY = (mouseTileYPos * tileHeight) + tileHeightHalf; //determine lower and upper boundary for y int minY = boost::numeric_cast&lt;int&gt;(2 * mouseTileYPos); int maxY = boost::numeric_cast&lt;int&gt;((2 * mouseTileYPos) + 1); if (mouseYPos &gt;= screenRectCenterY) { minY = maxY; maxY++; } //calc triangle sides in pixels char mouseRectangleSector[2]{}; double opposite; double adjacent; if (mouseYPos &gt;= screenRectCenterY) { mouseRectangleSector[0] = 'S'; opposite = mouseYPos - screenRectCenterY; } else { mouseRectangleSector[0] = 'N'; opposite = screenRectCenterY - mouseYPos; } if (mouseXPos &gt;= screenRectCenterX) { mouseRectangleSector[1] = 'E'; adjacent = (screenRectCenterX + tileWidthHalf) - mouseXPos; } else{ mouseRectangleSector[1] = 'W'; adjacent = tileWidthHalf - (screenRectCenterX - mouseXPos); } double hypothenuse = std::sqrt(std::pow(opposite, 2) + std::pow(adjacent, 2)); //calculate cos and corresponding angle in rad and deg double cos = adjacent / hypothenuse; double angleRad = std::acos(cos); double angleDeg = angleRad * 180 / PI; //calculate initial rotation angle in rad and deg double controlAtan = 0.5; double controlAngleRad = std::atan(controlAtan); double controlAngleDeg = controlAngleRad * 180 / PI; //determine final position for y if (mouseRectangleSector[0] == 'S') { if (angleRad &gt; controlAngleRad) { mouseTileYPos = maxY; } else { mouseTileYPos = minY; } } else { if (angleRad &lt; controlAngleRad) { mouseTileYPos = maxY; } else { mouseTileYPos = minY; } } //determine position for x double mouseTileXPos; if ((boost::numeric_cast&lt;int&gt;(mouseTileYPos)) % 2 == 0) { mouseTileXPos = (mouseXPos + tileWidthHalf) / tileWidth; } else { mouseTileXPos = mouseXPos / tileWidth; } mouseTileXPos = std::floor(mouseTileXPos); Point gridXY{(std::size_t)mouseTileXPos, (std::size_t)mouseTileYPos}; return gridXY; } int main(int argc, char *args[]) { const double PI = 3.1415926535897932384626433832795; const int SCREEN_WIDTH = 1600; const int SCREEN_HEIGHT = 900; //init SDL Components if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { return 1; } SDL_Window *sdlWindow = SDL_CreateWindow("A New Era", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); SDL_Renderer *sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (sdlWindow == nullptr) { SDL_DestroyWindow(sdlWindow); SDL_Quit(); return 1; } if (sdlRenderer == nullptr) { SDL_DestroyWindow(sdlWindow); SDL_DestroyRenderer(sdlRenderer); SDL_Quit(); return 1; } if (!(IMG_Init(IMG_INIT_PNG))) { SDL_DestroyWindow(sdlWindow); SDL_DestroyRenderer(sdlRenderer); SDL_Quit(); return 1; } SDL_SetRenderDrawColor(sdlRenderer, 0, 0, 0, 255); SDL_RenderClear(sdlRenderer); SDL_SetRenderDrawColor(sdlRenderer, 255, 255, 255, SDL_ALPHA_OPAQUE); //tile dimensions std::size_t tileWidth = 128; std::size_t tileHeight = 64; std::size_t tileWidthHalf = tileWidth / 2; std::size_t tileHeightHalf = tileHeight / 2; int originX = 0; int originY = 0; int xScreenOffset; int yScreenOffset = 0 - tileHeightHalf; //add pseudo data points to tile vector std::vector&lt;Point&gt; mapTiles{}; for (std::size_t y = 0; y &lt; 10; y++) { for (std::size_t x = 0; x &lt; 10; x++) { Point point{x, y}; mapTiles.push_back(point); } } for (std::vector&lt;Point&gt;::iterator itPoint = mapTiles.begin(); itPoint &lt; mapTiles.end(); itPoint++) { if (itPoint-&gt;y % 2 == 0) { xScreenOffset = 0; } else { xScreenOffset = tileWidthHalf; } //draw 2:1 rombus std::size_t tileOriginX = itPoint-&gt;x * tileWidth; std::size_t tileOriginY = itPoint-&gt;y * tileHeightHalf; std::size_t x1 = tileOriginX + tileWidthHalf; std::size_t y1 = tileOriginY + tileHeightHalf; SDL_RenderDrawLine(sdlRenderer, tileOriginX + originX + xScreenOffset, tileOriginY + originY + yScreenOffset, x1 + originX + xScreenOffset, y1 + originY + yScreenOffset); std::size_t x = x1; std::size_t y = y1; x1 = x - tileWidthHalf; y1 = y + tileHeightHalf; SDL_RenderDrawLine(sdlRenderer, x + originX + xScreenOffset, y + originY + yScreenOffset, x1 + originX + xScreenOffset, y1 + originY + yScreenOffset); x = x1; y = y1; x1 = x - tileWidthHalf; y1 = y - tileHeightHalf; SDL_RenderDrawLine(sdlRenderer, x + originX + xScreenOffset, y + originY + yScreenOffset, x1 + originX + xScreenOffset, y1 + originY + yScreenOffset); x = x1; y = y1; x1 = tileOriginX; y1 = tileOriginY; SDL_RenderDrawLine(sdlRenderer, x + originX + xScreenOffset, y + originY + yScreenOffset, x1 + originX + xScreenOffset, y1 + originY + yScreenOffset); } SDL_RenderPresent(sdlRenderer); //game loop //control variables SDL_Event event; bool quit = false; //originX = originX - tileWidthHalf; while (!quit) { while (SDL_PollEvent(&amp;event) != 0) { if (event.type == SDL_QUIT) { quit = true; } else if (event.type == SDL_MOUSEBUTTONDOWN) { if (event.button.button == SDL_BUTTON_LEFT) { int mouseXPos; int mouseYPos; SDL_GetMouseState(&amp;mouseXPos, &amp;mouseYPos); Point gridCoordinates = mouseToGrid(mouseXPos, mouseYPos, tileWidth, tileHeight, PI, SCREEN_WIDTH, SCREEN_HEIGHT); std::cout &lt;&lt; "x,y : " &lt;&lt; gridCoordinates.x &lt;&lt; "," &lt;&lt; gridCoordinates.y &lt;&lt; std::endl; } } } } SDL_DestroyWindow(sdlWindow); SDL_DestroyRenderer(sdlRenderer); SDL_Quit(); return 0; } </code></pre> <p>As I said, the algorithm works so I don't need help getting it to run. I am looking for help or advice on how to make it more compact (reduce lines of code). Maybe I can get rid of a couple of if statements by doing some more maths. This is really the first time after my graduation I used this kind of maths in programming so there might be some tweaks that can be done.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T17:17:44.327", "Id": "407316", "Score": "3", "body": "Code stubs aren't appropriate for this site. Flesh it out to make it a complete code with the minimal amount required to compile and run it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T00:24:32.020", "Id": "407344", "Score": "0", "body": "I will add a fully functional example tomorrow, thank your for the advice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T18:12:54.017", "Id": "407415", "Score": "0", "body": "the code in my question is now a fully functional minimal example" } ]
[ { "body": "<p><strong><em>If</strong> it is immaterial</em> whether <code>minY</code> or <code>maxY</code> is used in case of <code>angleRad == controlAngleRad</code>, you can avoid duplication in the <em>final position for y</em>-handling:</p>\n\n<pre><code>//determine final position for y\nmouseTileYPos = (mouseRectangleSector[0] == 'S')\n == (angleRad &gt; controlAngleRad) ? maxY : minY;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:13:18.257", "Id": "407328", "Score": "0", "body": "As for number of lines, I prefer block delimiters in-line with control structures, and more often than not use them when mandatory, only. IDEs and tools like `indent` (`the flags *do me*.`) are good at bulk-changing such conventions to see whether one prefers one convention over the other." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:12:29.740", "Id": "210705", "ParentId": "210695", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T17:05:24.803", "Id": "210695", "Score": "7", "Tags": [ "c++", "game", "coordinate-system" ], "Title": "Mouse coordinates to grid coordinates within an isometric map" }
210695
<p>Here is part of my implementation of reading a Kinesis stream. I am not confident that this is the best way to implement synchronizing returns from goroutine.</p> <p>Assuming there are N shards in the stream, the code spawns goroutines for each shard in the stream for processing. Goroutine-N works indefinitely until the underlying context is canceled or until an error is encountered during processing.</p> <p>The code below is supposed to wait for all N routines to terminate successfully (i.e without any of them writing to <code>errc</code>) or wait for at least one routine to write to <code>errc</code> (return an error).</p> <p>If all routines terminate without writing to <code>errc</code>, the WaitGroup sync lock is released, closing the <code>errc</code> and <code>done</code> channels. Which would, in turn, resume the current thread. However, if one of the routines terminate writing to <code>errc</code>, we force all routines to terminate by calling the underlying context's cancel function and wait for <code>done</code> channel to close.</p> <pre class="lang-golang prettyprint-override"><code>func (c *Consumer) scanShards(col Collector, streamName string, ids []string) error { checkpoints, err := col.GetSequenceNumberForShards(streamName, ids) if err != nil { return fmt.Errorf("error retrieving stored checkpoints for shards: %v", err) } errc := make(chan error, 1) done := make(chan error, 1) wg := sync.WaitGroup{} wg.Add(len(ids)) for _, id := range ids { seqNum := checkpoints[id] ctx, cancel := context.WithCancel(context.Background()) c.cancelFuncs = append(c.cancelFuncs, cancel) go func(ctx context.Context, shardID, startSeqNum string) { defer wg.Done() if err := c.scanShard(ctx, shardID, startSeqNum); err != nil { errc &lt;- fmt.Errorf("error in shard %q: %v", shardID, err) } }(ctx, id, seqNum) } go func() { wg.Wait() close(errc) close(done) }() err = &lt;-errc if err != nil { // Cancel all scans, to release the worker goroutines from // the pool. for _, cancel := range c.cancelFuncs { cancel() } } &lt;-done // Wait for all goroutines to exit. return err } </code></pre>
[]
[ { "body": "<p>Alright, there's a number of issues with the code you posted here. I'll go through it all, and point out issues, step by step:</p>\n\n<pre><code>func (c *Consumer) scanShards(col Collector, streamName string, ids []string) error {\n</code></pre>\n\n<p>Alright, so we have a <code>*Consumer</code> (exported type), with a non-exported <code>scanShards</code> function. That's fine. The thing I'm slightly baffled by is why the <code>Collector</code> is passed as an argument here. In AWS Kinesis terms, a <code>Collector</code> is what you use to send stuff to Kinesis in a single request. To me, it's sort of like a buffered writer. This collector, however, seems to provide the consumer with data about the shards that you're about to consume. The collector is actually a core dependency of your consumer, it seems. It'd make sense for the consumer to have the underlying collector assigned to a field:</p>\n\n<pre><code>type Consumer struct {\n collector Collector // Rename needed, though\n cancelFuncs []context.CancelFunc // more on this later!\n}\n</code></pre>\n\n<p>Because you're dealing with streams, I'd strongly recommend you use the context package, too (I know you are, but you're not getting the most out of it - see below). Convention dictates that the context argument comes first, so the function would now look like this:</p>\n\n<pre><code>func (c *Consumer) scanShards(ctx context.Context, streamName string, ids []string) error {\n</code></pre>\n\n<p>The arguments could probably do with some renaming, but I'm probably the worst person to suggest a good variable name. Anyway, onwards:</p>\n\n<pre><code> checkpoints, err := col.GetSequenceNumberForShards(streamName, ids)\n if err != nil {\n return fmt.Errorf(\"error retrieving stored checkpoints for shards: %v\", err)\n }\n</code></pre>\n\n<p>Right, so the <em>\"collector\"</em> has an <em>exported</em> function getting sequence, and you're expecting the collector to be passed in as an argument. This is kind of weird. It'd make much more sense for someone to use a <code>Consumer</code> object and call something like <code>consumer.GetShards()</code>, because that actually <em>tells</em> me something: I know that I'm working with a consumer that is taking its data from a shards X, Y, and Z.<br>\nI've looked at what comes next, but I'll be returning to the <code>checkpoints</code> variable later on. First let me just recommend you look at <a href=\"https://github.com/pkg/errors\" rel=\"nofollow noreferrer\">this package</a> for errors. You're essentially returning a specific error (which is OK), but it's a hard one to detect on the caller-side. The string value of the error still contains all of the raw/initial error value. With the package I linked to, you'd be able to write the same like so:</p>\n\n<pre><code>return errors.Wrap(err, \"error retrieving stored checkpoints for shards\")\n</code></pre>\n\n<p>Replace the string constant with an exported constant like so</p>\n\n<pre><code>const ErrRetrievingCheckpoints = \"error retrievign stroed checkpoints for shards\")\n// and use:\nreturn errors.Wrap(err, ErrRetrievingCheckpoints)\n</code></pre>\n\n<p>And you'll have a much easier time actually detecting what error was returned, without losing the underlying error details.</p>\n\n<p>OK, let's move on to the channel stuff now:</p>\n\n<pre><code> errc := make(chan error, 1)\n done := make(chan error, 1)\n wg := sync.WaitGroup{}\n wg.Add(len(ids))\n</code></pre>\n\n<p>Right, So you're creating a waitgroup, and add the length of ids to it, so there's going to be 1 routine per ID. Fine. Then you create an error and done channel, both with a buffer of 1. I'll explain how in a bit, but you can (and should) get rid of the <code>done</code> channel entirely. Having said that, channels like <code>done</code> are generally defined as <code>done := make(chan struct{})</code>: no buffer needed, and an empty struct is defined in the golang specs as a 0-byte type. </p>\n\n<p>The error channel, however, has a bit of a problem: Suppose I'm going to start 10 routines, and I've got 3 errors. The first routine to err will write its error value onto the channel, and be done with it. The second and third routines to fail will be blocked, waiting for you to read the error from the channel. You have the code to do this, so you'll get that error, and the second routine will now write a new error value to the channel. The third routine is still blocked!</p>\n\n<p>What your code does next, is cancel all routines (sort of), and wait for the <code>wg.Wait()</code> call to return. Because the third routine is blocked, this will never happen. You've got a deadlock on your hands. The <code>done</code> channel won't get closed, and thus this function won't return, all because your error channel is blocking routines from completing. That's not what we want. There's a quick (and not always ideal) solution to this problem: increase the channel buffer:</p>\n\n<p>errCh := make(chan error, len(ids) -1) // we'll always read 1, hence -1 is big enough</p>\n\n<p>Of course, we're assuming <code>ids</code> is not empty. Just in case, it's always a good idea to add some basic checks like <code>if len(ids) == 0</code> and return early.</p>\n\n<p>Still, I'll explain later how we fix this without having to increase the channel buffers too much. For now, let's carry on with the line-by-line review:</p>\n\n<pre><code> for _, id := range ids {\n seqNum := checkpoints[id]\n</code></pre>\n\n<p>Yes, I have an issue with this already. <code>checkpoints</code> clearly is a var of type <code>map[string]string</code>. I know this because <code>ids</code> is <code>[]string</code>, and the <code>seqNum</code> variable is passed to a goroutine with the type <code>string</code>. Why, then, iterate over a slice, and then perform a lookup in a map to get the corresponding value? Why not simply write:</p>\n\n<pre><code>for id, seqNum := range checkpoints {\n</code></pre>\n\n<p>That's a lot cleaner, and reduces the risk of someone else looking at your code and adding something like this:</p>\n\n<pre><code>seqNum, ok := checkpoints[id]\nif !ok {\n return errors.New(\"checkpoint missing\")\n}\n</code></pre>\n\n<p>Nevermind the risk of someone changing the <code>GetSequenceNumberForShards</code> function to not return an error if not all id's were found! Suppose your <code>ids</code> var holds <code>{\"foo\", \"bar\", \"zar\", \"car\"}</code>, but the <code>checkpoints</code> map only was returned without the <code>zar</code> key...</p>\n\n<p>For the same reason, you really should replace <code>wg.Add(len(ids))</code> with <code>wg.Add(len(checkpoints))</code></p>\n\n<p>Right, onwards, let's get stuck in with the context:</p>\n\n<pre><code> ctx, cancel := context.WithCancel(context.Background())\n c.cancelFuncs = append(c.cancelFuncs, cancel)\n</code></pre>\n\n<p>Why? Why on earth? You're creating a cancel context for <em>each</em> routine, and append the cancel func to a slice without a way to retrieve a specific cancel function. The slice is also stored on the <code>Consumer</code> type. The function uses a pointer receiver, so there's a genuine risk of race conditions here! Suppose I do this:</p>\n\n<pre><code>go consumer.scanShards(col1, \"foo\", []string{\"a\", \"b\", \"c\"})\ngo consumer.scanShards(col2, \"bar\", []string{\"foo\", \"bar\", \"car\", \"zar\"})\n</code></pre>\n\n<p>Both routines are appending to the same slice of cancel functions. They're both calling all of them blindly, too. These routines are messing things up for eachother. And that's just one example, imagine someone coming along and writing this:</p>\n\n<pre><code>func (c *Consumer) Reset() {\n // restoring some fields\n c.cancelFuncs = []context.CancelFunc{}\n // more fields here\n}\n</code></pre>\n\n<p>These kind of things can be really hard to debug, and your code is very vulnerable to these issues. You may think that the <code>Reset</code> func I've written here is an unlikely scenario, but given that there's nothing in your code that actually <em>removes</em> the <code>cancel</code> values from the slice, your slice will grow, and grow, and grow, and things will get slowed down.</p>\n\n<p>OK, I had to rant about these things somewhat, but remember how I said that you ought to have your first argument be a context? Right, do it, it allows the caller to pass in a <code>context.WithCancel</code>, or <code>context.WithTimeout</code>, for example, so the caller can determine whether they want to/need to wait on your function to return. Secondly: why not have <em>all your routines share the same context?</em>. You're just re-wrapping the <code>Background</code> context anyway. Instead of doing that, I'd simply wrap the context from the argument once (outside the loop):</p>\n\n<pre><code>rctx, cfunc := context.WithCancel(ctx)\n</code></pre>\n\n<p>If the context passed as an argument gets cancelled, the cancellation will propagate, if you want to cancel the context, call <code>cfunc</code>, and all your routines will receive the cancellation signal (<code>&lt;-ctx.Done()</code>). The caller is unaffected.</p>\n\n<p>So with this in mind, let's rewrite the loop a bit (more improvements to follow below, but what we have thusfar):</p>\n\n<pre><code>func (c *Consumer) scanShards(ctx context.Context, stream string, ids []string) error {\n if len(ids) == 0 {\n return ErrNoIdsProvided\n }\n checkpoints, err := c.collector.GetSequenceNumberForShards(stream, ids)\n if err != nil {\n return errors.Wrap(err, ErrRetrievingCheckpoints)\n }\n if len(checkpoints) == 0 {\n return ErrNothingToCheck // something like this, should be handled properly\n }\n // note ids is irrelevant, checkpoints is the source of truth now\n errCh := make(chan error, len(checkpoints) - 1)\n // we'll get rid of this, but I've not explained how, so it's here still:\n done := make(chan struct{})\n wg := sync.WaitGroup{}\n wg.Add(len(checkpoints))\n // wrap around ctx argument once!\n rctx, cfunc := context.WithCancel(ctx)\n\n for id, seqNum := range checkpoints {\n go func(ctx context.Context, shardID, startSeqNum string) {\n defer wg.Done()\n if err := c.scanShard(ctx, shardID, startSeqNum); err != nil {\n errc &lt;- fmt.Errorf(\"error in shard %q: %v\", shardID, err)\n }\n }(rctx, id, seqNum)\n }\n</code></pre>\n\n<p>OK, that's where we are now. Because the <code>rctx</code> is not in the <code>for</code> scope, and is shared by all routines, you can simply write the routine like so:</p>\n\n<pre><code>go func(id, seqNum string) {\n defer wg.Done()\n // note: rctx, not ctx!\n if err := c.scanShard(rctx, id, seqNum); err != nil {\n errCh &lt;- err\n }\n}(id, seqNum)\n</code></pre>\n\n<p>The routine centers around <code>c.scanShard</code>, a function you've not posted, and thus I have no idea what it does (how it uses the context etc...). What is clear to me, though, is that it's an unexported function, and you have control over it. You could just as easily make it into a function that behaves exactly like the routine you wrapped the call in, so you can replace the <code>go func()</code> bit simply with this:</p>\n\n<pre><code>go c.scanShard(rctx, &amp;wg, id, seqNum, errCh)\n// given scanShard looks like this:\nfunc (c *Consumer) scanShard(ctx context.Context, wg *sync.WaitGroup, id, seqNum string, errCh chan&lt;- error)\n</code></pre>\n\n<p>Anyway, the rest of your code is about tying things together:</p>\n\n<pre><code> go func() {\n wg.Wait()\n close(errc)\n close(done)\n }()\n</code></pre>\n\n<p>So waiting for the routines to return before closing the channels, which is fair enough, seeing as writing to a closed channel is bad. Closing the <code>done</code> channel here, though is what actually allows your function to return. But does it add any value?</p>\n\n<pre><code> err = &lt;-errc\n if err != nil {\n for _, cancel := range c.cancelFuncs {\n cancel()\n }\n }\n &lt;-done // Wait for all goroutines to exit.\n return err\n}\n</code></pre>\n\n<p>And this is where things get realy messy: you're first checking the error channel (fair enough), but because you're not sure whether or not you've passed the blocking read (<code>err = &lt;-errCh</code>) because the channel was closed or not, you have to check whether or not you actually have an error. If not, you're still checking the <code>done</code> channel, completely pointlessly. Even with your code as it stands, the <code>done</code> channel is completely redundant, the error channel already does the same thing.</p>\n\n<p>Get rid of <code>done</code>, even with your current code, it serves no purpose whatsoever.</p>\n\n<hr>\n\n<h2>Alternative approach</h2>\n\n<p>I've been ranting plenty for now, and I think this is a decent starting point. When I started looking at your code, my mind did jump to <code>select</code> statements, and using the <code>ctx.Done()</code> to stop calling the <code>scanShard</code> function. I'm not sure if it's actually the better way for this particular case, but it might be worth considering. I'll just include a quick write-up of how I'd write this function using <code>ctx.Done</code> and <code>select</code> to control the flow. It's a bit more verbose, and actually looks more complex than it needs to be IMHO, but it's just to show an alternative approach, that in some cases might be worth considering. I have to say, all code in the answer is untested, and just written as I went along, so typo's and bugs are possible:</p>\n\n<pre><code>package main\n\nimport (\n \"context\"\n \"fmt\"\n \"sync\"\n)\n\nfunc (c *Consumer) scanShards(ctx context.Context, streamName string, ids []string) error {\n checkpoints, err := c.collector.GetSequenceNumberForShards(streamName, ids)\n if err != nil {\n // zerolog\n c.logger.Error().Err(err).Msg(\"Error retrieving stored checkpoints for shards\")\n return err\n }\n\n errc := make(chan error, 1)\n defer close(errc)\n wg := sync.WaitGroup{}\n wg.Add(len(checkpoints))\n rctx, cfunc := context.WithCancel(ctx)\n for id, seqNum := range checkpoints {\n go func(shardID, startSeqNum string) {\n defer wg.Done()\n select {\n case &lt;-rctx.Done():\n // context cancelled, no need to do anything\n return\n default:\n if err := c.scanShard(rctx, shardID, startSeqNum); err != nil {\n c.logger.Error().Err(err).Msg(\"Error in shard %q\", shardID)\n errc &lt;- fmt.Errorf(\"error in shard %q: %v\", shardID, err)\n }\n }\n }(id, seqNum)\n }\n go func() {\n // wg cleared -&gt; cancel context\n wg.Wait()\n cfunc()\n }()\n select {\n case &lt;-ctx.Done():\n // ctx was closed after waitgroup, so nothing to do here\n return nil\n case err := &lt;-errc:\n // error -&gt; cancel routines\n cfunc()\n return err // return, this will close channel\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:31:42.620", "Id": "211054", "ParentId": "210698", "Score": "2" } } ]
{ "AcceptedAnswerId": "211054", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:06:11.783", "Id": "210698", "Score": "4", "Tags": [ "go", "concurrency" ], "Title": "Reading shards from a Kinesis stream" }
210698
<p>I wrote this small program to open a .torrent file, retrieve its info-hash and size. I'm still a beginner at Python so the main focus of this program was to try and utilize classes and objects instead of having just a bunch of functions. It works but I wanted to know if this is a good design. Also, I feel some of the code I wrote is redundant especially the number of times <code>self</code> is used. </p> <pre><code>import hashlib, bencode class Torrent(object): def __init__(self, torrentfile): self.metainfo = bencode.bdecode(torrentfile.read()) self.info = self.metainfo['info'] self.files = self.metainfo['info']['files'] self.md5hash = self.md5hash(self.info) self.size = self.size(self.files) def md5hash(self, info): return hashlib.sha1(bencode.bencode(info)).hexdigest() def size(self, files): filesize = 0 for file in files: filesize += file['length'] return filesize torrentfile = Torrent(open("test.torrent", "rb")) print(torrentfile.md5hash) print(torrentfile.size) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:45:40.690", "Id": "407326", "Score": "2", "body": "Welcome to Code Review! Commendable presentation of purpose and concerns!" } ]
[ { "body": "<p>Using classes for this seems like a good idea, since you end up with a number of class instances, where each one represents a specific torrent.</p>\n\n<p>In terms of the specific code, you're doing things slightly wrong in 2 ways.</p>\n\n<p>Firstly, you don't need to pass instance parameters into the methods of a class. So you can access <code>info</code> and <code>file</code> as <code>self.info</code> and <code>self.file</code>, so your methods only need the <code>self</code> argument.</p>\n\n<p>Secondly, I can see that you're doing this to try to cache the results of the method calls by overriding the methods in <code>__init__</code>, and while caching is good, this is a bad way of trying to achieve it.</p>\n\n<p>There are 2 alternatives that spring to mind, depending on what you want to do:</p>\n\n<p>If you always want the size and hash calculated when the class is instantiated, then do something similar to what you're doing now, but use different names for the data variables and the methods:</p>\n\n<pre><code>def __init__(self, torrentfile):\n self.metainfo = bencode.bdecode(torrentfile.read())\n self.info = self.metainfo['info']\n self.files = self.metainfo['info']['files']\n self.md5hash = self.calculate_md5hash()\n self.size = self.calculate_size()\n\ndef calculate_md5hash(self):\n return hashlib.sha1(bencode.bencode(self.info)).hexdigest()\n\ndef calculate_size(self):\n filesize = 0\n for file in self.files:\n filesize += file['length'] \n return filesize\n</code></pre>\n\n<p>Alternatively, if you only want the hash and size calculated when the methods are specifically called, but you also want caching, use <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"noreferrer\">lru_cache</a></p>\n\n<p><code>lru_cache</code> will cache the result of a function the first time it is run, and then simply return the result for future calls, providing the arguments to the function remain the same.</p>\n\n<pre><code>from functools import lru_cache\n\nclass Torrent(object):\n\n def __init__(self, torrentfile):\n self.metainfo = bencode.bdecode(torrentfile.read())\n self.info = self.metainfo['info']\n self.files = self.metainfo['info']['files']\n\n @lru_cache()\n def md5hash(self):\n return hashlib.sha1(bencode.bencode(self.info)).hexdigest()\n\n @lru_cache()\n def size(self):\n filesize = 0\n for file in self.files:\n filesize += file['length'] \n return filesize\n</code></pre>\n\n<p>Then call the methods explicitly:</p>\n\n<pre><code>print(torrentfile.md5hash())\nprint(torrentfile.size())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:29:50.277", "Id": "210701", "ParentId": "210700", "Score": "6" } }, { "body": "<p>@MathiasEttinger picked up most of the issues. Here's a random assortment of others:</p>\n\n<h2>Import what you need</h2>\n\n<p>If you do:</p>\n\n<pre><code>from hashlib import sha1\nfrom bencode import bencode, bdecode\n</code></pre>\n\n<p>Then your usage can be shortened to:</p>\n\n<pre><code>self.metainfo = bdecode(torrentfile.read())\n# ...\nreturn sha1(bencode(info)).hexdigest()\n</code></pre>\n\n<h2>Use list comprehensions</h2>\n\n<p>This:</p>\n\n<pre><code> filesize = 0\n for file in files:\n filesize += file['length'] \n return filesize\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return sum(f['length'] for f in files)\n</code></pre>\n\n<h2>Use context management</h2>\n\n<p>You don't <code>close</code> your file, which is an issue; but you don't need to do it explicitly - do it implicitly:</p>\n\n<pre><code>with open(\"test.torrent\", \"rb\") as torrentfile:\n torrent = Torrent(torrentfile)\nprint(torrent.md5hash)\nprint(torrent.size)\n</code></pre>\n\n<p>Note that this assumes <code>Torrent</code> is done with the file at the end of the constructor.</p>\n\n<h2>Use a <code>main</code> function</h2>\n\n<p>Put your global code into a main function to clean up the global namespace and allow others to use your code as a library rather than a command.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T11:46:19.417", "Id": "407649", "Score": "0", "body": "Just to add - while it isn't an issue in a small project like this, always be aware that importing using 'from' can potentially pollute your namespace, and sometimes having a single 'top-level' module name with child methods is a safer route. (Agree with everything else though!)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T03:12:08.067", "Id": "210720", "ParentId": "210700", "Score": "3" } } ]
{ "AcceptedAnswerId": "210701", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T18:11:55.433", "Id": "210700", "Score": "5", "Tags": [ "python", "object-oriented" ], "Title": "Program to calculate Hash and Size of a torrent" }
210700
<p>This is my implementation of a string class similar to <code>std::string</code> and supports the following:</p> <ol> <li>range-<code>for</code> loops</li> <li>iterators</li> <li>basic utility functions</li> <li>exponential capacity increase</li> <li>operator overloads</li> </ol> <p>I am looking for specific reviews on implementation of iterators, exponential capacity increase, usage of <code>noexcept</code> and implementations of some functions like <code>resize()</code>, <code>operator+=</code>, <code>operator=</code>, and <code>operator+</code>.</p> <h2>mystring.h</h2> <pre><code>#ifndef MY_STRING_H_ #define MY_STRING_H_ #include &lt;cstring&gt; #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;algorithm&gt; #include &lt;stdexcept&gt; #include &lt;limits&gt; namespace kapil { class string final { private: // default capacity of empty string. //Minimum default_capacity is 2. static constexpr size_t default_capacity_ = 16; // current capacity of the string container. size_t current_capacity_; //size of string. size_t sz_; // pointer to character std::unique_ptr&lt;char[]&gt; ptr_; public: string(); string(const string&amp;); string(string&amp;&amp;) noexcept; string(const char*); explicit string(char); ~string() noexcept; size_t capacity() const noexcept; size_t size() const noexcept; size_t length() const noexcept; void resize(size_t, char ch = '\0'); void clear() noexcept; bool empty() const noexcept; char&amp; at(size_t); const char&amp; at(size_t) const; char&amp; back(); const char&amp; back() const; char&amp; front(); const char&amp; front() const; string&amp; append(const string&amp;); string&amp; append(const char*); string&amp; append(string&amp;&amp;); string&amp; append(char); void push_back(char); string&amp; assign(const string&amp;); string&amp; assign(const char*); string&amp; assign(string&amp;&amp;); void swap(string&amp;); const char* c_str() const noexcept; const char* data() const noexcept; string&amp; operator = (const string&amp;); string&amp; operator = (string&amp;&amp;) noexcept; string&amp; operator = (const char*); string&amp; operator = (char); string&amp; operator += (const string&amp;); string&amp; operator += (const char*); string&amp; operator += (char); string&amp; operator += (string&amp;&amp;); char&amp; operator[] (size_t); const char&amp; operator[] (size_t) const; friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp;, const string&amp;); friend string operator + (const string&amp;, const string&amp;); friend string operator + (const string&amp;, const char*); friend string operator + (const char*, const string&amp;); friend string operator + (string&amp;&amp;, string&amp;&amp;); friend string operator + (string&amp;&amp;, const char*); friend string operator + (const char*, string&amp;&amp;); friend string operator + (const string&amp;, string&amp;&amp;); friend string operator + (string&amp;&amp;, const string&amp;); friend string operator + (const string&amp;, char); friend string operator + (char, const string&amp;); friend string operator + (string&amp;&amp;, char); friend string operator + (char, string&amp;&amp;); friend bool operator == (const string&amp;, const string&amp;) noexcept; friend bool operator == (const string&amp;, const char*) noexcept; friend bool operator == (const char*, const string&amp;) noexcept; friend bool operator == (const string&amp;, char) noexcept; friend bool operator == (char, const string&amp;) noexcept; friend bool operator == (const string&amp;, string&amp;&amp;) noexcept; friend bool operator == (string&amp;&amp;, const string&amp;) noexcept; friend bool operator == (string&amp;&amp;, string&amp;&amp;) noexcept; friend bool operator == (string&amp;&amp;, char) noexcept; friend bool operator == (char, string&amp;&amp;) noexcept; friend bool operator == (const char*, string&amp;&amp;) noexcept; friend bool operator == (string&amp;&amp;, const char*) noexcept; friend bool operator != (const string&amp;, const string&amp;) noexcept; friend bool operator != (const string&amp;, const char*) noexcept; friend bool operator != (const char*, const string&amp;) noexcept; friend bool operator != (const string&amp;, char) noexcept; friend bool operator != (char, const string&amp;) noexcept; friend bool operator != (const string&amp;, string&amp;&amp;) noexcept; friend bool operator != (string&amp;&amp;, const string&amp;) noexcept; friend bool operator != (string&amp;&amp;, string&amp;&amp;) noexcept; friend bool operator != (string&amp;&amp;, char) noexcept; friend bool operator != (char, string&amp;&amp;) noexcept; friend bool operator != (const char*, string&amp;&amp;) noexcept; friend bool operator != (string&amp;&amp;, const char*) noexcept; class iterator { private: string* str_; size_t index_; public: iterator(string* = nullptr, size_t = 0) noexcept; iterator(const iterator&amp;) noexcept; iterator(iterator&amp;&amp;) noexcept; ~iterator() noexcept; iterator&amp; operator = (const iterator&amp;) noexcept; iterator&amp; operator = (iterator&amp;&amp;) noexcept; bool operator != (const iterator&amp;) const noexcept; bool operator == (const iterator&amp;) const noexcept; iterator&amp; operator ++ () noexcept; iterator&amp; operator ++ (int) noexcept; iterator&amp; operator -- () noexcept; iterator&amp; operator -- (int) noexcept; char&amp; operator * () const; }; iterator begin(); iterator end(); class const_iterator { private: const string* str_; size_t index_; public: const_iterator(const string*, size_t) noexcept; const_iterator(const const_iterator&amp;) noexcept; const_iterator(const_iterator&amp;&amp;) noexcept; ~const_iterator() noexcept; const_iterator&amp; operator = (const const_iterator&amp;) noexcept; const_iterator&amp; operator = (const_iterator&amp;&amp;) noexcept; bool operator != (const const_iterator&amp;) const noexcept; bool operator == (const const_iterator&amp;) const noexcept; const_iterator&amp; operator ++ () noexcept; const_iterator&amp; operator ++ (int) noexcept; const_iterator&amp; operator -- () noexcept; const_iterator&amp; operator -- (int) noexcept; const char&amp; operator * () const; }; const_iterator cbegin(); const_iterator cend(); class reverse_iterator { private: string* str_; size_t index_; public: reverse_iterator(string* = nullptr, size_t = 0) noexcept; reverse_iterator(const reverse_iterator&amp;) noexcept; reverse_iterator(reverse_iterator&amp;&amp;) noexcept; ~reverse_iterator() noexcept; reverse_iterator&amp; operator = (const reverse_iterator&amp;) noexcept; reverse_iterator&amp; operator = (reverse_iterator&amp;&amp;) noexcept; bool operator != (const reverse_iterator&amp;) const noexcept; bool operator == (const reverse_iterator&amp;) const noexcept; reverse_iterator&amp; operator ++ () noexcept; reverse_iterator&amp; operator ++ (int) noexcept; reverse_iterator&amp; operator -- () noexcept; reverse_iterator&amp; operator -- (int) noexcept; char&amp; operator * () const; }; reverse_iterator rbegin(); reverse_iterator rend(); class reverse_const_iterator { private: const string* str_; size_t index_; public: reverse_const_iterator(const string*, size_t) noexcept; reverse_const_iterator(const reverse_const_iterator&amp;) noexcept; reverse_const_iterator(reverse_const_iterator&amp;&amp;) noexcept; ~reverse_const_iterator() noexcept; reverse_const_iterator&amp; operator = (const reverse_const_iterator&amp;) noexcept; reverse_const_iterator&amp; operator = (reverse_const_iterator&amp;&amp;) noexcept; bool operator != (const reverse_const_iterator&amp;) const noexcept; bool operator == (const reverse_const_iterator&amp;) const noexcept; reverse_const_iterator&amp; operator ++ () noexcept; reverse_const_iterator&amp; operator ++ (int) noexcept; reverse_const_iterator&amp; operator -- () noexcept; reverse_const_iterator&amp; operator -- (int) noexcept; const char&amp; operator * () const; }; reverse_const_iterator crbegin(); reverse_const_iterator crend(); }; } //kapil #endif </code></pre> <h2>my_string.cpp</h2> <pre><code>#include "my_string.h" namespace kapil { /* For the given new_string_length, the appropriate capacity is the next power of 2 that is greater than new_string_length. */ size_t get_appropriate_capacity(size_t new_string_length) { size_t appropriate_capacity = 16; if ((static_cast&lt;unsigned long&gt;(new_string_length) &lt;&lt; 1) &gt; std::numeric_limits&lt;size_t&gt;::max()) { appropriate_capacity = new_string_length; } else { appropriate_capacity = 16; if (appropriate_capacity &lt;= new_string_length) { if (!(new_string_length &amp; (new_string_length - 1))) { appropriate_capacity = new_string_length &lt;&lt; 1; } else { while (appropriate_capacity &lt; new_string_length) { appropriate_capacity &lt;&lt;= 1; } } } } return appropriate_capacity; } /**************************************** member functions *********************/ string::string() : current_capacity_{ default_capacity_ } { sz_ = 0; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); ptr_.get()[0] = '\0'; } string::string(const string&amp; other) { current_capacity_ = other.current_capacity_; sz_ = other.sz_; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); std::strcpy(ptr_.get(), other.ptr_.get()); } string::string(string&amp;&amp; rval) noexcept : current_capacity_{ rval.current_capacity_ }, sz_{ rval.sz_ }, ptr_{ std::move(rval.ptr_) } { } string::string(const char* c_string) { sz_ = std::strlen(c_string); current_capacity_ = get_appropriate_capacity(sz_); ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); std::strcpy(ptr_.get(), c_string); } string::string(char ch) { sz_ = 1; current_capacity_ = default_capacity_; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); ptr_.get()[0] = ch; ptr_.get()[1] = '\0'; } string::~string() noexcept { current_capacity_ = 0; sz_ = 0; ptr_.reset(nullptr); }; /**************************************** member functions *********************/ size_t string::capacity() const noexcept { return current_capacity_; } size_t string::size() const noexcept { return sz_; } size_t string::length() const noexcept { return sz_; } void string::resize(size_t n, char ch) { if (n == sz_) { return; } size_t appropriate_capacity = get_appropriate_capacity(n); std::unique_ptr&lt;char[]&gt; temp; auto resized = bool{false}; if (current_capacity_ != appropriate_capacity) { resized = true; current_capacity_ = appropriate_capacity; temp = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); } if (n &lt; sz_) { if (resized) { std::strncpy(temp.get(), ptr_.get(), n); temp.get()[n] = '\0'; } else { ptr_.get()[n] = '\0'; } } else if (n &gt; sz_) { if (resized) { std::strncpy(temp.get(), ptr_.get(), sz_); std::fill(temp.get() + sz_, temp.get() + n, ch); temp.get()[n] = '\0'; } else { std::fill(ptr_.get() + sz_, ptr_.get() + n, ch); ptr_.get()[n] = '\0'; } } sz_ = n; if (resized) { ptr_ = std::move(temp); } } void string::clear() noexcept { current_capacity_ = default_capacity_; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); ptr_.get()[0] = '\0'; sz_ = 0; } bool string::empty() const noexcept { return sz_ == 0; } char&amp; string::at(size_t idx) { if (idx &lt; 0 || idx &gt;= sz_) { throw std::out_of_range{"out of range memory access"}; } return (*this)[idx]; } const char&amp; string::at(size_t idx) const { if (idx &lt; 0 || idx &gt;= sz_) { throw std::out_of_range{"out of range memory access"}; } return (*this)[idx]; } char&amp; string::back() { return (*this)[sz_ - 1]; } const char&amp; string::back() const { return (*this)[sz_ - 1]; } char&amp; string::front() { return (*this)[0]; } const char&amp; string::front() const { return (*this)[0]; } string&amp; string::append(const string&amp; rhs) { (*this) += rhs; return *this; } string&amp; string::append(const char* rhs) { (*this) += rhs; return *this; } string&amp; string::append(string&amp;&amp; rhs) { (*this) += rhs; return *this; } string&amp; string::append(char ch) { (*this) += ch; return *this; } void string::push_back(char ch) { (*this) += ch; return; } string&amp; string::assign(const string&amp; rhs) { (*this) = rhs; return *this; } string&amp; string::assign(const char* rhs) { (*this) = rhs; return *this; } string&amp; string::assign(string&amp;&amp; rhs) { (*this) = rhs; return *this; } void string::swap(string &amp;str) { string temp{str}; str = *this; *this = temp; } const char* string::c_str() const noexcept { return ptr_.get(); } const char* string::data() const noexcept { return c_str(); } /**************************************** member operator overloads*********************/ string&amp; string::operator = (const string&amp; rhs) { if (this != &amp;rhs) { if (current_capacity_ != rhs.current_capacity_) { current_capacity_ = rhs.current_capacity_; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); } sz_ = rhs.sz_; std::strcpy(ptr_.get(), rhs.c_str()); } return *this; } string&amp; string::operator = (string&amp;&amp; rval) noexcept { current_capacity_ = rval.current_capacity_; sz_ = rval.sz_; ptr_ = std::move(rval.ptr_); return *this; } string&amp; string::operator = (const char* c_string) { sz_ = std::strlen(c_string); auto appropriate_capacity = get_appropriate_capacity(sz_); if (current_capacity_ != appropriate_capacity) { current_capacity_ = appropriate_capacity; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); } std::strcpy(ptr_.get(), c_string); return *this; } string&amp; string::operator = (char ch) { current_capacity_ = default_capacity_; sz_ = 1; ptr_ = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); ptr_.get()[0] = ch; ptr_.get()[1] = '\0'; return *this; } string&amp; string::operator += (const string&amp; rhs) { std::unique_ptr&lt;char[]&gt; temp; auto appropriate_capacity = get_appropriate_capacity(sz_ + rhs.sz_); if (current_capacity_ != appropriate_capacity) { current_capacity_ = appropriate_capacity; temp = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); std::strcpy(temp.get(), ptr_.get()); ptr_ = std::move(temp); } std::strcpy(ptr_.get() + sz_, rhs.c_str()); sz_ += rhs.sz_; return *this; } string&amp; string::operator += (const char* rhs) { std::unique_ptr&lt;char[]&gt; temp; auto rhs_sz = std::strlen(rhs); auto appropriate_capacity = get_appropriate_capacity(sz_ + rhs_sz); if (current_capacity_ != appropriate_capacity) { current_capacity_ = appropriate_capacity; temp = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); std::strcpy(temp.get(), ptr_.get()); ptr_ = std::move(temp); } std::strcpy(ptr_.get() + sz_, rhs); sz_ += rhs_sz; return *this; } string&amp; string::operator += (char ch) { auto appropriate_capacity = get_appropriate_capacity(sz_ + 1); std::unique_ptr&lt;char[]&gt; temp; if (current_capacity_ != appropriate_capacity) { current_capacity_ = appropriate_capacity; temp = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); strcpy(temp.get(), ptr_.get()); ptr_ = std::move(temp); } ptr_.get()[sz_] = ch; ptr_.get()[sz_ + 1] = '\0'; sz_ += 1; return *this; } string&amp; string::operator += (string&amp;&amp; rval) { std::unique_ptr&lt;char[]&gt; temp; auto appropriate_capacity = get_appropriate_capacity(sz_ + rval.sz_); if (current_capacity_ != appropriate_capacity) { current_capacity_ = appropriate_capacity; temp = std::make_unique&lt;char[]&gt;(current_capacity_ + 1); std::strcpy(temp.get(), ptr_.get()); ptr_ = std::move(temp); } std::strcpy(ptr_.get() + sz_, rval.c_str()); sz_ += rval.sz_; return *this; } char&amp; string::operator [] (size_t idx) { return ptr_.get()[idx]; } const char&amp; string::operator [] (size_t idx) const { return ptr_.get()[idx]; } /**************************************** friend operator overloads *********************/ std::ostream&amp; operator &lt;&lt; (std::ostream&amp; out, const string&amp; str) { if (str.size() &gt; 0) { out.write(str.c_str(), str.size()); } return out; } string operator + (const string&amp; lhs, const string&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (const string&amp; lhs, const char* rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (const char* lhs, const string&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (string&amp;&amp; lhs, string&amp;&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (string&amp;&amp; lhs, const char* rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (const char* lhs, string&amp;&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (const string&amp; lhs, string&amp;&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (string&amp;&amp; lhs, const string&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (const string&amp; lhs, char rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (char lhs, const string&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (string&amp;&amp; lhs, char rhs) { string temp{lhs}; temp += rhs; return temp; } string operator + (char lhs, string&amp;&amp; rhs) { string temp{lhs}; temp += rhs; return temp; } bool operator == (const string&amp; lhs, const string&amp; rhs) noexcept { return (lhs.sz_ == rhs.sz_) &amp;&amp; ((lhs.sz_ == 0) ? true : (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) == 0)); } bool operator == (const string&amp; lhs, const char* rhs) noexcept { return (lhs.sz_ == std::strlen(rhs)) &amp;&amp; ((lhs.sz_ == 0) ? true : (std::strncmp(lhs.ptr_.get(), rhs, lhs.sz_) == 0)); } bool operator == (const char* lhs, const string&amp; rhs) noexcept { return (strlen(lhs) == rhs.sz_) &amp;&amp; ((rhs.sz_ == 0) ? true : (std::strncmp(lhs, rhs.ptr_.get(), rhs.sz_) == 0)); } bool operator == (const string&amp; lhs, char rhs) noexcept { return (lhs.sz_ == 1) &amp;&amp; (lhs.ptr_.get()[0] == rhs); } bool operator == (char lhs, const string&amp; rhs) noexcept { return (rhs.sz_ == 1) &amp;&amp; (lhs == rhs.ptr_.get()[0]); } bool operator == (const string&amp; lhs, string&amp;&amp; rhs) noexcept { return (lhs.sz_ == rhs.sz_) &amp;&amp; ((lhs.sz_ == 0) ? true : (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) == 0)); } bool operator == (string&amp;&amp; lhs, const string&amp; rhs) noexcept { return (lhs.sz_ == rhs.sz_) &amp;&amp; ((lhs.sz_ == 0) ? true : (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) == 0)); } bool operator == (string&amp;&amp; lhs, string&amp;&amp; rhs) noexcept { return (lhs.sz_ == rhs.sz_) &amp;&amp; ((lhs.sz_ == 0) ? true : (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) == 0)); } bool operator == (string&amp;&amp; lhs, char rhs) noexcept { return (lhs.sz_ == 1) &amp;&amp; (lhs.ptr_.get()[0] == rhs); } bool operator == (char lhs, string&amp;&amp; rhs) noexcept { return (rhs.sz_ == 1) &amp;&amp; (rhs.ptr_.get()[0] == lhs); } bool operator == (string&amp;&amp; lhs, const char* rhs) noexcept { return (lhs.sz_ == std::strlen(rhs)) &amp;&amp; ((lhs.sz_ == 0) ? true : (std::strncmp(lhs.ptr_.get(), rhs, lhs.sz_) == 0)); } bool operator == (const char* lhs, string &amp;&amp; rhs) noexcept { return (std::strlen(lhs) == rhs.sz_) &amp;&amp; ((rhs.sz_ == 0) ? true : (std::strncmp(lhs, rhs.ptr_.get(), rhs.sz_) == 0)); } bool operator != (const string&amp; lhs, const string&amp; rhs) noexcept { return !(lhs == rhs); } bool operator != (const string&amp; lhs, const char* rhs) noexcept { return !(lhs == rhs); } bool operator != (const char* lhs, const string&amp; rhs) noexcept { return !(lhs == rhs); } bool operator != (const string&amp; lhs, char rhs) noexcept { return !(lhs == rhs); } bool operator != (char lhs, const string&amp; rhs) noexcept { return !(lhs == rhs); } bool operator != (const string&amp; lhs, string&amp;&amp; rhs) noexcept { return (lhs.sz_ != rhs.sz_) || (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) != 0); } bool operator != (string&amp;&amp; lhs, const string&amp; rhs) noexcept { return (lhs.sz_ != rhs.sz_) || (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) != 0); } bool operator != (string&amp;&amp; lhs, string&amp;&amp; rhs) noexcept { return (lhs.sz_ != rhs.sz_) || (std::strncmp(lhs.ptr_.get(), rhs.ptr_.get(), lhs.sz_) != 0); } bool operator != (string&amp;&amp; lhs, char rhs) noexcept { return (lhs.sz_ != 1) || (lhs.ptr_.get()[0] != rhs); } bool operator != (char lhs, string&amp;&amp; rhs) noexcept { return (rhs.sz_ != 1) || (rhs.ptr_.get()[0] != lhs); } bool operator != (string&amp;&amp; lhs, const char* rhs) noexcept { return (lhs.sz_ != std::strlen(rhs)) || (std::strncmp(lhs.ptr_.get(), rhs, lhs.sz_) != 0); } bool operator != (const char* lhs, string &amp;&amp; rhs) noexcept { return (std::strlen(lhs) != rhs.sz_) || (std::strncmp(lhs, rhs.ptr_.get(), rhs.sz_) != 0); } /**************************************** iterator related implementations *********************/ using iterator = string::iterator; iterator::iterator(string *str, size_t index) noexcept : str_{str}, index_{index} { } iterator::iterator(const iterator&amp; itr) noexcept : str_{itr.str_}, index_{itr.index_} { } iterator::iterator(iterator&amp;&amp; rval) noexcept : str_{rval.str_}, index_{rval.index_} { } iterator::~iterator() noexcept { str_ = nullptr; index_ = 0; } iterator&amp; iterator::operator = (const iterator&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } iterator&amp; iterator::operator = (iterator&amp;&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } bool iterator::operator != (const iterator&amp; rhs) const noexcept { return (str_ != rhs.str_) || (index_ != rhs.index_); } bool iterator::operator == (const iterator&amp; rhs) const noexcept { return (str_ == rhs.str_) &amp;&amp; (index_ == rhs.index_); } iterator&amp; iterator::operator ++ () noexcept { ++index_; return *this; } iterator&amp; iterator::operator ++ (int dummy) noexcept { ++(*this); return *this; } iterator&amp; iterator::operator -- () noexcept { --index_; return *this; } iterator&amp; iterator::operator -- (int dummy) noexcept { --(*this); return *this; } char&amp; iterator::operator * () const { return (*str_)[index_]; } iterator string::begin() { return iterator(this); } iterator string::end() { return iterator(this, sz_); } using const_iterator = string::const_iterator; const_iterator::const_iterator(const string* str, size_t index) noexcept : str_{str}, index_{index} { } const_iterator::const_iterator(const const_iterator&amp; itr) noexcept : str_{itr.str_}, index_{itr.index_} { } const_iterator::const_iterator(const_iterator&amp;&amp; rval) noexcept : str_{rval.str_}, index_{rval.index_} { } const_iterator::~const_iterator() noexcept { str_ = nullptr; index_ = 0; } const_iterator&amp; const_iterator::operator = (const const_iterator&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } const_iterator&amp; const_iterator::operator = (const_iterator&amp;&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } bool const_iterator::operator != (const const_iterator&amp; rhs) const noexcept { return (str_ != rhs.str_) || (index_ != rhs.index_); } bool const_iterator::operator == (const const_iterator&amp; rhs) const noexcept { return (str_ == rhs.str_) &amp;&amp; (index_ == rhs.index_); } const_iterator&amp; const_iterator::operator ++ () noexcept { ++index_; return *this; } const_iterator&amp; const_iterator::operator ++ (int dummy) noexcept { ++(*this); return *this; } const_iterator&amp; const_iterator::operator -- () noexcept { --index_; return *this; } const_iterator&amp; const_iterator::operator -- (int dummy) noexcept { --(*this); return *this; } const char&amp; const_iterator::operator * () const { return (*str_)[index_]; } const_iterator string::cbegin() { return const_iterator(this, 0); } const_iterator string::cend() { return const_iterator(this, sz_); } using reverse_iterator = string::reverse_iterator; reverse_iterator::reverse_iterator(string *str, size_t index) noexcept : str_{str}, index_{index} { } reverse_iterator::reverse_iterator(const reverse_iterator&amp; itr) noexcept : str_{itr.str_}, index_{itr.index_} { } reverse_iterator::reverse_iterator(reverse_iterator&amp;&amp; rval) noexcept : str_{rval.str_}, index_{rval.index_} { } reverse_iterator::~reverse_iterator() noexcept { str_ = nullptr; index_ = 0; } reverse_iterator&amp; reverse_iterator::operator = (const reverse_iterator&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } reverse_iterator&amp; reverse_iterator::operator = (reverse_iterator&amp;&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } bool reverse_iterator::operator != (const reverse_iterator&amp; rhs) const noexcept { return (str_ != rhs.str_) || (index_ != rhs.index_); } bool reverse_iterator::operator == (const reverse_iterator&amp; rhs) const noexcept { return (str_ == rhs.str_) &amp;&amp; (index_ == rhs.index_); } reverse_iterator&amp; reverse_iterator::operator ++ () noexcept { --index_; return *this; } reverse_iterator&amp; reverse_iterator::operator ++ (int dummy) noexcept { ++(*this); return *this; } reverse_iterator&amp; reverse_iterator::operator -- () noexcept { ++index_; return *this; } reverse_iterator&amp; reverse_iterator::operator -- (int dummy) noexcept { --(*this); return *this; } char&amp; reverse_iterator::operator * () const { return (*str_)[index_]; } reverse_iterator string::rbegin() { return reverse_iterator(this, sz_ - 1); } reverse_iterator string::rend() { return reverse_iterator(this, -1); } using reverse_const_iterator = string::reverse_const_iterator; reverse_const_iterator::reverse_const_iterator(const string* str, size_t index) noexcept : str_{str}, index_{index} { } reverse_const_iterator::reverse_const_iterator(const reverse_const_iterator&amp; itr) noexcept : str_{itr.str_}, index_{itr.index_} { } reverse_const_iterator::reverse_const_iterator(reverse_const_iterator&amp;&amp; rval) noexcept : str_{rval.str_}, index_{rval.index_} { } reverse_const_iterator::~reverse_const_iterator() noexcept { str_ = nullptr; index_ = 0; } reverse_const_iterator&amp; reverse_const_iterator::operator = (const reverse_const_iterator&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } reverse_const_iterator&amp; reverse_const_iterator::operator = (reverse_const_iterator&amp;&amp; rhs) noexcept { str_ = rhs.str_; index_ = rhs.index_; return *this; } bool reverse_const_iterator::operator != (const reverse_const_iterator&amp; rhs) const noexcept { return (str_ != rhs.str_) || (index_ != rhs.index_); } bool reverse_const_iterator::operator == (const reverse_const_iterator&amp; rhs) const noexcept { return (str_ == rhs.str_) &amp;&amp; (index_ == rhs.index_); } reverse_const_iterator&amp; reverse_const_iterator::operator ++ () noexcept { --index_; return *this; } reverse_const_iterator&amp; reverse_const_iterator::operator ++ (int dummy) noexcept { ++(*this); return *this; } reverse_const_iterator&amp; reverse_const_iterator::operator -- () noexcept { ++index_; return *this; } reverse_const_iterator&amp; reverse_const_iterator::operator -- (int dummy) noexcept { --(*this); return *this; } const char&amp; reverse_const_iterator::operator * () const { return (*str_)[index_]; } reverse_const_iterator string::crbegin() { return reverse_const_iterator(this, sz_ - 1); } reverse_const_iterator string::crend() { return reverse_const_iterator(this, -1); } } //kapil </code></pre> <p>Here is a test file which shows the usage:</p> <h2>test_string.cpp</h2> <pre><code>#include "my_string.h" using namespace kapil; int main() { string x{"kapil"}; std::cout &lt;&lt; " size : " &lt;&lt; x.size() &lt;&lt; " length : " &lt;&lt; x.length() &lt;&lt; " is empty : " &lt;&lt; x.empty() &lt;&lt; " at 2 : " &lt;&lt; x.at(2) &lt;&lt; " back : " &lt;&lt; x.back() &lt;&lt; " c_str : " &lt;&lt; x.c_str() &lt;&lt; " data : " &lt;&lt; x.data() &lt;&lt; std::endl; x.clear(); x = "dev"; string y{" singh"}; x.append(y); x.append(" is"); y.assign(" assigned"); x += " operator +"; x += y; std::cout &lt;&lt; " x : " &lt;&lt; x &lt;&lt; " x cap : " &lt;&lt; x.capacity() &lt;&lt; "\n y : " &lt;&lt; y &lt;&lt; " y cap : " &lt;&lt; y.capacity() &lt;&lt; std::endl; string added = "i am binary + " + y + string{" ravl add "} + 'x'; std::cout &lt;&lt; " added : " &lt;&lt; added &lt;&lt; " added cap : " &lt;&lt; added.capacity() &lt;&lt; std::endl; added = "kapil"; added.resize(10, 'k'); std::cout &lt;&lt; " added resize 10 : " &lt;&lt; added &lt;&lt; " added cap : " &lt;&lt; added.capacity() &lt;&lt; std::endl; added.resize(78, 'l'); std::cout &lt;&lt; " added resize 78 : " &lt;&lt; added &lt;&lt; " added cap : " &lt;&lt; added.capacity() &lt;&lt; std::endl; string s1 = "kapil"; s1.swap(added); std::cout &lt;&lt; " added : " &lt;&lt; added &lt;&lt; " s1 : " &lt;&lt; s1 &lt;&lt; std::endl; for (auto it : s1) { std::cout &lt;&lt; it &lt;&lt; " "; } std::cout &lt;&lt; "\n"; return 0; } </code></pre>
[]
[ { "body": "<h3>Errors / bugs / warnings</h3>\n\n<p>So the first thing I did was try to compile your code. Baring in mind my command was:</p>\n\n<pre><code>g++ -std=c++14 -pedantic -Wall -Wextra -Werror\n</code></pre>\n\n<p>And then some more extra warnings. (I assume your program is C++ 14 since <code>std::make_unique</code> was added in C++ 14)</p>\n\n<p>Here are the list of errors:</p>\n\n<pre><code>error: no previous declaration for ‘size_t kapil::get_appropriate_capacity(size_t)’\n</code></pre>\n\n<p>That function should be in an anonymous namespace or declared <code>static</code>, since it's a local helper function.</p>\n\n<pre><code>(In \"std::size_t get_appropriate_capacity(std::size_t)\")\nerror: useless cast to type ‘long unsigned int’\n if ((static_cast&lt;unsigned long&gt;(new_string_length) &lt;&lt; 1) &gt; std::numeric_limits&lt;size_t&gt;::max()) {\n ^\n</code></pre>\n\n<p>I see what your trying to do here, but the way you go about it is not quite right. To check for an unsigned overflow here, the easiest way would be to check if the number is smaller after bitshifting:</p>\n\n<pre><code>if ((new_string_length &lt;&lt; 1) &lt; new_string_length) {\n</code></pre>\n\n<p>A more general solution would be:</p>\n\n<pre><code>if (std::numeric_limits&lt;std::size_t&gt;::max() &gt;&gt; a &lt; new_string_length) {\n// So `new_string_length &lt;&lt; a` would have been greater than SIZE_T_MAX\n</code></pre>\n\n\n\n<pre><code>(After \"string::~string() noexcept\")\nerror: extra ‘;’\n</code></pre>\n\n<p>You just have an extra <code>;</code> that most compilers ignore. Simple fix, remove it.</p>\n\n<pre><code>error: comparison of unsigned expression &lt; 0 is always false\n if (idx &lt; 0 || idx &gt;= sz_) {\n ~~~~^~~\n</code></pre>\n\n<p>As the error says, since <code>idx</code> is a <code>std::size_t</code> (Unsigned), it can never be less than <code>0</code>. Just remove the check.</p>\n\n<pre><code>(In \"std::ostream&amp; operator &lt;&lt;(std::ostream&amp;, const string&amp;)\")\nerror: conversion to ‘std::streamsize {aka long int}’ from ‘size_t {aka long unsigned int}’ may change the sign of the result\n out.write(str.c_str(), str.size());\n ~~~~~~~~^~\n</code></pre>\n\n<p>For (convoluted) reasons, <code>std::ostream::write</code> takes a signed number for it's count. Just <code>static_cast&lt;std::stream_size&gt;(str.size())</code>.</p>\n\n<pre><code>(In \"string::reverse_iterator string::rend()\")\nerror: negative integer implicitly converted to unsigned type\n return reverse__iterator(this, -1);\n ~^\n</code></pre>\n\n<p>So you obviously want the index before <code>0</code> to be the end. This works, but the index before <code>0</code> is <code>SIZE_T_MAX</code>. But to show clearly that this is what you wanted, you should have casted to a <code>std::size_t</code>: <code>std::size_t{-1}</code> or <code>static_cast&lt;std::size_t&gt;(-1)</code>.</p>\n\n<p>Another warning I have: Use of <code>::size_t</code> (<code>size_t</code> in the global namespace). This is not defined in the C++ standard. You should instead use <code>std::size_t</code> to be compatible with all conforming compilers.</p>\n\n<p>Another bug is in your definition of <code>operator++(int)</code> and <code>operator--(int)</code> for various classes. The \"normal\" definition is: return a copy of the current value, but increment the value (not the copy).</p>\n\n<p>So, it is should look something like this:</p>\n\n<pre><code>T T::operator++(int) noexcept {\n T copy = *this;\n ++*this;\n return copy;\n}\n</code></pre>\n\n<p>Your current implementation just means that <code>++it</code> and <code>it++</code> do the same thing.</p>\n\n<p>As for <code>noexcept</code>, the following functions should be noexcept:</p>\n\n<pre><code>static std::size_t get_appropriate_capacity(std::size_t)\nchar&amp; string::back();\nconst char&amp; string::back() const;\nchar&amp; string::front();\nconst char&amp; string::front() const;\nstring&amp; string::assign(string&amp;&amp; rhs);\n// Also that one should be:\nstring&amp; string::assign(string&amp;&amp; rhs) noexcept { (*this) = std::move(rhs); return *this; }\n// Otherwise it doesn't move (`rhs` is an lvalue)\nchar&amp; string::operator[](std::size_t); // Though this one's debatable\nconst char&amp; string::operator[](std::size_t) const; // Same with this one\n</code></pre>\n\n<p>Your <code>void string::clear()</code> should <em>not</em> be <code>noexcept</code>. It calls <code>std::make_unique</code>, which could throw. If you do want to make a <code>noexcept</code> version, you could do something like this:</p>\n\n<pre><code>void string::clear() noexcept {\n try {\n ptr_ = std::make_unique&lt;char[]&gt;(default_capacity_ + 1);\n current_capacity_ = default_capacity_;\n } catch (const std::bad_alloc&amp;) { /* Reuse old capacity */ }\n ptr_.get()[0] = '\\0';\n sz_ = 0;\n}\n</code></pre>\n\n<p>Consider removing <code>string&amp; string::append(string&amp;&amp; rhs);</code> and <code>string&amp; string::operator+=(string&amp;&amp;)</code> (Since you make a copy anyways).</p>\n\n<p>Also, all your <code>operator==</code> which take <code>string&amp;&amp;</code> are unnecessary. An rvalue can bind to a <code>const string&amp;</code> just fine, and you don't mutate, let alone move, the arguments anyways, so there just isn't any point.</p>\n\n<p>Consider reimplementing <code>void string::swap(string&amp;)</code>. Currently, it makes a temporary copy. You could just <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/swap\" rel=\"nofollow noreferrer\"><code>swap</code></a> the data pointers, and swap the members. This would also be <code>noexcecpt</code>.</p>\n\n<pre><code>void string::swap(string&amp; rhs) noexcept {\n using std::swap;\n swap(current_capacity_, rhs.current_capacity_);\n swap(sz_, rhs.sz_);\n swap(ptr_, rhs.ptr_);\n}\n</code></pre>\n\n<p>Also, have a look where you use <code>std::strcpy</code>. This is guaranteed to not do what you expect if a string has a <code>'\\0'</code> in it. E.g.: <code>string s = string{\"\"}+'\\0'+'\\0'; string copy = s; copy == s // false</code>. Use <code>memcpy</code> with the number of characters you are copying (Usually the fix would be: <code>std::strcpy(a, other.ptr_.get())</code> -> <code>std::memcpy(a, other.ptr_.get(), other.sz_ + 1); // + 1 for nul terminator</code>)</p>\n\n<p>These functions should be <code>const</code>:</p>\n\n<pre><code>const_iterator string::cbegin() const;\nconst_iterator string::cend() const;\nconst_reverse_iterator string::crbegin() const;\nconst_reverse_iterator string::crend() const;\n</code></pre>\n\n<h3>Design</h3>\n\n<p>You don't overload <code>operator&lt;</code> and friends, so it's hard to compare strings.</p>\n\n<p>As for how you handle memory allocation, you are a bit too eager. Reallocation is expensive (As it is allocate + copy in this case). You should only use <code>get_appropriate_capacity</code> when the new size would be bigger than the current capacity.</p>\n\n<p>As for your <code>get_appropriate_capacity</code> function itself, it seems pretty good.</p>\n\n<p>As a side note, try using <a href=\"https://en.cppreference.com/w/cpp/iterator/reverse_iterator\" rel=\"nofollow noreferrer\"><code>std::reverse_iterator</code></a> instead of implementing a completely seperate class. Also, I don't know if you were reimplementing it on purpose, but <code>string::iterator</code> can just be <code>char*</code>, and <code>string::const_iterator</code> as <code>const char*</code>.</p>\n\n<p>You might also want to expose <code>current_capacity_</code> as a member function like: <code>std::size_t string::capacity() const noexcept { return current_capacity_; }</code></p>\n\n<p>Also, to actually make your class \"Swappable\", you need to have a free function <code>swap</code>:</p>\n\n<pre><code>// .h file\nnamespace kapil {\n void swap(string&amp;, string&amp;) noexcept;\n}\n// .cpp file\nnamespace kapil {\n void swap(string&amp; rhs, string&amp; lhs) noexcept {\n rhs.swap(lhs);\n }\n}\n</code></pre>\n\n<p>As a next goal, try to implement custom <code>CharT</code>s (Have a template class, so you can use <code>wchar</code> instead of <code>char</code> easily), custom <a href=\"https://en.cppreference.com/w/cpp/named_req/CharTraits\" rel=\"nofollow noreferrer\">\"CharTraits\"</a> (Another template argument, like <a href=\"https://en.cppreference.com/w/cpp/string/char_traits\" rel=\"nofollow noreferrer\"><code>std::char_traits&lt;CharT&gt;</code></a>) and finally custom <a href=\"https://en.cppreference.com/w/cpp/named_req/Allocator\" rel=\"nofollow noreferrer\">\"Allocators\"</a> as the third template argument. These are the 3 template arguments that are used with <a href=\"https://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\"><code>std::basic_string</code></a> (<code>std::string</code> is <code>std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt;&gt;</code>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T18:06:02.397", "Id": "407414", "Score": "0", "body": "Dear @Artyer\nI have some further clarifications :\n\n[1] I have not made the following functions as 'noexcept' since these may have undefined behavior for empty strings.\n`char& string::back();\nconst char& string::back() const;\nchar& string::front();\nconst char& string::front() const;`\n\n[2] In your comment \n`if (std::numeric_limits<std::size_t>::max() >> a < new_string_length) {\n// So `new_string_length << a` would have been greater than SIZE_T_MAX`\nwhat is 'a' ?\n\nI am extremely glad that you took out time to review my code :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:26:17.810", "Id": "407568", "Score": "0", "body": "@kapil `a` is anything you want. In your case, `a` would have been `1`. That is just a general check for if `x << a` overflows.\n\nUndefined behaviour is still `noexcept`, as in if the preconditions are met (string is not empty) it will never thow. I personally would make it noexcept, but many people wouldn't. Same reasoning for `operator[]`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T01:36:38.757", "Id": "210717", "ParentId": "210707", "Score": "5" } } ]
{ "AcceptedAnswerId": "210717", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T19:58:23.907", "Id": "210707", "Score": "4", "Tags": [ "c++", "strings", "c++11" ], "Title": "C++ string class implementation, providing support for various C++11 features" }
210707
<p>The script below uses an ArcPy package which helps to create buffer of the impact around a location where a blast occurs(user entered), intersects with building footprint which is the point of interest to figure out if the blast impact will be there on the point of interest. This I am intending to use for blast analysis and the impact it does on the point of interest.</p> <p>So far the code runs fine without any issues, however, I was curious if someone could sense check the code and review it for a better way to write the same and any modifications that could help. It's a simple though a long code so I am not expecting anyone to rewrite the entire code, but any alternative style or corrections in error handling to make it more efficient will be helpful.</p> <pre><code>import arcpy import sys,os import datetime from datetime import datetime arcpy.env.overwriteOutput = True ##Tool input## Pfc = arcpy.GetParameterAsText(0)##Blast locations idField = arcpy.GetParameterAsText(1) ##Blast ID field - can be object id or user defined/named field pointID = arcpy.GetParameterAsText(2) ##ID of blast location to be used (Amazon = Front Entrance or Loading Bay) bFootprints = arcpy.GetParameterAsText(3)##Building footprint totalEx = arcpy.GetParameterAsText(4) ##Total building exposure buildType = arcpy.GetParameterAsText(5) ##Building construction type - this influences loss ratios outGDB = arcpy.GetParameterAsText(6)##Output Location (gdb) buffName = arcpy.GetParameterAsText(7) ##Buffer name - this will persist for intersect name(s) too BlastZones = arcpy.GetParameterAsText(8) ##Blast zones to use - DHS or Lloyds. BlastSize = arcpy.GetParameterAsText(9) ##Blast size - drop down list outCorName = arcpy.GetParameterAsText(10) ##output coordinate system - drop down list lossTable = arcpy.GetParameterAsText(11) ##Output loss table (to GDB) outShape = arcpy.GetParameterAsText(12) ##Output to shapefile - T or F outCSV = arcpy.GetParameterAsText(13) ##Output loss table as csv - T or F ##NAD 83 NAD83 = arcpy.SpatialReference(6350) ##WGS 84 Web Mercator WebMerc = arcpy.SpatialReference(3857) ##BNG BNG = arcpy.SpatialReference(27700) ##Check if being run in ArcMap - if yes, change some variables if 'ArcMap.exe' in os.path.basename(sys.executable): ##Alter Pfc desc = arcpy.Describe(Pfc) Pfc = str(desc.path) + "\\" + desc.name ##Alter fc desc = arcpy.Describe(Pfc) fc = str(desc.path) + "\\" + desc.name ####Processing starts here...#### ##Set output coordinates if outCorName == "NAD83": outCor = NAD83 elif outCorName == "WebMerc": outCor = WebMerc elif outCorName == "BNG": outCor = BNG ##Set csv and shapefile output location outFolder = os.path.join(outGDB.rsplit("\\",1)[0],str(buffName+"_output")) if os.path.exists(outFolder): pass else: arcpy.CreateFolder_management(outGDB.rsplit("\\",1)[0],str(buffName+"_output")) ##UID field - used in update cursor BF_name = bFootprints.rsplit("\\",1)[1] ####Set blast size(s) and associated loss ratios if BlastZones == "Lloyds": if BlastSize == "Backpack": blastSize = "36;65;104" LR1 = 0.8 LR2 = 0.4 LR3 = 0.05 elif BlastSize == "truck1Ton": blastSize = "121;213;338" LR1 = 0.8 LR2 = 0.4 LR3 = 0.05 elif BlastSize == "truck2Ton": blastSize = "656;1312;1640" LR1 = 1 LR2 = 0.25 LR3 = 0.1 if BlastZones == "DHS": if BlastSize == "Backpack": blastSize = "26;80;125" LR1 = 1 LR2 = 0.25 LR3 = 0.1 elif BlastSize == "truck1Ton": blastSize = "85;260;375" LR1 = 1 LR2 = 0.25 LR3 = 0.1 elif BlastSize == "truck2Ton": blastSize = "100;335;500" LR1 = 1 LR2 = 0.25 LR3 = 0.1 elif BlastSize == "truck5Ton": blastSize = "140;450;640" LR1 = 1 LR2 = 0.25 LR3 = 0.1 elif BlastSize == "truck6Ton": blastSize = "175;590;980" LR1 = 1 LR2 = 0.25 LR3 = 0.1 ##Set for area calc. geom = "AREA_GEODESIC" ##Add new fields to building footprints - to store intersected blast radius tmp = blastSize.rsplit(";") Field1 = "BuildingArea" Field2 = "AREA_GEO" fList = [Field1,Field2] ##sList = [Field1,Field2,Field3,Field4] TField1 = "DamageLevel" TField2 = "ImpactZoneByFeet" TField3 = "PropertyFootprint_Area" TField4 = "PropertyImpacted_Area" TField5 = "TotalExposure" TField6 = "ImpactRatio" TField7 = "ImpactExposure" TField8 = "LossRatio" TField9 = "Loss" TablefList = [TField1,TField2,TField3,TField4,TField5,TField6,TField7,TField8,TField9] tExp = float(totalEx) IZ1 = tmp[0] IZ2 = tmp[1] IZ3 = tmp[2] tableTemplate = r"O:\LossTable" ##Building intersection function## def buildIntersect(outInt,fields,fc): with arcpy.da.SearchCursor(outInt,fields) as sCursor: for row in sCursor: bID = str(row[0]) BR = int(row[1]) intArea = row[2] where = "OBJECTID = " + bID with arcpy.da.UpdateCursor(fc,fList,where) as uCursor: for row in uCursor: if BR == int(tmp[0]): row[0] = intArea elif BR == int(tmp[1]): row[1] = intArea elif BR == int(tmp[2]): row[2] = intArea uCursor.updateRow(row) del sCursor, uCursor ##Loss Table function## def LossTable(fc, TablefList, tableName): bArea = [] intArea = [] with arcpy.da.SearchCursor(fc,fList) as sCursor: for row in sCursor: bArea.append(row[0]) intArea.append(row[1]) del sCursor table = os.path.join(outGDB,tableName) arcpy.CopyRows_management(tableTemplate,table) with arcpy.da.UpdateCursor(table,TablefList) as uCursor: for row in uCursor: DL = row[0] if DL == "Heavy": row[1] = IZ1 row[2] = bArea[0] row[3] = intArea[0] row[4] = totalEx row[5] = row[3]/row[2] row[6] = int(row[4])*row[5] row[7] = LR1 row[8] = row[6]*row[7] elif DL == "Moderate": row[1] = IZ2 row[2] = bArea[0] row[3] = intArea[1] row[4] = totalEx row[5] = row[3]/row[2] row[6] = int(row[4])*row[5] row[7] = LR2 row[8] = row[6]*row[7] elif DL == "Light": row[1] = IZ3 row[2] = bArea[0] row[3] = intArea[2] row[4] = totalEx row[5] = row[3]/row[2] row[6] = int(row[4])*row[5] row[7] = LR3 row[8] = row[6]*row[7] uCursor.updateRow(row) del uCursor OutTableName = str(tableName) +".csv" if str(outCSV) == "true": arcpy.TableToTable_conversion(table,outFolder,OutTableName) arcpy.AddMessage("Loss calculation table created and saved in: " + outFolder) ##Output shapefile function## def OutShapes(fcList,outFolder): for fc in fcList: outShp = str(fc.rsplit("\\",1)[1])+".shp" print(outShp) arcpy.FeatureClassToFeatureClass_conversion(fc,outFolder,outShp) try: ##Blast Pressures Pres_1 = 10 Pres_2 = 2 Pres_3 = 1 ####Processing starts here#### fcList = [] if type(pointID) == str: pointID = "'"+pointID+"'" print(pointID) field = str(idField) where = field +" = " + str(pointID) memoryFeature = "in_memory" + "\\" + "myMemoryFeature" arcpy.Select_analysis(Pfc, memoryFeature, where) baseName = buffName buffName = os.path.join(outGDB,str(baseName + "_Buffer")) fcList.append(buffName) ##Add geometry in selected CRS to building footprints arcpy.AddGeometryAttributes_management(bFootprints,geom,"","",outCor) arcpy.AddMessage("Geometry added") ##Add field if needed if len(arcpy.ListFields(bFootprints,"BuildingArea"))&gt;0: print("Building area field exists") else: arcpy.AddField_management(bFootprints, "BuildingArea", "DOUBLE") arcpy.CalculateField_management(bFootprints, "BuildingArea", "!AREA_GEO!",expression_type="PYTHON_9.3") fcList.append(bFootprints) print("Buffering...") arcpy.MultipleRingBuffer_analysis(memoryFeature, buffName, Distances=blastSize, Buffer_Unit="Feet", Field_Name="BlastRadius", Dissolve_Option="ALL", Outside_Polygons_Only="FULL") arcpy.AddMessage("Buffering done") print("Buffering done") tableName = baseName + "_LossTable" arcpy.Delete_management(memoryFeature) ##Intersect buffer with building footprint Buff = os.path.join(outGDB,str(baseName + "_Buffer")) outInt = os.path.join(outGDB,str(baseName+"_BuildingIntersect")) fcList.append(outInt) print("Intersecting...") arcpy.Intersect_analysis(in_features = [Buff, bFootprints], out_feature_class=outInt, join_attributes="ALL", output_type = "INPUT") arcpy.AddGeometryAttributes_management(outInt,geom,"","",outCor) ##Update bFootprints with intersected values where building ID and blast radius match arcpy.AddMessage("Intersecting complete") print("Intersecting complete") if str(lossTable) == "true": tableName = str(baseName) + "_LossTable" LossTable(outInt,TablefList,tableName) if str(outShape) == "true": OutShapes(fcList,outFolder) arcpy.AddMessage("Feature classes copied to shapefile in the folder: " + outFolder) except Exception, e: import traceback, sys, os tb = sys.exc_info()[2] print("Line %i" % tb.tb_lineno) arcpy.AddMessage("Line %i" % tb.tb_lineno) arcpy.AddMessage(str(e)) arcpy.AddMessage(arcpy.GetMessages()) print(str(e)) finally: del arcpy </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:38:34.953", "Id": "407964", "Score": "0", "body": "If you want to have this question deleted, the process for asking for deletion of an answered question is described in http://meta.stackexchange.com/a/5222/213556" } ]
[ { "body": "<p>Congratulations on the development. I have been able to verify some lines of code that can be better managed with the module \"os\" in order to take advantage of it more since you have it imported.\nI also suggest using the MakeFeatureLayer tool instead of Select_analysis, since the latter has a much longer processing time, in addition, the purpose in that section is to obtain a temporary layer in the processing.\nI also suggest assigning variables to the operations, to facilitate the use during the process.\nI suspect that in the section where the arcpy.da cursors are used, you can also optimize but for this it would be necessary to perform the tests with the ScripTool and real information.\nExcuse my English, I'm from Perú, greetings.</p>\n\n<pre><code>outFolder = os.path.abspath(os.path.join(outGDB, '../%s_output' % buffName))\n# outFolder = os.path.join(outGDB.rsplit(\"\\\\\",1)[0],str(buffName+\"_output\"))\n\n#------------------------------------------------------------------------------\n\nif not os.path.exists(outFolder):\n arcpy.CreateFolder_management(os.path.dirname(outFolder), os.path.basename(outFolder))\n\n# if os.path.exists(outFolder):\n# pass\n# else:\n# arcpy.CreateFolder_management(outGDB.rsplit(\"\\\\\",1)[0],str(buffName+\"_output\"))\n\n#------------------------------------------------------------------------------\n\n##UID field - used in update cursor\nBF_name = os.path.basename(bFootprints)\n# BF_name = bFootprints.rsplit(\"\\\\\",1)[1]\n\n#------------------------------------------------------------------------------\n\nprint(\"Buffering...\")\narcpy.MultipleRingBuffer_analysis(mfl, buffName, Distances=blastSize, \nBuffer_Unit=\"Feet\", Field_Name=\"BlastRadius\", Dissolve_Option=\"ALL\", \nOutside_Polygons_Only=\"FULL\")\n\n# arcpy.MultipleRingBuffer_analysis(memoryFeature, buffName, Distances=blastSize, \n# Buffer_Unit=\"Feet\", Field_Name=\"BlastRadius\", Dissolve_Option=\"ALL\", \n# Outside_Polygons_Only=\"FULL\")\n\n#------------------------------------------------------------------------------\n\narcpy.Delete_management(mfl)\n# arcpy.Delete_management(memoryFeature)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T16:42:04.530", "Id": "210941", "ParentId": "210709", "Score": "1" } }, { "body": "<p>Reading this code, two immediate things came to mind:</p>\n\n<ol>\n<li><p>use multi-assignments. Instead of:</p>\n\n<pre><code>for row in sCursor:\n bID = str(row[0])\n BR = int(row[1])\n intArea = row[2]\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>for (bID, BR, intArea) in sCursor:\n bID, BR = str(bID), int(BR)\n</code></pre>\n\n<p>and instead of:</p>\n\n<pre><code>tmp = blastSize.rsplit(\";\")\nIZ1 = tmp[0]\nIZ2 = tmp[1]\nIZ3 = tmp[2]\n</code></pre>\n\n<p>you can just do:</p>\n\n<pre><code>IZ1, IZ2, IZ3 = blastSize.rsplit(\";\")\n</code></pre></li>\n<li><p>use dicts instead of chained if..then. Instead of:</p>\n\n<pre><code>if BlastZones == \"DHS\":\nif BlastSize == \"Backpack\":\n blastSize = \"26;80;125\"\n LR1 = 1\n LR2 = 0.25\n LR3 = 0.1\nelif BlastSize == \"truck1Ton\":\n blastSize = \"85;260;375\"\n LR1 = 1\n LR2 = 0.25\n LR3 = 0.1\nelif BlastSize == \"truck2Ton\":\n blastSize = \"100;335;500\"\n LR1 = 1\n LR2 = 0.25\n LR3 = 0.1\nelif BlastSize == \"truck5Ton\":\n blastSize = \"140;450;640\"\n LR1 = 1\n LR2 = 0.25\n LR3 = 0.1\nelif BlastSize == \"truck6Ton\":\n blastSize = \"175;590;980\"\n LR1 = 1\n LR2 = 0.25\n LR3 = 0.1\n</code></pre>\n\n<p>you can do:</p>\n\n<pre><code>blastSizes = {\"Backpack\": \"26;80;125\",\n \"truck1Ton\": \"85;260;375\",\n \"truck2Ton\": \"100;335;500\",\n \"truck5Ton\": \"140;450;640\",\n \"truck6Ton\": \"175;590;980\"\n }\n\nif BlatZones == \"DHS\":\n LR1, LR2, LR3 = 1, 0.25, 1\n blastSize = blastSizes[BlastSize]\n</code></pre></li>\n<li><p>avoid empty statements. Instead of:</p>\n\n<pre><code>if os.path.exists(outFolder):\n pass\nelse:\n arcpy.CreateFolder_management(outGDB.rsplit(\"\\\\\",1)[0],str(buffName+\"_output\"))\n</code></pre>\n\n<p>use your boolean operators:</p>\n\n<pre><code> if not os.path.exists(outFolder):\n arcpy.CreateFolder_management(outGDB.rsplit(\"\\\\\",1)[0],str(buffName+\"_output\")) \n</code></pre></li>\n<li><p>use introspection. Instead of:</p>\n\n<pre><code>##Set output coordinates\nif outCorName == \"NAD83\":\n outCor = NAD83\nelif outCorName == \"WebMerc\":\n outCor = WebMerc\nelif outCorName == \"BNG\":\n outCor = BNG\n</code></pre>\n\n<p>you can do:</p>\n\n<pre><code>outCor = locals()[outCorName]\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T00:32:16.790", "Id": "407802", "Score": "0", "body": "\"use scatter/gather\" That's not what you showed. Scatter/gather is the name of a vectored I/O strategy. What you're doing is tuple assignment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T20:19:12.573", "Id": "210944", "ParentId": "210709", "Score": "1" } }, { "body": "<h2>Don't confuse module and module symbol imports</h2>\n\n<p>You wrote this:</p>\n\n<pre><code>import datetime\nfrom datetime import datetime\n</code></pre>\n\n<p>which is both confusing and unnecessary. It doesn't seem that you use <code>datetime</code> anywhere, so just delete these lines. Even if you did need to use <code>datetime</code>, choose one or the other - either just import the module and use it for qualified names, or import symbols from it - not both.</p>\n\n<h2>Make some functions</h2>\n\n<p>You don't have any functions. Everything is hanging out in the same global scope. This is cluttered, difficult to read and difficult to maintain and debug. Write some functions!</p>\n\n<h2>Make the computer do the repetition</h2>\n\n<p>This:</p>\n\n<pre><code>Pfc = arcpy.GetParameterAsText(0)##Blast locations\nidField = arcpy.GetParameterAsText(1) ##Blast ID field - can be object id or user defined/named field\npointID = arcpy.GetParameterAsText(2) ##ID of blast location to be used (Amazon = Front Entrance or Loading Bay)\nbFootprints = arcpy.GetParameterAsText(3)##Building footprint\ntotalEx = arcpy.GetParameterAsText(4) ##Total building exposure\nbuildType = arcpy.GetParameterAsText(5) ##Building construction type - this influences loss ratios\noutGDB = arcpy.GetParameterAsText(6)##Output Location (gdb)\nbuffName = arcpy.GetParameterAsText(7) ##Buffer name - this will persist for intersect name(s) too\nBlastZones = arcpy.GetParameterAsText(8) ##Blast zones to use - DHS or Lloyds.\nBlastSize = arcpy.GetParameterAsText(9) ##Blast size - drop down list\noutCorName = arcpy.GetParameterAsText(10) ##output coordinate system - drop down list\nlossTable = arcpy.GetParameterAsText(11) ##Output loss table (to GDB)\noutShape = arcpy.GetParameterAsText(12) ##Output to shapefile - T or F\noutCSV = arcpy.GetParameterAsText(13) ##Output loss table as csv - T or F\n</code></pre>\n\n<p>should be populating either a class, or maybe a dictionary. If you do it as a dictionary, then:</p>\n\n<pre><code>vars = {name: arcpy.GetParameterAsText(i)\n for i, name in enumerate((\n 'Pfc', # Blast ID field - can be object ID or user defined/named field\n 'idField', # ID of blast location to be used\n # ...\n ))\n }\n</code></pre>\n\n<h2>Use OS methods</h2>\n\n<p>This seems harmless:</p>\n\n<pre><code>Pfc = str(desc.path) + \"\\\\\" + desc.name\n</code></pre>\n\n<p>though it could be cleaned up somewhat by the use of a raw f-string:</p>\n\n<pre><code>Pfc = rf'{desc.path}\\{desc.name}'\n</code></pre>\n\n<p>But wait! Not all operating systems use a backslash as a path separator! So instead you should do</p>\n\n<pre><code>Pfc = os.path.join(desc.path, desc.name)\n</code></pre>\n\n<h2>Just use literals</h2>\n\n<p>This:</p>\n\n<pre><code>TField1 = \"DamageLevel\"\nTField2 = \"ImpactZoneByFeet\"\nTField3 = \"PropertyFootprint_Area\"\nTField4 = \"PropertyImpacted_Area\"\nTField5 = \"TotalExposure\"\nTField6 = \"ImpactRatio\"\nTField7 = \"ImpactExposure\"\nTField8 = \"LossRatio\"\nTField9 = \"Loss\"\nTablefList = [TField1,TField2,TField3,TField4,TField5,TField6,TField7,TField8,TField9]\n</code></pre>\n\n<p>should really just be</p>\n\n<pre><code>table_f_list = [\n 'DamageLevel',\n 'ImpactZoneByFeet',\n # ...\n]\n</code></pre>\n\n<h2>Parametrize hard-coded paths</h2>\n\n<p>If this <em>never</em> changes:</p>\n\n<pre><code>tableTemplate = r\"O:\\LossTable\"\n</code></pre>\n\n<p>then it should be made capitalized (<code>TABLE_TEMPLATE</code>). However, it'd be better represented as an environmental variable or command-line argument.</p>\n\n<h2>Don't use comma notation for exceptions</h2>\n\n<p>This:</p>\n\n<pre><code>except Exception, e:\n</code></pre>\n\n<p>should be converted to the \"new\" (Python 2.6 and later, so... really not new at all) syntax:</p>\n\n<pre><code>except Exception as e:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T00:48:46.790", "Id": "210953", "ParentId": "210709", "Score": "2" } } ]
{ "AcceptedAnswerId": "210941", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T20:12:42.203", "Id": "210709", "Score": "5", "Tags": [ "python", "arcpy" ], "Title": "Python code for buffer creation and intersection" }
210709
<p>I have written a Java Program to place a bunch of rectangles into the smallest possible rectangluar area(no overlapping and rotating).</p> <p>Here is a short summary:</p> <p>I calculate minArea and maxArea:</p> <p>minArea: minArea is sum up all given rectangle areas.</p> <p>maxArea: put all given rectangles side by side, maxArea is rectangle area in which all given rectangles fit in.</p> <p>Between minArea and maxArea must exist the smallest rectangular area, in which all given rectangles fit in.</p> <p>For each rectangular area between minArea and maxArea I try recursiv, if all given rectangles fit in the rectangular area.</p> <p>Example input/output:</p> <pre><code>(height,width of rectangles) 2,3 4,4 5,5 7,2 1,1 9,3 1 1 1 2 2 2 2 6 6 6 1 1 1 2 2 2 2 6 6 6 4 4 5 2 2 2 2 6 6 6 4 4 0 2 2 2 2 6 6 6 4 4 3 3 3 3 3 6 6 6 4 4 3 3 3 3 3 6 6 6 4 4 3 3 3 3 3 6 6 6 4 4 3 3 3 3 3 6 6 6 4 4 3 3 3 3 3 6 6 6 </code></pre> <p>0 represents free space, all other numbers are for differentiating rectangles.</p> <p>RectanglePacking.java:</p> <pre><code>import java.util.ArrayList; import java.util.Scanner; import java.awt.Point; import java.io.IOException; class Rectangle { public int id; public int width; public int height; public Rectangle(int height, int width, int id) { this.width = width; this.height = height; this.id = id; } } public class RectanglePacking { private ArrayList&lt;Rectangle&gt; rectangleList = new ArrayList&lt;Rectangle&gt;(); private int minArea; private int maxArea; private int getMinArea() { for (Rectangle r : rectangleList) { minArea = minArea + r.height * r.width; } return minArea; } private int getMaxArea() { int totalWidth = 0; int height = 0; int maxHeight = 0; for (Rectangle r : rectangleList) { totalWidth = totalWidth + r.width; height = r.height; if (height &gt;= maxHeight) { maxHeight = height; } } maxArea = totalWidth * maxHeight; return maxArea; } private ArrayList&lt;Point&gt; possiblePlaces(int field[][], int id) { ArrayList&lt;Point&gt; places = new ArrayList&lt;Point&gt;(); for (int i = 0; i &lt; field.length; i++) { for (int j = 0; j &lt; field[0].length; j++) { if (isEmpty(field, i, j, rectangleList.get(id).height, rectangleList.get(id).width)) { places.add(new Point(i, j)); } } } return places; } public boolean isEmpty(int[][] field, int x, int y, int height, int width) { for (int i = x; i &lt; x + height; i++) { for (int j = y; j &lt; y + width; j++) { if (i &gt; field.length - 1 || j &gt; field[0].length - 1 || field[i][j] != 0) { return false; } } } return true; } private int[][] markRectangle(int field[][], int x, int y, int height, int width, int id) { id = id + 1; for (int i = x; i &lt; x + height; i++) { for (int j = y; j &lt; y + width; j++) { field[i][j] = id; } } return field; } private void removeRectangle(int field[][], int x, int y, int height, int width) { for (int i = x; i &lt; x + height; i++) { for (int j = y; j &lt; y + width; j++) { field[i][j] = 0; } } } private void placeRectangles(int field[][], int id) { if (id == rectangleList.size()) { printSolution(field); System.exit(0); } ArrayList&lt;Point&gt; possiblePlaces = possiblePlaces(field, id); for (int i = 0; i &lt; possiblePlaces.size(); i++) { Point p = possiblePlaces.get(i); field = markRectangle(field, p.x, p.y, rectangleList.get(id).height, rectangleList.get(id).width, id); placeRectangles(field, id + 1); removeRectangle(field, p.x, p.y, rectangleList.get(id).height, rectangleList.get(id).width); } } private ArrayList&lt;Point&gt; calcPossibleAreas() { ArrayList&lt;Point&gt; possibleAreas= new ArrayList&lt;Point&gt;(); ArrayList&lt;Point&gt; factors = new ArrayList&lt;Point&gt;(); for (int i = getMinArea(); i &lt;= getMaxArea(); i++) { factors = calcFactors(i); for (int j = 0; j &lt; factors.size(); j++) { possibleAreas.add(new Point(factors.get(j).x, factors.get(j).y)); } } return possibleAreas; } private ArrayList&lt;Point&gt; calcFactors(int number) { ArrayList&lt;Point&gt; factors = new ArrayList&lt;Point&gt;(); for (int i = 1; i &lt;= number; i++) { if (number % i == 0) { factors.add(new Point(i, number/i)); factors.add(new Point(number/i, i)); } } return factors; } private void calcMinArea() { ArrayList&lt;Point&gt; possibleAreas = calcPossibleAreas(); int field[][]; for (int i = 0; i &lt; possibleAreas.size(); i++) { int x = possibleAreas.get(i).x; int y = possibleAreas.get(i).y; field = new int[x][y]; placeRectangles(field, 0); } } private void printSolution(int field[][]) { System.out.println("Solution:"); for (int i = 0; i &lt; field.length; i++) { for (int j = 0; j &lt; field[0].length; j++) { System.out.print(" "+field[i][j] + " "); } System.out.println(); } } public static void main(String[] args) throws IOException { RectanglePacking r = new RectanglePacking(); Scanner input = new Scanner(System.in); int id = 1; try { while (true) { String line = input.nextLine(); if (line.equals("")) { break; } String split[] = line.split(","); int height = Integer.parseInt(split[0]); int width = Integer.parseInt(split[1]); r.rectangleList.add(new Rectangle(height, width, id)); id++; } input.close(); } catch (Exception ex) { ex.printStackTrace(); } r.calcMinArea(); } } </code></pre> <p>How can I improve my code?</p> <p>Any help is really appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T10:38:05.770", "Id": "407496", "Score": "0", "body": "Change your algortihm to https://www.ijcai.org/Proceedings/09/Papers/092.pdf" } ]
[ { "body": "<blockquote>\n <p>For each rectangular area between minArea and maxArea I [test recursively] if all given rectangles fit in the rectangular area.</p>\n</blockquote>\n\n<p>My first comment is that this subproblem seems like a perfect application for <a href=\"https://en.wikipedia.org/wiki/Dancing_Links\" rel=\"nofollow noreferrer\">Dancing Links</a>.\nIt won't solve your entire problem (the \"area minimization\" problem), but it will very quickly solve your subproblem (the \"can I fit all the rectangles into this other rectangle\" problem).</p>\n\n<hr>\n\n<p>It is weird that your <code>markRectangle</code> function returns a value (the value of <code>field</code>, which is just its first parameter), but your <code>removeRectangle</code> function returns void. I would expect both of them to return void.</p>\n\n<hr>\n\n<p>Let's see how you compute \"each rectangular area between minArea and maxArea\". Slightly reformatted for whitespace:</p>\n\n<pre><code>private ArrayList&lt;Point&gt; calcPossibleAreas() {\n ArrayList&lt;Point&gt; possibleAreas = new ArrayList&lt;Point&gt;();\n ArrayList&lt;Point&gt; factors = new ArrayList&lt;Point&gt;();\n for (int i = getMinArea(); i &lt;= getMaxArea(); ++i) {\n factors = calcFactors(i);\n for (int j = 0; j &lt; factors.size(); ++j) {\n possibleAreas.add(new Point(factors.get(j).x, factors.get(j).y));\n }\n }\n return possibleAreas;\n}\n</code></pre>\n\n<p>Calculating <code>getMaxArea()</code> every time through the loop is silly. <em>Also</em>, you set <code>factors</code> to <code>new ArrayList&lt;Point&gt;()</code> at the top of the function, and then immediately throw away that value by assigning it a new value inside the loop. So at the bare minimum, I'd expect</p>\n\n<pre><code>private ArrayList&lt;Point&gt; calcPossibleAreas() {\n ArrayList&lt;Point&gt; possibleAreas = new ArrayList&lt;Point&gt;();\n int maxArea = getMaxArea();\n for (int i = getMinArea(); i &lt;= maxArea; ++i) {\n ArrayList&lt;Point&gt; factors = calcFactors(i);\n for (int j = 0; j &lt; factors.size(); ++j) {\n possibleAreas.add(factors.get(j));\n }\n }\n return possibleAreas;\n}\n</code></pre>\n\n<p>And then (AFAIK) you can use Java 5's <code>for</code>-each loop:</p>\n\n<pre><code>private ArrayList&lt;Point&gt; calcPossibleAreas() {\n ArrayList&lt;Point&gt; possibleAreas = new ArrayList&lt;Point&gt;();\n int maxArea = getMaxArea();\n for (int i = getMinArea(); i &lt;= maxArea; ++i) {\n for (Point factor : calcFactors(i)) {\n possibleAreas.add(factor);\n }\n }\n return possibleAreas;\n}\n</code></pre>\n\n<p>But all that <code>calcFactors</code> is expensive; <em>and</em> you wind up with a lot of 2xN rectangles that can't possibly be filled. So I would rather write it like this:</p>\n\n<pre><code>private ArrayList&lt;Point&gt; calcPossibleAreas() {\n ArrayList&lt;Point&gt; possibleAreas = new ArrayList&lt;Point&gt;();\n int minWidth = 0;\n int maxWidth = 0;\n int minHeight = 0;\n int maxHeight = 0;\n int minArea = 0;\n for (Rectangle r : rectangleList) {\n minWidth = Math.max(minWidth, r.width);\n minHeight = Math.max(minHeight, r.height);\n maxWidth += r.width;\n maxHeight += r.height;\n minArea += r.width * r.height;\n }\n int maxArea = Math.min(maxWidth * minHeight, minWidth * maxHeight);\n for (int x = minWidth; x &lt;= maxWidth; ++x) {\n for (int y = minHeight; y &lt;= maxHeight; ++y) {\n if (minArea &lt;= x * y &amp;&amp; x * y &lt;= maxArea) {\n possibleAreas.add(new Point(x, y));\n }\n }\n }\n // Now sort possibleAreas so we'll try the smaller rectangles first.\n Collections.sort(possibleAreas, new Comparator&lt;Point&gt;() {\n @Override\n public int compare(Point lhs, Point rhs) {\n int la = (lhs.x * lhs.y), ra = (rhs.x * rhs.y);\n return (la &lt; ra) ? -1 : (la &gt; ra);\n }\n });\n}\n</code></pre>\n\n<hr>\n\n<p>Of course, <code>calcPossibleAreas()</code> is just a preliminary step that will be very fast compared to <code>placeRectangles()</code>. So <a href=\"https://en.wikipedia.org/wiki/Amdahl%27s_law\" rel=\"nofollow noreferrer\">Amdahl's Law</a> says that you (and I ;)) should spend time optimizing <code>placeRectangles()</code> rather than <code>calcPossibleAreas()</code>. I would recommend looking at some way to eliminate the <code>O(w*h)</code> writes to <code>field[][]</code> — is there some way you can express \"all these positions are filled\" without actually doing the <code>O(w*h)</code> writes? Vice versa, is there some way you can test \"is this a valid placement for my current rectangle\" without doing <code>O(w*h)</code> reads?</p>\n\n<p>Rather than looking for <em>places to put</em> each <em>rectangle</em>, it might be better to look for <em>ways to fill</em> each point in the target. Pretend you have your set of rectangles, plus just enough \"spare\" 1x1 rectangles to fill up the empty spaces. If you try to fill all the points in the target, working downward from the upper left corner, then you have to try each rectangle in only one position — and you can skip rectangles that are too wide or tall to fit — and if none of your rectangles fit, <em>and</em> you're out of spare 1x1s, then you know it's time to backtrack. (This is essentially how Dancing Links would do it.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T19:36:40.517", "Id": "210759", "ParentId": "210711", "Score": "1" } } ]
{ "AcceptedAnswerId": "210759", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T20:25:56.390", "Id": "210711", "Score": "1", "Tags": [ "java", "performance", "recursion" ], "Title": "Rectangle packing in smallest possible area" }
210711
<p>I have a method that takes a JSON string as input and "fixes" it. By that, I mean, that the JSON string comes in with all values quoted. My method un-quotes the values that shouldn't be quoted (i.e. true, false, numbers, {}, etc). The method was originally doing it by doing 4 string replaces (for the true / false, etc) and regex replace for the numbers. Kind of slow. So I re-wrote it with <code>StringBuilder</code>:</p> <pre><code> protected static string FixupJson(string json) { if (json == null) throw new ArgumentNullException(nameof(json)); int nLen = json.Length; StringBuilder sb = new StringBuilder(nLen); for (int i = 0; i &lt; nLen; i++) { char ch = json[i]; if (ch == ':' &amp;&amp; json[i+1] == ' ' &amp;&amp; json[i + 2] == '\"') { int k = json.IndexOf('\"', i + 3); sb.Append(": "); string g = json.Substring(i + 3, k - i - 3); bool bQuote = true; if (g == "true" || g == "false" || g == "null" || g == "{}") bQuote = false; else if (g == "NaN") bQuote = true; else if (Double.TryParse(g, out double d)) bQuote = false; if (bQuote) sb.Append('\"'); sb.Append(g); if (bQuote) sb.Append('\"'); i = k; } else { sb.Append(ch); } } return sb.ToString(); } </code></pre> <p>This got me a 35% improvement, but I want to see if there is a better approach or if I can get this faster. My first <code>StringBuilder</code> approach, instead of appending char by char would append chunks pulled out with <code>SubString()</code>. That was actually a lot slower then this version.</p> <p>Yes, I understand the right way to do it would be to fix it at the source :), which I do control, but the way the json gets serialized out at the source, I don't know if the value needs to be quoted until the json is fully spit out (or at least until the value is fully spit out) as a single value can be a formatted string from multiple sources (i.e. "myVal": "(this part from one place)|(this part from another place))". So "fixing it there" would mean going from a single <code>String.Format()</code> for the entire json to a bunch of them for each value. Right now the JSON is "pre-rendered" (once) and passed into a <code>String.Format()</code> to fill in the values, so by fixing it there I'd have to go to a bunch of little <code>String.Format()</code>'s to format each value then pass it in to the big <code>String.Format()</code>… so I figure this is a decent compromise.</p> <p>EDIT: Should handle any old json, but this was the one I was using in my test app in C# string format ready to paste :).</p> <p>"{\r\n \"xxx\": \"TRACE|1\",\r\n \"Timestamp\": \"2019-01-01 12:44:36.529\",\r\n \"Message\": {\r\n \"a\": \"bbb\",\r\n \"b1\": {\r\n \"b2\": \"test2\",\r\n \"b3\": \"Test1\",\r\n \"b4\": \"true\",\r\n \"b5\": \"178\"\r\n }\r\n },\r\n \"ThreadId\": \"1\",\r\n \"Exception\": \"{}\"\r\n}"</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T01:28:05.993", "Id": "407348", "Score": "0", "body": "What would the typical json string look like? What does the format method look like? More eyes on it might see an even better solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T02:44:58.313", "Id": "407350", "Score": "0", "body": "@tinstaafl I added the one I am testing with. Basically just any old json. In this case, it should unquote the true, 178, 1 and {}. The json is generated dynamically at runtime based on a user template. My original design for performance was to parse the template once and build a \"shell\" string I could pass into String.Format() with as much of it pre-formatted as possible. For the above example it would start off as \"{\\r\\n \\\"xxx\\\": \\\"{0}|{1}..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T02:47:44.217", "Id": "407351", "Score": "0", "body": "@tinstaafl make sense? Since the template is used over and over, I just pass in the cached string and the params to String.Format()… the problem with that is that for example, I don't know what the {0}|{1} is going to resolve to until the StringFormat is done, so I don't know if I need to quote it. Obviously in that case I would because of the | character :)… but it could just as easily be just {0} and then I wouldn't know what it is... so essentially I need to take the whole value (could be {0}{1} as a better example) at once to decide if I want to quote it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T06:57:21.087", "Id": "407360", "Score": "2", "body": "This is a typical [XY problem](https://en.wikipedia.org/wiki/XY_problem). I think you should have shown us how you create json first instead of trying to fix the serializer _bugs_ later ;-]" } ]
[ { "body": "<p>I find your method for fixing <em>invalid</em> <code>JSON</code> is the worst possible because it treats <code>JSON</code> as a pure <code>string</code> and not a tree of properties/keys and values. This increases the possibility of changing values that might not be values at all. IMO the optimal approach would be to parse it with <code>JSON.NET</code> by using <code>JToken.Parse</code> and recreate the resulting tree with <em>correct</em> values.</p>\n\n<p>You can take a look how it could be done <a href=\"https://codereview.stackexchange.com/questions/208641/chaining-json-transformations-with-visitors\">here</a> where I'm using the <a href=\"https://www.oodesign.com/visitor-pattern.html\" rel=\"nofollow noreferrer\">Visitor Pattern</a> to transform <code>JSON</code> too. </p>\n\n<hr>\n\n<p>But honestly, unless you need to be able to read some old data, you should really fix the serializer so that it outputs valid <code>JSON</code> instead of trying to fix its <em>bugs</em> with even more dirty workarounds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T09:14:23.093", "Id": "210727", "ParentId": "210716", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T00:44:39.913", "Id": "210716", "Score": "2", "Tags": [ "c#", "performance", "json", "escaping" ], "Title": "Unquoting booleans, numbers, etc. in a JSON string" }
210716
<p>Given a chessboard of N size (square matrix), the position of Knight and position of a target, find out minimum steps (both count and exact steps) from start to target for a Knight.</p> <p>If it is not possible to reach to the given position, return -1 as step count.</p> <p>Here is my implementation in Scala (assuming N = 4 or 4X4 chess board):</p> <pre><code>import scala.collection.mutable._ object KnightMoves extends App { case class Pos(row: Int, col: Int) val Size = 4 def calculateMoves(from: Pos, target: Pos ): (Int, Seq[Pos])= { val pendingPos = collection.mutable.Queue[Pos](from) val positionVisited = collection.mutable.HashMap[Pos, (Int, Seq[Pos])](from -&gt; (0, Seq())) var targetReached = false while(pendingPos.nonEmpty &amp;&amp; !targetReached) { val p = pendingPos.dequeue() possibleMoves(p) foreach { position =&gt; if ( position == target) { targetReached = true } else if (!(positionVisited contains position)) { pendingPos enqueue position } positionVisited += position -&gt; ((positionVisited(p)._1 + 1,(positionVisited(p)._2 ++ Seq(p)))) } } if (targetReached) positionVisited(target) else (-1, Seq()) } def isValidPos(position: Pos): Boolean = ((0 until Size) contains position.row) &amp;&amp; ((0 until Size) contains position.col) def possibleMoves(position: Pos): List[Pos] = List(Pos(position.row - 2, position.col + 1), Pos(position.row - 2, position.col - 1), Pos(position.row + 2, position.col + 1), Pos(position.row + 2, position.col - 1), Pos(position.row - 1 , position.col + 2), Pos(position.row - 1 , position.col - 2), Pos(position.row + 1 , position.col + 2), Pos(position.row + 1 , position.col - 2) ) filter( pos =&gt; isValidPos(pos)) println(calculateMoves(Pos(0,1),Pos(0,0))) println(calculateMoves(Pos(0,1),Pos(0,2))) } </code></pre> <p>This program generates the following output for two test statements at bottom.</p> <pre><code>(3,ArrayBuffer(Pos(0,1), Pos(2,0), Pos(1,2))) (3,ArrayBuffer(Pos(0,1), Pos(2,2), Pos(1,0))) </code></pre>
[]
[ { "body": "<p>At first glance, the <code>isValidPos()</code> method looks to be clear and succinct, requiring only two tests to see if the passed position is on the board.</p>\n\n<pre><code>def isValidPos(position: Pos): Boolean =\n ((0 until Size) contains position.row) &amp;&amp; ((0 until Size) contains position.col)\n</code></pre>\n\n<p>But it turns out that the <code>contains()</code> method on a <code>Range</code> is <a href=\"https://github.com/scala/scala/blob/38cd84d976880eab16af17a44d186bbddcd554f2/src/library/scala/collection/immutable/Range.scala#L343\" rel=\"nofollow noreferrer\">a bit complicated</a> and most valid positions will have to pass around 10 <code>if</code> checks before the method returns <code>true</code>, so there are probably more efficient ways to get the same result.</p>\n\n<p>But a bigger question is, can this be done without any mutable collections or variables?</p>\n\n<p>One approach is to create a <code>Knight</code> class that holds all current valid board positions and the history of how each position was arrived at and then, when taking the next step, instead of modifying the <code>Knight</code> instance you create a new immutable <code>Knight</code> instance with all the new information built from the current (old) data.</p>\n\n<pre><code>type Cell = (Int,Int)\n\nclass Knight(dim :Int, history :Map[Cell,Cell], val cells :Set[Cell]) {\n def this(dim :Int, cell :Cell) = this(dim, Map(cell-&gt;(-1,-1)), Set(cell))\n\n def backtrack(cell :Cell) :List[Cell] =\n if (history(cell) == (-1,-1)) cell :: Nil\n else cell :: backtrack(history(cell))\n\n def next :Knight = (new Knight(dim, _:Map[Cell,Cell], _:Set[Cell])).tupled{\n cells.foldLeft((history, Set.empty[Cell])){\n case ((hMap,cSet),(x,y)) =&gt;\n val newSet = Set((x-2, y-1), (x-2, y+1), (x-1, y-2), (x-1, y+2)\n ,(x+1, y-2), (x+1, y+2), (x+2, y-1), (x+2, y+1)\n ).filter{ case (a,b) =&gt;\n a &gt;= 0 &amp;&amp; a &lt; dim &amp;&amp; b &gt;= 0 &amp;&amp; b &lt; dim &amp;&amp; !hMap.keySet((a,b))\n }\n (hMap ++ newSet.map(_ -&gt; (x,y)).toMap, cSet ++ newSet)\n }\n }\n}\n\ndef knightMoves(boardSize :Int, knight :Cell, target :Cell) :List[Cell] = {\n def loop(k1 :Knight, k2 :Knight) :List[Cell] = {\n val met :Set[Cell] = k1.cells.intersect(k2.cells)\n if (met.nonEmpty) k1.backtrack(met.head).reverse ++\n k2.backtrack(met.head).tail\n else if (k1.cells.isEmpty || k2.cells.isEmpty) Nil\n else if (k1.cells.size &gt; k2.cells.size) loop(k1, k2.next)\n else loop(k1.next, k2)\n }\n loop(new Knight(boardSize, knight), new Knight(boardSize, target))\n}\n\nknightMoves(3,(0,1),(1,1)) //res0: List[Cell] = List()\nknightMoves(14,(0,1),(10,12)) //res1: List[Cell] = List((0,1), (2,2), (4,3), (6,4), (7,6), (8,8), (9,10), (10,12))\n</code></pre>\n\n<p>Some efficiency is obtained here by making the target position a <code>Knight</code> instance as well. That way they can \"move\" toward each other and, as soon as they intersect, a path from one to the other is found.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T22:52:11.270", "Id": "212661", "ParentId": "210723", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T05:22:41.937", "Id": "210723", "Score": "1", "Tags": [ "interview-questions", "matrix", "scala", "cache", "chess" ], "Title": "Minimum steps to reach target by a Knight In Scala" }
210723
<p>I am working through a PHP book, and date comparison was mentioned as one of the uses of <code>usort()</code>, so I wrote a date comparison function to use in line with <code>usort()</code>. Writing the function wasn't as easy as I expected (there was a pesky bug which took me a while to identify), so I thought I would submit my comparison code for review. </p> <h2>dates.php</h2> <pre><code>&lt;? function dateParse($date) { return (count(explode("-", $date)) == 3)?(explode("-", $date)):(explode("/", $date)); #Returns the date as an array. } function dateSort($date1, $date2, $format=1) { if ($format == 0) #dd/mm/yyyy format. { list($day1, $month1, $year1) = dateParse($date1); list($day2, $month2, $year2) = dateParse($date2); } elseif ($format == 1) #mm/dd/yyyy format. { list($month1, $day1, $year1) = dateParse($date1); list($month2, $day2, $year2) = dateParse($date2); } elseif ($format == 2) #yyyy/mm/dd format. { list($year1, $month1, $day1) = dateParse($date1); list($year2, $month2, $day2) = dateParse($date2); } $day1 = str_pad($day1, 2, "0", STR_PAD_LEFT); #Adds a leading "0" if the day is a single digit. $day2 = str_pad($day2, 2, "0", STR_PAD_LEFT); #Adds a leading "0" if the day is a single digit. $month1 = str_pad($month1, 2, "0", STR_PAD_LEFT); #Adds a leading "0" if the month is a single digit. $month2 = str_pad($month2, 2, "0", STR_PAD_LEFT); #Adds a leading "0" if the month is a single digit. $x1 = $year1.$month1.$day1; $x2 = $year2.$month2.$day2; return ((int)$x1 &lt;=&gt; (int)$x2); } ?&gt; </code></pre>
[]
[ { "body": "<ul>\n<li><strong><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic numbers</a> are a bad code smell and should be avoided. Use a constant instead.</strong></li>\n</ul>\n\n<p>In your definition of <code>dateSort()</code>, your third parameter is <code>format=1</code>. What does <code>1</code> mean? Without reviewing the code it isn't clear which makes maintaining the code more difficult. A common way to avoid this is to define constants with human readable names and use them in place of the magic numbers. Note that the names of these constants are arbitrary. Name them in such a way that makes sense to the reader what value they hold or reflect.</p>\n\n<pre><code> defined('DATE_FORMAT_EU_SLASHES') || define('DATE_FORMAT_EU_SLASHES', 0);\n defined('DATE_FORMAT_US') || define('DATE_FORMAT_US', 1);\n defined('DATE_FORMAT_YEAR_FIRST') || define('DATE_FORMAT_YEAR_FIRST', 2);\n</code></pre>\n\n<ul>\n<li><strong>Using <code>date_parse()</code> is okay but working with <code>DateTime()</code> objects is preferred.</strong> </li>\n</ul>\n\n<p>PHP offers a lot of ways of working with dates which can be a good or bad thing. In general using <a href=\"http://php.net/manual/en/book.datetime.php\" rel=\"nofollow noreferrer\"><code>DateTime()</code></a> objects are preferred as they were designed specifically for this purpose (and is the most powerful). </p>\n\n<p>Your code can be simplified as <code>DateTime()</code> can parse most date formats natively and also handle not standard formats easily. <code>date_parse()</code> will fail once the format becomes non-standard or irregular.</p>\n\n<p>Additionally, <code>DateTime()</code> objects are comparable so you don't need to output a string variable in a comparable format to do your comparison. Just compare the <em>objects themselves</em>.</p>\n\n<pre><code>$datetime1 = new DateTime($date1);\n$datetime2 = new DateTime($date2);\nreturn datetime1 &lt;=&gt; datetime2;\n</code></pre>\n\n<p>Simpler! </p>\n\n<ul>\n<li><strong>Use a <a href=\"http://php.net/manual/en/control-structures.switch.php\" rel=\"nofollow noreferrer\"><code>switch</code> statement</a> instead of a potentially giant if/else</strong> </li>\n</ul>\n\n<p>Because we can have situations where <code>DateTime()</code> can handle the format natively, there is no need to have an if/else statement for every date format. <code>switch</code> allows us to allow conditions to be handled by the same code block. It also offers us a <code>default</code> option which means we no longer need to define our default format in the function signature and can let the <code>switch</code> statement handle it for us.</p>\n\n<pre><code>defined('DATE_FORMAT_EU_SLASHES') || define('DATE_FORMAT_EU_SLASHES', 0);\ndefined('DATE_FORMAT_US') || define('DATE_FORMAT_US', 1);\ndefined('DATE_FORMAT_YEAR_FIRST') || define('DATE_FORMAT_YEAR_FIRST', 2);\n\nfunction dateSort($date1, $date2, $format = null)\n switch ($format) {\n case DATE_FORMAT_EU_SLASHES :\n // DateTime::createFromFormat() offers us flexibility\n $datetime1 = DateTime::createFromFormat('d/m/Y', $date1);\n $datetime2 = DateTime::createFromFormat('d/m/Y', $date2);\n break;\n case DATE_FORMAT_US :\n case DATE_FORMAT_YEAR_FIRST :\n default :\n // DateTime() can handle both formats natively so no need to handle them \n // individually. You can also ad formats like YYYY-MM-DD with only a couple \n // of lines of code\n $datetime1 = new DateTime($date1);\n $datetime2 = new DateTime($date2);\n break;\n }\n return datetime1 &lt;=&gt; datetime2;\n} \n</code></pre>\n\n<p>If you want to take it a step further, you could simplify your code and only specify when the format is non-standard and handle them specifically. Otherwise, fall to the default date handler:</p>\n\n<pre><code>defined('DATE_FORMAT_EU_SLASHES') || define('DATE_FORMAT_EU_SLASHES', 0);\n\nfunction dateSort($date1, $date2, $format = null)\n switch ($format) {\n case DATE_FORMAT_EU_SLASHES :\n $datetime1 = DateTime::createFromFormat('d/m/Y', $date1);\n $datetime2 = DateTime::createFromFormat('d/m/Y', $date2);\n break;\n default :\n $datetime1 = new DateTime($date1);\n $datetime2 = new DateTime($date2);\n break;\n }\n return datetime1 &lt;=&gt; datetime2;\n} \n</code></pre>\n\n<p><sup>*None of this code is tested -- I just wrote it off of the top of my head -- but hopefully it gives you ideas about how to improve this code</sup></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T13:28:07.257", "Id": "407381", "Score": "0", "body": "Thank you very much. The entry on magic numbers was enlightening, and I'll take note of that in the future." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T13:04:24.173", "Id": "210737", "ParentId": "210732", "Score": "3" } }, { "body": "<p>I only have one addition to make to John's excellent review...</p>\n\n<p>When you have a strictly formatted <code>$format == 2</code> scenario where no zero padding is necessary, you can avoid prepping, parsing, or even generating DateTime objects. So long as the delimiters are the same throughout, they do not matter.</p>\n\n<p>Comparing the values as strings will offer the same sorting behavior with an absolute minimum expense.</p>\n\n<pre><code>return $date1 &lt;=&gt; $date2;\n</code></pre>\n\n<p>...for this reason, <code>sort()</code> is actually all that you need in this one/specific scenario.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:25:45.037", "Id": "210821", "ParentId": "210732", "Score": "1" } }, { "body": "<h3>Closing PHP in a PHP-only file</h3>\n\n<p>In PHP, it may look like <code>&lt;?php</code> and <code>?&gt;</code> are paired in the same way as <code>{</code> and <code>}</code> or <code>()[]</code>, etc. But they actually aren't. Each file starts in HTML context. That means that it just blats out whatever you write. This is normally used to display HTML. When you use <code>&lt;?php</code> or <code>&lt;?</code>, it switches to PHP context, where it evaluates what you write as PHP code. In many (most) files, you will do this on the first line, so that you can write comments about copyright and licensing. </p>\n\n<p>In your case, you are writing PHP only. You only need to open the PHP block. You do not need to close it with a <code>?&gt;</code>. In general, if your file only contains PHP and never needs to enter HTML context, you leave off any final <code>?&gt;</code>. </p>\n\n<p>One reason for this is that if you put anything in HTML context after a closing <code>?&gt;</code>, PHP blats it out as if it were HTML. In many cases, this is fine. But if you try to issue a header later, it will give you an error about headers already being sent. This is because the first HTML (which could be blank space) that is sent implicitly triggers the sending of the headers. So a standard practice is to leave off the <code>?&gt;</code>, so no spaces (e.g. blank lines) can appear as if they were HTML in a file that is just doing PHP with no output. </p>\n\n<p>The headers already sent error can be annoying to debug, as it shows up at the place where you want the headers to be sent rather than the place where they actually were. </p>\n\n<h3>String delimiters</h3>\n\n<p>You are using double quotes to delimit your strings. This works. But there is an argument in favor of using single quotes. Single quotes do not do variable interpolation. So by using them, you implicitly let people know that your string is not using variable interpolation. </p>\n\n<p>None of your strings do variable interpolation, which is when you embed a variable in a string so that the string gets the contents of the variable. E.g. <code>\"Hello, $name\"</code> will contain \"Hello, Tobi Alfin\" if <code>$name = 'Tobi Alfin';</code>. </p>\n\n<p>There are <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">four types of PHP strings</a>: </p>\n\n<ul>\n<li>Single quoted: no variable interpolation.</li>\n<li>Double quoted: variable interpolation and escaped characters.</li>\n<li>Heredoc: multiple lines with variable interpolation and escaped characters.</li>\n<li>Nowdoc: multiple lines with no variable interpolation. </li>\n</ul>\n\n<p>Because your strings are all single line (some are single character) without variable interpolation, I would write them with single quotes. Not a big deal, but it makes it slightly more obvious which strings are doing variable interpolation. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T04:01:18.187", "Id": "407617", "Score": "0", "body": "I wasn't aware about leaving off the closing tags, so thanks for that. I was aware about the difference between different PHP strings, but didn't consider not using `\"\"` as I'm used to it. I think I'll try them out going forward." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T23:00:44.860", "Id": "210843", "ParentId": "210732", "Score": "1" } } ]
{ "AcceptedAnswerId": "210737", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T11:53:13.957", "Id": "210732", "Score": "1", "Tags": [ "beginner", "php" ], "Title": "Date Comparison Function for `usort()`" }
210732
<p>For a computation engineering model, I want to do a grid search for all feasible parameter combinations. Each parameter has a certain possibility range, e.g. (0 … 100) and the parameter combination must fulfil the condition <code>a+b+c=100</code>. An example: </p> <pre><code>ranges = { 'a': (95, 99), 'b': (1, 4), 'c': (1, 2)} increment = 1.0 target = 100.0 </code></pre> <p>So the combinations <em>that fulfil the condition</em> <code>a+b+c=100</code> are:</p> <pre><code>[(95, 4, 1), (95, 3, 2), (96, 2, 2), (96, 3, 1), (97, 1, 2), (97, 2, 1), (98, 1, 1)] </code></pre> <p>This algorithm should run with any number of parameters, range lengths, and increments. </p> <p>The solutions I have come up with is brute-forcing the problem. That means calculating <em>all</em> combinations and then discarding the ones that do not fulfil the given condition. I have to use <code>np.isclose()</code>, because when using floats, the rounding error in Python's will not lead to an exact sum.</p> <pre><code>def solution(ranges, increment, target): combinations = [] for parameter in ranges: combinations.append(list(np.arange(ranges[parameter][0], ranges[parameter][1], increment))) # np.arange() is exclusive of the upper bound, let's fix that if combinations[-1][-1] != ranges[parameter][1]: combinations[-1].append(ranges[parameter][1]) result = [] for combination in itertools.product(*combinations): # using np.isclose() so that the algorithm works for floats if np.isclose(sum(combination), target): result.append(combination) df = pd.DataFrame(result, columns=ranges.keys()) return df </code></pre> <p>However, this quickly takes a few days to compute. Hence, both solutions are not viable for large number of parameters and ranges. For instance, one set that I am trying to solve is (already unpacked <code>combinations</code> variable):</p> <pre><code>[[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0], [22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 66.0, 67.0, 68.0, 69.0, 70.0, 71.0, 72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 79.0, 80.0, 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], [0.0, 1.0, 2.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0], [0.0]] </code></pre> <p>This results in memory use of >40 GB and calculation time >400 hours. Do you see a solution that is either faster or more intelligent, i.e. not trying to brute-force the problem?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T12:14:41.887", "Id": "407370", "Score": "0", "body": "Maybe a bit trivial, but just found that doing a first check with `sum()` *before* doing the actual check with `np.isclose()` saves a lot of time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T12:21:23.097", "Id": "407371", "Score": "0", "body": "Welcome to CodeReview.StackExchange! Do you know what the condition is going to be like ? In your case, it seems to be linear constraint. Will it always be the case ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T12:23:15.180", "Id": "407372", "Score": "0", "body": "Sorry - not sure if I understand the question. The condition is that the sum of the combinations must equal the `target` variable, which is constant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T12:27:02.063", "Id": "407373", "Score": "0", "body": "Ha ok, fair enough, I didn't understand that the condition was always that the sum of the params should be equal to the target value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T12:41:25.960", "Id": "407374", "Score": "0", "body": "Also, are the values known to be all positive ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T12:42:46.337", "Id": "407376", "Score": "0", "body": "Yes. Zeros are allowed. Should work for floats though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T21:34:49.867", "Id": "407425", "Score": "1", "body": "Looks suspiciously similar to a [subset sum](https://en.wikipedia.org/wiki/Subset_sum_problem) problem. Don't hold your breath." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T00:29:42.100", "Id": "407452", "Score": "0", "body": "Since you've only implied this: are (a, b, c) required to be integers, or can they take floating-point values between whole numbers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T00:31:49.397", "Id": "407453", "Score": "0", "body": "If, within your generated valid combinations, some have more merit than others, this is an ideal problem for ILP. Is that the case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:50:14.583", "Id": "407676", "Score": "0", "body": "@Reinderien It should work with floats, yes. Not sure if I get the point about ILP. The numbers will be inputs to a non-linear model to find ideal parameter combinations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:12:03.060", "Id": "407729", "Score": "0", "body": "@n1000 Can you provide information on what the non-linear model is? It would be more efficient to combine that with the work of this current program." } ]
[ { "body": "<p>This is (nearly) the perfect application for <a href=\"https://en.wikipedia.org/wiki/Integer_programming\" rel=\"nofollow noreferrer\">ILP</a>, with a catch - whereas you want to enumerate <em>all</em> possible combinations, ILP is for convex optimization within certain constraints, has a cost metric, and only outputs <em>the best</em> possible combination (where you define best).</p>\n\n<p>You haven't given us a lot of detail on the \"computation engineering model\", but it's likely that not all of your output combinations are preferable, and there's some other selection process at work after your Python program has run. <em>If</em> you can capture this selection process as a linear cost metric, then ILP was made for your problem.</p>\n\n<p>If you're married to Python, then you can use Numpy and the <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html\" rel=\"nofollow noreferrer\"><code>scipy.optimize.linprog</code></a> package, but it has some shortcomings - prominently, that it doesn't support ILP, only LP (with floating-point values). If you aren't married to Python, then use something like <a href=\"https://www.gnu.org/software/glpk/\" rel=\"nofollow noreferrer\"><code>glpk</code></a> - either directly or through something like <a href=\"https://octave.org/doc/v4.0.0/Linear-Programming.html\" rel=\"nofollow noreferrer\">Octave's interface</a>.</p>\n\n<p>To illustrate, following along with Chapter 1.1 of the <a href=\"https://kam.mff.cuni.cz/~elias/glpk.pdf\" rel=\"nofollow noreferrer\">glpk documentation</a> and matching it to your example:</p>\n\n<ul>\n<li>Your a, b, and c would form a three-element vector <em>x</em> that glpk is responsible for determining</li>\n<li>You would have to create a matrix <em>c</em> to determine the cost (\"objective\") function against which glpk will optimize</li>\n<li>Your <code>ranges</code> would be converted into the vectors <em>l</em> and <em>u</em></li>\n<li>The constraint coefficient matrix <em>a</em> would be set to a vector of all 1s</li>\n<li>Your <code>target</code> would be converted into the \"constraint auxiliary variable\"</li>\n</ul>\n\n<p>If you actually need to constrain the output to whole numbers (i.e. your <code>increment</code> is 1), then use MIP (\"mixed integer linear programming\") mode directly.</p>\n\n<p>If <code>increment</code> is not 1 and you still need to constrain output to a linear space following those increments, you'll need a pre- and post-scaling operation so that you're still using MIP.</p>\n\n<p>If it actually doesn't matter that the numbers be constrained to increments at all, then just use LP mode.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T01:16:06.027", "Id": "210778", "ParentId": "210733", "Score": "1" } }, { "body": "<h1>split</h1>\n<p>The method does a few things at the same time.</p>\n<ul>\n<li>It expands the ranges</li>\n<li>generates the combinations</li>\n<li>takes the sums</li>\n<li>compares to the target</li>\n<li>assembles a DataFrame</li>\n</ul>\n<p>better would be to split it up in a few logical units. This will not only help freeing memory in-between steps, but also help with debugging the intermediate values</p>\n<h1>looping</h1>\n<p>Check the talk &quot;Looping like a pro&quot;</p>\n<p>You loop over the index, and end up with real long variables like <code>ranges[parameter][0]</code>. If you use tuple expansion, you can do this:</p>\n<pre><code>def expand(ranges, increment):\n for start, end in ranges.values():\n expansion= list(np.arange(start, end, increment))\n # np.arange() is exclusive of the upper bound, let's fix that\n if expansion[-1] != end:\n expansion.append(end)\n yield expansion\n</code></pre>\n<p>For me, this is a lot clearer. It also has the benefit of keeping the lines shorter.</p>\n<p>Since it are more the expansions of the ranges you create instead of the combinations, I renamed the method and variables.</p>\n<p>This also uses a generator instead of an intermediate list.</p>\n<p>This alternative might even simpler:</p>\n<pre><code>def expand(ranges, increment):\n for start, end in ranges.values():\n yield np.arange(start, end + increment/2, increment)\n</code></pre>\n<p>This can then be combined and summed like this:</p>\n<pre><code>def combine_naive(expansions, target):\n for combination in itertools.product(*expansions):\n # using np.isclose() so that the algorithm works for floats\n if np.isclose(sum(combination), target):\n yield combination\n</code></pre>\n<p>I like your comment there. It explains why you use <code>np.isclose</code> instead of <code>==</code></p>\n<h1>Alternative approaches</h1>\n<h2>numpy</h2>\n<p>instead of having <code>itertools.product</code> assemble the combinations, you could use <code>numpy.meshgrid</code></p>\n<pre><code>def combine_numpy(expansions, target):\n grid = np.meshgrid(*expansions)\n summary = np.array(grid).sum(axis=0)\n indices = np.where(np.isclose(summary, target))\n return (\n [row[i] for row, i in zip(expansions, idx)]\n for idx in zip(*indices)\n )\n</code></pre>\n<p>This is approximately the same, but staying in the <code>numpy</code> universe. You can reduce the memory footprint here with the correct choice of <code>dtype</code> and reducing the number of intermediary variables</p>\n<h1>sorted</h1>\n<p>or you could use the fact the expansions are sorted, and break when a sum is over the target. This uses recursion, tuple unpacking and the fact an empty sequence is <code>False</code>y.</p>\n<pre><code>def combine_sorted(expansions, target, previous=()):\n series, *rest = expansions\n\n sum_max = sum(item[-1] for item in rest)\n for item in series:\n current = previous + (item,)\n sum_current = sum(current)\n if rest:\n if sum_current + sum_max &lt; target and not np.isclose(\n sum_current + sum_max, target\n ):\n continue\n yield from combine_sorted(rest, target, previous=current)\n else:\n if np.isclose(sum_current, target):\n yield current\n elif sum_current &gt; target:\n return\n</code></pre>\n<p>The <code>sum_max</code> is to skip numbers where the total some will be less than <code>target</code> as soon as possible.</p>\n<p>testing and timing with real data will show which option is more memory and CPU intensive.</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n ranges = {&quot;a&quot;: (95, 99), &quot;b&quot;: (1, 4), &quot;c&quot;: (1, 2)}\n increment = 1.0\n target = 100.0\n df = solution(ranges, increment, target)\n\n expansions = list(expand(ranges, increment))\n results = list(combine_naive(expansions, target))\n df1 = pd.DataFrame(results, columns=ranges.keys())\n print(df1)\n\n results_sorted = list(combine_sorted(expansions, target))\n print(results_sorted)\n df_sorted = pd.DataFrame(results_sorted, columns=ranges.keys())\n print(df_sorted)\n\n results_numpy = list(combine_numpy(expansions, target))\n print(results_numpy)\n df_sorted = pd.DataFrame(results_numpy, columns=ranges.keys())\n print(df_sorted)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:24:18.717", "Id": "407689", "Score": "0", "body": "Actually my first try was to put all combinations into a dataframe and drop all that were not equal to the target. But I ran into memory issues. Your solutions and feedback are nice! Here are calculation time and max. memory usage for a relatively large example: `combine_naive()`: 32.3min, 60.3MB, `combine_sorted()`: 6.1min, 60.5MB, `combine_numpy()`: 0.4min, 6761MB. Seems like `combine_sorted()` may be a great compromise between speed and memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T08:38:12.760", "Id": "407928", "Score": "0", "body": "you can do both. Try the `combine_numpy` and catch the `MemoryError`. If it doesn't succeed, fall back to the `combine_sorted`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:19:32.810", "Id": "407982", "Score": "0", "body": "Hmm. Intereseting. I did not get a `MemoryError`, however. MacOS started swapping like crazy. I am not sure if it is easily possible to keep taps on the memory consumption of a script. @Maarten Fabré" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T17:00:32.157", "Id": "408002", "Score": "0", "body": "another possibility would be to calculate the number of combinations (product of the lengths of the ranges), and decide based on that" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T11:39:36.753", "Id": "210808", "ParentId": "210733", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T11:54:31.937", "Id": "210733", "Score": "3", "Tags": [ "python", "combinatorics" ], "Title": "Grid search parameter combinations in Python" }
210733
<p>I'm new to programming and in back-end. Right now I'm trying to learn flask, so I wrote a very simple website that currently encrypts and decrypts the message using RSA and DES. </p> <p>I feel like my app.py file is just bad and should do it much better. I mean, there're a lot of repeating code like this: </p> <pre><code>@app.route('/rsa_encrypt', methods=['GET', 'POST']) def RSA_enc(): global get_form if request.method == "GET": get_form = True return render_template('rsa_encrypt.html', gf=get_form) else: get_form = False rsa = RSA(request.form.get('pt'), p=request.form.get('p'), q=request.form.get('q'), e=request.form.get('e')) return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn) </code></pre> <p>I tried to write some decorators for those routes, but they didn't work well. </p> <p>Can you take a look and tell me what should I do better? It works but I think not as well as it should.</p> <p>app.py </p> <pre><code>from flask import Flask, render_template, request, url_for, jsonify from ciphers import RSA, DES from prime import generate_semiprime_number as gspn app = Flask(__name__) get_form = None @app.route('/') def index(): return render_template('index.html') @app.route('/rsa_encrypt', methods=['GET', 'POST']) def RSA_enc(): global get_form if request.method == "GET": get_form = True return render_template('rsa_encrypt.html', gf=get_form) else: get_form = False rsa = RSA(request.form.get('pt'), p=request.form.get('p'), q=request.form.get('q'), e=request.form.get('e')) return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn) @app.route('/rsa_decrypt', methods=['GET', 'POST']) def RSA_dec(): global get_form if request.method == "GET": get_form = True return render_template('rsa_decrypt.html', gf=get_form) else: get_form = False ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')] rsa = RSA(ciphertext=ct, p=request.form.get('p'), q=request.form.get('q'), e=request.form.get('e')) return render_template('rsa_decrypt.html', gf=get_form, rsa=rsa) @app.route('/des_encrypt', methods=['GET', 'POST']) def DES_enc(): global get_form if request.method == "GET": get_form = True return render_template('des_encrypt.html', gf=get_form) else: get_form = False des = DES(request.form.get('pt'), user_key=request.form.get('key')) return render_template('des_encrypt.html', gf=get_form, des=des) @app.route('/des_decrypt', methods=['GET', 'POST']) def DES_dec(): global get_form if request.method == "GET": get_form = True return render_template('des_decrypt.html', gf=get_form) else: get_form = False des = DES(ciphertext=request.form.get('ct'), user_key=request.form.get('key')) return render_template('des_decrypt.html', gf=get_form, des=des) @app.route('/gpsn', methods=['POST']) def _gpsn(): return jsonify({'result' : str(gspn(request.form['bits']))}) if __name__ == '__main__': app.run() </code></pre> <p>Other files <a href="https://github.com/6sixsix/pyCRYPT" rel="nofollow noreferrer">repository</a>. It's also hosted so you can quickly take a look.</p>
[]
[ { "body": "<p>Your main issue is (as you've already noticed) one of code repetition. Some simple helper methods here will do the trick; caveat - untested:</p>\n\n<pre><code>from flask import Flask, render_template, request, url_for, jsonify\nfrom ciphers import RSA, DES\nfrom prime import generate_semiprime_number as gspn\n\napp = Flask(__name__)\nget_form = None\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\ndef do_rsa(encrypting):\n global get_form\n\n direction = 'en' if encrypting else 'de'\n tmpl = f'rsa_{direction}crypt.html'\n\n if request.method == 'GET':\n return render_template(tmpl, gf=True)\n\n kwargs = {'p': request.form.get('p'),\n 'q': request.form.get('q'),\n 'e': request.form.get('e')}\n if encrypting:\n rsa = RSA(request.form.get('pt'), **kwargs)\n else:\n ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')]\n rsa = RSA(ciphertext=ct, **kwargs)\n\n kwargs = {}\n if encrypting:\n kwargs['gpsn'] = gpsn\n return render_template(tmpl, gf=False, rsa=rsa, **kwargs)\n\n@app.route('/rsa_encrypt', methods=('GET', 'POST'))\ndef RSA_enc():\n return do_rsa(True)\n\n@app.route('/rsa_decrypt', methods=('GET', 'POST'))\ndef RSA_dec():\n return do_rsa(False)\n\ndef do_des(encrypting):\n global get_form\n\n direction = 'en' if encrypting else 'de'\n tmpl = f'des_{direction}crypt.html'\n\n if request.method == 'GET':\n return render_template(tmpl, gf=True)\n\n kwargs = {'user_key': request.form.get('key')}\n if encrypting:\n des = DES(request.form.get('pt'), **kwargs)\n else:\n des = DES(ciphertext=request.form.get('ct'), **kwargs)\n\n return render_template(tmpl, gf=False, des=des)\n\n\n@app.route('/des_encrypt', methods=('GET', 'POST'))\ndef DES_enc():\n return do_des(True)\n\n@app.route('/des_decrypt', methods=('GET', 'POST'))\ndef DES_dec():\n return do_des(False)\n\n@app.route('/gpsn', methods=('POST',))\ndef _gpsn():\n return jsonify({'result' : str(gspn(request.form['bits']))})\n\n\nif __name__ == '__main__':\n app.run()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:14:06.413", "Id": "210747", "ParentId": "210736", "Score": "0" } } ]
{ "AcceptedAnswerId": "210747", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T13:00:36.517", "Id": "210736", "Score": "4", "Tags": [ "python", "beginner", "flask" ], "Title": "Python Flask website" }
210736
<p>I currently have an Android <code>Activity</code> that allows the users to select the <code>startDate</code>, <code>endDate</code>, <code>startTime</code> and <code>endTime</code>. Once they click the "submit" button, I will combine the <code>startDate</code> and <code>startTime</code> together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the <code>AlarmManager</code>. So far, I was able to convert the <code>startDate</code> and <code>startTime</code> to milliseconds. However, I feel that there are far better solutions out there, which I am not aware of.</p> <p>Here is the screenshot of my layout and my Java code:</p> <p><a href="https://i.stack.imgur.com/R7lXr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R7lXr.png" alt="enter image description here"></a></p> <p>MainActivity</p> <pre><code>public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener, View.OnClickListener { private TextView txtStartDate; private TextView txtEndDate; private TextView txtStartTime; private TextView txtEndTime; private Button btnSubmit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtStartDate = findViewById(R.id.txtStartDate); txtEndDate = findViewById(R.id.txtEndDate); txtStartTime = findViewById(R.id.txtStartTime); txtEndTime = findViewById(R.id.txtEndTime); btnSubmit = findViewById(R.id.btnSubmit); txtStartDate.setOnClickListener(this); txtEndDate.setOnClickListener(this); txtStartTime.setOnClickListener(this); txtEndTime.setOnClickListener(this); btnSubmit.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.txtStartDate: /* You need to define a unique tag name for each fragment */ createDialogFragment("StartDatePicker"); break; case R.id.txtEndDate: createDialogFragment("EndDatePicker"); break; case R.id.txtStartTime: createDialogFragment("StartTimePicker"); break; case R.id.txtEndTime: createDialogFragment("EndTimePicker"); break; case R.id.btnSubmit: retrieveInput(); } } private void createDialogFragment(String tag) { /* getSupportFragmentManager() will return a FragmentManager * that is used to manage the fragments */ if (tag.equals("StartDatePicker") || tag.equals("EndDatePicker")) { DialogFragment datePicker = new DatePickerFragment(); datePicker.show(getSupportFragmentManager(), tag); } else { DialogFragment timePicker = new TimePickerFragment(); timePicker.show(getSupportFragmentManager(), tag); } } @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, month); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime()); FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag("StartDatePicker") != null) { txtStartDate.setText(currentDateString); } else { txtEndDate.setText(currentDateString); } } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, hourOfDay); c.set(Calendar.MINUTE, minute); String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime()); FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag("StartTimePicker") != null) { txtStartTime.setText(currentTimeString); } else { txtEndTime.setText(currentTimeString); } } private void retrieveInput() { /* Get the startDate and startTime and covert it to milliseconds */ String date = txtStartDate.getText().toString(); String time = txtStartTime.getText().toString(); String datetime = date + " " + time; SimpleDateFormat df = new SimpleDateFormat("EEEE, MMMM d, yyyy hh:mm a"); Date date1 = null; long milli = 0; try { date1 = df.parse(datetime); milli = date1.getTime(); } catch (ParseException e) { e.printStackTrace(); } Toast.makeText(this, "" + milli, Toast.LENGTH_SHORT).show(); } } </code></pre> <p>activity_main.xml</p> <pre class="lang-xml prettyprint-override"><code>&lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:layout_editor_absoluteY="81dp"&gt; &lt;TextView android:id="@+id/txtStartDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="48dp" android:layout_marginLeft="48dp" android:layout_marginTop="136dp" android:text="Start Date" android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;TextView android:id="@+id/txtEndDate" android:layout_width="wrap_content" android:layout_height="27dp" android:layout_marginStart="48dp" android:layout_marginLeft="48dp" android:layout_marginTop="36dp" android:text="EndDate" android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtStartDate" /&gt; &lt;TextView android:id="@+id/txtStartTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="136dp" android:layout_marginEnd="56dp" android:layout_marginRight="56dp" android:text="Start Time" android:textSize="16sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;TextView android:id="@+id/txtEndTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginEnd="60dp" android:layout_marginRight="60dp" android:text="End Time" android:textSize="16sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtStartTime" /&gt; &lt;Button android:id="@+id/btnSubmit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginLeft="8dp" android:layout_marginEnd="8dp" android:layout_marginRight="8dp" android:layout_marginBottom="192dp" android:text="Submit" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>DatePickerFragment.java</p> <pre class="lang-java prettyprint-override"><code>public class DatePickerFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { // Get the current time and use it as the default values for the picker Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); // Create and return an instance of the DatePickerDialog return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day); </code></pre> <p>TimePickerFragment.java</p> <pre class="lang-java prettyprint-override"><code>public class TimePickerFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity())); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T02:58:31.303", "Id": "407456", "Score": "0", "body": "Have you considered merging your 2 dialogs into 1 [DateTimePickerdialog](https://www.journaldev.com/9976/android-date-time-picker-dialog)? Also you might want to take a look at the various classes and methods in the java.time api." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T14:18:53.383", "Id": "210739", "Score": "1", "Tags": [ "java", "datetime", "android" ], "Title": "Retrieving date and time from Datepicker and Timepicker and then converting it to milliseconds" }
210739
<p>I just created a simple game. Now I'm thinking what could be done better here. I want to get some tips how to make the code better/easier or what to add to it.</p> <p><strong>Code:</strong></p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Test extends JFrame implements ActionListener { private JButton[] button = new JButton[9]; private boolean changePlayer = true; private Test() { setTitle("Tic Tac Toe"); setSize(316, 339); setLocationRelativeTo(null); setLayout(null); setResizable(false); for (int i = 0; i &lt;= 8; i++) { button[i] = new JButton(String.valueOf(i)); button[i].setBackground(Color.WHITE); button[i].setFont(new Font("Arial", Font.BOLD, 0)); button[i].setFocusPainted(false); button[i].addActionListener(this); add(button[i]); } button[0].setBounds(0, 0, 100, 100); button[1].setBounds(100, 0, 100, 100); button[2].setBounds(200, 0, 100, 100); button[3].setBounds(0, 100, 100, 100); button[4].setBounds(100, 100, 100, 100); button[5].setBounds(200, 100, 100, 100); button[6].setBounds(0, 200, 100, 100); button[7].setBounds(100, 200, 100, 100); button[8].setBounds(200, 200, 100, 100); } private void restartGame() { int playAgain = JOptionPane.showConfirmDialog(null, "Wanna play again?", "You won!", JOptionPane.YES_NO_OPTION); if (playAgain == JOptionPane.NO_OPTION) { System.exit(0); } else { for (int i = 0; i &lt;= 8; i++) { button[i].setText(String.valueOf(i)); button[i].setFont(new Font("Arial", Font.BOLD, 0)); button[i].setForeground(Color.black); } } } private void restartGameNoWinner() { int playAgain = JOptionPane.showConfirmDialog(null, "Wanna play again?", "Draw!", JOptionPane.YES_NO_OPTION); if (playAgain == JOptionPane.NO_OPTION) { System.exit(0); } else { for (int i = 0; i &lt;= 8; i++) { button[i].setText(String.valueOf(i)); button[i].setFont(new Font("Arial", Font.BOLD, 0)); } } } @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i &lt;= 8; i++) { if (e.getSource() == button[i]) { if (changePlayer) { button[i].setText("X"); button[i].setFont(new Font("Arial", Font.BOLD, 70)); changePlayer = false; } else { button[i].setText("O"); button[i].setFont(new Font("Arial", Font.BOLD, 70)); changePlayer = true; } } } if (button[0].getText().equals(button[1].getText()) &amp;&amp; button[1].getText().equals(button[2].getText())) { button[0].setForeground(Color.RED); button[1].setForeground(Color.RED); button[2].setForeground(Color.RED); } else if (button[0].getText().equals(button[3].getText()) &amp;&amp; button[3].getText().equals(button[6].getText())) { button[0].setForeground(Color.RED); button[3].setForeground(Color.RED); button[6].setForeground(Color.RED); } else if (button[0].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[8].getText())) { button[0].setForeground(Color.RED); button[4].setForeground(Color.RED); button[8].setForeground(Color.RED); } else if (button[1].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[7].getText())) { button[1].setForeground(Color.RED); button[4].setForeground(Color.RED); button[7].setForeground(Color.RED); } else if (button[2].getText().equals(button[5].getText()) &amp;&amp; button[5].getText().equals(button[8].getText())) { button[2].setForeground(Color.RED); button[5].setForeground(Color.RED); button[8].setForeground(Color.RED); } else if (button[3].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[5].getText())) { button[3].setForeground(Color.RED); button[4].setForeground(Color.RED); button[5].setForeground(Color.RED); } else if (button[6].getText().equals(button[7].getText()) &amp;&amp; button[7].getText().equals(button[8].getText())) { button[6].setForeground(Color.RED); button[7].setForeground(Color.RED); button[8].setForeground(Color.RED); } if (button[6].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[2].getText())) { button[6].setForeground(Color.RED); button[4].setForeground(Color.RED); button[2].setForeground(Color.RED); } if ((button[0].getForeground() == Color.RED &amp;&amp; button[1].getForeground() == Color.RED &amp;&amp; button[2].getForeground() == Color.RED) || (button[0].getForeground() == Color.RED &amp;&amp; button[3].getForeground() == Color.RED &amp;&amp; button[6].getForeground() == Color.RED) || (button[0].getForeground() == Color.RED &amp;&amp; button[4].getForeground() == Color.RED &amp;&amp; button[8].getForeground() == Color.RED) || (button[1].getForeground() == Color.RED &amp;&amp; button[4].getForeground() == Color.RED &amp;&amp; button[7].getForeground() == Color.RED) || (button[2].getForeground() == Color.RED &amp;&amp; button[5].getForeground() == Color.RED &amp;&amp; button[8].getForeground() == Color.RED) || (button[3].getForeground() == Color.RED &amp;&amp; button[4].getForeground() == Color.RED &amp;&amp; button[5].getForeground() == Color.RED) || (button[6].getForeground() == Color.RED &amp;&amp; button[7].getForeground() == Color.RED &amp;&amp; button[8].getForeground() == Color.RED) || (button[2].getForeground() == Color.RED &amp;&amp; button[4].getForeground() == Color.RED &amp;&amp; button[6].getForeground() == Color.RED)) { restartGame(); } else if ((button[0].getText().equals("X") || button[0].getText().equals("O")) &amp;&amp; (button[1].getText().equals("X") || button[1].getText().equals("O")) &amp;&amp; (button[2].getText().equals("X") || button[2].getText().equals("O")) &amp;&amp; (button[3].getText().equals("X") || button[3].getText().equals("O")) &amp;&amp; (button[4].getText().equals("X") || button[4].getText().equals("O")) &amp;&amp; (button[5].getText().equals("X") || button[5].getText().equals("O")) &amp;&amp; (button[6].getText().equals("X") || button[6].getText().equals("O")) &amp;&amp; (button[7].getText().equals("X") || button[7].getText().equals("O")) &amp;&amp; (button[8].getText().equals("X") || button[8].getText().equals("O"))) { restartGameNoWinner(); } } public static void main(String[] args) { Test app = new Test(); app.setDefaultCloseOperation(EXIT_ON_CLOSE); app.setVisible(true); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:25:02.023", "Id": "407390", "Score": "2", "body": "See [MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T10:35:19.750", "Id": "407495", "Score": "0", "body": "While short, @Gnik's comment is, imho, the best answer to this question :)" } ]
[ { "body": "<p>You have a lot of code that do similar things for your 9 buttons. Maybe a custom Button class is a good idea. Also I would merge the two restartGame methods if I was you. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:00:56.917", "Id": "210743", "ParentId": "210741", "Score": "0" } }, { "body": "<pre><code> if (button[0].getText().equals(button[1].getText()) &amp;&amp; button[1].getText().equals(button[2].getText())) {\n button[0].setForeground(Color.RED);\n button[1].setForeground(Color.RED);\n button[2].setForeground(Color.RED);\n } else if (button[0].getText().equals(button[3].getText()) &amp;&amp; button[3].getText().equals(button[6].getText())) {\n button[0].setForeground(Color.RED);\n button[3].setForeground(Color.RED);\n button[6].setForeground(Color.RED);\n } else if (...\n</code></pre>\n\n<p>This part can be simplified to</p>\n\n<pre><code>// Winning Combinations\nBoolean[][] winCombs = {\n {0, 1, 2},\n {0, 3, 6},\n ...\n};\n\nfor (int i = 0; i &lt; winCombs.length; i++) {\n if (button[winCombs[i][0]].getText().equals(button[winCombs[i][1]].getText()) &amp;&amp;\n button[winCombs[i][1]].getText().equals(button[winCombs[i][2]].getText())) {\n for (int j = 0; j &lt; 3; j++)\n button[winCombs[i][j]].setForeground(Color.RED);\n }\n}\n</code></pre>\n\n<p>And the same for the next part. Any huge block of if conditions can always be simplified to an array and a loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:52:46.683", "Id": "210751", "ParentId": "210741", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T14:53:49.100", "Id": "210741", "Score": "1", "Tags": [ "java", "game", "tic-tac-toe", "swing" ], "Title": "Tic Tac Toe Java Swing game" }
210741
<p>I'm doing a lot of Python development lately for various (small-)data analysis pipelines at work. I've been wrestling with how to robustly and ~automatically version the code at a fine-grained level, so as to provide strong guarantees of reproducibility of a result generated from any particular version of the code, at any particular point in my development process.</p> <p>I've settled on a <a href="https://calver.org/" rel="nofollow noreferrer">CalVer</a> approach. Given that I often want to have multiple versions of the code tagged within a single day, I'm using a ~nonstandard <code>$TIMESTAMP</code> format of <code>YYYY.MM.DD.hhmm</code>. (<code>hhmmss</code> seemed like it would be overkill.)</p> <p>In any event, I want two things to happen every time I commit code to one of these data analysis repos:</p> <ol> <li>Wherever relevant in the package (usually just in the main <code>__init__.py</code>), <code>__version__</code> should be updated to <code>$TIMESTAMP</code>.</li> <li>Once the code is committed, a tag named <code>$TIMESTAMP</code> should be applied to the new commit</li> </ol> <p>Ancillary goals are the usual: easy to configure, minimal likelihood of breaking all the things, and minimal additional cleanup effort in common non-happy-path scenarios.</p> <p>The following is a bash script I've put together for the purpose:</p> <pre><code>#! /bin/bash export TIMESTAMP="$( date '+%Y.%m.%d.%H%M' )" export VERPATH='.verpath' if [ -z $VERPATH ] then # Complain and exit echo "ERROR: Path to files with versions to update must be provided in {repo root}/.verpath" echo " " exit 1 fi # $VERPATH must contain the paths to the files to be updated with # the timestamped version, one per line while read VERFILE do # Cosmetic echo "" if [ -e "$VERFILE" ] then # File to be updated with version exists; update and add to commit. # Tempfile with old file stored in case of commit cancellation. echo "Updating $VERFILE" cp "$VERFILE" "$VERFILE.tmp" sed -i "s/^__version__ = .*$/__version__ = '$TIMESTAMP'/" $VERFILE git add "$VERFILE" else echo "$VERFILE not found!" fi done &lt; $VERPATH # Cosmetic echo "" # So user can see what was updated sleep 2s # Actually do the commit, passing through any parameters git commit $@ # If the commit succeeded, tag HEAD with $TIMESTAMP and delete temp file(s). # If the commit failed, restore the prior state of the $VERFILEs. if [ "$?" -eq "0" ] then git tag -f "$TIMESTAMP" while read VERFILE do rm -f "$VERFILE.tmp" done &lt; $VERPATH else while read VERFILE do if [ -e "$VERFILE.tmp" ] then git reset HEAD "$VERFILE" &gt; /dev/null 2&gt;&amp;1 rm "$VERFILE" mv "$VERFILE.tmp" "$VERFILE" fi done &lt; $VERPATH fi </code></pre> <p>The contents of <code>.verpath</code> in my test repo are:</p> <pre><code>pkg/__init__.py pkg/__dupe__.py pkg/nofile.py </code></pre> <p>Both <code>pkg/__init__.py</code> and <code>pkg/__dupe__.py</code> exist; <code>pkg/nofile.py</code> does not.</p> <p>I have <code>*.tmp</code> in my <code>.gitignore</code> so that the <code>$VERFILE.tmp</code> don't show up as untracked files when drafting the commit message.</p> <hr> <p>It works like I want it to... the happy path works great, and it handles aborted commits and nonexistent <code>.verpath</code> files gracefully.</p> <p>I'm no bash expert, though, so I'm partly concerned about subtle misbehaviors I haven't thought of. Also, I'm not <em>super</em> thrilled about the use of in-folder temporary files, and per <a href="https://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable/10929511#10929511">here</a> and <a href="https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash?rq=1">here</a> the <code>while read VERFILE ... done &lt; $VERPATH</code> has the potential to be fragile if I don't set it up correctly.</p>
[]
[ { "body": "<p>It's good practice to preserve file permissions on copy, especially as your backup may replace the original. <code>cp -p</code> does so.</p>\n\n<p>Most file-handling commands can't handle filenames beginning with hyphen, unless you terminate the options with <code>--</code>, as in <code>mv -- $old $new</code>. It's prudent to include the terminator whenever you're sending user-supplied filenames to a command.</p>\n\n<p><code>while read .. do rm</code> gives me the willies. I'd instead keep track of .tmp files we've created, and remove those, as in:</p>\n\n<pre><code># array\ndeclare -a to_remove\n...\n# queue removal on successful copy else exit\ncp -p -- \"$VERFILE\" \"$VERFILE.tmp\" &amp;&amp; to_remove+=( \"$VERFILE.tmp\" ) || exit 1 \n...\nif git commit \"$@\"\nthen \n git tag -f \"$TIMESTAMP\"\n rm -f -- \"${to_remove[@]}\"\nelse\n for backup in \"${to_remove[@]}\"\n do\n original=\"${backup%.tmp}\"\n # no need to explicitly test existence: just attempt the mv + bail on failure\n mv -- \"$backup\" \"$original\" &amp;&amp; git reset HEAD \"$original\" &gt;&amp; /dev/null\n done\nfi\n</code></pre>\n\n<p><code>echo</code> and <code>echo \"\"</code> are equivalent.</p>\n\n<p><code>$@</code> should be double-quoted; this protects internal quotes. Unquoted <code>$*</code> is appropriate to use when you know quoting is unnecessary.</p>\n\n<p>You can use <code>[[ .. ]]</code> instead of <code>[ .. ]</code> to do tests. The former is a bash builtin and saves a fork.</p>\n\n<p>Your tests can use the more specific <code>-f</code> (is file or symlink to file) instead of <code>-e</code> (exists).</p>\n\n<p><code>&gt;&amp; /dev/null</code> is equivalent to <code>&gt;/dev/null 2&gt;&amp;1</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T05:09:40.850", "Id": "210854", "ParentId": "210745", "Score": "2" } }, { "body": "<p>First of all I'd like to recommend shellcheck (<a href=\"https://www.shellcheck.net/#\" rel=\"nofollow noreferrer\">online</a>, <a href=\"https://github.com/koalaman/shellcheck\" rel=\"nofollow noreferrer\">GitHub</a>) as a very useful tool to detect errors (even small misspellings of variables) and possible misbehaviours, etc.. With this you would have been warned about double-quoting your variables to prevent accidental splitting.</p>\n\n<pre><code>#! /bin/bash\n</code></pre>\n\n<p>There is no need to export these variables, since they won't be used after the termination of the script.<br>\nI'd personally stay clear from all caps variable names, if they are not environment variables. (By this convention, shellcheck will not complain for these variables if they are unset, as it assumes these to be provided by the shell.)<br>\nIn principle, there is no need to double-quote a subshell, but it does not hurt.</p>\n\n<pre><code>timestamp=\"$( date '+%Y.%m.%d.%H%M' )\"\nverpath='.verpath'\n</code></pre>\n\n<p>Since you have just set the variable, this if clause will never trigger, as it is never empty. You probably would like to check whether the file exists (and is readable). </p>\n\n<blockquote>\n<pre><code>if [ -z $VERPATH ]\nthen\n # Complain and exit\n echo \"ERROR: Path to files with versions to update must be provided in {repo root}/.verpath\"\n echo \" \"\n exit 1\nfi\n</code></pre>\n</blockquote>\n\n<p>I second switching to the bash built-in test <code>[[ expression ]]</code>.<br>\nFor debugging purposes I try to stick with positive evaluations, usually inserting a statement that it works as intended.<br>\nWhile in a simple script like this, echo is perfectly fine, I still recommend looking at <code>printf</code> for more complex things. I'd probably use something like the following:</p>\n\n<pre><code>if [[ -f \"$verpath\" &amp;&amp; -r \"$verpath\" ]] ; then\n : # do nothing (or give a debug statement)\nelse\n # complain and exit\n printf 'ERROR: Paths to files with versions to update should be provided in %s.\\n\\n' \"$verpath\"\n exit 1\nfi\n</code></pre>\n\n<p>Be aware that <code>read</code> without the option <code>-r</code> will mangle backslashes (see <a href=\"https://github.com/koalaman/shellcheck/wiki/SC2162\" rel=\"nofollow noreferrer\">SC2162</a>). If for whatever reason the carriage return is missing from the last line, it will be ignored, better use the following while loop, where <code>-n</code> tests for a non-zero length string:</p>\n\n<pre><code>while read -r verfile || [[ -n \"$verfile\" ]] ; do\n : # do something\ndone &lt; \"$verpath\"\n</code></pre>\n\n<p>Like in the other answer suggested, I also prefer to keep track of temporary files, instead of assuming they have been created as intended. This will also spare you of reading in the file again.<br>\nSince you are making backups, I would also switch to a different ending like <code>.bak</code>. Initialise the array first:</p>\n\n<pre><code>declare -a backups\n</code></pre>\n\n<p>I'd again check whether the file exists and is readable.<br>\nSince these are backups, I'd also use the <code>-a</code> option to <code>cp</code> to archive them. I'd advise on exiting if the command fails. You might also want to consider checking whether the target backup file does already exist and exit if it does.<br>\nThe inline substitution with <code>sed</code> might have a catch, if there are fewer of more spaces in the search pattern. I think you could be a bit more greedy.</p>\n\n<pre><code>if [[ -f \"$varfile\" &amp;&amp; -r \"$varfile\" ]] ; then \n printf 'INFO: Updating %s.\\n' \"$varfile\"\n # Add backup file to array\n backups+=( \"$varfile.bak\" )\n [[ -e \"${backups[-1]} ]] &amp;&amp; { printf 'WARNING: backup %s exists.\\n' \"${backups[-1]}\" ; exit 1 ; }\n cp -a -- \"$varfile\" \"${[backups[-1]}\" || { printf 'ERROR: backup of %s failed.\\n' \"$varfile\" ; exit 1 ; }\n sed -i \"s/^__version__.*$/__version__ = '$timestamp'/\" \"$verfile\"\n git add \"$verfile\" || { printf 'ERROR: adding %s to repository failed\\n' \"$verfile\" ; exit 1 ; }\n printf '\\n'\nelse\n printf 'INFO: file %s not found.\\n\\n' \"$verfile\"\nfi\n\n# So user can see what was updated\nsleep 2s\n</code></pre>\n\n<p>The bash built-in <code>$@</code> is an array, it needs to be double-quoted to prevent resplitting. On the other hand, <code>$*</code> is a string, i.e. it looses the elements of an array. Unquoted, it will also be resplit, which is hardly ever anything you would want.<br>\nAlways check the exit state of a command directly to prevent it being overwritten.</p>\n\n<pre><code># Actually do the commit, passing through any parameters\nif git commit \"$@\"\nthen\n# Commit succeeded: tag HEAD with $timestamp and delete backup file(s).\n git tag -f \"$TIMESTAMP\" || { printf 'WARNING: Adding tag failed.\\n' ; }\n rm -f -- \"${backups[@]}\"\nelse\n# Commit failed: restore the backups to its original location.\n for file in \"${backups[@]}\" ; do\n mv -- \"$file\" \"${file%.bak}\" &amp;&amp; git reset HEAD \"$file\" &amp;&gt; /dev/null \n done\nfi\n</code></pre>\n\n<hr>\n\n<p>Generally I do all file handlings much more verbose, wrapping everything into a function and switch off the output of that function as necessary, i.e.</p>\n\n<pre><code>#! /bin/bash\nmybackup ()\n{\n while [[ -n $1 ]] ; do\n : # Things to do\n source=\"$1\"\n shift\n target=\"$source.bak\"\n cp -vp \"$source\" \"$target\" &gt;&amp;3 2&gt;&amp;3\n done\n : # more things to do ...\n}\n\nif [[ \"$1\" == \"-s\" ]] ; then\n exec 3&gt; /dev/null\n shift\nelse\n exec 3&gt;&amp;1\nfi\n\nmybackup \"$@\"\n</code></pre>\n\n<p>This would also make things simpler if you were to create logfiles of your script, but that is beyond this review.</p>\n\n<p>Right now your versioning depends on an auxiliary file, that you probably create manually. I don't know how large your repositories are and how often you are using the versioning statements. It might be better to either check every file, or hardcode the ones that need to be checked into the script, instead of an external file. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:27:39.050", "Id": "210911", "ParentId": "210745", "Score": "3" } } ]
{ "AcceptedAnswerId": "210854", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T15:38:06.600", "Id": "210745", "Score": "3", "Tags": [ "bash", "shell", "git" ], "Title": "bash wrapper around 'git commit' to automatically bump (Python) package CalVer and create matching CalVer tag on new commit" }
210745
<p>When I show others how to use this module I have them make a <code>PROJECT</code> instance and then add other objects.</p> <pre><code>&gt;&gt;&gt; from Abstracted import PROJECT &gt;&gt;&gt; project = PROJECT('bob', Y_factor=2, use_MQTT=True) </code></pre> <pre class="lang-none prettyprint-override"><code>MQTT status: started Yay, your new Project named "bob" has been created </code></pre> <p>They may do this from a terminal which does not show the docstring balloons <a href="https://stackoverflow.com/q/53988820/3904031">the way IDLE and many other IDEs can</a>. So instead I've found a way so that when they type the instance, <strong>a few lines only</strong> of helpful text appears. This is in contrast to <a href="https://stackoverflow.com/q/53995957/3904031"><code>help()</code> which can generate dozens of lines</a> and scroll their previous work right up off the top of the screen.</p> <pre><code>&gt;&gt;&gt; project </code></pre> <pre class="lang-none prettyprint-override"><code>PROJECT("bob") intantiate with p = PROJECT(name, Y_factor=None, use_MQTT=False) later use start_MQTT(), stop_MQTT(), and add THINGs with p.new_CARROT(name) or p.new_ONION(name, n_rings=None) </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; carrot = project.new_CARROT('carrotte') </code></pre> <pre class="lang-none prettyprint-override"><code>a CARROT was added! </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; onion = project.new_ONION('onionne', n_rings=42) </code></pre> <pre class="lang-none prettyprint-override"><code>an ONION was added! </code></pre> <p>Type the object, and a few lines with a few "main methods" and helpful hints shows up. <em>This is the functionality that I am asking about</em>.</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; carrot </code></pre> <pre class="lang-py prettyprint-override"><code>CARROT("carrotte") instantiate with c = CARROT(project, name) change thread with c.change_thread_value(new_value) &gt;&gt;&gt; onion </code></pre> <pre class="lang-none prettyprint-override"><code>ONION("onionne"), n_rings=42 instantiate with o = ONION(project, name, n_rings=None) increase onionrings with o.multiply(factor) </code></pre> <p><strong>Question:</strong> Am I re-inventing the wheel? Is this recreating something that Python does naturally? I've only really learned about docstrings in the past 24 hours, so maybe there are better ways to do this?</p> <hr> <p>Here is <code>Abstracted.py</code>, an abstracted version of a large module. All of the functionality I'm asking about is contained here.</p> <pre class="lang-py prettyprint-override"><code>import time, datetime, logging, socket, Queue from threading import Thread, Lock, Event #import paho.mqtt.client as mqtt important_lock = Lock() # the rest of threading not shown class PROJECT(object): """ intantiate with p = PROJECT(name, Y_factor=None, use_MQTT=False) later use start_MQTT(), stop_MQTT(), and add THINGs with p.new_CARROT(name, X) or p.new_ONION(name)""" def __init__(self, name, Y_factor=None, use_MQTT=False): self.name = name self.use_MQTT = use_MQTT self.things = [] if Y_factor == None: Y_factor = -1 self.Y_factor = Y_factor if self.use_MQTT: status = self.start_MQTT() print "MQTT status: {}".format(status) self.info = ('{self.__class__.__name__}("{self.name}")' .format(self=self)) print 'Yay, your new Project named "{}" has been created'.format(self.name) def __repr__(self): return (self.info + '\n' + self.__doc__) def doc(self): print self.__doc__ def start_MQTT(self, start_looping=False): """(start_looping=False) creates an MQTT client attribute and connects it""" # do stuff status = 'started' self.client = 'client instance' return status def stop_MQTT(self): """disconnects from MQTT""" # do stuff status = 'stopped' return status def new_ONION(self, name, n_rings=None): """def new_ONION""" onion = ONION(project=self, name=name, n_rings=n_rings) self.things.append(onion) print "an ONION was added!" return onion def new_CARROT(self, name): """def new_CARROT""" carrot = CARROT(project=self, name=name) self.things.append(carrot) print "a CARROT was added!" return carrot class THING(object): """THING!""" def __init__(self, project, name): """THING.__init__!""" self.project = project self.name = name self.Y_factor = self.project.Y_factor def __repr__(self): return (self.info + '\n' + self.__doc__) class ONION(THING): """ instantiate with o = ONION(project, name, n_rings=None) increase onionrings with o.multiply(factor)""" def __init__(self, project, name, n_rings=None): """ONION.__init__!""" if n_rings==None: n_rings = 7 self.n_rings = n_rings THING.__init__(self, project, name) self.info = ('{self.__class__.__name__}("{self.name}"), n_rings={self.n_rings}' .format(self=self)) def multiply(self, factor): if type(factor) in (int, float): self.n_rings *= factor class CARROT(THING): """ instantiate with c = CARROT(project, name) change thread with c.change_thread_value(new_value)""" def __init__(self, project, name): """CARROT.__init__!""" self.thread_value = 1 THING.__init__(self, project, name) self.info = ('{self.__class__.__name__}("{self.name}")' .format(self=self)) def change_thread_value(self, new_value): with important_lock: self.thread_value = new_value </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:41:29.907", "Id": "407398", "Score": "0", "body": "Good question! Would `print(onion.__doc__)` provide the desired behavior? What about [`inspect.getdoc()`](https://docs.python.org/3/library/inspect.html#inspect.getdoc)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:08:51.190", "Id": "407438", "Score": "0", "body": "@alecxe my power went off right after I posted, just got back on line... Those are particularly wordy for two-finger typers, and remembering that is a bit hard for python noobs, and by the time they finish typing it they may forget what it was they were hoping to do. I'm looking for a quick way, as easy as remembering help() but not actually help(). Thanks!" } ]
[ { "body": "<h2>Disclaimer</h2>\n\n<p>Now that the OP has clarified that they intend to use this as a teaching tool, my answer has lost relevance for their use-case. It can still be taken as general advice for most Python modules.</p>\n\n<p>I do agree with @jpmc26 to a certain extent, specifically that this code itself as currently written should not be used as an example for new learners of Python. I am certainly not advocating teaching students bad Python style. But I think that this could be a useful learning aid within the context the OP provides.</p>\n\n<h2>Original answer</h2>\n\n<p>I realize this is one of the central premises of your program, but printing help docstrings during normal use of the program is highly unusual behavior and likely to be annoying to users of your program. For example, a user might already know how to use your API, and doesn't need to be told how every time they invoke it; it would just clutter up the command line. Besides, you're solving a problem that doesn't really need to be solved: a class docstring may scroll the screen as described, but function and method docstrings do not, and the Python REPL interpreter already allows you to short circuit the scrolling.</p>\n\n<p>Instead, I would recommend using more descriptive and helpful docstrings. For example, informing the user of the class calling conventions in isolation is not useful; explaining what the class's intended use is, and what the various parameters mean would be more useful. <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a> provides guidance on how to write good docstrings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:15:24.410", "Id": "407440", "Score": "0", "body": "*The first sentence* of my question makes it clear that this is an exercise that I am leading them through, rather than a module for general release. In this case Python is a tool, but not the topic. Getting short, helpful docstrings will not be annoying to them, but instead helpful. I would have mentioned this right away, but my power went out right after posting (I usually babysit my questions). In any event, I'll take your answer to be that you don't feel there is a better way to do this (type an object and receive hints how to use it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:35:56.617", "Id": "407442", "Score": "0", "body": "@uhoh My answer was premised on the assumption that this was code intended to be a general Python module for distribution, not a teaching tool. I read the first sentence, but I was genuinely confused as to who the intended audience was. Perhaps adding a sentence or two that provides the additional context, and editing your question title would help you receive answers that are closer to what you're looking for; my answer is by no means a comprehensive analysis of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:41:00.660", "Id": "407443", "Score": "0", "body": "It's unfortunate the power went out and I couldn't stay with my post. I've just gotten home now after spending the night in a McDonalds writing with a pen in a notebook (it's been a while, surprised I remembered how!). I'll update the question in a few hours. Until then let's assume that the behavior indicated really is the behavior needed, and I'm checking if there is a simpler way to do this, rather than asking \"is this a good idea\". Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:46:41.623", "Id": "407445", "Score": "0", "body": "\"Now that the OP has clarified that they intend to use this as a teaching tool\" **NO!** It is *vital* that education conforms to the norms of the language and teaches students to adhere to them. The students will be far better served by the teacher *using the correct, existing technology for the task they are trying to perform*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:53:05.180", "Id": "407447", "Score": "0", "body": "@jpmc26 I think it depends on what level of education the students are at, and the general context. If the OP wants to show their students how to instantiate objects and how objects work in Python, then this might be a useful tool. But, there are probably better tools. And I do agree that if this code is used, the underlying code should not be shown to students as an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:53:41.037", "Id": "407448", "Score": "0", "body": "@Graham [In this case Python is a tool, but not the topic](https://codereview.stackexchange.com/questions/210746/implementing-a-customized-helpful-hints-function-which-includes-docstring-but-mu#comment407440_210753)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:55:18.500", "Id": "407449", "Score": "0", "body": "@uhoh What *is* the topic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T00:01:23.793", "Id": "407451", "Score": "0", "body": "@Graham bunch of science gizmos connected to a Raspberry Pi. Focus is primarily on the data that's generated. Plots pop up, etc. The module will let them connect several different things and start using them without having to understand the python at first. There will be a more PEPy and pythonic version for those who want it as well, but I'm trying to make this version as friendly as possible. So the idea here is that you type an object, and it make suggestions how it can be used. But it needs to be close to the standard version, I'm not looking for a whole new framework." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:08:31.937", "Id": "210753", "ParentId": "210746", "Score": "8" } }, { "body": "<p>I'm not sure whether you're reinventing the wheel, but you are using the wrong tools for the job.</p>\n\n<p>I've been through the phase where I think I'm doing something unique enough that I need to do something nonstandard. Every time I've done it, I inevitably regret it. Don't do it. It's not a good idea. Use tools very closely to the way they were intended to be used.</p>\n\n<p>You seem to be trying to do basically two things.</p>\n\n<h1>A guidance system to aid developers</h1>\n\n<p>The first is a sort of \"brief help\" that prompts the users with details about the API.</p>\n\n<p>You implement this with <code>repr</code>, but <code>repr</code> is absolutely the wrong tool for this job. \n<code>repr</code> is <em>not</em> intended to return help messages. <code>repr</code> is intended to be a quick and dirty introspection tool, showing just enough information for the programmer to identify the object they're looking at. You're reducing their ability to do so by misusing it, which is far and away something I would not advise for beginners.</p>\n\n<p>To be honest, I wouldn't recommend building this into Python itself at all. Doing so is very nonstandard. Instead, I'd be more inclined to generate a set of HTML docs for them to use. <a href=\"https://docs.python.org/2.7/library/pydoc.html\" rel=\"nofollow noreferrer\">pydoc</a> is built in and is probably a good starting point. <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">Sphinx</a> is also well known and used. <a href=\"https://wiki.python.org/moin/DocumentationTools\" rel=\"nofollow noreferrer\">Python's wiki</a> lists others to consider as well. Some of these will allow you to include documentation not just of the API, but also custom pages including examples and what have you. A set of HTML docs is likely to be infinitely more usable to your users since it doesn't require backspacing the command they're in the middle of typing.</p>\n\n<p>Bottom line: I'd use the existing standard tools to provide your users with this kind of guidance, and the standard is to make it external to the code itself.</p>\n\n<p>You might also want to take note of the <a href=\"https://docs.python.org/2/library/functions.html#dir\" rel=\"nofollow noreferrer\"><code>dir</code> command</a>. <code>dir(o)</code> lists the names bound to <code>o</code>, which includes attributes, descriptors (similar to \"properties\" in other languages), and methods. This can be combined with <code>pprint</code> or <code>pformat</code> for easier to read output, and the <code>if</code> clause of list comprehensions can be used to filter out private names (i.e., <code>[a for a in dir(o) if not a.startswith('_')]</code>) or based on other conditions. I use this myself to explore an API when the documentation is poor. <a href=\"https://docs.python.org/2/library/functions.html#vars\" rel=\"nofollow noreferrer\"><code>vars(o)</code></a> may also be useful for viewing attributes.</p>\n\n<p>If it absolutely <em>must</em> be accessible by code, I think I'd probably implement it as a new \"protocol\". Something like this:</p>\n\n<pre><code>class PROJECT(object):\n # Your other code\n @staticmethod\n def _mytips():\n return \"\"\"\n PROJECT(\"bob\")\n intantiate with p = PROJECT(name, Y_factor=None, use_MQTT=False)\n later use start_MQTT(), stop_MQTT(), and\n add THINGs with p.new_CARROT(name) or p.new_ONION(name, n_rings=None)\n \"\"\"\n</code></pre>\n\n<p>Then in another module, you can leverage this <code>_mytips()</code> method:</p>\n\n<pre><code>import os\n\ndef tips(o):\n try:\n raw_tips = o._mytips()\n # Use standardized indentation\n return (os.linesep + ' ').join([l.strip() for l in raw_tips.strip().splitlines()])\n except AttributeError:\n raise ValueError('object does not support tips')\n</code></pre>\n\n<p>Then it can be used like this:</p>\n\n<pre><code>&gt;&gt;&gt; tips(PROJECT)\nPROJECT(\"bob\")\n intantiate with p = PROJECT(name, Y_factor=None, use_MQTT=False)\n later use start_MQTT(), stop_MQTT(), and\n add THINGs with p.new_CARROT(name) or p.new_ONION(name, n_rings=None)\n&gt;&gt;&gt; p = PROJECT()\n&gt;&gt;&gt; tips(p)\nPROJECT(\"bob\")\n intantiate with p = PROJECT(name, Y_factor=None, use_MQTT=False)\n later use start_MQTT(), stop_MQTT(), and\n add THINGs with p.new_CARROT(name) or p.new_ONION(name, n_rings=None)\n</code></pre>\n\n<p>Calling the method <code>_mytips</code> gives the <code>tips</code> call a standard method to look for, and prefixing it with an underscore indicates it's not intended to be called directly. Note that you should <em>not</em> use something like <code>__mytips__</code>, as the magic method syntax is reserved for the language or the standard library. Making it static means you can use it on other the class directly or an instance. You still have to write the documentation yourself or generate it somehow. This is not particularly common, but at least this is in line with the standard \"protocol pattern\" Python uses for things that need to be implemented by lots of different classes/objects. Other devs will recognize what you're doing when they look at the <code>tips</code> code.</p>\n\n<p>I'd still prefer an actual help page open in the browser, though, and don't really recommend it. You might consider loading the tips from an actual external document, giving you both with the same content.</p>\n\n<h1>Informational messages</h1>\n\n<p>The other thing you seem to want to implement is informational messages. The standard solution for this is <em>logging</em>. That is definitely what you're doing when you print the \"added\" messages. Using the logging module in those cases would look like this:</p>\n\n<pre><code>def new_carrot(self, name):\n \"\"\"def new_carrot\"\"\"\n\n carrot = Carrot(project=self, name=name)\n\n self.things.append(carrot)\n logging.debug(\"a Carrot was added!\")\n return carrot\n</code></pre>\n\n<p>But requires a tiny bit of set up:</p>\n\n<pre><code>import logging\n\nlogging.basicConfig(level=logging.DEBUG)\n</code></pre>\n\n<p>You can get fancier if you want more control over the format, but I'm not going to get into all those details here.</p>\n\n<p>This also gives your users the option of disabling these messages by cranking up the message level:</p>\n\n<pre><code>logging.getLogger().setLevel(logging.INFO)\n</code></pre>\n\n<h1>Other concerns</h1>\n\n<h3>Resource management</h3>\n\n<p>I notice your <code>PROJECT</code> class starts up something in its initializer:</p>\n\n<pre><code>status = self.start_MQTT()\n</code></pre>\n\n<p>and then has a stop method as well.</p>\n\n<p>The Python standard for managing resources is <a href=\"http://book.pythontips.com/en/latest/context_managers.html\" rel=\"nofollow noreferrer\"><strong>context managers</strong></a>. Context managers are a fantastic little tool that will make your code much simpler. If you convert <code>PROJECT</code> to one, then callers will have much less boilerplate managing it:</p>\n\n<pre><code>with PROJECT(\"myproj\", use_MQTT=True) as p:\n p.new_CARROT(\"carrot 1\")\n</code></pre>\n\n<p>Yes, that block of code is correct. There is no need to call <code>stop_MQTT</code>, and that's because the <code>with</code> block invokes the method to release it automatically:</p>\n\n<pre><code>class PROJECT(object):\n def __init__(self, name, Y_factor=None, use_MQTT=False):\n # Everything EXCEPT starting the server\n\n def __enter__(self):\n if self.use_MQTT:\n # do stuff\n status = 'started'\n self.client = 'client instance'\n logging.debug(\"MQTT status: {}\".format(status))\n\n def __exit__(self, type, value, traceback):\n if self.status == 'started':\n # do stuff to stop server\n status = 'stopped'\n return status\n\n # Other methods\n</code></pre>\n\n<p>Some details may not exactly line up with what you need to do, but you have pseudocode here anyway. <em>Much</em> simpler for your callers.</p>\n\n<h3>Use <code>super</code></h3>\n\n<p>You have this call:</p>\n\n<pre><code>THING.__init__(self, project, name)\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/27134600/1394393\">Don't do that</a>. Use <code>super</code>:</p>\n\n<pre><code>super(ONION, self).__init__(project, name)\n</code></pre>\n\n<h3>Naming and formatting standards</h3>\n\n<p>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> for naming conventions. Right off the bat, I notice that <code>PROJECT</code> would be <code>Project</code> and <code>Y_factor</code> should be <code>yfactor</code>. (One might argue that <code>y_factor</code> is also acceptable, but PEP8 notes that underscores should be used \"to improve readability\". Putting it after just a <code>y</code> doesn't really add any readability.)</p>\n\n<h1>Conclusion</h1>\n\n<p>The bottom line here is that Python has a lot of norms and standards, and your code doesn't conform to them. This isn't just a matter of being pedantic. Python's norms are built around <em>practical</em> concerns and avoiding <em>real world problems</em>. When you use Python the way it was intended to be used, it will make solving your problems easier.</p>\n\n<p>If you want a sort of intro to the idea of writing \"Pythonic\" code and why it's important and a practical example, check out Raymond Hettinger's <a href=\"https://youtu.be/wf-BqAjZb8M\" rel=\"nofollow noreferrer\">Beyond PEP8</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:09:47.053", "Id": "407457", "Score": "1", "body": "`+n!` This is an excellent answer and what I needed, thank you! You are right about logger, elsewhere I've echoed the logged events to the screen with a second handler using `logging.getLogger('').addHandler(console)` and that may be what I need here. I've used context manager for the threading lock (and files) but never realized it could be used this way, nice! I have the manual stop method for other reasons (example: if you turn off WiFi to save batteries, then MQTT's looping/pinging starts complaining) but for final shut down, what you've shown is great." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:11:55.960", "Id": "407458", "Score": "0", "body": "`Super` looks super, I will dig in and read about that now. Again, thank you for taking the time for a thorough review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T23:40:54.047", "Id": "407607", "Score": "1", "body": "@uhoh I added some notes about `dir` and `vars` you may find useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T03:03:43.523", "Id": "407616", "Score": "0", "body": "yep, thanks. Maybe what I'm really looking for is something that could *look like* and work like a Built-in function, and be called `pretty_help(class)`, `concise_help(class)` or even `local_hints(class)`. Something that returns a few concise lines of main methods, hints, or other things that are what users are most likely to need, and because of compactness still leave your current train of thought on the screen, even if the screen is small. I'm a heavy python *user* but will never be, or think like you steel-trap-minded developers, and there are a lot of us who could use some simple hints." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T04:25:14.040", "Id": "407618", "Score": "1", "body": "@uhoh I'm not really opposed to the idea; I can see the usefulness.Jupyter/IPython do something similar, after all. It's just that such a thing does not exist out of the box, and hijacking functionality that's supposed to do something else will hurt you more that it will help in the long run. I read documentation all day long, and I find myself using help pages *way* more than any kind of command line help. That said, I've made one more addition: designing your own protocol method. It's not my preference and I don't really encourage it, but at least it doesn't conflict with existing things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T04:48:56.297", "Id": "407912", "Score": "0", "body": "any thoughts? [Instance should execute final instructions when exiting python or closing terminal, these don't work.](https://stackoverflow.com/q/54068650/3904031)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T01:36:22.267", "Id": "210779", "ParentId": "210746", "Score": "7" } }, { "body": "<p>It is difficult to add anything to the existing great and detailed answers, but, to follow up your comment that <code>.__doc__</code> might be to difficult to remember for newcomers, you could then <em>wrap it around your custom function</em>:</p>\n<pre><code>def doc(obj):\n &quot;&quot;&quot;Prints a docstring of a given object.&quot;&quot;&quot;\n print(obj.__doc__)\n</code></pre>\n<p>Usage:</p>\n<pre><code>In [2]: class CARROT:\n ...: &quot;&quot;&quot; instantiate with c = CARROT(project, name)\n ...: change thread with c.change_thread_value(new_value)&quot;&quot;&quot;\n ...: \n\nIn [3]: carrot = CARROT()\n\nIn [4]: doc(carrot)\n instantiate with c = CARROT(project, name)\n change thread with c.change_thread_value(new_value)\n</code></pre>\n<hr />\n<h3>Jupyter Notebooks?</h3>\n<p>As a side note, you may switch to using <a href=\"https://jupyter.org/\" rel=\"nofollow noreferrer\">Jupyter notebooks</a> that may actually be a good learning environment for newcomers and would let them use the standard built-in <code>help()</code> in the Jupyter cells.</p>\n<p>There are also built-in shortcuts, like <code>shift+TAB</code> to access a help popup:</p>\n<p><a href=\"https://i.stack.imgur.com/he27X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/he27X.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:16:25.580", "Id": "407459", "Score": "1", "body": "I'd forgotten about Jupyter, thanks! You might want to add a \"me too\" answer [there](https://stackoverflow.com/q/53988820/3904031) (or not). I won't have control over what people use, and this question is for those who live 100% inside a terminal. \"They may do this from a terminal which does not show the docstring balloons the way IDLE and many other IDEs can. So instead I've found a way...\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T02:51:47.457", "Id": "210783", "ParentId": "210746", "Score": "3" } } ]
{ "AcceptedAnswerId": "210779", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:02:27.257", "Id": "210746", "Score": "6", "Tags": [ "python", "python-2.x", "user-interface" ], "Title": "Implementing a customized helpful hints function which includes docstring but much shorter than Python help()" }
210746
<p>I've created an RPN evaluator in Haskell, as an exercise because I'm new to this language.</p> <p>It runs well:</p> <pre><code>$ ./rpn 2 3 4 5 + - + -4 </code></pre> <p>And the source code:</p> <pre><code>{-# LANGUAGE BangPatterns #-} import Data.String import System.IO data Token = TNum Int | TOp Operator data Operator = Add | Sub | Mul | Div main :: IO () main = do line &lt;- getLine let tokens = tokenise line (numc, opc) = countTok tokens !junk = if numc == opc + 1 then () else error "Not a correct expression." print $ eval [] tokens tokenise :: String -&gt; [Token] tokenise = map str2tok . words eval :: [Int] -&gt; [Token] -&gt; Int eval (s:_) [] = s eval stack (TNum t:ts) = eval (t : stack) ts eval (x:y:stacknoxy) (TOp t:ts) = eval (applyOp t y x : stacknoxy) ts str2tok :: String -&gt; Token str2tok tkn@(c:_) | c `elem` ['0'..'9'] = TNum (read tkn :: Int) | otherwise = TOp $ case tkn of "+" -&gt; Add "-" -&gt; Sub "*" -&gt; Mul "/" -&gt; Div _ -&gt; error $ "No such operator " ++ tkn applyOp :: Operator -&gt; Int -&gt; Int -&gt; Int applyOp Add a b = a + b applyOp Sub a b = a - b applyOp Mul a b = a * b applyOp Div a b = a `div` b countTok :: [Token] -&gt; (Int, Int) countTok [] = (0, 0) countTok (t:ts) = let (x, y) = case t of TNum _ -&gt; (1, 0) _ -&gt; (0, 1) in (x, y) `addPair` countTok ts addPair :: (Num a, Num b) =&gt; (a, b) -&gt; (a, b) -&gt; (a, b) addPair (x, y) (z, w) = (x + z, y + w) </code></pre> <p>How can this code be improved? I hope my implementation is elegant, and if it isn't - what are the ways to clean it up? In particular, I really don't like the <code>error</code>s because they're just ugly:</p> <pre><code>./rpn 5 6 + + rpn: Not a correct expression. CallStack (from HasCallStack): error, called at rpn.hs:16:22 in main:Main </code></pre> <p>I know they can be replaced with <code>fail</code>, which has a much nicer output, but from what I've read it can only be done inside a function that returns <code>IO ()</code>.</p>
[]
[ { "body": "<p>First, I would convert all of the functions which might throw an error to return some kind of failable type, like <code>Maybe Int</code> or <code>Either String Token</code>. This includes <code>str2tok</code>, <code>tokenize</code>, and <code>eval</code>. This would also remove the need for the <code>countTok</code> function, since the program can just return an error value from <code>eval</code> instead. With the help of the <code>Monad</code> instances for these error types, this is a relatively simple change.</p>\n\n<p>Next, I would use <a href=\"http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Char.html#v:isDigit\" rel=\"nofollow noreferrer\"><code>isDigit</code></a> from <code>Data.Char</code> instead of <code>c `elem` ['0'..'9']</code> because <code>isDigit</code> makes less comparisons in order to determine if it's a digit.</p>\n\n<p>Lastly, I would change the <code>Operator</code> type to the function type <code>Int -&gt; Int -&gt; Int</code>. This will remove the need for <code>applyOp</code> and will consolidate all the places that would be necessary to change if you wanted to extend the program to accept more operators.</p>\n\n<pre><code>import Data.Char (isDigit)\n\ndata Token = TNum Int | TOp (Int -&gt; Int -&gt; Int)\n\nmain :: IO ()\nmain = do\n line &lt;- getLine\n either putStrLn print $ do\n tokens &lt;- tokenize line\n eval [] tokens\n\ntokenize :: String -&gt; Either String [Token]\ntokenize = mapM str2tok . words\n\nstr2tok :: String -&gt; Either String Token\nstr2tok tkn\n | (c:_) &lt;- tkn, isDigit c = Right $ TNum (read tkn)\n | otherwise = TOp &lt;$&gt; case tkn of\n \"+\" -&gt; Right (+)\n \"-\" -&gt; Right (-)\n \"*\" -&gt; Right (*)\n \"/\" -&gt; Right div\n _ -&gt; Left $ \"No such operator \" ++ tkn\n\neval :: [Int] -&gt; [Token] -&gt; Either String Int\neval (s:_) [] = Right s\neval stack (TNum t:ts) = eval (t : stack) ts\neval (x:y:stacknoxy) (TOp t:ts) = eval (t y x : stacknoxy) ts\neval _ _ = Left \"Not a correct expression.\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:13:33.313", "Id": "407516", "Score": "0", "body": "Brilliant! But I have one more question, what does the `<$>` do? I suspect it has to do something to do with Monads, which I don't grasp, unfortunately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:16:33.333", "Id": "407517", "Score": "1", "body": "`<$>` is the infix operator alias for `fmap`. If it's easier for you to read, you could use `fmap TOp $` instead of `TOp <$>`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T02:18:03.620", "Id": "210781", "ParentId": "210749", "Score": "2" } } ]
{ "AcceptedAnswerId": "210781", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:32:03.807", "Id": "210749", "Score": "1", "Tags": [ "beginner", "haskell", "math-expression-eval" ], "Title": "Reverse Polish Notation evaluator in Haskell" }
210749
<p>I wrote a MergeSort implementation of doubly linked list, based on the MergeSort implementation of array on the textbook <em>Algorithms 4th</em>, which is definitely <span class="math-container">\$O(n \log n)\$</span>.</p> <p>I think my linked list implementation is <span class="math-container">\$O(n \log n)\$</span>, but it runs so much slower than the array version so I am getting very confused and doubting!</p> <p><strong>Is my linked list implementation <span class="math-container">\$O(n \log n)\$</span> time complexity?</strong> If it is, then is it normal that it's so much slower than the array version? If it's not, where did I make mistakes?</p> <p>Besides, anything that natively, hugely improve the linked list version's performance is appreciated. (For simplicity, I do not use <code>template</code> every where, this can be put aside first.)</p> <h2>Linked list version:</h2> <p><strong>doublelinkedlist.h</strong></p> <pre><code>#pragma once #include &lt;stdexcept&gt; #include &lt;iostream&gt; #include &lt;initializer_list&gt; namespace ythlearn{ template&lt;typename T&gt; class DLinkList{ public: class Node{ public: Node* next; Node* prev; T elem; }; Node head; Node tail; int _size; bool linked; public: DLinkList(){ head.next = head.prev = tail.next = tail.prev = nullptr; _size = 0; linked = false; } DLinkList(std::initializer_list&lt;T&gt; init_list){ head.next = head.prev = tail.next = tail.prev = nullptr; _size = 0; linked = false; for(auto s = init_list.begin(); s!=init_list.end(); s++){ push_right(*s); } } int size(){ return _size; } bool isEmpty(){ return size() == 0; } Node* getIndexPointer(int index){ if(index &gt;= size()){ throw std::runtime_error("getIndexPointer index overflow"); }else{ int i = 0; Node* n_ptr = head.next; while(i != index){ n_ptr = n_ptr-&gt;next; i++; } return n_ptr; } } Node* getIndexPointer(Node* start_position_ptr, int distance){ if(distance &gt;= size()){ throw std::runtime_error("getIndexPointer(with start_position) index overflow"); }else{ int i = 0; Node* n_ptr = start_position_ptr; while(i != distance){ n_ptr = n_ptr-&gt;next; i++; } return n_ptr; } } bool isSorted(){ Node* n_ptr = head.next; while(n_ptr != tail.next-&gt;prev){ if(n_ptr-&gt;elem &gt; n_ptr-&gt;next-&gt;elem) return false; n_ptr = n_ptr-&gt;next; } return true; } DLinkList&amp; push_right(T elem){ Node* n = new Node; n-&gt;elem = elem; if(isEmpty()){ head.next = tail.next = n; n-&gt;next = n-&gt;prev = n; }else{ n-&gt;next = head.next; n-&gt;prev = tail.next; tail.next-&gt;next = n; tail.next = n; head.next-&gt;prev = tail.next; } ++_size; return *this; } DLinkList&amp; push_left(T elem){ //deleted for simplicity } T pop_left(){ //deleted for simplicity } T pop_right(){ //deleted for simplicity } void print(){ //deleted for simplicity } DLinkList(const DLinkList&amp;) = delete; DLinkList&amp; operator=(const DLinkList&amp;) const = delete; ~DLinkList(){ if(!linked){ Node* node_to_delete; while(head.next != tail.next){ node_to_delete = head.next; head.next = head.next-&gt;next; delete node_to_delete; } delete tail.next; } } }; } </code></pre> <p><strong>mergeSortTopDownLinkedList.h:</strong></p> <pre><code>#pragma once #include "doublelinkedlist.h" class MergeTopDown{ public: static void sort(ythlearn::DLinkList&lt;int&gt; &amp;a){ sort(a, 0, a.size() - 1); } private: static void sort(ythlearn::DLinkList&lt;int&gt; &amp;a, int lo, int hi){ int mid = lo + (hi - lo) / 2; if(hi &lt;= lo) return; sort(a, lo, mid); sort(a, mid+1, hi); merge(a, lo, mid, hi); } public: static void merge(ythlearn::DLinkList&lt;int&gt; &amp;a, int lo, int mid, int hi){ auto loPtr = a.getIndexPointer(lo); auto midPtr = a.getIndexPointer(loPtr, mid - lo); auto midPlus1 = midPtr-&gt;next; auto hiPtr = a.getIndexPointer(midPtr, hi - mid); //if it's not sorted from head to tail, then need these two helper Node auto NodePtrBeforeLo = loPtr-&gt;prev; auto NodePtrAfterHi = hiPtr-&gt;next; //split them into 2 isolated chains midPtr-&gt;next = nullptr; hiPtr-&gt;next = nullptr; ythlearn::DLinkList&lt;int&gt;::Node newList; decltype(loPtr) newListPtr = &amp;newList; while(loPtr != nullptr &amp;&amp; midPlus1 != nullptr){ if(loPtr-&gt;elem &lt; midPlus1-&gt;elem){ newListPtr-&gt;next = loPtr; loPtr-&gt;prev = newListPtr; loPtr = loPtr-&gt;next; newListPtr = newListPtr-&gt;next; }else{ newListPtr-&gt;next = midPlus1; midPlus1-&gt;prev = newListPtr; midPlus1 = midPlus1-&gt;next; newListPtr = newListPtr-&gt;next; } } if(loPtr == nullptr){ newListPtr-&gt;next = midPlus1; midPlus1-&gt;prev = newListPtr; if(hi-lo != a.size() - 1){ NodePtrAfterHi-&gt;prev = hiPtr; hiPtr-&gt;next = NodePtrAfterHi; } if(hi == a.size() - 1){ a.tail.next = hiPtr; } }else{ newListPtr-&gt;next = loPtr; loPtr-&gt;prev = newListPtr; if(hi-lo != a.size() - 1){ NodePtrAfterHi-&gt;prev = midPtr; midPtr-&gt;next = NodePtrAfterHi; } if(hi == a.size() - 1){ a.tail.next = midPtr; } } //Insert it back if(hi - lo != a.size() - 1){ NodePtrBeforeLo-&gt;next = newList.next; newList.next-&gt;prev = NodePtrBeforeLo; } if(lo == 0){ a.head.next = newList.next; } } }; </code></pre> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;random&gt; #include "doublelinkedlist.h" #include "mergeSortTopDownLinkedList.h" #include &lt;chrono&gt; using namespace std; using namespace ythlearn; using namespace std::chrono; random_device rd; mt19937 e(rd()); uniform_int_distribution&lt;int&gt; dist(INT16_MIN, INT16_MAX); int main(){ cout //&lt;&lt; "i\t" &lt;&lt; "runtime\t" &lt;&lt; endl; for(int i = 32; true; i = i * 2){ DLinkList&lt;int&gt; dl; for(int j = 0; j &lt; i; j++){ dl.push_right(dist(e)); } auto start = high_resolution_clock::now(); MergeTopDown::sort(dl); auto stop = high_resolution_clock::now(); auto duration = duration_cast&lt;microseconds&gt;(stop - start); cout &lt;&lt; duration.count() &lt;&lt; endl; } return 0; } </code></pre> <hr> <h2>Array (<code>std::vector</code>) version:</h2> <p><strong>mergeSortTopDown.h:</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;iostream&gt; class MergeTopDown{ public: static void sort(std::vector&lt;int&gt; &amp;a, std::vector&lt;int&gt; &amp;aux){ sort(a, aux, 0, a.size() - 1); } private: static void sort(std::vector&lt;int&gt; &amp;a, std::vector&lt;int&gt; &amp;aux, int lo, int hi){ int mid = lo + (hi - lo) / 2; if(hi &lt;= lo) return; sort(a, aux, lo, mid); sort(a, aux, mid+1, hi); merge(a, aux, lo, mid, hi); } static void merge(std::vector&lt;int&gt; &amp;a, std::vector&lt;int&gt; &amp;aux, int lo, int mid, int hi){ for(int k = lo; k &lt;= hi; k++){ aux[k] = a[k]; } int i = lo, j = mid+1; for(int k = lo; k &lt;= hi; k++){ if(i &gt; mid){ a[k] = aux[j++]; }else if (j &gt; hi){ a[k] = aux[i++]; }else if(aux[i] &lt; aux[j]){ a[k] = aux[i++]; }else{ a[k] = aux[j++]; } } } }; </code></pre> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;random&gt; #include &lt;chrono&gt; #include "mergeSortTopDown.h" using namespace std::chrono; using namespace std; random_device rd; mt19937 e(rd()); uniform_int_distribution&lt;int&gt; dist(INT16_MIN, INT16_MAX); int main(){ for(int i = 32; true ; i = i * 2){ vector&lt;int&gt; a(i); vector&lt;int&gt; aux(i); for(int j = 0; j &lt; i ; j++){ a[j] = dist(e); } auto start = high_resolution_clock::now(); MergeTopDown::sort(a, aux); auto stop = high_resolution_clock::now(); auto duration = duration_cast&lt;microseconds&gt;(stop - start); cout &lt;&lt; duration.count() &lt;&lt; endl; } return 0; } </code></pre> <hr> <h1>Runtime test</h1> <p><strong>Array (<code>vector</code>)</strong>:</p> <pre class="lang-none prettyprint-override"><code> MergeSort Array input output(runtime, milliseconds) seconds 32 0 0 64 0 0 128 0 0 256 0 0 512 0 0 1024 0 0 2048 0 0 4096 1 0.001 8192 2 0.002 16384 6 0.006 32768 14 0.014 65536 28 0.028 131072 60 0.06 262144 126 0.126 524288 262 0.262 1048576 548 0.548 2097152 1206 1.206 4194304 2347 2.347 8388608 4847 4.847 16777216 10353 10.353 33554432 21698 21.698 </code></pre> <p><strong>Linked list:</strong></p> <pre class="lang-none prettyprint-override"><code> MergeSort Doubly Linked List input output(runtime, milliseconds) seconds 32 0 0 64 0 0 128 0 0 256 0 0 512 0 0 1024 2 0.002 2048 11 0.011 4096 47 0.047 8192 237 0.237 16384 1310 1.31 32768 6440 6.44 65536 29737 29.737 131072 209752 209.752 262144 Too long to wait 524288 1048576 2097152 4194304 8388608 16777216 33554432 </code></pre> <p>As you can see the linked list version is sooo much slower than the array one. Take input size of <code>65536</code> as example, <code>0.028s</code> vs <code>29.737s</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:47:44.517", "Id": "407399", "Score": "2", "body": "The big-O question isn't really on-topic for CodeReview. But you can figure out the answer yourself! When you double N (say, from 8194 to 16384, or from 16384 to 32768, or from 32768 to 65536), what happens to the running time of your code? It goes up by a factor of 4, right? So what is the big-O here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:50:00.663", "Id": "407400", "Score": "2", "body": "To see *why* your algorithm is `O(n^2)`, look at how each `merge` calls `getIndexPointer`. How many times do you call `merge`? How many times do you call `getIndexPointer`? What is the big-O of `getIndexPointer`? (In particular, what is the _difference_ in big-O between your version of `getIndexPointer` for linked lists and the textbook's version of `getIndexPointer` for arrays?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:00:54.807", "Id": "407403", "Score": "0", "body": "Really, I don't think you should post the big-O question anywhere. You're just posting O(n^2) code disguised in a bunch of nested function calls and asking \"why is this O(n^2)?\" The answer is \"because it does O(n^2) work.\" There's no answer there that would be of general interest to the StackExchange community. If you want a review on the *code* — things like \"don't `using namespace std;`\" or \"a global variable of type `random_device` is really strange\" — indeed CodeReview is the place (but you can delete all the tables of timings)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:06:22.377", "Id": "407406", "Score": "0", "body": "@Quuxplusone OK, I got it. Give me a few mins to understand your explanations before I ask to close this question. Much thanks for help :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:12:32.540", "Id": "407407", "Score": "2", "body": "@Quuxplusone Damn you are amazing and I am being so stupid. It's indeed `O(n^2)`. I just ignore that factor 4 characteristic... . Also I do a power function regression in Excel and R square = 99.43% ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:14:57.987", "Id": "407408", "Score": "0", "body": "@Quuxplusone But you know how I think? I think, if I implement it based on the textbook array version,if I do not modify the whole algorithm structure, and only use single layer loop inside `merge`, at most I get `aN` (`a` is a constant )time complexity inside `merge`, then I think it would be the same`O(nlogn)` as the array version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:20:09.030", "Id": "407409", "Score": "1", "body": "Yep, if you could avoid modifying the algorithm and keep that single loop, it'd be `O(n lg n)`. But since you *added* a second, nested, loop, in `getIndexPointer` (another factor of `O(n)`), the result is `O(n lg n) * O(n) = O(n^2 lg n)`. (Or thereabouts. I didn't even bother with the factor of `lg n` because, as a wise man once said, `lg n` is about 30.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:26:31.960", "Id": "407411", "Score": "0", "body": "@Quuxplusone Ok I see. The reason why I want to implement it baesd on the original structure is because those C++ implementations on Web are difficult to understand and I was trying to be lazy... \"Reuse your code\"... But I was really feeling doubted on these code and could not convince myself. Now you pointed it out. Thank you again. ❤ And at last feel free to close it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T16:41:02.727", "Id": "210750", "Score": "2", "Tags": [ "c++", "performance", "complexity", "mergesort" ], "Title": "MergeSort linked list implementation" }
210750
<p>I just want feedback about the code. Better implementation, more commentary etc.</p> <p><a href="https://i.stack.imgur.com/Dzy4A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dzy4A.png" alt="The first storyboard"></a> </p> <p><a href="https://i.stack.imgur.com/tREA9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tREA9.png" alt="Second storyboard"></a></p> <ul> <li><p>app Delegate.swift</p> <pre><code>import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool { // Override point for customization after application launch. let storyboard = UIStoryboard(name: "Main", bundle: nil) let savedResultVC = storyboard.instantiateViewController(withIdentifier: "SavedResultViewController") as? SavesResultsTableViewController let introductionVC = window?.rootViewController as? IntroductionViewController introductionVC?.delegate = savedResultVC return true } </code></pre></li> <li><p>Introduction view controller</p> <pre><code>import UIKit class IntroductionViewController: UIViewController{ var delegate: SavesResultsTableViewControllerDelegate? @IBOutlet weak var matematicQuizButton: UIButton! @IBOutlet weak var montryQuizButton: UIButton! override func viewDidLoad() { super.viewDidLoad() delegate?.setResult(result: nil) // Do any additional setup after loading the view. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ContryQuizSegue" { let navigationController = segue.destination as! UINavigationController let quizViewController = navigationController.topViewController as! QuizViewController quizViewController.matematicalQuizIsHidden = true } } @IBAction func unwindResultToMenue(unwindSegue: UIStoryboardSegue) { } @IBAction func unwindSavedResultToMenue(unwindSegue: UIStoryboardSegue) { } </code></pre></li> <li><p>QuizViewController</p> <pre><code>import UIKit class QuizViewController: UIViewController { var matematicalExpressionAnswers = [MatematicalExpression]() var contryQuizAnswers = [Image_Contry]() var matematicalExpressionsNumber = 0 var contrysNumber = 0 var questionIndex = 1 var timer = Timer() var time:Int = 0 var matematicExpression:MatematicalExpression? var contry:Image_Contry? @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var matematicalQuizStackview: UIStackView! @IBOutlet weak var contryQuizStackView: UIStackView! @IBOutlet weak var matematicalExpressionTimerLabel: UILabel! @IBOutlet weak var matematicalExpresionLabel: UILabel! @IBOutlet weak var matematicalExpressionTextField: UITextField! @IBOutlet weak var contryQuizTimerLabel: UILabel! @IBOutlet weak var contryQuizImageView: UIImageView! @IBOutlet var contryQuizAnswerChoicesButtons: [UIButton]! var matematicalQuizIsHidden:Bool? var matematicalExpressions:[MatematicalExpression] = [MatematicalExpression(expression: "2 × 2", answer: "4", playerCorectlyAnswered: false), MatematicalExpression(expression: "5 + 2 × 6", answer: "17", playerCorectlyAnswered: false), MatematicalExpression(expression: "6 - 3 × 8 ÷ 4", answer: "0", playerCorectlyAnswered: false), MatematicalExpression(expression: "4 + 6 × 3 - 8", answer: "14", playerCorectlyAnswered: false), MatematicalExpression(expression: "3 × 5 - 36 ÷ 4 + 1", answer: "7", playerCorectlyAnswered: false), MatematicalExpression(expression: "5 + 3 - 9 × 2", answer: "-10", playerCorectlyAnswered: false)] // See pixeEb for image var contrys:[Image_Contry] = [Image_Contry(image: #imageLiteral(resourceName: "Pyramide"), answer: "Égypte", answerPossibility:["Cuba","Inde","Brésil","Égypte"] ,playerCorectlyAnswered: false), Image_Contry(image: #imageLiteral(resourceName: "Tour Eiffel"), answer: "France", answerPossibility: ["Angleterre","Russie","Allemagne","France"], playerCorectlyAnswered: false), Image_Contry(image: #imageLiteral(resourceName: "Machu Picchu"),answer:"Perou", answerPossibility: [ "Chili","Chine","Asie","Perou"], playerCorectlyAnswered: false), Image_Contry(image: #imageLiteral(resourceName: "Empire State Building"), answer: "Étas-Unis", answerPossibility: ["Mexique","Indonésie","Japon","Étas-Unis"], playerCorectlyAnswered: false), Image_Contry(image: #imageLiteral(resourceName: "gaspesie-1373018_1920"), answer: "Canada", answerPossibility: ["Grèce","Australie","Haïti","Canada"], playerCorectlyAnswered: false), Image_Contry(image: #imageLiteral(resourceName: "london-2393098_1920"), answer: "Angleterre", answerPossibility: ["Espagne","Italie","Corée du Sud","Angleterre"], playerCorectlyAnswered: false)] override func viewDidLoad() { super.viewDidLoad() if let hidden = matematicalQuizIsHidden { contrysNumber = contrys.count startContryTimer() matematicalQuizStackview.isHidden = hidden updateContryQuizUI() } else { matematicalExpressionsNumber = matematicalExpressions.count startMatematicalTimer() contryQuizStackView.isHidden = true updateMatematicalQuizUI() } // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } @IBAction func playerGuessedAnswerMatematicalExpression(_ sender: UITextField) { guard let answer = sender.text else {return} guard !answer.isEmpty else {return} sender.isEnabled = false if sender.text == matematicExpression?.answer { sender.textColor = UIColor.green matematicExpression?.playerCorectlyAnswered = true matematicalExpressionAnswers.append(matematicExpression!) } else { sender.textColor = UIColor.red matematicExpression?.playerCorectlyAnswered = false matematicalExpressionAnswers.append(matematicExpression!) } stopTimer() nextMatematicalExpression() } //UI matematicalQuizModification func updateMatematicalQuizUI() -&gt; Bool { guard matematicalExpressions.isEmpty == false else {return false} let number = Int.random(in: 0...matematicalExpressions.count - 1) matematicExpression = matematicalExpressions.remove(at: number) matematicalExpresionLabel.text = matematicExpression?.expression let totalProgress = Float(self.questionIndex)/Float(self.matematicalExpressionsNumber) self.progressBar.setProgress(totalProgress, animated: true) return true } func nextMatematicalExpression() { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.questionIndex += 1 self.matematicalExpressionTimerLabel.textColor = UIColor.black self.matematicalExpressionTextField.textColor = UIColor.black self.matematicalExpressionTextField.text = "" if self.updateMatematicalQuizUI() { self.matematicalExpressionTimerLabel.text = "10" self.startMatematicalTimer() self.matematicalExpressionTextField.isEnabled = true } else { self.matematicalExpressionTextField.isEnabled = false self.performSegue(withIdentifier: "ResultSegue", sender: nil) } } } func startMatematicalTimer() { time = 10 timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateMatematicalTimer), userInfo: nil, repeats: true) } func stopTimer() { timer.invalidate() } //text field func @objc func updateMatematicalTimer() { time -= 1 matematicalExpressionTimerLabel.text = String(time) if time &lt;= 0 { stopTimer() self.matematicExpression?.playerCorectlyAnswered = false self.matematicalExpressionTextField.isEnabled = false matematicalExpressionTimerLabel.textColor = UIColor.red matematicalExpressionAnswers.append(matematicExpression!) nextMatematicalExpression() } } //ContryUI function func startContryTimer() { time = 10 timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateContryTimer) , userInfo: nil, repeats: true) } @objc func updateContryTimer() { time -= 1 contryQuizTimerLabel.text = String(time) if time == 0 { stopTimer() contry?.playerCorectlyAnswered = false for button in self.contryQuizAnswerChoicesButtons { button.isEnabled = false } contryQuizTimerLabel.textColor = UIColor.red contryQuizAnswers.append(contry!) nextContry() } } func updateContryQuizUI() -&gt; Bool { guard !contrys.isEmpty else {return false} let number = Int.random(in: 0...contrys.count - 1) contry = contrys.remove(at: number) contryQuizImageView.image = contry?.image updateContryQuizButton(contry: contry!, buttons: contryQuizAnswerChoicesButtons) let totalProgress = Float(self.questionIndex)/Float(self.contrysNumber) self.progressBar.setProgress(totalProgress, animated: true) return true } func nextContry() { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.questionIndex += 1 self.contryQuizTimerLabel.textColor = UIColor.black for button in self.contryQuizAnswerChoicesButtons { button.titleLabel?.textColor = UIColor.black } for button in self.contryQuizAnswerChoicesButtons { button.isEnabled = true button.setTitleColor(.black, for: .normal) } if self.updateContryQuizUI() { self.contryQuizTimerLabel.text = "10" self.startContryTimer() } else { for button in self.contryQuizAnswerChoicesButtons { button.isEnabled = false } self.questionIndex = 0 self.performSegue(withIdentifier: "ResultSegue", sender:nil) } } } @IBAction func playerAnswerContryQuiz(_ sender: UIButton) { guard let answer = sender.titleLabel?.text else {return} for button in self.contryQuizAnswerChoicesButtons { button.isEnabled = false } if answer == contry?.answer { sender.setTitleColor(.green, for: .normal) contry?.playerCorectlyAnswered = true contryQuizAnswers.append(contry!) } else { sender.setTitleColor(.red, for: .normal) contry?.playerCorectlyAnswered = false contryQuizAnswers.append(contry!) } stopTimer() nextContry() } //prepare for segue func override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let resultViewController = segue.destination as? ResultViewController if matematicalQuizStackview.isHidden == true { resultViewController?.contryAnswers = contryQuizAnswers resultViewController?.matematicalAnswers = nil } else { resultViewController?.matematicalAnswers = matematicalExpressionAnswers resultViewController?.contryAnswers = nil } let resultVC = segue.destination as? ResultViewController let savedResultVC = storyboard?.instantiateViewController(withIdentifier: "SavedResultViewController") as? SavesResultsTableViewController resultVC?.delegate = savedResultVC } </code></pre></li> <li><p>Result ViewController</p> <pre><code>import UIKit protocol SavesResultsTableViewControllerDelegate { func setResult(result: QuizResult?) } class ResultViewController: UIViewController { var delegate: SavesResultsTableViewControllerDelegate? var matematicalAnswers:[MatematicalExpression]? var contryAnswers:[Image_Contry]? var goodAnswersNumber:Double { //Calcaulating the number of good answer var goodAnswers = 0 if let answers = matematicalAnswers { for answer in answers { if answer.playerCorectlyAnswered == true { goodAnswers += 1 } } } if let answers = contryAnswers { for answer in answers { if answer.playerCorectlyAnswered == true { goodAnswers += 1 } } } return Double(goodAnswers) } var result:String { var results = "" if let answers = matematicalAnswers { //Calculating the answer pourcentage let goodAnswerPourcentage = goodAnswersNumber/Double(answers.count) if goodAnswerPourcentage &lt; 0.25 { results = "Stupide" } else if goodAnswerPourcentage &gt;= 0.25 &amp;&amp; goodAnswerPourcentage &lt; 0.5 { results = "Dans la moyenne" } else if goodAnswerPourcentage &gt;= 0.50 &amp;&amp; goodAnswerPourcentage &lt; 0.75 { results = "In the averge" } else if goodAnswerPourcentage &gt;= 0.75 &amp;&amp; goodAnswerPourcentage &lt; 1 { results = "Au dessu de la moyenne" } else if goodAnswerPourcentage == 1 { results = "Génie" } } else if let answer = contryAnswers { let goodAnswerPourcentage = goodAnswersNumber/Double(answer.count) if goodAnswerPourcentage &lt; 0.25 { results = "Stupide" } else if goodAnswerPourcentage &gt;= 0.25 &amp;&amp; goodAnswerPourcentage &lt; 0.5 { results = "Dans la moyenne" } else if goodAnswerPourcentage &gt;= 0.50 &amp;&amp; goodAnswerPourcentage &lt; 1 { results = "Au dessu de la moyenne" } else if goodAnswerPourcentage == 1 { results = "Génie" } } return results } var resultText:String { var resultText = "" // define the result switch result { case "Stupide": resultText = "Vous avez peut être besoin de reviser vos mathématique ou d'appronfondir vos connaissance générale" case "Dans la moyenne": resultText = "Vous n'ête pas spécialement intelligent mais pas si idiot." case "Au dessu de la moyenne": resultText = "Vous êtes supérieur à la moyenne" case "Génie": resultText = "Vous mériter de controller le monde tellement vos faculté intelectuelle sont élevé" default: resultText = "Il y a eu une erreur" } return resultText } var quizResult:QuizResult { var type = "" if matematicalAnswers != nil { type = "Matematical Quiz" } if contryAnswers != nil { type = "Contry Quiz" } return QuizResult(quizType:type, result: result) } @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var resultDescriptionTextView: UITextView! @IBOutlet weak var resultTableView: UITableView! var tableViewDataSource = ResultTableViewDataSource() override func viewDidLoad() { super.viewDidLoad() tableViewDataSource.matematicalResults = matematicalAnswers tableViewDataSource.contryResults = contryAnswers self.resultLabel.text = result self.resultDescriptionTextView.text = resultText self.resultTableView.dataSource = tableViewDataSource delegate?.setResult(result: quizResult) // Do any additional setup after loading the view. } </code></pre></li> <li><p>SavesResultTableViewController</p> <pre><code>import UIKit class SavesResultsTableViewController: UITableViewController, SavesResultsTableViewControllerDelegate { func setResult(result: QuizResult?) { if let savedResult = QuizResult.loadFromFile() { self.results = savedResult } if let result = result { self.results.append(result) } } var results = [QuizResult]() { didSet { QuizResult.saveToFile(quizResults: results) } } override func viewDidLoad() { super.viewDidLoad() if let savedResult = QuizResult.loadFromFile() { self.results = savedResult } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { // #warning Incomplete implementation, return the number of rows return results.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "savedResult", for: indexPath) cell.textLabel?.text = "\(indexPath.row + 1). \(results[indexPath.row].quizType)" cell.detailTextLabel?.text = "\(results[indexPath.row].result)" return cell } </code></pre></li> <li><p>ResultTableViewDataSource</p> <pre><code>import UIKit class ResultTableViewDataSource: NSObject, UITableViewDataSource { var matematicalResults:[MatematicalExpression]? var contryResults:[Image_Contry]? func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { var resultsCount = 0 if let results = matematicalResults { resultsCount = results.count } else if let results = contryResults { resultsCount = results.count } return resultsCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell") as! ResultTableViewCell if let results = matematicalResults { cell.contryQuizStackView.isHidden = true let matematicalExpression = results[indexPath.row] cell.matematicalExpressionTrueOrFalseAnswer.textColor = matematicalExpression.playerCorectlyAnswered == true ? UIColor.green:UIColor.red cell.updateMatematicalExpressionStackViewContent(matematicalExpression: matematicalExpression.expression , trueOrFalse: matematicalExpression.playerCorectlyAnswered == true ? "✔︎":"✖︎") } else if let results = contryResults { cell.matematicalStackView.isHidden = true let contry = results[indexPath.row] cell.contryTrueOrFalseAnswer.textColor = contry.playerCorectlyAnswered == true ? UIColor.green:UIColor.red cell.updateContryStackViewContent(image: contry.image, trueOrFalse: contry.playerCorectlyAnswered == true ? "✔︎":"✖︎") } return cell } </code></pre></li> <li><p>ResultTableViewCell</p> <pre><code>{ @IBOutlet weak var contryQuizStackView: UIStackView! @IBOutlet weak var contryImage: UIImageView! @IBOutlet weak var contryTrueOrFalseAnswer: UILabel! @IBOutlet weak var matematicalStackView: UIStackView! @IBOutlet weak var matematicalExpressionLabel: UILabel! @IBOutlet weak var matematicalExpressionTrueOrFalseAnswer: UILabel! func updateContryStackViewContent(image:UIImage, trueOrFalse:String) { contryImage.image = image contryTrueOrFalseAnswer.text = trueOrFalse } func updateMatematicalExpressionStackViewContent(matematicalExpression: String, trueOrFalse: String) { matematicalExpressionLabel.text = matematicalExpression matematicalExpressionTrueOrFalseAnswer.text = trueOrFalse } } </code></pre></li> <li><p>MatematicalExpression</p> <pre><code>import Foundation struct MatematicalExpression { var expression:String var answer:String var playerCorectlyAnswered = false } </code></pre></li> <li><p>Image_Contry</p> <pre><code>import UIKit import Foundation struct Image_Contry { var image:UIImage var answer:String var answerPossibility:[String] var playerCorectlyAnswered = false } </code></pre></li> <li><p>QuizResult</p> <pre><code>import Foundation class QuizResult: Codable { var quizType:String var result:String static var documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! static var archiveURL = QuizResult.documentDirectory.appendingPathComponent("QuizResult").appendingPathExtension("plist") init(quizType:String,result:String) { self.quizType = quizType self.result = result } static func saveToFile(quizResults:[QuizResult]) { let quizResultEncoder = PropertyListEncoder() let encodedQuizResult = try? quizResultEncoder.encode(quizResults) try? encodedQuizResult?.write(to: archiveURL) } static func loadFromFile() -&gt; [QuizResult]? { let quizResultDecoder = PropertyListDecoder() if let retrivedQuizResults = try? Data(contentsOf: archiveURL) { if let decodedQuizResults = try? quizResultDecoder.decode(Array&lt;QuizResult&gt;.self, from: retrivedQuizResults) { return decodedQuizResults } } return nil } } </code></pre></li> <li><p>UpdateContryQuizButton</p> <pre><code>import UIKit // It was a test to see if I can put function in other file func updateContryQuizButton(contry:Image_Contry,buttons:[UIButton]) { var answerPossibilitys = contry.answerPossibility for button in buttons { let number = Int.random(in: 0...answerPossibilitys.count - 1) button.setTitle(answerPossibilitys.remove(at: number), for: .normal) } } </code></pre></li> </ul>
[]
[ { "body": "<p>First of all I want to mention that I used Swift 4.2/Xcode 10.1 to write this answer.</p>\n\n<p>You should have this <code>extension</code> in your project, <code>count(of:)</code> returns count of elements in a sequence that fit to your statement:</p>\n\n<pre><code>extension Sequence {\n func count(where predicate: (Element) -&gt; Bool) -&gt; Int {\n return reduce(0) { currentResult, currentItem in\n return currentResult + (predicate(currentItem) ? 1 : 0)\n }\n }\n}\n</code></pre>\n\n<p>As far as I can see in your code, <code>MatematicalExpression</code> and <code>Image_Contry</code> are very similar. You can declare a protocol that demonstrates this feature:</p>\n\n<pre><code>protocol AnswerDataProvider {\n var answer: String { get }\n var playerCorectlyAnswered: Bool { get }\n}\n</code></pre>\n\n<p><code>MatematicalExpression</code> and <code>Image_Contry</code> should implement this protocol:</p>\n\n<pre><code>extension MatematicalExpression: AnswerDataProvider { }\n\nextension Image_Contry: AnswerDataProvider { }\n</code></pre>\n\n<p>With this <code>extension</code> you can easily get count of correct answers:</p>\n\n<pre><code>extension Sequence where Element: AnswerDataProvider {\n var countOfCorrectAnswers: Int {\n return count { $0.playerCorectlyAnswered }\n }\n}\n</code></pre>\n\n<p>You have a lot of similar strings, use this <code>enum</code> to solve the problem:</p>\n\n<pre><code>enum Comment {\n case stupid\n case belowAverage\n case average\n case aboveAverage\n case genius\n\n var translation: String {\n switch self {\n case .stupid:\n return \"Stupide\"\n case .belowAverage:\n return \"Dans la moyenne\"\n case .average:\n return \"In the averge\"\n case .aboveAverage:\n return \"Au dessu de la moyenne\"\n case .genius:\n return \"Génie\"\n }\n }\n}\n</code></pre>\n\n<p>With this <code>enum</code> you will have only 1 property for <code>matematicalAnswers</code> and <code>contryAnswers</code> in <code>ResultViewController</code>:</p>\n\n<pre><code>enum Answers {\n case matematical([MatematicalExpression])\n case country([Image_Contry])\n}\n</code></pre>\n\n<p>I guess these functions can help you to solve different problems:</p>\n\n<pre><code>extension Answers {\n var countOfAllAnswers: Int {\n switch self {\n case .matematical(let matematicalExpressions):\n return matematicalExpressions.count\n case .country(let contryAnswers):\n return contryAnswers.count\n }\n }\n\n var countOfCorrectAnswers: Int {\n switch self {\n case .matematical(let matematicalExpressions):\n return matematicalExpressions.countOfCorrectAnswers\n case .country(let contryAnswers):\n return contryAnswers.countOfCorrectAnswers\n }\n }\n\n var goodAnswerPercentage: Double {\n return Double(countOfCorrectAnswers)/Double(countOfAllAnswers)\n }\n\n var percentageWithComments: [(Double, Comment)] {\n switch self {\n case .matematical:\n return [\n (0.0, .stupid),\n (0.25, .belowAverage),\n (0.5, .average),\n (0.75, .aboveAverage),\n (1.0, .genius)\n ]\n case .country:\n return [\n (0.0, .stupid),\n (0.25, .belowAverage),\n (0.5, .aboveAverage),\n (1.0, .genius)\n ]\n }\n }\n\n var result: String {\n let goodAnswerPercentageValue = goodAnswerPercentage\n return percentageWithComments.reversed().first {\n return goodAnswerPercentageValue &gt;= $0.0\n }?.1.translation ?? \"\"\n }\n\n var quizResult: QuizResult {\n let type: String\n switch self {\n case .matematical:\n type = \"Matematical Quiz\"\n case .country:\n type = \"Contry Quiz\"\n }\n return QuizResult(quizType: type, result: result)\n }\n}\n</code></pre>\n\n<p>In such case <code>ResultViewController</code> will be shorter:</p>\n\n<pre><code>class ResultViewController: UIViewController {\n\n var answers: Answers?\n var goodAnswersNumber: Double {\n return Double(answers?.countOfCorrectAnswers ?? 0)\n }\n\n var result: String {\n return answers?.result ?? \"\"\n }\n\n var quizResult: QuizResult {\n return answers?.quizResult ?? QuizResult(quizType: \"\", result: result)\n }\n\n //Other functions and properties\n}\n</code></pre>\n\n<p>You can try to refactor other controllers with the similar protocols and enums.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:47:49.233", "Id": "409810", "Score": "0", "body": "Thanks for the answer but I dont understand the \"where predicate: (Element)\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T17:32:00.877", "Id": "409815", "Score": "0", "body": "@C.Calvinno this function returns count of items that fit some statement. In your case you can use it for the count of correct answers. For more information check these links: https://forums.swift.org/t/count-where-on-sequence/11186 and https://github.com/apple/swift-evolution/blob/master/proposals/0220-count-where.md ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:22:37.007", "Id": "410098", "Score": "1", "body": "Hello @C.Calvinno. Do you still have questions regarding the `func count(where:)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:56:35.583", "Id": "410141", "Score": "0", "body": "No ,thanks, I had some question about the where keyword but I find the information on the internet. Now I gradually understand your way of coding and change mine" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T20:43:43.907", "Id": "211878", "ParentId": "210752", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T17:04:24.507", "Id": "210752", "Score": "1", "Tags": [ "swift", "quiz", "cocoa" ], "Title": "A quiz to practice some of the notion of the chapter four of app development with swift" }
210752
<p>This is a little project I did over Christmas, I wanted to understand a bit more about how RFC 1951 (<a href="https://www.ietf.org/rfc/rfc1951.txt" rel="nofollow noreferrer">https://www.ietf.org/rfc/rfc1951.txt</a>) compression worked, mostly out of curiosity really. RFC 1951 is used to compress PNG images, zip files and portions of PDF files ( and probably other things as well ). I have tried to keep the C# code fairly simple, concise and hopefully comprehensible, rather than being too concerned with efficiency. Here's the code:</p> <pre><code>using Generic = System.Collections.Generic; class Encoder : Generic.List&lt;byte&gt; // Data compression per RFC 1950, RFC 1951. { public Generic.List&lt;byte&gt; Deflate( byte [] inp ) { Clear(); Add( 0x78); Add( 0x9C ); // RFC 1950 bytes. ReadInp( inp ); while ( DoOutput( 1 ) == 0 ); FlushBitBuf(); Put32( Adler32( inp ) ); // RFC 1950 checksum. // System.Console.WriteLine( "Encoder.Deflate, input size=" + inp.Length + " output size=" + this.Count ); return this; } class PosList{ public int Pos; public PosList Next; } // List of 3-byte match positions. void ReadInp( byte [] input ) // LZ77 compression, per RFC 1951. { Generic.Dictionary&lt;int,PosList&gt; dict = new Generic.Dictionary&lt;int,PosList&gt;(); int n = input.Length; SetIBufSize( n ); int w = 0; // Holds last 3 bytes of input. int todo = 0; // Number of bytes in w that have not yet been output to IBuf, can be negative when a match is found. int pendingMatchLen = 0, pendingDist = 0; for ( int i = 0; i &lt; 2 &amp;&amp; i &lt; n; i += 1 ) { w = ( w &lt;&lt; 8 ) | input[ i ]; todo += 1; } for ( int i = 2; i &lt; n; i += 1 ) { w = ( ( w &lt;&lt; 8 ) | input[ i ] ) &amp; 0xffffff; todo += 1; PosList e, x = new PosList(); x.Pos = i; int bestMatchLen = 0, bestDist = 0; if ( dict.TryGetValue( w, out e ) ) { x.Next = e; PosList p = x; if ( todo &gt;= 3 ) while ( e != null ) { int dist = i - e.Pos; if ( dist &gt; 32768 ) { p.Next = null; break; } int matchLen = MatchLen( input, dist, i ); if ( matchLen &gt; bestMatchLen ) { bestMatchLen = matchLen; bestDist = dist; } p = e; e = e.Next; } } dict[ w ] = x; ISpace(); // "Lazy matching" RFC 1951 p.15 : if there are overlapping matches, there is a choice over which of the match to use. // Example: "abc012bc345.... abc345". Here abc345 can be encoded as either [abc][345] or as a[bc345]. // Since a range typically needs more bits to encode than a literal, choose the latter. if ( pendingMatchLen &gt; 0 ) { if ( bestMatchLen &gt; pendingMatchLen || bestMatchLen == pendingMatchLen &amp;&amp; bestDist &lt; pendingDist ) { IPut( input[ i-3 ] ); todo -= 1; } else // Save the pending match, suppress bestMatch if any. { IPut( 257 + pendingMatchLen ); IPut( pendingDist ); todo -= pendingMatchLen; bestMatchLen = 0; } pendingMatchLen = 0; } if ( bestMatchLen &gt; 0 ) { pendingMatchLen = bestMatchLen; pendingDist = bestDist; } else if ( todo == 3 ) { IPut( w &gt;&gt; 16 ); todo = 2; } } // End of main input loop. if ( pendingMatchLen &gt; 0 ) { IPut( 257 + pendingMatchLen ); IPut( pendingDist ); todo -= pendingMatchLen; } while ( todo &gt; 0 ){ todo -= 1; IPut( (byte)( w &gt;&gt; (todo*8) ) ); } } // end ReadInp int MatchLen( byte [] input, int dist, int i ) { // We have a match of 3 bytes, this function computes total match. int end = input.Length; if ( end - i &gt; 256 ) end = i + 256; // Maximum match is 258. int x = i + 1; while ( x &lt; end &amp;&amp; input[ x ] == input[ x-dist ] ) x += 1; return x - i + 2; } ushort [] IBuf; // Intermediate circular buffer, holds output from LZ77 algorithm. const int IBufSizeMax = 0x40000; int IBufSize, IBufI, IBufJ; void IPut( int x ) { IBuf[ IBufI++ ] = (ushort)x; if ( IBufI == IBufSize ) IBufI = 0; } int IGet(){ int result = IBuf[ IBufJ++ ]; if ( IBufJ == IBufSize ) IBufJ = 0; return result; } int ICount(){ if ( IBufI &gt;= IBufJ ) return IBufI - IBufJ; else return IBufI + IBufSize - IBufJ; } // Number of values in IBuf. void ISpace(){ while ( ICount() &gt; IBufSize - 10 ) DoOutput( 0 ); } // Ensure IBuf has space for at least 10 values. void SetIBufSize( int x ) { x += 20; if ( x &gt; IBufSizeMax ) x = IBufSizeMax; if ( IBufSize &lt; x ) { IBufSize = x; IBuf = new ushort[ x ]; } } byte DoOutput( byte lastBlock ) // While DoBlock fails, retry with a smaller amount of input. { int n = ICount(); while ( !DoBlock( n, lastBlock ) ) { lastBlock = 0; n -= n / 20; } return lastBlock; } // RFC 1951 encoding constants. static byte [] ClenAlphabet = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static byte [] MatchExtra = { 0,0,0,0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5, 0 }; static ushort [] MatchOff = { 3,4,5,6, 7,8,9,10, 11,13,15,17, 19,23,27,31, 35,43,51,59, 67,83,99,115, 131,163,195,227, 258, 0xffff }; static byte [] DistExtra = { 0,0,0,0, 1,1,2,2, 3,3,4,4, 5,5,6,6, 7,7,8,8, 9,9,10,10, 11,11,12,12, 13,13 }; static ushort [] DistOff = { 1,2,3,4, 5,7,9,13, 17,25,33,49, 65,97,129,193, 257,385,513,769, 1025,1537,2049,3073, 4097,6145,8193,12289, 16385,24577, 0xffff }; int [] LitFreq = new int [ 288 ], DistFreq = new int [ 32 ], LenFreq = new int [ 19 ]; byte [] LitLen = new byte [ 288 ], DistLen = new byte [ 32 ], LenLen = new byte [ 19 ]; ushort[] LitCode = new ushort[ 288 ], DistCode = new ushort[ 32 ], LenCode = new ushort[ 19 ]; bool DoBlock( int n, byte lastBlock ) { // First compute symbol frequencies. Clear( LitFreq ); Clear( DistFreq ); int saveIBufJ = IBufJ; int got = 0; while ( got &lt; n ) { int x = IGet(); got += 1; if ( x &lt; 256 ) LitFreq[ x ] += 1; else { x -= 257; int dist = IGet(); got += 1; int mc = 0; while ( x &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 0; while ( dist &gt;= DistOff[ dc ] ) dc += 1; dc -= 1; LitFreq[ 257 + mc ] += 1; DistFreq[ dc ] += 1; } } LitFreq[ 256 ] += 1; // End of block code. IBufJ = saveIBufJ; // Now compute Huffman codes. int nLitCode = Huff.ComputeCode( 15, LitFreq, LitLen, LitCode ); if ( nLitCode &lt; 0 ) return false; int nDistCode = Huff.ComputeCode( 15, DistFreq, DistLen, DistCode ); if ( nDistCode &lt; 0 ) return false; if ( nDistCode == 0 ) nDistCode = 1; Clear( LenFreq ); LenPass = 1; DoLengths( nLitCode, LitLen, true ); DoLengths( nDistCode, DistLen, false ); if ( Huff.ComputeCode( 7, LenFreq, LenLen, LenCode ) &lt; 0 ) return false; int nLenCode = 19; while ( nLenCode &gt; 4 &amp;&amp; LenLen[ ClenAlphabet[ nLenCode - 1 ] ] == 0 ) nLenCode -= 1; // Now output dynamic Huffman block. For small blocks fixed coding might work better, not implemented. PutBit( lastBlock ); PutBits( 2, 2 ); PutBits( 5, nLitCode - 257 ); PutBits( 5, nDistCode - 1 ); PutBits( 4, nLenCode - 4 ); for ( int i = 0; i &lt; nLenCode; i += 1 ) PutBits( 3, LenLen[ ClenAlphabet[ i ] ] ); LenPass = 2; DoLengths( nLitCode, LitLen, true ); DoLengths( nDistCode, DistLen, false ); got = 0; while ( got &lt; n ) // Similar to loop above, but does output instead of computing symbol frequencies. { int x = IGet(); got += 1; if ( x &lt; 256 ) PutBits( LitLen[ x ], LitCode[ x ] ); else { x -= 257; int dist = IGet(); got += 1; int mc = 0; while ( x &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 0; while ( dist &gt;= DistOff[ dc ] ) dc += 1; dc -= 1; PutBits( LitLen[ 257 + mc ], LitCode[ 257 + mc ] ); PutBits( MatchExtra[ mc ], x-MatchOff[ mc ] ); PutBits( DistLen[ dc ], DistCode[ dc ] ); PutBits( DistExtra[ dc ], dist-DistOff[ dc ] ); } } PutBits( LitLen[ 256 ], LitCode[ 256 ] ); // End of block code. return true; } // end DoBlock // Run length encoding of code lengths - RFC 1951, page 13. int LenPass, Plen, ZeroRun, Repeat; void PutLenCode( int code ) { if ( LenPass == 1 ) LenFreq[ code ] += 1; else PutBits( LenLen[ code ], LenCode[ code ] ); } void DoLengths( int n, byte [] a, bool isLit ) { if ( isLit ) { Plen = 0; ZeroRun = 0; Repeat = 0; } for ( int i = 0; i &lt; n; i += 1 ) { int len = a[ i ]; if ( len == 0 ){ EncRepeat(); ZeroRun += 1; Plen = 0; } else if ( len == Plen ) { Repeat += 1; } else { EncZeroRun(); EncRepeat(); PutLenCode( len ); Plen = len; } } if ( !isLit ) { EncZeroRun(); EncRepeat(); } } void EncRepeat() { while ( Repeat &gt; 0 ) { if ( Repeat &lt; 3 ) { PutLenCode( Plen ); Repeat -= 1; } else { int x = Repeat; if ( x &gt; 6 ) x = 6; PutLenCode( 16 ); if ( LenPass == 2 ) PutBits( 2, x-3 ); Repeat -= x; } } } void EncZeroRun() { while ( ZeroRun &gt; 0 ) { if ( ZeroRun &lt; 3 ) { PutLenCode( 0 ); ZeroRun -= 1; } else if ( ZeroRun &lt; 11 ) { PutLenCode( 17 ); if ( LenPass == 2 ) PutBits( 3, ZeroRun-3 ); ZeroRun = 0; } else { int x = ZeroRun; if ( x &gt; 138 ) x = 138; PutLenCode( 18 ); if ( LenPass == 2 ) PutBits( 7, x - 11 ); ZeroRun -= x; } } } public static uint Adler32( byte [] b ) // Checksum function per RFC 1950. { uint s1 = 1, s2 = 0; for ( int i = 0; i &lt; b.Length; i += 1 ) { s1 = ( s1 + b[ i ] ) % 65521; s2 = ( s2 + s1 ) % 65521; } return s2*65536 + s1; } static void Clear( int [] f ){ System.Array.Clear( f, 0, f.Length ); } // Output stream. byte Buf = 0, M = 1; void PutBit( int b ) { if ( b != 0 ) Buf |= M; M &lt;&lt;= 1; if ( M == 0 ) { Add(Buf); Buf = 0; M = 1; } } void PutBits( int n, int x ) { for ( int i = 0; i &lt; n; i += 1 ) { PutBit( x &amp; 1 ); x &gt;&gt;= 1; } } void FlushBitBuf(){ while ( M != 1 ) PutBit( 0 ); } void Put32( uint x ) { Add( (byte)( x &gt;&gt; 24 ) ); Add( (byte)( x &gt;&gt; 16 ) ); Add( (byte)( x &gt;&gt; 8 ) ); Add( (byte) x ); } } // end class Encoder //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ class Huff // Given a list of frequencies (freq), compute Huffman code lengths (nbits) and codes (tree_code). { public static int ComputeCode( int bitLimit, int [] freq, byte [] nbits, ushort [] tree_code ) { int ncode = freq.Length; Node [] heap = new Node[ ncode ]; int hn = 0; for ( int i = 0; i &lt; ncode; i += 1 ) { int f = freq[ i ]; if ( f &gt; 0 ) { Node n = new Node(); n.Freq = f; n.Code = (ushort)i; HeapInsert( heap, hn, n ); hn += 1; } } for ( int i = 0; i &lt; nbits.Length; i += 1 ) nbits[ i ] = 0; if ( hn &lt;= 1 ) // Special case. { if ( hn == 1 ) nbits[ heap[ 0 ].Code ] = 1; } else { while ( hn &gt; 1 ) // Keep pairing the lowest frequency nodes. { Node n = new Node(); hn -= 1; n.Left = HeapRemove( heap, hn ); hn -= 1; n.Right = HeapRemove( heap, hn ); n.Freq = n.Left.Freq + n.Right.Freq; n.Depth = (byte) ( 1 + ( n.Left.Depth &gt; n.Right.Depth ? n.Left.Depth : n.Right.Depth ) ); HeapInsert( heap, hn, n ); hn += 1; } Walk( nbits, heap[ 0 ], 0 ); // Walk the tree to find the code lengths (nbits). } for ( int i = 0; i &lt; ncode; i += 1 ) if ( nbits[ i ] &gt; bitLimit ) return -1; // Now compute codes, code below is from RFC 1951 page 7. int maxBits = 0; for ( int i = 0; i &lt; ncode; i += 1 ) if ( nbits[ i ] &gt; maxBits ) maxBits = nbits[ i ]; int [] bl_count = new int[ maxBits+1 ]; for ( int i = 0; i &lt; ncode; i += 1 ) bl_count[ nbits[ i ] ] += 1; int [] next_code = new int[ maxBits+1 ]; int code = 0; bl_count[ 0 ] = 0; for ( int i = 0; i &lt; maxBits; i += 1 ) { code = ( code + bl_count[ i ] ) &lt;&lt; 1; next_code[ i+1 ] = code; } for ( int i = 0; i &lt; ncode; i += 1 ) { int len = nbits[ i ]; if ( len != 0 ) { tree_code[ i ] = (ushort)Reverse( next_code[ len ], len ); next_code[ len ] += 1; } } while ( ncode &gt; 0 &amp;&amp; nbits[ ncode - 1 ] == 0 ) ncode -= 1; //System.Console.WriteLine( "Huff.ComputeCode" ); //for ( int i = 0; i &lt; ncode; i += 1 ) if ( nbits[ i ] &gt; 0 ) // System.Console.WriteLine( "i=" + i + " len=" + nbits[ i ] + " tc=" + tree_code[ i ].ToString("X") + " freq=" + freq[ i ] ); return ncode; } class Node{ public Node Left, Right; public int Freq; public ushort Code; public byte Depth; } static int Reverse( int x, int bits ) { int result = 0; for ( int i = 0; i &lt; bits; i += 1 ) { result &lt;&lt;= 1; result |= x &amp; 1; x &gt;&gt;= 1; } return result; } static void Walk( byte [] a, Node n, int len ) { if ( n.Left == null ) a[ n.Code ] = (byte)len; else { Walk( a, n.Left, len+1 ); Walk( a, n.Right, len+1 ); } } static bool LessThan( Node a, Node b ) { return a.Freq &lt; b.Freq || a.Freq == b.Freq &amp;&amp; a.Depth &lt; b.Depth; } // See e.g. https://en.wikipedia.org/wiki/Heap_(data_structure) for information on heap data structure. static void HeapInsert( Node [] heap, int h, Node n ) // h is size of heap before insertion. { int j = h; while ( j &gt; 0 ) { int p = ( j - 1 ) / 2; // Index of parent. Node pn = heap[ p ]; if ( !LessThan( n, pn ) ) break; heap[ j ] = pn; // Demote parent. j = p; } heap[ j ] = n; } static Node HeapRemove( Node [] heap, int h ) // h is size of heap after removal. { Node result = heap[ 0 ]; Node n = heap[ h ]; int j = 0; while ( true ) { int c = j * 2 + 1; if ( c &gt;= h ) break; Node cn = heap[ c ]; if ( c + 1 &lt; h ) { Node cn2 = heap[ c + 1 ]; if ( LessThan( cn2, cn ) ) { c += 1; cn = cn2; } } if ( !LessThan( cn, n ) ) break; heap[ j ] = cn; j = c; } heap[ j ] = n; return result; } } // end class Huff </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T19:21:22.653", "Id": "407421", "Score": "5", "body": "I find your one-liners, abbreviations and lots of strange names and formatting scarry, ugly, incomprihesible and generally terrible - do you always write code like this? :-\\" } ]
[ { "body": "<p>Welcome to Code Review. I am sorry but I do not find your code as comprehensible as you were hoping. I find myself more aligned to the comment by @t3chb0t.</p>\n\n<p>I really must ask have you ever read any parts of the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"noreferrer\">C# Naming Guidelines</a>? I am not saying that to be mean. Given that you are a new poster, we do try to be nice but unfortunately sometimes a certain bluntness cannot be avoided.</p>\n\n<p>Something to also consider is that you should <strong>favor composition over inheritance</strong> (<a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"noreferrer\">Wikipedia link</a>). Here is a good <a href=\"https://stackoverflow.com/a/53354/2152078\">StackOverflow link</a> on it too. Rather than class <code>Encoder</code> implementing <code>List&lt;byte&gt;</code>, it would be better to have a private field of <code>List&lt;byte&gt;</code>. This also prevents someone from inadvertently performing any method that modifies the encoded value, such as an Add, Clear, or Remove. You could then expose that field publicly as a read only value. </p>\n\n<p>You have a fair amount in a section related to the intermediate circular buffer. This bugs me for several reasons. For one, I think the buffer, variables, and methods could be put into its own class, even if its a private internal class. And having variable names being with \"I\" conflicts with the naming guideline on many fronts: (1) variables should begin with lowercase letters, and (2) a capital \"I\" makes me think its an <strong>I</strong>nterface.</p>\n\n<p>I applaud you for emphasizing simple and concise over efficient. Next I would urge you think strongly about readability. Ask yourself how well a mediocre C# developer would understand your code without having to ask you questions about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T22:52:38.603", "Id": "407433", "Score": "1", "body": "Rick, strictly speaking, according the the guidelines, \"The field-naming guidelines apply to static public and protected fields. Internal and private fields are not covered by guidelines\", but leaving that aside, I use the convention that local variables and parameters begin with lower-case, and other names begin with upper-case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:01:26.147", "Id": "407434", "Score": "1", "body": "Oops, pressed enter before I meant to... \n\nStill, the \"IBuf\" and associated fields could be better named, I didn't give any real thought to it. \n\nAgreed about composition and inheritance. I also plead guilty to abbreviation, I hope poor t3chb0t isn't scarred for life! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:16:12.083", "Id": "407474", "Score": "3", "body": "@GeorgeBarwood haha, I'm not ;-] I just find that carelessness about non-public code leads to many unnecessary hours of debugging and re-trying to understand the old code. The compiler doesn't care about the formatting or naming etc but people do and if I cannot relatively _quickly_ understand how the code works I do everything to avoid it (and not only me)... this is why you most likely should not expect a thorough review becasue your code is extremely difficult to read and to understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:16:28.523", "Id": "407475", "Score": "0", "body": "@GeorgeBarwood If you expect other people to read your non-public code you should treat it as public and take great care of it too and try to make it as clean as possible." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T21:13:28.467", "Id": "210768", "ParentId": "210757", "Score": "6" } }, { "body": "<h3>Readability</h3>\n\n<p>To expand a bit on what Rick and t3chb0t already said, here are some specific things that hurt the readability of your code:</p>\n\n<ul>\n<li>Unnecessary abbreviations and undescriptive names. Some names convey virtually no meaning at all (<code>n</code>, <code>w</code>, <code>x</code>, <code>p</code>), while others are very unclear or do not accurately describe their meaning: <code>ReadInp</code> apparently performs deflation, not just input reading, and what does the 'do' in <code>DoBlock</code> mean?</li>\n<li>Stuffing multiple statements on a single line. This makes code much more difficult to 'scan', and code that's difficult to read tends to be difficult to maintain and debug.\n\n<ul>\n<li>Especially jarring are lines like <br><code>int mc = 0; while (x &gt;= MatchOff[mc]) mc += 1; mc -= 1;</code><br>There's no clear distinction between what's part of the <code>while</code> loop body and what's not. This can lead to subtle problems. Putting each statement on a separate line, and indenting the loop body makes it easier to identify the control flow at a glance.</li>\n<li>Declaring multiple variables of the same type at once, separated by commas, also falls under this: it requires more care to see whether each has been properly initialized, and if not, whether that was intentional or not.</li>\n</ul></li>\n<li>Related to the above point, the occasional omission of braces and sometimes inconsistent indentation doesn't help either.</li>\n<li>Lack of whitespace:\n\n<ul>\n<li>Adding an empty line between subsequent <code>if</code> statements makes it more clear that they're not related, which makes it easier to quickly scan control flow.</li>\n<li>Leave an empty lines between methods to provide some 'breathing space'. A wall of text is more difficult to read than an article that's split up into chapters and paragraphs.</li>\n</ul></li>\n<li>Magic values - specific (numeric) values whose meaning is unclear, such as <code>19</code>, <code>256</code>, <code>257</code> and <code>288</code>. Try using properly named constants instead.</li>\n</ul>\n\n<h3>C# specific</h3>\n\n<ul>\n<li>It's strange to see <code>using Generic = System.Collections.Generic;</code>. Namespace aliases are useful to prevent name clashes, but in my experience that's rarely a problem. In this case, <code>System.Collections.Generic</code> is so ubiquitously used that doing anything else than <code>using System.Collections.Generic;</code> will only cause confusion.</li>\n<li>C# supports type inference, so <code>Dictionary&lt;int, PosList&gt; dict = new Dictionary&lt;int, PosList&gt;();</code> can be simplified to <code>var dict = new Dictionary&lt;int, PosList&gt;();</code>.</li>\n<li><code>out</code> variables can be declared in-line, so <code>if (dict.TryGetValue(w, out e))</code> can be simplified to <code>if (dict.TryGetValue(w, out PosList e))</code> or <code>if (dict.TryGetValue(w, out var e))</code>.</li>\n</ul>\n\n<h3>Design</h3>\n\n<ul>\n<li>Inheritance is the wrong tool here, as Rick already pointed out. Just because an encoder uses byte-sequences as input and output does not make it a list of bytes itself. Note how calling <code>Deflate</code> again will overwrite the result of any previous calls - that's very surprising behavior (in a negative way). Also note that a lot of state that is only useful during the actual deflation is kept around - wasting memory, and making your job more difficult because you have to remember to properly reset things.</li>\n<li>I see two designs that could work well here:\n\n<ul>\n<li>A <code>Stream</code>-based design, where you provide a <code>CompressionStream</code> class that inherits from <code>Stream</code> (it's a stream that you can read decompressed data from) and that wraps another <code>Stream</code> (which contains the still-compressed data). This integrates well with file and network stream reading, among other things. Be sure to read up on how disposal (<code>IDisposable</code>) works.</li>\n<li>An <code>IEnumerable&lt;byte&gt;</code>-based design, with an <code>IEnumerable&lt;byte&gt; Deflate(IEnumerable&lt;byte&gt; compressedData)</code> method. This lets you pass in a variety of collections, including arrays, lists and lazily evaluated sequences such as the results of Linq extension methods. Returning an <code>IEnumerable&lt;byte&gt;</code> allows you to return any of these as well, and lets you use <code>yield</code>, which can be useful in certain cases. <code>Deflate(byteArray.Skip(4))</code>, for example, deflates all but the first 4 bytes from <code>byteArray</code>, without any modifications to your code. And if <code>Deflate</code> uses <code>yield</code>, then <code>Deflate(byteArray).Take(4)</code> only deflates the first 4 bytes, while <code>Deflate(byteArray).ToArray()</code> gives you an array that contains all deflated data.</li>\n</ul></li>\n<li>Rick also mentioned those buffer-related methods, they're better moved to a separate buffer class. The same can be said for those 'output stream' methods. Take a look at how <code>StreamWriter</code> lets you write text to an underlying <code>Stream</code>, while taking care of things like encoding and buffering. You could create a similar construction for writing bits.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:04:58.623", "Id": "407537", "Score": "0", "body": "The idea was for the class to compress many parts of a PDF ( each page of a PDF has a \"content stream\" which can be \"deflated\" ), so the plan was to avoid re-allocating arrays/lists each time a page is compressed, reducing garbage collection overhead. But I didn't entirely follow-through on this, and whether it's worth worrying about I don't know - I haven't done any performance testing at all, or compared it to the standard Zlib implementation. Thanks for the C# tips, I had no idea about \"var\" or the other language features you mention." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T13:09:00.993", "Id": "210815", "ParentId": "210757", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T18:00:14.917", "Id": "210757", "Score": "3", "Tags": [ "c#", "compression", "heap" ], "Title": "RFC 1951 \"Deflate\" compression" }
210757
<p>I have a script running as an hourly cron job. It finds all screenshots on the Desktop and moves them to directories sorted by year/month/day.</p> <p>On MacOS, screenshots are automatically saved to the desktop with the following filename structure:</p> <p><code>"/Users/&lt;USER&gt;/Desktop/Screen Shot 2019-01-02 at 11.56.42 AM.png"</code></p> <pre><code>require 'fileutils' class Screenshot attr_reader :filepath def initialize(filepath) @filepath = filepath end def dir_exists? File.exists?(destination) || FileUtils.mkdir_p(destination) end def date @date ||= filepath.match(screenshot_regex) end def move FileUtils.mv(filepath, destination) if dir_exists? end def base_path "/Users/home/Pictures/Screenshots" end def destination "#{base_path}/#{date[:year]}/#{date[:month]}/#{date[:day]}" end def screenshot_regex /Shot (?&lt;year&gt;(.*))-(?&lt;month&gt;(.*))-(?&lt;day&gt;(.*)) at/ end end class Screenshots attr_reader :directory def initialize(directory) @directory = directory end def filepaths Dir.glob("#{directory}/Screen Shot*.png") end def files filepaths.map{|i| Screenshot.new(i)} end def move_all files.each(&amp;:move) end end Screenshots.new("/Users/home/Desktop").move_all </code></pre> <p>I'm sure there's a less messy approach here and I'd love to hear any criticism.</p>
[]
[ { "body": "<p>Your program is over-engineered in a way that makes it hard to decipher. Because every method is one line long, it's like reading a poem whose lines have been scrambled. You would be much better off writing a simple function, like this:</p>\n\n<pre><code>require 'fileutils'\n\ndef move_screenshots(src_dir, dest_tree)\n re = /^Screen Shot (?&lt;year&gt;\\d{4})-(?&lt;month&gt;\\d{2})-(?&lt;day&gt;\\d{2}) at/\n Dir.foreach(src_dir) do |filename|\n if date = re.match(filename)\n dest_dir = \"#{dest_tree}/#{date[:year]}/#{date[:month]}/#{date[:day]}\"\n FileUtils.mkdir_p(dest_dir)\n FileUtils.mv(\"#{src_dir}/#{filename}\", dest_dir)\n end\n end\nend\n\nmove_screenshots(\"/Users/home/Desktop\", \"/Users/home/Pictures/Screenshots\")\n</code></pre>\n\n<p>I wouldn't bother with <code>Dir#glob</code>, since it's a bit redundant with the regex. Note that screenshots aren't necessarily in PNG format: <a href=\"https://www.idownloadblog.com/2014/07/31/how-to-change-mac-screenshot-file-format/\" rel=\"nofollow noreferrer\">the image format can be configured using <code>defaults write com.apple.screencapture type …</code></a>. I also wouldn't bother testing <code>File#exists?</code> before calling <code>FileUtils#mkdir_p</code>, since <code>mkdir_p</code> implicitly performs that check anyway.</p>\n\n<p>Instead of an hourly cron job, consider creating a <a href=\"https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_folder_actions.html\" rel=\"nofollow noreferrer\">Folder Action Script</a> that is triggered instantly when a file is added to the folder.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:28:23.363", "Id": "407552", "Score": "0", "body": "I started off with something similar but broke it apart into those classes mostly for fun, but also with the intent to eventually revisit and expand it to target other common filetypes that might end up on my desktop. Wanted to use these as a starting point for that. Awesome suggestion on the folder action scripts. I had no idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:35:39.350", "Id": "407555", "Score": "0", "body": "Imagining for a second that this is part of a larger program, would this be an acceptable way to interact with a collection of object x that all need action y performed on them (separate class to represent the collection, mapping the seed data into a group of x instances, then calling y on each from within the collection obj)? Or would I still be overcomplicating it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:10:10.727", "Id": "407562", "Score": "0", "body": "If your program needs to be extensible, or if the classes are polymorphic in more than one method, then OOP might be worthwhile. Otherwise, you are probably overcomplicating it. Post a separate question with a specific use case, if you are unsure." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T20:50:18.003", "Id": "210766", "ParentId": "210760", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T19:43:30.160", "Id": "210760", "Score": "5", "Tags": [ "object-oriented", "ruby", "datetime", "file-system", "scheduled-tasks" ], "Title": "Scheduled file sorting with Ruby" }
210760
<p>I tried to make a generic, header-only vector thingy I can use in other projects in the future. I omitted documentation comments because it's already quite long.</p> <pre><code>#ifndef __VECTOR__ #define __VECTOR__ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; static int VECTOR_DEFAULT_SIZE = 1; typedef struct vector { void** data; int max; int size; } vector; static int vector_size(vector* v) { return v-&gt;size; } static int vector_capacity(vector* v) { return v-&gt;max; } static void* vector_get(vector* v, int i) { if (i &lt; 0 || i &gt;= vector_capacity(v)) return NULL; return v-&gt;data[i]; } static void vector_set(vector* v, int i, void* e) { if (i &lt; 0 || i &gt;= vector_capacity(v)) return; v-&gt;data[i] = e; } static vector* vector_create_sized(int size) { vector* v = malloc(sizeof(vector)); v-&gt;data = malloc(sizeof(void*) * size); v-&gt;max = size; v-&gt;size = 0; return v; }; static vector* vector_create() { return vector_create_sized(VECTOR_DEFAULT_SIZE); }; static void vector_clear(vector* v) { for(int i = 0; i &lt; v-&gt;max; i++) { vector_set(v, i, NULL); } v-&gt;size = 0; } static bool vector_is_empty(vector* v) { return vector_size(v) == 0; } static void vector_resize(vector* v, int size) { if (size &gt; vector_capacity(v)) { void** new = malloc(sizeof(void*) * size); for(int i = 0; i &lt; vector_capacity(v); i++) { new[i] = vector_get(v, i); } free(v-&gt;data); v-&gt;data = new; v-&gt;max = size; } } static void vector_insert(vector* v, int i, void* e) { if (i &lt; 0 || i &gt;= vector_capacity(v)) return; for(int j = vector_capacity(v) - 2; j &gt;= i; j--) { vector_set(v, j + 1, vector_get(v, j)); } vector_set(v, i, e); v-&gt;size++; if (vector_size(v) == vector_capacity(v)) vector_resize(v, vector_capacity(v) * 2); } static void vector_unshift(vector* v, void* e) { vector_insert(v, 0, e); } static void vector_push(vector* v, void* e) { vector_insert(v, vector_size(v), e); } static void vector_foreach(vector* v, void (*func)(int, const void*)) { if (vector_is_empty(v)) return; for(int i = 0; i &lt; vector_size(v); i++) { func(i, v-&gt;data[i]); } } static vector* vector_map(vector* v, void* (*func)(int, const void*)) { vector* w = vector_create_sized(vector_capacity(v)); for(int i = 0; i &lt; vector_size(v); i++) { void* e = vector_get(v, i); vector_push(w, func(i, e)); } return w; } static vector* vector_filter(vector* v, bool (*func)(int, const void*)) { vector* w = vector_create_sized(VECTOR_DEFAULT_SIZE); for(int i = 0; i &lt; vector_size(v); i++) { void* e = vector_get(v, i); if (func(i, e)) vector_push(w, e); } return w; } static bool vector_any(vector* v, bool (*func)(int, const void*)) { for(int i = 0; i &lt; vector_size(v); i++) { void* e = vector_get(v, i); if (func(i, e)) return true; } return false; } static bool vector_all(vector* v, bool (*func)(int, const void*)) { for(int i = 0; i &lt; vector_size(v); i++) { void* e = vector_get(v, i); if (!func(i, e)) return false; } return true; } static vector* vector_copy(vector* v) { vector* w = vector_create_sized(vector_capacity(v)); for(int i = 0; i &lt; vector_size(v); i++) { void* e = vector_get(v, i); vector_push(w, e); } return w; } static void* vector_remove(vector* v, int i) { if (i &lt; 0 || i &gt;= vector_capacity(v) || vector_is_empty(v)) return NULL; void* tmp = vector_get(v, i); for(int j = i; j &lt; vector_size(v); j++) { vector_set(v, j, vector_get(v, j + 1)); } v-&gt;size--; return tmp; } static void vector_erase(vector* v, bool (*func)(int, const void*)) { for(int i = vector_size(v) - 1; i &gt;= 0; i--) { void* e = vector_get(v, i); if (func(i, e)) vector_remove(v, i); } } static void* vector_pop(vector* v) { return vector_remove(v, vector_size(v) - 1); } static void* vector_shift(vector* v) { return vector_remove(v, 0); } static void vector_swap(vector* v, int i, int j) { if (i &lt; 0 || i &gt;= vector_size(v) || j &lt; 0 || j &gt;= vector_size(v)) return; void* tmp = vector_get(v, i); vector_set(v, i, vector_get(v, j)); vector_set(v, j, tmp); } static void vector_sort(vector* v, int (*cmp)(const void*, const void*)) { for (int i = 0; i &lt; vector_size(v); i++) { int j = i; while (j &gt; 0 &amp;&amp; cmp(vector_get(v, j - 1), vector_get(v, j)) &gt; 0) { vector_swap(v, j, j - 1); j--; } } } static void vector_reverse(vector* v) { int i = vector_size(v) - 1; int j = 0; while(i &gt; j) { vector_swap(v, i, j); i--; j++; } } static vector* vector_concat(vector* a, vector* b) { vector* c = vector_create_sized(vector_size(a) + vector_size(b)); for(int i = 0; i &lt; vector_size(a); i++) { vector_push(c, vector_get(a, i)); } for(int i = 0; i &lt; vector_size(b); i++) { vector_push(c, vector_get(b, i)); } return c; } static void vector_debug(vector* v) { printf("\n----------\nVector %i/%i\n", vector_size(v), vector_capacity(v)); for(int i = 0; i &lt; vector_size(v); i++) { printf("%i %p\n", i, vector_get(v, i)); } for(int i = vector_size(v); i &lt; vector_capacity(v); i++) { printf("%i NULL\n", i); } printf("----------\n"); } static void vector_free(vector* v) { free(v-&gt;data); free(v); }; #endif </code></pre> <p>Also here's a short example of usage, generating 2 vectors of random ints, concatenating, sorting and then reversing them in a third list:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; #include "vector.h" void free_int(int x, const void* p) { int* i = (int*)p; free(i); } void print_int(int x, const void* p) { int* i = (int*)p; int j = *i; printf("%i ", j); } int sort(const void* a, const void* b) { return *((int*)a) - *((int*)b); } int main(void) { srand(time(NULL)); vector* a = vector_create(); vector* b = vector_create(); for(int i = 0; i &lt; 10; i++) { int* n = malloc(sizeof(int)); *n = rand() % 50; vector_push(a, n); } for(int i = 0; i &lt; 10; i++) { int* n = malloc(sizeof(int)); *n = rand() % 50; vector_push(b, n); } printf("A: "); vector_foreach(a, print_int); printf("\nB: "); vector_foreach(b, print_int); vector* c = vector_concat(a, b); vector_sort(c, sort); vector_reverse(c); printf("\n\nA concat B sorted descending:\n"); vector_foreach(c, print_int); vector_foreach(c, free_int); vector_free(a); vector_free(b); vector_free(c); return 0; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T01:33:09.377", "Id": "408591", "Score": "0", "body": "Comment on `vector_resize`: it's probably easier and faster to use `realloc`." } ]
[ { "body": "<p><strong>Why one way re-sizing?</strong></p>\n\n<p><code>vector_resize()</code> only allows the vector to grow.</p>\n\n<p><strong><code>vector_insert()</code> growth oddity</strong></p>\n\n<p>Code can grow the vector size indefinitely if done by inserting at the end, yet quietly fails if the insert is far beyond the end.</p>\n\n<p>I'd expect the function to not grow at all or allow an insertion anywhere.</p>\n\n<p><strong>Sort can overflow</strong></p>\n\n<p>In <code>sort()</code>, rather than <code>return a - b</code> (with its UB overflow), use the idiomatic, not overflow possible: <code>return (a &gt; b) - (a &lt; b)</code>.</p>\n\n<p><strong>Avoid C++ keywords</strong></p>\n\n<p>For potential portability as well as clarity, avoid <code>new</code> as an object in C code.</p>\n\n<p>Code <em>looks</em> wrong.</p>\n\n<pre><code>void** new = malloc(sizeof(void*) * size);\n</code></pre>\n\n<p><strong>Allocate to the size of the de-referenced object</strong></p>\n\n<p>Avoid size errors. Do not allocate to the size of the type. The below is easier to code right, review and maintain.</p>\n\n<pre><code>// void** new = malloc(sizeof(void*) * size);\nvoid** nu = malloc(sizeof *nu * size);\n</code></pre>\n\n<p><strong>Allow state</strong></p>\n\n<p>With <code>vector_any()</code> pass in a <em>state</em> argument and return <code>int</code> for additional flexibility.</p>\n\n<pre><code>static int vector_any_alt(vector* v, void *state, int (*func)(state, int, const void*)) {\n for(int i = 0; i &lt; vector_size(v); i++) {\n int retval = func(state, i, v-&gt;data[i]);\n if (retval) {\n return retval;\n }\n }\n return 0;\n}\n</code></pre>\n\n<p><strong>Minor: <code>int</code> indexing vs. <code>size_t</code></strong></p>\n\n<p>I would have used <code>size_t</code> indexing rather than <code>int</code>, yet I suspect OP's desires <code>int</code>.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>Why call use <code>.max</code> instead of <code>.capacity</code>? or<br>\nWhy call use <code>vector_capacity()</code> instead of <code>vector_max()</code>.</p>\n\n<p><strong>Use <code>const</code></strong></p>\n\n<p>Various functions like <code>vector_is_empty(vector* v)</code> convey meaning better, allow for expanded use and sometime optimize better with <code>const</code>.</p>\n\n<pre><code>// vector_is_empty(vector* v)\nvector_is_empty(const vector* v)\n</code></pre>\n\n<p><strong>Use <code>(void)</code></strong></p>\n\n<p>With <code>()</code>, no parameters checking occurs allowing <code>vector_create(1,2,3)</code> to not generate an error.</p>\n\n<pre><code>// static vector* vector_create()\nstatic vector* vector_create(void)\n</code></pre>\n\n<p><strong>Why clear to capacity?</strong></p>\n\n<p><code>vector_clear()</code> clears all <code>v-&gt;max</code> rather than <code>v&gt;size</code>.</p>\n\n<p><strong>Why upper case object name?</strong></p>\n\n<p><code>static int VECTOR_DEFAULT_SIZE = 1;</code> will certainly throw off users. Consider <code>static int vector_default_size = 1;</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T05:05:16.650", "Id": "210787", "ParentId": "210761", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T19:54:28.803", "Id": "210761", "Score": "1", "Tags": [ "c", "memory-management", "vectors", "memory-optimization" ], "Title": "Header-only vector implementation in C" }
210761
<p>I have a <a href="https://github.com/boostorg/math/pull/173" rel="nofollow noreferrer">PR</a> implementing denoising discrete Lanczos derivatives, following <a href="https://doi.org/10.1080/00207160.2012.666348" rel="nofollow noreferrer">this paper</a>. The following code works well, but <em>the design is a train wreck</em>, and I was hoping to get some advice to improve it.</p> <p>But here's what it does: Give it some noisy data, and it will compute a reasonable derivative from it, so long as the SNR > 1:</p> <p><a href="https://i.stack.imgur.com/FObAf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FObAf.png" alt="LIGO signal"></a></p> <p>The orange time series shows the raw LIGO signal. The blue is the derivative of the LIGO signal computed with the (n,p) = (60, 4) discrete Lanczos derivative, and the gray is the standard finite difference formula, which is total garbage.</p> <p>I will only post the code, but here are the <a href="https://raw.githubusercontent.com/boostorg/math/d76d49533ab0d917579a471f1d542c02612ed421/test/lanczos_smoothing_test.cpp" rel="nofollow noreferrer">tests</a> and <a href="https://raw.githubusercontent.com/boostorg/math/d76d49533ab0d917579a471f1d542c02612ed421/doc/differentiation/lanczos_smoothing.qbk" rel="nofollow noreferrer">documentation</a>.</p> <pre><code>#ifndef BOOST_MATH_DIFFERENTIATION_LANCZOS_SMOOTHING_HPP #define BOOST_MATH_DIFFERENTIATION_LANCZOS_SMOOTHING_HPP #include &lt;vector&gt; #include &lt;boost/assert.hpp&gt; namespace boost::math::differentiation { namespace detail { template &lt;typename Real&gt; class discrete_legendre { public: explicit discrete_legendre(size_t n) : m_n{n}, m_r{2}, m_x{std::numeric_limits&lt;Real&gt;::quiet_NaN()}, m_qrm2{std::numeric_limits&lt;Real&gt;::quiet_NaN()}, m_qrm1{std::numeric_limits&lt;Real&gt;::quiet_NaN()}, m_qrm2p{std::numeric_limits&lt;Real&gt;::quiet_NaN()}, m_qrm1p{std::numeric_limits&lt;Real&gt;::quiet_NaN()}, m_qrm2pp{std::numeric_limits&lt;Real&gt;::quiet_NaN()}, m_qrm1pp{std::numeric_limits&lt;Real&gt;::quiet_NaN()} { // The integer n indexes a family of discrete Legendre polynomials indexed by k &lt;= 2*n } Real norm_sq(int r) { Real prod = Real(2) / Real(2 * r + 1); for (int k = -r; k &lt;= r; ++k) { prod *= Real(2 * m_n + 1 + k) / Real(2 * m_n); } return prod; } void initialize_recursion(Real x) { using std::abs; BOOST_ASSERT_MSG(abs(x) &lt;= 1, "Three term recurrence is stable only for |x| &lt;=1."); m_qrm2 = 1; m_qrm1 = x; // Derivatives: m_qrm2p = 0; m_qrm1p = 1; // Second derivatives: m_qrm2pp = 0; m_qrm1pp = 0; m_r = 2; m_x = x; } Real next() { Real N = 2 * m_n + 1; Real num = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) * m_qrm2; Real tmp = (2 * m_r - 1) * m_x * m_qrm1 - num / Real(4 * m_n * m_n); m_qrm2 = m_qrm1; m_qrm1 = tmp / m_r; ++m_r; return m_qrm1; } Real next_prime() { Real N = 2 * m_n + 1; Real s = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) / Real(4 * m_n * m_n); Real tmp1 = ((2 * m_r - 1) * m_x * m_qrm1 - s * m_qrm2) / m_r; Real tmp2 = ((2 * m_r - 1) * (m_qrm1 + m_x * m_qrm1p) - s * m_qrm2p) / m_r; m_qrm2 = m_qrm1; m_qrm1 = tmp1; m_qrm2p = m_qrm1p; m_qrm1p = tmp2; ++m_r; return m_qrm1p; } Real next_dbl_prime() { Real N = 2*m_n + 1; Real trm1 = 2*m_r - 1; Real s = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) / Real(4 * m_n * m_n); Real rqrpp = 2*trm1*m_qrm1p + trm1*m_x*m_qrm1pp - s*m_qrm2pp; Real tmp1 = ((2 * m_r - 1) * m_x * m_qrm1 - s * m_qrm2) / m_r; Real tmp2 = ((2 * m_r - 1) * (m_qrm1 + m_x * m_qrm1p) - s * m_qrm2p) / m_r; m_qrm2 = m_qrm1; m_qrm1 = tmp1; m_qrm2p = m_qrm1p; m_qrm1p = tmp2; m_qrm2pp = m_qrm1pp; m_qrm1pp = rqrpp/m_r; ++m_r; return m_qrm1pp; } Real operator()(Real x, size_t k) { BOOST_ASSERT_MSG(k &lt;= 2 * m_n, "r &lt;= 2n is required."); if (k == 0) { return 1; } if (k == 1) { return x; } Real qrm2 = 1; Real qrm1 = x; Real N = 2 * m_n + 1; for (size_t r = 2; r &lt;= k; ++r) { Real num = (r - 1) * (N * N - (r - 1) * (r - 1)) * qrm2; Real tmp = (2 * r - 1) * x * qrm1 - num / Real(4 * m_n * m_n); qrm2 = qrm1; qrm1 = tmp / r; } return qrm1; } Real prime(Real x, size_t k) { BOOST_ASSERT_MSG(k &lt;= 2 * m_n, "r &lt;= 2n is required."); if (k == 0) { return 0; } if (k == 1) { return 1; } Real qrm2 = 1; Real qrm1 = x; Real qrm2p = 0; Real qrm1p = 1; Real N = 2 * m_n + 1; for (size_t r = 2; r &lt;= k; ++r) { Real s = (r - 1) * (N * N - (r - 1) * (r - 1)) / Real(4 * m_n * m_n); Real tmp1 = ((2 * r - 1) * x * qrm1 - s * qrm2) / r; Real tmp2 = ((2 * r - 1) * (qrm1 + x * qrm1p) - s * qrm2p) / r; qrm2 = qrm1; qrm1 = tmp1; qrm2p = qrm1p; qrm1p = tmp2; } return qrm1p; } private: size_t m_n; size_t m_r; Real m_x; Real m_qrm2; Real m_qrm1; Real m_qrm2p; Real m_qrm1p; Real m_qrm2pp; Real m_qrm1pp; }; template &lt;class Real&gt; std::vector&lt;Real&gt; interior_filter(size_t n, size_t p) { // We could make the filter length n, as f[0] = 0, // but that'd make the indexing awkward when applying the filter. std::vector&lt;Real&gt; f(n + 1, 0); auto dlp = discrete_legendre&lt;Real&gt;(n); std::vector&lt;Real&gt; coeffs(p+1, std::numeric_limits&lt;Real&gt;::quiet_NaN()); dlp.initialize_recursion(0); coeffs[1] = 1/dlp.norm_sq(1); for (size_t l = 3; l &lt; p + 1; l += 2) { dlp.next_prime(); coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l); } for (size_t j = 1; j &lt; f.size(); ++j) { Real arg = Real(j) / Real(n); dlp.initialize_recursion(arg); f[j] = coeffs[1]*arg; for (size_t l = 3; l &lt;= p; l += 2) { dlp.next(); f[j] += coeffs[l]*dlp.next(); } f[j] /= (n * n); } return f; } template &lt;class Real&gt; std::vector&lt;Real&gt; boundary_filter(size_t n, size_t p, int64_t s) { std::vector&lt;Real&gt; f(2 * n + 1, 0); auto dlp = discrete_legendre&lt;Real&gt;(n); Real sn = Real(s) / Real(n); std::vector&lt;Real&gt; coeffs(p+1, std::numeric_limits&lt;Real&gt;::quiet_NaN()); dlp.initialize_recursion(sn); coeffs[0] = 0; coeffs[1] = 1/dlp.norm_sq(1); for (size_t l = 2; l &lt; p + 1; ++l) { // Calculation of the norms is common to all filters, // so it seems like an obvious optimization target. // I tried this: The spent in computing the norms time is not negligible, // but still a small fraction of the total compute time. // Hence I'm not refactoring out these norm calculations. coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l); } for (size_t k = 0; k &lt; f.size(); ++k) { Real j = Real(k) - Real(n); f[k] = 0; Real arg = j/Real(n); dlp.initialize_recursion(arg); f[k] = coeffs[1]*arg; for (size_t l = 2; l &lt;= p; ++l) { f[k] += coeffs[l]*dlp.next(); } f[k] /= (n * n); } return f; } template &lt;class Real&gt; std::vector&lt;Real&gt; acceleration_boundary_filter(size_t n, size_t p, int64_t s) { BOOST_ASSERT_MSG(p &lt;= 2*n, "Approximation order must be &lt;= 2*n"); BOOST_ASSERT_MSG(p &gt; 2, "Approximation order must be &gt; 2"); std::vector&lt;Real&gt; f(2 * n + 1, 0); auto dlp = discrete_legendre&lt;Real&gt;(n); Real sn = Real(s) / Real(n); std::vector&lt;Real&gt; coeffs(p+2, std::numeric_limits&lt;Real&gt;::quiet_NaN()); dlp.initialize_recursion(sn); coeffs[0] = 0; coeffs[1] = 0; for (size_t l = 2; l &lt; p + 2; ++l) { coeffs[l] = dlp.next_dbl_prime()/ dlp.norm_sq(l); } for (size_t k = 0; k &lt; f.size(); ++k) { Real j = Real(k) - Real(n); f[k] = 0; Real arg = j/Real(n); dlp.initialize_recursion(arg); f[k] = coeffs[1]*arg; for (size_t l = 2; l &lt;= p; ++l) { f[k] += coeffs[l]*dlp.next(); } f[k] /= (n * n * n); } return f; } } // namespace detail template &lt;typename Real, size_t order = 1&gt; class discrete_lanczos_derivative { public: discrete_lanczos_derivative(Real const &amp; spacing, size_t n = 18, size_t approximation_order = 3) : m_dt{spacing} { static_assert(!std::is_integral_v&lt;Real&gt;, "Spacing must be a floating point type."); BOOST_ASSERT_MSG(spacing &gt; 0, "Spacing between samples must be &gt; 0."); if constexpr (order == 1) { BOOST_ASSERT_MSG(approximation_order &lt;= 2 * n, "The approximation order must be &lt;= 2n"); BOOST_ASSERT_MSG(approximation_order &gt;= 2, "The approximation order must be &gt;= 2"); m_f = detail::interior_filter&lt;Real&gt;(n, approximation_order); m_boundary_filters.resize(n); for (size_t i = 0; i &lt; n; ++i) { // s = i - n; int64_t s = static_cast&lt;int64_t&gt;(i) - static_cast&lt;int64_t&gt;(n); m_boundary_filters[i] = detail::boundary_filter&lt;Real&gt;(n, approximation_order, s); } } else if constexpr (order == 2) { auto f = detail::acceleration_boundary_filter&lt;Real&gt;(n, approximation_order, 0); m_f.resize(n+1); for (size_t i = 0; i &lt; m_f.size(); ++i) { m_f[i] = f[i+n]; } m_boundary_filters.resize(n); for (size_t i = 0; i &lt; n; ++i) { int64_t s = static_cast&lt;int64_t&gt;(i) - static_cast&lt;int64_t&gt;(n); m_boundary_filters[i] = detail::acceleration_boundary_filter&lt;Real&gt;(n, approximation_order, s); } } else { BOOST_ASSERT_MSG(false, "Derivatives of order 3 and higher are not implemented."); } } void reset_spacing(Real const &amp; spacing) { BOOST_ASSERT_MSG(spacing &gt; 0, "Spacing between samples must be &gt; 0."); m_dt = spacing; } Real spacing() const { return m_dt; } template&lt;class RandomAccessContainer&gt; Real operator()(RandomAccessContainer const &amp; v, size_t i) const { static_assert(std::is_same_v&lt;typename RandomAccessContainer::value_type, Real&gt;, "The type of the values in the vector provided does not match the type in the filters."); using std::size; BOOST_ASSERT_MSG(size(v) &gt;= m_boundary_filters[0].size(), "Vector must be at least as long as the filter length"); if constexpr (order==1) { if (i &gt;= m_f.size() - 1 &amp;&amp; i &lt;= size(v) - m_f.size()) { Real dv = 0; for (size_t j = 1; j &lt; m_f.size(); ++j) { dv += m_f[j] * (v[i + j] - v[i - j]); } return dv / m_dt; } // m_f.size() = N+1 if (i &lt; m_f.size() - 1) { auto &amp;bf = m_boundary_filters[i]; Real dv = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { dv += bf[j] * v[j]; } return dv / m_dt; } if (i &gt; size(v) - m_f.size() &amp;&amp; i &lt; size(v)) { int k = size(v) - 1 - i; auto &amp;bf = m_boundary_filters[k]; Real dv = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { dv += bf[j] * v[size(v) - 1 - j]; } return -dv / m_dt; } } else if constexpr (order==2) { if (i &gt;= m_f.size() - 1 &amp;&amp; i &lt;= size(v) - m_f.size()) { Real d2v = m_f[0]*v[i]; for (size_t j = 1; j &lt; m_f.size(); ++j) { d2v += m_f[j] * (v[i + j] + v[i - j]); } return d2v / (m_dt*m_dt); } // m_f.size() = N+1 if (i &lt; m_f.size() - 1) { auto &amp;bf = m_boundary_filters[i]; Real d2v = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { d2v += bf[j] * v[j]; } return d2v / (m_dt*m_dt); } if (i &gt; size(v) - m_f.size() &amp;&amp; i &lt; size(v)) { int k = size(v) - 1 - i; auto &amp;bf = m_boundary_filters[k]; Real d2v = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { d2v += bf[j] * v[size(v) - 1 - j]; } return d2v / (m_dt*m_dt); } } // OOB access: BOOST_ASSERT_MSG(false, "Out of bounds access in Lanczos derivative"); return std::numeric_limits&lt;Real&gt;::quiet_NaN(); } template&lt;class RandomAccessContainer&gt; RandomAccessContainer operator()(RandomAccessContainer const &amp; v) const { static_assert(std::is_same_v&lt;typename RandomAccessContainer::value_type, Real&gt;, "The type of the values in the vector provided does not match the type in the filters."); using std::size; BOOST_ASSERT_MSG(size(v) &gt;= m_boundary_filters[0].size(), "Vector must be at least as long as the filter length"); RandomAccessContainer w(size(v)); if constexpr (order==1) { for (size_t i = 0; i &lt; m_f.size() - 1; ++i) { auto &amp;bf = m_boundary_filters[i]; Real dv = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { dv += bf[j] * v[j]; } w[i] = dv / m_dt; } for(size_t i = m_f.size() - 1; i &lt;= size(v) - m_f.size(); ++i) { Real dv = 0; for (size_t j = 1; j &lt; m_f.size(); ++j) { dv += m_f[j] * (v[i + j] - v[i - j]); } w[i] = dv / m_dt; } for(size_t i = size(v) - m_f.size() + 1; i &lt; size(v); ++i) { int k = size(v) - 1 - i; auto &amp;f = m_boundary_filters[k]; Real dv = 0; for (size_t j = 0; j &lt; f.size(); ++j) { dv += f[j] * v[size(v) - 1 - j]; } w[i] = -dv / m_dt; } } else if constexpr (order==2) { // m_f.size() = N+1 for (size_t i = 0; i &lt; m_f.size() - 1; ++i) { auto &amp;bf = m_boundary_filters[i]; Real d2v = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { d2v += bf[j] * v[j]; } w[i] = d2v / (m_dt*m_dt); } for (size_t i = m_f.size() - 1; i &lt;= size(v) - m_f.size(); ++i) { Real d2v = m_f[0]*v[i]; for (size_t j = 1; j &lt; m_f.size(); ++j) { d2v += m_f[j] * (v[i + j] + v[i - j]); } w[i] = d2v / (m_dt*m_dt); } for (size_t i = size(v) - m_f.size() + 1; i &lt; size(v); ++i) { int k = size(v) - 1 - i; auto &amp;bf = m_boundary_filters[k]; Real d2v = 0; for (size_t j = 0; j &lt; bf.size(); ++j) { d2v += bf[j] * v[size(v) - 1 - j]; } w[i] = d2v / (m_dt*m_dt); } } return w; } private: std::vector&lt;Real&gt; m_f; std::vector&lt;std::vector&lt;Real&gt;&gt; m_boundary_filters; Real m_dt; }; } // namespaces #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:17:00.483", "Id": "411413", "Score": "0", "body": "The tests fail to compile with this code; did you accidentally link to the wrong version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T18:25:59.943", "Id": "411450", "Score": "0", "body": "@TobySpeight: I received code review on github from the maintainers of boost.math, and failed to keep this question in sync with the resulting code changes. Fortunately, your comments were almost completely orthogonal to the comments made by the maintainers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T09:40:20.870", "Id": "464886", "Score": "0", "body": "I have a question: was this code actually used in LIGO signal analysis which entered official LIGO publications? I am wandering whether one can cite LIGO analysis as an example of use of Lanczos(-like) derivatives." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T13:41:07.587", "Id": "464907", "Score": "0", "body": "No it was not used in LIGO signal analysis. I used the LIGO signal because the LIGO people made their data easily available." } ]
[ { "body": "<p>That's a pretty dramatic demonstration image - there's no doubt that the function is worth having!</p>\n\n<p>I make no claim to understand the mathematics, but I'll happily look over the C++ code.</p>\n\n<hr>\n\n<p>I'll start with the includes, as we seem to be missing some that are required:</p>\n\n<pre><code>#include &lt;limits&gt;\n#include &lt;cmath&gt;\n#include &lt;cstdint&gt;\n</code></pre>\n\n<p>We have a portability problem, as we've consistently omitted the namespace of <code>std::size_t</code> and <code>std::int64_t</code> (BTW, consider <code>std::int_fast64_t</code> as a better alternative to the latter, unless we need <em>exactly</em> 64 bits).</p>\n\n<hr>\n\n<p>Now, let's move on to <code>class discrete_legendre</code>.</p>\n\n<p>It's usually a bad idea to have a class that is constructed into an unusable state, requiring a second \"initialization\" phase before it's valid. Sometimes it's unavoidable, but that's not the case here. Simply pass the initialization parameters to the constructor, and omit the <code>initialize_recursion()</code> member (simply create a new instance, as that's no more work than resetting all the members).</p>\n\n<pre><code> class discrete_legendre {\n public:\n discrete_legendre(std::size_t n, Real x)\n : m_n{n},\n m_r{2},\n m_x{x},\n m_qrm2{1},\n m_qrm1{x},\n m_qrm2p{0},\n m_qrm1p{1},\n m_qrm2pp{0},\n m_qrm1pp{0}\n {\n // The integer n indexes a family of discrete Legendre\n // polynomials indexed by k &lt;= 2*n\n }\n</code></pre>\n\n<p>Here's an example of where we replace re-initialisation with re-construction:</p>\n\n<pre><code>template &lt;class Real&gt;\nstd::vector&lt;Real&gt; interior_filter(std::size_t n, std::size_t p) {\n // We could make the filter length n, as f[0] = 0,\n // but that'd make the indexing awkward when applying the filter.\n std::vector&lt;Real&gt; f(n + 1, 0);\n auto dlp = discrete_legendre&lt;Real&gt;(n, 0.0);\n std::vector&lt;Real&gt; coeffs(p+1, std::numeric_limits&lt;Real&gt;::quiet_NaN());\n coeffs[1] = 1/dlp.norm_sq(1);\n for (std::size_t l = 3; l &lt; p + 1; l += 2)\n {\n dlp.next_prime();\n coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l);\n }\n\n for (std::size_t j = 1; j &lt; f.size(); ++j)\n {\n Real arg = Real(j) / Real(n);\n dlp = {n, arg};\n f[j] = coeffs[1]*arg;\n for (std::size_t l = 3; l &lt;= p; l += 2)\n {\n dlp.next();\n f[j] += coeffs[l]*dlp.next();\n }\n f[j] /= (n * n);\n }\n return f;\n}\n</code></pre>\n\n<p>Minor issues: <code>norm_sq()</code> can be declared <code>const</code>.</p>\n\n<hr>\n\n<p>The filter functions are next.</p>\n\n<p>Please don't use <code>l</code> as a variable name; it looks too much like the digit <code>1</code>!</p>\n\n<p>For indexing vectors, a good practice would be to use <code>std::vector&lt;&gt;::size_type</code> rather than assuming that it's <code>std::size_t</code>. But don't get hung up on that.</p>\n\n<p>All three filters have a common step, which should be factored out for maintainability:</p>\n\n<blockquote>\n<pre><code>for (std::size_t j = 1; j &lt; f.size(); ++j)\n{\n Real arg = Real(j) / Real(n);\n dlp = {n, arg};\n f[j] = coeffs[1]*arg;\n for (std::size_t l = 3; l &lt;= p; l += 2)\n {\n dlp.next();\n f[j] += coeffs[l]*dlp.next();\n }\n f[j] /= (n * n);\n}\nreturn f;\n</code></pre>\n</blockquote>\n\n<p>We could consider a Strategy pattern here, but I suspect that would lead to bigger and less clear code.</p>\n\n<hr>\n\n<p>Leaving the <code>detail</code> namespace, we reach the main class, <code>discrete_lanczos_derivative</code>.</p>\n\n<blockquote>\n<pre><code> static_assert(!std::is_integral_v&lt;Real&gt;, \"Spacing must be a floating point type.\");\n</code></pre>\n</blockquote>\n\n<p>Why <code>!std::is_integral_v</code> rather than the more obvious <code>std::is_floating_point_v</code>? Are we expecting this to work for <code>std::complex&lt;&gt;</code> values, perhaps?</p>\n\n<p>Given that almost every method switches on <code>order</code>, I think that specializations or separate classes for first-order and second-order are likely to be clearer. We could put the common parts in a base class.</p>\n\n<blockquote>\n<pre><code> BOOST_ASSERT_MSG(size(v) &gt;= m_boundary_filters[0].size(),\n \"Vector must be at least as long as the filter length\");\n</code></pre>\n</blockquote>\n\n<p><code>v</code> is user-supplied, so an assert is the wrong kind of check here if it terminates the program. I think it's better to throw a <code>std::out_of_range</code> or similar instead.</p>\n\n<blockquote>\n<pre><code> BOOST_ASSERT_MSG(false, \"Out of bounds access in Lanczos derivative\");\n return std::numeric_limits&lt;Real&gt;::quiet_NaN();\n</code></pre>\n</blockquote>\n\n<p>Perhaps a signalling NaN would be more appropriate here? Although, as I understand it, this seems to be reached only if we're instantiated for an out-of-range <code>order</code>.</p>\n\n<blockquote>\n<pre><code>template&lt;class RandomAccessContainer&gt;\nRandomAccessContainer operator()(RandomAccessContainer const &amp; v) const\n</code></pre>\n</blockquote>\n\n<p>This seems to be a duplicate of <code>operator()(RandomAccessContainer const &amp; v, std::size_t i)</code>, with <code>i</code> set to <code>size(v)</code>. So implement it by delegating:</p>\n\n<pre><code>template&lt;class RandomAccessContainer&gt;\nRandomAccessContainer operator()(RandomAccessContainer const &amp; v) const\n{\n using std::size;\n return operator()(v, size(v));\n}\n\ntemplate&lt;class RandomAccessContainer&gt;\nReal operator()(RandomAccessContainer const &amp; v,\n typename RandomAccessContainer::size_type i) const\n</code></pre>\n\n<p>There's not necessarily a performance penalty for this - the compiler may choose to inline it, or (better) arrange the functions so that one is a prefix of the other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T22:21:38.550", "Id": "411468", "Score": "0", "body": "I have implemented basically every suggestion, except a couple: The variable `l` matches the notation in the reference; is that worth the readability? Maybe, maybe not, but it's consistent with how I've done other implementations. `std::is_integral_v` is used because multiprecision and interval arithmetic types don't pass `std::is_float_point_v`, and I still wanted to make sure that the imaging procssing guys don't use this unless they know what they're doing (I haven't tested any integer types; doubt it works.) All other mistakes have been fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T22:23:03.470", "Id": "411469", "Score": "0", "body": "I know that you're not supposed to say thanks in the comments-which seems like reasonable guidance for other stack exchanges-but not for this one. That was a huge effort on your part which considerably improved my code. Thanks is absolutely in order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T09:29:19.993", "Id": "411635", "Score": "0", "body": "Thanks for your explanation of `!std::is_integral_v` against other choices - it may be worth adding a comment there so a future maintainer doesn't attempt to \"correct\" it (I haven't inspected the unit tests closely, but I expect such a change would break some). As for the variable `l`, that's one of those general guidelines - you understand the reason for the advice, and then you can make a considered judgement whether it's clearer to match the reference or to rename the variable. A judgement call, indeed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:59:23.327", "Id": "212703", "ParentId": "210762", "Score": "3" } } ]
{ "AcceptedAnswerId": "212703", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T20:07:40.183", "Id": "210762", "Score": "9", "Tags": [ "c++", "c++17", "numerical-methods", "signal-processing" ], "Title": "Discrete Lanczos Derivatives" }
210762
<p>I was looking to get some reviews of my code, so I can improve my writing. Functionally it works the exact way I want it to based on my patch notes .md file. I'm open to all suggestions for improving the code, especially in making it more performant.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> state = { open: false, notes: null } componentDidMount() { this.getData(); } getData = () =&gt; { axios.get(patchnotes_md_urlpath) .then((response) =&gt; { const updates = response.data.replace(/(\r\n|\n|\r)/g, '').split('### '); let i; let j; let notes = []; for ( i = 1; i &lt; updates.length; i++ ) { let update = updates[i].split('* '); const newObj = Object.assign({}); newObj.version = update[0]; let list = []; for ( j = 1; j &lt; update.length; j++ ) { list.push(update[j]); } newObj.notes = list; notes.push(newObj); } this.setState({ notes }); }).catch((error) =&gt; { console.error(error); }); }</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>### 0.1.2 * Patch notes now implemented when the modal starts. * Added top lists for organizations ### 0.0.1 * Patch Notes Added * Modal to include Patch Notes</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T22:00:37.997", "Id": "407428", "Score": "0", "body": "Could you edit with an example markdown file you would be using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T01:25:21.370", "Id": "407454", "Score": "0", "body": "Added an example .MD file." } ]
[ { "body": "<p>You got the first step right by removing every white space and line breaks from your string. Next you will have to remove the first occurence of <code>###</code> by splitting your string and then <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"nofollow noreferrer\">slicing</a> out the first element.</p>\n\n<p>When done, you will have to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>map</code></a> the result of your split. Map will create a new array the exact same size of your input and apply the same function on every attribute of it.</p>\n\n<p>You will then have to split each update by the <code>*</code>. When done, you can get the first value of your array with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift\" rel=\"nofollow noreferrer\"><code>shift</code></a>. This function will give out the first element of your array and delete it from the array, only leaving the notes that are going to be put in the <code>notes</code> variable :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = '### 0.1.2\\n* Patch notes now implemented when the modal starts.\\n* Added top lists for organizations\\n### 0.0.1\\n* Patch Notes Added\\n* Modal to include Patch Notes'\n\nconst updates = data.replace(/(\\r\\n|\\n|\\r)/g, '').split('### ').slice(1).map(update =&gt; {\n updateData = update.split('* ')\n return {\n version: updateData.shift(),\n notes: updateData\n }\n})\n\nconsole.log(updates)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You can then put this function in the <code>.then</code> of your axios call</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:51:38.990", "Id": "211063", "ParentId": "210763", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T20:31:33.850", "Id": "210763", "Score": "2", "Tags": [ "object-oriented", "array", "react.js", "jsx" ], "Title": "Create an Array of Objects for Patch Notes in React" }
210763
<p>While I was working on a personal project, I found I needed to exclude certain characters in a regex range. So I thought, why not implement a custom range exclusion check for greater efficiency, it'll only take 5 lines or so. 60+ lines later, I produced this:</p> <p><code>regex_supplement.py</code>:</p> <pre><code>"""Supplementary regex modifying methods.""" from itertools import tee def pairwise(iterable): """s -&gt; (s0,s1), (s1,s2), (s2, s3), ... From the itertools recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) def _offset_byte_char(char, offset): """Offset a single byte char""" return (ord(char) + offset).to_bytes(1, byteorder='big') def escape_byte_in_character_class(char): """Escapes characters as necessary within the character class.""" return b'\\' + char if char in b'-]^' else char def byte_range(startchar, endchar, excluded): """Returns a pattern matching characters in the range startchar-endchar. Characters in excluded are excluded from the range. """ excluded = sorted(char for char in excluded if startchar &lt;= char &lt;= endchar) char_ranges = [] if len(excluded) &gt;= 1: first_exclude = excluded[0] if startchar != first_exclude: # Another possibility = + 1 char_ranges.append( (startchar, _offset_byte_char(first_exclude, -1)) ) for start, end in pairwise(excluded): # Adjacent or equal if ord(end) - 1 &lt;= ord(start): continue char_ranges.append( (_offset_byte_char(start, 1), _offset_byte_char(end, -1)) ) last_exclude = excluded[-1] if endchar != last_exclude: char_ranges.append( (_offset_byte_char(last_exclude, 1), endchar) ) else: char_ranges = [(startchar, endchar)] char_output = b'' escape = escape_byte_in_character_class for char_range in char_ranges: # Doesn't minimize all '-', but that quickly gets complicated. # (Whether '-' needs to be escaped within a regex range is context dependent.) # '^' has even more potential easy optimization. start, end = char_range if start == end: char_output += escape(start) elif ord(start) == ord(end) - 1: char_output += escape(start) + escape(end) else: char_output += escape(start) + b'-' + escape(end) return b'[' + char_output + b']' </code></pre> <p><code>test_regex_supplement.py</code>:</p> <pre><code>"""Regex supplement tests""" import regex_supplement as re_supp def test_byte_regex_range_empty(): """Test that empty exclusions do not affect the range""" assert re_supp.byte_range(b'a', b'c', []) == b'[a-c]' def test_byte_regex_range_exclusion_outside(): """An exclusion outside of the regex range should have no effect.""" assert re_supp.byte_range(b'a', b'c', [b'e']) == b'[a-c]' offset = re_supp._offset_byte_char def compare_escaped_within_range(char): """Test that the character is escaped at the beginning of a range.""" end = offset(char, 3) assert re_supp.byte_range(char, end, [end]) == b'[\\' + char + b'-' + offset(end, -1) + b']' def test_byte_regex_range_escaped_rbrac(): """Test that ']' is escaped""" compare_escaped_within_range(b']') def test_byte_regex_range_escaped_hyphen(): """Test that '-' is escaped""" compare_escaped_within_range(b'-') def test_byte_regex_range_escaped_caret(): """Test that '^' is escaped""" compare_escaped_within_range(b'^') def test_byte_regex_range_standard_1(): """Test that a standard range behaves as expected""" assert re_supp.byte_range(b'a', b'g', [b'd']) == b'[a-ce-g]' def test_byte_regex_range_standard_2(): """Test that a standard range with multiple exclusions behaves as expected""" assert re_supp.byte_range(b'a', b'k', [b'd', b'h']) == b'[a-ce-gi-k]' def test_byte_regex_range_optimized_1(): """Test that ranges of 1 char are optimized to single characters.""" assert re_supp.byte_range(b'a', b'c', [b'b']) == b'[ac]' def test_byte_regex_range_optimized_2(): """Test that multiple ranges of 1 chars are optimized to single characters.""" assert re_supp.byte_range(b'a', b'e', [b'b', b'd']) == b'[ace]' </code></pre> <p>This is only implemented for bytestrings, because that's what I needed for my project. I actually learned that Python regular expressions can handle bytestrings during this project. The tests are intended to be run by pytest. I was originally considering adding in an optimization for single character ranges, but I decided not to because it would lead to more complicated escape-handling code (and the possibility for subtle bugs like double-escaping <code>]</code>), and it wasn't needed for my purposes.</p> <p>I'm mostly concerned with efficiency (mostly of the resultant regex, but also of the program) and accuracy-checking, but stylistic and readability improvements are also appreciated.</p> <p>Also, in hindsight, I might have considered implementing a lookahead with an exclusion character check preceding the range, but my current approach does have the advantage of discarding excluded characters that are outside of the range, and requiring less escaping.</p>
[]
[ { "body": "<pre><code>offset = re_supp._offset_byte_char\n\ndef compare_escaped_within_range(char):\n \"\"\"Test that the character is escaped at the beginning of a range.\"\"\"\n end = offset(char, 3)\n assert re_supp.byte_range(char, end, [end]) == b'[\\\\' + char + b'-' + offset(end, -1) + b']'\n</code></pre>\n\n<p>Two weird things going on here. First, your unit test depends on an internal implementation detail of <code>re_supp</code> (namely the <code>_offset_byte_char</code> method). Second, you're actually storing that method in a <em>global variable</em>, which makes your test not standalone. You couldn't extract just the <code>compare_escaped_within_range</code> test into a different test file, for example, unless you brought the global <code>offset</code> along with it. It would at least be more maintainable to say</p>\n\n<pre><code>def compare_escaped_within_range(char):\n \"\"\"Test that the character is escaped at the beginning of a range.\"\"\"\n offset = re_supp._offset_byte_char\n end = offset(char, 3)\n assert re_supp.byte_range(char, end, [end]) == b'[\\\\' + char + b'-' + offset(end, -1) + b']'\n</code></pre>\n\n<p>But it would be even better not to depend on that detail at all! Either make <code>_offset_byte_char</code> a public member of the API (lose the underscore), or just reimplement it yourself where you need it.</p>\n\n<p>When you reimplement it, consider that Python offers the <code>chr</code> builtin to do exactly what you're currently doing with all that <code>byteorder='big'</code> nonsense on ints. Although I guess Python3 does force you to know about <code>latin_1</code> encoding:</p>\n\n<pre><code>offset = lambda x, y: chr(ord(x) + y).encode('latin_1')\n</code></pre>\n\n<hr>\n\n<p>IIUC, your public API really just consists of the function <code>byte_range(b, e, xs)</code>, where <code>b</code> and <code>e</code> are single bytes and <code>xs</code> is an iterable of bytes — which generates a regex character class matching any of the bytes in <code>b</code> to <code>e</code> inclusive, but excluding all of the bytes in <code>xs</code>.</p>\n\n<p>In other words, it produces a regex which is the moral equivalent of <code>(?=[b-e])(?![xs]).</code>, or more succinctly <code>(?![xs])[b-e]</code>.</p>\n\n<p>I guess you knew this, but it does feel like your 60-line thing is a bit overengineered. ;)</p>\n\n<hr>\n\n<p>Personally I would write <code>ch</code> everywhere you wrote <code>char</code>, but that's probably partly due to my being primarily a C and C++ programmer. ;) <code>ch</code> would still be shorter and arguably harder to confuse with <code>chr</code>, though...</p>\n\n<hr>\n\n<p>Again on the testing side: your <code>compare_escaped_within_range</code> seems overdetermined and overcomplicated. If I were writing tests for your API, I would write one like this:</p>\n\n<pre><code>def test_inputs(b, e, xs):\n needle = re_supp.byte_range(b, e, xs)\n for i in range(256):\n haystack = chr(i).encode('latin_1')\n expected = (ord(b) &lt;= i &lt;= ord(e)) and (haystack not in xs)\n actual = bool(re.match(needle, haystack))\n assert actual == expected\n</code></pre>\n\n<p>And then I'd make sure all of my tests <em>at least</em> verified that <code>test_inputs(b, e, xs)</code> passed for their inputs. Even if they went on to verify other properties.</p>\n\n<pre><code>def test_byte_regex_range_escaped_caret():\n \"\"\"Test that '^' is escaped\"\"\"\n test_inputs(b'^', b'a', [b'a'])\n assert re_supp.byte_range(b'^', b'a', [b'a']) == b'[\\\\^-`]') # should we even verify this, or are we micromanaging?\n</code></pre>\n\n<p>Incidentally, you got very lucky that out of <code>]</code>, <code>^</code>, and <code>-</code>, no two of them are exactly 2 positions apart in the ASCII table! Did you know that? Do you expect your maintainer to know that <code>3</code> is a magic number in this respect — or should you maybe document it for posterity?</p>\n\n<hr>\n\n<p>I ran my <code>test_inputs</code> on some random data and discovered some bugs in your code. Most blatantly, you forgot that <code>\\</code> needs to be escaped. So <code>test_inputs(b'\\\\', b'A', [])</code> fails.</p>\n\n<p>Fix the trivial bug by adding two characters in <code>escape_byte_in_character_class</code>. Now add a regression test: <code>compare_escaped_within_range(b'\\\\')</code>. The test still fails! Why? :)</p>\n\n<p>And you don't handle the completely empty case: <code>test_inputs(b'A', b'A', [b'A'])</code> fails.</p>\n\n<p>And you don't handle <code>test_inputs(b'B', b'A', [])</code> either, but that's more of an input validation issue, which is an issue of taste. Maybe you want to return <code>b'(?!.).'</code> in that case; maybe you want to assert-fail; or maybe you're happy just saying \"don't do that.\"</p>\n\n<p>The moral of the story is that you should always write a test harness that permits fuzzing! It's never wasted effort. ...Well, it's never <em>effort that fails to find bugs,</em> anyway. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T13:38:19.863", "Id": "407511", "Score": "0", "body": "Very useful answer all around! Regarding switching to `chr().encode('latin1')`, I feel like that's relying on an implementation detail of bytestrings that `latin1` happens to map to bytestrings perfectly. I guess that's unlikely to change, but I still feel it makes the code less clear. I think Python just has a rough edge by always requiring `byteorder` in `to_bytes`. For 1 byte conversions, there are no *bytes* to order, so it doesn't have relevance! And yes, my solution is admittedly over-engineered, but it does have *some* benefits, which I mentioned in the last paragraph of my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:09:49.480", "Id": "407515", "Score": "1", "body": "I could have also done `bytes([i])` for the int to bytestring conversion, which might be the most succinct and best solution. I'm not arguing that what I've done with `offset` is good style (it's clearly bad style), but I'm not certain what you mean when say \"You couldn't extract just the `compare_escaped_within_range` test into a different test file, for example, unless you brought the global `offset` along with it.\" If you extracted `compare_escaped_within_range`, it would keep the reference to the global `offset` within the original module, unless I misunderstand what you mean by \"extract\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T05:12:27.647", "Id": "210789", "ParentId": "210765", "Score": "4" } } ]
{ "AcceptedAnswerId": "210789", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T20:46:11.313", "Id": "210765", "Score": "5", "Tags": [ "python", "python-3.x", "regex" ], "Title": "Regex character class range generator with certain characters excluded" }
210765
<p>Simple truncating method for characters, words, and sentences for a personal utility library I've been working on.</p> <p>Improvements &amp; criticism welcomed! Especially around default param usage, as I've not utilized it much to date.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const truncate = (( value = '', int = 0, elipsis = '\u2026', /* ... */ prune = (val, num, at) =&gt; val.split(at).splice(0, num).join(at) ) =&gt; { const sentences = (val = value, num = int, end = elipsis) =&gt; prune(val, '.', num) + end; const words = (val = value, num = int, end = elipsis) =&gt; prune(val, ' ', num) + end; const characters = (val = value, num = int, end = elipsis) =&gt; val.substring(0, num) + end; return {sentences, words, characters}; })(); console.clear(); console.log([ truncate.sentences("This is a sentence. There are many like it but you won't see the 2nd one", 1, '.'), truncate.words("These are words but you won't see what's after this because it'll be hidden", 10), truncate.characters("This won't exceed 31 characters so we cutting off the ending", 31, '!') ]);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T21:42:54.813", "Id": "407426", "Score": "1", "body": "What does `10` at `truncate.words(\"These are words but you won't see what's after this because it'll be hidden\", 10)` reflect at output? Is `[\n \".\",\n \"…\",\n \"This won't exceed 31 characters!\"\n]` the expected result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:30:48.263", "Id": "407521", "Score": "0", "body": "Looks like i messed up a few things when I renamed the variables and didn't test: https://jsfiddle.net/darcher/j36mzp4w/ <-- original" } ]
[ { "body": "<p>The parameters of <code>sentences</code> and <code>words</code> appear to be out of order when passed to <code>prune()</code>. Not sure why the parameters passed to <code>prune</code> are hard-coded at the example, though still passed to <code>prune()</code>. Since <code>words</code> does not pass a parameter for <code>at</code>, <code>10</code> is used, which is not the expected result, though can be remedied by defining the parameter <code>at</code> at <code>words</code> and <code>sentences</code> functions, given that each function call expects all three parameters, and <code>at</code> is not defined at any of the functions at the code at the question; instead <code>num</code> is set to <code>int</code>. </p>\n\n<p>Adjusted body of <code>prune</code> to include an immediately invoked arrow function to handle the resulting array of <code>.split()</code> where delimiter character <code>!</code> is not contained in string by checking if the element at index <code>0</code> of array is equal to <code>val</code>, if true spread <code>val</code> to array else use existing array to chain <code>.splice()</code> to, then concatenate an empty string or <code>at</code> following <code>.join()</code> call. At which point the same function can be substituted for <code>sentences</code>, <code>words</code> and <code>characters</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const truncate = ((\n value = '',\n int = 0,\n elipsis = '\\u2026', /* ... */\n prune = (val, at, num) =&gt; \n ((s, k = s[0] === val) =&gt; \n `${(k ? [...val] : s)\n .splice(0, num)\n .join(k ? '' : at)}${k ? at : ''}`)\n (val.split(at))\n) =&gt; {\n const sentences = (val = value, at, num = int, end = elipsis) =&gt; prune(val, at, num) + end;\n const words = (val = value, at, num = int, end = elipsis) =&gt; prune(val, at, num) + end;\n const characters = (val = value, at, num = int, end = elipsis) =&gt; prune(val, at, num) + end;\n return {sentences, words, characters};\n})();\n\nconsole.clear();\nconsole.log([\n truncate.sentences(\"This is a sentence. There are many like it but you won't see the 2nd one\", '.', 1),\n truncate.words(\"These are words but you won't see what's after this because it'll be hidden\", ' ', 10),\n truncate.characters(\"This won't exceed 31 characters so we cutting off the ending\", '!', 31)\n]);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Alternatively, though not consistent with the <code>sentences</code>, <code>words</code> can be composed with <code>at</code> being set as a default parameter</p>\n\n<pre><code>const words = ({val = value, at = ' ', num = int, end = elipsis} = {}) =&gt; prune(val, at, num) + end;\n</code></pre>\n\n<p>which would be called with</p>\n\n<pre><code>truncate.words({val: \"These are words but you won't see what's after this because it'll be hidden\", num: 10})\n</code></pre>\n\n<p>providing the ability to call the function without explicitly setting and passing <code>at</code> as a parameter.</p>\n\n<p>Substituting a single function for <code>sentences</code>, <code>words</code> and <code>characters</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const truncate = (\n value = '',\n at = '',\n num = 0,\n elipsis = '\\u2026', /* ... */\n) =&gt; ((val, k = val[0] === value) =&gt; \n `${(k ? [...value] : val).splice(0, num)\n .join(k ? '' : at)}${k ? at : ''}${elipsis}`)\n (value.split(at));\n\nconsole.clear();\nconsole.log([\n truncate(\"This is a sentence. There are many like it but you won't see the 2nd one\", '.', 1),\n truncate(\"These are words but you won't see what's after this because it'll be hidden\", ' ', 10),\n truncate(\"This won't exceed 31 characters so we cutting off the ending\", '!', 31)\n]);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:26:09.680", "Id": "407520", "Score": "0", "body": "Really good feedback, I can certainly see my shortcomings and like your use of template literals here. I can certainly see the benefit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T22:49:17.300", "Id": "210771", "ParentId": "210767", "Score": "1" } }, { "body": "<h1>Review</h1>\n<p>There was a slight bug in your code. The last two arguments for <code>prune</code> were in the wrong order.</p>\n<p>You have a lot of duplicated code. Good code is DRY (Don't Repeat Yourself)</p>\n<p>The code is clean and style is consistent.</p>\n<h2>Some points</h2>\n<ul>\n<li><p>I can not see the point of arguments as part of the singleton pattern. Not that there's is anything wrong with it, it just seems to add code for no benefit.</p>\n</li>\n<li><p>Default parameters should be set at the bottom of the call stack (the function where the arguments are used). This means that you don't need to repeat the defaults each time you pass on arguments and lets you use a shorter syntax.</p>\n</li>\n<li><p>You can reduce the source size by moving the three truncate functions into the returned singleton. No need to type their names twice.</p>\n</li>\n<li><p>Naming is somewhat poor,</p>\n<ul>\n<li>Don't name variables by their type. <code>int</code> ??? I assume you mean its an integer, but that gives no information as to what it does. Maybe <code>count</code>. Don't name variables by their type, that is inferred.</li>\n<li><code>num</code> ??? LOL again, you are naming for what they are. Name for what the represent. Maybe <code>count</code>.</li>\n<li><code>value</code> Is string or string like, but <code>value</code> implies a quantitative like property. A clearer name could be <code>str</code> or <code>string</code>.</li>\n<li><code>truncate</code> truncates but internally you <code>prune</code> Be consistent when naming different parts of your code. <code>prune</code> may be better as <code>truncate</code>.</li>\n</ul>\n</li>\n</ul>\n<h2>Design</h2>\n<p>You are mixing function roles. Eg <code>truncate.words</code> calls <code>prune</code> and then appends <code>end</code>. Adding <code>end</code> is better done in <code>prune</code>. When you find yourself repeating code ask yourself why? Am I mixing roles?</p>\n<p>Singletons provide great encapsulation, and I think are one of the best ways to maintain a trusted state. However that trust is only as strong as the weakest link. You can add one more level of encapsulation by freezing the singleton you return using <code>Object.freeze</code>, it also gives a small increase in performance.</p>\n<h2>Rewrite</h2>\n<p>Less code means less room for bugs. This is part of the DRY philosophy. The aim of the rewrite is to reduce repeated source code.</p>\n<p>The first version is not as DRY as it could be (the repeated <code>(...args) =&gt; truncate(&quot;.&quot;, ...args)</code>) but there is a point where striving to DRY out code makes it more obscure.</p>\n<p>The first example is preferable, the second example is just to demonstrate how code can become less clears as it is compressed.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const truncate = (() =&gt; {\n const truncate = (at, str = \"\", count = 1, end = \"\\u2026\") =&gt;\n (at === \"\" ? str.substring(0, count) : str.split(at).splice(0, count).join(at)) + end;\n return Object.freeze({\n sentences: (...args) =&gt; truncate(\".\", ...args),\n words: (...args) =&gt; truncate(\" \", ...args),\n characters: (...args) =&gt; truncate(\"\", ...args),\n });\n})();\n\n\n\nconst l=d=&gt;Log.appendChild(Object.assign(document.createElement(\"div\"),{textContent: d}));\nl(truncate.sentences(\"This is a sentence. There are many like it\", 1, \".\"))\nl(truncate.words(\"These are words but you won't see what's after this foo\", 10))\nl(truncate.characters(\"This won't exceed 31 characters so \", 31, \"!\"))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;code id=\"Log\"&gt;&lt;/code&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This example is on the border of too DRY</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const truncate = (() =&gt; {\n const API = {}, types = [[\"sentences\", \".\"], [\"words\", \" \"], [\"characters\", \"\"]];\n const trunc = (at, str = \"\", count = 1, end = \"\\u2026\") =&gt;\n (at === \"\" ? str.substring(0, count) : str.split(at).splice(0, count).join(at)) + end;\n types.forEach(type =&gt; API[type[0]] = (...args) =&gt; trunc(type[1], ...args));\n return Object.freeze(API);\n})();\n\n\nconst l=d=&gt;Log.appendChild(Object.assign(document.createElement(\"div\"),{textContent: d}));\nl(truncate.sentences(\"This is a sentence. There are many like it\", 1, \".\"))\nl(truncate.words(\"These are words but you won't see what's after this foo\", 10))\nl(truncate.characters(\"This won't exceed 31 characters so \", 31, \"!\"))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;code id=\"Log\"&gt;&lt;/code&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:23:42.100", "Id": "407519", "Score": "0", "body": "This is why I love peer review, really helps to get different perspectives and in this case, greatly elevated information. I really appreciate this feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T04:10:01.797", "Id": "210786", "ParentId": "210767", "Score": "1" } } ]
{ "AcceptedAnswerId": "210786", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T21:01:51.780", "Id": "210767", "Score": "1", "Tags": [ "javascript", "strings", "formatting" ], "Title": "Simple ES6 Truncate method for character, word, and sentence limits" }
210767
<p>I am trying to do an auxilliary function to print pairs of value-uncertainty in a formal way, given their name, value and uncertainty.</p> <p>The "technical" agreement is that "uncertainty rules", meaning that the significant digits of a pair to be printed are given by the decimal size of the uncertainty value. For example: real values (123.456789, 0.012345) should be converted to a representation of (123.456, 0.012), and real values (123456.789, 123.45) should be converted to a representation of (123450, 120).</p> <p>Additional rules:</p> <ul> <li>If an uncertainty is greater than 10^3 or smaller than 10^-3, then exponent notation will be used with 1 decimal digit for the <em>value</em> (ideally, the pair should share the exponent factor which would be given by the <em>value</em> exponent factor, but I don't know how to do that yet - I marked it as <em>to-do</em> in the code). For example, (6.31e+03, 0.31e+03) would be the ideal, now I am getting (6.310000e+03, 3.1000000e+02).</li> <li>Don't print decimal point if the uncertainty value is greater than 10.</li> </ul> <p>Some options I try to give:</p> <p>Whitespace formatting:</p> <pre><code>'{:{ws}{nfmt}}'.format(ws = ' ' if ws in [True, ' '] else '', nfmt = ...) # nfmt stands for number formatting, e.g. .1f, etc. see code. </code></pre> <p>Representation formatting: useful for latex, unicode printing, simple/ascii or shorthand notation (I don't know how to implement exponent notation in short notation representation, that's why I refer to making a custom repr method in the code).</p> <ul> <li>Simple/ascii: <code>0.210+/-0.011</code></li> <li>Short: <code>0.210(11) # uncertainty takes integer form. I don't know how to do this one</code></li> <li>Short-composite: <code>0.210(0.011)</code></li> <li>Fancy/utf-8: <code>0.210 ± 0.011</code></li> <li>Latex: <code>$0.210 \pm 0.011$</code></li> </ul> <p>Note that the exponent factor should be printed outside: if it was (0.000210, 0.000011) (to comply with condition of u &lt;= 10^-3), it should print <code>(2.10 ± 0.11)e-04</code> and variants or <code>210(11)e-06</code> for short notation. I don't know how to simply do neither of them either :(.</p> <p>Edit: the short notation is more complicated than I thought. I added what it should look like on short+exponent notation. Also added exponent condition for small numbers.</p> <p>Edit #2: I'm seeing a lot of bad style here. Technically, exponent notation should be also printed outside for all the representations. That's another reason to do a specific formal <code>repr</code> function for pairs. Now I'm realizing that this probably isn't a good post. If somebody tells me to, I'll delete the post and redo it after I've given it a better try. Only issue is I should probably be studying for finals :p</p> <p>Here is the full code:</p> <pre><code>def _print_fres(names, vals, uncs, sigds = 2, rfmt = 'pm', ws = False): # sigds are the significance digits # inputs are lists of names, values and uncertainties respectively try: if all([str(u).lower() not in 'inf' for u in uncs]): sigs = [ (re.search('[1-9]', str(u)).start()-2 \ if re.match('0\.', str(u)) \ else -re.search('\.', str(float(u))).start())+sigds \ for u in uncs ] # significant digits rule in uncertainty else: print('Warning: infinity in uncertainty values') sigs = [sigds] * len(uncs) except TypeError: #NaN or None raise TypeError('Error: odd uncertainty values') rfmt = rfmt.lower() # this can be done better/prettier I think if rfmt in ['fancy', 'pms']: # pms stands for pmsign res_str = '{{0}} = {{1:{ws}{nfmt}}} ± {{2:{ws}{nfmt}}}' elif rfmt in ['basic', 'pm', 'ascii']: res_str = '{{0}} = {{1:{ws}{nfmt}}}+/-{{2:{ws}{nfmt}}}' elif rfmt in ['tex', 'latex']: res_str = '${{0}} = {{1:{ws}{nfmt}}} \\pm {{2:{ws}{nfmt}}}$' elif rfmt in ['s1', 'short1']: res_str = '{{0}} = {{1:{ws}{nfmt}}} ± {{2:{ws}{nfmt}}}' # not yet supported. to do: shorthand notation elif rfmt in ['s2', 'short2']: res_str = '{{0}} = {{1:{ws}{nfmt}}}({{2:{ws}{nfmt}}})' else: raise KeyError('rfmt value is invalid') for i in range(len(vals)): try: print((res_str.format( nfmt = '1e' if uncs[i] &gt;= 1000 or uncs[i] &lt;= 0.001 \ # 1 decimal exponent notation for big/small numbers else ( 'd' if sigs[i] &lt;= 0 \ # integer if uncertainty &gt;= 10 else '.{}f'.format(sigs[i])), ws = ' ' if ws in [True, ' '] else '' ) ).format( names[i], round(vals[i], sigs[i]), round(uncs[i], sigs[i]) # round to allow non-decimal significances ) ) except (TypeError, ValueError, OverflowError) as e: print('{} value is invalid'.format(uncs[i])) print(e) continue # to do: a repr method to get numbers well represented # instead of this whole mess </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T08:22:00.810", "Id": "407483", "Score": "0", "body": "What does \"(123.456789, 0.012345) should be a representation of (123.456, 0.012)\" mean? Is either tuple a decimal with its uncertainty? If so, which one, and what is the other tuple?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:05:22.913", "Id": "407547", "Score": "0", "body": "@l0b0 sorry, I meant \"converted to representation of\"; edited. Either way, both of them are pairs of numbers, not necessarily tuples. The program takes a list of measurements a list of their uncertainties, that's why the inputs are lists instead of single elements. Also, the function is was originally intended to be private since it's a minor part of a much bigger function/algorithm. I'm working on a solution via class, however. I'll probably post it in another post since it's completely different? I don't know, I'm new to this site and haven't really taken the time to read the whole faq." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Rather than explaining parameters in comments, simply name the variables so that the comments become unnecessary. A signature of <code>def format_uncertain_values(names, values, uncertainties, significant_digits=2, format='pm', word_separated=False)</code> should do it.</li>\n<li>There are three distinct sections to your method, which should probably be separate methods.</li>\n<li>This code is a great candidate for <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>. Declare types using for example <code>names: typing.List[str]</code> and validate them using the <code>mypy</code> command line tool (be sure to look into the MyPy options, because the default configuration is very lax). This will highlight at least one implementation issue: <code>ws</code> is treated as <em>either</em> a boolean or a string, but\n\n<ul>\n<li>boolean arguments are a code smell (<a href=\"https://softwareengineering.stackexchange.com/q/147977/13162\">1</a>, <a href=\"https://softwareengineering.stackexchange.com/q/323554/13162\">2</a>) and</li>\n<li>making it a string (possibly defaulting it to the empty string) would remove the need for the <code>ws = ' ' if …</code> line.</li>\n</ul></li>\n<li>The code would be much simpler if it simply took a <em>single</em> name, value and uncertainty. Then the user\n\n<ul>\n<li>avoids having to wrap everything in lists to format a single variable and</li>\n<li>can still trivially loop over their values to print all of them.</li>\n</ul></li>\n<li>Send the code through at least one linter such as <code>flake8</code> or <code>pycodestyle</code> until it passes all the tests. Then your code will be much more idiomatic, and therefore easier to read and maintain for people familiar with Python.</li>\n<li>Default arguments are IMO a code smell. They should only really be used if it is completely obvious what the default is, even for someone who only reads the body of the method.</li>\n<li>The format names are magic strings, and as such should be either constants or enums.</li>\n<li>The format synonyms such as <code>['fancy', 'pms']</code> feel like over-engineering. If you're the only user for now, why make your code more complicated than it needs to be?</li>\n<li>The method should <code>return</code> rather than <code>print()</code> the result (see above about handling only a single variable at a time) so that it can be <em>reused</em> by other code. It would be trivial to add a wrapper like <code>def main()</code> to <code>print()</code> it.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:14:29.387", "Id": "407548", "Score": "1", "body": "Why are boolean arguments a code smell? I see them used frequently in libraries such as scipy, pandas, etc." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T08:30:43.660", "Id": "210799", "ParentId": "210775", "Score": "1" } } ]
{ "AcceptedAnswerId": "210799", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T00:38:07.270", "Id": "210775", "Score": "4", "Tags": [ "python", "strings", "formatting" ], "Title": "Printing (number, uncertainty) pair in a formal way" }
210775
<p>I have been working on my first ever C# project and I'd love some feedback of the any and all aspects variety. I am building a game called <a href="https://github.com/bruglesco/fleet-command-rewrite/tree/dev" rel="nofollow noreferrer">Fleet Command</a>. In the <code>MainWindow</code> I use a <code>ContentControl</code> to use various <code>UserControl</code>s based on user interaction. The screen navigation is pretty simple so for the most part I am leaving it out. But for context I would like to give you this:</p> <p><strong>MainWindow.xaml</strong></p> <pre><code>&lt;Window x:Class="FleetCommand.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="Fleet Command" Height="700" Width="1200" Background="DarkSlateGray"&gt; &lt;Grid&gt; &lt;ContentControl x:Name="MainScreenContent"/&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>and</p> <p><strong>MainWindow.xaml.cs</strong></p> <pre><code>using System.Windows; using System.Windows.Controls; namespace FleetCommand { /// &lt;summary&gt; /// Struct to encapsulate initialization state from Custom game settings. /// Used to simplify passing many parameters to initialization function and minimize errors. /// &lt;/summary&gt; public struct InitialState { public int NumberPlayerCharacters; public int NumberNonPlayerCharacters; public int StartingOil; public int StartingCash; public int StartingResearch; public Difficulty Difficulty; } public enum Difficulty { Easy, Normal, Hard } /// &lt;summary&gt; /// Interaction logic for MainWindow.xaml /// &lt;/summary&gt; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); SetScreen(SplashScreen); } public void ReturnToSplash() =&gt; SetScreen(SplashScreen); public void OpenNewGameScreen() =&gt; SetScreen(NewGameScreen); public void OpenLoadGameScreen() { LoadGameScreen.Set(); SetScreen(LoadGameScreen); } public void OpenCustomScreen() =&gt; SetScreen(CustomGameScreen); public void OpenWorldMap() =&gt; GameScreen.OpenWorldMap(); public void OpenCity(string CityName) =&gt; GameScreen.OpenCity(CityName); public void StartCampaign() { GameData.StartGame(); SetScreen(GameScreen); } public void StartCustomGame(InitialState state) { GameData.StartGame(state); SetScreen(GameScreen); } public void StartLoadedGame(LoadFile FileSlot) { GameData.StartGame(FileSlot); SetScreen(GameScreen); } public void Reset() { CustomGameScreen.Reset(); GameScreen.Reset(); GameData.Reset(); } public void Save(LoadFile SaveSlot) =&gt; GameData.Save(SaveSlot); private void SetScreen(UserControl screen) =&gt; MainScreenContent.Content = screen; private static SplashScreen SplashScreen { get; } = new SplashScreen(); private static NewGameScreen NewGameScreen { get; } = new NewGameScreen(); private static LoadGameScreen LoadGameScreen { get; } = new LoadGameScreen(); private static CustomGameScreen CustomGameScreen { get; } = new CustomGameScreen(); private static GameScreen GameScreen { get; } = new GameScreen(); private static GameData GameData { get; set; } = new GameData(); } } </code></pre> <p>The various <code>UserControl</code>s call the public methods the <code>MainWindow</code> provides and then it acts accordingly.</p> <p>However, then I come to the <code>GameScreen</code>. This is where I need a review. <code>GameScreen</code> also provides a <code>ContentControl</code> that can be swapped out with various <code>UserControl</code>s in response to users. I'm not unhappy with that and don't think I need to change it, but I don't know, do I? I give the <code>GameScreen</code> all of the buttons it will need in it's various states. Here is. . .</p> <p><strong>GameScreen.xaml</strong> </p> <pre><code>&lt;UserControl x:Class="FleetCommand.GameScreen" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="20"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="20"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;ContentControl Grid.Column="1" Grid.ColumnSpan="8" Grid.Row="1" Grid.RowSpan="14" x:Name="GameField"/&gt; &lt;Rectangle Grid.Column="0" Grid.Row="0" Grid.RowSpan="16" Width="auto" Height="auto" Fill="SteelBlue"/&gt; &lt;Rectangle Grid.Column="9" Grid.Row="0" Grid.RowSpan="16" Width="auto" Height="auto" Fill="SteelBlue"/&gt; &lt;Button Grid.Column="1" Grid.Row="0" Content="Menu" Click="Click_Button" x:Name="menu" VerticalContentAlignment="Top" BorderThickness="0"/&gt; &lt;Button Grid.Column="1" Grid.Row="1" Content="Save" Click="Click_Button" x:Name="save" Visibility="Collapsed"/&gt; &lt;Button Grid.Column="1" Grid.Row="2" Content="Exit" Click="Click_Button" x:Name="exit" Visibility="Collapsed"/&gt; &lt;Button Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="15" Content="Dashboard" Click="Click_Button" x:Name="dashboard"/&gt; &lt;Button Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="15" Content="Research" Click="Click_Button" x:Name="research"/&gt; &lt;Button Grid.Column="5" Grid.ColumnSpan="2" Grid.Row="15" Content="Fleet" Click="Click_Button" x:Name="fleet"/&gt; &lt;Button Grid.Column="7" Grid.ColumnSpan="2" Grid.Row="15" Content="End Turn" Click="Click_Button" x:Name="endTurn"/&gt; &lt;Button Grid.ColumnSpan="2" Grid.Row="15" Content="Unit Design" Click="Click_Button" x:Name="unit" Visibility="Collapsed"/&gt; &lt;Button Grid.Column="7" Grid.ColumnSpan="2" Grid.Row="15" Content="Map" Click="Click_Button" x:Name="world" Visibility="Collapsed"/&gt; &lt;Button Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="15" Content="City Map" Click="Click_Button" x:Name="cityMap" Visibility="Collapsed"/&gt; &lt;Button Grid.Column="5" Grid.ColumnSpan="2" Grid.Row="15" Content="Upgrade City" Click="Click_Button" x:Name="cityUpgrade" Visibility="Collapsed"/&gt; &lt;Button Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="15" Click="Click_Button" x:Name="cityDashboard" Visibility="Collapsed"/&gt; &lt;TextBlock Grid.Column="2" Grid.ColumnSpan="2" Grid.Row="0" x:Name="playerName" Text="Placeholder Name" Background="SteelBlue" FontSize="36"/&gt; &lt;TextBlock Grid.Column="4" Grid.ColumnSpan="2" Grid.Row="0" x:Name="playerOil" Text="10000" Background="SteelBlue" FontSize="36"/&gt; &lt;TextBlock Grid.Column="6" Grid.ColumnSpan="2" Grid.Row="0" x:Name="playerCash" Text="1000" Background="SteelBlue" FontSize="36"/&gt; &lt;TextBlock Grid.Column="8" Grid.Row="0" x:Name="playerResearch" Text="10" Background="SteelBlue" FontSize="36"/&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>I collapse visibility on buttons not in use. I'm still not sure there is anything wrong with this approach but now I am starting to get into a bit of code duplication and I'm not sure of a way around it. As seen in. . .</p> <p><strong>GameScreen.xaml.cs</strong></p> <pre><code>using System.Windows; using System.Windows.Controls; namespace FleetCommand { /// &lt;summary&gt; /// Interaction logic for GameScreen.xaml /// &lt;/summary&gt; public partial class GameScreen : UserControl { public GameScreen() { InitializeComponent(); SetGameField(OuterMap); } public void Reset() { SetGameField(OuterMap); OuterMap.Reset(); CloseMenu(); } public void OpenWorldMap() =&gt; OpenWorld(); public void OpenCity(string CityName) =&gt; OpenCityManager(CityName); private void SetGameField(UserControl field) =&gt; GameField.Content = field; private void Click_Button(object sender, RoutedEventArgs e) { Button button = sender as Button; switch (button.Name) { case "menu": Menu(); break; case "save": Save(); break; case "exit": Exit(); break; case "dashboard": OpenDashboard(); break; case "research": OpenResearch(); break; case "fleet": OpenFleet(); break; case "unit": OpenUnitDesign(); break; case "cityMap": OpenCityMap(); break; case "cityUpgrade": OpenCityUpgrade(); break; case "cityDashboard": OpenCity(NameOfCity); break; case "world": OpenWorld(); break; case "endTurn": EndTurn(); break; default: break; } } private void Menu() { if (IsMenuOpen) { CloseMenu(); } else { OpenMenu(); } } private void Save() { SaveWindow saveWindow = new SaveWindow(); saveWindow.ShowDialog(); } private void Exit() { bool? proceed = true; Confirm confirm = new Confirm(); proceed = confirm.ShowDialog(); if (proceed != null &amp;&amp; (bool)proceed) { MainWindow window = Application.Current.MainWindow as MainWindow; window.ReturnToSplash(); window.Reset(); } } private void OpenWorld() { dashboard.Visibility = Visibility.Visible; research.Visibility = Visibility.Visible; fleet.Visibility = Visibility.Visible; endTurn.Visibility = Visibility.Visible; unit.Visibility = Visibility.Collapsed; world.Visibility = Visibility.Collapsed; cityMap.Visibility = Visibility.Collapsed; cityUpgrade.Visibility = Visibility.Collapsed; cityDashboard.Visibility = Visibility.Collapsed; SetGameField(OuterMap); OuterMap.OpenWorldMap(); } private void OpenDashboard() { Grid.SetColumn(unit, 1); unit.Visibility = Visibility.Visible; research.Visibility = Visibility.Visible; fleet.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; dashboard.Visibility = Visibility.Collapsed; endTurn.Visibility = Visibility.Collapsed; cityMap.Visibility = Visibility.Collapsed; cityUpgrade.Visibility = Visibility.Collapsed; cityDashboard.Visibility = Visibility.Collapsed; SetGameField(Dashboard); } private void OpenResearch() { Grid.SetColumn(unit, 3); dashboard.Visibility = Visibility.Visible; unit.Visibility = Visibility.Visible; fleet.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; research.Visibility = Visibility.Collapsed; endTurn.Visibility = Visibility.Collapsed; cityMap.Visibility = Visibility.Collapsed; cityUpgrade.Visibility = Visibility.Collapsed; cityDashboard.Visibility = Visibility.Collapsed; SetGameField(Research); } private void OpenFleet() { Grid.SetColumn(unit, 5); dashboard.Visibility = Visibility.Visible; research.Visibility = Visibility.Visible; unit.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; fleet.Visibility = Visibility.Visible; endTurn.Visibility = Visibility.Visible; cityMap.Visibility = Visibility.Collapsed; cityUpgrade.Visibility = Visibility.Collapsed; cityDashboard.Visibility = Visibility.Collapsed; SetGameField(Fleet); } private void OpenCityManager(string CityName) { dashboard.Visibility = Visibility.Visible; cityMap.Visibility = Visibility.Visible; cityUpgrade.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; research.Visibility = Visibility.Collapsed; unit.Visibility = Visibility.Collapsed; fleet.Visibility = Visibility.Collapsed; endTurn.Visibility = Visibility.Collapsed; cityDashboard.Visibility = Visibility.Collapsed; cityDashboard.Content = NameOfCity = CityName; SetGameField(CityDashboard); } private void OpenCityMap() { Grid.SetColumn(unit, 3); cityDashboard.Visibility = Visibility.Visible; unit.Visibility = Visibility.Visible; cityUpgrade.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; dashboard.Visibility = Visibility.Collapsed; cityMap.Visibility = Visibility.Collapsed; research.Visibility = Visibility.Collapsed; fleet.Visibility = Visibility.Collapsed; endTurn.Visibility = Visibility.Collapsed; SetGameField(OuterMap); OuterMap.OpenCityMap(NameOfCity); } private void OpenUnitDesign() { dashboard.Visibility = Visibility.Visible; research.Visibility = Visibility.Visible; fleet.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; cityDashboard.Visibility = Visibility.Collapsed; unit.Visibility = Visibility.Collapsed; cityUpgrade.Visibility = Visibility.Collapsed; cityMap.Visibility = Visibility.Collapsed; endTurn.Visibility = Visibility.Collapsed; SetGameField(UnitDesign); } private void OpenCityUpgrade() { Grid.SetColumn(unit, 5); cityDashboard.Visibility = Visibility.Visible; cityMap.Visibility = Visibility.Visible; unit.Visibility = Visibility.Visible; world.Visibility = Visibility.Visible; dashboard.Visibility = Visibility.Collapsed; research.Visibility = Visibility.Collapsed; fleet.Visibility = Visibility.Collapsed; cityUpgrade.Visibility = Visibility.Collapsed; endTurn.Visibility = Visibility.Collapsed; SetGameField(CityUpgrade); } private void EndTurn() { // TODO: End Turn via Data } private void OpenMenu() { save.Visibility = Visibility.Visible; exit.Visibility = Visibility.Visible; IsMenuOpen = true; } private void CloseMenu() { save.Visibility = Visibility.Hidden; exit.Visibility = Visibility.Hidden; IsMenuOpen = false; } private string NameOfCity { get; set; } private string PlayerName { get; set; } private string PlayerOil { get; set; } private string PlayerCash { get; set; } private string PlayerResearch { get; set; } private bool IsMenuOpen { get; set; } = false; private static OuterMap OuterMap { get; } = new OuterMap(); private static Dashboard Dashboard { get; } = new Dashboard(); private static CityDashboard CityDashboard { get; } = new CityDashboard(); private static Research Research { get; } = new Research(); private static Fleet Fleet { get; } = new Fleet(); private static UnitDesign UnitDesign { get; } = new UnitDesign(); private static CityUpgrade CityUpgrade { get; } = new CityUpgrade(); } } </code></pre> <p>My biggest issue with this approach is manually handling the visibility of each button as I navigate through each subcontent of the <code>GameScreen</code>. I had considered not needing the <code>GameScreen</code> at all (after all each <code>UserControl</code> could simply be the content of the <code>MainWindow</code>, but they all share so many elements that I didn't like that idea. I could move just the <code>&lt;Button&gt;</code>s but that wouldn't actually remove the repetitiveness it would just spread it out across multiple files. I think I would prefer to keep it together in one place. It will make making changes easier I believe.</p> <p>I can add more of the files if needed but the <code>GameScreen</code> is the big and ugly one I'm worried about. I am also interested in anything else you might see.</p>
[]
[ { "body": "<p>There is one thing that struck me most namely that you use event handlers for the buttons:</p>\n\n<blockquote>\n<pre><code>Click=\"Click_Button\"\n</code></pre>\n</blockquote>\n\n<p>The WPF or rather MVVM way would be to use commands to handle these actions. This way you could get rid of all the ugly <code>switch</code> with <code>case \"menu\":</code> etc. </p>\n\n<blockquote>\n<pre><code>public partial class GameScreen : UserControl\n</code></pre>\n</blockquote>\n\n<p>The <code>UserControl</code> would then become a <code>GameScreenModel</code> that you would <em>data-bind</em> to the window.</p>\n\n<p>Also all your visibility assignments like <code>dashboard.Visibility = Visibility.Visible;</code> could be driven much easier and automatically by binding them to dependency properties on the <code>GameScreenModel</code>. It might also be necessary to create a custom converter from a <code>GameScreenModel</code> property like an enum to <code>Visibility</code>. You could then setup nearly everything declaratively in XAML only.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:01:42.550", "Id": "407664", "Score": "0", "body": "IS MVVM relatively inseparable from WPF? I'm brand new to C# and this project was just me plunging right in. The more I spent reading the more I found MVVM popping up but is it unconventional to do WPF without it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:59:55.433", "Id": "407678", "Score": "0", "body": "@bruglesco MVVM is just a design pattern to help you make certain things easier to implement, maintain and test, primarily via data-binding. Such design virtually forces you to separate the model from the view so theoretically you could much easier exchange them but practically it makes testing easier because you don't require the view to test its model. Sure, you can do WPF without MVVM, there is nothing wrong with that but it's not the most popular way and that it has its disadvantages, so yes, it's pretty unconventional. Once you get how MVVM works, you won't be doing anything else ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T08:05:58.440", "Id": "210797", "ParentId": "210776", "Score": "2" } } ]
{ "AcceptedAnswerId": "210797", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T01:07:57.140", "Id": "210776", "Score": "2", "Tags": [ "c#", "beginner", "game", "wpf", "xaml" ], "Title": "WPF Content Navigation and Button management" }
210776
<p>I have a text file with letters (tab delimited), and a numpy array (<code>obj</code>) with a few letters (single row). The text file has rows with different numbers of columns. Some rows in the text file may have multiple copies of same letters (I will like to consider only a single copy of a letter in each row). Also, each letter of the numpy array <code>obj</code> is present in one or more rows of the text file. </p> <p>Letters in the same row of the text file are assumed to be similar to each other. Imagine a similarity metric (between two letters) which can take values 1 (related), or 0 (not related). When any pair of letters are in the same row then they are assumed to have similarity metric value = 1. In the example given below, the letters <code>j</code> and <code>n</code> are in the same row (second row). Hence <code>j</code> and <code>n</code> have similarity metric value = 1.</p> <p>Here is an example of the text file (you can download the file from <a href="https://drive.google.com/file/d/1hrs6AFa5jQWiTQH_aoTr0hR_Igl-2J1e/view?usp=sharing" rel="nofollow noreferrer">here</a>):</p> <pre><code>b q a i m l r j n o r o e i k u i s </code></pre> <p>In the example, the letter <code>o</code> is mentioned two times in the second row, and the letter <code>i</code> is denoted two times in the third row. I will like to consider single copies of letters rows of the text file.</p> <p>This is an example of <code>obj</code>:</p> <pre><code>obj = np.asarray(['a', 'e', 'i', 'o', 'u']) </code></pre> <p>I want to compare <code>obj</code> with rows of the text file and <strong>form clusters from elements in <code>obj</code></strong>.</p> <p>This is how I want to do it. Corresponding to each row of the text file, I want to have a list which denotes a cluster (In the above example we will have three clusters since the text file has three rows). For every given element of <code>obj</code>, I want to find rows of the text file where the element is present. Then, I will like to <strong>assign index of that element of <code>obj</code> to the cluster which corresponds to the row with maximum length</strong> (the lengths of rows are decided with all rows having single copies of letters).</p> <pre><code>import pandas as pd import numpy as np data = pd.read_csv('file.txt', sep=r'\t+', header=None, engine='python').values[:,:].astype('&lt;U1000') obj = np.asarray(['a', 'e', 'i', 'o', 'u']) for i in range(data.shape[0]): globals()['data_row' + str(i).zfill(3)] = [] globals()['clust' + str(i).zfill(3)] = [] for j in range(len(obj)): if obj[j] in set(data[i, :]): globals()['data_row' + str(i).zfill(3)] += [j] for i in range(len(obj)): globals()['obj_lst' + str(i).zfill(3)] = [0]*data.shape[0] for j in range(data.shape[0]): if i in globals()['data_row' + str(j).zfill(3)]: globals()['obj_lst' + str(i).zfill(3)][j] = len(globals()['data_row' + str(j).zfill(3)]) indx_max = globals()['obj_lst' + str(i).zfill(3)].index( max(globals()['obj_lst' + str(i).zfill(3)]) ) globals()['clust' + str(indx_max).zfill(3)] += [i] for i in range(data.shape[0]): print globals()['clust' + str(i).zfill(3)] &gt;&gt; [0] &gt;&gt; [3] &gt;&gt; [1, 2, 4] </code></pre> <p>The code gives me the right answer. But, in my actual work, <strong>the text file has tens of thousands of rows</strong>, and the <strong>numpy array has hundreds of thousands of elements</strong>. And, the above given code is not very fast. So, I want to know if there is a better (<strong>faster</strong>) way to implement the above functionality and aim (using Python).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:40:29.040", "Id": "407479", "Score": "1", "body": "What do you mean by this statement: \"Letters in the same row of the text file are assumed to be similar to each other.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T08:12:07.240", "Id": "407482", "Score": "1", "body": "In general, try to explain what you're trying to do without reference to the actual variables in the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:37:58.930", "Id": "407709", "Score": "0", "body": "@I0b0 : By the mentioned statement, I meant that the letters in the same row are related to each other. Imagine a similarity metric (between two letters) which can take values 1 (related), or 0 (not related). When any pair of letters are in the same row then they are assumed to have similarity metric value = 1. In the given example 'j' and 'n' are in the same row, i.e. the second row. Hence 'j' and 'n' have similarity metric value = 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:09:50.713", "Id": "407721", "Score": "0", "body": "You should update the question to include this extra information." } ]
[ { "body": "<p>I can't understand your algorithm as written, but some very general advice applies:</p>\n\n<ul>\n<li>Use <a href=\"https://docs.python.org/3.7/library/string.html#string.Formatter.format\" rel=\"nofollow noreferrer\"><code>format()</code></a> or <a href=\"https://docs.python.org/3.7/library/string.html#template-strings\" rel=\"nofollow noreferrer\">template strings</a> to format strings.</li>\n<li>Rather than creating dynamic dictionary keys, I would create variables <code>data_row</code>, <code>clust</code> (but see naming review below), etc. and assign to indexes in these lists. That way you get rid of the global variables (which are bad for reasons discussed at great length elsewhere), you won't need to format strings all over the place, <em>and</em> you won't need to do the <code>str()</code> conversions. You should also be able to get rid of the array initialization this way, something which is a code smell in garbage collected languages.</li>\n<li>Can there really be <em>multiple</em> tab characters between columns? That would be weird. If not, you might get less surprising results using a single tab as the column separator.</li>\n<li>Naming could use some work. For example:\n\n<ul>\n<li>In general, don't use abbreviations, especially not single letter ones or ones which shorten by only one or two letters. For example, use <code>index</code> (or <code>[something]_index</code> if there are multiple indexes in the current context) rather than <code>indx</code>, <code>idx</code>, <code>i</code> or <code>j</code>.</li>\n<li><code>data</code> should be something like <code>character_table</code>.</li>\n<li>I don't know what <code>obj</code> <em>is</em>, but <code>obj</code> gives me no information at all. Should it be <code>vowels</code>?</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T08:02:34.620", "Id": "210796", "ParentId": "210784", "Score": "2" } }, { "body": "<h2>Do one thing at a time</h2>\n\n<p>Don't put multiple statements on one line, i.e.</p>\n\n<pre><code>if obj[j] in set(data[i, :]): globals()['data_row' + str(i).zfill(3)] += [j]\n</code></pre>\n\n<h2>Global population?</h2>\n\n<p>You're doing a curious thing. You're populating the global namespace with some variable names that have integral indices baked into them. Since I can't find a reason for this anywhere in your description (and even if you did have a reason, it probably wouldn't be a good one), really try to avoid doing this. In other words, rather than writing to</p>\n\n<pre><code>globals['data_row001']\n</code></pre>\n\n<p>just write to a list called <code>data_row</code> (and <code>obj_lst</code>, etc.). You can still print it in whatever format you want later.</p>\n\n<h2>Use fluent syntax</h2>\n\n<p>For long statements with several <code>.</code> calls, such as this:</p>\n\n<pre><code>data = pd.read_csv('file.txt', sep=r'\\t+', header=None, engine='python').values[:,:].astype('&lt;U1000')\n</code></pre>\n\n<p>try rewriting it on multiple lines for legibility:</p>\n\n<pre><code>data = (pd\n .read_csv('file.txt', sep=r'\\t+', header=None, engine='python')\n .values[:,:]\n .astype('&lt;U1000')\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:01:51.247", "Id": "210903", "ParentId": "210784", "Score": "1" } } ]
{ "AcceptedAnswerId": "210796", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T03:50:26.047", "Id": "210784", "Score": "2", "Tags": [ "python", "array", "numpy", "pandas" ], "Title": "Compare an array with a file and form groups from elements of an array" }
210784
<p>I have a function that will calculate the sum of a list of integer, however if any of the number is negative, it will should an error instead (not throwing exception).</p> <p>The following is a working Haskell code (Glasgow Haskell Compiler, Version 7.10.3): </p> <pre><code>addAll :: [Int] -&gt; Either String Int addAll xs = foldl safeAdd (Right 0) xs where safeAdd :: Either String Int -&gt; Int -&gt; Either String Int safeAdd = (\acc next -&gt; case acc of Left s -&gt; Left s Right n -&gt; if next &lt; 0 then Left (show next ++ " is not positive") else Right (n + next)) </code></pre> <p>Examples output of the function:</p> <pre><code>addAll [1,2,3] -- Right 6 addAll [-1,2,3] -- Left "-1 is not positive" </code></pre> <p>Although the code works, but I'm not entirely satisfied with it, because the recursion keeps going until the last element even though errors are encountered early. Not only that, it feels a little more complicated than it should be. </p> <p>After reading some SO posts such as <a href="https://stackoverflow.com/questions/7464208/folding-across-maybes-in-haskell">this one</a>, I think that the code above can be further simplified using functions like <code>foldM</code> or even applicative <code>&lt;$&gt;</code>. </p> <p>But, I'm just not sure how to use those functions, so please do show me a way to simplify the code above.</p>
[]
[ { "body": "<pre><code>import Data.Foldable\n\naddAll :: [Int] -&gt; Either String Int \naddAll = foldlM safeAdd 0 where\n safeAdd :: Int -&gt; Int -&gt; Either String Int\n safeAdd n next = if next &lt; 0\n then Left (show next ++ \" is not positive\")\n else Right (n + next)\n</code></pre>\n\n<p>Refer <a href=\"http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Foldable.html#v:foldlM\" rel=\"nofollow noreferrer\">http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Foldable.html#v:foldlM</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:14:36.860", "Id": "210874", "ParentId": "210785", "Score": "1" } } ]
{ "AcceptedAnswerId": "210874", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T04:05:43.400", "Id": "210785", "Score": "0", "Tags": [ "haskell", "error-handling", "monads" ], "Title": "Using foldl to add numbers, while validating that they are nonnegative" }
210785
<p>I learnt lots about ruby from my last post <a href="https://codereview.stackexchange.com/questions/209661/game-of-life-in-ruby">Game of Life in Ruby</a>, so I have my next try in Ruby, it is Gomoku. </p> <p>It is still an console game and I use three classes <code>Game</code> <code>Grid</code> <code>Cell</code>, the structure is similar with the @Johan Wentholt 's example code. But of course game rule is different.</p> <h3>Game class</h3> <p>Game class to run the game</p> <pre><code>class Game def initialize(width=15) @width = width @users = ["A", "B"] @user_piece = {"A"=&gt;"+", "B"=&gt;"*"} @user_index = 0 end def reset @grid = Grid.new(@width) end def start reset puts @grid until @grid.gameover user = @users[@user_index] print "Now for user&lt;#{user}&gt;, Enter your move(split by space)[0-#{@width-1}]:" begin move = gets.chomp.split.map(&amp;:to_i) if not @grid.update?(move, @user_piece[user]) puts "Invalid move!!!" else switch_user puts @grid end rescue puts "Invalid move!!!" end end show_result end def switch_user @user_index = (@user_index + 1) % @users.length end def show_result if not @grid.draw switch_user print "Game Over the Winner is &lt;#{@users[@user_index]}&gt;" else print "Game Over Draw" end end end </code></pre> <h3>Grid class</h3> <p>Grid present is the gomoku game board, keep updating piece on board and whether the game is over</p> <pre><code>class Grid attr_reader :gameover, :draw def initialize(width) @cells = Array.new(width * width).map { Cell.new } @grid = @cells.each_slice(width).to_a @gameover = false @draw = false @width = width assign_cell_neighbours end def update?(move, piece) x, y = move if x.negative? || x &gt;= @width || y.negative? || y &gt;= @width return false end cell = @grid.dig(x,y) if not cell.place?(piece) return false end if not full? @gameover = cell.win? else @gameover = true @draw = true end return true end def full? @cells.none?{|cell| cell.empty?} end def to_s @grid.map {|row| row.map(&amp;:to_s).join}.join("\n") end private def assign_cell_neighbours @grid.each_with_index do |row, row_index| row.each_with_index do |cell, column_index| Cell::RELATIVE_NEIGHBOUR_COORDINATES.each do |dir, rel_coord| (rel_row_index, rel_column_index) = rel_coord neighbour_row_index = row_index neighbour_column_index = column_index neighbours = [] loop do neighbour_row_index += rel_row_index neighbour_column_index += rel_column_index break if neighbour_row_index.negative? || neighbour_column_index.negative? || neighbour_row_index &gt;= @width || neighbour_column_index &gt;= @width neighbours &lt;&lt; @grid.dig(neighbour_row_index, neighbour_column_index) end cell[dir] = neighbours end end end end end </code></pre> <h3>Cell class</h3> <p>Cell class keep the cell state and alse judge whether current update on cell lead to a win</p> <pre><code>class Cell RELATIVE_NEIGHBOUR_COORDINATES = { north: [-1, 0].freeze, north_east: [-1, 1].freeze, east: [0, 1].freeze, south_east: [1, 1].freeze, south: [1, 0].freeze, south_west: [1, -1].freeze, west: [0, -1].freeze, north_west: [-1, -1].freeze, }.freeze NEIGHBOUR_DIRECTIONS = RELATIVE_NEIGHBOUR_COORDINATES.keys.freeze PAIR_DIRECTIONS = [[:north, :south].freeze, [:east, :west].freeze, [:north_east, :south_west].freeze, [:north_west, :south_east].freeze].freeze EMPTY = "." attr_accessor(*NEIGHBOUR_DIRECTIONS) def initialize @cell = EMPTY end def empty? @cell == EMPTY end def place?(piece) if empty? and valid_piece?(piece) @cell = piece return true end return false end def win? neighbours.compact.select{|x| x&gt;=4}.length &gt; 0 end def [](direction) validate_direction(direction) send(direction) end def []=(direction, neighbour) validate_direction(direction) send("#{direction}=", neighbour) end def neighbours PAIR_DIRECTIONS.map{ |directions| directions.map{|direction| self[direction].find_index{|neighbour| neighbour.to_s != self.to_s} }.compact.inject(:+) } end def to_s @cell end def inspect "&lt;#{self.class} #{@cell}&gt;" end private def validate_direction(direction) unless NEIGHBOUR_DIRECTIONS.map(&amp;:to_s).include?(direction.to_s) raise "unsupported direction #{direction}" end end def valid_piece?(piece) piece != EMPTY end end </code></pre> <h3>Full code</h3> <pre><code>#!/usr/bin/ruby class Cell RELATIVE_NEIGHBOUR_COORDINATES = { north: [-1, 0].freeze, north_east: [-1, 1].freeze, east: [0, 1].freeze, south_east: [1, 1].freeze, south: [1, 0].freeze, south_west: [1, -1].freeze, west: [0, -1].freeze, north_west: [-1, -1].freeze, }.freeze NEIGHBOUR_DIRECTIONS = RELATIVE_NEIGHBOUR_COORDINATES.keys.freeze PAIR_DIRECTIONS = [[:north, :south].freeze, [:east, :west].freeze, [:north_east, :south_west].freeze, [:north_west, :south_east].freeze].freeze EMPTY = "." attr_accessor(*NEIGHBOUR_DIRECTIONS) def initialize @cell = EMPTY end def empty? @cell == EMPTY end def place?(piece) if empty? and valid_piece?(piece) @cell = piece return true end return false end def win? neighbours.compact.select{|x| x&gt;=4}.length &gt; 0 end def [](direction) validate_direction(direction) send(direction) end def []=(direction, neighbour) validate_direction(direction) send("#{direction}=", neighbour) end def neighbours PAIR_DIRECTIONS.map{ |directions| directions.map{|direction| self[direction].find_index{|neighbour| neighbour.to_s != self.to_s} }.compact.inject(:+) } end def to_s @cell end def inspect "&lt;#{self.class} #{@cell}&gt;" end private def validate_direction(direction) unless NEIGHBOUR_DIRECTIONS.map(&amp;:to_s).include?(direction.to_s) raise "unsupported direction #{direction}" end end def valid_piece?(piece) piece != EMPTY end end class Grid attr_reader :gameover, :draw def initialize(width) @cells = Array.new(width * width).map { Cell.new } @grid = @cells.each_slice(width).to_a @gameover = false @draw = false @width = width assign_cell_neighbours end def update?(move, piece) x, y = move if x.negative? || x &gt;= @width || y.negative? || y &gt;= @width return false end cell = @grid.dig(x,y) if not cell.place?(piece) return false end if not full? @gameover = cell.win? else @gameover = true @draw = true end return true end def full? @cells.none?{|cell| cell.empty?} end def to_s @grid.map {|row| row.map(&amp;:to_s).join}.join("\n") end private def assign_cell_neighbours @grid.each_with_index do |row, row_index| row.each_with_index do |cell, column_index| Cell::RELATIVE_NEIGHBOUR_COORDINATES.each do |dir, rel_coord| (rel_row_index, rel_column_index) = rel_coord neighbour_row_index = row_index neighbour_column_index = column_index neighbours = [] loop do neighbour_row_index += rel_row_index neighbour_column_index += rel_column_index break if neighbour_row_index.negative? || neighbour_column_index.negative? || neighbour_row_index &gt;= @width || neighbour_column_index &gt;= @width neighbours &lt;&lt; @grid.dig(neighbour_row_index, neighbour_column_index) end cell[dir] = neighbours end end end end end class Game def initialize(width=15) @width = width @users = ["A", "B"] @user_piece = {"A"=&gt;"+", "B"=&gt;"*"} @user_index = 0 end def reset @grid = Grid.new(@width) end def start reset puts @grid until @grid.gameover user = @users[@user_index] print "Now for user&lt;#{user}&gt;, Enter your move(split by space)[0-#{@width-1}]:" begin move = gets.chomp.split.map(&amp;:to_i) if not @grid.update?(move, @user_piece[user]) puts "Invalid move!!!" else switch_user puts @grid end rescue puts "Invalid move!!!" end end show_result end def switch_user @user_index = (@user_index + 1) % @users.length end def show_result if not @grid.draw switch_user print "Game Over the Winner is &lt;#{@users[@user_index]}&gt;" else print "Game Over Draw" end end end game = Game.new() game.start </code></pre> <p>All reviews are welcome!</p>
[]
[ { "body": "<ol>\n<li>Simplify <code>@user</code>/<code>@user_index</code>/<code>switch_user</code> using <code>Array#rotate!</code></li>\n</ol>\n\n<pre class=\"lang-rb prettyprint-override\"><code>user_queue = ['A', 'B']\nuser_queue.rotate!.first # 'B'\nuser_queue.rotate!.first # 'A'\n</code></pre>\n\n<ol start=\"2\">\n<li>The boolean-success return value is fine for this small program, but in general, it's strange because the methods like <code>update?</code> aren't only reads, they're actions as well. It's like if <code>number.even?</code> somehow modified <code>number</code> underneath.<br>\nI think the code would flow better if the actions and the validations were separated. For example:</li>\n</ol>\n\n<pre class=\"lang-rb prettyprint-override\"><code>until @grid.gameover?\n turn_user = @user_queue.first\n move = gets_move(turn_user) until @grid.valid_move?(move, turn_user)\n @grid.update!(turn_user, move)\n @user_queue.rotate!\n # ...\nend\n</code></pre>\n\n<ol start=\"3\">\n<li>Leverage the built-in bounds-checking and concise syntax sugar of Ruby:</li>\n</ol>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def valid_move?(move, user)\n !!@grid.dig(*move)&amp;.empty? # simplified to one line, same as:\n # @grid.dig(*move) # nil if out of bounds\n # cell&amp;.empty? # same as `cell &amp;&amp; cell.empty?`\nend\n\nnot full? # substitutes to:\nnot @cells.none?{|cell| cell.empty?} # double negative, easily avoidable:\n\n@cells.any?(&amp;:empty?) # `&amp;:empty?` same as sending a `{ |x| x.empty? }` block\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-03T12:12:27.523", "Id": "214641", "ParentId": "210788", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T05:11:16.467", "Id": "210788", "Score": "0", "Tags": [ "ruby" ], "Title": "Gomoku Game in Ruby" }
210788
<p>PHP's <code>shuffle()</code> function destroys the array keys, so I decided to write a shuffle function that doesn't do that and instead rearranges key-value associations. As I would be using the function in place of <code>shuffle()</code> most of the time, I'd like it to be as fast and memory efficient (if a time-space tradeoff is needed, I think I would prioritise time) as possible:</p> <pre><code>&lt;? function swap(&amp;$a, &amp;$b) { $tmp = $a; $a = $b; $b = $tmp; } function shuffleX(&amp;$arr) #Shuffles the key-value associations in an array. { $keys = array_keys($arr); #extract the keys from the array. $length = count($keys); $i = 0; #Index. while ($i &lt; $length-1) { $target = rand(($i+1), $length-1); #This ensures that no value ends up mapped to the same key. swap($arr[$keys[$i]], $arr[$keys[$target]]); #Swap each element of the array with another. $i++; } } ?&gt; </code></pre>
[]
[ { "body": "<p><strong>The <code>swap()</code> function is unecessary</strong></p>\n\n<p>There's no need to create a <code>swap()</code> function. This can be done as a one-liner using native PHP. And, generally speaking, native functionality is going to be more performant than user-defined functions. It also means less code for you to write or maintain.</p>\n\n<pre><code>list($a,$b) = [$b, $a];\n</code></pre>\n\n<p>This takes two values, places them in an array and then using <code>list()</code> swaps them. In your case it would look like:</p>\n\n<pre><code>list($arr[$keys[$i]],$arr[$keys[$target]]) = [$arr[$keys[$target]], $arr[$keys[$i]]];\n</code></pre>\n\n<p><strong>Friendly reminder: don't use short tags</strong> </p>\n\n<p>Short PHP tags (<code>&lt;?</code>) has been discouraged for a long time. Although it is still supported it is disabled by default in the php.ini file and its use is discouraged. It sounds like it is not a big deal but this means having to make sure every time you set up an environment for this to run you have to make a special configuration change which is risky and time consuming and really shouldn't be necessary. (The short echo tag (<code>&lt;?=</code>) is not discouraged and always available so feel free to use that as much as you like).</p>\n\n<blockquote>\n <p>PHP also allows for short open tag <code>&lt;?</code> (which is discouraged since it is only available if enabled using the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option).</p>\n</blockquote>\n\n<p><a href=\"http://php.net/manual/en/language.basic-syntax.phptags.php\" rel=\"nofollow noreferrer\">Source</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:38:43.713", "Id": "407524", "Score": "0", "body": "Oh my, the great John Conde comes to CodeReview. Welcome sir! I wonder what your opinion on php7 array deconstruction is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:12:55.110", "Id": "407539", "Score": "1", "body": "I like it. In fact, it is better than my proposed solution. I've been stuck in a PHP 5.6 world due to the size and complexity of my company's applications. But we're finishing up our (large and painful) PHP 7 migration so I'll get to start thinking in PHP 7 full time very soon!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:14:59.463", "Id": "407540", "Score": "0", "body": "I don't know about great but I figured participating here will help me think creatively as I do less coding now than every before and I hope to keep my mind sharp. Or at least working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:32:13.677", "Id": "407553", "Score": "0", "body": "@JohnConde I'm aware that it is discouraged, and only use it for convenience in a testing/learning environment." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T12:48:34.910", "Id": "210813", "ParentId": "210790", "Score": "3" } }, { "body": "<p>Rather than making iterated <code>rand()</code> calls, you should randomize the data once for best efficiency. To do this, just isolate the keys, shuffle them, then rejoin the values to the appropriate keys in the new order.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/C11n9\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function preserve_shuffle(&amp;$arr) #Shuffles the key-value associations in an array.\n{\n $keys = array_keys($arr); #extract the keys from the array.\n shuffle($keys);\n for ($index = 0, $length = count($keys); $index &lt; $length; ++$index) {\n $result[$keys[$index]] = $arr[$keys[$index]];\n }\n $arr = $result;\n}\n\n$arr = [\"a\" =&gt; \"apple\", \"b\" =&gt; \"banana\", \"c\" =&gt; \"capsicum\", \"d\" =&gt; \"dill\"];\npreserve_shuffle($arr);\nvar_export($arr);\n</code></pre>\n\n<p>Or, if you prefer greater brevity or a functional syntax, you could use the following inside your custom function:</p>\n\n<pre><code>$keys = array_keys($arr); #extract the keys from the array.\nshuffle($keys);\n$arr = array_merge(array_flip($keys), $arr);\n</code></pre>\n\n<p>Proof that it also works: <a href=\"https://3v4l.org/eLMo6\" rel=\"nofollow noreferrer\">https://3v4l.org/eLMo6</a></p>\n\n<hr>\n\n<p>My earlier snippets only reorder the associative data. The following will shuffle the associations without shuffling the key orders. It does not guarantee that all initially associations will be destroyed -- which I feel is beneficial / less predictable in a randomized result.</p>\n\n<pre><code>function random_disassociate(&amp;$assoc_array)\n{\n if (sizeof($assoc_array) &lt; 2) {\n return; // data cannot be disassociated\n }\n $keys = array_keys($assoc_array);\n shuffle($assoc_array);\n $assoc_array = array_combine($keys, $assoc_array);\n}\n\n$arr = [\"a\" =&gt; \"apple\", \"b\" =&gt; \"banana\", \"c\" =&gt; \"capsicum\", \"d\" =&gt; \"dill\"];\nrandom_disassociate($arr);\nvar_export($arr);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:10:01.503", "Id": "407561", "Score": "0", "body": "Your function version doesn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T05:39:17.190", "Id": "407621", "Score": "0", "body": "That doesn't rearrange the key to value mappings. It just changes the order in which they are presented, but the key to value mappings are the same. The function is supposed to rearrange the key to value mappings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T05:46:04.003", "Id": "407623", "Score": "0", "body": "You require all initial pairs to be disassociated in the result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T07:40:46.003", "Id": "407629", "Score": "0", "body": "That is the idea. They don't have to be disassociated, but I expect that the probability of finding the original associations would be extremely small (probability drops exponentially with the size of the array). My original code actually made it `0`, but that isn't necessary for what I would consider a working shuffle function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T07:46:39.857", "Id": "407630", "Score": "0", "body": "I was using the `for` loop version previously, but I'll check out your edit. DId you by any chance benchmark them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T07:51:17.633", "Id": "407631", "Score": "0", "body": "I did not benchmark." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T08:00:18.183", "Id": "407632", "Score": "1", "body": "I think the edited function is much more legible and easier to read than the first one. Ultimately, I would probably just use the faster one. Thank you very much for your time and assistance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T08:36:42.803", "Id": "407634", "Score": "0", "body": "I benchmarked them, and edited your functions to better suit my needs. I would add it as a solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T08:38:18.807", "Id": "407635", "Score": "0", "body": "What aspects of my answer were not suitable for your needs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T08:40:53.597", "Id": "407636", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/87828/discussion-between-tobi-alafin-and-mickmackusa)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T09:08:07.717", "Id": "407637", "Score": "0", "body": "I'm having trouble submitting the answer, but here it is for reference: http://pastebin.com/ktQViXky" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T09:32:37.433", "Id": "407641", "Score": "0", "body": "`count()` should not be called in the 2nd param of `for()` if you are microoptimizing because that will be a function call that is made on each iteraration. Rather, declare the count as a variable ONCE in the 1st param or before the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T10:12:31.103", "Id": "407643", "Score": "0", "body": "Noted, I'll change that and rebenchmark." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T10:33:40.527", "Id": "407644", "Score": "0", "body": "Rebenchmarked here: https://imgur.com/a/UWTGhBT, I got a 31% improvement which is a little above what I got previously (longer runtimes are because my system is currently busier than it was then). I'm guessing that `count($arr)` was ultimately a negligible cost seeing as removing it didn't improve run time even over a million iterations." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:00:32.970", "Id": "210820", "ParentId": "210790", "Score": "4" } } ]
{ "AcceptedAnswerId": "210820", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T05:23:49.360", "Id": "210790", "Score": "2", "Tags": [ "performance", "beginner", "php", "array", "shuffle" ], "Title": "Shuffle array elements by rearranging the key value associations" }
210790
<p>I wanted to make a matrix template class to see if I can learn how to use templates, work on figuring out the indexing in loops, and making an interface so the user can know if an operation will work. Eventually I would like to add more cache optimization, calculating the inverse, and other ways to get data into the matrix such as raw pointers. </p> <p>For now everything is one header and I will separate out the implementation</p> <pre><code>#pragma once #include &lt;cstdint&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;type_traits&gt; template&lt;typename T&gt; class LiteMatrix { public: LiteMatrix(const size_t &amp;rows, const size_t &amp;cols); LiteMatrix(const size_t &amp;rows, const size_t &amp;cols, const std::vector&lt;T&gt;&amp;data); ~LiteMatrix() = default; LiteMatrix(const LiteMatrix &amp;rhs) = default; // copy constructor LiteMatrix(LiteMatrix &amp;&amp; rhs) = default; // move constructor LiteMatrix&amp; operator=(const LiteMatrix&amp; rhs) = default; // copy assignment LiteMatrix&amp; operator=(LiteMatrix&amp;&amp; rhs) = default; // move assignment LiteMatrix&amp; zeroes(); LiteMatrix&amp; ones(); LiteMatrix operator+(const LiteMatrix&lt;T&gt; &amp;rhs); LiteMatrix&amp; operator+=(const LiteMatrix&lt;T&gt;&amp; rhs); LiteMatrix operator-(const LiteMatrix&lt;T&gt; &amp;rhs); LiteMatrix&amp; operator-=(const LiteMatrix&lt;T&gt;&amp; rhs); LiteMatrix operator*(const LiteMatrix&lt;T&gt; &amp;rhs); LiteMatrix&amp; operator*=(const LiteMatrix&lt;T&gt;&amp; rhs); T&amp; operator()(const size_t &amp;rIndex, const size_t &amp;cIndex); LiteMatrix operator*(const T &amp;rhs); LiteMatrix&amp; operator*=(const T &amp;rhs); bool operator!=(const LiteMatrix&lt;T&gt;&amp; rhs) const; bool operator==(const LiteMatrix&lt;T&gt;&amp; rhs) const; template&lt;typename T&gt; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const LiteMatrix&lt;T&gt;&amp; rhs); size_t rowCount() const; size_t colCount() const; bool isAddSubLegal(const LiteMatrix&amp; rhs) const; bool isMultLegal(const LiteMatrix&amp; rhs) const; void setMatrix(const std::vector&lt;T&gt;&amp; val); void setElement(const size_t row, const size_t col, const T&amp; val); void setRow(const size_t row, const std::vector&lt;T&gt; val); void setCol(const size_t col, const std::vector&lt;T&gt; val); T getElement(const size_t row, const size_t col) const; LiteMatrix&amp; transpose(); private: size_t m_rows; size_t m_cols; std::vector&lt;T&gt; m_mat; }; //#include "LiteMatrix.tcc" template&lt;typename T&gt; LiteMatrix&lt;T&gt;::LiteMatrix(const size_t &amp; rows, const size_t &amp; cols) : m_rows(rows), m_cols(cols) { m_mat = std::vector&lt;T&gt;(rows * cols); } template&lt;typename T&gt; LiteMatrix&lt;T&gt;::LiteMatrix(const size_t &amp; rows, const size_t &amp; cols, const std::vector&lt;T&gt;&amp; data) : m_rows(rows), m_cols(cols), m_mat(data) { } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::zeroes() { std::fill(m_mat.begin(), m_mat.end(), 0); return *this; } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::ones() { std::fill(m_mat.begin(), m_mat.end(), 1); return *this; } template&lt;typename T&gt; LiteMatrix&lt;T&gt; LiteMatrix&lt;T&gt;::operator+(const LiteMatrix&amp; rhs) { LiteMatrix ret(*this); ret += rhs; return ret; } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::operator+=(const LiteMatrix&amp; rhs) { if (!isAddSubLegal(rhs)) throw std::range_error("Matrix sizes are not compatible\n"); std::transform(m_mat.begin(), m_mat.end(), rhs.m_mat.begin(), m_mat.begin(), std::plus&lt;&gt;()); return *this; } template&lt;typename T&gt; LiteMatrix&lt;T&gt; LiteMatrix&lt;T&gt;::operator-(const LiteMatrix&amp; rhs) { LiteMatrix ret(*this); ret -= rhs; return ret; } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::operator-=(const LiteMatrix&amp; rhs) { if (!isAddSubLegal(rhs)) throw std::range_error("Matrix sizes are not compatible\n"); std::transform(m_mat.begin(), m_mat.end(), rhs.m_mat.begin(), m_mat.begin(), std::minus&lt;&gt;()); return *this; } template&lt;typename T&gt; LiteMatrix&lt;T&gt; LiteMatrix&lt;T&gt;::operator*(const LiteMatrix&amp; rhs) { LiteMatrix ret(*this); ret *= rhs; return ret; } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::operator*=(const LiteMatrix&amp; rhs) { if (!isMultLegal(rhs)) throw std::range_error("Matrix index are not compatible\n"); LiteMatrix&lt;T&gt; temp(m_rows, rhs.m_cols); for (size_t i = 0; i &lt; m_rows; i++) { for (size_t j = 0; j &lt; m_cols; ++j) { for (size_t k = 0; k &lt; m_cols; ++k) { temp.m_mat[i * rhs.m_cols + j] += m_mat[i * m_cols + k] * rhs.m_mat[j + k * m_cols]; } } } *this = std::move(temp); return *this; } template&lt;typename T&gt; LiteMatrix&lt;T&gt; LiteMatrix&lt;T&gt;::operator*(const T&amp; rhs) { LiteMatrix ret(*this); ret *= rhs; return ret; } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::operator*=(const T&amp; rhs) { std::transform(m_mat.begin(), m_mat.end(), m_mat.begin(), std::bind(std::multiplies&lt;T&gt;(), std::placeholders::_1, rhs)); return *this; } template&lt;typename T&gt; T&amp; LiteMatrix&lt;T&gt;::operator()(const size_t&amp; rIndex, const size_t&amp; cIndex) { return m_mat[rIndex * m_cols + cIndex]; } template&lt;typename T&gt; bool LiteMatrix&lt;T&gt;::operator!=(const LiteMatrix&amp; rhs) const { bool isNotEqual = false; for (size_t i = 0; i &lt; m_rows; i++) { for (size_t j = 0; j &lt; m_cols; ++j) { isNotEqual = std::numeric_limits&lt;T&gt;::epsilon() &lt;= std::abs(m_mat[i * m_cols + j] - rhs.m_mat[i * m_cols + j]); if (isNotEqual) break; } } return isNotEqual; } template&lt;typename T&gt; bool LiteMatrix&lt;T&gt;::operator==(const LiteMatrix&amp; rhs) const { return !(*this != rhs); } template&lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const LiteMatrix&lt;T&gt;&amp; rhs) { for (size_t i = 0; i &lt; rhs.m_rows; ++i) { for (size_t j = 0; j &lt; rhs.m_cols; ++j) os &lt;&lt; std::setw(5) &lt;&lt; std::setprecision(2) &lt;&lt; rhs.m_mat[i * rhs.m_cols + j] &lt;&lt; ' '; os &lt;&lt; '\n'; } return os; } template&lt;typename T&gt; size_t LiteMatrix&lt;T&gt;::rowCount() const { return m_rows; } template&lt;typename T&gt; size_t LiteMatrix&lt;T&gt;::colCount() const { return m_cols; } template&lt;typename T&gt; bool LiteMatrix&lt;T&gt;::isAddSubLegal(const LiteMatrix&amp; rhs) const { return ((m_rows == rhs.m_rows) &amp;&amp; (m_cols == rhs.m_cols)); } template&lt;typename T&gt; bool LiteMatrix&lt;T&gt;::isMultLegal(const LiteMatrix&amp; rhs) const { return (m_cols == rhs.m_rows); } template&lt;typename T&gt; void LiteMatrix&lt;T&gt;::setMatrix(const std::vector&lt;T&gt;&amp; val) { std::copy(val.begin(), val.end(), m_mat.begin()); return; } template&lt;typename T&gt; void LiteMatrix&lt;T&gt;::setElement(const size_t row, const size_t col, const T&amp; val) { m_mat.at(row * m_rows + col) = val; return; } template&lt;typename T&gt; void LiteMatrix&lt;T&gt;::setRow(const size_t row, const std::vector&lt;T&gt; val) { if(row &gt;= m_rows) throw std::range_error("Matrix index is out of range\n"); if (val.size() &gt; m_cols) { throw std::range_error("Data size is too large\n"); } std::copy(val.begin(), val.end(), m_mat.begin() + row * m_cols); } template&lt;typename T&gt; void LiteMatrix&lt;T&gt;::setCol(const size_t col, const std::vector&lt;T&gt; val) { if (col &gt;= m_cols) throw std::range_error("Matrix index is out of range\n"); if (val.size() &gt; m_rows) { throw std::range_error("Data size is too large\n"); } for (size_t i = 0; i != val.size(); i++) { m_mat[col + i * m_rows] = val[i]; } } template&lt;typename T&gt; T LiteMatrix&lt;T&gt;::getElement(const size_t row, const size_t col) const { return m_mat.at(row * m_rows + col); } template&lt;typename T&gt; LiteMatrix&lt;T&gt;&amp; LiteMatrix&lt;T&gt;::transpose() { // TODO: insert return statement here if (m_cols != 1 &amp;&amp; m_rows != 1) { decltype(m_cols) colStart = 0; for (size_t i = 0; i &lt; m_rows; ++i) { for (size_t j = colStart; j &lt; m_cols; ++j) { std::iter_swap(m_mat.begin() + (i * m_cols + j), m_mat.begin() + (j * m_rows + i)); } ++colStart; } } std::swap(m_rows, m_cols); return *this; } </code></pre> <p>main.cpp</p> <pre><code>#include "LiteMatrix.h" #include &lt;iostream&gt; int main() { LiteMatrix&lt;double&gt; m1(2, 2); std::cout &lt;&lt; "Row Count: " &lt;&lt; m1.rowCount() &lt;&lt; std::endl; std::cout &lt;&lt; "Column Count: " &lt;&lt; m1.colCount() &lt;&lt; std::endl; LiteMatrix&lt;double&gt; m2(2, 2); std::cout &lt;&lt; m1.ones(); std::cout &lt;&lt; m2.ones(); LiteMatrix&lt;double&gt; m4(2, 2, std::vector&lt;double&gt;{1, 2, 3, 4}); LiteMatrix&lt;double&gt; m5(2, 1); m5.setMatrix(std::vector&lt;double&gt; {7.5, 10.8}); LiteMatrix&lt;double&gt; m6(3, 3, std::vector&lt;double&gt;{1, 2, 3, 4, 5, 6, 7, 8, 9}); std::cout &lt;&lt; "m6\n"; std::cout &lt;&lt; m6; std::cout &lt;&lt; m6.transpose(); LiteMatrix&lt;double&gt; m7(3, 1, std::vector&lt;double&gt;{1, 2, 3}); std::cout &lt;&lt; "m7\n"; std::cout &lt;&lt; m7; std::cout &lt;&lt; m7.transpose(); m1.setElement(0, 0, 19.0); std::cout &lt;&lt; m1.getElement(0, 0); std::cout &lt;&lt; "Is Addition Legal: " &lt;&lt; m1.isAddSubLegal(m2) &lt;&lt; std::endl; m1 += m1; std::cout &lt;&lt; "m1 + m2\n" &lt;&lt; m1 + m2; std::cout &lt;&lt; "m2 - m2\n" &lt;&lt; m2 - m2; std::cout &lt;&lt; "m1 * m2\n" &lt;&lt; m1 * m2; std::cout &lt;&lt; "m1 != m2: " &lt;&lt; (m1 != m2) &lt;&lt; std::endl; std::cout &lt;&lt; "m1 == m2: " &lt;&lt; (m1 == m2) &lt;&lt; std::endl; m1.ones(); std::cout &lt;&lt; "m1 != m2: " &lt;&lt; (m1 != m2) &lt;&lt; std::endl; std::cout &lt;&lt; "m1 == m2: " &lt;&lt; (m1 == m2) &lt;&lt; std::endl; LiteMatrix&lt;double&gt; m3(10, 10); m3.ones(); std::cout &lt;&lt; "Is Addition Legal: " &lt;&lt; m1.isAddSubLegal(m3) &lt;&lt; std::endl; m3.setRow(0, std::vector&lt;double&gt; {22, 33, 44, 55}); m3.setCol(9, std::vector&lt;double&gt; {66, 77, 88, 99}); std::cout &lt;&lt; m3; if(m1.isAddSubLegal(m3)) m3 += m1; return 0; } </code></pre>
[]
[ { "body": "<p>In the constructor that take a vector, you might want to validate the size and raise an exception if it does not match the expected size.</p>\n\n<p>Since you are using <code>operator()</code> to update a value, why not replace <code>getElement</code> by a const version of <code>operator()</code>? That way, you won't have to use different code for read and for write access.</p>\n\n<p><code>isAddSubLegal</code> and <code>isMultLegal</code> should probably be private as they are not intended for public use.</p>\n\n<p>I am not sure if <code>operator==</code> and <code>operator!=</code> should be declared. The fact that an epsilon is used for comparison is a red flag. If you need to compare with some tolerance, it might be preferable to use a function that take an additional parameter for the tolerance to use. For an internal library, I would not make such function available unless I actually need it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T21:32:40.063", "Id": "210842", "ParentId": "210791", "Score": "0" } }, { "body": "<h3>OverView</h3>\n\n<p>I understand that it is common to use <code>rows</code> and <code>cols</code> in the constructor. <strong>BUT</strong> if you use it as part of the type information you can do some compile time checks that prevents illegal expressions.</p>\n\n<p>For example: In multiplications. You can check that the size of the matrices are correct for the multiplication at compile time.</p>\n\n<p>The down size is that you can not have dynamically sized matrices. So it may not be appropriate for your use case.</p>\n\n<p>Its a matrix why do you not support standard matrix access operations?</p>\n\n<pre><code>LiteMatrix&lt;int&gt; x(15,5);\n\nstd::cout &lt;&lt; x[2][3] &lt;&lt; \"\\n\";\n// Much nicer than \nstd::cout &lt;&lt; x.getElement(2, 3) &lt;&lt; \"\\n\";\n</code></pre>\n\n<h3>CodeReview</h3>\n\n<p>Inside the class definition you don't need to specify the <code>&lt;T&gt;</code> everywhere. This is implicit as you are inside the <code>LiteMatrix</code> definition.</p>\n\n<pre><code>template&lt;typename T&gt;\nclass LiteMatrix\n{\n // STUFF\n LiteMatrix operator+(const LiteMatrix&lt;T&gt; &amp;rhs);\n LiteMatrix&amp; operator+=(const LiteMatrix&lt;T&gt;&amp; rhs);\n\n // STUFF\n template&lt;typename T&gt;\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const LiteMatrix&lt;T&gt;&amp; rhs);\n // STUFF\n}\n</code></pre>\n\n<p>This could simply be:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass LiteMatrix\n{\n // STUFF\n LiteMatrix operator+(const LiteMatrix&amp; rhs);\n LiteMatrix&amp; operator+=(const LiteMatrix&amp; rhs);\n\n // STUFF\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const LiteMatrix&amp; rhs);\n // STUFF\n}\n</code></pre>\n\n<p>You have a copy object.</p>\n\n<pre><code> void setMatrix(const std::vector&lt;T&gt;&amp; val);\n void setElement(const size_t row, const size_t col, const T&amp; val);\n</code></pre>\n\n<p>You might as well have also have a move version!</p>\n\n<pre><code> void setMatrix(std::vector&lt;T&gt;&amp;&amp; val);\n void setElement(const size_t row, const size_t col, T&amp;&amp; val);\n</code></pre>\n\n<p>You forgot the reference here:</p>\n\n<pre><code> // Passing by value is going to cause a copy of the array\n void setRow(const size_t row, const std::vector&lt;T&gt; val);\n void setCol(const size_t col, const std::vector&lt;T&gt; val);\n</code></pre>\n\n<p>When getting a value return by <code>const reference</code> to avoid an unnecessary copy.</p>\n\n<pre><code> T getElement(const size_t row, const size_t col) const;\n</code></pre>\n\n<p>I would also have a non cost version of this that returns a reference to the internal value. That way you can allow updates in a more normal matrix like way.</p>\n\n<p>Why not initialize the vector in the initializer list?</p>\n\n<pre><code>template&lt;typename T&gt;\nLiteMatrix&lt;T&gt;::LiteMatrix(const size_t &amp; rows, const size_t &amp; cols)\n : m_rows(rows), m_cols(cols)\n{\n m_mat = std::vector&lt;T&gt;(rows * cols);\n}\n</code></pre>\n\n<p>I would have just done:</p>\n\n<pre><code>template&lt;typename T&gt;\nLiteMatrix&lt;T&gt;::LiteMatrix(const size_t &amp; rows, const size_t &amp; cols)\n : m_rows(rows)\n , m_cols(cols)\n , m_mat(rows * cols)\n{}\n</code></pre>\n\n<p>Simply return the value of the expression.</p>\n\n<pre><code>template&lt;typename T&gt;\nLiteMatrix&lt;T&gt; LiteMatrix&lt;T&gt;::operator+(const LiteMatrix&amp; rhs)\n{\n // Simpler to write as:\n return LiteMatrix(*this) += rhs;\n}\n</code></pre>\n\n<p>Yes this works:</p>\n\n<pre><code>template&lt;typename T&gt;\nT&amp; LiteMatrix&lt;T&gt;::operator()(const size_t&amp; rIndex, const size_t&amp; cIndex)\n{\n return m_mat[rIndex * m_cols + cIndex];\n}\n</code></pre>\n\n<p>But much more traditional to use <code>operator[]</code> on matrix objects.\nsee: <a href=\"https://stackoverflow.com/a/1971207/14065\">https://stackoverflow.com/a/1971207/14065</a></p>\n\n<p>OK. I see what you are doing here:</p>\n\n<pre><code>template&lt;typename T&gt;\nbool LiteMatrix&lt;T&gt;::operator!=(const LiteMatrix&amp; rhs) const\n{\n // STUFF\n isNotEqual = std::numeric_limits&lt;T&gt;::epsilon() &lt;= \n std::abs(m_mat[i * m_cols + j] - rhs.m_mat[i * m_cols + j]);\n // STUFF\n}\n</code></pre>\n\n<p>This is correct. But personally I think I may have gone with some form of type specialization. That would have simply done the test on integer numbers and used epsilon on floating point numbers.</p>\n\n<p>So many lines for simply returning the value.\nI would have had these as single liners inside the class definition.</p>\n\n<pre><code>template&lt;typename T&gt;\nsize_t LiteMatrix&lt;T&gt;::rowCount() const\n{\n return m_rows;\n}\n\ntemplate&lt;typename T&gt;\nsize_t LiteMatrix&lt;T&gt;::colCount() const\n{\n return m_cols;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T04:47:26.660", "Id": "407911", "Score": "0", "body": "The comment of removing the <T> in the friend operator doesn't work. It needs to stay in there. When I wrote the code I referenced this and I couldn't get it to work otherwise, https://stackoverflow.com/a/4660153/10824002. Your post has been very helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T05:33:17.853", "Id": "407915", "Score": "0", "body": "@EddieC.Actually very sure that's not the case: http://cpp.sh/4r3wj The article you link shows a situation where `operator<<` is defined outside the class. In that situation you will need the `tempalte` stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:18:44.263", "Id": "408075", "Score": "0", "body": "I finally had a chance to try it again. if I don't include the <T> with operator<< I get a compiler error of cannot access private member in class LiteMatrix<double>. When I have the <T> the error goes away and the code works as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T06:16:04.913", "Id": "408082", "Score": "0", "body": "@EddieC. I know that it is not necessary. Could you put your code in a gist so I can see the exact code you are talking about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T05:29:29.040", "Id": "408256", "Score": "0", "body": "I put what I tried on gist. Sorry for the delay this is the time when i get on. https://gist.github.com/CodingEddie/49edfad9efca80897fb38d954091f425" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T17:49:22.997", "Id": "408415", "Score": "0", "body": "@EddieC. Yes you will need the template declaration when you do it outside the class. But anything inside the class declaration will not need it. Also the `friend` attribute is only useful inside the class declaration. If it is inside the `class declaration` you will not need to add the template parameters for the class you are defining." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T00:07:06.997", "Id": "210848", "ParentId": "210791", "Score": "4" } } ]
{ "AcceptedAnswerId": "210848", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T05:52:58.553", "Id": "210791", "Score": "3", "Tags": [ "c++", "matrix", "c++14", "template", "vectors" ], "Title": "Simple Matrix Template Class" }
210791
<p><a href="https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-changing-links/" rel="nofollow noreferrer">GeeksForGeeks challenge</a>:</p> <blockquote> <p>Given a singly linked list, write a function to swap nodes pairwise. </p> <p><strong>For example</strong> :</p> <p>if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5</p> </blockquote> <pre><code>#include &lt;iostream&gt; // structure of a Node in the linked list struct Node { int data; Node *next; }; // append data to end of linked list Node *append(Node *head, int data) { auto newNode = new Node{data, nullptr}; if (head == nullptr) return newNode; auto temp{head}; while (temp-&gt;next) temp = temp-&gt;next; temp-&gt;next = newNode; return head; } // display the list void display(Node *head) { std::cout &lt;&lt; "The list : \t"; while (head != nullptr) { std::cout &lt;&lt; head-&gt;data &lt;&lt; " "; head = head-&gt;next; } std::cout &lt;&lt; std::endl ; } // pairwise swap of the elements in the given linked lists void pairwiseSwap(Node **head_ref) { if(((*head_ref) == nullptr) || ((*head_ref)-&gt;next == nullptr)) return ; Node *temp1 = nullptr, *temp2 = nullptr ; Node *prev = nullptr, *curr =(*head_ref) ; while(curr != nullptr) { // temp1 : first element of the pair // temp2 : second element of the pair temp1 = curr; temp2 = curr-&gt;next; // if the the 2nd element in the pair is nullptr, then exit the loop if(temp2 == nullptr){ break ; } // curr = curr-&gt;next-&gt;next ; // if the current element is head, then previous one must be nullptr // In either case swapping the nodes if(prev == nullptr){ prev = temp1; temp1-&gt;next = temp2-&gt;next; temp2-&gt;next = temp1; (*head_ref) = temp2 ; } else { temp1-&gt;next = temp2-&gt;next; temp2-&gt;next = temp1; prev-&gt;next = temp2; prev = temp1; } // moving to the next pair of nodes curr = temp1-&gt;next ; } } // Driver function int main() { Node *a = nullptr ; // for odd number of nodes a = append(a, 15); a = append(a, 10); a = append(a, 5); a = append(a, 20); a = append(a, 3); // a = append(a, 2); pairwiseSwap(&amp;a); display(a); // for even number of nodes a = append(a, 15); a = append(a, 10); a = append(a, 5); a = append(a, 20); a = append(a, 3); a = append(a, 2); pairwiseSwap(&amp;a); display(a); } </code></pre>
[]
[ { "body": "<p>It's weird that you picked <code>append</code> as your primitive for building test cases, when <code>prepend</code> would be so much simpler and faster — <code>O(1)</code> instead of <code>O(n)</code>.</p>\n\n<hr>\n\n<pre><code>auto newNode = new Node{data, nullptr};\n</code></pre>\n\n<p>This is a very \"modern\" way of writing what would be more idiomatically written as</p>\n\n<pre><code>Node *newNode = new Node(data, nullptr);\n</code></pre>\n\n<p>I would weakly recommend the latter. And I would <em>strongly</em> recommend, if you do nothing else, at least calling out explicitly when you're working with raw (non-owning) pointers:</p>\n\n<pre><code>auto *newNode = new Node{data, nullptr}; // the asterisk means watch out!\n</code></pre>\n\n<hr>\n\n<pre><code>auto temp{head};\n</code></pre>\n\n<p>Again, I'd write simply</p>\n\n<pre><code>Node *temp = head;\n</code></pre>\n\n<p>or at least</p>\n\n<pre><code>auto *temp = head;\n</code></pre>\n\n<p>The <code>*</code> signals the reader to watch out for pointer pitfalls (aliasing, memory leaks); the <code>=</code> signals the reader that an initialization is happening here. You might be surprised how easy it is to glance over <code>auto temp{head};</code> surrounded by other lines of code and not even recognize that it's <em>introducing the name <code>temp</code>!</em></p>\n\n<hr>\n\n<pre><code>// pairwise swap of the elements in the given linked lists\nvoid pairwiseSwap(Node **head_ref) {\n</code></pre>\n\n<p>Some coding guidelines tell you to pass the inout parameter <code>head_ref</code> by pointer here, instead of by reference. I'm going to assume you're following one of those guidelines.</p>\n\n<hr>\n\n<pre><code>return ;\n</code></pre>\n\n<p>is an unidiomatic whitespace style; most programmers would write</p>\n\n<pre><code>return;\n</code></pre>\n\n<p>You actually put an extra space before a <em>lot</em> of semicolons in this function (but not consistently). Are you French? ;)</p>\n\n<hr>\n\n<p>You should definitely factor out the \"swap two nodes\" functionality into a named function. I somewhat suspect that this would do, but you'd have to draw it out on paper...</p>\n\n<pre><code>void swap_two_nodes(Node *&amp;p, Node *&amp;q) {\n assert(p-&gt;next == q);\n std::swap(p, q);\n}\n</code></pre>\n\n<p>Alternatively — and since I've confused myself ;) — you could just write a recursive version of the whole thing:</p>\n\n<pre><code>Node *pairwise_swap(Node *head) {\n if (head &amp;&amp; head-&gt;next) {\n Node *first = head-&gt;next;\n Node *second = head;\n Node *tail = pairwise_swap(head-&gt;next-&gt;next);\n head = first;\n first-&gt;next = second;\n second-&gt;next = tail;\n }\n return head;\n}\n</code></pre>\n\n<p>Turning this into tail-recursion is left as an (easy) exercise for the reader.</p>\n\n<hr>\n\n<pre><code>// for even number of nodes\na = append(a, 15); \n</code></pre>\n\n<p>Appending an even number of nodes to an odd-length list does <em>not</em> result in an even-length list. Did you try <em>running</em> your test code? Did you look at the output and verify that it was correct? You should have!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T06:53:39.993", "Id": "210793", "ParentId": "210792", "Score": "2" } }, { "body": "<p>Looking at just your <code>pairwiseSwap()</code> function… there are too many special cases.</p>\n\n<p>Every iteration through the loop should verify that there are at least two more elements to process. You shouldn't need a special case to check for <code>if(((*head_ref) == nullptr) || ((*head_ref)-&gt;next == nullptr)) return ;</code> to start.</p>\n\n<p>On the other hand, the loop condition should make it clear that at least two nodes are required to proceed. You've obfuscated the check for the second node as <code>if(temp2 == nullptr) { break ; }</code>.</p>\n\n<p>You then have a special case for the first iteration (<code>// if the current element is head, then previous one must be nullptr</code>). That special case would be better handled by introducing a <code>preHead</code> object, whose <code>next</code> points to the original head node.</p>\n\n<p>After eliminating the special cases as described above, and renaming <code>temp1</code> → <code>a</code> and <code>temp2</code> → <code>b</code> (because \"temp\" is nearly always meaningless in a variable name), we get this simple solution:</p>\n\n<pre><code>void pairwiseSwap(Node **head) {\n Node preHead{0, *head};\n for (Node *prev = &amp;preHead, *a, *b; (a = prev-&gt;next) &amp;&amp; (b = a-&gt;next); prev = a) {\n a-&gt;next = b-&gt;next;\n b-&gt;next = a;\n prev-&gt;next = b;\n }\n *head = preHead.next;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T07:53:28.113", "Id": "210795", "ParentId": "210792", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T05:55:07.150", "Id": "210792", "Score": "1", "Tags": [ "c++", "c++11", "linked-list" ], "Title": "Pairwise swap elements of a given linked list by changing links" }
210792
<p>I wrote a macro which works, but given the large amount of data, it takes a lot of time. I wonder if there is a way to speed it up. Here is a summary of what it does:</p> <ol> <li>In "Summary (All)" tab I have global sheet with all the data.</li> <li>I have several tabs corresponding to the each months.</li> <li>I want to have the data distributed to those tabs, based on the value in one column (should match the tab name). </li> </ol> <p>My code</p> <pre><code>Option Explicit Sub CopyDataOutToSheets() Dim sh As Worksheet Dim SourceSh As Worksheet Dim Last As Long Dim shLast As Long Dim CopyRng As Range Dim StartRow As Long Dim lrow As Long Dim r As Long With Application .ScreenUpdating = False .EnableEvents = False End With Set SourceSh = ActiveWorkbook.Worksheets("Summary (All)") Application.DisplayAlerts = False On Error Resume Next On Error GoTo 0 For Each sh In ActiveWorkbook.Worksheets If IsError(Application.Match(sh.Name, _ Array(SourceSh.Name, "List Data", _ "Lists", "Summary (Filtered)"), 0)) Then lrow = lastRow(sh) If lrow &gt; 6 Then sh.Rows("7:" &amp; lrow).Delete End If If lastRow(SourceSh) &lt; 7 Then MsgBox ("Nothing to move") Exit Sub End If For r = lastRow(SourceSh) To 7 Step -1 'Finding the first empty row in column A on destination worksheet If SourceSh.Range("N" &amp; r).Value = sh.Name Then SourceSh.Rows(r).Copy Destination:= _ sh.Range("A" &amp; lastRow(sh) + 1) End If Next r End If Next ExitTheSub: Application.Goto SourceSh.Cells(1) Application.DisplayAlerts = True With Application .ScreenUpdating = True .EnableEvents = True End With End Sub </code></pre> <p>There are few thousands rows in global tab, so I'm expecting to have roughly 1000 in each tab after distribution. Could you please let me know what would be the best way to make it happen more quickly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:06:18.957", "Id": "407583", "Score": "0", "body": "A review of your code that includes style and several suggestions for improvements can be found in answer to [your related question](https://stackoverflow.com/a/54008383/4717755), though your other question concerns in the input side of things. Your code here would greatly benefit from applying the same suggestions. Additionally, look at how to [transfer data from a worksheet to a memory array and back](https://excelmacromastery.com/excel-vba-array/) which will help you in speeding up your macro by quite a bit." } ]
[ { "body": "<p>Maybe <code>Dim SourceSh As Variant</code> and instead of working out of the worksheet, <code>SourceSh</code> will equal your worksheet. By putting the worksheet into an <code>Array</code> (puts it in memory) you will work a ton quicker on all your loops. I had a similar issue a few weeks ago, splitting a master sheet (data draw) into month tabs.</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=h9FTX7TgkpM&amp;list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5&amp;index=28\" rel=\"nofollow noreferrer\">WiseOwl</a> has a good video on Arrays. <a href=\"https://www.youtube.com/watch?v=h9FTX7TgkpM&amp;list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5&amp;index=28\" rel=\"nofollow noreferrer\">Here</a> is my post and the answer I received, a lot of solid advice!</p>\n\n<p>Since I am still practicing, I will take a crack at it, update your question with information like an example of the data you are moving, the sheets and anything else that you think is relevant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T02:12:38.833", "Id": "211006", "ParentId": "210804", "Score": "0" } }, { "body": "<p>Use any method that make a \"directly-interation\" with worksheet like copy, paste, <code>range.value = something (...)</code> intensifies the runtime of the code. To solve this you need to create an array to store the <code>SourceSh.Rows(r)</code> values. Before the loop change spreadsheet you parse all values stored in the array to cells using the method that I will show in the example. When the loop change spreadsheet you clear the array.</p>\n\n<p>With that I think that you will have at least 65% better performance.</p>\n\n<p>I created an example comparing runtime of the array method with the single value method, \nto 20k cells. See the difference?</p>\n\n<p>[<img src=\"https://i.stack.imgur.com/9VwqX.png\" alt=\"Result image[1]\"></p>\n\n<pre><code>Sub Compare()\n\nDim arr() As Variant\nDim max As Long\nDim start As Double\n\nstart = Timer\n\nmax = 20000\nReDim arr(max)\n\nApplication.ScreenUpdating = False\n\n'Using the array method\n\nFor i = 1 To max\n\n arr(i) = i\n\nNext i\n\nSheets(\"Planilha1\").Range(\"A1:A\" &amp; UBound(arr) + 1) = WorksheetFunction.Transpose(arr)\nDebug.Print \"Array method in seconds: \" &amp; Round(Timer - start, 2)\n\n\n'Parsing single values method\n\nstart = Timer\n\nFor i = 1 To UBound(arr)\n\n Sheets(\"Planilha1\").Range(\"A1:A\" &amp; UBound(arr) + 1) = i\n\nNext i\n\nDebug.Print \"Value method in seconds: \" &amp; Round(Timer - start, 2)\n\n\nApplication.ScreenUpdating = True\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:22:40.980", "Id": "211187", "ParentId": "210804", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T10:02:02.400", "Id": "210804", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Macro to distribute data within the sheets based on tabs name" }
210804
<p>If one menu-item is clicked then the description with the same data-filter attribute should be shown.</p> <p>I added a class to the description elements to associate each one with the affiliated menu item.</p> <p>What do you think?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(".button").click(function() { $(".button").removeClass("active-filter"); $(this).addClass("active-filter"); var button = $(this).attr("data-filter"); var active_element = $('.descr[data-filter="' + button + '"]'); $(".descr").removeClass("active-element"); active_element.addClass("active-element"); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.element { display: inline-block; background-color: lightgreen; width: 220px; } .filter { display: inline-block; margin: 10px; background-color: orange; } .button { width: 60px; height: 60px; padding: 10px; margin: 10px; background-color: lightgrey; float: left; } .descr { display: block; max-height: 0; visibility: hidden; background-color: lightgrey; padding: 10px; position: absolute; top: 0; left: 0; right: 0; margin: 10px; } .data-element { height: 60px; display: block; background-color: orange; margin: 10px; position: relative; } .active-filter { background-color: yellow; display: block; } .active-element { background-color: yellow; max-height: 100%; visibility: visible; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="element"&gt; &lt;div class="filter"&gt; &lt;div class="button active-filter" data-filter="3"&gt;data-filter 1&lt;/div&gt; &lt;div class="button" data-filter="4"&gt;data-filter 2&lt;/div&gt; &lt;/div&gt; &lt;div class="data-element"&gt; &lt;div class="descr active-element" data-filter="3"&gt;data-element 1&lt;/div&gt; &lt;div class="descr" data-filter="4"&gt;data-element 2&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T13:33:04.323", "Id": "407509", "Score": "0", "body": "Just to clarify, you are talking about this line being not so elegant right? `var active_element = $('.d[data-filter=\"' + b + '\"]');`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:37:08.930", "Id": "407542", "Score": "1", "body": "@JoopEggen The code at the question does work as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:52:02.663", "Id": "407543", "Score": "0", "body": "@guest271314 sorry, \"I don't get it right\" and some code that looked to me not so okay made me add the comment. Thanks very much for preventing the OP to be stalled." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:59:56.850", "Id": "407545", "Score": "0", "body": "@JoopEggen It appears OP at some attempted to use `.find()` or `.filter()` to chain jQuery methods, instead of declaring multiple variables." } ]
[ { "body": "<p>One purpose for using jQuery is the ability to chain methods. You can first remove the <code>\"active-element\"</code> class from <code>.d</code>, then utilize <code>.filter()</code> with a single line passed as parameter within a template literal which removes the <code>\"active-filter\"</code> class from <code>.b</code> elements, filters and adds the same class to <code>this</code> element, and concludes by returning the <code>.data()</code> of the current element, which is the attribute value selector to match the corresponding <code>.d</code> element where the <code>\"active-element\"</code> class is added.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\".b\").click(function(e) {\n $(\".d\").removeClass(\"active-element\")\n .filter(`[data-filter='${\n $(\".b\").removeClass(\"active-filter\")\n .filter(this).addClass(\"active-filter\")\n .data().filter\n }']`)\n .addClass(\"active-element\");\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.b {\n width: 60px;\n height: 60px;\n padding: 10px;\n margin: 10px;\n background-color: lightgrey;\n float: left;\n}\n\n.c {\n width: 60px;\n height: 60px;\n padding: 10px;\n margin: 10px;\n background-color: lightgrey;\n float: left;\n}\n\n.element {\n float: left;\n display: block;\n}\n\n.active-filter {\n background-color: pink;\n}\n\n.active-element {\n background-color: yellow;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;div class=\"element\"&gt;\n &lt;div&gt;\n &lt;div class=\"b active-filter\" data-filter=\"3\"&gt;data-filter&lt;/div&gt;\n &lt;div class=\"b\" data-filter=\"4\"&gt;data-filter&lt;/div&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;div class=\"c d\" data-filter=\"3\"&gt;data-element&lt;/div&gt;\n &lt;div class=\"c d\" data-filter=\"4\"&gt;data-element&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:30:06.497", "Id": "210825", "ParentId": "210811", "Score": "1" } }, { "body": "<p>The code looks okay. The Javascript code looks somewhat simple but then again it is jQuery code. There are some inefficiencies - for example, the DOM elements are not cached so on every click there are at least three DOM queries. This could be improved by storing those references in variables when the DOM is ready - typically done with the jQuery DOM ready callback - <code>$(function() { ... })</code> (formerly <a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\"><code>$(document).ready(function() { ... });</code></a> but as of version 3 that is deprecated<sup><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">1</a></sup>. Once the DOM elements are stored after the DOM is ready, the description elements can later be filtered using the <a href=\"http://api.jquery.com/filter/\" rel=\"nofollow noreferrer\"><code>.filter()</code></a> method.</p>\n\n<p>The <a href=\"http://api.jquery.com/data/\" rel=\"nofollow noreferrer\"><code>.data()</code></a> method could also be used to simplify the lookup of <a href=\"https://html.spec.whatwg.org/multipage/dom.html#dom-dataset\" rel=\"nofollow noreferrer\">the dataset attributes</a>.</p>\n\n<p>The name <code>button</code> for the variable to store the value of the attribute <code>data-filter</code> feels a little misleading.</p>\n\n<blockquote>\n<pre><code>var button = $(this).attr(\"data-filter\");\n</code></pre>\n</blockquote>\n\n<p>A more appropriate name would be <code>filterValue</code> or something along those lines.</p>\n\n<h3>A rewrite</h3>\n\n<p>The re-written code utilizes the advice above.</p>\n\n<p>I tried to find a way to utilize <a href=\"http://api.jquery.com/toggleClass\" rel=\"nofollow noreferrer\"><code>.toggleClass()</code></a> to simplify adding and removing classes but I couldn't find anything that was any simpler.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(function() {//DOM ready\n var buttons = $('.button');\n var descriptions = $('.descr');\n buttons.click(function() {\n buttons.removeClass(\"active-filter\");\n $(this).addClass(\"active-filter\");\n var filterValue = $(this).data('filter');\n var active_element = descriptions.filter('[data-filter=\"' + filterValue + '\"]');\n\n descriptions.removeClass(\"active-element\");\n active_element.addClass(\"active-element\");\n });\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.element {\n display: inline-block;\n background-color: lightgreen;\n width: 220px;\n}\n\n.filter {\n display: inline-block;\n margin: 10px;\n background-color: orange;\n}\n\n.button {\n width: 60px;\n height: 60px;\n padding: 10px;\n margin: 10px;\n background-color: lightgrey;\n float: left;\n}\n\n.descr {\n display: block;\n max-height: 0;\n visibility: hidden;\n background-color: lightgrey;\n padding: 10px;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n margin: 10px;\n}\n\n.data-element {\n height: 60px;\n display: block;\n background-color: orange;\n margin: 10px;\n position: relative;\n}\n\n.active-filter {\n background-color: yellow;\n display: block;\n}\n\n.active-element {\n background-color: yellow;\n max-height: 100%;\n visibility: visible;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;div class=\"element\"&gt;\n &lt;div class=\"filter\"&gt;\n &lt;div class=\"button active-filter\" data-filter=\"3\"&gt;data-filter 1&lt;/div&gt;\n &lt;div class=\"button\" data-filter=\"4\"&gt;data-filter 2&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"data-element\"&gt;\n &lt;div class=\"descr active-element\" data-filter=\"3\"&gt;data-element 1&lt;/div&gt;\n &lt;div class=\"descr\" data-filter=\"4\"&gt;data-element 2&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sup>1</sup><sub><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">https://api.jquery.com/ready/</a></sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T20:58:06.610", "Id": "211351", "ParentId": "210811", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T12:32:31.110", "Id": "210811", "Score": "2", "Tags": [ "javascript", "jquery", "html", "css", "event-handling" ], "Title": "Simple menu with descriptions" }
210811
<p>To become more familiar with templates I attempted a doubly linked list implementation in C++. Is this a valid use for a template?</p> <pre><code>template &lt;class T&gt; struct LinkedListNode { LinkedListNode&lt;T&gt;* m_previous; T m_data; LinkedListNode&lt;T&gt;* m_next; }; template &lt;class T&gt; class LinkedList { public: LinkedList() { m_head = nullptr; } LinkedListNode&lt;T&gt;* m_head; void InsertEnd(T data); void InsertFront(T data); }; template&lt;class T&gt; inline void LinkedList&lt;T&gt;::InsertFront(T data) { LinkedListNode&lt;T&gt;* insertedNode = new LinkedListNode&lt;T&gt;(); LinkedListNode&lt;T&gt;* firstNode = m_head; if (!firstNode) { insertedNode-&gt;m_data = data; insertedNode-&gt;m_next = nullptr; insertedNode-&gt;m_previous = nullptr; m_head = insertedNode; } else { while (firstNode-&gt;m_previous != nullptr) { firstNode = firstNode-&gt;m_previous; } insertedNode-&gt;m_next = firstNode; insertedNode-&gt;m_previous = nullptr; insertedNode-&gt;m_data = data; firstNode-&gt;m_previous = insertedNode; m_head = insertedNode; } } template&lt;class T&gt; inline void LinkedList&lt;T&gt;::InsertEnd(T data) { LinkedListNode&lt;T&gt;* insertedNode = new LinkedListNode&lt;T&gt;(); LinkedListNode&lt;T&gt;* lastNode = m_head; if (!lastNode) { insertedNode-&gt;m_data = data; insertedNode-&gt;m_next = nullptr; insertedNode-&gt;m_previous = nullptr; m_head = insertedNode; } else { while (lastNode-&gt;m_next != nullptr) { lastNode = lastNode-&gt;m_next; } lastNode-&gt;m_next = insertedNode; insertedNode-&gt;m_previous = lastNode; insertedNode-&gt;m_next = nullptr; insertedNode-&gt;m_data = data; m_head = insertedNode; } } </code></pre> <p>main.cpp</p> <pre><code>LinkedList&lt;int&gt;* linkedList = new LinkedList&lt;int&gt;(); linkedList-&gt;InsertEnd(2); linkedList-&gt;InsertEnd(5); linkedList-&gt;InsertEnd(9); linkedList-&gt;InsertFront(1); linkedList-&gt;InsertEnd(10); LinkedList&lt;std::string&gt;* stringList = new LinkedList&lt;std::string&gt;(); stringList-&gt;InsertFront("one"); stringList-&gt;InsertEnd("two"); stringList-&gt;InsertFront("three"); </code></pre> <p>Ordering should be <strong>linkedList</strong> <code>1,2,5,9,10</code> <strong>stringList</strong> <code>three,one,two</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:32:30.560", "Id": "407526", "Score": "1", "body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information. Specifically `InsertEnd` is faulty. Have you tested this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:46:30.607", "Id": "407530", "Score": "0", "body": "@Edward Hi, thanks for the reply. I have tested the code and it runs fine for me and I have debugged this to ensure the ordering is correct, unless there are other cases that I have missed that produces incorrect results. I am not looking for help in fixing the code, but rather whether it is a correct usage for templates, and/or if anything could be done better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:49:53.253", "Id": "407531", "Score": "1", "body": "Strengths of a doubly linked list are constant time front, back and random insertion/lookup/removal. The given implementation does neither of those operations in constant time (no lookup/removal at all, no random insertion, front and back insertion in linear time). (Just voicing my expectations when I hear \"doubly linked list\" - this doesn't mean your code is wrong, just that the implementation didn't match my expectations from the title)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T15:53:38.723", "Id": "407532", "Score": "0", "body": "@hoffmale Thanks for the reply. I agree the implementation is not finished, I was more focused on the approach, template usage, inline functions etc... and whether or not they were correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:00:15.023", "Id": "407533", "Score": "2", "body": "It would be useful if you augmented the question with the code you used to test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:02:56.133", "Id": "407535", "Score": "0", "body": "@jjmcc I'm not sure it's worth a close vote but you should have finished implementing at least the fundamental features. removal and access are critical to a container and I'm not sure there is much to review without those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:07:18.807", "Id": "407538", "Score": "1", "body": "@bruglesco I will finish the implementation then. Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:38:29.940", "Id": "407556", "Score": "0", "body": "Just a recommendation: The node class is so closely linked to the list that it likely will not exist on its own - so you might prefer making node a nested class of list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T20:19:08.467", "Id": "407601", "Score": "0", "body": "To simplify code, you might implement a circular list with a dummy element at the expense of 1 waste node." } ]
[ { "body": "<p>The biggest thing I can say about your code is don't use raw pointers, start getting into the habit of using <a href=\"https://en.cppreference.com/w/cpp/memory\" rel=\"nofollow noreferrer\">smart pointers</a>.</p>\n\n<blockquote>\n <p>Smart pointers enable automatic, exception-safe, object lifetime management.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:09:28.723", "Id": "210823", "ParentId": "210819", "Score": "1" } }, { "body": "<p><strong>InsertFront</strong>:</p>\n\n<p><code>m_head</code> should always point to the first node. So <code>while (firstNode-&gt;m_previous != nullptr)</code> loop looks unnecessary to me. If you're concerned about having <code>m_head</code> changed by the caller then i would make <code>m_head</code> private and provide getter method for that. Than you can merge if/else blocks as they are very similar.</p>\n\n<p><strong>InsertEnd</strong>:</p>\n\n<p>Instead of iterating to find the last node every time (which makes it O(n)), you may maintain another pointer which always points to the last node. After that you may merge if/else blocks.</p>\n\n<p>AFAIK following style of initializing class variables are more preferred.</p>\n\n<pre><code>LinkedList(): m_head(nullptr) {\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T16:41:08.517", "Id": "210826", "ParentId": "210819", "Score": "1" } } ]
{ "AcceptedAnswerId": "210823", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:44:01.790", "Id": "210819", "Score": "0", "Tags": [ "c++", "linked-list" ], "Title": "Doubly linked list C++" }
210819
<p>My problem is this causes more lag as time goes on. I use this commonly to chat with my friends, and I need it the site to update in real-time whenever a message gets edited/deleted/added. Any solutions?</p> <pre><code>function update(){ var i = 0; var leadsRef = firebase.database().ref(room); leadsRef.on('value', function(snapshot) { var old_room = room; snapshot.forEach(function(childSnapshot) { var childData = childSnapshot.val(); if(i === 0){ document.getElementById("comments").innerHTML = ""; } document.getElementById("comments").innerHTML += encode(childData.datee); document.getElementById("comments").innerHTML += " "; document.getElementById("comments").innerHTML += encode(childData.namee); document.getElementById("comments").innerHTML += ": "; document.getElementById("comments").innerHTML += encode(childData.contentss); document.getElementById("comments").innerHTML += "&lt;br&gt;"; i += 1 }); i = 0; return 0; }); } window.setInterval(update, 100); </code></pre> <p>The full code can be found <a href="https://github.com/MilkyWay90/MilkyWay90.github.io/blob/master/chat.html" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:59:59.560", "Id": "407558", "Score": "2", "body": "What do you mean by _\"I need it to be real-time.\"_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:02:52.887", "Id": "407559", "Score": "0", "body": "@guest271314 As in the site should update in real-time when somebody types in a message" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:07:17.433", "Id": "407560", "Score": "0", "body": "Have you tried using a `<form>` element, and either `change` of `input` event attached to a `<textarea>` or `<input type=\"text\">` element, or an `<input type=\"submit\">` for the user to press when they want to send a message? Am not certain about why `setInterval` is being used, though should be able to be substituted for `requestAnimationFrame` and logic within the function body. Does the code at the question currently produce the expected result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:10:19.080", "Id": "407563", "Score": "0", "body": "@guest271314 Not sure hwo to do that, could you put the complete code in an answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:12:53.143", "Id": "407564", "Score": "0", "body": "Have not tried Firebase. Why does `update` need to be called every `100` milliseconds to re-declare `leadsRef` and reattach `value` event to `leadsRef` variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:14:03.303", "Id": "407565", "Score": "0", "body": "@guest271314 I am not sure how to change the text only when the database has changed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:14:42.147", "Id": "407566", "Score": "0", "body": "What triggers `value` event attached to `leadsRef` to be dispatched?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:18:41.917", "Id": "407567", "Score": "0", "body": "@guest271314 Can you automatically move this discussion to chat? It's not letting me saying you're suspended from chatting. I dont know when it is dispatched" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:26:35.070", "Id": "407569", "Score": "0", "body": "@MilkyWay90 Can you list the properties of `childData`? Does it have more than just `datee`, `namee`, and `contentss`? Such as an `id` or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:28:42.583", "Id": "407571", "Score": "0", "body": "@202_accepted No. I made a link to the full code which tell you the answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:29:08.993", "Id": "407572", "Score": "0", "body": "@MilkyWay90 Am banned from chat at SE sites as the message you got states. It appears that you need to first understand what your own code does before asking how to improve your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:30:04.720", "Id": "407573", "Score": "0", "body": "@guest271314 Oh. So should I delete the question because I need to know what my code does before asking?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:30:31.847", "Id": "407574", "Score": "0", "body": "@guest271314 or should I ask on StackOverflow pretty quickly and just come back hee with the answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:31:30.207", "Id": "407575", "Score": "1", "body": "@MilkyWay90 That would be a practical first step. You could ask on SO, though you would still be in the position of clearly not knowing what your own code is doing, nor precisely what the expected result is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:31:33.723", "Id": "407576", "Score": "1", "body": "@MilkyWay90 Any and all code relevant to the problem should be embedded in the question, linking off-site is not permitted, as described in the help-center: https://codereview.stackexchange.com/help/on-topic. Additionally, you should fully understand what the code does, and it sounds like you may not, though I'm going to give you the benefit of the doubt and assume you do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:34:17.217", "Id": "407577", "Score": "2", "body": "Additionally, the root of your problem is the `+=` and constant reloading of _all_ messages, you need to find a way to track what the \"last\" message was and only load \"new\" messages, that will be the first step towards success." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:35:44.823", "Id": "407579", "Score": "0", "body": "@202_accepted Got it! I think that should be my answer, so can you put that in an answer and I'll accept it." } ]
[ { "body": "<h1>1. Leaking</h1>\n\n<p>Between:</p>\n\n<pre><code>window.setInterval(update, 100);\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>leadsRef.on('value', function(snapshot) {...}\n</code></pre>\n\n<p>You are adding a new copy of the event handler every 100ms. which just stacks the handle so it runs (time elapsed since page load)/100ms times every time data hits the pipe. </p>\n\n<p>Setting your on('value') handler should fire every time firebase get new data. It's a watcher you've got here not a getter.</p>\n\n<h1>2. Redundant Look ups</h1>\n\n<pre><code>document.getElementById(\"comments\")\n</code></pre>\n\n<p>This can be held in a variable and reused rather than finding the element for every stub of text.</p>\n\n<h1>3. innerHTML</h1>\n\n<p>Setting innerHTML from user input is considered bad practice, use innerText instead. Also build you full string(if possible) and and update all at once, this limits the browser having to re-render the page</p>\n\n<h1>4. Data / Output Structure</h1>\n\n<p>Each message is an individual item and should be treated as such, showing all the messages into a single p element muddies the distinction and make addressing an individual item difficult if desired</p>\n\n<h1>Other/Misc</h1>\n\n<p>You should be able to replace the provided code with somthing like this (warning untested, also assumes comments is a div not a p as in the linked code):</p>\n\n<pre><code>firebase.database().ref(room).on('value', function (snapshot) {\n var comments = [];\n var commentParent = document.getElementById(\"comments\")\n snapshot.forEach(function (childSnapshot) {\n var childData = childSnapshot.val();\n var commentElm = document.createElement(\"div\");\n commentElm.setAttribute(\"class\", \"comment\")\n commentElm.innerText = encode(childData.datee) + \" \" + encode(childData.namee) + \": \" + encode(childData.contentss);\n comments.push(commentElm)\n });\n commentParent.innerHTML=''\n commentParent.append(...comments)\n return 0;\n});\n</code></pre>\n\n<p>Also there is an additional bug with room handling, when changing rooms the handler should be removed and recreated for the new room.</p>\n\n<p>And your linked code pollutes all over the global space >.> not as important since it's not a shared lib but it still rubs me the wrong way.</p>\n\n<p>jsfiddle: <a href=\"https://jsfiddle.net/plloi/fc37pmqa/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/plloi/fc37pmqa/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:49:54.753", "Id": "407595", "Score": "0", "body": "Keeps on outputting \"[object HTMLDivElement],\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:53:10.333", "Id": "407596", "Score": "0", "body": "Missed a spread operator, updated" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:53:55.593", "Id": "407597", "Score": "0", "body": "Okay, let me test it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:56:22.513", "Id": "407598", "Score": "0", "body": "Okay, that issue is resolved, but now it keeps on outputting the entire script every second" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:56:54.837", "Id": "407599", "Score": "0", "body": "Like if it said \"MW90: hi\", it would keep on outputting \"MW90: hi\" every second. Wait, that just can be fixed by setting document.getElementById(\"comments\") to []" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T20:03:52.060", "Id": "407600", "Score": "0", "body": "Squashed a bug, added a link to jsfiddle, slightly less untested." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:42:59.223", "Id": "210838", "ParentId": "210829", "Score": "1" } } ]
{ "AcceptedAnswerId": "210838", "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T17:51:48.640", "Id": "210829", "Score": "-2", "Tags": [ "javascript", "performance", "html5", "firebase" ], "Title": "Updating text with JavaScript and Firebase" }
210829
<p>I'm very new to Haskell's ReadP library, and the entire concept of parser combinators, so I was wondering whether there are better ways to do some things in this program:</p> <pre><code>import Text.ParserCombinators.ReadP import Control.Applicative import Data.List data Operator = Add | Subtract instance Show Operator where show Add = "+" show Subtract = "-" instance Read Operator where readsPrec _ "+" = [(Add, "")] readsPrec _ "-" = [(Subtract, "")] readsPrec _ _ = [] data Expression = Number Int | Infix { left :: Expression, op :: Operator, right :: Expression } instance Show Expression where show (Number x) = show x show (Infix left op right) = "(" ++ (show left) ++ " " ++ (show op) ++ " " ++ (show right) ++ ")" digit :: ReadP Char digit = satisfy $ \char -&gt; char &gt;= '0' &amp;&amp; char &lt;= '9' number :: ReadP Expression number = fmap (Number . read) (many1 digit) operator :: ReadP Operator operator = fmap read (string "+" &lt;|&gt; string "-") expression :: ReadP Expression expression = do skipSpaces left &lt;- number skipSpaces op &lt;- Control.Applicative.optional operator case op of Nothing -&gt; return left Just op -&gt; do skipSpaces right &lt;- expression return (Infix left op right) parseExpression :: String -&gt; Maybe Expression parseExpression input = case readP_to_S expression input of [] -&gt; Nothing xs -&gt; (Just . fst . last) xs </code></pre> <p>The main area where I'm looking for improvements is the <code>expression</code> function, and specifically the things which seem improvable are the repeated calls to <code>skipSpaces</code> and the case expression to check whether an operator was parsed, but of course if you notice anything else that would be helpful too!</p>
[]
[ { "body": "<p>First, a standard approach for dealing with the <code>skipSpaces</code> issue is to define a higher-order parser combinator, traditionally called <code>lexeme</code>:</p>\n\n<pre><code>lexeme :: ReadP a -&gt; ReadP a\nlexeme p = p &lt;* skipSpaces\n</code></pre>\n\n<p>Here, <code>lexeme</code> takes a space-naive parser <code>p</code>, and converts it into a new parser that parses whatever <code>p</code> was planning to parse, and then reads and discards any trailing spaces. You use <code>lexeme</code> in the definitions of any of your parsers that would reasonably be assumed to read a complete \"lexeme\" and ignore any trailing space. For example, <code>number</code> should be a <code>lexeme</code> parser:</p>\n\n<pre><code>number :: ReadP Expression\nnumber = lexeme $ fmap (Number . read) (many1 digit)\n</code></pre>\n\n<p>So should <code>operator</code>, though obviously not <code>digit</code>! <code>expression</code> won't need to use <code>lexeme</code>, because we'll arrange to end it with a lexeme parser.</p>\n\n<p>It's also helpful to define a <code>symbol</code> parser which is essentially <code>string</code> that ignores trailing spaces:</p>\n\n<pre><code>symbol :: String -&gt; ReadP String\nsymbol = lexeme . string\n</code></pre>\n\n<p>Consistently used, <code>lexeme</code> (and <code>symbol</code>) will deal with all unwanted spaces, other than any leading spaces at the very start of your parse. If you have a non-recursive \"top level\" grammar production, like say a parser for <code>program :: ReadP Program</code>, then you would probably deal with them there. In your example, you don't have such a production (e.g., <code>expression</code> is recursive), so you'd stick an extra <code>skipSpaces</code> in <code>parseExpression</code>. This is also a good place to put <code>eof</code> to make sure there isn't any trailing material that you aren't parsing:</p>\n\n<pre><code>parseExpression :: String -&gt; Maybe Expression\nparseExpression input = case readP_to_S (skipSpaces *&gt; expression &lt;* eof) input of\n [] -&gt; Nothing\n xs -&gt; (Just . fst . last) xs\n</code></pre>\n\n<p>Second, your use of a <code>Read</code> instance for parsing your operators is very unusual. It would be more standard to make it a helper in the <code>operator</code> parser, writing something like:</p>\n\n<pre><code>operator :: ReadP Operator\noperator = readSymbol &lt;$&gt; (symbol \"+\" &lt;|&gt; symbol \"-\")\n where readSymbol \"+\" = Add\n readSymbol \"-\" = Subtract\n</code></pre>\n\n<p>(though an even <em>more</em> standard version is given below).</p>\n\n<p>Third, in <code>expression</code>, you can avoid the <code>case</code> construct by using alternation <code>(&lt;|&gt;)</code> like so:</p>\n\n<pre><code>expression' :: ReadP Expression\nexpression' = do\n left &lt;- number\n (do op &lt;- operator\n right &lt;- expression\n return (Infix left op right)\n &lt;|&gt; return left)\n</code></pre>\n\n<p>This would be the standard approach for non-parallel parser libraries (e.g., Parsec or Megaparsec). For <code>ReadP</code>, it's better to replace the <code>(&lt;|&gt;)</code> operator with the ReadP-specific <code>(&lt;++)</code> operator to avoid also following the unwanted second parse in parallel. Beware that <code>(&lt;++)</code> has higher precedence than <code>(&lt;|&gt;)</code>, so some extra parentheses might be needed if it's being used in combination with other operators, as in the examples below.</p>\n\n<p>Fourth, you've probably noticed my use of the applicative operators <code>&lt;*</code> and <code>*&gt;</code> and the alias <code>&lt;$&gt;</code> for <code>fmap</code> in the code above. It is <strong>very common</strong> to use these -- plus the additional applicative operator <code>&lt;*&gt;</code> and sometimes the operators <code>&lt;**&gt;</code> or <code>&lt;$</code> -- in parsers. Once you get used to them, they tend to lead to less cluttered code.</p>\n\n<p>For example, a more standard way of writing <code>expression</code> would be:</p>\n\n<pre><code>expression' :: ReadP Expression\nexpression' = Infix &lt;$&gt; number &lt;*&gt; operator &lt;*&gt; expression\n &lt;|&gt; number\n</code></pre>\n\n<p>or the slightly more efficient solution:</p>\n\n<pre><code>expression :: ReadP Expression\nexpression = do\n left &lt;- number\n (Infix left &lt;$&gt; operator &lt;*&gt; expression) &lt;++ return left\n</code></pre>\n\n<p>Note that, in the context of parsers, an expression like <code>f &lt;$&gt; p &lt;*&gt; q</code> means \"try to run the parser <code>p</code>, and then the parser <code>q</code>; assuming they both succeed, pass their return values to <code>f</code>\". In other words, that <code>Infix</code> expression is essentially:</p>\n\n<pre><code>Infix left op right\n</code></pre>\n\n<p>where <code>op</code> is the return value from the parser <code>operator</code> and <code>right</code> is the return value from the parser <code>expression</code>.</p>\n\n<p>Similarly, the standard way of writing <code>operator</code> is actually:</p>\n\n<pre><code>operator :: ReadP Operator\noperator = Add &lt;$ symbol \"+\" &lt;|&gt; Subtract &lt;$ symbol \"-\"\n</code></pre>\n\n<p>This one requires an additional word of explanation. The operator <code>&lt;$</code> is kind of an odd duck. It's type signature is:</p>\n\n<pre><code>(&lt;$) :: a -&gt; f b -&gt; f a\n</code></pre>\n\n<p>but in the context of parsers specifically, the meaning of <code>x &lt;$ p</code> is \"try to run the parser <code>p</code>; if it succeeds, ignore its return value and return <code>x</code>\". Basically, it's used to replace the return value of a parser that's used only for its success or failure and not its return value.</p>\n\n<p>Note that these versions of <code>expression</code>, like your original version, treat the operators as right associative. This may be a problem if you're trying to parse \"1-2-3\" as equivalent to \"(1-2)-3\" instead of \"1-(2-3)\".</p>\n\n<p>A few additional minor points:</p>\n\n<ul>\n<li><code>isDigit</code> is a more readable name for <code>\\c -&gt; c &gt;= '0' &amp;&amp; c &lt;= '9'</code></li>\n<li><code>munch1</code> is more efficient than <code>many1 (satisfy xxx)</code>, so I'd redefine <code>number</code> to use it</li>\n<li>for testing, it's probably a good idea to have a <code>parseExpressions</code> function that looks at <em>all</em> the parses</li>\n<li>for production, it's probably a good idea to check for ambiguous parses and do something about it, rather than (fairly arbitrarily) selecting the last parse in the list</li>\n</ul>\n\n<p>With all of these suggestions implemented, the final version would look something like:</p>\n\n<pre><code>{-# OPTIONS_GHC -Wall #-}\n\nimport Data.Char (isDigit)\nimport Control.Applicative\nimport Text.ParserCombinators.ReadP (eof, munch1, ReadP, readP_to_S,\n skipSpaces, string, (&lt;++))\n\ndata Operator = Add | Subtract\n\ndata Expression = Number Int\n | Infix { left :: Expression, op :: Operator, right :: Expression }\n\nlexeme :: ReadP a -&gt; ReadP a\nlexeme p = p &lt;* skipSpaces\n\nsymbol :: String -&gt; ReadP String\nsymbol = lexeme . string\n\nnumber :: ReadP Expression\nnumber = lexeme $ Number . read &lt;$&gt; munch1 isDigit\n\noperator :: ReadP Operator\noperator = Add &lt;$ symbol \"+\" &lt;|&gt; Subtract &lt;$ symbol \"-\"\n\nexpression :: ReadP Expression\nexpression = do\n x &lt;- number\n (Infix x &lt;$&gt; operator &lt;*&gt; expression) &lt;++ return x\n\ntop :: ReadP Expression\ntop = skipSpaces *&gt; expression &lt;* eof\n\nparseExpressions :: String -&gt; [(Expression, String)]\nparseExpressions = readP_to_S top\n\nparseExpression :: String -&gt; Maybe Expression\nparseExpression input = case parseExpressions input of\n [] -&gt; Nothing\n [(x,\"\")] -&gt; Just x\n _ -&gt; error \"ambiguous parse\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T01:06:07.283", "Id": "219147", "ParentId": "210830", "Score": "4" } } ]
{ "AcceptedAnswerId": "219147", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T18:01:48.457", "Id": "210830", "Score": "2", "Tags": [ "parsing", "haskell" ], "Title": "Parsing expressions with combinators" }
210830
<p>I wrote a function that can be used to generate a probability distribution for an array of elements <code>(probGen())</code>, and another that can be used to select an element from an array with a specified probability <code>(probSelect())</code>. I want to optimise my code.</p> <h3>probGen.php</h3> <pre><code>&lt;? require_once("randX.php"); #"randX()" generates a random floating point number in a specified range. error_reporting(E_ERROR | E_WARNING | E_PARSE); function probGen(array $arr, float $control = 0.01) /* * Generates a valid, random probability distribution for a given array of elements, that can be used in conjunction with "probSelect()". * Input: $arr: An array of elements. $control: A value that decides how much mass is allowed to be unilaterally dumped onto one element. A high value would permit distributions where most of the mass is concentrated on one element. If an invalid value is provided, the default is used. * Output: An associative array where the keys are the elements in the original array, and the values are their probabilities. */ { $control = ($control &lt;= 1 &amp;&amp; $control &gt;= 0)?($control):(0.00001); #Use the default value if an invalid number is supplied. static $result = []; #Initialises $result with an empty array on first function call. static $max = 1; #Initialises $max with 1 on first function call. foreach ($arr as $value) { $x = randX(0, $max); #Random probability value. $result[$value] = ($result[$value] + $x)??0; #Initialise the array with 0 on first call, and on subsequent calls increment by $x to assign probability mass. $max -= $x; #Ensures that the probability never sums to more than one. } /* * After the execution of the above code, there would be some leftover probability mass. * The code below adds it to a random element. */ $var = array_values($arr); if($max &lt;= $control) #To limit concentration of most of the probability mass in one variable. { $result[$var[rand(0,(count($var)-1))]] += $max; #Selects a random key and adds $max to it. return $result; } else return probGen($arr, $control); } ?&gt; </code></pre> <h3>probSelect.php</h3> <pre><code>&lt;? require_once("confirm.php"); function probSelect(array $arr) /* * A function to select an element from an array with indicated probabilites. * Input: An associative array whose keys are the elements to be selected from, and whose values are the associated probabilities. * Output: The selected element, or "NULL" if an invalid probability distribution was supplied. */ { if(confirm($arr)) { $var = lcg_value(); #The random float that would be used to select the element. $sum = 0; foreach ($arr as $key =&gt; $value) { $sum += $value; if($var &lt;= $sum) return $key; } } else { print("ERROR!!! The supplied probability distribution must sum to 1. &lt;br&gt;"); return null; } } ?&gt; </code></pre> <hr> <h2>Dependencies</h2> <p>The required functions in case they are necessary for evaluating performance: </p> <h3>randX.php</h3> <pre><code>&lt;? function randX(float $a, float $b): float /* * Generates a random number between between two real numbers (both inclusive). * Input: Two floating point numbers. * Output: A random floating point number. */ { $max = max($a, $b); $min = min($a, $b); $x = $max - $min; $y = lcg_value()*$x; return ($min+$y); } ?&gt; </code></pre> <h3>confirm.php</h3> <pre><code>&lt;? function confirm(array $arr) #Confirms that the supplied array has a valid probability distribution { return (array_sum($arr) == 1)?true:false; } ?&gt; </code></pre>
[]
[ { "body": "<p>A few little things:</p>\n\n<p><strong>Don't put comments in between function declarations and curly braces (or anything similar to that like classes or methods)</strong></p>\n\n<p>That's hard to read and an eye sore. Put your function comments <em>above</em> the function itself. Ideally using standard <a href=\"http://docs.phpdoc.org/guides/docblocks.html\" rel=\"nofollow noreferrer\">docblock format</a>. </p>\n\n<pre><code>/**\n* Generates a valid, random probability distribution for a given array of elements, that can be used in conjunction with \"probSelect()\".\n* \n* @param array $arr An array of elements\n* @param float $control A value that decides how much mass is allowed to be unilaterally dumped onto one element. A high value would permit distributions where most of the mass is concentrated on one element. \n* @return array An associative array where the keys are the elements in the original array, and the values are their probabilities. \n*/\nfunction probGen(array $arr, float $control = 0.01) \n{\n</code></pre>\n\n<p><strong>Use better variable names</strong></p>\n\n<p>What does <code>$arr</code> mean? I can guess that it is probably an array but my IDE can already tell me that. What's actually <em>in</em> that array? <code>$elements</code> would be a better name based on the function comments. A better name would be <code>$elementsOfSomething</code> where <code>something</code> accurately describe the characteristic of those elements.</p>\n\n<p><strong>Always use curly braces for control structures</strong> </p>\n\n<p>Although it is perfectly valid syntax to omit curly braces when a control structure only contains one line of code. But it is a best practice to always use them as they make the code more rreadable and prevent future errors. Future you or another developer may want to add a line to a control block and introduce a hard to find bug because they didn't realize the curly braces weren't there.</p>\n\n<pre><code>if($var &lt;= $sum)\n return $key;\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>if($var &lt;= $sum) {\n return $key;\n}\n</code></pre>\n\n<p><strong>Use <code>echo</code> over <code>print()</code></strong></p>\n\n<p><code>print()</code> is an alias of <code>echo</code> but there are minor differences between the two. Although they don't come into play here, it is the PHP convention to use <code>echo</code> for outputting content.</p>\n\n<p><strong>Don't output content from your functions</strong></p>\n\n<p>Your functions that do work <em>and</em> output content but only when there is an error are inconstant and doing too much. If you have an error, let the function report that back through a special return value (like <code>false</code> or <code>null</code>) or by throwing an exception. Let the calling code worry about reporting back the error and let the function focus on doing one thing and one thing only (just like a good OOP class should be doing).</p>\n\n<p><strong>You can simply statements that check for a Boolean to return a Boolean</strong></p>\n\n<p>Your statement <code>return (sum($arr) == 1)?true:false;</code> is checking if a statement is true and returning <code>true</code> if it is. <code>false</code> if it is false. So you can return the result of your conditional without having to explicitly return <code>true</code> or <code>false</code> because you already have that value:</p>\n\n<pre><code>return (sum($arr) == 1); // will return true or false\n</code></pre>\n\n<p><strong>An alternative randx() function</strong></p>\n\n<p>The internet seems like it is already full of example functions that will generate a random float. They tend to be similar to the one below. Is there any reason you did not choose to go this route? It has fewer function calls so it should be more performant.</p>\n\n<pre><code>function frand($min, $max, $decimals = 0) {\n $scale = pow(10, $decimals);\n return mt_rand($min * $scale, $max * $scale) / $scale;\n}\n\necho \"frand(0, 10, 2) = \" . frand(0, 10, 2) . \"\\n\";\n</code></pre>\n\n<p><strong>The PHP community prefers // to # for comments</strong></p>\n\n<p>Although <code>#</code> is a valid syntax for a one line comment in PHP, it is common practice to use <code>//</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T10:37:13.067", "Id": "407645", "Score": "0", "body": "\"The PHP community prefers // to # for comments\" Do you happen to know why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T18:00:57.470", "Id": "407712", "Score": "0", "body": "@Mast I'm 99.44% sure this came about from the PEAR standards" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:32:28.337", "Id": "210836", "ParentId": "210833", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:04:46.123", "Id": "210833", "Score": "0", "Tags": [ "performance", "beginner", "php", "algorithm", "random" ], "Title": "Probability suite for an array of elements" }
210833
<p>This is my first console application in C# and I think it's unnecessarily wrong and I made some bad practices, but at least it works smoothly. How could I improve this code so that next time I write a console application it won't be as garbled as this?</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static readonly int gridW = 90; static readonly int gridH = 25; static Cell[, ] grid = new Cell[gridH, gridW]; static Cell currentCell; static Cell food; static int FoodCount; static int direction; //0=Up 1=Right 2=Down 3=Left static readonly int speed = 1; static bool Populated = false; static bool Lost = false; static int snakeLength; static void Main(string[] args) { if (!Populated) { FoodCount = 0; snakeLength = 5; populateGrid(); currentCell = grid[(int) Math.Ceiling((double) gridH / 2), (int) Math.Ceiling((double) gridW / 2)]; updatePos(); addFood(); Populated = true; } while (!Lost) { Restart(); } } static void Restart() { Console.SetCursorPosition(0, 0); printGrid(); Console.WriteLine("Length: {0}", snakeLength); getInput(); } static void updateScreen() { Console.SetCursorPosition(0, 0); printGrid(); Console.WriteLine("Length: {0}", snakeLength); } static void getInput() { //Console.Write("Where to move? [WASD] "); ConsoleKeyInfo input; while (!Console.KeyAvailable) { Move(); updateScreen(); } input = Console.ReadKey(); doInput(input.KeyChar); } static void checkCell(Cell cell) { if (cell.val == "%") { eatFood(); } if (cell.visited) { Lose(); } } static void Lose() { Console.WriteLine("\n You lose!"); Thread.Sleep(1000); Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location); Environment.Exit(-1); } static void doInput(char inp) { switch (inp) { case 'w': goUp(); break; case 's': goDown(); break; case 'a': goRight(); break; case 'd': goLeft(); break; } } static void addFood() { Random r = new Random(); Cell cell; while (true) { cell = grid[r.Next(grid.GetLength(0)), r.Next(grid.GetLength(1))]; if (cell.val == " ") cell.val = "%"; break; } } static void eatFood() { snakeLength += 1; addFood(); } static void goUp() { if (direction == 2) return; direction = 0; } static void goRight() { if (direction == 3) return; direction = 1; } static void goDown() { if (direction == 0) return; direction = 2; } static void goLeft() { if (direction == 1) return; direction = 3; } static void Move() { if (direction == 0) { //up if (grid[currentCell.y - 1, currentCell.x].val == "*") { Lose(); return; } visitCell(grid[currentCell.y - 1, currentCell.x]); } else if (direction == 1) { //right if (grid[currentCell.y, currentCell.x - 1].val == "*") { Lose(); return; } visitCell(grid[currentCell.y, currentCell.x - 1]); } else if (direction == 2) { //down if (grid[currentCell.y + 1, currentCell.x].val == "*") { Lose(); return; } visitCell(grid[currentCell.y + 1, currentCell.x]); } else if (direction == 3) { //left if (grid[currentCell.y, currentCell.x + 1].val == "*") { Lose(); return; } visitCell(grid[currentCell.y, currentCell.x + 1]); } Thread.Sleep(speed * 100); } static void visitCell(Cell cell) { currentCell.val = "#"; currentCell.visited = true; currentCell.decay = snakeLength; checkCell(cell); currentCell = cell; updatePos(); //checkCell(currentCell); } static void updatePos() { currentCell.Set("@"); if (direction == 0) { currentCell.val = "^"; } else if (direction == 1) { currentCell.val = "&lt;"; } else if (direction == 2) { currentCell.val = "v"; } else if (direction == 3) { currentCell.val = "&gt;"; } currentCell.visited = false; return; } static void populateGrid() { Random random = new Random(); for (int col = 0; col &lt; gridH; col++) { for (int row = 0; row &lt; gridW; row++) { Cell cell = new Cell(); cell.x = row; cell.y = col; cell.visited = false; if (cell.x == 0 || cell.x &gt; gridW - 2 || cell.y == 0 || cell.y &gt; gridH - 2) cell.Set("*"); else cell.Clear(); grid[col, row] = cell; } } } static void printGrid() { string toPrint = ""; for (int col = 0; col &lt; gridH; col++) { for (int row = 0; row &lt; gridW; row++) { grid[col, row].decaySnake(); toPrint += grid[col, row].val; } toPrint += "\n"; } Console.WriteLine(toPrint); } public class Cell { public string val { get; set; } public int x { get; set; } public int y { get; set; } public bool visited { get; set; } public int decay { get; set; } public void decaySnake() { decay -= 1; if (decay == 0) { visited = false; val = " "; } } public void Clear() { val = " "; } public void Set(string newVal) { val = newVal; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:16:08.860", "Id": "407588", "Score": "0", "body": "Does that code work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:27:09.420", "Id": "407589", "Score": "0", "body": "it appears to run [when I try it on onlinegdb](https://onlinegdb.com/rkEezJ3ZN) though that interactive interface isn't optimal..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:35:06.177", "Id": "407591", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ i didnt intend it to be used in online interpreters, i wrote it in visual studio" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:35:35.093", "Id": "407592", "Score": "2", "body": "I know - I just wanted to test it without VS" } ]
[ { "body": "<p>Well, this is my first code review and by no means I'm an C# expert or something like that, but anyways I'd like to give a general opinion about your code.</p>\n\n<p>First and foremost, you're using C# which is mostly an OO language, so I encourage you to write your code using OO constructs. In this case, it means that you should create classes to abstract the things that build your game. So for example, you would create a <code>SnakeGame</code> class, a <code>Snake</code> class, etc. This not only will help you to make your program more maintainable, but also will allow you to remove all the static properties and methods you've created. </p>\n\n<p>Ideally, you <code>Main</code> method should be as short as possible. For example, inside your <code>SnakeGame</code> you could create a public <code>Run</code> method and in <code>Main</code> you would only need to instantiate that class and only invoke its <code>Run</code> method. In code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var game = new SnakeGame();\n game.Run();\n}\n</code></pre>\n\n<p>On the other hand, don't use <code>int</code> when you can use an <code>enum</code>. In your program you've used an <code>int</code> for the field <code>direction</code>. Instead you could create a simple <code>enum</code>:</p>\n\n<pre><code>enum Direction\n{\n Up, Right, Down, Left\n}\n</code></pre>\n\n<p>Then in the hypothetical <code>SnakeGame</code> class you could have: <code>private Direction snakeDirection;</code>, instead of <code>static int direction;</code> that you currently have in the class <code>Program</code>.</p>\n\n<p>About the style I noticed that you have mixed camelCase with PascalCase for fields and methods: e.g., the fields <code>Populated</code> and <code>Lost</code> use PascalCase whereas the field <code>snakeLength</code> uses camelCase. Likewise, the method <code>updateScreen</code> uses camelCase, but the method <code>Restart</code> uses PascalCase, and this is not good. Choose a style and stick with it: be consistent!. FYI, in C# is common to use camelCase for variables, in particular for fields, and PascalCase for classes and methods. So my general advice here would be to follow the standard conventions. And since we're talking about conventions, it's also a common standard in C# to use the <a href=\"https://en.wikipedia.org/wiki/Indentation_style#Allman_style\" rel=\"noreferrer\">Allman style</a> for indentation.</p>\n\n<p>Finally, there are a couple things I want to comment. First is about the class <code>Cell</code>. From the way you use it in your code, there is already a built-in struct in .NET framework that would do most of the work for you: the struct <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.drawing.point?view=netframework-4.7.2\" rel=\"noreferrer\"><code>Point</code></a>. It's in the namespace <code>System.Drawing</code>. As its name says, it represent a point in Cartesian coordinates and it has already properties to get and set the <code>X</code> and <code>Y</code> coordinates among other methods.</p>\n\n<p>And about namespaces, only include those that you really need. For example, you could safely remove the namespace <code>System.Collections.Generic</code> <code>System.Text</code>, etc., and instead add the namespace <code>System.Reflection</code>. But, in a better designed code you wouldn't need such a namespace ;) </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T05:07:44.700", "Id": "211158", "ParentId": "210835", "Score": "11" } }, { "body": "<p>I've been flirting with writing a snake game console app in C# for a while. Running across your question on a weekend when my girlfriend is working allowed me to devote some time to it.</p>\n\n<p>Thank you for inspiring me, and providing working algorithms. Your program runs fine for me. It taught me some general concepts about this type of game - like Decay(), along with things like waiting for a console keypress without blocking. Thanks also to @Xam for your comments and the heads up on the Point class (which I am happy to know about even though I didn't use it in this case). Overall, I converted the existing code to my personal object-oriented programming (OOP) style. </p>\n\n<p>While the code captures the bulk of my commentary, here are some additional points:</p>\n\n<ol>\n<li>Phil Karlton said one of my favorite programming quotes of all time: “There are only two hard things in Computer Science: cache invalidation and naming things.” While I have done little with cache invalidation in my coding career, naming is a constant practice for all developers. I like to invest time and energy to think of names that make sense.</li>\n<li>On that note, I typically rely on the domain for many names. When coding a snake game, it’s very likely that I’ll have Game, Board, and Snake classes. While you managed to wrangle your solution into just two classes, to me, such an approach does little to describe and document the domain. I wound up with six “domain” classes (excluding the Program and the “App”).</li>\n<li>Considering that the size of the snake will never be huge, to enable easy adds and removes, I used a LinkedList for the Snake’s body. (first time I’ve used a LinkedList in a while – perhaps since college.)</li>\n<li>I use the relatively new C# feature of Expression-Bodied members pretty much wherever possible – e.g. public int Length => BodyLength + 1;. </li>\n<li>I typically avoid “static”. I even keep Main() as short as possible, immediately passing control to a normal non-static class. The one exception I made in this case was to make the DirectionMap a “global” variable – i.e. static on the Board class. I use it in a few different places and wanted to avoid passing a board object all over. </li>\n<li>When first building the object model, I had cells being able to find their own neighbors. That relied on the board’s grid being static so that anyone could access it. Then I thought, “To find its neighbors, a cell has to know the whole board, which might be stretching their responsibilities too far.” So, I made finding a cell’s neighbors the responsibility of the board, which allowed the grid to become private again. Likewise, I had the Snake determining whether it had collided with something, but decided that also lies within the Board class’s responsibilities.</li>\n<li>In short, I consider each class’s nature and boundaries to figure out what properties and responsibilities it “owns” and what should go on another class, or a new class.</li>\n<li>Other areas where I erred on the side of abstracting / encapsulating things include the eHeading enum and the Direction class.</li>\n<li>David West says something to the effect that at its core, object-oriented programming (OOP) is an approach to message passing. In this case, I’m using crude (but effective) ways to pass messages between objects, such as the Snake’s “HasEaten” flag. It lets the board know that it needs to put out more food. Ostensibly this whole thing could be an event-driven app, with events like “OnStart”, “OnKeyPress”, “OnMove”, “OnEat”, and “OnCollide”. While I’ve done some event-driven stuff in C#, it’s far from my strong suit, so I stayed with the approach of looping through turns.</li>\n<li>Pausing between each turn to slow the game to human speed is great. In your code as the speed increases so does the pause, making 1 the fastest speed. I found it more intuitive to make the pause go down as the speed goes up. And, I set a max speed of 5 (which is now the fastest speed).</li>\n<li>I employ a concept I call “endoskeletal programming\". Perhaps because I am a bit neurotic about the appearance and readability of my code, I typically conceal monstrous predicates and other calculations, even small ones, in their own property or method. This gives the benefit of naming the predicate or calculation, which in my opinion boosts readability and makes the code largely self-documenting. </li>\n</ol>\n\n<p>For example: to determine if a cell is part of the border you had:</p>\n\n<pre><code>if (cell.x == 0 || cell.x &gt; gridW - 2 || cell.y == 0 || cell.y &gt; gridH - 2)\n cell.Set(\"*\");\nelse\n cell.Clear();\n</code></pre>\n\n<p>My approach is:</p>\n\n<pre><code>private int leftEdgeX =&gt; 0;\nprivate int rightEdgeX =&gt; Width - 1;\nprivate int topEdgeY =&gt; 0;\nprivate int bottomEdgeY =&gt; Height - 1;\nprivate bool isBorder(Cell cell) =&gt; cell.X == leftEdgeX || cell.X &gt;= rightEdgeX || cell.Y == topEdgeY || cell.Y &gt;= bottomEdgeY;\nif (isBorder(cell))\n{\n cell.SetBorder();\n}\nelse\n{\n cell.SetEmpty();\n}\n</code></pre>\n\n<p>They both get the job done. My intention is to give more insight into what the job is and how we’re doing it.</p>\n\n<p>As you can probably tell, I'm a fan of OOP. Not everyone is. Even among those that do, some consider my style verbose. You proved that we can express the same logic in a far shorter code base. But, I optimize for readability, maintainability, domain descriptiveness, and my own sense of craftsmanship… rather than size.</p>\n\n<p>Things we could add / modify include:</p>\n\n<ul>\n<li>A separate Body class</li>\n<li>Avoid putting food in a corner (though it is theortically possible to get food from a corner)</li>\n<li>Cell.IsHead and Cell.IsTail properties</li>\n<li>Prompt user for speed when starting and show speed </li>\n<li>A game timer</li>\n<li>Declare instructions on the Game class and possibly even add separate Instructions class</li>\n<li>Come up with a better name than \"DoTurn\"</li>\n<li>Avoid having DirectionMap as static</li>\n</ul>\n\n<p>Here is the code. I am interested in your feedback on this approach.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\nnamespace SnakeGame\n{\n class Program\n {\n static void Main(string[] args)\n {\n var app = new SnakeGameApp();\n app.Run();\n if (System.Diagnostics.Debugger.IsAttached)\n {\n Console.WriteLine(\"\\nPress &lt;Enter&gt; to continue...\");\n Console.ReadLine();\n }\n }\n }\n\n public class SnakeGameApp\n {\n private readonly int delayBetweenGames = 1500;\n\n public void Run()\n {\n var finished = false;\n while (!finished)\n {\n var game = new Game();\n game.Play();\n finished = game.Quit;\n if (game.Lost)\n {\n Console.WriteLine(\"\\nYou lost.\");\n Thread.Sleep(delayBetweenGames);\n Console.Clear();\n }\n }\n }\n }\n\n public class Game\n {\n private readonly eHeading initialHeading = eHeading.Up;\n private DirectionMap directionMap = Board.DirectionMap;\n\n private Board board;\n public bool Lost { get; private set; } = false;\n public bool Quit { get; private set; } = false;\n\n public Game(int snakeLength = 5)\n {\n board = new Board();\n var head = board.Center;\n board.Add(new Snake(head, initBody(head, snakeLength - 1), directionMap.Get(initialHeading)));\n board.AddFood(); //to avoid the snake overwriting food, add food after snake\n board.Draw();\n }\n\n public void Play()\n {\n while (!Lost &amp;&amp; !Quit)\n {\n ConsoleKeyInfo input;\n if (Console.KeyAvailable)\n {\n input = Console.ReadKey(true); //intercept = true (don't print char on console)\n //If the directionMap doesn't find a direction for the character \n //the user pressed it throws an exception.\n //Wrapping this in a try/catch allows us to ignore all non-direction keys\n //except Escape, which quits the game.\n try\n {\n var direction = directionMap.Get(input.KeyChar);\n board.DoTurn(direction);\n Lost = board.HasCollided;\n }\n catch\n {\n Quit = input.Key == ConsoleKey.Escape;\n }\n }\n else\n {\n board.DoTurn();\n Lost = board.HasCollided;\n }\n }\n }\n\n private LinkedList&lt;Cell&gt; initBody(Cell head, int bodyLength)\n {\n var body = new LinkedList&lt;Cell&gt;();\n var current = board.BottomNeighbor(head);\n for (var i = 0; i &lt; bodyLength; i++)\n {\n body.AddLast(current);\n current.SetBody(bodyLength - i);\n current = board.BottomNeighbor(current);\n }\n return body;\n }\n }\n\n public class Board\n {\n public static DirectionMap DirectionMap { get; } = new DirectionMap();\n\n private readonly string instructions = \"How to Play: Avoid hitting walls or yourself. Grow by eating food (%). Highest length wins.\";\n private readonly string commandBase = \"Commands: {0}, Esc: Quit\\n\";\n private readonly string lengthBase = \"Length: {0}\\n\";\n\n private Cell[,] grid;\n private Random random = new Random();\n private int leftEdgeX =&gt; 0;\n private int rightEdgeX =&gt; Width - 1;\n private int topEdgeY =&gt; 0;\n private int bottomEdgeY =&gt; Height - 1;\n\n public Snake Snake { get; private set; }\n public int Height { get; private set; }\n public int Width { get; private set; }\n public Cell Current =&gt; Snake.Head;\n public Cell Center =&gt; get(Width / 2, Height / 2);\n public Cell Food { get; private set; }\n public bool HasCollided { get; private set; }\n\n public Board(int width = 90, int height = 25)\n {\n Width = width;\n Height = height;\n grid = new Cell[Width, Height];\n initGrid();\n }\n\n //continue in the same direction\n public void DoTurn()\n {\n doTurn(Snake.Direction, getDestination(Snake.Direction));\n }\n\n public void DoTurn(Direction direction)\n {\n doTurn(direction, getDestination(direction));\n }\n\n public void Draw()\n {\n Console.SetCursorPosition(0, 0);\n Console.WriteLine(ToString());\n }\n\n public void Add(Snake snake) =&gt; Snake = snake;\n public void AddFood() =&gt; randomCell().SetFood();\n\n public Cell TopNeighbor(Cell cell) =&gt; grid[cell.X, cell.Y - 1];\n public Cell RightNeighbor(Cell cell) =&gt; grid[cell.X + 1, cell.Y];\n public Cell BottomNeighbor(Cell cell) =&gt; grid[cell.X, cell.Y + 1];\n public Cell LeftNeighbor(Cell cell) =&gt; grid[cell.X - 1, cell.Y];\n\n public override string ToString()\n {\n var sb = new StringBuilder();\n //y is in outer loop, so we draw by rows\n for (int y = 0; y &lt; Height; y++)\n {\n for (int x = 0; x &lt; Width; x++)\n {\n sb.Append(grid[x, y].Value);\n }\n sb.Append(\"\\n\"); //terminate row\n }\n sb.AppendFormat(lengthBase, Snake.Length);\n sb.AppendLine(instructions);\n sb.AppendFormat(commandBase, DirectionMap.ToString());\n return sb.ToString();\n }\n\n private Cell get(int x, int y) =&gt; grid[x, y];\n\n private void add(Cell cell) =&gt; grid[cell.X, cell.Y] = cell;\n\n private bool isBorder(Cell cell) =&gt; cell.X == leftEdgeX || cell.X &gt;= rightEdgeX\n || cell.Y == topEdgeY || cell.Y &gt;= bottomEdgeY;\n\n private void doTurn(Direction direction, Cell target)\n {\n if (isLegalMove(direction, target))\n {\n Snake.Move(direction, target);\n\n if (Snake.HasEaten)\n {\n Snake.Grow(getNewTail());\n AddFood();\n }\n\n Draw();\n }\n }\n\n private bool isLegalMove(Direction direction, Cell target)\n {\n if (direction.IsOpposite(Snake.Direction))\n {\n return false;\n }\n\n HasCollided = target.IsForbidden;\n\n return !HasCollided;\n }\n\n private Cell getDestination(Direction direction) =&gt; getDirectionalNeighbor(Snake.Head, direction);\n\n private Cell getNewTail() =&gt; getDirectionalNeighbor(Snake.Tail, Snake.Direction.Opposite);\n\n private Cell getDirectionalNeighbor(Cell cell, Direction direction)\n {\n var neighbor = new Cell(-1, -1); //initialize to dummy cell\n\n if (direction.IsUp)\n {\n neighbor = TopNeighbor(cell);\n }\n else if (direction.IsRight)\n {\n neighbor = RightNeighbor(cell);\n }\n else if (direction.IsDown)\n {\n neighbor = BottomNeighbor(cell);\n }\n else if (direction.IsLeft)\n {\n neighbor = LeftNeighbor(cell);\n }\n\n return neighbor;\n }\n\n private Cell randomCell()\n {\n bool isEmpty;\n var cell = new Cell(-1, -1); //initialize to dummy cell\n do\n {\n cell = grid[random.Next(Width), random.Next(Height)];\n isEmpty = cell.IsEmpty;\n } while (!isEmpty);\n\n return cell;\n }\n\n private void initGrid()\n {\n for (int y = 0; y &lt; Height; y++)\n {\n for (int x = 0; x &lt; Width; x++)\n {\n var cell = new Cell(x, y);\n\n add(cell);\n\n if (isBorder(cell))\n {\n cell.SetBorder();\n }\n else\n {\n cell.SetEmpty();\n }\n }\n }\n }\n }\n\n //int values are degrees\n public enum eHeading\n {\n Up = 0,\n Right = 90,\n Down = 180,\n Left = 270\n }\n\n public class Direction\n {\n public eHeading Heading { get; private set; }\n public char KeyPress { get; private set; }\n public char HeadToken { get; private set; }\n public int Degrees =&gt; (int)Heading;\n public Direction Opposite =&gt; Board.DirectionMap.Get((eHeading)(Degrees &gt;= 180 ? Degrees - 180 : Degrees + 180));\n\n public bool IsUp =&gt; Heading == eHeading.Up;\n public bool IsRight =&gt; Heading == eHeading.Right;\n public bool IsDown =&gt; Heading == eHeading.Down;\n public bool IsLeft =&gt; Heading == eHeading.Left;\n\n public Direction(eHeading vector, char keyPress, char headToken)\n {\n Heading = vector;\n KeyPress = keyPress;\n HeadToken = headToken;\n }\n\n public bool IsOpposite(Direction dir) =&gt; Math.Abs(Degrees - dir.Degrees) == 180;\n\n public bool IsSame(Direction dir) =&gt; Heading == dir.Heading;\n\n public string ToCommand() =&gt; $\"{KeyPress}: {Heading}\";\n }\n\n public class DirectionMap\n {\n private Dictionary&lt;char, Direction&gt; _directionKeys;\n private Dictionary&lt;char, Direction&gt; directionKeys\n {\n get\n {\n _directionKeys = _directionKeys ?? directionKeyMap();\n return _directionKeys;\n }\n }\n\n private Dictionary&lt;eHeading, Direction&gt; _directionVectors;\n private Dictionary&lt;eHeading, Direction&gt; directionVectors\n {\n get\n {\n _directionVectors = _directionVectors ?? directionVectorMap();\n return _directionVectors;\n }\n }\n\n public Direction Get(char c)\n {\n if (directionKeys.TryGetValue(c, out Direction direction))\n {\n return direction;\n }\n else\n {\n throw new Exception($\"{c} not found in direction map.\");\n }\n }\n\n public Direction Get(eHeading vector)\n {\n if (directionVectors.TryGetValue(vector, out Direction direction))\n {\n return direction;\n }\n else\n {\n throw new Exception($\"Vector {vector.ToString()} not found in direction map.\");\n }\n }\n\n public override string ToString() =&gt; string.Join(\", \", directionVectors.Select(v =&gt; v.Value.ToCommand()));\n\n private Dictionary&lt;eHeading, Direction&gt; directionVectorMap()\n {\n return new Dictionary&lt;eHeading, Direction&gt;\n {\n {eHeading.Left, new Direction(eHeading.Left , 'a', '&lt;')},\n {eHeading.Right, new Direction(eHeading.Right,'d', '&gt;') },\n {eHeading.Down, new Direction(eHeading.Down, 's', 'v') },\n {eHeading.Up, new Direction(eHeading.Up, 'w', '^') }\n };\n }\n\n private Dictionary&lt;char, Direction&gt; directionKeyMap() =&gt; directionVectors.ToDictionary(d =&gt; d.Value.KeyPress, d =&gt; d.Value);\n }\n\n public class Cell\n {\n private readonly char unitializedToken = char.MinValue;\n private readonly char emptyToken = ' ';\n private readonly char borderToken = '*';\n private readonly char bodyToken = '#';\n private readonly char foodToken = '%';\n\n private int remaining;\n\n public int X { get; private set; }\n public int Y { get; private set; }\n public char Value { get; private set; }\n\n public bool IsBorder =&gt; Value == borderToken;\n public bool IsBody =&gt; Value == bodyToken;\n public bool IsFood =&gt; Value == foodToken;\n public bool IsEmpty =&gt; Value == emptyToken || Value == unitializedToken;\n public bool IsForbidden =&gt; IsBorder || IsBody;\n\n public Cell(int x, int y)\n {\n X = x;\n Y = y;\n }\n\n public void SetEmpty() =&gt; Update(emptyToken);\n\n public void SetHead(char headToken)\n {\n Update(headToken);\n }\n\n public void SetBody(int length)\n {\n Update(bodyToken);\n remaining = length;\n }\n\n public void SetBorder() =&gt; Update(borderToken);\n\n public void SetFood() =&gt; Update(foodToken);\n\n public void Update(char newVal) =&gt; Value = newVal;\n\n public void Decay()\n {\n if (--remaining == 0)\n {\n SetEmpty();\n }\n }\n\n public override string ToString() =&gt; $\"{X}, {Y}\";\n }\n\n public class Snake\n {\n private readonly int maxSpeed = 5;\n private readonly int delayMultiplier = 700;\n\n public Cell Head { get; private set; }\n public LinkedList&lt;Cell&gt; Body { get; private set; }\n public Cell Tail =&gt; Body.Last();\n public Direction Direction { get; private set; }\n public int Length =&gt; BodyLength + 1;\n public int BodyLength =&gt; Body.Count; // full length includes head\n public int Speed { get; private set; }\n public bool HasEaten { get; private set; }\n\n public Snake(Cell head, LinkedList&lt;Cell&gt; body, Direction initialHeading, int speed = 1)\n {\n Head = head;\n Body = body;\n Speed = Math.Min(speed, maxSpeed);\n Direction = initialHeading;\n Head.SetHead(Direction.HeadToken);\n }\n\n public void Move(Direction direction, Cell nextHead)\n {\n var originalHead = Head;\n\n Direction = direction;\n\n HasEaten = false; //reset to false on each turn\n\n //be sure to eat before resetting the head cell to an arrow\n if (nextHead.IsFood)\n {\n Eat();\n }\n\n Head = nextHead;\n\n Head.SetHead(direction.HeadToken);\n\n moveBody(originalHead);\n\n pause(); //controls speed of play\n }\n\n public void Eat()\n {\n HasEaten = true;\n }\n\n public void Grow(Cell newTail)\n {\n newTail.SetBody(1);\n Body.AddLast(newTail);\n }\n\n private void moveBody(Cell originalHead)\n {\n foreach (var cell in Body)\n {\n cell.Decay(); //handles clearing\n }\n Body.AddFirst(originalHead);\n originalHead.SetBody(BodyLength - 1);\n Body.RemoveLast();\n }\n\n private void pause() =&gt; Thread.Sleep(maxSpeed - Speed + 1 * delayMultiplier);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-16T19:11:53.437", "Id": "409260", "Score": "0", "body": "I dont understand why 'static' and 'public' are always a big nono, whats bad with them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-16T20:53:01.040", "Id": "409270", "Score": "0", "body": "Under the principle of encapsulation, `public` should be used to expose things that it makes sense for other objects to see and/or use. Everything else should be `private` within the class itself or `protected` within the class and its descendants (classes that inherit from it). `Static` is a different story. It exposes things globally, which is contrary to encapsulation. Furthermore, excessive use of static makes your program procedural instead of being a collection of objects working together." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-13T19:09:59.483", "Id": "211429", "ParentId": "210835", "Score": "1" } } ]
{ "AcceptedAnswerId": "211158", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T19:14:03.937", "Id": "210835", "Score": "10", "Tags": [ "c#", "game", "console", "snake-game" ], "Title": "Console snake game in C#" }
210835
<p>I have to read a lot of code and search through many code bases. I frequently find myself using something like <code>grep -r --include=.C "test string" .</code> to find files containing a certain string or regular expression. However, to simplify this and expedite the process, I want to create a function that allows me to specify what I am looking for, what are acceptable file extensions and what are inacceptable file extensions. </p> <p>The function I have written is below. I am not sure if this follows best practices. Also, the hack using the brace expansion with the <code>.\?</code> is bad. I really appreciate any feedback that you have.</p> <pre><code>findInFile() { # Function to be placed in bash profile # Allows user to specify what contents of a file they are looking for # in what file types and in what NOT file types # Iterate over the number of scripts arugments # TODO: How can I create documentation for this function outside of code comments? while [[ "$#" -gt 0 ]] do case $1 in -ft|--fileTypes) local fileTypes=$2 ;; -et|--excludeTypes) local excludeTypes=$2 ;; *) # Catch the case where user does not specify # these arguments local searchTerm=$1 ;; esac shift done echo "fileTypes: $fileTypes" echo "excludeTypes: $excludeTypes" echo "searchTerm: $searchTerm" # TODO: Should probably clean up with case statement # TODO: I am using this \? in the include and exclude as a hack # to catch the case where only one file type is provided. if [ -n "$fileTypes" ] &amp;&amp; [ -n "$excludeTypes" ] then #searchString="grep -r --include=\*{$fileTypes} --exclude=\*{$excludeTypes} "$searchTerm" ." searchString="grep -r --include=\*{$fileTypes,.\?} --exclude=\*{$excludeTypes,.\?} "$searchTerm" ." elif [ -n "$fileTypes" ] then #searchString="grep -r --include=\*{$fileTypes} "$searchTerm" ." searchString="grep -r --include=\*{$fileTypes,.\?} "$searchTerm" ." elif [ -n "$excludeTypes" ] then #searchString="grep -r --exclude=\*{$excludeTypes} "$searchTerm" ." searchString="grep -r --exclude=\*{$excludeTypes,.\?} "$searchTerm" ." else searchString="grep -r "$searchTerm" ." fi #searchString="grep -r --include=\*{$fileTypes} "$searchTerm" ." echo "searchString: $searchString" eval $searchString # TODO: Allow the user to type a number to then programmatically jump to that # file in the text editor of their choice } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T01:10:33.580", "Id": "407609", "Score": "0", "body": "check out ack and its contemporaries, designed to solve your exact problem. `grep -r --include=.C \"test string\"` becomes `ack --cc \"test string\"`\n\n\nhttps://beyondgrep.com/feature-comparison/\nhttps://beyondgrep.com/why-ack/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T02:00:00.963", "Id": "407612", "Score": "1", "body": "You should have a look at [`ag`, the silver searcher](https://geoff.greer.fm/ag/) -- very fast, automatically recursive, PCRE regexes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T05:52:14.000", "Id": "407624", "Score": "0", "body": "@glenn take a look at ripgrep " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:14:49.893", "Id": "407667", "Score": "1", "body": "I feel silly. All of these look like awesome options. I have been writing grep for years! This has been really helpful. Thank you everyone." } ]
[ { "body": "<p>You can use <code>[[ .. ]]</code> instead of <code>[ .. ]</code> to do tests. The former is a bash builtin and saves a fork.</p>\n\n<p>You don't need to eval anything since you're just building a couple of optional switches to grep. Start with empty strings and populate variables or an array, and pass the result to an invocation of grep as variables. This also avoids enumerating every possible combination of arguments (already 4 combos with 2 options -- that approach quickly becomes unsustainable).</p>\n\n<p>There's no need to absorb searchTerm. Just leave it in the arguments and pass all those to grep, which allows you to include grep switches too, like <code>-i</code>.</p>\n\n<p>Use <code>set +x</code> to see what's going on.</p>\n\n<p>Tying it all together:</p>\n\n<pre><code>findInFile() {\n :&lt;&lt;_comment_\n Function to be placed in bash profile\n Allows user to specify what contents of a file they are looking for\n in what file types and in what NOT file types\n Iterate over the number of scripts arugments\n_comment_\n declare -a select\n while [[ \"$#\" -gt 0 ]]\n do\n if [[ $1 =~ ^(-ft|--fileTypes|-et|--excludeTypes)$ ]]\n then\n local type=\"$2\"\n [[ \"$type\" == *,* ]] &amp;&amp; type=\"{$type}\"\n if [[ $1 == *-f* ]]\n then \n select+=( \"--include=*$type\" )\n else\n select+=( \"--exclude=*$type\" )\n fi\n shift 2\n else\n break\n fi\n done\n set -x\n grep -r ${select[@]} \"$@\" .\n { set +x; } 2&gt;/dev/null\n}\n</code></pre>\n\n<p>You can include long comments as here-docs piped to the null operator <code>:</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T01:53:36.173", "Id": "210849", "ParentId": "210845", "Score": "3" } } ]
{ "AcceptedAnswerId": "210849", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T23:42:54.833", "Id": "210845", "Score": "4", "Tags": [ "bash", "shell" ], "Title": "Bash function to find contents of a file with a certain extension" }
210845
<p>I'm writing a small C++14 library for myself that allows me to decorate a type with dimensionality information, so that I can leverage the template/type system to avoid mistakes such as adding velocity to distance (or similar). This is my first time working with C++ templates to any meaningful extent. I know that this reinvents the wheel, but I'm trying to focus more on improving my skills with C++ and C++ template programming.</p> <p>In my approach, I'm wrapping some type (let's call it <code>TYPE</code>) in an instantiation of a class template (<code>dim</code>). This template includes other template arguments (<code>LEN</code>, <code>MASS</code>, <code>TIME</code>), each of which corresponds to the power of that fundamental unit. For example, a 64-bit floating point acceleration (length*time<sup>-2</sup>) would be a <code>dim&lt;double, 1, 0, -2&gt;</code>. </p> <p>I don't want to deal with the complexity of wrapping a vector/collection type and implementing logic to wrap and unwrap dimensional values when indexing into the collection, so I expect that a vector of masses would be a <code>vector&lt;dim&lt;double, 0, 1, 0&gt;&gt;</code>, not a <code>dim&lt;vector&lt;double&gt;, 0, 1, 0&gt;</code></p> <p>My goals are to keep the code memory- and time-efficient at runtime when compiled with optimization enabled, while keeping it fairly convenient to use. So far, inspections of assembly make me believe that this is the case (the class is only as large the type it wraps, and the assembly looks terse and clean).</p> <p>Eventually, I would like to include some dimensionally-aware specializations of helpers such as square root, power, etc, as well as other underlying types used for the dimensional value (so I could have e.g. a dimensioned value including experimental uncertainty i.e. <code>dim&lt;uncertain&lt;double&gt;, 1, 1, -2</code>)</p> <p>The class definition is below. Please note that I've removed some repetitive operator overloads (e.g. subtraction and division, because they are analogous to addition and multiplication)</p> <pre><code>#ifndef DIMENSIONAL_DIMENSIONAL_H #define DIMENSIONAL_DIMENSIONAL_H #include &lt;type_traits&gt; #include &lt;ostream&gt; template&lt;class TYPE, int LEN, int MASS, int TIME&gt; class dim { TYPE value_; public: dim(const TYPE value) : value_(value) {} // construct explicitly // copy, allowing conversion of contained type // Unfortunately, this doesn't warn properly for narrowing conversions. template&lt;class TYPE2&gt; explicit dim(const dim&lt;TYPE2, LEN, MASS, TIME&gt; &amp;d) { value_ = d.value(); } dim(dim&lt;TYPE, LEN, MASS, TIME&gt; const &amp;d) { value_ = d.value(); } // comparison // it's possible to make this a non-template function(dim&lt;TYPE, LEN, MASS, TIME&gt; &amp;rhs) // However, template and static_assert gives better diagnostics to the user. template&lt;class TYPE2, int LEN2, int MASS2, int TIME2&gt; bool operator==(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) const { static_assert(std::is_same&lt;TYPE, TYPE2&gt;(), "Integral type of dimensional expressions must match"); static_assert(LEN == LEN2 &amp;&amp; MASS == MASS2 &amp;&amp; TIME == TIME2, "Dimension types of dimensional expressions must match"); return value_ == rhs.value_; } bool operator!=(const dim &amp;rhs) const { return !(rhs == *this); } template&lt;class TYPE2, int LEN2, int MASS2, int TIME2&gt; bool operator&lt;(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) const { static_assert(LEN == LEN2 &amp;&amp; MASS == MASS2 &amp;&amp; TIME == TIME2, "Dimension types of dimensional expressions must match"); return value_ &lt; rhs.value_; } bool operator&gt;(const dim &amp;rhs) const { return rhs &lt; *this; } bool operator&lt;=(const dim &amp;rhs) const { return !(rhs &lt; *this); } bool operator&gt;=(const dim &amp;rhs) const { return !(*this &lt; rhs); } // arithmetic template&lt;class TYPE2, int LEN2, int MASS2, int TIME2, typename RTYPE=typename std::common_type&lt;TYPE, TYPE2&gt;::type&gt; auto operator+(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) const { static_assert(LEN == LEN2 &amp;&amp; MASS == MASS2 &amp;&amp; TIME == TIME2, "Dimension types of dimensional expressions must match"); return dim&lt;RTYPE, LEN, MASS, TIME&gt;(value() + rhs.value()); } template&lt;class TYPE2, int LEN2, int MASS2, int TIME2&gt; auto operator+=(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) { static_assert(LEN == LEN2 &amp;&amp; MASS == MASS2 &amp;&amp; TIME == TIME2, "Dimension types of dimensional expressions must match"); value_ += rhs.value(); return *this; } // subtraction implemented similarly template&lt;class TYPE2, int LEN2, int MASS2, int TIME2, typename RTYPE=typename std::common_type&lt;TYPE, TYPE2&gt;::type&gt; auto operator*(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) const { return dim&lt;RTYPE, LEN+LEN2, MASS+MASS2, TIME+TIME2&gt;(value() * rhs.value()); } template&lt;class TYPE2, typename RTYPE=typename std::common_type&lt;TYPE, TYPE2&gt;::type&gt; auto operator*(const TYPE2 &amp;rhs) const { return dim&lt;RTYPE, LEN, MASS, TIME&gt;(value() * rhs); } template&lt;class TYPE2, int LEN2, int MASS2, int TIME2&gt; auto operator*=(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) { static_assert(LEN2 == 0 &amp;&amp; MASS2 == 0 &amp;&amp; TIME2 == 0, "Compound multiplication only defined for unitless right-hand-side"); value_ *= rhs.value(); return *this; } auto operator*=(const TYPE &amp;rhs) { value_ *= rhs; return *this; } // division implemented similarly // mutation void set(TYPE value) { value_ = value; } template&lt;class TYPE2, int LEN2, int MASS2, int TIME2&gt; dim&lt;TYPE, LEN, MASS, TIME&gt;&amp; operator=(const dim&lt;TYPE2, LEN2, MASS2, TIME2&gt; &amp;rhs) { static_assert(LEN == LEN2 &amp;&amp; MASS == MASS2 &amp;&amp; TIME == TIME2, "Dimension types of dimensional expressions must match"); value_ = rhs.value(); return *this; } dim&lt;TYPE, LEN, MASS, TIME&gt;&amp; operator=(TYPE rhs) { value_ = rhs; return *this; } // conversion TYPE value() const { return value_; } operator TYPE() const { static_assert(LEN == 0 &amp;&amp; MASS == 0 &amp;&amp; TIME == 0, "Conversion operator only defined for dimensionless values."); return value_; } friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const dim &amp;d) { // Snip; prints e.g. "9.81 [m^1 s^-2]" } }; template&lt;typename T&gt; dim&lt;T, 0, 0, 0&gt; make_pure(T t) { return dim&lt;T, 0, 0, 0&gt;(t); } #endif //DIMENSIONAL_DIMENSIONAL_H </code></pre> <p>Here's an example of how I would use it:</p> <pre><code>auto mass = dim&lt;double, 0, 1, 0&gt;(10); auto dist = dim&lt;double, 1, 0, 0&gt;(15); auto time = dim&lt;double, 0, 0, 1&gt;(5); auto momentum = mass*dist/time; std::cout &lt;&lt; "momentum: " &lt;&lt; momentum &lt;&lt; std::endl; </code></pre> <p>Of course, in a larger project, I could use type aliases for useful derived units.</p> <p>I'm currently facing some difficulties with the special-case of unitless values (i.e. <code>dim&lt;TYPE, 0, 0, 0&gt;</code>). The multiplication and division operator overloads are fairly bloated since they special-case the multiplication by a "normal" numeric type. I'm wondering if it's worth it to implicitly convert e.g. double into <code>dim&lt;double, 0, 0, 0&gt;</code>, to avoid this bloat and facilitate cleaner usage.</p> <p>I'm also facing the issue of extending the set of base units to include other base units (bits, kelvin, etc). The current design isn't terribly extensible and requires additional template arguments added everywhere whenever a new base unit is added. </p>
[]
[ { "body": "<p>Well, instead of reinventing the well, I have done a search and found:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/21868368/units-of-measurement-in-c\">Design patterns - Units of measurement in C++</a></li>\n<li><a href=\"https://stackoverflow.com/questions/19910888/type-safe-physics-operations-in-c\">C++11 - Type safe physics operations in C++</a></li>\n<li><a href=\"https://www.codeproject.com/Articles/791511/%2fArticles%2f791511%2fUnits-of-measurement-types-in-Cplusplus-Using-comp\" rel=\"nofollow noreferrer\">Units of measurement types in C++. Using compile time template programming</a></li>\n</ul>\n\n<p>From those links, you can find other links like units from boost.</p>\n\n<p>Some library are more complete than others and will allows to do unit conversions for example.</p>\n\n<p>By the way, C++ already contains units for duration (seconds, minutes, hours…)</p>\n\n<p>As you have noticed, your approach don't scale well when adding other unit types and is relatively limited since you only support some unspecified unit for a given measurement (are you using SI or US units?). </p>\n\n<p><del>Finally some of your operator seems to return incorrect type like <code>operator *</code> which seems to ignore LEN2, MASS2...</del> OK This one is used when multiplying by a number.</p>\n\n<ul>\n<li>In the constructor <code>dim(const TYPE value)</code> there is no point to specify <code>const</code>. In fact, you might want to prevent <code>TYPE</code> from being a reference.</li>\n<li>You might consider making that constructor <code>explicit</code> to prevent unwanted conversion.</li>\n<li>For * operator, you might want to provide an operator where the left hand-side is a number. It would need to be a free function. Because of commutativity, you could simply call existing member function that take a number on the right side.</li>\n<li>For your comparison operators, you don't handle right-hand side the same way for all operators if left and right operator are not of the same type. For <code>==</code> and <code>&lt;</code> you will get a static assertion if the dimensions are different while for others (!=, >, &lt;=, >=), the function would not be defined (and the conversion constructor would not be used because it is explicit). </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T02:36:41.127", "Id": "407613", "Score": "0", "body": "Thank you for the feedback and the references on other implementations. In spite of the other solutions I'd still like to finish reinventing this wheel for the practice with the language. That said, I'm struggling to see the error on `operator*`'s overloads since I'm not fully comfortable with the template logic involved; as far as I can tell I am properly adding the base unit exponents in the `operator*(dim...` overload and handling a unitless scalar as a unitless scalar in the `operator*(TYPE2` version. Would you be able to clarify the issue there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T14:14:10.847", "Id": "407656", "Score": "1", "body": "Nevertheless, there is no point for us to repeat what others have already done. At that point, you know some limitation of your approach like hard to add new units so most improvement will come by learning what other have done. Once read, you could try to do it by yourself maybe a few days later without using the reference." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T02:21:37.623", "Id": "210851", "ParentId": "210847", "Score": "1" } } ]
{ "AcceptedAnswerId": "210851", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T00:01:54.813", "Id": "210847", "Score": "3", "Tags": [ "c++", "reinventing-the-wheel", "c++14", "template-meta-programming" ], "Title": "C++ template-based dimension-tagged type" }
210847
<p>I tried to implement a Python-esque <code>list</code> in C. Having not really used C in anger, I'd like some pointers on style and error handling in particular.</p> <h2>Header</h2> <pre><code>#ifndef __TYPE_LIST_H__ #define __TYPE_LIST_H__ /* Generic list implementation for holding a set of pointers to a type (has to be consistently handled by the element_match and element_delete functions) */ typedef struct list_s list_t; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; extern const uint16_t default_capacity; list_t* list_create( uint16_t initial_capacity, bool (*element_match )(const void* a, const void* b), void (*element_delete)(void* element)); void list_delete(list_t* list); bool list_append(list_t* list, void* element); void* list_pop(list_t* list); bool list_remove(list_t* list, void* element); int16_t list_index(list_t* list, void* element); bool list_contains(list_t* list, void* element); bool list_empty(list_t* list); #endif </code></pre> <h2>Source</h2> <pre><code>#include &lt;type/list.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; const uint16_t default_capacity = 256; struct list_s { uint16_t length; uint16_t capacity; void** elements; bool (*element_match )(const void* a, const void* b); void (*element_delete)(void* element); }; list_t* list_create( uint16_t initial_capacity, bool (*element_match )(const void* a, const void* b), void (*element_delete)(void* element)) { list_t* list = (list_t*) malloc(sizeof(list_t)); if (!list) return NULL; if (!initial_capacity) { initial_capacity = default_capacity; } list-&gt;elements = (void**) malloc(sizeof(void*) * initial_capacity); if (!list-&gt;elements) return NULL; list-&gt;length = 0; list-&gt;capacity = initial_capacity; list-&gt;element_match = element_match; list-&gt;element_delete = element_delete; return list; } void list_delete(list_t* list) { if (!list) return; if (list-&gt;element_delete) { unsigned i; for (i = 0; i&lt; list-&gt;length; i++) { list-&gt;element_delete(list-&gt;elements[i]); } } else { fprintf(stderr, "WARNING: no element_delete specified"); } free(list); } bool list_append(list_t* list, void* element) { if (!list || !element) return false; if (list-&gt;length &gt;= list-&gt;capacity) { // expand the elements array list-&gt;capacity *= 2; list-&gt;elements = realloc(list-&gt;elements, sizeof(void*) * list-&gt;capacity); if (!list-&gt;elements) { return false; } } list-&gt;length += 1; list-&gt;elements[list-&gt;length] = element; return true; } void* list_pop(list_t* list) { if (!list || list_empty(list)) { return NULL; } void* element = list-&gt;elements[list-&gt;length]; list-&gt;elements[list-&gt;length] = NULL; list-&gt;length -= 1; return element; } bool list_remove(list_t* list, void* element) { if (!list || !list-&gt;element_match) { return false; } unsigned i; bool found = false; for (i = 0; i &lt; list-&gt;length; i++) { if (!found &amp;&amp; list-&gt;element_match(list-&gt;elements[i], element)) { found = true; list-&gt;length -= 1; } if (found) { // shift all subsequent elements back one list-&gt;elements[i] = list-&gt;elements[i + 1]; } } return found; } int16_t list_index(list_t* list, void* element) { int16_t i; for (i = 0; i &lt; list-&gt;length; i++) { if (list-&gt;element_match(list-&gt;elements[i], element)) { return i; } } return -1; } bool list_contains(list_t* list, void* element) { return (list_index(list, element) != -1); } bool list_empty(list_t* list) { return (list-&gt;length == 0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T03:26:33.577", "Id": "408700", "Score": "0", "body": "I wanted to suggest you add a `main` so that the code is self-contained and can be compiled and tested without further effort. It would also show a usage example. But you already have collected 7 (!!!) answers, so you probably don’t care to do so. :/" } ]
[ { "body": "<p>You error on missing function pointers when you try and use them. You should error out when you create the list.</p>\n\n<p>Don't printf in library functions, even to stderr. </p>\n\n<p><code>uint16_t</code> only allows 65k elements, this is really tiny for a list.</p>\n\n<p>You don't allow NULL elements. Sometimes you want NULL elements in your list, it's a big reason why one would use a list of pointers instead of a list by value.</p>\n\n<p>There is no way to index into the list or iterate over it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:34:42.987", "Id": "407692", "Score": "0", "body": "Thanks for the tips. Re: \"Don't printf in library functions\" - can you expand on why? Should I be returning error codes or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T00:06:05.367", "Id": "408590", "Score": "0", "body": "`C` error reporting is really up to you, but here I would specify that `element_delete` be in `list_create`, and if it's null, you should return null and set `errno`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T13:41:48.613", "Id": "210868", "ParentId": "210861", "Score": "4" } }, { "body": "<h2>Consider using <code>restrict</code></h2>\n\n<p>...on your pointer arguments. If you aren't familiar with this keyword, it requires more explanation than can reasonably go into this answer, so you'll have to do some reading, but - in short, it can help with performance.</p>\n\n<h2>Use a <code>define</code> instead of a variable</h2>\n\n<p>This:</p>\n\n<pre><code>extern const uint16_t default_capacity;\n</code></pre>\n\n<p>isn't terrible, but it hinders the compiler's capability to optimize based on known constants. Advanced compilers with \"whole program optimization\" that have an optimization stage between object compilation and link can figure this out, but older or naively configured compilers won't. Using a <code>#define</code> in your header will fix this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:45:56.370", "Id": "407696", "Score": "0", "body": "\"[restrict] requires more explanation than can reasonably go into this answer\", no it really doesn't, restrict isn't voodo magic, it is a way for the programmer to tell the compiler \"these pointers are un related, and point to different objects\". What I said might have even been shorter than your own explanation that you couldn't explain it. Not to mention it can also *hurt* performance on certain platforms. For example, in CUDA, using restrict can cause register pressure and lower occupancy on SMs (though not always)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:51:59.257", "Id": "407698", "Score": "0", "body": "@opa I didn't say it was voodoo; I said it *can* (and not *will*) improve performance; and I recommended that the OP *consider* adding this, rather than unconditionally recommending that it be added. You say that the topic is trivially explained, but then contradict this by saying that the behaviour is complex and platform-dependent. So I maintain my recommendation that the OP do further reading." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:57:17.127", "Id": "407699", "Score": "0", "body": "I literally explained it, the explanation was trivial, the consequences of using it are not trivial, but then again, literally nothing low level is going to be trivial with respect to determining performance for all platforms, even using inlined constants and instructions can cause instruction cache misses critically lowering performance, but the actual explanation of such ideas is fairly simple. In the time you've spent providing excuses and avoiding explaining something important that could help OP, you could have written up a short explanation of restrict." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:18:35.007", "Id": "407704", "Score": "1", "body": "@opa but the subtleties around letting the compiler assume it are not that trivial." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T02:08:50.733", "Id": "408594", "Score": "0", "body": "I prefer the extern constant as it reduce compilation dependencies and avoiding macros is a good thing too." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:02:43.973", "Id": "210880", "ParentId": "210861", "Score": "4" } }, { "body": "<p>What I see:</p>\n\n<p>Like <a href=\"https://codereview.stackexchange.com/a/210868/137598\">this answer states</a> you should not be printing as an recoverable error. If your program needs to crash, then you can print, but printing when execution of the program should continue will unexpectedly fill the output stream with stderr symbols that the end user has no easy control of stopping. Instead, use return codes and possibly provide your own error function that returns the proper string of characters that need to be printed based upon the error code. That way they can choose to check the error code, do nothing, fix the problem, or crash on their own volition. </p>\n\n<p>I'm not sure why you chose <code>uint16_t</code> as your list size type, but incase there are actually situations in which you want to do this, I would suggest instead using </p>\n\n<pre><code>typedef uint16_t list_size_t;\n</code></pre>\n\n<p>so you could potentially do something like:</p>\n\n<pre><code>#if defined MY_UINT64_DEFINED_VAR\ntypedef uint64_t list_size_t;\n#elif defined MY_UINT32_DEFINED_VAR\ntypedef uint32_t list_size_t;\n#elif defined MY_UINT16_DEFINED_VAR\ntypedef uint16_t list_size_t;\n#endif\n</code></pre>\n\n<p>provided you can find a compiler variable or find the size of int or some other compile time definition to figure out the size type you want your system to use. </p>\n\n<p>You also need to be able to iterate through list elements. I suggest using a function like:</p>\n\n<pre><code>void* list_get(list_size_t index)\n</code></pre>\n\n<p>which would then return the pointer to the element at the given index. </p>\n\n<p>Another thing you might want to consider is namespace conflicts with:</p>\n\n<pre><code>typedef struct list_s list_t \n</code></pre>\n\n<p>Because of the lack of namespaces in C, such names can conflict with other names within the same scope and lead to a whole bunch of odd errors that may or may not be hard to track down. list_t is such a generic name, I'm not sure it is appropriate to use directly here, you may want to not pollute the namespace with list_t, and instead keep it as struct list_s. However there is another solution to this problem that also solves other potential namespace conflicts. </p>\n\n<p>You may want to prefix all of your names with a sort of psuedo namespace specifier (which a lot of other C APIs do, like opengl, vulkan opencv's now defunct C api etc...)</p>\n\n<p>I would recommend even doing this on macros as well, as they have the same problem (and this practice is also standard). </p>\n\n<p>for example, lets say you decide to use \"abc\" as your pseudo namespace name. You would then change:</p>\n\n<pre><code>bool list_append(list_t* list, void* element);\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>bool abc_list_append(abc_list_t* list, void* element);\n</code></pre>\n\n<p>yes, this is annoying, but if someone wants to use your library but wants multiple list types, or have multiple libraries called list but don't do the same thing, then they are out of luck. If you use a \"pseudo namespace\" then they can avoid many of these conflicts. If however, this is only supposed to be used internally in another project or is never going to be released to be used as its own library, you do not have to worry about name-spacing these components to other people, though you may still find conflicts on your own. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T18:41:32.380", "Id": "210896", "ParentId": "210861", "Score": "3" } }, { "body": "<ul>\n<li><p>Do not cast what <code>malloc</code> returns.</p></li>\n<li><p>It is beneficial to take size of a variable, rather than a type.</p>\n\n<pre><code> list_t* list = malloc(sizeof *list);\n</code></pre>\n\n<p>is immune to possible changes in type of <code>list</code>.</p>\n\n<p>Along the same line, <code>calloc</code> is preferable when allocating arrays. First, the allocated memory is in known state, and second, multiplication <code>size * number</code> may overflow. Consider</p>\n\n<pre><code> list-&gt;elements = calloc(initial_capacity, sizeof list-&gt;elements[0]);\n</code></pre></li>\n<li><p><code>list_delete</code> doesn't <code>free(list-&gt;elements)</code>.</p></li>\n<li><p><code>list-&gt;elements[0]</code> is never initialized. This would cause problems with <code>list_delete</code>. Similarly, <code>list_delete</code> does not touch the last element. Along the same line, <code>list-&gt;elements[list-&gt;length]</code> gives an impression of out of bounds access.</p>\n\n<p>An idiomatic way would be to assign the pointer first, and only then increment the length, e.g.</p>\n\n<pre><code> list-&gt;elements[list-&gt;length++] = element;\n</code></pre></li>\n<li><p><code>list_remove</code> is unnecessarily complicated. Consider breaking it up, e.g.</p>\n\n<pre><code> i = list_index(list, element)\n\n if (i == -1) {\n return false;\n }\n\n while (i &lt; list_length - 1) {\n list-&gt;elements[i] = list-&gt;elements[i+1];\n }\n</code></pre>\n\n<p>I also recommend to factor the last loop out into a <code>list_shift</code> method.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T03:29:06.300", "Id": "408701", "Score": "2", "body": "That should be `malloc(sizeof list)`. You probably need more space than a single pointer..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:11:10.257", "Id": "210905", "ParentId": "210861", "Score": "4" } }, { "body": "<p>In addition to list_get, as opa mentioned, and list_size / list_length to go with it, I would include a version of list_remove that takes an index instead of an element to compare to, for the fairly common scenario where you want to see if an element is in the list, possibly do something with it, and then delete it.</p>\n\n<pre><code>int player_index = list_index(entity_list, \"player\");\nif(player_index == -1) \n{\n handle_no_player();\n}\nelse\n{\n handle_player();\n list_remove_at(entity_list, player_index);\n}\n</code></pre>\n\n<p>Also, since you're using a function pointer for equality comparison anyway, it would be easy to include a version that takes a predicate:</p>\n\n<pre><code>bool is_on_fire(void *entity) { return ((game_entity*)entity)-&gt;on_fire; }\nint first_on_fire = list_index(entity_list, &amp;is_on_fire);\n</code></pre>\n\n<p>As the name first_on_fire indicates, the third issue is that if this is representing a general list rather than a set (meaning there can be duplicate elements), then you need a version of list_index that takes a starting index to search from, so that it's possible to find the second / third / nth instance of a given element.</p>\n\n<p>list_pop is an ambiguous name, since it's not apparent whether it works like a stack or a queue. list_pop_back would be more clear.</p>\n\n<p>A function that inserts into the middle of a list could be useful as well. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:18:20.827", "Id": "210906", "ParentId": "210861", "Score": "3" } }, { "body": "<p><strong>Surprising name</strong></p>\n\n<p><code>default_capacity</code> is in the public .h file</p>\n\n<p>In a header for <code>list_this</code> and <code>list_that</code>, finding <code>default_capacity</code> is not good and a name-space collision headache. Suggest <code>list_default_capacity</code> instead.</p>\n\n<p><strong>0 allocation</strong></p>\n\n<p>Be careful about allocating 0 memory (possible with <code>default_capacity == 0</code> and <code>list_create(0, ...)</code>). Receiving <code>NULL</code> in that case does not certainly indicate an out-of-memory condition.</p>\n\n<pre><code>// list-&gt;elements = (void**) malloc(sizeof(void*) * initial_capacity);\n// if (!list-&gt;elements) return NULL;\n\nlist-&gt;elements = malloc(sizeof list-&gt;elements[0] * initial_capacity);\nif (list-&gt;elements == NULL &amp;&amp; initial_capacity == 0) {\n return NULL;\n}\n</code></pre>\n\n<p><strong><code>default_capacity</code> not needed</strong></p>\n\n<p>With generic list code, I'd expect the ability to create a 0 length list and not have 0 indicate \"use a default value\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T00:28:52.070", "Id": "211005", "ParentId": "210861", "Score": "5" } }, { "body": "<p>Probably pedantic, but your code could be more robust to errors without significant changes. In your constructor, you could fail-fast the <code>element_delete</code> and not worry about it in your destructor. Instead of going though serially and initialising one by one in <code>create_list</code>, consider setting values to the default first before calling <code>malloc</code>; then you're always in a valid state.</p>\n\n<pre><code>/* The newly created list or a null pointer and errno is set, (probably, it\n depends what standard you're using for it to be guaranteed.) */\nlist_t* list_create(\n const uint16_t initial_capacity,\n const bool (*element_match )(const void* a, const void* b),\n const void (*element_delete)(void* element)) \n{\n list_t* list;\n\n /* Pre-conditions. */\n if(!element_delete || !initial_capacity) {\n errno = EDOM;\n return NULL;\n }\n\n list = malloc(sizeof *list);\n if (!list) return NULL; /* The malloc will (probably) set the errno. */\n list-&gt;length = 0;\n list-&gt;capacity = initial_capacity;\n list-&gt;elements = NULL;\n list-&gt;element_match = element_match;\n list-&gt;element_delete = element_delete;\n\n /* This could fail, so it's after initialisation. */\n list-&gt;elements = malloc(sizeof *list-&gt;elements * initial_capacity);\n if (!list-&gt;elements) {\n list_delete(list);\n return NULL;\n }\n\n return list;\n}\n\n/* If the list has been initialised, this will work regardless. */\nvoid list_delete(const list_t* list) \n{\n unsigned i;\n if (!list) return;\n for (i = 0; i &lt; list-&gt;length; i++) {\n list-&gt;element_delete(list-&gt;elements[i]);\n }\n free(list-&gt;elements);\n free(list);\n}\n</code></pre>\n\n<p>(I haven't tested this. You will need to <code>#include &lt;errno.h&gt;</code>.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T01:15:43.693", "Id": "211298", "ParentId": "210861", "Score": "3" } }, { "body": "<p>For anyone curious, here's my code with the comments taken on board:</p>\n\n<h2>Header</h2>\n\n<pre><code>#ifndef __TYPE_LIST_H__\n#define __TYPE_LIST_H__\n\n/* Generic list implementation for holding a set of pointers to a type\n (has to be consistently handled by the element_match and element_delete \n functions)\n*/\n\ntypedef struct sdlui_list_s sdlui_list_t;\n\n#include &lt;stdbool.h&gt;\n#include &lt;stdint.h&gt;\n\nsdlui_list_t* sdlui_list_create(\n uint32_t initial_capacity,\n bool (*element_match )(const void* a, const void* b),\n void (*element_delete)(void* element));\n\nvoid sdlui_list_delete(sdlui_list_t* list);\n\nbool sdlui_list_append (sdlui_list_t* list, void* element);\nbool sdlui_list_pop_back (sdlui_list_t* list, void* ret);\nbool sdlui_list_get (sdlui_list_t* list, uint32_t index, void* ret);\nbool sdlui_list_remove (sdlui_list_t* list, void* element);\nbool sdlui_list_remove_at (sdlui_list_t* list, uint32_t index);\nvoid sdlui_list_shift (sdlui_list_t* list, int64_t start_index);\nint64_t sdlui_list_index (sdlui_list_t* list, void* element);\nint64_t sdlui_list_index_from (sdlui_list_t* list, void* element,\n int64_t start_index);\nbool sdlui_list_contains (sdlui_list_t* list, void* element);\nbool sdlui_list_empty (sdlui_list_t* list);\nuint32_t sdlui_list_length (sdlui_list_t* list);\n\n#endif\n</code></pre>\n\n<h2>Source</h2>\n\n<pre><code>#include &lt;errno.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#include &lt;type/list.h&gt;\n\nstruct sdlui_list_s\n{\n uint32_t length;\n uint32_t capacity;\n void** elements;\n bool (*element_match )(const void* a, const void* b);\n void (*element_delete)(void* element);\n};\n\nsdlui_list_t* sdlui_list_create(\n uint32_t initial_capacity,\n bool (*element_match )(const void* a, const void* b),\n void (*element_delete)(void* element))\n{\n sdlui_list_t* list;\n\n if (!element_delete || !initial_capacity) {\n errno = EDOM;\n return NULL;\n }\n list = (sdlui_list_t*) malloc(sizeof(sdlui_list_t));\n if (!list) return NULL;\n\n list-&gt;length = 0;\n list-&gt;capacity = initial_capacity;\n list-&gt;element_match = element_match;\n list-&gt;element_delete = element_delete;\n\n list-&gt;elements = (void**) malloc(sizeof(list-&gt;elements[0]) * initial_capacity);\n if (!list-&gt;elements) {\n sdlui_list_delete(list);\n return NULL;\n }\n return list;\n}\n\nvoid sdlui_list_delete(sdlui_list_t* list)\n{\n unsigned i;\n for (i = 0; i&lt; list-&gt;length; i++) {\n list-&gt;element_delete(list-&gt;elements[i]);\n }\n free(list-&gt;elements);\n free(list);\n}\n\nbool sdlui_list_append(sdlui_list_t* list, void* element)\n{\n if (!list)\n return false;\n if (list-&gt;length &gt;= list-&gt;capacity) {\n // expand the elements array\n list-&gt;capacity *= 2;\n list-&gt;elements = realloc(list-&gt;elements, sizeof(void*) * list-&gt;capacity);\n if (!list-&gt;elements) {\n return false;\n }\n }\n list-&gt;elements[list-&gt;length++] = element;\n return true;\n}\n\nbool sdlui_list_get(sdlui_list_t* list, uint32_t index, void* ret) {\n if (!list || index &gt; list-&gt;length) {\n return false;\n }\n ret = list-&gt;elements[index];\n return true;\n}\n\nbool sdlui_list_pop_back(sdlui_list_t* list, void* ret)\n{\n if (!list || sdlui_list_empty(list)) {\n return false;\n }\n ret = list-&gt;elements[list-&gt;length];\n list-&gt;elements[list-&gt;length] = NULL;\n list-&gt;length--;\n return true;\n}\n\nbool sdlui_list_remove(sdlui_list_t* list, void* element)\n{\n int64_t i = sdlui_list_index(list, element);\n\n if (i == -1) {\n return false;\n }\n\n sdlui_list_shift(list, i);\n list-&gt;length--;\n return true;\n}\n\nbool sdlui_list_remove_at(sdlui_list_t* list, uint32_t index)\n{\n if (list-&gt;length == 0) {\n return false;\n }\n sdlui_list_shift(list, index);\n list-&gt;length--;\n return true;\n}\n\nvoid sdlui_list_shift(sdlui_list_t* list, int64_t start_index)\n{\n while ((uint32_t)start_index &lt; list-&gt;length - 1) {\n list-&gt;elements[start_index] = list-&gt;elements[start_index+1];\n start_index++;\n }\n}\n\nint64_t sdlui_list_index(sdlui_list_t* list, void* element)\n{\n return sdlui_list_index_from(list, element, 0);\n}\n\nint64_t sdlui_list_index_from (sdlui_list_t* list, void* element,\n int64_t start_index)\n{\n if (!list-&gt;element_match || list-&gt;length &lt; (uint32_t) start_index) {\n /* No way to compare */\n return -1;\n }\n uint32_t i;\n for (i = start_index; i &lt; list-&gt;length; i++) {\n if (list-&gt;element_match(list-&gt;elements[i], element)) {\n return i;\n }\n }\n return -1;\n}\n\n\nbool sdlui_list_contains(sdlui_list_t* list, void* element) {\n return (sdlui_list_index(list, element) != -1);\n}\n\nbool sdlui_list_empty(sdlui_list_t* list)\n{\n if (!list) {\n return false;\n }\n else {\n return (list-&gt;length == 0);\n }\n}\n\nuint32_t sdlui_list_length(sdlui_list_t* list) {\n return list-&gt;length;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:02:51.563", "Id": "212429", "ParentId": "210861", "Score": "0" } } ]
{ "AcceptedAnswerId": "210905", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T10:24:59.350", "Id": "210861", "Score": "5", "Tags": [ "beginner", "c", "reinventing-the-wheel" ], "Title": "List implementation in C" }
210861
<p>Given an array of words representing a sentence and a word to search for, the method must determine whether the word appears in the sentence.</p> <p><strong>Specifications</strong></p> <ul> <li>Case insensitive.</li> <li>The arguments are never <code>null</code>.</li> <li>The sentence is in the English language.</li> </ul> <pre class="lang-java prettyprint-override"><code>/** * A case-insensitive search on a sentence to find whether a given word can be found in it. It * keeps certain punctuation in mind. * * @param aSentence An array of words forming a sentence. Cannot be {@code null}. * @param aWord The word to search for. Cannot be {@code null}. * * @return {@code true} if the word appeared at least once in the sentence, {@code false} * otherwise. */ public boolean sentenceContainsWord(final String[] aSentence, String aWord) { // The search is case-insensitive aWord = aWord.toLowerCase(); // Loop through the words in the sentence for (int i = 0; i &lt; aSentence.length; i++) { String sentenceWord = aSentence[i]; // If the word in the sentence matches, return immediately if (sentenceWord.toLowerCase().equals(aWord)) { return true; } // The word could end with punctuation like a comma or a dot int lastSentenceWordIndex = sentenceWord.length() - 1; String lastCharacter = Character.toString(sentenceWord.charAt(lastSentenceWordIndex)); if (lastCharacter.matches("[.,:;]") &amp;&amp; sentenceWord.substring(0, lastSentenceWordIndex).equals(aWord)) { return true; } } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T12:26:46.870", "Id": "407650", "Score": "0", "body": "What about punctuation inside or in front of a word? `'Like,' he said 'RobAu's comment?'` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T12:33:20.863", "Id": "407651", "Score": "0", "body": "Also, if to pass an empty-string as word, you will get an `IndexOutOfBoundsException`" } ]
[ { "body": "<p>The String class provides the method <code>.equalsIgnoreCase()</code>. It seems to me, calling <code>.toLowerCase()</code> and then <code>.equals()</code> has to process the string twice, but could be done in a single run.</p>\n\n<p>It is unclear how well the sentence is processed before it enters the method as array. I will be a little optimistic in my assumptions.</p>\n\n<p>You can give it a cleaner structure using streams [if you are using Java 1.8 at least]. It provides a method <code>.noneMatch(predicate)</code> which is short-circuiting just as your loop is now. Using streams makes it easy to add a cascade of string preprocessing steps before the final comparison. Removing punctuation as you have it now, it could be written as follows:</p>\n\n<pre><code>import java.util.Arrays;\n\npublic static boolean sentenceContainsWord(final String[] aSentence, final String aWord)\n{\n return !Arrays.stream(aSentence)\n .map((w) -&gt; w.replaceAll(\"\\\\.|,|:|;\", \"\"))\n .noneMatch((w) -&gt; w.equalsIgnoreCase(aWord));\n}\n</code></pre>\n\n<p>My optimistic assumption here is that there is no punctuation in between a word which might result from a too simplistic tokenisation (e.g. <code>.split(\" \")</code>). Using <code>.replaceAll()</code> removes a lot of the clutter around finding trailing punctuation and extracting substrings.</p>\n\n<p><strong>Resources:</strong> </p>\n\n<ul>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#noneMatch-java.util.function.Predicate-\" rel=\"nofollow noreferrer\">Java Doc:\nStream::noneMatch</a></li>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-\" rel=\"nofollow noreferrer\">Java Doc:\nString::equalsIgnoreCase</a></li>\n<li><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-\" rel=\"nofollow noreferrer\">Java Doc:\nString::replaceAll</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T22:59:20.400", "Id": "211229", "ParentId": "210864", "Score": "2" } }, { "body": "<pre><code>boolean result = Arrays.asList(sentence.split(\"\\\\s+\")).contains(word);\n</code></pre>\n\n<p>If you want this solution to answer irrespective of lowercase or uppercase, then you can use String.toLowerCase() for all given inputs. </p>\n\n<pre><code>boolean result = Arrays.asList(sentence.toLowerCase().split(\"\\\\s+\")).contains(word.toLowerCase());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-11T20:28:21.523", "Id": "449294", "Score": "0", "body": "Punctuation was already highlighted in earlier comments." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-11T15:58:33.333", "Id": "230554", "ParentId": "210864", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T12:05:29.920", "Id": "210864", "Score": "3", "Tags": [ "java", "strings" ], "Title": "Determine whether a word appears in a sentence" }
210864
<h3>Introduction</h3> <p>I'm using Advent of Code 2018 to learn Python better, interested in the new type support for Python 3.7, I decided to go with that.</p> <p>Here is my solution to <a href="https://adventofcode.com/2018/day/4" rel="noreferrer">Advent of Code Day 4</a>, both part 1 and 2. I'm returning the answers for both part 1 and 2 as a tuple.</p> <h3>Problem Description</h3> <p>The problem essentially boils down to: Given a timestamped unsorted list of events of guards beginning their shift, waking up and falling asleep, determine the following:</p> <p>Part 1: Which guard is asleep the most and on which minute is that guard mostly asleep? Return guard id multiplied by the minute number.</p> <p>Part 2: Which guard is most frequently asleep on the same minute? Again, return guard id multiplied by the minute number.</p> <p>For full problem description, please see <a href="https://adventofcode.com/2018/day/4" rel="noreferrer">Advent of Code Day 4</a></p> <h3>Concerns</h3> <p>I'm a big fan of Java 8 Stream API and C# Linq, I kind of expected Python to be more like that. I'm not sure if the nested function calls like <code>sorted(list(...))</code> or <code>len(list(...))</code> are <em>"Pythonic"</em>. Likewise, it feels like I should be able to use some reducer-like function calls instead of imperatively looping through stuff to find the most common sleeper of some kind. Or is the way I have written this code the Python way to do it?</p> <h3>Code</h3> <pre><code>from dataclasses import dataclass from datetime import datetime from days import read_file from enum import Enum from collections import defaultdict, namedtuple from statistics import mode import statistics import operator import re class EventType(Enum): STARTS_SHIFT = 1 FALLS_ASLEEP = 2 WAKES_UP = 3 @dataclass class Event: time: datetime guard: int event: EventType @dataclass class GuardSleep: sleep_total: int last_sleep: int sleeps: list def add_sleeps(self, minute): for i in range(self.last_sleep, minute): self.sleeps.append(i) def get_guard(line: str): if "Guard" in line: guard_id = re.search("Guard #(\\d+)", line) return int(guard_id.group(1)) return -1 def event_type(line): if "begins shift" in line: return EventType.STARTS_SHIFT if "falls asleep" in line: return EventType.FALLS_ASLEEP if "wakes up" in line: return EventType.WAKES_UP raise Exception("Unknown line: " + line) def day4() -&gt; (int, int): events = sorted(list(Event(datetime.strptime(line[1:17], "%Y-%m-%d %H:%M"), get_guard(line), event_type(line)) for line in read_file(4)), key=operator.attrgetter("time")) guard = -1 guardsleep = defaultdict(lambda: GuardSleep(0, 0, [])) for event in events: if event.guard &gt;= 0: guard = event.guard if event.event == EventType.FALLS_ASLEEP: guardsleep[guard].last_sleep = event.time.minute if event.event == EventType.WAKES_UP: guardsleep[guard].sleep_total += event.time.minute - guardsleep[guard].last_sleep guardsleep[guard].add_sleeps(event.time.minute) most_sleepy_guard_number = max(guardsleep, key=(lambda key: guardsleep[key].sleep_total)) most_sleepy_guard = guardsleep[most_sleepy_guard_number] part1_result = most_sleepy_guard_number * mode(sorted(most_sleepy_guard.sleeps)) # Part 2 MostSleepy = namedtuple('MostCommon', ['id', 'minute', 'amount']) most_sleepy = MostSleepy(0, 0, 0) for k in guardsleep: current_guard = guardsleep[k] try: most_common_minute = mode(sorted(current_guard.sleeps)) amount = len(list((m for m in current_guard.sleeps if m == most_common_minute))) if amount &gt; most_sleepy.amount: most_sleepy = MostSleepy(k, most_common_minute, amount) except statistics.StatisticsError: print("No unique most common minute for " + str(k)) return part1_result, most_sleepy.id * most_sleepy.minute if __name__ == '__main__': print(day4()) </code></pre>
[]
[ { "body": "<h2>Replacing chained <code>if</code> with dictionary lookup</h2>\n\n<p>This function:</p>\n\n<pre><code>def event_type(line):\n if \"begins shift\" in line:\n return EventType.STARTS_SHIFT\n if \"falls asleep\" in line:\n return EventType.FALLS_ASLEEP\n if \"wakes up\" in line:\n return EventType.WAKES_UP\n raise Exception(\"Unknown line: \" + line)\n</code></pre>\n\n<p>isn't bad, but chained <code>if</code> like this smell. It may be better represented as a dictionary, where the key is the string above, the value is the enum value, and you do a simple key lookup based on the last two words of every line. Whereas chained <code>if</code> is worst-case O(n), dictionary lookup is O(1). Then - no <code>if</code>s needed, and you get the exception for free if key lookup fails.</p>\n\n<h2>Use raw strings</h2>\n\n<pre><code>re.search(\"Guard #(\\\\d+)\", line)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>re.search(r\"Guard #(\\d+)\", line)\n</code></pre>\n\n<h2>Settle down with the one-liners</h2>\n\n<p>This:</p>\n\n<pre><code>events = sorted(list(Event(datetime.strptime(line[1:17], \"%Y-%m-%d %H:%M\"), get_guard(line), event_type(line)) for line in read_file(4)), key=operator.attrgetter(\"time\"))\n</code></pre>\n\n<p>is effectively illegible. Break this up into multiple lines - including a temporary variable for the <code>strptime</code>, as well as linebreaks in the list comprehension itself.</p>\n\n<h2>Don't use lists if you can use tuples</h2>\n\n<p>This:</p>\n\n<pre><code>MostSleepy = namedtuple('MostCommon', ['id', 'minute', 'amount'])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>MostSleepy = namedtuple('MostCommon', ('id', 'minute', 'amount'))\n</code></pre>\n\n<p>for various reasons - tuples are immutable, so use them for immutable data; and under certain narrow contexts (certainly not this one) they're faster.</p>\n\n<h2>Use a sum instead of a list constructor</h2>\n\n<p>This:</p>\n\n<pre><code>amount = len(list((m for m in current_guard.sleeps if m == most_common_minute)))\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>amount = sum(1 for m in current_guard.sleeps if m == most_common_minute)\n</code></pre>\n\n<p>(Also, even if you kept using <code>len</code>, you should use a <code>tuple</code> constructor instead of a <code>list</code> constructor.)</p>\n\n<p>Another footnote - don't put inner parens in expressions like <code>list((...generator...))</code>. Constructors can accept generator expressions directly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:51:14.787", "Id": "408041", "Score": "0", "body": "I'm not sure I follow your logic on the tuple vs list in the call to `namedtuple`. The second argument (field names) can be a list, tuple, string, etc. I think it's largely irrelevant which you choose.\n\nAlso while technically I suppose it's true that worst-case chained if's is O(n), so is dictionary lookup if you have lots of collisions. I agree that in some instances dictionary lookup can stand-in for if branches, but I think that is somewhat a preference or dictated by the number of branches you have (e.g. 100 diff conditionals would be a sign of a problem)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:57:01.827", "Id": "408042", "Score": "0", "body": "I would however suggest that he use \"elif\" instead of multiple \"if\" statements. In this scenario, the \"if\" statements are mutually exclusive, so it doesn't make a difference, but the conveyed intent could be misleading in other circumstances. If you want only one branch to execute, as opposed to each time there is a match, use \"elif\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:40:29.860", "Id": "210877", "ParentId": "210869", "Score": "4" } }, { "body": "<p>You could eliminate some of the many dependencies:</p>\n\n<ul>\n<li>Since you're already using <code>@dataclass</code>, you could use it for <code>MostSleepy</code> instead of <code>namedtuple</code></li>\n<li>It looks strange to <code>import statistics</code> after <code>from statistics import mode</code>. Aside from <code>mode</code>, the only other thing used from it is <code>StatisticsError</code>. So you could use <code>from statistics import mode, StatisticsError</code> and not import the entire <code>statistics</code></li>\n<li>I don't see the <code>enum</code> doing anything useful. You could remove it and the program will still work.</li>\n<li>The <code>operator</code> is not very useful either. You could replace <code>operator.attrgetter(\"time\")</code> with <code>lambda t: t.time</code></li>\n</ul>\n\n<p>The <code>add_sleeps</code> function could be written more compactly:</p>\n\n<pre><code>def add_sleeps(self, minute):\n self.sleeps.extend(list(range(self.last_sleep, minute)))\n</code></pre>\n\n<p>When creating the <code>events</code> list,\nyou used helper functions <code>get_guard</code> and <code>event_type</code>.\nIt would have been good to do the same for the time too.</p>\n\n<p>The <code>last_sleep</code> attribute doesn't belong in <code>GuardSleep</code>.\nIt's an implementation detail of the parsing of the lines,\nit has no other use for a <code>GuardSleep</code> instance.</p>\n\n<p>Instead of string concatenation like <code>\"foo \" + str(bar)</code>,\nthe recommended way is f-strings, <code>f\"foo {bar}\"</code>.</p>\n\n<p>The input would have allowed some simplifications.\nFor example, alphabetic sorting of the lines gives the same results as sorting by time.\nAnd, it seems all the \"falls asleep\" and \"wakes up\" events happen in the 0th hour.\nAs such, you could just parse the minute instead of the entire time:</p>\n\n<pre><code>events = [Event(int(line[15:17]), get_guard(line), event_type(line)) for line in sorted(read_file(4))]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-10T20:45:49.900", "Id": "211289", "ParentId": "210869", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T13:55:35.980", "Id": "210869", "Score": "5", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Advent of Code 2018 Day 4 - Pythonic Sleepy Guards" }
210869
<p>I have a csv-file that consists of all match outcome probabilities for soccer matches. Each math can be result in a win, draw or loss. I also included the actual outcome. In order to test how accurate my predictions are I want to use the Ranked Probability Score (RPS). Basically, the RPS compares the cumulative probability distributions of the predictions and the outcome:</p> <blockquote> <p><span class="math-container">\$ RPS = \frac{1}{r-1} \sum\limits_{i=1}^{r}\left(\sum\limits_{j=1}^i p_j - \sum\limits_{j=1}^i e_j \right)^2, \$</span></p> <p>where <span class="math-container">\$r\$</span> is the number of potential outcomes, and <span class="math-container">\$p_j\$</span> and <span class="math-container">\$e_j\$</span> are the forecasts and observed outcomes at position <span class="math-container">\$j\$</span>.</p> </blockquote> <p>For additional information, see the following <a href="https://qmro.qmul.ac.uk/xmlui/bitstream/handle/123456789/10783/Constantinou%20Solving%20the%20Problem%20of%20Inadequate%202012%20Accepted.pdf" rel="nofollow noreferrer">link</a>.</p> <pre><code>import numpy as np import pandas as pd def RPS(predictions, observed): ncat = 3 npred = len(predictions) RPS = np.zeros(npred) for x in range(0, npred): obsvec = np.zeros(ncat) obsvec[observed.iloc[x]-1] = 1 cumulative = 0 for i in range(1, ncat): cumulative = cumulative + (sum(predictions.iloc[x, 1:i]) - sum(obsvec[1:i])) ** 2 RPS[x] = (1/(ncat-1)) * cumulative return RPS df = pd.read_csv('test.csv', header=0) predictions = df[['H', 'D', 'L']] observed = df[['Outcome']] RPS = RPS(predictions, observed) </code></pre> <p>The first argument (predictions) is a matrix with the predictions and the corresponding probabilities. Each row is one prediction, laid out in the proper order (H, D, L), where each element is a probability and each row sum to 1. The second argument (observed) is a numeric vector that indicates which outcome that was actually observed (1, 2, 3)</p> <p>Feel free to give any feedback! Thank you </p> <p><strong>Edit:</strong> </p> <p>For some reason I am not able to reproduce the results of Table 3 of the <a href="https://qmro.qmul.ac.uk/xmlui/bitstream/handle/123456789/10783/Constantinou%20Solving%20the%20Problem%20of%20Inadequate%202012%20Accepted.pdf" rel="nofollow noreferrer">link</a>. I use Table 1 as input for predictions and observed. Any help is much appreciated!</p> <p><strong>Edit #2:</strong> </p> <p>Hereby the small sample of the paper:</p> <pre><code>predictions = {'H': [1, 0.9, 0.8, 0.5, 0.35, 0.6, 0.6, 0.6, 0.5, 0.55], 'D': [0, 0.1, 0.1, 0.25, 0.3, 0.3, 0.3, 0.1, 0.45, 0.1], 'L': [0, 0, 0.1, 0.25, 0.35, 0.1, 0.1, 0.3, 0.05, 0.35]} observed = {'Outcome': [1, 1, 1, 1, 2, 2, 1, 1, 1, 1]} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:01:54.547", "Id": "407736", "Score": "2", "body": "_\"I am not able to reproduce the results of Table 3\"_ If the code is not working correctly it is not ready for review." } ]
[ { "body": "<h2>Tidy up your math</h2>\n\n<pre><code>cumulative = cumulative + (sum(predictions.iloc[x, 1:i]) - sum(obsvec[1:i])) ** 2\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>cumulative += (sum(predictions.iloc[x, 1:i]) - sum(obsvec[1:i])) ** 2\n</code></pre>\n\n<p>and </p>\n\n<pre><code>RPS[x] = (1/(ncat-1)) * cumulative\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>RPS[x] = cumulative / (ncat-1)\n</code></pre>\n\n<h2>Make a main method</h2>\n\n<p>This is a very small script, but still benefits from pulling your global code into a <code>main</code>.</p>\n\n<h2>PEP8</h2>\n\n<p>By convention, method names (i.e. <code>RPS</code>) should be lowercase.</p>\n\n<p>That's all I see for now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:26:10.080", "Id": "210875", "ParentId": "210870", "Score": "0" } }, { "body": "<p>Thanks for all the replies. In the end it was relatively simple. My code is based on R, matrices start with 1 in R. Python, however, starts with 0. Adjusting my original code with this insight (sorry..) I am able to reproduce the output. I also included the remarks of Reinderien.</p>\n\n<pre><code>import numpy as np\nimport pandas as pd\n\ndef rps(predictions, observed):\n ncat = 3\n npred = len(predictions)\n rps = np.zeros(npred)\n\n for x in range(0, npred):\n obsvec = np.zeros(ncat)\n obsvec[observed.iloc[x]-1] = 1\n cumulative = 0\n for i in range(1, ncat):\n cumulative += (sum(predictions.iloc[x, 0:i]) - sum(obsvec[0:i])) ** 2\n rps[x] = cumulative / (ncat-1))\n\n return rps\n\ndf = pd.read_csv('test.csv', header=0)\npredictions = df[['H', 'D', 'L']]\nobserved = df[['Outcome']]\nrps = rps(predictions, observed)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T03:08:18.217", "Id": "407810", "Score": "1", "body": "I'm glad you figured out your issue, but - a few things. Your code in your answer is not properly indented. Also, it definitely doesn't run, because you wrote `RPS`, which no longer exists. Finally: if your code was broken in the first place, then this entire question is off-topic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T04:29:35.240", "Id": "210926", "ParentId": "210870", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T13:56:16.033", "Id": "210870", "Score": "2", "Tags": [ "python" ], "Title": "Calculate Ranked Probability Score" }
210870
<p>(See the <a href="https://codereview.stackexchange.com/questions/119969/an-iterator-returning-all-possible-permutations-of-a-list-in-java">previous and initial</a> iteration.)</p> <p>My main attempt here was to get rid of monolithic code and split the implementation into smaller methods when applicable and do more extensive commenting. Here we go:</p> <pre><code>package net.coderodde.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.stream.IntStream; /** * This class implements an iterable over a list. The underlying permuting * algorithm is deterministic but does not produce the permutation in any * interesting order. The actual list to permute does not change the original * order. What comes to actual permutation, for each a new empty list is * constructed so it is safe to modify each of them. * * @author Rodde "rodde" Efremov * @version 1.6 (Jan 4, 2019) */ public class PermutationIterable&lt;T&gt; implements Iterable&lt;List&lt;T&gt;&gt; { /** * The actual list from which to compute the permutation. This will not * change its order. */ private final List&lt;T&gt; actualElements = new ArrayList&lt;&gt;(); /** * Constructs this iterable object. * * @param actualElements the list to permute. */ public PermutationIterable(List&lt;T&gt; actualElements) { this.actualElements.addAll(actualElements); } @Override public Iterator&lt;List&lt;T&gt;&gt; iterator() { return actualElements.isEmpty() ? new EmptyIterator() : new PermutationIterator(actualElements); } /** * A stub permutation iterator for empty input lists. */ private final class EmptyIterator implements Iterator&lt;List&lt;T&gt;&gt; { @Override public boolean hasNext() { return false; } @Override public List&lt;T&gt; next() { throw new UnsupportedOperationException(); } } /** * The actual permutation iterator for non-empty input llsts. */ private final class PermutationIterator implements Iterator&lt;List&lt;T&gt;&gt; { /** * The list to return upon next call to {@code next}. Set to an empty * list when there is no more permutations to compute. */ private List&lt;T&gt; nextElements; /** * The list of actual elements to permute. */ private final List&lt;T&gt; actualElements = new ArrayList&lt;&gt;(); /** * The array of indices. Each new permutation is generated by setting * {@code i}th element in {@code nextElements} to * {@code actualElements.get(indices[i]}. */ private final int[] indices; private PermutationIterator(List&lt;T&gt; actualElements) { this.actualElements.addAll(actualElements); this.indices = createIndexArray(actualElements.size()); this.nextElements = populateOutputArray(); } @Override public boolean hasNext() { return !nextElements.isEmpty(); } @Override public List&lt;T&gt; next() { List&lt;T&gt; tmp = this.nextElements; constructNextPermutation(); return tmp; } /* * Loads {@code nextEleements} with the next permutation to remove. */ private void constructNextPermutation() { int inversionStartIndex = findAscendingPairStartIndex(); if (inversionStartIndex == -1) { this.nextElements = Collections.&lt;T&gt;emptyList(); return; } int largestElementIndex = findSmallestElementIndexLargerThanInputIndex( inversionStartIndex + 1, indices[inversionStartIndex]); swap(indices, inversionStartIndex, largestElementIndex); reverse(indices, inversionStartIndex + 1, indices.length); this.nextElements = populateOutputArray(); } private int[] createIndexArray(int size) { return IntStream.range(0, size).toArray(); } /* * Scans the index array from right to left stopping when an ascending * pair is encountered, returning the smaller index of the two. */ private int findAscendingPairStartIndex() { int i = actualElements.size() - 2; for (; i &gt;= 0; i--) { if (indices[i] &lt; indices[i + 1]) { return i; } } return -1; } /** * Returns the index of the smallest integer no smaller or equal to * {@code lowerBound}. * * @param lowerBoundIndex the smallest relevant index into the array * prefix. * @param lowerBound * @return */ private int findSmallestElementIndexLargerThanInputIndex( int lowerBoundIndex, int lowerBound) { int smallestFitElement = Integer.MAX_VALUE; int smallestFitElementIndex = -1; for (int i = lowerBoundIndex; i &lt; indices.length; i++) { int currentElement = indices[i]; if (currentElement &gt; lowerBound &amp;&amp; currentElement &lt; smallestFitElement) { smallestFitElement = currentElement; smallestFitElementIndex = i; } } return smallestFitElementIndex; } /** * Swaps to array components. * * @param array the target array. * @param index1 the index of one array component. * @param index2 the index of another array component. */ private void swap(int[] array, int index1, int index2) { int tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } /** * Reverses an integer array {@code array[startIndex], ..., * endIndex}. * * @param array the target array. * @param startIndex the starting, inclusive index. * @param endIndex the ending, exclusive index. */ private void reverse(int[] array, int startIndex, int endIndex) { for (int i = startIndex, j = endIndex - 1; i &lt; j; i++, j--) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Creates a new permutation list according to current indices. */ private List&lt;T&gt; populateOutputArray() { List&lt;T&gt; out = new ArrayList&lt;&gt;(indices.length); IntStream.of(indices) .forEach((int i) -&gt; { out.add(actualElements.get(i));}); return out; } } public static void main(String[] args) { List&lt;String&gt; strings = Arrays.asList("0", "1", "2", "3"); int lineNumber = 1; for (List&lt;String&gt; permutation : new PermutationIterable&lt;&gt;(strings)) { System.out.printf("%2d: %s\n", lineNumber++, permutation); } } } </code></pre> <p>Any critique is much appreciated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T15:10:28.427", "Id": "210873", "Score": "1", "Tags": [ "java", "algorithm", "object-oriented", "iterator" ], "Title": "An iterator returning all possible permutations of a list in Java - follow-up" }
210873
<p>I've written a function that should get rid of empty p, span, etc tags and those with just '&nbsp;' and am looking for ways to improve it. My original solution was very 'wet', but I've managed to come up with a drier solution.</p> <p>The Original HTML:</p> <pre><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id='test'&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;/div&gt; </code></pre> <p>My Original Solution:</p> <pre><code>/* How to make this drier? ORIGINAL UNCLEAN SOLUTION */ var ps = document.getElementsByTagName('p'), spans = document.getElementsByTagName('span'), strongs = document.getElementsByTagName('strong'); for (let el of ps) { if (el.innerHTML == '&amp;nbsp;') { // can't also include if '' at this stage el.parentNode.removeChild(el); } } for (let el of spans) { if (el.innerHTML == '&amp;nbsp;' || el.innerHTML == '') { el.parentNode.removeChild(el); } } for (let el of strongs) { if (el.innerHTML == '&amp;nbsp;' || el.innerHTML == '') { el.parentNode.removeChild(el); } } for (let el of ps) { if (el.innerHTML == '') { el.parentNode.removeChild(el); } } </code></pre> <p>My 'drier' solution:</p> <pre><code>/* MY CLEANER SOLUTION */ var ps = document.getElementsByTagName('p'), spans = document.getElementsByTagName('span'), strongs = document.getElementsByTagName('strong'); for (let el of ps) { cleaner(el); } for (let el of spans) { cleaner(el); } for (let el of strongs) { cleaner(el); } function cleaner(el) { if (el.innerHTML == '&amp;nbsp;' || el.innerHTML == '') { el.parentNode.removeChild(el); } } </code></pre> <p>Would someone mind quickly running over both solutions and verifying that my 2nd solution is best? Also, I wonder whether that could be improved, or whether anyone has any better ideas for a solution? Thanks for the help here - for brevity, I'm looking at writing concise but also clear code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T00:12:11.153", "Id": "407742", "Score": "0", "body": "Does the code at the question produce the expected result? Should `<p></p>` be a child element of `#test` following execution of the code? Can you include the expected resulting HTML at the question?" } ]
[ { "body": "<p>You can use <a href=\"https://www.w3schools.com/jsref/met_document_queryselectorall.asp\" rel=\"nofollow noreferrer\">querySelectorAll</a> to simplify your code further:</p>\n\n<pre><code>var elements = document.querySelectorAll('p, span, strong'),\n\nfor (let el of elements) {\n cleaner(el);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:01:59.117", "Id": "210884", "ParentId": "210883", "Score": "3" } }, { "body": "<p>I support the main aspect of <a href=\"https://codereview.stackexchange.com/a/210884/120114\">Carra's answer</a> (i.e. using <code>querySelectorAll()</code>). In addition, a functional approach can be used, since the function <code>cleaner</code> is applied to each element. For that, utilize <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>Array.prototype.forEach()</code></a>.</p>\n\n<pre><code>elements.forEach(cleaner);\n</code></pre>\n\n<p>That way, there is no need to set up an iterator variable (e.g. <code>el</code> in the <code>for...of</code> loop just to pass it to the function. The function will receive the element as the first parameter each time it is called - once for each element in the collection.</p>\n\n<p>Additionally, since <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> features like <code>for...of</code> and <code>let</code> are used, others like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> can be used (e.g. for any variable that doesn't need to be re-assigned). One could also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a> if desired.</p>\n\n<p>And it would be a good habit to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness\" rel=\"nofollow noreferrer\">strict equality comparison</a> (i.e. <code>===</code>) when comparing the innerHTML properties with the strings.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function cleaner(el) {\n if (el.innerHTML === '&amp;nbsp;' || el.innerHTML === '') {\n el.parentNode.removeChild(el);\n }\n}\n\nconst elements = document.querySelectorAll('p, span, strong');\nelements.forEach(cleaner);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;div id='test'&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T08:59:25.880", "Id": "407930", "Score": "0", "body": "thanks, some interesting points to take home :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T18:19:04.913", "Id": "210895", "ParentId": "210883", "Score": "2" } }, { "body": "<p>Beside suggested improvements:</p>\n\n<ol>\n<li><p>If <code>&lt;p&gt; &lt;/p&gt;</code> is an empty element to you, then change your <code>cleaner()</code>:</p>\n\n<pre><code>function cleaner(el) {\n if (el.innerHTML.match(/^\\s+$/) !== null) {\n el.parentNode.removeChild(el);\n }\n}\n</code></pre></li>\n<li><p>You might need to consider going recursive towards elements that have been emptied because of your cleaning procedure.</p></li>\n<li><p><strong>[Edit]</strong> I'm used to verbal function names (a best practice to follow), so I would suggest using <code>clean</code> or <code>remove</code> instead of <code>cleaner</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T19:29:28.177", "Id": "210898", "ParentId": "210883", "Score": "3" } }, { "body": "<h1>There is a bug</h1>\n\n<p>You need to run the script several times to remove all empty elements.</p>\n\n<h2>Two points</h2>\n\n<ol>\n<li><p>You say remove empty tags that contain <code>\"\"</code> or a single space <code>\"&amp;nbsp;\"</code>. Does that include <code>\" \"</code> or <code>\" \"</code> two or more spaces. What about other white space characters?</p></li>\n<li><p>Your element removal is order dependent because you use <code>getElementsByTagName</code> which returns a live list.</p>\n\n<p>Consider the html <code>&lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;</code> You first check all the <code>p</code> tags which fail the empty test, then you test the <code>span</code> tags which passes and you get <code>&lt;p&gt;&lt;/p&gt;</code> which is, by your definition, empty and should have been removed.</p>\n\n<p>On the other hand the html <code>&lt;span&gt;&lt;p&gt;&lt;/p&gt;&lt;/span&gt;</code> will first remove the <code>p</code> then remove the <code>span</code>. </p>\n\n<p>The removal process is order dependent. Not what your question indicates.</p></li>\n</ol>\n\n<h2>Changes</h2>\n\n<p>For the first point you could use <code>element.textContent</code> to check for empty elements. It will ignore the HTML and convert the <code>&amp;nbsp;</code> to a space for you. You could even use <code>element.textContent.trim()</code> and thus get all blank elements (like the pseudo-class <code>:blank</code> (Which has very limited support FF only))</p>\n\n<p>This also covers the second point.</p>\n\n<h3>Example Mark and remove</h3>\n\n<p>To reduce the DOM calls you can mark and remove deleting the marked elements only.</p>\n\n<pre><code>const isNotMarked = el =&gt; {\n while (el &amp;&amp; el.parentNode &amp;&amp; !el.parentNode.marked) {\n el = el.parentNode;\n if (el.marked) { return false }\n }\n return true;\n}\n[...document.querySelectorAll(\"span, p, strong\")]\n .filter(el =&gt; el.textContent.trim() === \"\" &amp;&amp; isNotMarked(el) ? el.marked = true : false)\n .forEach(el =&gt; el.parentNode.removeChild(el));\n</code></pre>\n\n<h3>Example simple brute force</h3>\n\n<p>Mark and remove saves you attempting to delete already deleted elements but you may not care, as the shorter form, is a two liner, and thus could be argued to be the better solution.</p>\n\n<pre><code>document.querySelectorAll(\"span, p, strong\")\n .forEach(el =&gt; el.textContent.trim() === \"\" &amp;&amp; el.parentNode.removeChild(el))\n</code></pre>\n\n<p>The following snippet shows the HTML after using your function and then the two example functions </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> /*================================================================================= \nOP ver modified for example\n =================================================================================*/\n\nvar ps = cleaned.getElementsByTagName('p'),\n spans = cleaned.getElementsByTagName('span'),\n strongs = cleaned.getElementsByTagName('strong');\n\n for (let el of ps) { cleaner(el); }\n for (let el of spans) { cleaner(el); }\n for (let el of strongs) { cleaner(el); }\n\n function cleaner(el) {\n if (el.innerHTML == '&amp;nbsp;' || el.innerHTML == '') {\n el.parentNode.removeChild(el);\n }\n }\n content.textContent = cleaned.innerHTML;\n\n\n\n\n/*================================================================================= \n Mark and remove\n =================================================================================*/\nconst isNotMarked = el =&gt; {\n while (el &amp;&amp; el.parentNode &amp;&amp; !el.parentNode.marked) {\n el = el.parentNode;\n if (el.marked) { return false }\n }\n return true;\n}\n[...cleanerClean.querySelectorAll(\"span, p, strong\")]\n .filter(el =&gt; el.textContent.trim() === \"\" &amp;&amp; isNotMarked(el) ? el.marked = true : false)\n .forEach(el =&gt; el.parentNode.removeChild(el));\n\ncontentA.textContent = cleanerClean.innerHTML;\n\n\n\n/*================================================================================= \n Brute force remove\n =================================================================================*/\nsimplerClean.querySelectorAll(\"span, p, strong\")\n .forEach(el =&gt; el.textContent.trim() === \"\" &amp;&amp; el.parentNode.removeChild(el))\n\ncontentB.textContent = simplerClean.innerHTML;</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#content {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"cleaned\" style=\"display:none;\"&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n&lt;/div&gt; \n&lt;fieldset&gt;\n&lt;legend&gt;Original OPs script &amp; Resulting HTML&lt;/legend&gt;\n&lt;code id = \"content\"&gt;&lt;/code&gt;\n&lt;/fieldset&gt;\n\n\n&lt;div id=\"cleanerClean\" style=\"display:none;\"&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n&lt;/div&gt; \n\n&lt;fieldset&gt;\n&lt;legend&gt;Mark and remove&lt;/legend&gt;\n&lt;code id = \"contentA\"&gt;&lt;/code&gt;\n&lt;/fieldset&gt;\n\n&lt;div id=\"simplerClean\" style=\"display:none;\"&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;\n &lt;p&gt;text&lt;/p&gt;\n&lt;/div&gt; \n\n&lt;fieldset&gt;\n&lt;legend&gt;Brute force remove&lt;/legend&gt;\n&lt;code id = \"contentB\"&gt;&lt;/code&gt;\n&lt;/fieldset&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T10:01:38.150", "Id": "508283", "Score": "0", "body": "Maybe you should use el.innerHTML.trim() instead. In my case, <p><img ..></p> was removed aswell." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:57:46.803", "Id": "210915", "ParentId": "210883", "Score": "5" } } ]
{ "AcceptedAnswerId": "210915", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T16:56:18.207", "Id": "210883", "Score": "2", "Tags": [ "javascript", "strings", "html", "ecmascript-6" ], "Title": "A simple function that removes empty or tags containing just '&nbsp;'" }
210883
<p>I have a large table in which I store region/state/province codes (two letters) from different countries. I use these region codes further downstream for multiple process. One of the steps I do is a cleanup of regions to ensure it is a valid region/state/province code. I have a lookup table consisting of a country vs region code to validate each column.</p> <p>6 columns are validated separately. Is there a way to do this better?</p> <pre><code>UPDATE table_region SET a_region = NULL WHERE a_region IS NOT NULL AND country IS NOT NULL AND dbo.IsValidRegion(country,a_region) = 0; UPDATE table_region SET b_region = NULL WHERE b_region IS NOT NULL AND country IS NOT NULL AND dbo.IsValidRegion(country,b_region) = 0; UPDATE table_region SET c_region = NULL WHERE c_region IS NOT NULL AND country IS NOT NULL AND dbo.IsValidRegion(country, c_region) = 0; UPDATE table_region SET d_region = NULL WHERE d_region IS NOT NULL AND country IS NOT NULL AND dbo.IsValidRegion(country,d_region) = 0; UPDATE table_region SET e_region = NULL WHERE e_region IS NOT NULL AND country IS NOT NULL AND dbo.IsValidRegion(country, e_region) = 0; UPDATE table_region SET f_region = NULL WHERE f_region IS NOT NULL AND country IS NOT NULL AND dbo.IsValidRegion(country, f_region) = 0; </code></pre> <p>The function is like this:</p> <pre><code>ALTER Function [dbo].[IsValidRegion](@country VARCHAR(20), @value VARCHAR(20)) Returns INT AS BEGIN DECLARE @res INT BEGIN IF EXISTS (SELECT 1 FROM mapping.region WHERE country = @country AND region_code = @value) SELECT @res = 1 ELSE SELECT @res = 0 END RETURN @res END </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T08:41:52.490", "Id": "427064", "Score": "0", "body": "Please consider posting the DDL of both table table_region and mapping. This would makes things much easier for us to test in a fiddle." } ]
[ { "body": "<p>There's an intrinsic problem in using a scalar UDF to validate your country and region. Your scalar function essentially answers the \"is it valid?\" question for just a single pair of values - that might be fine in an \"as-the-insert-happens\" sense of a live system that only occasionally has a need for validation of a single row, but SQLServer design principles have a particular emphasis on thinking in terms of sets of data, rather than thinking of rows of data in a line-by-line fashion, requiring individual attention.</p>\n\n<p>If you're performing this on a large table/lot of rows (let's say 100,000) then you could conceive that SQLServer will run your select query 600,000 times. It's going to be considerably slower to run more than half a million queries that pick out one item of data at a time, than it is going to be to run a query that joins together 100,000 rows (SQLServer is good at joining data efficiently) and then loops over it, checking some conditions and making changes.</p>\n\n<p>There's a process you can follow that will allow SQLServer to more effectively pick apart your function and incorporate/integrate it with the main query more effectively, particularly in terms of processing the query in parallel - You can read more about it in blogs and stackexchange answers discussing <a href=\"https://www.mssqltips.com/sqlservertip/4772/refactor-sql-server-scalar-udf-to-inline-tvf-to-improve-performance/\" rel=\"nofollow noreferrer\">swapping scalar UDFs for inline TVFs</a>. Some relatively minor performance improvements can be had by <a href=\"https://blogs.msdn.microsoft.com/sqlcat/2016/02/17/soften-the-rbar-impact-with-native-compiled-udfs-in-sql-server-2016/\" rel=\"nofollow noreferrer\">compiling the function</a>. There is also <a href=\"https://blogs.msdn.microsoft.com/sqlserverstorageengine/2018/11/07/introducing-scalar-udf-inlining/\" rel=\"nofollow noreferrer\">work afoot</a> to improve SQLServer's ability to process scalar UDFs inline with the rest of the query, but at the moment it's potentially an absolute showstopper for the performance of your query</p>\n\n<p>You also have the option of doing away with the function (or not using it in this context) and doing the cleanup all in one go (and you could encapsulate this logic in a stored procedure if you wanted) :</p>\n\n<pre><code> UPDATE t\n SET \n a_region = ra.region_code,\n b_region = rb.region_code,\n c_region = rc.region_code,\n d_region = rd.region_code,\n e_region = re.region_code,\n f_region = rf.region_code\n FROM\n table_region t\n LEFT OUTER JOIN mapping.region ra WHERE t.country = ra.country AND t.a_region = ra.region_code\n LEFT OUTER JOIN mapping.region rb WHERE t.country = rb.country AND t.b_region = rb.region_code\n LEFT OUTER JOIN mapping.region rc WHERE t.country = rc.country AND t.c_region = rc.region_code\n LEFT OUTER JOIN mapping.region rd WHERE t.country = rd.country AND t.d_region = rd.region_code\n LEFT OUTER JOIN mapping.region re WHERE t.country = re.country AND t.e_region = re.region_code\n LEFT OUTER JOIN mapping.region rf WHERE t.country = rf.country AND t.f_region = rf.region_code\n</code></pre>\n\n<p>It basically works by left joining the region table 6 times, once for each of the <code>*_region</code> columns. </p>\n\n<ul>\n<li>If the relation works out, then the <code>r*.region_code</code> will be populated with a value (which means the <code>*_region</code> column is set to the same value it currently is, i.e. a non-op). </li>\n<li>If it doesn't work out, then the join fails, null is present in <code>r*.region_code</code></li>\n</ul>\n\n<p>You could run this regularly as a periodic fix. You could also turn this into a SELECT query and run it, to identify the ones that are failed. If you were then to move those out (to another table) so your table only contains valid related records, you could then consider making <code>table_region(country,*_region)</code> have multiple foreign keys to <code>mapping.region(country,region_code)</code> to ensure that records cannot be inserted into table_region that don't have a valid country/region mapping. This devolves responsibility to maintaining a valid country/region pairing to the constraints mechanism of the database and it will become impossible to insert data that has an invalid country/region pairing</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-15T11:54:28.567", "Id": "211539", "ParentId": "210885", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:02:26.810", "Id": "210885", "Score": "2", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Validating region/state/province codes for different countries" }
210885
<p>As far as I understood this problem, it is a subset of vertices of Graph G, such that every edge has at least one endpoint in the subset. This problem is considered to be NP Complete. However I think a polynomial time greedy solution exists for this problem. I have tested this greedy solution on 12 common instances and it seems to produce the right results.</p> <p>Either I have misunderstood the problem, or my solution is not polynomial time. Please visit the link below for 12 instances explained with diagram and the code executes all the 12 instances in the same order. Nodes in diagram marked with green are the vertices that should be in the subset.</p> <p><a href="https://drive.google.com/file/d/1Y0vrkDQsBSeP5SzK1usJ20nbeqSuq9oK/view?usp=sharing" rel="nofollow noreferrer">Problems With Diagrams</a></p> <pre><code>''' Vertex Cover Problem - Greedy approach for finding optimal solution ''' # case 1 case_1 = {'a': ['b', 'c'], 'b': ['a', 'c', 'd', 'e'], 'c': ['a', 'b', 'd'], 'd': ['c', 'b', 'e'], 'e': ['b', 'd']} # case 2 case_2 = {'a': ['f'], 'b': ['f'], 'c': ['f'], 'd': ['f'], 'e': ['f'], 'f': ['a', 'b', 'c', 'd', 'e', 'g'], 'g': ['f']} # case 3 case_3 = {'a': ['f'], 'b': ['f', 'c'], 'c': ['f', 'd', 'b'], 'd': ['f', 'c'], 'e': ['f'], 'f': ['a', 'b', 'c', 'd', 'e', 'g'], 'g': ['f']} # case 4 case_4 = {'a': ['f'], 'b': ['f', 'c'], 'c': ['f', 'd', 'b'], 'd': ['f'], 'e': ['f'], 'f': ['a', 'b', 'c', 'd', 'e', 'g'], 'g': ['f']} # case 5 case_5 = {'a': ['b', 'd'], 'b': ['a', 'c', 'd', 'e'], 'c': ['b', 'f', 'e'], 'd': ['a', 'b', 'e'], 'e': ['b', 'c', 'f'], 'f': ['c', 'e']} # case 6 case_6 = {'a': ['d', 'b'], 'b': ['a', 'e', 'f', 'c'], 'c': ['b', 'd'], 'd': ['a', 'c', 'f', 'e'], 'e': ['b', 'd', 'f'], 'f': ['b', 'd', 'e']} # case 7 case_7 = {'a': ['b','c'], 'b': ['a','c','d','e','f'], 'c': ['b','a'], 'd': ['b'], 'e': ['b'], 'f': ['b']} # case 8 case_8 = {'a': ['b','c'], 'b': ['a','c','d'], 'c': ['b','a', 'e'], 'd': ['b','f','e'], 'e': ['d','c'], 'f': ['d']} # case 9 case_9 = {'a': ['b', 'f'], 'b': ['a', 'c'], 'c': ['b', 'd'], 'd': ['c', 'a'], 'e': ['d', 'f'], 'f': ['e', 'a']} # case 10 case_10 = {'a': ['b'], 'b': ['c'], 'c': ['d'], 'd': ['e'], 'e': ['f'], 'f': ['a']} # case 11 case_11 = {'a': ['b', 'c', 'd', 'e', 'f'], 'b': ['c', 'a', 'd', 'e', 'f'], 'c': ['d', 'a', 'b', 'e', 'f'], 'd': ['e', 'a', 'b', 'c', 'f'], 'e': ['f', 'a', 'b', 'c', 'd'], 'f': ['a', 'b', 'c', 'd', 'e']} # case 12 case_12 = {'a': ['b', 'c'], 'b': ['d', 'a'], 'c': ['a', 'e'], 'd': ['b', 'f', 'g'], 'e': ['h', 'i', 'j'], 'f': ['k', 'l', 'm', 'd'], 'g': ['n', 'o', 'p', 'd'], 'h': ['e'], 'i': ['e'], 'j': ['q', 'e'], 'k': ['f'], 'l': ['f'], 'm': ['f'], 'n': ['g'], 'o': ['g'], 'p': ['g'], 'q': ['j']} cases = [case_1, case_2, case_3, case_4, case_5, case_6, case_7, case_8, case_9, case_10, case_11, case_12] class Node(object): def __init__(self, name): self.name = name self.adj_list = [] self.degree = -1 class Edge(object): def __init__(self, node1, node2, weight=0): self.node1 = node1 self.node2 = node2 self.weight = weight def __str__(self): return 'Node 1: %s, Node 2: %s' % (self.node1.name, self.node2.name) def __repr__(self): return '**Node 1: %s, Node 2: %s**' % (self.node1.name, self.node2.name) def name_of_highest_degree(nodes): h = -1 k = None for key in nodes: if nodes[key].degree &gt; h: h = nodes[key].degree k = nodes[key] return k # create Edges and Nodes def vertex_cover(edges, number): total_edges = 0 nodes = {} cover = [] for a in edges: n = Node(a) nodes[a] = n for n in edges: node = nodes[n] for e in edges[n]: edge = Edge(node, nodes[e]) node.adj_list.append(edge) node.degree += 1 total_edges += 1 # Actual algorithm while total_edges &gt; 0: pick_n = name_of_highest_degree(nodes) cover.append(pick_n) for key in nodes: curr_node = nodes[key] j = 0 while True: if len(curr_node.adj_list) &lt;= 0: break if j &gt;= len(curr_node.adj_list): break edge = curr_node.adj_list[j] if edge.node2.name == pick_n.name: curr_node.degree -= 1 del curr_node.adj_list[j] total_edges -= 1 continue if edge.node1.name == pick_n.name: del curr_node.adj_list[j] total_edges -= 1 continue j += 1 del nodes[pick_n.name] print('Case %d: ' % number, end='') for c in cover: print(c.name, end=' ') print() for i in range(len(cases)): vertex_cover(cases[i], i + 1) </code></pre> <p>Any review is highly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:28:02.363", "Id": "407854", "Score": "3", "body": "\"Please visit the link\" Please include the gist of the problem statement in the question itself. Questions should stand on their own for multiple reasons (links can rot, for example)." } ]
[ { "body": "<p>The true Vertex Cover Problem is to find the <em>minimum</em> size vertex cover i.e. the smallest set fulfilling the requirements. So I suppose with the minimum requirement it is an NP problem.</p>\n\n<p>For example, your greedy approach for</p>\n\n<pre><code>case_13 = {'a': ['b'], 'b': ['c', 'a'], 'c': ['b', 'd', 'f'], \n 'd': ['e', 'c'], 'e': ['d'], 'f': ['g', 'c'], 'g': ['f']}\n</code></pre>\n\n<p>yields <code>c a d f</code>, but the minimum cover is <code>b d f</code>.</p>\n\n<p>Other comments:</p>\n\n<p>You can delete <code>nodes.degree</code>; just use <code>len(nodes.adj_list)</code>. Have a <code>degree()</code> method on Nodes to calculate it.</p>\n\n<p>You can delete total_edges as well; you can exit the loop when <code>pick_n.degree() == 0</code>.</p>\n\n<p>The inner while loop in your code is then only there to clean up adj_list. Since that is filtering a list, the pythonic way to do it is with a list comprehension:</p>\n\n<pre><code> curr_node.adj_list = [\n edge for edge in curr_node.adj_list\n if edge.node2.name != pick_n.name\n and edge.node1.name != pick_n.name]\n</code></pre>\n\n<p>name_of_highest_degree() is misnamed, since it returns the node, not the name of the node.</p>\n\n<p>name_of_highest_degree() can be written as a one-liner <a href=\"https://medium.com/@antash/six-ways-to-find-max-value-of-a-list-in-python-b7d7ccfabc0d\" rel=\"nofollow noreferrer\">using python's max with <code>key=</code> parameter</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T08:37:04.937", "Id": "407762", "Score": "0", "body": "thank you for reviewing and suggesting case 13, code changes. This was really helpful. It cleared my doubts." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T19:28:57.150", "Id": "210897", "ParentId": "210887", "Score": "3" } } ]
{ "AcceptedAnswerId": "210897", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:12:18.283", "Id": "210887", "Score": "3", "Tags": [ "python", "python-3.x", "graph", "complexity" ], "Title": "Vertex Cover Problem Greedy Solution" }
210887
<p>I made a Tic Tac Toe game using classes to show a better approach than the Tic Tac Toe game in <a href="https://codereview.stackexchange.com/questions/210679/tic-tac-toe-in-c11/210681#210681">Tic Tac Toe in C++11</a> which works not with classes.</p> <p>I already posted the code there as an improvement over the code posted in that question.</p> <p>Now I wonder what I can still improve on my solution?</p> <p>Feel free to comment on anything which comes to youre mind to improve this code.</p> <p><strong>tic_tac_toe.h</strong></p> <pre><code>#ifndef TIC_TAC_TOE_020120180815 #define TIC_TAC_TOE_020120180815 #include &lt;array&gt; #include &lt;string&gt; namespace tic_tac_toe { class TicTacToe final{ public: TicTacToe() = default; ~TicTacToe() = default; // delete copy and move mechanism, we don't want to // copy a running game TicTacToe(const TicTacToe&amp;) = delete; TicTacToe(TicTacToe&amp;&amp; other) = delete; TicTacToe&amp; operator=(const TicTacToe&amp; other) = delete; TicTacToe&amp; operator=(TicTacToe&amp;&amp; other) = delete; void print_state_of_board() const; bool draw(int field); bool board_full() const; bool player1_win() const { return check_win_condition(FieldState::player1); } bool player2_win() const { return check_win_condition(FieldState::player2); } private: enum class FieldState { empty, player1, // X player2, // O }; bool check_win_condition(FieldState state) const; char field_state_to_char(FieldState state) const; std::array&lt;FieldState, 9&gt; m_board{ FieldState::empty }; bool m_player1_active{ true }; static constexpr char m_player1_token{ 'X' }; static constexpr char m_player2_token{ 'O' }; }; int get_user_input(const std::string&amp; user_message); void play_game(); // main routine to run the game logic; } // namespace tic_tac_toe #endif </code></pre> <p><strong>tic_tac_toe.cpp</strong></p> <pre><code>#include "tic_tac_toe.h" #include &lt;algorithm&gt; // std::find #include &lt;cctype&gt; // std::stoi #include &lt;iostream&gt; #include &lt;vector&gt; namespace tic_tac_toe { void TicTacToe::print_state_of_board() const /* Print the board. e.g: |X| |O| | |X| | |O| | | */ { for (auto i = 0; i &lt; m_board.size(); ++i) { if (i % 3 == 0 &amp;&amp; i != 0) { std::cout &lt;&lt; "|\n"; } auto token = field_state_to_char(m_board.at(i)); std::cout &lt;&lt; '|' &lt;&lt; token; } std::cout &lt;&lt; "|\n"; } bool TicTacToe::draw(int field) /* Tries to draw the next symbol in the field. Each time the function is called the player is changed. The user input has to be done out side. This way also a bot could play the game. If the selected field can not be set because its already occupied by player1 or player2 or out of range the return value becomes false */ { if (field &lt; 1 || field &gt; m_board.size() || m_board.at(field - 1) != FieldState::empty) { return false; } if (m_player1_active) { m_board.at(field - 1) = FieldState::player1; m_player1_active = false; } else { // player 2 active m_board.at(field - 1) = FieldState::player2; m_player1_active = true; } return true; } bool TicTacToe::board_full() const /* search for a empty field in the board indicating that board is full if no empty field available. */ { auto it = std::find( m_board.begin(), m_board.end(), FieldState::empty); return it == m_board.end(); } bool TicTacToe::check_win_condition(FieldState state) const { constexpr std::array&lt;std::array&lt;int, 3&gt;, 8&gt; combinations = { std::array&lt;int, 3&gt;{0,1,2}, std::array&lt;int, 3&gt;{3,4,5}, std::array&lt;int, 3&gt;{6,7,8}, std::array&lt;int, 3&gt;{0,3,6}, std::array&lt;int, 3&gt;{1,4,7}, std::array&lt;int, 3&gt;{2,5,8}, std::array&lt;int, 3&gt;{0,4,8}, std::array&lt;int, 3&gt;{2,4,6} }; for (const auto&amp; combination : combinations) { if (m_board.at(combination[0]) == state &amp;&amp; m_board.at(combination[1]) == state &amp;&amp; m_board.at(combination[2]) == state) { return true; } } return false; } char TicTacToe::field_state_to_char(FieldState state) const { if (state == FieldState::player1) { return m_player1_token; } if (state == FieldState::player2) { return m_player2_token; } return ' '; } int get_user_input(const std::string&amp; user_message) { while (true) { std::cout &lt;&lt; user_message; std::string input; std::cin &gt;&gt; input; /* If input is not an integer the stoi function will raise an exception. We use this to determine if the input was an int */ try { return std::stoi(input); } catch (std::invalid_argument&amp;) { std::cout &lt;&lt; "\nInput is not a number. Try again:"; } } } void play_game() /* Main routine to play the game with 2 players */ { while (true) { TicTacToe game; bool player1_active{ true }; while (!game.board_full() &amp;&amp; !game.player1_win() &amp;&amp; !game.player2_win()) { game.print_state_of_board(); std::string user_message; if (player1_active) { user_message = "1[X]:"; } else { // player2 active user_message = "2[O]:"; } if (!game.draw(get_user_input(user_message))) { std::cout &lt;&lt; "\nInvalid! Try again: \n"; } else { player1_active = !player1_active; } } game.print_state_of_board(); if (game.player1_win()) { std::cout &lt;&lt; "Player 1 wins!\n"; } else if (game.player2_win()) { std::cout &lt;&lt; "Player 2 wins!\n"; } else { std::cout &lt;&lt; "Draw!\n"; } int choice{}; while (true) { choice = get_user_input( "Play again[Yes = 1, No = 0]: "); if (choice == 0) { return; } if(choice == 1) { break; } } } } } // namespace tic_tac_toe </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "tic_tac_toe.h" #include &lt;iostream&gt; int main() try { tic_tac_toe::play_game(); } catch (std::runtime_error&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; "\n"; std::getchar(); } catch (...) { std::cerr &lt;&lt; "unknown error " &lt;&lt; "\n"; std::getchar(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T20:13:40.857", "Id": "407784", "Score": "2", "body": "What is your reason to delete copy and move constructor and assignment? I don’t see a need, as the class owns no data or resources, copy and move would be trivial, let the compiler generate those for you if needed, if you don’t use them they won’t be generated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T21:34:49.207", "Id": "407789", "Score": "0", "body": "hm i thought they are generated by default if you dont declare them. And since it makes no sense to copy a running game i thought its better to change from default to delete." } ]
[ { "body": "<p>This is definitely much improved over the previous version. Good job! There may still some things that might be improved.</p>\n\n<h2>Use only necessary <code>#include</code>s</h2>\n\n<p>The <code>#include &lt;vector&gt;</code> line is not necessary and can be safely removed.</p>\n\n<h2>Use all required <code>#include</code>s</h2>\n\n<p>Because <code>main</code> refers to <code>std::runtime_error</code> it should have <code>#include &lt;stdexcept&gt;</code>.</p>\n\n<h2>Reduce runtime complexity where practical</h2>\n\n<p>The <code>std::find</code> used in <code>board_full</code> is not bad, and as a practical matter, no human will ever notice the difference between it and a faster mechanism, but the simpler method is to simply keep a turn counter. If the number of turns is 9, then either someone just won or it's a tie. That would reduce the code to this:</p>\n\n<pre><code>bool isTie() const {\n return turn_count &gt;= 9;\n}\n</code></pre>\n\n<p>Note also that I've used the very common <code>is</code> prefix to make it perfectly unambiguous that it's a function returning a <code>bool</code> and <code>isTie</code> make clear what <code>true</code> means. </p>\n\n<p>Also, the <code>play_game</code> is more complex than it needs to be. Here's an alternative version:</p>\n\n<pre><code>void play_game() {\n TicTacToe game;\n game.play();\n}\n\nvoid TicTacToe::play() {\n for (bool ingame = true; ingame; player = 1 - player) {\n printMatrix();\n input(player);\n if (isWin()) {\n std::cout &lt;&lt; \"Player \" &lt;&lt; player+1 &lt;&lt; \" wins!\\n\";\n ingame = false;\n } else if (isTie()) {\n std::cout &lt;&lt; \"Draw!\\n\";\n ingame = false;\n }\n }\n}\n</code></pre>\n\n<p>In this version, the <em>game</em> keeps track of which player is playing, rather than having that knowledge external to the object.</p>\n\n<h2>Use object to group related things</h2>\n\n<p>In various places within the code, there is a <code>bool player1_active</code>, prompts such as <code>\"1[X]:\"</code>, <code>m_player1_token</code> and <code>FieldState::player1</code>. I think it would make the code simpler if these concepts were all grouped together into a <code>Player</code> object. This would also make it quite simple to adapt a robot player, since it could likely use the same <code>Player</code> interface, if carefully designed.</p>\n\n<h2>Think about the user</h2>\n\n<p>Although I think the board is less cluttered and easier to read in this version than when it had the squares numbered, it makes it difficult for the user to figure out how to enter a move. Having some instructions or maybe statically printing the numbering scheme as part of the prompt might help. Also, when one player has won the game it says something like \"Player 2 wins!\" but what the <em>user</em> deals with and thinks about is \"X\" and \"O\", not \"1\" and \"2\".</p>\n\n<h2>Example result</h2>\n\n<p>Here's how all of that might look if implemented. </p>\n\n<h3>tic_tac_toe.h</h3>\n\n<pre><code>#ifndef TIC_TAC_TOE_H\n#define TIC_TAC_TOE_H\n\n#include &lt;array&gt;\n#include &lt;string&gt;\n\nnamespace tic_tac_toe\n{\n class TicTacToe;\n\n class Player {\n public:\n constexpr Player(char token, const char* winmsg, const char* prompt) : \n token{token}, \n winmsg{winmsg},\n prompt{prompt}\n {}\n int select(const TicTacToe &amp;board) const; \n const char token;\n const char *winmsg;\n const char *prompt;\n };\n\n class TicTacToe final { \n public:\n TicTacToe() {\n m_board.fill(emptyToken);\n }\n void play(); \n bool occupied(unsigned square) const {\n return square &gt;= num_squares || m_board[square] != emptyToken;\n }\n static constexpr int num_squares{9};\n static constexpr char emptyToken{' '};\n private:\n void print_state_of_board() const;\n bool isWin() const;\n void input(int player);\n bool isTie() const {\n return turn_count &gt;= num_squares;\n }\n\n static constexpr Player players[2] = { \n { 'X', \"X Wins!\", \"1[X]:\" },\n { 'O', \"O Wins!\", \"2[O]:\" },\n };\n int turn_count = 0;\n int player = 0;\n std::array&lt;char, num_squares&gt; m_board;\n };\n\n int get_user_input(const std::string&amp; user_message);\n void play_game(); \n}\n#endif\n</code></pre>\n\n<h3>tic_tac_toe.cpp</h3>\n\n<pre><code>#include \"tic_tac_toe.h\"\n#include &lt;cctype&gt; \n#include &lt;iostream&gt;\n\nnamespace tic_tac_toe\n{\n constexpr Player TicTacToe::players[2];\n constexpr char TicTacToe::emptyToken;\n\n int Player::select(const TicTacToe &amp;board) const { \n while (true) {\n int answer = get_user_input(prompt)-1;\n if (!board.occupied(answer)) \n return answer;\n std::cout &lt;&lt; \"Invalid input; try again\\n\";\n } \n return 0; // should never get here!\n }\n\n void TicTacToe::print_state_of_board() const {\n auto col{3};\n for (std::size_t i = 0; i &lt; m_board.size(); ++i) {\n std::cout &lt;&lt; '|' &lt;&lt; m_board.at(i);\n if (--col == 0) {\n std::cout &lt;&lt; \"|\\n\";\n col = 3;\n }\n }\n }\n\n bool TicTacToe::isWin() const {\n static constexpr std::array&lt;std::array&lt;int, 3&gt;, 8&gt; combinations{{ \n {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6},\n {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}\n }};\n for (const auto&amp; combination : combinations) {\n if (m_board.at(combination[0]) == players[player].token &amp;&amp;\n m_board.at(combination[1]) == players[player].token &amp;&amp;\n m_board.at(combination[2]) == players[player].token) \n {\n return true;\n }\n } \n return false;\n }\n\n void TicTacToe::input(int player) {\n m_board[players[player].select(*this)] = players[player].token;\n ++turn_count;\n }\n void TicTacToe::play() {\n for (bool ingame = true; ingame; player = 1 - player) {\n print_state_of_board();\n input(player);\n if (isWin()) {\n std::cout &lt;&lt; players[player].winmsg &lt;&lt; '\\n';\n ingame = false;\n } else if (isTie()) {\n std::cout &lt;&lt; \"Draw!\\n\";\n ingame = false;\n }\n }\n }\n\n int get_user_input(const std::string&amp; user_message)\n {\n while (true) {\n std::cout &lt;&lt; user_message;\n std::string input;\n std::cin &gt;&gt; input;\n try {\n return std::stoi(input);\n }\n catch (std::invalid_argument&amp;) {\n std::cout &lt;&lt; \"\\nInput is not a number. Try again:\";\n }\n }\n }\n\n void play_game() {\n for (bool gaming{true}; \n gaming; \n gaming = get_user_input(\"Play again[Yes = 1, No = 0]: \") == 1)\n {\n TicTacToe game;\n game.play();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T10:30:10.797", "Id": "407763", "Score": "0", "body": "Thanks for the feedback. Im not sure of how to implement the Player interface. How can `std::array<FieldState, 9> m_board{ FieldState::empty }` By making 3 Player Objects in the TicTacToe class? I would appreachiate an example of how the Player interface could look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T18:32:10.677", "Id": "407774", "Score": "0", "body": "I've updated the answer to show a fully worked version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T18:03:56.843", "Id": "407863", "Score": "0", "body": "thanks for the example. Some questions about it. Is there a reason to use `char*` for the literals? Ithought in c++ you should avoid it. also in youre cpp i dont think you need `constexpr Player TicTacToe::players[2];`\n `constexpr char TicTacToe::emptyToken;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:13:36.493", "Id": "407883", "Score": "0", "body": "Good question. The only reason to use `char *` is to allow the use of `constexpr`. If your compiler supports [`std::string_view`](https://en.cppreference.com/w/cpp/string/basic_string_view), that's another way to do it. The limitation all of this is intended to get around is that one can't have a `constexpr` `std::string`. The values don't *need* to be `constexpr` but it's nicer if they are since it means there is zero runtime overhead and many more compiler optimizations are enabled with `constexpr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:58:24.840", "Id": "408024", "Score": "0", "body": "thanks for the hint with string_view. i catched myself replacing const char* in a c++ project with string_view." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:52:36.320", "Id": "210908", "ParentId": "210889", "Score": "5" } } ]
{ "AcceptedAnswerId": "210908", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:33:06.470", "Id": "210889", "Score": "6", "Tags": [ "c++", "object-oriented", "c++11", "tic-tac-toe" ], "Title": "Tic Tac Toe Game in C++ using Classes" }
210889
<p>Just on a chapter 3 of <a href="https://doc.rust-lang.org/book/" rel="nofollow noreferrer">Rust Book</a> so not much good in Rust. so tried to implement a simple temprature calculator as suggest in <a href="https://doc.rust-lang.org/book/ch03-05-control-flow.html#summary" rel="nofollow noreferrer">this</a> chapter. so i would like you guys to point anything you feel</p> <pre><code>use std::io; fn main() { println!("Enter Temperature as 56f or 98c"); let mut usr_inpt = String::new(); io::stdin() .read_line(&amp;mut usr_inpt) .expect("can not read user input"); let usr_inpt = usr_inpt.trim_end().to_lowercase(); if usr_inpt.ends_with("f") || usr_inpt.ends_with("c") { // remove the last indication 56f -&gt; 56 or 56c -&gt; 56 let _temp: String = usr_inpt.chars().take(usr_inpt.len() - 1).collect(); let num: u32 = match _temp.parse() { Ok(num) =&gt; num, Err(_) =&gt; 0, }; if usr_inpt.ends_with("f") { println!("celcius -&gt; {}", (num - 32) * 5 / 9); } else if usr_inpt.ends_with("c") { println!("farenheit -&gt; {}", num * 9 / 5 + 32); } } else { println!("invalid input"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T07:59:19.193", "Id": "407820", "Score": "0", "body": "Welcome to Code Review. I've rolled your question back to its previous state, as it invalidated an already existing review. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T08:05:06.820", "Id": "407822", "Score": "1", "body": "my bad sure will take care of it ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T08:03:44.340", "Id": "408280", "Score": "0", "body": "Please take a look at https://codereview.stackexchange.com/questions/207481/fahrenheit-and-celsius-converter-in-rust" } ]
[ { "body": "<blockquote>\n<pre><code>use std::io;\n\nfn main() {\n println!(\"Enter Temperature as 56f or 98c\");\n\n let mut usr_inpt = String::new();\n\n io::stdin()\n .read_line(&amp;mut usr_inpt)\n .expect(\"can not read user input\");\n</code></pre>\n</blockquote>\n\n<p>I like that you’re using <code>expect</code> here instead of <code>unwrap</code>. \nIt allows for a much nicer user experience when things go sideways. \nIf I was nitpicking, I’d remind you to use proper capitalization and punctuation. </p>\n\n<blockquote>\n<pre><code> let usr_inpt = usr_inpt.trim_end().to_lowercase();\n\n if usr_inpt.ends_with(\"f\") || usr_inpt.ends_with(\"c\") {\n // remove the last indication 56f -&gt; 56 or 56c -&gt; 56\n let _temp: String = usr_inpt.chars().take(usr_inpt.len() - 1).collect();\n</code></pre>\n</blockquote>\n\n<p><code>temp</code> is rarely a good name. \nIf you meant <code>temperature</code> instead of <code>temporary</code>, it would be good to spell it out. </p>\n\n<blockquote>\n<pre><code> let num: u32 = match _temp.parse() {\n Ok(num) =&gt; num,\n Err(_) =&gt; 0,\n };\n</code></pre>\n</blockquote>\n\n<p>Is it really the right thing to return zero in the error case?\nI would expect the error case here to be caused by invalid user input (or a bug in your previous parsing logic maybe).\nIt would probably be best to alert the user to this failure instead of the slightly enigmatic result of <code>0</code>. </p>\n\n<blockquote>\n<pre><code> if usr_inpt.ends_with(\"f\") {\n println!(\"celcius -&gt; {}\", (num - 32) * 5 / 9);\n } else if usr_inpt.ends_with(\"c\") {\n println!(\"farenheit -&gt; {}\", num * 9 / 5 + 32);\n }\n</code></pre>\n</blockquote>\n\n<p>It smells a little funny that we’re making the same checks again as we did above. If you extracted the parsing logic into a function, you could just call it for each case. I would probably also extract proper <code>fahrenheit_to_celcius</code> and <code>celcius_to_fahrenheit</code> functions. </p>\n\n<blockquote>\n<pre><code> } else {\n println!(\"invalid input\");\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Error messages should be printed to <code>stderr</code>. \nUse the <a href=\"https://doc.rust-lang.org/std/macro.eprintln.html\" rel=\"nofollow noreferrer\"><code>eprintln</code> macro</a> instead. </p>\n\n<p>———————</p>\n\n<p>All in all it’s pretty good for a first go. \nI would take a look at using some types for <code>Fahrenheit</code> and <code>Celsius</code> though. Your parse method could return a <code>Temperature</code> that contains either a <code>Celsius</code> or <code>Fahrenheit</code> measurement. </p>\n\n<p>I’ve not run this through the compiler, but hopefully it illustrates the idea. </p>\n\n<pre><code>struct Celsius { value: u32 }\nimpl Celsius {\n fn to_farhenheit(&amp;self) -&gt; Farhenheit {\n Fahrenheit { value: self.value * 9 / 5 + 32 }\n }\n}\n\nstruct Fahrenheit { value: u32 }\nimpl Fahrenheit {\n fn to_celsius(&amp;self) -&gt; Celsius {\n Celsius { value: ( self.value - 32) * 5 / 9 }\n }\n}\n\nenum Temperature {\n Fahrenheit(Fahrenheit),\n Celsius(Celsius)\n Err(String)\n}\n\nfn parse_input(input: &amp;str) -&gt; Temperature {\n if input.ends_with(\"f\") {\n Fahrenheit { value: parse_num(input) }\n } else if input.ends_with(“c”) {\n Celsius { value: parse_num(input) }\n } else {\n Err(“Input invalid. Must end with ‘c’ or ‘f’.”)\n }\n}\n\nfn parse_num(input: &amp;str) -&gt; u32 {\n let temperature: String = usr_inpt.chars().take(usr_inpt.len() - 1).collect();\n\n match temperature.parse() {\n Ok(num) =&gt; num,\n Err(_) =&gt; 0,\n };\n}\n</code></pre>\n\n<p>Then we tie it all together in main. </p>\n\n<pre><code>fn main() {\n println!(\"Enter Temperature as 56f or 98c\");\n\n let mut usr_inpt = String::new();\n\n io::stdin()\n .read_line(&amp;mut usr_inpt)\n .expect(\"can not read user input\");\n\n let temperature = parse_input(usr_inpt.trim_end().to_lowercase());\n\n match temperature {\n Temperature::Celsius { celsius } =&gt; println!(\"celcius -&gt; {}\", celcius.to_fahrenheit()),\n Temperature::Fahrenheit { fahrenheit } =&gt; println!(“fahrenheit -&gt; {}”, fahrenheit.to_celsius()),\n Err(reason) =&gt; eprintln!(reason)\n }\n}\n</code></pre>\n\n<p>While it’s certainly more code, it raises the level of abstraction in your <code>main</code> function quite a bit. </p>\n\n<ul>\n<li>Greet user</li>\n<li>Get input</li>\n<li>Parse input</li>\n<li>Write out results </li>\n</ul>\n\n<p>This also provides the opportunity (left as an exercise for the reader) to propagate errors from <code>parse_num</code> all the way back up to the user, rather than silently returning an invalid result. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T07:44:59.877", "Id": "407818", "Score": "0", "body": "This is helpful, So not completely but i have updated the code a bit since i am not very comfortable with enums and all in Rust i will follow your advice once i am comfortable with these things.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T13:38:25.197", "Id": "407839", "Score": "0", "body": "No worries @MAK. I kind of figured. That’s why I broke my answer into two parts." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:38:45.947", "Id": "210954", "ParentId": "210891", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:41:41.963", "Id": "210891", "Score": "3", "Tags": [ "beginner", "rust", "unit-conversion" ], "Title": "Temperature calculator in Rust" }
210891
<p>Over the past few months, I've been actively using python and I have made a few scripts to scrape #hashtag data from Instagram.</p> <p>It all started with some basic script I had made early 2017 and I have been adding and modifying it ever since. Over the last few months, I made progress in my own skill of Python, successfully adding things like user agent and proxy rotation.</p> <p>Now that I have a tool that does exactly what I want, I'm looking to:</p> <ul> <li>Optimize code structure (it's really copying and pasting mostly) and removing 'crappy' code.</li> </ul> <p>Therefore I'm hoping SO can help me analyze my code and suggest optimizations.</p> <p>My script does the following:</p> <ul> <li>It analyzes hashtags from the input file (hashtags.txt)</li> <li>It then scrapes data from Instagram (like post count, average engagement,...)</li> <li>This data is then stored in a .csv. Which is being processed again afterward to remove duplicates.</li> </ul> <p>I also included user agent randomization and proxy rotation.</p> <p>However, I feel like my code is far from optimal and when I want to add additional things (like catching HTTP errors, retrying on proxy timeouts,...) I'm just adding more levels of indentation so I'm pretty sure there are other options there!</p> <p>Any help or feedback to optimize my code below is GREATLY appreciated!</p> <pre><code> # This script is written for personal research and is not endorsed by Instagram. # Use at your own risk! # -*- coding: utf-8 -*- import csv import requests import urllib.request import json import re import random import time from fake_useragent import UserAgent from random import randint from time import sleep ua = UserAgent(cache=False) ts = time.gmtime() timestamp = time.strftime(&quot;%d-%m-%Y %H-%M&quot;, ts) def get_csv_header(top_numb): fieldnames = ['Hashtag','Active Days Ago','Post Count','AVG. Likes','MAX. Likes','MIN. Likes','AVG. Comments','Hashtag URL','Post Ready Tag'] return fieldnames def write_csv_header(filename, headers): with open(filename, 'w', newline='') as f_out: writer = csv.DictWriter(f_out, fieldnames=headers) writer.writeheader() return def read_keywords(t_file): with open(t_file) as f: keyword_list = f.read().splitlines() return keyword_list def read_proxies(p_file): with open(p_file) as f: proxy_list = f.read().splitlines() return proxy_list #file data_filename = 'Hashtag Scrape ' + timestamp + '.csv' KEYWORD_FILE = './hashtags.txt' DATA_FILE = './' + data_filename PROXY_FILE = './proxies.txt' keywords = read_keywords(KEYWORD_FILE) proxies = read_proxies(PROXY_FILE) csv_headers = get_csv_header(9) write_csv_header(DATA_FILE, csv_headers) #Ask for randomisation input fields low = input(&quot;Please enter minimal delay time (in seconds): &quot;) low_random = int(low) high = input(&quot;Please enter maximal delay time (in seconds): &quot;) high_random = int(high) #get the data for keyword in keywords: import urllib, json if len(proxies)!=0: proxy_ip = random.choice(proxies) proxy_support = urllib.request.ProxyHandler({'https':proxy_ip}) opener = urllib.request.build_opener(proxy_support) urllib.request.install_opener(opener) prepare_url = urllib.request.Request( 'https://www.instagram.com/explore/tags/' + urllib.parse.quote_plus(keyword) + '/?__a=1', headers={ 'User-Agent': ua.random } ) url = urllib.request.urlopen(prepare_url) post_info = {} response = json.load(url) #response is the JSON dump of the url. #defining some script helpers x = len(response['graphql']['hashtag']['edge_hashtag_to_top_posts']['edges']) i = avg_post_likes = 0 likes_value = [] comments_value = [] #Getting the general tag data hashtag_name = response['graphql']['hashtag']['name'] post_count = response['graphql']['hashtag']['edge_hashtag_to_media']['count'] hashtag_url = 'https://www.instagram.com/explore/tags/' + keyword post_ready_tag = '#' + keyword top_posts = response['graphql']['hashtag']['edge_hashtag_to_top_posts']['edges'] #calculate the active days ago most_recent_post = response['graphql']['hashtag']['edge_hashtag_to_media']['edges'][0]['node']['taken_at_timestamp'] import datetime from dateutil import relativedelta post_datetime = datetime.datetime.fromtimestamp(most_recent_post).strftime('%Y-%m-%d %H:%M:%S') post_cleandate = datetime.datetime.fromtimestamp(most_recent_post).strftime('%Y-%m-%d') from datetime import datetime, date most_recent_clean = datetime.strptime(post_cleandate, '%Y-%m-%d') today = datetime.strptime(str(date.today()),'%Y-%m-%d') posted_days_ago = relativedelta.relativedelta(today, most_recent_clean).days while i &lt;=x-1: #Getting data from top posts top_post_likes = response['graphql']['hashtag']['edge_hashtag_to_top_posts']['edges'][i]['node']['edge_liked_by'] post_like = response['graphql']['hashtag']['edge_hashtag_to_top_posts']['edges'][i]['node']['edge_liked_by']['count'] post_comment = response['graphql']['hashtag']['edge_hashtag_to_top_posts']['edges'][i]['node']['edge_media_to_comment']['count'] likes_value.append(post_like) comments_value.append(post_comment) i += 1 print('Writing ' + keyword + ' to output file') with open(data_filename, 'a', newline='', encoding='utf-8') as data_out: post_info[&quot;Hashtag&quot;] = hashtag_name post_info[&quot;Active Days Ago&quot;] = posted_days_ago post_info[&quot;Post Count&quot;] = post_count post_info[&quot;AVG. Likes&quot;] = round(sum(likes_value)/len(likes_value),2) post_info[&quot;MAX. Likes&quot;] = max(likes_value) post_info[&quot;MIN. Likes&quot;] = min(likes_value) post_info[&quot;AVG. Comments&quot;] = round(sum(comments_value)/len(comments_value),2) post_info[&quot;Hashtag URL&quot;] = hashtag_url post_info[&quot;Post Ready Tag&quot;] = post_ready_tag csv_writer = csv.DictWriter(data_out, fieldnames=csv_headers) csv_writer.writerow(post_info) #Randomly pause script based on input values sleep(randint(low_random,high_random)) #cleaning up the file: destination = data_filename[:-4] + '_unique.csv' data = open(data_filename, 'r',encoding='utf-8') target = open(destination, 'w',encoding='utf-8') # Let the user know you are starting, in case you are de-dupping a huge file print(&quot;\nRemoving duplicates from %r&quot; % data_filename) # Initialize variables and counters unique_lines = set() source_lines = 0 duplicate_lines = 0 # Loop through data, write uniques to output file, skip duplicates. for line in data: source_lines += 1 # Strip out the junk for an easy set check, also saves memory line_to_check = line.strip('\r\n') if line_to_check in unique_lines: # Skip if line is already in set duplicate_lines += 1 continue else: # Write if new and append stripped line to list of seen lines target.write(line) unique_lines.add(line_to_check) # Be nice and close out the files target.close() data.close() import os os.remove(data_filename) os.rename(destination, data_filename) print(&quot;SUCCESS: Removed %d duplicate line(s) from file with %d line(s).&quot; % \ (duplicate_lines, source_lines)) print(&quot;Wrote output to %r\n&quot; % data_filename) print(&quot;\n&quot; + 'ALL DONE !!!! ') </code></pre> <p>For those interested, this is how the output file looks:</p> <p><a href="https://i.stack.imgur.com/VdfQU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VdfQU.png" alt="output file" /></a></p> <p>Thanks in advance! &lt;3</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T18:01:37.687", "Id": "407713", "Score": "0", "body": "Why aren't you using their API? https://www.instagram.com/developer/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T18:11:50.393", "Id": "407715", "Score": "0", "body": "Because I don't need to (yet), and don't really want to either :). I can get this data without using tokens and login credentials. So that's my preferred approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T19:07:09.737", "Id": "407718", "Score": "0", "body": "I coded something as similar as yours: https://codereview.stackexchange.com/questions/210613/web-scraping-the-titles-and-descriptions-of-trending-youtube-videos If you're interested in more web scraping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T08:26:55.637", "Id": "407758", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>This function:</p>\n\n<pre><code>def get_csv_header(top_numb):\n fieldnames = ['Hashtag','Active Days Ago','Post Count','AVG. Likes','MAX. Likes','MIN. Likes','AVG. Comments','Hashtag URL','Post Ready Tag']\n return fieldnames\n</code></pre>\n\n<p>has a few issues. <code>top_numb</code> is unused, so delete it. You can both construct and return the list in the same statement, but due to its length I suggest that you add some linebreaks in that list. Finally: per <a href=\"https://docs.python.org/3/library/csv.html#csv.DictWriter\" rel=\"noreferrer\">Python 3 docs</a>, <code>fieldnames</code> must be a sequence but needn't be a list - so make this a tuple <code>()</code> and not a list <code>[]</code> because the data are immutable.</p>\n\n<p>Otherwise:</p>\n\n<h2>Remove redundant <code>return</code>s</h2>\n\n<p>i.e. the no-op <code>return</code> seen in <code>write_csv_header</code>.</p>\n\n<h2>Make a <code>main</code> function</h2>\n\n<p>...for all of your global code, for a couple of reasons - to clean up the global namespace, and to make your code callable as a library for other applications.</p>\n\n<h2>Use f-strings</h2>\n\n<p>...for strings like this:</p>\n\n<pre><code>data_filename = 'Hashtag Scrape ' + timestamp + '.csv'\n</code></pre>\n\n<p>that can be:</p>\n\n<pre><code>data_filename = f'Hashtag Scrape {timestamp}.csv'\n</code></pre>\n\n<h2>Write more subroutines</h2>\n\n<p>The bulk of your logic within the main <code>for keyword in keywords</code> loop is quite long. Break this up into several subroutines for legibility and maintainability.</p>\n\n<h2>Use <code>requests</code></h2>\n\n<p>You're calling into <code>urllib.request.Request</code>, but there's usually no good reason to do this. Use <code>requests</code> instead, which is better in nearly every way.</p>\n\n<h2>Apply a linter</h2>\n\n<p>This will catch non-PEP8 whitespace (or lack thereof) such as that seen in this statement:</p>\n\n<pre><code>if len(proxies)!=0:\n</code></pre>\n\n<h2>Imports at the top</h2>\n\n<p>In the middle of your source, we see:</p>\n\n<pre><code>import datetime\nfrom dateutil import relativedelta\npost_datetime = datetime.datetime.fromtimestamp(most_recent_post).strftime('%Y-%m-%d %H:%M:%S')\npost_cleandate = datetime.datetime.fromtimestamp(most_recent_post).strftime('%Y-%m-%d')\nfrom datetime import datetime, date\n</code></pre>\n\n<p>It's usually considered better practice to do all of your imports at the top of the source file.</p>\n\n<h2>Don't declare indices that you don't use</h2>\n\n<p>This loop:</p>\n\n<pre><code>i = avg_post_likes = 0\nwhile i &lt;=x-1:\n # ...\n i += 1\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>for _ in range(x):\n # ...\n</code></pre>\n\n<p>You also need a better name for <code>x</code>.</p>\n\n<h2>Use <code>dict.update</code></h2>\n\n<p>This code:</p>\n\n<pre><code> post_info[\"Hashtag\"] = hashtag_name\n post_info[\"Active Days Ago\"] = posted_days_ago\n post_info[\"Post Count\"] = post_count\n post_info[\"AVG. Likes\"] = round(sum(likes_value)/len(likes_value),2)\n post_info[\"MAX. Likes\"] = max(likes_value)\n post_info[\"MIN. Likes\"] = min(likes_value)\n post_info[\"AVG. Comments\"] = round(sum(comments_value)/len(comments_value),2)\n post_info[\"Hashtag URL\"] = hashtag_url\n post_info[\"Post Ready Tag\"] = post_ready_tag\n</code></pre>\n\n<p>can be greatly simplified by use of <code>update</code>:</p>\n\n<pre><code>post_info.update({\n 'Hashtag': hashtag_name,\n 'Active Days Ago': posted_days_ago,\n # ...\n</code></pre>\n\n<h2>Use context management</h2>\n\n<p>You were doing so well elsewhere in the file! But then we see this:</p>\n\n<pre><code>data = open(data_filename, 'r',encoding='utf-8')\ntarget = open(destination, 'w',encoding='utf-8')\n</code></pre>\n\n<p>Those should also use <code>with</code>. You can keep the indentation from getting out-of-control by writing more subroutines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T18:17:55.207", "Id": "210894", "ParentId": "210893", "Score": "5" } } ]
{ "AcceptedAnswerId": "210894", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T17:47:14.530", "Id": "210893", "Score": "8", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "Scraping Instagram for Hashtag data" }
210893
<p>I decided to make a calculator as a project. Implementing basic addition, subtraction, division, and multiplication was fairly easy.</p> <p>I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this. Any advice?</p> <pre><code>def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def div(x, y): value = None while True: try: value = x / y break except ZeroDivisionError: print('Value is not dividable by 0, try again') break return value def num_input(prompt='Enter a number: '): while True: try: print(prompt, end='') x = int(input()) break except ValueError: print('You must input a number. Try again.') return x def get_two_val(): x, y = num_input(), num_input() return x, y print("Welcome to Simple Calc") # declaration of variables num_of_calc_counter = 0 index_of_calc = 1 calculations = [] while True: print("Choose from the following options:") print(" 1. Add") print(" 2. Subtract") print(" 3. Multiply") print(" 4. Divide") print(" 5. Sales Tax Calculator") print(" 6. Recent Calculations") print(" 0. Quit") usrChoice = num_input('Enter your choice: ') ''' Menu workflow options 1-4 take in two numbers and perform the specified calculation and then add the result to a master list that the user can reference later. lastly, the workflow increments the num_of_calc variable by 1 for recent calc logic option 5 is a simple tax calculator that needs work or option to enter or find tax rate option 6 returns a list of all the calculations perform by the user ''' if usrChoice is 1: numbers = get_two_val() result = add(*numbers) print(numbers[0], "plus", numbers[1], "equals", result) calculations.extend([result]) num_of_calc_counter += 1 elif usrChoice is 2: numbers = get_two_val() result = sub(*numbers) print(numbers[0], "minus", numbers[1], "equals", result) calculations.extend([result]) num_of_calc_counter += 1 elif usrChoice is 3: numbers = get_two_val() result = mul(*numbers) print(numbers[0], "times", numbers[1], "equals", result) calculations.extend([result]) num_of_calc_counter += 1 elif usrChoice is 4: numbers = get_two_val() result = div(*numbers) print(numbers[0], "divided by", numbers[1], "equals", result) calculations.extend([result]) num_of_calc_counter += 1 elif usrChoice is 5: tax_rate = .0875 price = float(input("What is the price?: ")) total_tax = tax_rate * price final_amount = total_tax + price print('Tax rate: ', tax_rate, '%') print('Sales tax: $', total_tax) print('_____________________________') print('Final amount: $', final_amount) # elif usrChoice is 6: if len(calculations) is 0: print('There are no calculations') elif num_of_calc_counter == 0: index_of_calc = 1 for i in calculations: print(index_of_calc, i) index_of_calc += 1 num_of_calc_counter += 1 elif index_of_calc == num_of_calc_counter: index_of_calc = 1 for i in calculations: print(index_of_calc, i) index_of_calc += 1 num_of_calc_counter += 1 elif num_of_calc_counter &gt; index_of_calc: index_of_calc = 1 for i in calculations: print(index_of_calc, i) index_of_calc += 1 num_of_calc_counter -= 1 elif num_of_calc_counter &lt; index_of_calc: index_of_calc = 1 for i in calculations: print(index_of_calc, i) index_of_calc += 1 num_of_calc_counter += 1 elif usrChoice is 0: break </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:02:39.137", "Id": "407719", "Score": "0", "body": "Sales tax calculations are excluded from the history? Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:31:55.250", "Id": "407727", "Score": "1", "body": "I disagree with that close vote - this seems on-topic to me. The OP describes it as being functional." } ]
[ { "body": "<h2>Use the <code>operator</code> package</h2>\n\n<p>This series of functions:</p>\n\n<pre><code>def add(x, y):\n return x + y\n\n\ndef sub(x, y):\n return x - y\n\n\ndef mul(x, y):\n return x * y\n</code></pre>\n\n<p>can go away entirely. (You can include <code>div</code> too if you rework the way that exceptions are handled). Instead, use the <a href=\"https://docs.python.org/3.4/library/operator.html\" rel=\"nofollow noreferrer\">operator package</a>.</p>\n\n<h2>Early return</h2>\n\n<p>This:</p>\n\n<pre><code>def num_input(prompt='Enter a number: '):\n while True:\n try:\n print(prompt, end='')\n x = int(input())\n break\n except ValueError:\n print('You must input a number. Try again.')\n return x\n</code></pre>\n\n<p>doesn't need a <code>break</code>. Replace the <code>break</code> with a <code>return</code> and delete the return outside of the loop.</p>\n\n<h2>Write a <code>main</code> method</h2>\n\n<p>...to pull your code out of global scope.</p>\n\n<h2>Use more loops</h2>\n\n<p>This:</p>\n\n<pre><code>print(\" 1. Add\")\nprint(\" 2. Subtract\")\nprint(\" 3. Multiply\")\nprint(\" 4. Divide\")\nprint(\" 5. Sales Tax Calculator\")\nprint(\" 6. Recent Calculations\")\nprint(\" 0. Quit\")\n</code></pre>\n\n<p>can be rewritten as a tuple:</p>\n\n<pre><code>menu_choices = (\n ('Add', do_add),\n ('Subtract', do_subtract),\n # ...\n)\n</code></pre>\n\n<p>The index of the outer tuple is the user input, the first element of the inner tuple is the menu item name, and the second element of the inner tuple is the name of a function you can call to execute the menu item feature. Then your input logic can be simplified to something like</p>\n\n<pre><code>print('Choose from the following options:')\nprint('\\n'.join('%2d. %s' % (i, name)\n for i, (name, _) in enumerate(menu_choices)))\nuser_choice = num_input('Enter your choice:')\nif 0 &lt;= user_choice &lt; len(menu_choices):\n menu_choices[user_choice][1]()\n</code></pre>\n\n<h2>Use append instead of extend</h2>\n\n<p>This:</p>\n\n<pre><code>calculations.extend([result])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>calculations.append(result)\n</code></pre>\n\n<h2>Don't repeat yourself</h2>\n\n<p>These four blocks:</p>\n\n<pre><code> elif num_of_calc_counter == 0:\n index_of_calc = 1\n for i in calculations:\n print(index_of_calc, i)\n index_of_calc += 1\n num_of_calc_counter += 1\n elif index_of_calc == num_of_calc_counter:\n index_of_calc = 1\n for i in calculations:\n print(index_of_calc, i)\n index_of_calc += 1\n num_of_calc_counter += 1\n elif num_of_calc_counter &gt; index_of_calc:\n index_of_calc = 1\n for i in calculations:\n print(index_of_calc, i)\n index_of_calc += 1\n num_of_calc_counter -= 1\n elif num_of_calc_counter &lt; index_of_calc:\n index_of_calc = 1\n for i in calculations:\n print(index_of_calc, i)\n index_of_calc += 1\n num_of_calc_counter += 1\n</code></pre>\n\n<p>do the exact same thing! So just replace them all with one <code>else</code> following your <code>if len(calculations) == 0</code>.</p>\n\n<p>Also, that first <code>if</code> can be simplified to <code>if not calculations</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:46:51.963", "Id": "210900", "ParentId": "210899", "Score": "2" } } ]
{ "AcceptedAnswerId": "210900", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T19:58:27.370", "Id": "210899", "Score": "2", "Tags": [ "python", "beginner" ], "Title": "Implementing a history of user action for a calculator" }
210899
<p>This is a program to purchase tickets for a ferry. There are two classes - <code>business</code> and <code>economy</code>. I am wondering what is a better way to write this piece of code. Honestly I want someone to review my whole code file and give me feedback on things I can improve. I just want to improve my coding ability and become a better and efficient coder by learning from the mistakes that I make.</p> <pre><code>import datetime import json import os from colorama import Fore, Back from colorama import init # Clears commandline screen for windows init() def clear_screen(): def clear(): return os.system('cls') clear() # Returns Time of the trip def get_time(): while (True): clear_screen() print_purchasing_header() try: time = int(input("""Enter time of departure (24-hour): 1. 10:00 2. 11:00 3. 12:00 4. 13:00 5. 14:00 6. 15:00 7. 16:00 8. 17:00\n\nEnter selection: """)) if (time == 1): return 10 elif (time == 2): return 11 elif (time == 3): return 12 elif (time == 4): return 13 elif (time == 5): return 14 elif (time == 6): return 15 elif (time == 7): return 16 elif (time == 8): return 17 else: input( "Please enter valid choice.. press [Enter] to continue . . . ") except ValueError: input("Please Enter a Number only! Press [Enter] to try again. .") # Returns destination for the trip def get_destination(): while (True): clear_screen() print_purchasing_header() try: destination_choice = int(input("""Select your destination : 1.Penang - Langkawi 2.Langkawi - Penang\n\nEnter selection :""")) destination = None if (destination_choice == 1): destination = "Langkawi" return destination elif (destination_choice == 2): destination = "Penang" return destination else: input("Invalid Number...Press [Enter] to try again. .") except ValueError: input("Please enter a Number only! Press [Enter] to try again. . ") # Returns the name of the customer def get_name(): while (True): customer_f_name = input("Enter your first name: ") customer_m_name = input( "Enter your middle name(if no middle name leave blank): ") customer_l_name = input("Enter your last name: ") customer_name = customer_f_name + " " + customer_m_name + " " + customer_l_name if customer_f_name.isalpha() and customer_l_name.isalpha(): return customer_name # Create list of tuples that contains (1st trip time, 2nd trip time) def create_timeslot(): time_slot = [] for time in range(10, 18, 1): time_slot.append((time - 9, time)) return time_slot # Creates list with [source, destination, (different time slots)] def create_schedule_penang(time_slot): schedule_penang = [] for trip_penang in range(0, 8, 1): schedule_penang.append(["Langkawi", "Penang", time_slot[trip_penang]]) return schedule_penang # Creates list with [source, destination, (different time slots)] # This Function can be generalized to allow the user to create # Schedule for more than one destination def create_schedule_langkawi(time_slot): schedule_langkawi = [] for trip_langkawi in range(0, 8, 1): schedule_langkawi.append( ["Penang", "Langkawi", time_slot[trip_langkawi]]) return schedule_langkawi # Creates a mapping of ferry number to schedules # of different destinations def create_ferry_schedule(schedule_langkawi, schedule_penang): ferry_schedule = {} for item in range(0, 8, 1): ferry_schedule['FERRY' + " " + str(item + 1)] = schedule_langkawi[item] ferry_schedule['FERRY' + " " + str(item + 9)] = schedule_penang[item] return ferry_schedule # Creates dictionary containing seating arrangement # Key = Seat Number and Value = Booked[1]/Unbooked[0] # Initially all seats are unbooked def init_ferry(): ferry = {} # Could replace 11 by N to accommodate more seats for business_seats in range(1, 11, 1): if business_seats &gt;= 10: business_seats = 'B' + str(business_seats) else: business_seats = 'B0' + str(business_seats) ferry[business_seats] = 0 # Could replace 40 by M to accommodate more seats for economy_seats in range(1, 41, 1): if economy_seats &lt; 10: economy_seats = 'E0' + str(economy_seats) else: economy_seats = 'E' + str(economy_seats) ferry[economy_seats] = 0 return ferry # Creates a list of ferries containing dictionaries # created by init_ferry function # Hardcoded to create 8 Ferries only def create_ferry_list(ferry): list_of_ferry = {} # Could replace 9 by no_of_ferries for more ferries for ferry_number in range(1, 17, 1): list_of_ferry['FERRY' + " " + str(ferry_number)] = ferry return list_of_ferry # Returns the ferry schedule dictionary containing # ferry number and schedule def get_ferry_schedule(): ferry_schedule = create_ferry_schedule(create_schedule_langkawi(create_timeslot()), create_schedule_penang(create_timeslot())) return ferry_schedule # Returns ferry ID of the ferry associated with the # customers choice of destination and time def auto_select_ferry(destination_choice, time_choice): ferry_schedule = get_ferry_schedule() for ferry_id, schedule in ferry_schedule.items(): destination = schedule[1] if destination_choice == destination: time_slot = schedule[2] for time in time_slot: if (time_choice == time): return ferry_id def get_source(destination_choice): ferry_schedule = get_ferry_schedule() for ferry_id, schedule in ferry_schedule.items(): destination = schedule[1] if destination_choice == destination: return schedule[0] # Returns whether ferry is full or not def is_ferry_full(ferry_id, ferry_list): for ferry_number, ferry in ferry_list.items(): if ferry_number == ferry_id: for seat_number, availability in ferry.items(): if availability == 0: return False elif availability == 1: continue return True # Returns if business/economy zone seats are available or not def is_zone_available(ferry_id, type_of_seat, ferry_list): ferry = ferry_list[ferry_id] business = list(ferry) economy = list(ferry) if (type_of_seat == "BUSINESS"): business = business[:10] for seat in business: if ferry[seat] == 0: return True return False else: economy = economy[10:] for seat in economy: if ferry[seat] == 0: return True return False # Returns if seat chosen by customer is available or not def is_seat_available(ferry_id, customer_seat, ferry_list): for ferry_number, ferry in ferry_list.items(): if ferry_number == ferry_id: for seat_number, availability in ferry.items(): if seat_number == customer_seat and availability == 0: return True elif seat_number == customer_seat and availability == 1: return False else: continue # Returns seating arrangement def display_ferry_seats(ferry_id, ferry_list): clear_screen() ferry = ferry_list[ferry_id] date = datetime.datetime.now().strftime("%d-%m-%Y") count = 0 # used to format the output so that after every 5 seats there is a \n or line-break print("-" * 65 + "\n\t\t\tSEATING ARRANGEMENT\n" + "-" * 65 + "\n") print("Ferry ID: {} \t\t\t\t Date: {}".format(ferry_id, date)) print(Fore.YELLOW, "\n" + "-" * 65 + "\n\t\t\tBUSINESS CLASS\n" + "-" * 65, Fore.RESET) for seat_number, availability in ferry.items(): count += 1 if availability == 0: seat_color = Back.BLUE else: seat_color = Back.RED if count % 5 != 0: print(Back.RESET, " ", end=' ') print(seat_color, "* {} * ".format(seat_number, availability), end=' ') if count == 10: print(Back.RESET, " ", end=' ') print(seat_color, "* {} * ".format(seat_number, availability), end=' ') print(Back.RESET, Fore.CYAN, "\n" + "-" * 65 + "\n\t\t\tECONOMY CLASS\n" + "-" * 65, Fore.RESET) elif count % 5 == 0: print(Back.RESET, " ", end=' ') print(seat_color, "* {} * ".format(seat_number, availability), end=' ') print("\n") print(Back.RESET, "\nB = Business Seats \t\t E = Economy Seats") print(Back.RED, "RED", end=' ') print(Back.RESET, "= Booked Seats\t\t", end=' ') print(Back.BLUE, "BLUE", end=' ') print(Back.RESET, "= Available Seats") input("Press [Enter] to continue. . .") # Books an available seat and updates the dictionary and saves to file def assign_seat(ferry_id, customer_seat, ferry_list): if is_ferry_full(ferry_id, ferry_list): print("The ferry is full next ferry is in one hour") else: if is_seat_available(ferry_id, customer_seat, ferry_list): for ferry_number, ferry in ferry_list.items(): if ferry_number == ferry_id: for seat_number, availability in ferry.items(): if seat_number == customer_seat: ferry_list[ferry_id][customer_seat] = 1 save_to_file(ferry_list) else: return "Seat not available" def print_purchasing_header(): print("-" * 60, "\n\t\t\tPurchasing Module\n" + "-" * 60) def prompt_user_seat(seat_type, seat_string, ferry_id, ferry_list): while (True): clear_screen() display_ferry_seats(ferry_id.upper(), ferry_list) seat_text = seat_string try: seat_number = input("\nType the seat number" + seat_text + ": ") # Add input validation seat_number = seat_number.upper() count = 0 for ferry_number, ferry in ferry_list.items(): if ferry_number == ferry_id: for seat, availability in ferry.items(): count += 1 if seat_type == "BUSINESS" and count &gt; 0 and count &lt;= 10: if seat == seat_number: return seat_number elif seat_type == "BUSINESS" and count &gt; 10: input("Please enter seats between [B01-B10]..Press [Enter] to Continue. .") break elif seat_type == "ECONOMY" and count &gt; 10: if seat == seat_number: return seat_number elif seat_type == "ECONOMY" and seat_number[0] == 'B' and count &lt;= 10: input("Please enter seats between [E01-E40]..Press [Enter] to Continue. .") break except: input("Please input a valid seat number..Press [Enter] to Continue. .") def get_type_of_seat(): while (True): clear_screen() type_of_seat = input("""Select Type of Seat: B - Business E - Economy Type the letter of the desired class of seat[Ex: B for Business] &gt;&gt; """) if type_of_seat.upper() == "B": return "business" elif type_of_seat.upper() == "E": return "economy" else: input( "Please enter only [B or E]. . Press [Enter] to try again. . . ") def get_seat(type_of_seat, ferry_id, ferry_list): while (True): if type_of_seat == "BUSINESS": example_string = "[Ex: B04]" else: example_string = "[Ex: E06]" seat_number = prompt_user_seat(type_of_seat, example_string, ferry_id, ferry_list) seat_number = seat_number.upper() if (is_seat_available(ferry_id.upper(), seat_number, ferry_list)): assign_seat(ferry_id.upper(), seat_number, ferry_list) return seat_number else: input("Seat is not available please choose another seat!") # Optimize this function def purchase_menu(): clear_screen() print_purchasing_header() ferry_list = file_exists() customer_name = get_name() destination_choice = get_destination() time_choice = get_time() ferry_schedule = get_ferry_schedule() ferry_id = auto_select_ferry(destination_choice, time_choice) if is_ferry_full(ferry_id, ferry_list): input( "Sorry the ferry is full, next ferry departs in 1 hour!\nPress [Enter] to Continue. . . ") main_menu() else: type_of_seat = get_type_of_seat() type_of_seat = type_of_seat.upper() if type_of_seat == "BUSINESS": if is_zone_available(ferry_id.upper(), type_of_seat, ferry_list): seat_number = get_seat(type_of_seat, ferry_id, ferry_list) else: type_of_seat = "ECONOMY" if is_zone_available(ferry_id.upper(), type_of_seat, ferry_list): choice = input( "Business zone is fully booked, is it okay to be placed in Economy Class? Type and Enter['Yes' or 'No'] &gt;&gt; ") if choice.upper() == "YES": seat_number = get_seat( type_of_seat, ferry_id, ferry_list) elif choice.upper() == "NO": input( "Next Ferry is in 1 hour\nPress [Enter] to Continue. . . ") main_menu() else: input("Invalid input...Press [Enter] to try again. .") seat_number = get_seat( type_of_seat, ferry_id, ferry_list) else: input( "Ferry is full, next ferry is in 1 hour\nPress [Enter] to Continue. . . ") main_menu() else: if is_zone_available(ferry_id.upper(), type_of_seat, ferry_list): seat_number = get_seat(type_of_seat, ferry_id, ferry_list) else: type_of_seat = "BUSINESS" if is_zone_available(ferry_id.upper(), type_of_seat, ferry_list): choice = input( "Economy zone is fully booked, is it okay to be placed in Business Class? ['Yes' or 'No'] ") if choice.upper() == "YES": seat_number = get_seat( type_of_seat, ferry_id, ferry_list) elif choice.upper() == "NO": input( "Next Ferry is in 1 hour\nPress [Enter] to Continue. . . ") main_menu() else: input("Invalid input... Press [Enter] to try again. .") seat_number = get_seat( type_of_seat, ferry_id, ferry_list) else: input( "Ferry is full, next ferry is in 1 hour\nPress [Enter] to Continue. . . ") main_menu() source = get_source(destination_choice) date = datetime.datetime.now().strftime("%d-%m-%Y") time_choice = str(time_choice) + ":00" print_boarding_ticket(customer_name, source, destination_choice, date, time_choice, type_of_seat, seat_number, ferry_id) def view_seating(): while (True): clear_screen() selection = input("-" * 60 + "\n\t\t\tSEATING ARRANGEMENT MODULE\n" + "-" * 60 + """ F - To select Ferry ID M - Return to Main Menu Please enter one of the Options[F or M]: """) if (selection.upper() == "F"): ferry_menu() #elif (selection.upper() == "T"): #trip_time_menu() # Need to make menu elif (selection.upper() == "M"): main_menu() else: input( "Invalid Input! Please try again... Press [Enter] to Continue. . . ") def ferry_selection(ferry_list): while (True): clear_screen() try: print("\nSELECT A FERRY TO VIEW THE SEATING ARRANGEMENT\n\n") for number, ferry_number in enumerate(ferry_list): print(number + 1, "--&gt;", ferry_number) print("\n") selection = int( input("Enter the number to view the associated ferry seating [Ex: 2] &gt;&gt; ")) if (selection &gt; 0 and selection &lt; 17): return selection else: input( "Please enter number between 1 and 16.. Press [Enter] to Continue. .") except ValueError: input("Please enter numbers only! Press [Enter] to continue. .") def chosen_ferry(selection, ferry_list): for number, ferry_number in enumerate(ferry_list): if (selection == number): return ferry_number else: continue # Improve this function def ferry_menu(): ferry_list = file_exists() while (True): clear_screen() selection = ferry_selection(ferry_list) ferry_id = chosen_ferry(selection - 1, ferry_list) if ferry_id.upper() in ferry_list: display_ferry_seats(ferry_id.upper(), ferry_list) break else: input("Enter valid ferry number! Press [Enter] to try again. .") def main_menu(): while (True): clear_screen() selection = input("-" * 60 + "\n\t\t\tMain Menu\n" + "-" * 60 + """ P - To Purchase Ticket V - To View Seating Arrangement Q - To Quit the System Please Enter one of the Options[P or V or Q]: """) if (selection.upper() == "P"): purchase_menu() elif (selection.upper() == "V"): view_seating() elif (selection.upper() == "Q"): while True: choice = input( "Are you sure you want to quit?(Y - Yes or N - No) &gt;&gt; ") if choice.upper() == 'Y': quit() elif choice.upper() == "N": main_menu() else: input("Please answer with Y or N.. ") clear_screen() else: input( "\nInvalid Input!\nPlease try again...Press [Enter] to Continue. . . ") # Checks whether ferryseats.json file exists which # is the File used to save data of seating arrangement # If it doesn't exists a new file is created with # All seats initially unbooked def file_exists(): if data_path_exists(): try: with open('data/ferryseats.json') as seats_data: ferry_list = json.load(seats_data) return ferry_list except FileNotFoundError: with open('data/ferryseats.json', 'w') as file: json.dump(create_ferry_list(init_ferry()), file) finally: with open('data/ferryseats.json') as seats_data: ferry_list = json.load(seats_data) return ferry_list # Checks Whether Folder 'data' exists # If it doesn't creates the folder def data_path_exists(): if os.path.exists('data'): return True else: os.mkdir('data') return True def save_to_file(ferry_list): with open('data/ferryseats.json', 'w') as file: json.dump(ferry_list, file) def read_from_file(): with open('data/ferryseats.json') as seats_data: ferry_list = json.load(seats_data) return ferry_list def print_boarding_ticket(customer_name, source, destination, date, time, type_of_seat, seat_number, ferry_number): clear_screen() print("-" * 60 + "\n\t\t\tBOARDING TICKET\n" + "-" * 60) print("Customer Name: {}\nSource: {}\t\t\tDestination: {}\nDate: {}\t\t\tTime: {}\nType Of Seat: {}\t\t\tSeat Number: {}\nFerry ID: {}".format(customer_name, source, destination, date, time, type_of_seat, seat_number, ferry_number)) print("-" * 60 + "\n") input("Press [Enter] key to return to main menu. . . ") main_menu() </code></pre>
[]
[ { "body": "<h2>Combine imports</h2>\n\n<pre><code>from colorama import Fore, Back\nfrom colorama import init\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>from colorama import Fore, Back, init\n</code></pre>\n\n<h2>Trim unnecessary local functions</h2>\n\n<pre><code>def clear_screen():\n def clear(): return os.system('cls')\n clear()\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>def clear_screen():\n os.system('cls')\n</code></pre>\n\n<h2>Follow standard format for docstrings</h2>\n\n<p>This comment:</p>\n\n<pre><code># Returns Time of the trip\n</code></pre>\n\n<p>should land here:</p>\n\n<pre><code>def get_time():\n\"\"\"\nReturns time of the trip\n\"\"\"\n</code></pre>\n\n<p>Similar for your other functions.</p>\n\n<h2>Drop unneeded parens</h2>\n\n<p>This:</p>\n\n<pre><code>while (True):\n</code></pre>\n\n<p>doesn't need parens. Similar for</p>\n\n<pre><code>if (destination_choice == 1):\n</code></pre>\n\n<h2>Don't write <code>\\n</code> in a multi-line heredoc</h2>\n\n<p>This:</p>\n\n<pre><code>\"\"\"Enter time of departure (24-hour):\n 1. 10:00\n 2. 11:00\n 3. 12:00\n 4. 13:00\n 5. 14:00\n 6. 15:00\n 7. 16:00\n 8. 17:00\\n\\nEnter selection: \"\"\"\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code>\"\"\"Enter time of departure (24-hour):\n 1. 10:00\n 2. 11:00\n 3. 12:00\n 4. 13:00\n 5. 14:00\n 6. 15:00\n 7. 16:00\n 8. 17:00\n\n Enter selection: \"\"\"\n</code></pre>\n\n<h2>Use math instead of <code>if</code></h2>\n\n<p>These statements:</p>\n\n<pre><code> if (time == 1):\n return 10\n elif (time == 2):\n return 11\n elif (time == 3):\n return 12\n elif (time == 4):\n return 13\n elif (time == 5):\n return 14\n elif (time == 6):\n return 15\n elif (time == 7):\n return 16\n elif (time == 8):\n return 17\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code>return time + 9\n</code></pre>\n\n<h2>Use f-strings</h2>\n\n<p>This:</p>\n\n<pre><code>'FERRY' + \" \" + str(item + 1)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'FERRY {item + 1}'\n</code></pre>\n\n<h2>Drop ineffectual logic blocks</h2>\n\n<p>This:</p>\n\n<pre><code> if availability == 0:\n return False\n elif availability == 1:\n continue\n</code></pre>\n\n<p>has an <code>elif</code> that doesn't do anything. This might be a bug (if you intended for that to continue through the outer loop, which it won't). If it's working correctly, the <code>elif</code> can simply be deleted.</p>\n\n<h2>Don't <code>else</code> after a <code>return</code></h2>\n\n<p>This:</p>\n\n<pre><code> return False\nelse:\n</code></pre>\n\n<p>doesn't need an <code>else</code>, because the previous block already returned. De-indent the code in the <code>else</code> block and delete the <code>else</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:50:14.850", "Id": "407734", "Score": "0", "body": "Thank you for the feedback, could you please elaborate on the \"Use math instead of ifs\" part" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:58:33.440", "Id": "407735", "Score": "0", "body": "@AliAhsanSaeed Look at the numbers you're working with. There's a pattern. You can reduce all of those `if`s to a single mathematical expression based on the pattern. \"time + 9\" covers all 8 cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:14:15.920", "Id": "407737", "Score": "0", "body": "thank you! any general tips or pointers on what I should improve on? maybe some concepts that I should work on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:15:42.483", "Id": "407738", "Score": "0", "body": "@AliAhsanSaeed Other than what I've already written above - your data structures are a little ad-hoc. You could benefit from restructuring them as classes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:35:16.213", "Id": "210907", "ParentId": "210901", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T20:53:15.570", "Id": "210901", "Score": "0", "Tags": [ "python", "performance" ], "Title": "Purchasing tickets for a ferry" }
210901
<p>This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; void print_out_reversed(char string[]) { int index = strlen(string); while (string[index] != '\0') index--; for (int i = index; i &gt;= 0; i--) putchar(string[i]); putchar('\n'); } void print_decimal_number_binary(int number) { if (number == 0) { printf("0\n"); return; } char bits[sizeof(int) * 8 + 1] = {0}; int index = 0; while (number &gt; 0) { if (number % 2 == 0) { bits[index] = '0'; } else { bits[index] = '1'; } number = number / 2; index++; } print_out_reversed(bits); } int main() { printf("enter number: "); int number; scanf("%i", &amp;number); print_decimal_number_binary(number); } </code></pre>
[]
[ { "body": "<h2>Terminology</h2>\n\n<p>It's important to be able to understand (and describe) what's actually going on. Your program</p>\n\n<ol>\n<li>converts from an integer decimal string representation to an integer using <code>scanf</code>. This integer is then represented as a binary number in the processor.</li>\n<li>converts from that integer back into a string representation, but rather than it being decimal, it's binary.</li>\n</ol>\n\n<p>So yes - it technically converts from \"decimal to binary\", but really it's \"decimal string to integer to binary string\".</p>\n\n<h2>Use <code>const</code></h2>\n\n<pre><code>void print_out_reversed(char string[])\n</code></pre>\n\n<p>doesn't modify <code>string</code>, so write <code>const char string[]</code>.</p>\n\n<h2>Simplify your <code>strlen</code> usage</h2>\n\n<p>This:</p>\n\n<pre><code>int index = strlen(string);\n\nwhile (string[index] != '\\0')\n index--;\n\nfor (int i = index; i &gt;= 0; i--)\n putchar(string[i]);\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>for (int i = strlen(string)-1; i &gt;= 0; i--)\n putchar(string[i]);\n</code></pre>\n\n<p>It seems that you don't trust what <code>strlen</code> is doing, which is why you have that intermediate <code>while</code> loop. But that loop won't have any effect, because the null terminator will always be where <code>strlen</code> says it is.</p>\n\n<h2>Use math instead of <code>if</code></h2>\n\n<p>This:</p>\n\n<pre><code> if (number % 2 == 0)\n {\n bits[index] = '0';\n }\n else\n {\n bits[index] = '1';\n }\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>bits[index] = '0' + (number &amp; 1);\n</code></pre>\n\n<h2>Use combined operation and assignment</h2>\n\n<p>This:</p>\n\n<pre><code>number = number / 2;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>number /= 2;\n</code></pre>\n\n<p>or, for speed (which the compiler will do for you anyway)</p>\n\n<pre><code>number &gt;&gt;= 1;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T22:32:03.130", "Id": "407891", "Score": "2", "body": "`int number ... number /= 2;` is not the same code as `number >>= 1;` The first is well defined. The 2nd `number >>= 1;`, when `number < 0` the resulting value is implementation-defined. `number /= 2;` is preferred for unambiguity. Note: `(number & 1)` is incorrect code for the now rare _ones' complement_ platforms. OP's code functions correctly on all - even if it is ponderous." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:28:15.543", "Id": "210912", "ParentId": "210909", "Score": "8" } }, { "body": "<pre><code>#include &lt;stdio.h&gt;\n\nvoid get_bits(unsigned long long* num, char * out, int bytes);\n\nint main(void)\n{\n long long x = 0;\n\n printf(\"Enter a number: \");\n scanf(\"%lli\", &amp;x);\n\n char bits[sizeof(unsigned long long)+1] = {0};\n get_bits(&amp;x, bits, 4);\n\n printf(\"%d in binary %s\\n\", x, bits);\n\n return 0;\n}\n\n//assumes char array of length 1 greater than \n//number of bits\n//EDIT: VERSION WITHOUT MEMCPY AS REMINDED BY @REINDERIEN\n//REMOVED aliasing issue\nvoid get_bits(unsigned long long * num, char *out, int bytes)\n{\n unsigned long long filter = 0x8000000000000000;\n // unsigned long long *temp = num;\n\n if(bytes &lt;= 0) return;\n if(bytes &gt; 8) bytes = 8;\n\n filter = filter &gt;&gt; (8*(sizeof(unsigned long long)-bytes));\n //memcpy(&amp;temp, num, bytes);\n int bits = 8*bytes;\n for(int i=0;i&lt;bits;i++) {\n //if(filter &amp; temp)\n //if((filter &gt;&gt; i) &amp; *temp)\n if((filter &gt;&gt; i) &amp; *num)\n out[i] = '1';\n else\n out[i] = '0';\n\n //temp = temp &lt;&lt; 1;\n }\n out[bits] = '\\0';\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Void* removed</p>\n\n<h2>Improvements</h2>\n\n<p>The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles. </p>\n\n<p>The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).</p>\n\n<p>One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.</p>\n\n<h2>Alternative Solution</h2>\n\n<p>The function get_bits will accept any integer representation.</p>\n\n<p>It will \"return,\" really populate, a character array with up to a 64-bit bit representation of the number.</p>\n\n<p>It <em>NO LONGER</em> relies on memcpy from string.h.</p>\n\n<h2>Inputs for get_bits</h2>\n\n<p>unsigned long long* *num : a pointer to the memory address of the number to be represented in \n binary</p>\n\n<p>char *out : the address of a character array to store the bit representation.<br>\n NOTE: This should be of length 1 longer than the number of bits to \n be represented</p>\n\n<p>int bytes : number of bytes containing the number to represent in binary</p>\n\n<h2>Implementation</h2>\n\n<p>Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. The input number passed as an unsigned long long*. Using bit shifting, the filter is shifted to the right to align it with the highest bit of the number.</p>\n\n<p>Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.</p>\n\n<p>Only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and *temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.</p>\n\n<p>At the end of each iteration the filter is shifted incrementally by 1 more bit to the right.</p>\n\n<p>Ex. In binary, if temp is 1010, then temp &lt;&lt; 1 is 0100. (a suitable filter would be 1000 in binary). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T21:09:31.357", "Id": "407788", "Score": "0", "body": "Why would you make `bits` a 64-character string if you're only scanning a 32-bit integer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T22:37:10.393", "Id": "407793", "Score": "0", "body": "\"One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.\" You think so? Have you measured it? There's a third solution that uses your `void*` method, but can process input of an unlimited length (not restricted to 64 bits). Populating something in reverse is not slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T22:40:07.603", "Id": "407795", "Score": "0", "body": "Read through your own solution again. You aren't using one loop; you have a `memcpy` that isn't necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T00:13:21.167", "Id": "407801", "Score": "2", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/87897/discussion-between-reinderien-and-rjm)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:14:31.487", "Id": "407896", "Score": "0", "body": "Code assumes 8/byte. Reasonable, yet code could use `CHAR_BIT` instead of the magic number `8`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:17:04.827", "Id": "407897", "Score": "0", "body": "OP use `char bits[sizeof(int) * 8 + 1] = {0};` and this code uses `char bits[65] = {0};`. OP's code is better as it does not assume `int `width limitation and right-sizes the buffer. (Although I do not expect 128-bit `int` in the next 10 years)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:20:03.243", "Id": "407898", "Score": "0", "body": "`unsigned long long *temp = num;` is undefined behavior (UB) as it is not known that `num` is properly aligned for `unsigned long long` access." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T22:27:48.223", "Id": "408055", "Score": "0", "body": "Please keep discussions in comments to a minimum. This post has been auto-flagged as having too many comments. Continue the discussion in the chat room above, and please remove any comments that are no longer relevant. Much appreciated ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T08:52:05.663", "Id": "408091", "Score": "0", "body": "\"Assumes little endian address\" No, it doesn't? Why did you add this part? The advantage of shifts is that they are endianess-independent." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T23:50:31.130", "Id": "210919", "ParentId": "210909", "Score": "2" } }, { "body": "<p>I'm adding another answer in a different direction from my previous one, both to show the OP some alternative techniques, and to illustrate an adaptation of @RJM's method.</p>\n\n<p>Here's the code; it's quite simple:</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n\nstatic void printBinary(const uint8_t *restrict num, int bytes) {\n for (int p = bytes - 1; p &gt;= 0; p--) {\n uint8_t x = num[p];\n for (int i = 0; i &lt; 8; i++) {\n putchar('0' | (x &gt;&gt; 7));\n x &lt;&lt;= 1;\n }\n }\n}\n\nint main() {\n int64_t x;\n for (;;) {\n puts(\"Enter an integer: \");\n if (scanf(\"%lld\", &amp;x) == 1)\n break;\n while (getchar() != '\\n');\n }\n\n printBinary((uint8_t*)&amp;x, sizeof(x));\n putchar('\\n');\n\n return 0;\n}\n</code></pre>\n\n<p>Things to observe as compared to the OP's code (and RJM's code):</p>\n\n<ul>\n<li>There are no calls to <code>malloc</code> or <code>memcpy</code>.</li>\n<li>The result is not stored in memory; it's output directly to <code>stdout</code>.</li>\n<li>The input integer has a primitive form of validation. The program will loop until <code>scanf</code> succeeds.</li>\n<li>The input integer supports 64 bits instead of 32.</li>\n<li>The output routine supports integers of any length, with the assumption that the integer is little-endian.</li>\n<li>The bit sequence reversal is done directly in the decoding loop, rather than as a separate step.</li>\n<li>There is no need for a \"filter\" (mask) variable.</li>\n<li>The main loop does not need an <code>if</code>.</li>\n</ul>\n\n<h2>A brief word on computers</h2>\n\n<p>This code assumes a few things that are true in the vast (vast) majority of cases:</p>\n\n<ul>\n<li>The processor is little-endian</li>\n<li>There are 8 bits per byte</li>\n<li>The caller cares about the \"real\" binary representation of data in the processor, rather than the \"logical\" binary translation of variables</li>\n</ul>\n\n<p>The last point applies to both signed and floating-point data. This code does not care to write \"-10\", because that's not how the processor stores the data. This code will show either one's-complement (never seen these days) or two's-complement (always seen these days) machine representations of the data.</p>\n\n<p>Similarly, this code does not show \"-0.5\" as \"-0.1\" in binary. To do so would make the code more complicated.</p>\n\n<h2>A brief word on <code>restrict</code></h2>\n\n<p>For the dirty details, do some <a href=\"https://en.cppreference.com/w/c/language/restrict\" rel=\"nofollow noreferrer\">reading here</a>.</p>\n\n<p><code>restrict</code> is a promise that no aliasing is done; i.e. that this pointer is the only way to access the data it points to, to enable some optimizations that wouldn't otherwise be possible. In the context of this program, if it's self-contained, the keyword won't have any effect. <code>restrict</code> enables some optimizations that would make it invalid for other code to modify the same data. Even in a context where there is only one pointer argument to the function, <code>restrict</code> has meaning. A multi-threaded program could alias the data, or (though not the case here) this function could call out to another function that already holds an alias. These aliases and <code>restrict</code> cannot coexist.</p>\n\n<p>I'm happy to explain any aspect of this approach for the purposes of education.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:21:05.987", "Id": "407805", "Score": "0", "body": "Cool. Would that '0' | (x >> 7) be encoded as a '1'?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:21:52.497", "Id": "407806", "Score": "0", "body": "@RJM Yep! Assuming that the MSB is 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:24:24.360", "Id": "407807", "Score": "1", "body": "Thanks. Good discussion. Nice to meet you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:10:14.857", "Id": "407894", "Score": "0", "body": "Note this code prints out `-2` decimal as a positive binary `\"1111111111111111111111111111111111111111111111111111111111111110\\n\"`. A reasonable expectation for a negative value in binary is `\"-10\\n\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:12:46.210", "Id": "407895", "Score": "0", "body": "Code requires 8/byte. Reasonable, yet code could use `unsigned char` and `CHAR_BIT` to remove requiring the optional type `uint8_t` and `the magic number 8." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:15:37.347", "Id": "407997", "Score": "0", "body": "In my opinion `(x>>7) + '0'` is clearer than `'0' | (x >> 7)`. And of course `(x>>7) ? '1' : '0'` is the clearest, although I'm not sure if that would trigger the compiler to introduce an extra branch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:17:28.770", "Id": "407999", "Score": "0", "body": "What's the purpose of `restrict` here since the function only takes one pointer parameter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:42:08.567", "Id": "408001", "Score": "0", "body": "@Lundin - See notes in edited question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:35:14.913", "Id": "408320", "Score": "0", "body": "Little-endian layout is hardly the \"vast majority\" of systems (even if x86 claims a big chunk of desktop processors)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T00:12:54.217", "Id": "210951", "ParentId": "210909", "Score": "1" } }, { "body": "<blockquote>\n <p>if I have used the elements of this language properly. Suggestions for improvement are welcome.</p>\n</blockquote>\n\n<ul>\n<li>Good use of <code>sizeof(int)</code> to form a right size buffer rather than assuming some magic number.</li>\n</ul>\n\n<hr>\n\n<p>Improvements ideas</p>\n\n<p><strong>Negative numbers</strong></p>\n\n<p>Code only prints a <code>'\\n'</code> (and no visible text) when the <code>int</code> is negative.</p>\n\n<p><strong>Unnecessary code</strong></p>\n\n<p>The special test for <code>0</code> can be deleted ...</p>\n\n<pre><code>if (number == 0) {\n printf(\"0\\n\");\n return;\n}\n</code></pre>\n\n<p>... by using a following</p>\n\n<pre><code>do {\n ...\n} while (number &gt; 0);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>while (number &gt; 0) {\n ...\n}\n</code></pre>\n\n<p><strong>Assumed <code>char</code> size</strong></p>\n\n<p>Code assumes 8 bits/<code>char</code> with <code>sizeof(int) * 8</code>. This is very common yet not specified in C. Instead use <code>CHAR_BIT</code> for maximum portability. </p>\n\n<pre><code>#include &lt;limits.h&gt;\n\n// char bits[sizeof(int) * 8 + 1] = {0};\nchar bits[sizeof(int) * CHAR_BIT + 1] = {0};\n</code></pre>\n\n<p><strong>Simplified code</strong> </p>\n\n<p>To well print negative numbers takes a little work to properly handle <em>all</em> negative values including <code>INT_MIN</code>.</p>\n\n<p>Remember that <code>-number</code> is <em>undefined behavior</em> (UB) when <code>number == INT_MIN</code>.</p>\n\n<p>Simplified code that forms the string right-to-left to skip the reverse step.</p>\n\n<pre><code>#include &lt;limits.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid print_decimal_number_binary_alt(int number) {\n int n = number;\n char bits[sizeof(int) * CHAR_BIT + 2]; // + 2 for '-' and '\\0';\n\n char *s = &amp;bits[sizeof bits - 1]; // Point to last array element;\n *s = '\\0';\n\n do {\n s--;\n *s = '0' + (n % 2 != 0);\n n /= 2;\n } while (n);\n\n if (number &lt; 0) {\n *(--s) = '-';\n }\n\n puts(s);\n}\n</code></pre>\n\n<p>Sample</p>\n\n<pre><code>int main(void) {\n print_decimal_number_binary_alt(0);\n print_decimal_number_binary_alt(1);\n print_decimal_number_binary_alt(-1);\n print_decimal_number_binary_alt(42);\n print_decimal_number_binary_alt(INT_MAX);\n print_decimal_number_binary_alt(INT_MIN);\n}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>0\n1\n-1\n101010\n1111111111111111111111111111111\n-10000000000000000000000000000000\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:12:24.723", "Id": "407991", "Score": "0", "body": "This will work fine but some cache memory guru will probably whine. It might actually be faster to loop from MSB and downwards in search of the first `1`, then write to the array from index 0 to n. As a bonus, the code gets far less cryptic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:01:50.913", "Id": "408013", "Score": "0", "body": "@Lundin Such [sub-optimizations](https://codereview.stackexchange.com/questions/210909/convert-decimal-to-binary/211001?noredirect=1#comment407991_211001) are selectively better or worse. This code does less work for small values, unlike your suggestion. What part do you find cryptic? Without UB, it does show it handles the entire `int` range." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T07:26:01.777", "Id": "408087", "Score": "0", "body": "A line such as `*(--s) = '0' + (n % 2 != 0);` is not easy to digest even for veterans. Down-counting iterators in general make the code harder to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:03:48.073", "Id": "408139", "Score": "0", "body": "@Lundin Curious: How would you code `*(--s) = '0' + (n % 2 != 0);` to achieve similar functionality?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:10:24.800", "Id": "408141", "Score": "0", "body": "To begin with, separate iteration from assignment. Then I would prefer something like `(n & 1) ? '1' : '0'`, given that this doesn't result in more branches in the machine code. And overall, I think the method I cooked up in a separate answer will have superior performance. Though it doesn't use the definition of \"signed binary\" as you do here, but assumes that there's raw data that may or may not be represented as signed though 2's complement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:38:36.930", "Id": "408152", "Score": "0", "body": "@Lundin Yes using a separate line for `s--` tend to be favored - post amended. Makes little difference to me so I try various ways and listen for feedback. A weakness to `(n & 1)` vs. `n % 2 != 0` is that the first is incorrect functionality for those rusting out ones' complement machines. Still I tend to code for high portability avoiding assuming `int` encoding, width or even 8-bit bytes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:00:26.183", "Id": "408158", "Score": "0", "body": "To write code so that it is _not_ portable to non-8-bit bytes, _not_ portable to one's complement computers, _not_ supporting EBCDIC etc etc is a feature, not a limitation. Those who insist on using exotic/fictional/bad architectures can do the porting. Everyone wins, except the guy who demands that obsolete TI DSPs from early 1990s must be used in new designs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:23:55.413", "Id": "408165", "Score": "0", "body": "@Lundin Sure, non-8 bit byte and non-2's complement machines can be given little attention, yet endian, integer size, and many other implementation aspects of C's are not universal. One of C's greatest advantages is its portability to new and cutting edge architectures precisely because it does not over specify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:24:09.737", "Id": "408166", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/88009/discussion-between-chux-and-lundin)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:03:17.977", "Id": "211001", "ParentId": "210909", "Score": "2" } }, { "body": "<p>A decent compromise between readability and execution speed is this:</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n#include &lt;string.h&gt;\n\nchar* i32tostr (int32_t n, char str[32+1])\n{\n const char NIBBLE_LOOKUP[16][4] = \n {\n \"0000\", \"0001\", \"0010\", \"0011\",\n \"0100\", \"0101\", \"0110\", \"0111\",\n \"1000\", \"1001\", \"1010\", \"1011\",\n \"1100\", \"1101\", \"1110\", \"1111\",\n };\n\n char* ptr = str;\n for(uint32_t bit=32; bit&gt;0; bit-=4)\n {\n uint32_t shift = bit - 4;\n uint32_t mask = 0xFu &lt;&lt; shift;\n size_t index = (n &amp; mask) &gt;&gt; shift;\n memcpy(ptr, NIBBLE_LOOKUP[index], 4); \n ptr+=4;\n }\n *ptr = '\\0';\n\n return str;\n}\n</code></pre>\n\n<p>This reads the number 4 bits (a nibble) at a time from MSB to LSB. It masks out a nibble, then does a table look-up to get the pre-calculated string. </p>\n\n<p>As it happens, a 4 byte string can be copied in a single instruction on 32 bit computers. Note the intentional subtle detail: <code>const char NIBBLE_LOOKUP[16][4]</code> instead of <code>const char* NIBBLE_LOOKUP[16]</code>. This means that the null terminator in the string literals is <em>not</em> stored and we can't use <code>strcpy</code>. Instead we use the significantly faster <code>memcpy</code>.</p>\n\n<p>The local variables in the for loop are there for readability and don't affect performance. I could as well have written it as</p>\n\n<pre><code>for(uint32_t shift=28; shift&gt;0; shift-=4)\n{\n memcpy(ptr, NIBBLE_LOOKUP[(n &amp; 0xFu&lt;&lt;shift) &gt;&gt; shift], 4); \n ptr+=4;\n}\n</code></pre>\n\n<p>But that's much harder to read and yields exactly the same machine code anyway.</p>\n\n<p>In terms of execution speed, this should be much faster than parsing bit by bit and building up a string that way. The x86 disassembly looks pretty good; branch-free and cache-friendly: <a href=\"https://godbolt.org/z/DgJcVC\" rel=\"nofollow noreferrer\">https://godbolt.org/z/DgJcVC</a>.</p>\n\n<hr>\n\n<p>Complete example:</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n#include &lt;string.h&gt;\n\nchar* i32tostr (int32_t n, char str[32+1])\n{\n const char NIBBLE_LOOKUP[16][4] = \n {\n \"0000\", \"0001\", \"0010\", \"0011\",\n \"0100\", \"0101\", \"0110\", \"0111\",\n \"1000\", \"1001\", \"1010\", \"1011\",\n \"1100\", \"1101\", \"1110\", \"1111\",\n };\n\n char* ptr = str;\n for(uint32_t bit=32; bit&gt;0; bit-=4)\n {\n uint32_t shift = bit - 4;\n uint32_t mask = 0xFu &lt;&lt; shift;\n size_t index = (n &amp; mask) &gt;&gt; shift;\n memcpy(ptr, NIBBLE_LOOKUP[index], 4); \n ptr+=4;\n }\n *ptr = '\\0';\n\n return str;\n}\n\n#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\nint main (void)\n{\n char str[32+1];\n\n puts(i32tostr(0,str));\n puts(i32tostr(1,str));\n puts(i32tostr(-1,str));\n puts(i32tostr(INT_MIN,str));\n puts(i32tostr(INT_MAX,str));\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>00000000000000000000000000000000\n00000000000000000000000000000001\n11111111111111111111111111111111\n10000000000000000000000000000000\n01111111111111111111111111111111\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:30:56.273", "Id": "408149", "Score": "1", "body": "OP's goal involves `int`. Many attributes here focus on a 32-bit `int`. Not that that is bad, but not highly portable. In 2019 `int` is often 16-bit on many embedded processors and sometimes 64-bit on graphic ones. With that in mind, `0xFu << shift` should be more like `(uint32_t)0xFu << shift` to insure correct operation a 16-bit machine. Code uses `uint32_t` for `bit` and `shift`. Instead, code could well use `unsigned` here as forcing a type width could be counter productive. It wound be interesting how this code would be as `char* itostr (int n, char str[])` without assuming 32-bit `int`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:55:12.690", "Id": "408156", "Score": "0", "body": "@chux You could use `INT32_C(0xF)` if you prefer. But this version isn't really feasible on small microcontrollers, as 32 bit copies will be heavy lifting there, and they won't have cache memory nor branch prediction. This code is intended for modern mainstream CPUs such as x86, ARM or PowerPC. Also, using smaller legacy architectures for new system design in the year 2019 is simply bad engineering in the vast majority of cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:59:45.627", "Id": "408157", "Score": "0", "body": "Agree with most aside from implying designing for 16-bit `int/unsigned` is bad as such processors are made in the 100s of millions per year these days." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:14:39.160", "Id": "408162", "Score": "0", "body": "@chux Yeah but that's mostly because of the combination of skilled marketeers and incompetent engineers. For example, people still believe that 8-bitters are easy to use, because of some 20+ year old market hype. While the truth is that it's a pain to write C code for such legacy cores. I've been pretty much exclusively been coding for small, cramped, exotic MCU systems over the past 15 years. Nowadays, just use Cortex M, use `uint32_t` and relax. Hidden crappiness not included." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T08:39:17.837", "Id": "211083", "ParentId": "210909", "Score": "0" } } ]
{ "AcceptedAnswerId": "210912", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:56:44.700", "Id": "210909", "Score": "8", "Tags": [ "beginner", "c", "number-systems" ], "Title": "Convert decimal to binary" }
210909
<p>This is my first attempt at a jQuery plugin and really doing anything with jQuery which isn't simple DOM manipulation or initialising another plugin!</p> <p>I'm really keen to learn where I have gone wrong and improve on the code.</p> <p>The code for the plugin is:</p> <pre><code>(function($) { $.fn.unsplash = function(options, cbOnImageSelect) { var defaults = { apiRootURL: "https://api.unsplash.com", // root for API, should not need to be overridden searchTerm: '', // the search term the results will be relating to imagesToReturn: 6, // number of rows to output per page of results page: 1, // page of search results to display, will be 1 to start randomImagesToShow: 3, // number of images to display at the outset, 0 for none apiClientId: '6066a5f8e2e83faef343bdca81bd128aebccec5d601e8e27501b0f6375423477', // can be overridden for a client id per account orientation: 'landscape', // orientation of images to query for [landscape | portrait | squarish] source: '', // where the plugin is being called from cbOnImageSelect: $.noop }; images = []; totalImageCount = 0; selectedImage = {}; var settings = $.extend({}, defaults, options); //return to avoid breaking chaining return this.each(function() { //clear any content in the unsplash search $('#unsplashSearch').empty(); //add a search form $('#unsplashSearch').append('&lt;div class="in_searchBox"&gt;&lt;input type="text" name="us_searchTerm" id="us_searchTerm" value="" maxlength="50"&gt;&lt;button type="submit" name="us_SearchBtn" id="us_SearchBtn"&gt;&lt;span&gt;Search&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;'); //bind the search handler event to the button in the form $("#us_SearchBtn").bind("click", function(e) { e.preventDefault(); //reset page back to 1 to avoid a new search starting on the wrong page. settings.page = 1; //set the settings search term to the new value settings.searchTerm = $('#us_searchTerm').val(); searchAndPopulate(getSearchURL(settings.searchTerm, 1), settings.apiClientId); }); $('#unsplashSearch').append('&lt;ul id="imageList" class="horizontalList"&gt;&lt;/ul&gt;'); $('#unsplashSearch').append('&lt;div id="us_Paging" style="text-align: center;"&gt;&lt;/div&gt;'); if (settings.randomImagesToShow &gt; 0) { //build up the request url based on whether the search term is null or not... searchAndPopulate((!settings.searchTerm) ? getRandomURL(settings.randomImagesToShow) : getSearchURL(settings.searchTerm, 1), settings.apiClientId); } else { $('#us_Paging').hide(); } //private functions function callUnsplash(url) { return $.ajax({ url: url, dataType: 'json', method: 'GET', beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Client-ID ' + settings.apiClientId); xhr.setRequestHeader('Accept-Version', 'v1'); }, success: function(json) { totalImageCount = (json.hasOwnProperty('total')) ? json.total : settings.imagesToReturn; images = (json.hasOwnProperty('results')) ? json.results : json; }, error: function(xhr, status, error) { alert("Sorry, something went wrong (" + error + " " + xhr.status + " " + xhr.statusText + ")"); } }); } function searchAndPopulate(url, key) { var callUnsplashPromise = callUnsplash(url, key); callUnsplashPromise.done(populateImages); } function populateImages() { if (images.total == 0) { } else { //clear any existing images in the list $('#imageList').empty(); $.each(images, function(index, image) { var liContent = `&lt;li&gt;&lt;a href="#" class="splashImage" data-photoid="${image.id}"&gt;&lt;div class="in_max200"&gt;&lt;img src='${image.urls.thumb}' class='in_singlepic in_max200'&gt;&lt;/a&gt;&lt;/li&gt;`; $('#imageList').append(liContent); }); //bind the callback function to the splashImage so it is called when clicked. if no callback is provided, then the default will be performed $(".splashImage").bind("click", function(event) { event.preventDefault(); if (typeof settings.cbOnImageSelect == 'function') { var photoId = $(this).data('photoid'); var url = getImageURL(photoId); var getImagePromise = callUnsplash(url); getImagePromise.done(function(i) { settings.cbOnImageSelect.call(this, i); }); } }); if (totalImageCount &lt;= settings.imagesToReturn) { $('#us_Paging').hide(); } else { $('#us_Paging').empty().show(); if (totalImageCount &gt; settings.imagesToReturn) { var noOfPages = Math.ceil(totalImageCount / settings.imagesToReturn); var x = pagination(settings.page, noOfPages); for (var p = 0; p &lt; x.length; p++) { var linkText = ((x[p] !== '...') &amp;&amp; (x[p] !== settings.page)) ? '&lt;a href="##" class="us_changePage" data-page="' + x[p] + '"&gt;' + x[p] + '&lt;/a&gt;&amp;nbsp;&amp;nbsp;' : x[p] + '&amp;nbsp;&amp;nbsp;'; $('#us_Paging').append(linkText); } //add the click event to the buttons with the class us_changePage $(".us_changePage").bind("click", function(event) { event.preventDefault(); var nextPage = $(this).data('page'); settings.page = nextPage; var nextURL = getSearchURL(settings.searchTerm, nextPage); searchAndPopulate(nextURL, settings.apiClientId); }); } } } } function getSearchURL(searchTerm, pageToShow) { return settings.apiRootURL + '/search/photos?page=' + pageToShow + '&amp;per_page=' + settings.imagesToReturn + '&amp;orientation=' + settings.orientation + '&amp;query=' + searchTerm; } function getRandomURL(numberOfImages) { return settings.apiRootURL + '/photos/random?count=' + numberOfImages + '&amp;orientation=' + settings.orientation; } function getImageURL(photo_id) { return settings.apiRootURL + '/photos/' + photo_id; } function pagination(c, m) { var current = c, last = m, delta = 2, left = current - delta, right = current + delta + 1, range = [], rangeWithDots = [], l; for (var i = 1; i &lt;= last; i++) { if (i == 1 || i == last || i &gt;= left &amp;&amp; i &lt; right) { range.push(i); } } for (var i of range) { if (l) { if (i - l === 2) { rangeWithDots.push(l + 1); } else if (i - l !== 1) { rangeWithDots.push('...'); } } rangeWithDots.push(i); l = i; } return rangeWithDots; } }); }; })(jQuery); </code></pre> <p>A link to a demo on JSFiddle: <a href="https://jsfiddle.net/jaffakke/fwa7mh0d/4/" rel="nofollow noreferrer">click here</a></p> <p>Questions I have:</p> <p>Is there a better way of maintaining the returned images JSON between the Ajax request and populating the page i.e.</p> <pre><code>images = []; </code></pre> <p>Have I bound the click event handlers correctly in the plugin; i.e. </p> <pre><code>$("#us_SearchBtn").bind("click", function(e) { </code></pre> <p>Also if you have any suggestions on how to run a different callback depending on which "Choose background" link is clicked, I'd be really grateful.</p>
[]
[ { "body": "<blockquote>\n <p>Questions I have:</p>\n \n <p>Is there a better way of maintaining the returned images JSON between\n the Ajax request and populating the page i.e.</p>\n \n <p><code>images = [];</code></p>\n</blockquote>\n\n<p><code>images</code> is a value that can be removed from the global scope. The value is defined when the jQuery promise object returns a value</p>\n\n<p><code>images</code> variable is not necessary</p>\n\n<p>Define a function to handle errors</p>\n\n<pre><code> function handleError(error) {\n alert(error.message)\n }\n</code></pre>\n\n<p><code>return</code> a value from <code>callUnsplash</code></p>\n\n<pre><code> function callUnsplash(url) {\n return $.ajax({\n url: url,\n dataType: 'json',\n method: 'GET',\n beforeSend: function(xhr) {\n xhr.setRequestHeader('Authorization', 'Client-ID ' + settings.apiClientId);\n xhr.setRequestHeader('Accept-Version', 'v1');\n },\n success: function(json) {\n totalImageCount = (json.hasOwnProperty('total')) ? json.total : settings.imagesToReturn;\n // `return` value here, which will be `images` parameter at `populateImages`\n return json.hasOwnProperty('results') ? json.results : json;\n },\n error: function(xhr, status, error) {\n // throw error\n throw new Error(\"Sorry, something went wrong (\" + error + \" \" + xhr.status + \" \" + xhr.statusText + \")\");\n }\n });\n }\n</code></pre>\n\n<p><code>images</code> is value <code>return</code>ed from <code>callUnsplash()</code>. <code>$.map()</code> can be substituted for <code>$.each()</code> for ability to <code>return</code> an HTML string or jQuery object when passed as parameter to <code>.append()</code>. Concatenate HTML strings where possible instead of calling <code>.append()</code> more than once chained to more than one <code>jQuery()</code> call. Include missing closing <code>&lt;/div&gt;</code> where HTML is appended to <code>#imageList</code> unexpected results.</p>\n\n<pre><code> function populateImages(images) {\n if (images.total == 0) {} else {\n //clear any existing images in the list\n $('#imageList').empty()\n .append($.map(images, function(image, index) {\n return `&lt;li&gt;&lt;a href=\"#\" class=\"splashImage\" data-photoid=\"${image.id}\"&gt;&lt;div class=\"in_max200\"&gt;&lt;img src='${image.urls.thumb}' class='in_singlepic in_max200'&gt;&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;`\n }));\n //bind the callback function to the splashImage so it is called when clicked. if no callback is provided, then the default will be performed\n $(\".splashImage\").on(\"click\", function(event) {\n event.preventDefault();\n if (typeof settings.cbOnImageSelect == 'function') {\n var photoId = $(this).data('photoid');\n var url = getImageURL(photoId);\n // use `.then()`, handle errors\n callUnsplash(url).then(function(i) {\n settings.cbOnImageSelect.call(this, i);\n }, handleError);\n }\n });\n if (totalImageCount &lt;= settings.imagesToReturn) {\n $('#us_Paging').hide();\n } else {\n $('#us_Paging').empty().show();\n if (totalImageCount &gt; settings.imagesToReturn) {\n var noOfPages = Math.ceil(totalImageCount / settings.imagesToReturn);\n var x = pagination(settings.page, noOfPages);\n for (var p = 0; p &lt; x.length; p++) {\n var linkText = ((x[p] !== '...') &amp;&amp; (x[p] !== settings.page)) ? '&lt;a href=\"##\" class=\"us_changePage\" data-page=\"' + x[p] + '\"&gt;' + x[p] + '&lt;/a&gt;&amp;nbsp;&amp;nbsp;' : x[p] + '&amp;nbsp;&amp;nbsp;';\n $('#us_Paging').append(linkText);\n }\n //add the click event to the buttons with the class us_changePage\n $(\".us_changePage\").on(\"click\", function(event) {\n event.preventDefault();\n var nextPage = $(this).data('page');\n settings.page = nextPage;\n var nextURL = getSearchURL(settings.searchTerm, nextPage);\n searchAndPopulate(nextURL, settings.apiClientId);\n });\n }\n }\n }\n }\n</code></pre>\n\n<p>Use <code>.then()</code> instead of <code>.done()</code>. Handle errors</p>\n\n<pre><code> function searchAndPopulate(url, key) {\n callUnsplash(url, key)\n .then(populateImages, handleError);\n }\n</code></pre>\n\n<blockquote>\n <p>Have I bound the click event handlers correctly in the plugin; i.e.</p>\n \n <p><code>$(\"#us_SearchBtn\").bind(\"click\", function(e) {</code></p>\n</blockquote>\n\n<p>Substitute <code>.on()</code> for <code>.bind()</code> which is deprecated</p>\n\n<blockquote>\n <p>Also if you have any suggestions on how to run a different callback\n depending on which \"Choose background\" link is clicked, I'd be really\n grateful.</p>\n</blockquote>\n\n<p>Not certain what is meant by \"a different callback\". If a different handle for the <code>click</code> event is meant logic can be included in the function passed to <code>.on()</code> where the <code>data-photoid=\"${image.id}\"</code> of the clicked element can be evaluated to perform different tasks based on the <code>image.id</code> value. For example</p>\n\n<pre><code>if ($(this).data().photoid === \"abc\") {\n // do stuff\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function($) {\n /*\n * unsplash\n * \n * jQuery plugin to manage interaction with unsplash API\n * \n *\n */\n $.fn.unsplash = function(options, cbOnImageSelect) {\n // defaults for the plugin, client ID can be provided on a init by init basis so that each client can have their own CLIENTID and therefore won't count towards\n // a common limit\n var defaults = {\n apiRootURL: \"https://api.unsplash.com\", // root for API, should not need to be overridden \n searchTerm: '', // the search term the results will be relating to\n imagesToReturn: 6, // number of rows to output per page of results\n page: 1, // page of search results to display, will be 1 to start\n randomImagesToShow: 3, // number of images to display at the outset, 0 for none\n apiClientId: '9371fe014143706ce089532bc0149f75e5672f1a07acdd1599d42461c73e0707', // can be overridden for a client id per account\n orientation: 'landscape', // orientation of images to query for [landscape | portrait | squarish]\n source: '', // where the plugin is being called from\n cbOnImageSelect: $.noop\n };\n\n // images = [];\n var totalImageCount = 0;\n var selectedImage = {};\n\n function handleError(error) {\n alert(error.message)\n }\n\n var settings = $.extend({}, defaults, options);\n\n //return to avoid breaking chaining\n return this.each(function() {\n //clear any content in the unsplash search\n $('#unsplashSearch').empty()\n //add a search form\n .append('&lt;div class=\"in_searchBox\"&gt;&lt;input type=\"text\" name=\"us_searchTerm\" id=\"us_searchTerm\" value=\"\" maxlength=\"50\"&gt;&lt;button type=\"submit\" name=\"us_SearchBtn\" id=\"us_SearchBtn\"&gt;&lt;span&gt;Search&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;');\n //bind the search handler event to the button in the form\n $(\"#us_SearchBtn\").on(\"click\", function(e) {\n e.preventDefault();\n //reset page back to 1 to avoid a new search starting on the wrong page.\n settings.page = 1;\n //set the settings search term to the new value\n settings.searchTerm = $('#us_searchTerm').val();\n searchAndPopulate(getSearchURL(settings.searchTerm, 1), settings.apiClientId);\n });\n $('#unsplashSearch').append('&lt;ul id=\"imageList\" class=\"horizontalList\"&gt;&lt;/ul&gt;' +\n '&lt;div id=\"us_Paging\" style=\"text-align: center;\"&gt;&lt;/div&gt;');\n if (settings.randomImagesToShow &gt; 0) {\n //build up the request url based on whether the search term is null or not...\n searchAndPopulate((!settings.searchTerm) ? getRandomURL(settings.randomImagesToShow) : getSearchURL(settings.searchTerm, 1), settings.apiClientId);\n } else {\n $('#us_Paging').hide();\n }\n\n //private functions\n function callUnsplash(url) {\n return $.ajax({\n url: url,\n dataType: 'json',\n method: 'GET',\n beforeSend: function(xhr) {\n xhr.setRequestHeader('Authorization', 'Client-ID ' + settings.apiClientId);\n xhr.setRequestHeader('Accept-Version', 'v1');\n },\n success: function(json) {\n totalImageCount = (json.hasOwnProperty('total')) ? json.total : settings.imagesToReturn;\n return json.hasOwnProperty('results') ? json.results : json;\n },\n error: function(xhr, status, error) {\n throw new Error(\"Sorry, something went wrong (\" + error + \" \" + xhr.status + \" \" + xhr.statusText + \")\");\n }\n });\n }\n\n function searchAndPopulate(url, key) {\n callUnsplash(url, key)\n .then(populateImages, handleError);\n }\n\n function populateImages(images) {\n if (images.total == 0) {} else {\n //clear any existing images in the list\n $('#imageList').empty()\n .append($.map(images, function(image, index) {\n return `&lt;li&gt;&lt;a href=\"#\" class=\"splashImage\" data-photoid=\"${image.id}\"&gt;&lt;div class=\"in_max200\"&gt;&lt;img src='${image.urls.thumb}' class='in_singlepic in_max200'&gt;&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;`;\n }));\n //bind the callback function to the splashImage so it is called when clicked. if no callback is provided, then the default will be performed\n $(\".splashImage\").on(\"click\", function(event) {\n event.preventDefault();\n if (typeof settings.cbOnImageSelect == 'function') {\n var photoId = $(this).data('photoid');\n var url = getImageURL(photoId);\n callUnsplash(url).then(function(i) {\n settings.cbOnImageSelect.call(this, i);\n }, handleError);\n }\n });\n if (totalImageCount &lt;= settings.imagesToReturn) {\n $('#us_Paging').hide();\n } else {\n $('#us_Paging').empty().show();\n if (totalImageCount &gt; settings.imagesToReturn) {\n var noOfPages = Math.ceil(totalImageCount / settings.imagesToReturn);\n var x = pagination(settings.page, noOfPages);\n for (var p = 0; p &lt; x.length; p++) {\n var linkText = ((x[p] !== '...') &amp;&amp; (x[p] !== settings.page)) ? '&lt;a href=\"##\" class=\"us_changePage\" data-page=\"' + x[p] + '\"&gt;' + x[p] + '&lt;/a&gt;&amp;nbsp;&amp;nbsp;' : x[p] + '&amp;nbsp;&amp;nbsp;';\n $('#us_Paging').append(linkText);\n }\n //add the click event to the buttons with the class us_changePage\n $(\".us_changePage\").on(\"click\", function(event) {\n event.preventDefault();\n var nextPage = $(this).data('page');\n settings.page = nextPage;\n var nextURL = getSearchURL(settings.searchTerm, nextPage);\n searchAndPopulate(nextURL, settings.apiClientId);\n });\n }\n }\n }\n }\n\n function getSearchURL(searchTerm, pageToShow) {\n return settings.apiRootURL + '/search/photos?page=' + pageToShow + '&amp;per_page=' + settings.imagesToReturn + '&amp;orientation=' + settings.orientation + '&amp;query=' + searchTerm;\n }\n\n function getRandomURL(numberOfImages) {\n return settings.apiRootURL + '/photos/random?count=' + numberOfImages + '&amp;orientation=' + settings.orientation;\n }\n\n function getImageURL(photo_id) {\n return settings.apiRootURL + '/photos/' + photo_id;\n }\n\n function pagination(c, m) {\n var current = c,\n last = m,\n delta = 2,\n left = current - delta,\n right = current + delta + 1,\n range = [],\n rangeWithDots = [],\n l;\n for (var i = 1; i &lt;= last; i++) {\n if (i == 1 || i == last || i &gt;= left &amp;&amp; i &lt; right) {\n range.push(i);\n }\n }\n for (var i of range) {\n if (l) {\n if (i - l === 2) {\n rangeWithDots.push(l + 1);\n } else if (i - l !== 1) {\n rangeWithDots.push('...');\n }\n }\n rangeWithDots.push(i);\n l = i;\n }\n return rangeWithDots;\n }\n });\n };\n})(jQuery);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://jsfiddle.net/fwa7mh0d/6/\" rel=\"nofollow noreferrer\">jsfiddle</a> </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:22:14.347", "Id": "407952", "Score": "0", "body": "Thanks for the comments; when I say a different callback, I mean if you clicked on choose image on widget 1 and selecting an image it would run a different callback from clicking on choose image on widget 3 and selecting an image - even if all the chooseImage links were initialised with a single unsplash() call. So I guess putting the callback as a data attribute on the choose image link and using eval(). Is that bad practice and if so, is there a better way? thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:27:50.207", "Id": "408000", "Score": "0", "body": "@j4ffa By callback are you referring to the function set at `cbOnImageSelect`? `eval()` is not necessary." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T05:08:49.370", "Id": "211009", "ParentId": "210910", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T21:59:52.703", "Id": "210910", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Unsplash jQuery plugin with callback functionality" }
210910
<p>My solution to <a href="https://leetcode.com/articles/max-stack/" rel="nofollow noreferrer">Leetcode MaxStack in python</a> in Python. I have two solution one is using linked-list and another one is using list.</p> <blockquote> <p>Design a max stack that supports push, pop, top, peekMax and popMax.</p> <p><code>push(x)</code> -- Push element x onto stack.<br> <code>pop()</code> -- Remove the element on top of the stack and return it.<br> <code>top()</code> -- Get the element on the top.<br> <code>peekMax()</code> -- Retrieve the maximum element in the stack.<br> <code>popMax()</code> -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.</p> </blockquote> <p>Using list:</p> <pre><code>class MaxStack_list: def __init__(self): &quot;&quot;&quot; Initialize your data structure here. &quot;&quot;&quot; self.head = [] self.max_val = None def push(self, x): &quot;&quot;&quot; Push element x onto stack. :type x: int :rtype: void &quot;&quot;&quot; self.head.append(x) self.max_val = max(max(self.head), x) def pop(self): &quot;&quot;&quot; Removes the element on top of the stack and returns that element. :rtype: int &quot;&quot;&quot; self.head.pop() self.max_val = max(self.head) def top(self): &quot;&quot;&quot; Get the top element. :rtype: int &quot;&quot;&quot; return self.head[-1] if self.head else None def peekMax(self): &quot;&quot;&quot; Retrieve the maximum element in the stack. :rtype: int &quot;&quot;&quot; return self.max_val def popMax(self): &quot;&quot;&quot; Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. :rtype: void &quot;&quot;&quot; v = self.max_val self.head.remove(self.max_val) self.max_val = max(self.head) return v </code></pre> <p>Using LinkedList</p> <pre><code>class Node: def __init__(self, x): self.val = x self.next = None class MaxStack: def __init__(self): &quot;&quot;&quot; Initialize your data structure here. &quot;&quot;&quot; self.head = None self.max_val = None def push(self, x): &quot;&quot;&quot; Push element x onto stack. :type x: int :rtype: void &quot;&quot;&quot; if self.head: n = Node(x) n.next = self.head self.head = n else: self.head = Node(x) self.max_val = max(x, self.max_val) if self.max_val or self.max_val == 0 else x def pop(self): &quot;&quot;&quot; Removes the element on top of the stack and returns that element. :rtype: int &quot;&quot;&quot; rtn = None if self.head: rtn = self.head.val self.head = self.head.next head = self.head v = head.val if head else None while head: v = max(v, head.val) head = head.next self.max_val = v return rtn def top(self): &quot;&quot;&quot; Get the top element. :rtype: int &quot;&quot;&quot; if self.head: return self.head.val def peekMax(self): &quot;&quot;&quot; Retrieve the maximum element in the stack. :rtype: int &quot;&quot;&quot; return self.max_val def popMax(self): &quot;&quot;&quot; Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. :rtype: void &quot;&quot;&quot; prev, cur = None, self.head while cur: if cur.val == self.max_val and cur == self.head: self.head = cur.next break elif cur.val == self.max_val: prev.next = cur.next break prev, cur = cur, cur.next cur = self.head tmp = self.max_val v = cur.val if cur else None while cur: if cur: v = max(v, cur.val) cur = cur.next self.max_val = v return tmp </code></pre>
[]
[ { "body": "<p>The return type for <code>popMax</code> should be <code>int</code> not <code>void</code>. </p>\n\n<p>When you push a new item, your max can only increase above the current maximum. So instead of </p>\n\n<pre><code>self.max_val = max(max(self.head), x)\n</code></pre>\n\n<p>which is <span class=\"math-container\">\\$O(n)\\$</span>, you should have</p>\n\n<pre><code>self.max_val = max(self.max_val, x)\n</code></pre>\n\n<p>which is <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n\n<p>The<code>if self.max_val or self.max_val == 0</code> condition is better written as <code>if self.max_val is not None</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T02:40:43.190", "Id": "210925", "ParentId": "210914", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T22:46:55.667", "Id": "210914", "Score": "4", "Tags": [ "python", "python-3.x", "linked-list" ], "Title": "Leetcode MaxStack in Python" }
210914
<p>I solved <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/" rel="nofollow noreferrer">this problem</a>:</p> <blockquote> <p>Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.</p> </blockquote> <p>How can I improve its execution time? Is there any better way of doing it?</p> <pre><code>public int removeDuplicates(int[] numbers) { if(numbers.length == 0 || numbers.length == 1) { return numbers.length; } int indexForUniqueElements = 0; for (int index = 0; index &lt; numbers.length - 1; index++) { if (numbers[index] != numbers[index+1]) { numbers[indexForUniqueElements++] = numbers[index]; } } numbers[indexForUniqueElements++] = numbers[numbers.length - 1]; return indexForUniqueElements; } </code></pre>
[]
[ { "body": "<p>Your test <code>numbers.length == 0 || numbers.length == 1</code> could be simplified as <code>numbers.length &lt; 2</code>.</p>\n\n<p>Multiple <code>return</code> statement should be avoided. You could set <code>indexForUniqueElements</code> to <code>numbers.length</code> when less than 2, and use just one return statement at the end.</p>\n\n<p>You are reading each element from the <code>numbers[index]</code> array multiple times. Once in the duplicate test as the lhs, once in the duplicate test as the rhs, and possibly a third time to copy it into its new location. You could read the number once, into a local variable, and then reference the local variable. An enhanced <code>for</code> loop will do this for you, but you'd lose the index, which you use for testing against <code>numbers[index+1]</code>. You could instead test against the last value you read (cached in a local variable), and then you'd be free to use the enhanced for loop. The only difficultly is how to handle the first value, which has no previous. This can be trivially handled by using the first value in the array as the last value, and starting the fill-in index at 1.</p>\n\n<p>Here is a simple implementation of the above. Each element of the <code>numbers[]</code> array is read from only once, apart from the first element (which is read twice):</p>\n\n<pre><code>public int removeDuplicates(int[] numbers) {\n int idx = 0;\n if (numbers.length &gt; 0) {\n int last = numbers[idx++];\n for (int number : numbers)\n if (number != last)\n last = numbers[idx++] = number;\n }\n return idx;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T23:48:19.993", "Id": "210917", "ParentId": "210916", "Score": "0" } }, { "body": "<p>I don't see any way to greatly increase performance since your algorithm is already O(n).</p>\n\n<p>However, there is a minor optimization that can be made. You should try to avoid having a calculation as the limit in a for loop. This gets calculated on each iteration of the loop. Initialize a variable with the result and use that instead:</p>\n\n<pre><code>public int removeDuplicates(int[] numbers) {\n if(numbers.length == 0 || numbers.length == 1) {\n return numbers.length;\n }\n int indexForUniqueElements = 0;\n int limit = numbers.length - 1;\n for (int index = 0; index &lt; limit; index++) {\n if (numbers[index] != numbers[index+1]) {\n numbers[indexForUniqueElements++] = numbers[index];\n }\n }\n numbers[indexForUniqueElements++] = numbers[numbers.length - 1];\n return indexForUniqueElements;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T23:48:55.193", "Id": "210918", "ParentId": "210916", "Score": "2" } }, { "body": "<blockquote>\n<pre><code> if(numbers.length == 0 || numbers.length == 1) {\n</code></pre>\n</blockquote>\n\n<p>Could be </p>\n\n<pre><code> if (numbers.length &lt;= 1) {\n</code></pre>\n\n<p>Trivial time improvement (perhaps none; the compiler may optimize the original). Mostly preferable for simplicity's sake. </p>\n\n<blockquote>\n<pre><code> int indexForUniqueElements = 0;\n for (int index = 0; index &lt; numbers.length - 1; index++) {\n if (numbers[index] != numbers[index+1]) {\n numbers[indexForUniqueElements++] = numbers[index];\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This is more problematic. What happens if the elements of the array are already unique? You'll copy the entire array for no reason. Consider breaking this up into two loops. </p>\n\n<pre><code> int uniqueCount = 1;\n while (uniqueCount &lt; numbers.length &amp;&amp; numbers[uniqueCount - 1] != numbers[uniqueCount]) {\n uniqueCount++;\n }\n\n for (int index = uniqueCount + 1; index &lt; numbers.length; index++) {\n if (numbers[index - 1] != numbers[index]) {\n numbers[uniqueCount] = numbers[index];\n uniqueCount++;\n }\n }\n</code></pre>\n\n<p>Now, we skim over all the unique numbers. Once we find the first duplicate, we stop. The earliest that duplicate can be is position 1. Because there are no numbers before that to duplicate. We don't have to copy any of these numbers, as they are already in the array. </p>\n\n<p>The second loop copies subsequent unique numbers over top the duplicates and numbers out of order. If there are no duplicates (the first loop skimmed the entire array), then the second loop won't run at all. </p>\n\n<p>I changed the name to <code>uniqueCount</code> because I found it more descriptive of what the variable holds. At any moment, it tells us how many known unique elements are in the array. By contrast, I don't really know what an <code>indexForUniqueElements</code> is. I figured it out, but with <code>uniqueCount</code>, I don't need to do so. </p>\n\n<p>I moved the increment of <code>uniqueCount</code> in the second loop to its own line for readability. </p>\n\n<p>This saves the extra assignment at the end of your loop. Your loop is trying to copy the number at the lower index of the comparison. My loop assumes that they are already in the right place. It copies the number at the higher index. Another trivial improvement (sometimes this will not do an assignment at the end when your original code would have). </p>\n\n<p>This approach will not change the asymptotic performance. It's still <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. But it may make the program run faster, as it saves copying values that are already in the right place. And copying is an expensive operation. </p>\n\n<p>The only way to make a significant improvement from here would be to include the duplicate check with the sort. I.e. remove duplicates as you sort. But if you don't have control over the sort, there is no way that you can do that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T05:55:29.187", "Id": "210927", "ParentId": "210916", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T23:07:03.517", "Id": "210916", "Score": "1", "Tags": [ "java", "performance", "programming-challenge" ], "Title": "Remove duplicates from sorted array, in place" }
210916
<p><strong>Problem</strong> </p> <p>Spreadsheet cells are referenced by column and row identifiers. Columns are labeled with alphabetical characters, starting with "A", "B", "C", ...; rows are numbered from 1 in ascending order. Write a function that takes in a string identifying a range of cells in a spreadsheet and returns an ordered list of cells which compose that range.</p> <p>Example:</p> <pre><code>"A3:D5" -&gt; ["A3", "A4", "A5", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4", "D5"] "A3:D4" -&gt; ["A3", "A4", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4"] </code></pre> <p>Here is scala implementation of the same , </p> <pre><code>import scala.language.postfixOps object PrintSpreadSheet extends App { val validAlphabets = ('A' to 'Z').toSeq def cells(range: String): Seq[String] = { val corners = (range split ":") flatMap { corner =&gt; Seq(corner.head, corner.last) } val rows = (corners filter (r =&gt; validAlphabets.contains(r))) sorted val cols = (corners filter (c =&gt; !validAlphabets.contains(c))) sorted (rows.head to rows.last) flatMap { r =&gt; (cols.head to cols.last) map { c =&gt; r.toString + ":" + c.toString } } } cells("A1:D5") foreach println } </code></pre>
[]
[ { "body": "<p>I couldn't get your code to compile until I took out the <code>sorted</code>. The output was still good so I don't know what purpose it was supposed to serve.</p>\n\n<p>There's no point in casting <code>validAlphabets</code> to a <code>Seq[Char]</code>. As a <code>Range[Char]</code> the <code>contains()</code> method still works. Better still would be to cast it to a <code>Set[Char]</code>. Then the syntax is more concise and the lookup is faster.</p>\n\n<pre><code>val rows = corners filter validAlphabets\nval cols = corners filter (!validAlphabets(_))\n</code></pre>\n\n<p>Due to the use of <code>.head</code> and <code>.last</code>, this solution won't handle rows past <code>9</code>. There are also a number of input errors that it won't catch. These can be addressed if you use a Regex to parse the input.</p>\n\n<pre><code>def cells(range: String): Seq[String] = {\n val format = \"([A-Z])(\\\\d+):([A-Z])(\\\\d+)\".r\n val format(colStart, rowStart, colEnd, rowEnd) = range\n\n for {\n c &lt;- colStart.head to colEnd.head //from String to Char\n r &lt;- rowStart.toInt to rowEnd.toInt //from String to Int\n } yield s\"$c:$r\" //back to String\n}\n</code></pre>\n\n<p>This will throw if the input string doesn't match the expected format. If you'd prefer it print the error and return nothing (an empty <code>Seq[String]</code>) then you can use a <code>match</code> statement instead, with a default <code>case _ =&gt;</code> for the format failure.</p>\n\n<p>Notice that I use a <code>for</code> comprehension here. Whenever you see a <code>map()</code> inside a <code>flatMap()</code> that's a flag indicating that a <code>for</code> might do the same thing in a clearer/cleaner manner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T05:30:31.823", "Id": "407754", "Score": "0", "body": "Code is compiling for me, here is same code in a online compiler https://scastie.scala-lang.org/eQxRuAvfR9qgCwNMiapGmg \n\nAlso sorted is needed to handle input like \"D5:A1\" , else it will return empty seq. without sorted version - https://scastie.scala-lang.org/fD8FBWMDRRyzdvPvv4bazg\n\nI thought about using regex and agree it makes validation straightforward. But I am not very comfortable in writing regex (specially in an interview), learning it. \n\nHow about working with Strings and using some thing like this -\n\nscala> (\"A233\" take 1, \"A233\" drop 1)\nres92: (String, String) = (A,233)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T05:34:51.680", "Id": "407755", "Score": "0", "body": "But I do agree regex is best and I should learn it. It makes it super simple. \nI accept it as a answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T02:06:29.130", "Id": "210924", "ParentId": "210920", "Score": "1" } }, { "body": "<p>You're failing to handle columns beyond column Z (which should be AA) and rows beyond row 9. Your variable naming is also reversed: the columns are designated using letters and the rows are designated using numbers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T08:00:19.373", "Id": "210929", "ParentId": "210920", "Score": "0" } } ]
{ "AcceptedAnswerId": "210924", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T23:53:17.437", "Id": "210920", "Score": "0", "Tags": [ "interview-questions", "functional-programming", "scala" ], "Title": "Expand spreadsheet ranges to lists of cells in Scala" }
210920
<p>I started writing some of the standard algorithms for tuples, here are the first few non-modifying ones</p> <pre><code>#include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;optional&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; template &lt;typename Predicate, typename Tuple&gt; constexpr bool all_of(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { return std::apply( [&amp;](auto&amp;&amp;... xs) constexpr noexcept { return (... &amp;&amp; pred(std::forward&lt;decltype(xs)&gt;(xs))); }, std::forward&lt;decltype(t)&gt;(t)); } template &lt;typename Predicate, typename Tuple&gt; constexpr bool any_of(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { return std::apply( [&amp;](auto&amp;&amp;... xs) constexpr noexcept { return (... || pred(std::forward&lt;decltype(xs)&gt;(xs))); }, std::forward&lt;decltype(t)&gt;(t)); } template &lt;typename Predicate, typename Tuple&gt; constexpr bool none_of(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { return std::apply( [&amp;](auto&amp;&amp;... xs) constexpr noexcept { return !(... || pred(std::forward&lt;decltype(xs)&gt;(xs))); }, std::forward&lt;decltype(t)&gt;(t)); } template &lt;typename Predicate, typename Tuple&gt; constexpr void for_each(Predicate&amp;&amp; f, Tuple&amp;&amp; t) noexcept { return std::apply( [&amp;](auto&amp;&amp;... xs) constexpr noexcept { (..., f(std::forward&lt;decltype(xs)&gt;(xs))); }, std::forward&lt;decltype(t)&gt;(t)); } template &lt;typename Predicate, typename Tuple, std::size_t... Is&gt; constexpr void for_each_n_impl(Predicate&amp;&amp; f, Tuple&amp;&amp; t, std::index_sequence&lt;Is...&gt;) noexcept { return (..., f(std::get&lt;Is&gt;(t))); } template &lt;std::size_t N, typename Predicate, typename Tuple&gt; constexpr void for_each_n(Predicate&amp;&amp; f, Tuple&amp;&amp; t) noexcept { static_assert(N &lt;= std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt;); return for_each_n_impl(std::forward&lt;decltype(f)&gt;(f), std::forward&lt;decltype(t)&gt;(t), std::make_index_sequence&lt;N&gt;()); } template &lt;typename Tuple, typename T&gt; constexpr std::size_t count(Tuple&amp;&amp; t, const T&amp; value) noexcept { return std::apply( [&amp;](auto&amp;&amp;... xs) constexpr noexcept { return (0u + ... + static_cast&lt;std::size_t&gt;(value == xs)); }, std::forward&lt;decltype(t)&gt;(t)); } template &lt;typename Predicate, typename Tuple&gt; constexpr std::size_t count_if(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { return std::apply( [&amp;](auto&amp;&amp;... xs) constexpr noexcept { return (0u + ... + static_cast&lt;std::size_t&gt;(pred(std::forward&lt;decltype(xs)&gt;(xs)))); }, std::forward&lt;decltype(t)&gt;(t)); } template &lt;std::size_t N, typename TupleZero, typename TupleOne&gt; constexpr std::optional&lt;std::size_t&gt; mismatch_impl(TupleZero&amp;&amp; t0, TupleOne&amp;&amp; t1) noexcept { constexpr std::size_t I = std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt; - N; if constexpr (N == 0u) { return std::nullopt; } else { return std::get&lt;I&gt;(t0) == std::get&lt;I&gt;(t1) ? mismatch_impl&lt;N - 1u&gt;(std::forward&lt;decltype(t0)&gt;(t0), std::forward&lt;decltype(t1)&gt;(t1)) : std::make_optional(I); } } template &lt;std::size_t N, typename Predicate, typename TupleZero, typename TupleOne&gt; constexpr std::optional&lt;std::size_t&gt; mismatch_impl(Predicate&amp;&amp; pred, TupleZero&amp;&amp; t0, TupleOne&amp;&amp; t1) noexcept { constexpr std::size_t I = std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt; - N; if constexpr (N == 0u) { return std::nullopt; } else { return pred(std::get&lt;I&gt;(t0), std::get&lt;I&gt;(t1)) ? mismatch_impl&lt;N - 1u&gt;(std::forward&lt;decltype(pred)&gt;(pred), std::forward&lt;decltype(t0)&gt;(t0), std::forward&lt;decltype(t1)&gt;(t1)) : std::make_optional(I); } } template &lt;typename TupleZero, typename TupleOne&gt; constexpr std::optional&lt;std::size_t&gt; mismatch(TupleZero&amp;&amp; t0, TupleOne&amp;&amp; t1) noexcept { static_assert(std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt; &lt;= std::tuple_size_v&lt;std::decay_t&lt;decltype(t1)&gt;&gt;); return mismatch_impl&lt;std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt;&gt;( std::forward&lt;decltype(t0)&gt;(t0), std::forward&lt;decltype(t1)&gt;(t1)); } template &lt;typename Predicate, typename TupleZero, typename TupleOne&gt; constexpr std::optional&lt;std::size_t&gt; mismatch(Predicate&amp;&amp; pred, TupleZero&amp;&amp; t0, TupleOne&amp;&amp; t1) noexcept { static_assert(std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt; &lt;= std::tuple_size_v&lt;std::decay_t&lt;decltype(t1)&gt;&gt;); return mismatch_impl&lt;std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt;&gt;( std::forward&lt;decltype(pred)&gt;(pred), std::forward&lt;decltype(t0)&gt;(t0), std::forward&lt;decltype(t1)&gt;(t1)); } template &lt;std::size_t N, typename Tuple, typename T&gt; constexpr std::optional&lt;std::size_t&gt; find_impl(Tuple&amp;&amp; t, const T&amp; value) noexcept { constexpr std::size_t I = std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt; - N; if constexpr (N == 0u) { return std::nullopt; } else { return std::get&lt;I&gt;(t) == value ? std::make_optional(I) : find_impl&lt;N - 1u&gt;(std::forward&lt;decltype(t)&gt;(t), value); } } template &lt;typename Tuple, typename T&gt; constexpr std::optional&lt;std::size_t&gt; find(Tuple&amp;&amp; t, const T&amp; value) noexcept { return find_impl&lt;std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt;&gt;( std::forward&lt;decltype(t)&gt;(t), value); } template &lt;std::size_t N, typename Predicate, typename Tuple&gt; constexpr std::optional&lt;std::size_t&gt; find_if_impl(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { constexpr std::size_t I = std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt; - N; if constexpr (N == 0u) { return std::nullopt; } else { return pred(std::get&lt;I&gt;(t)) ? std::make_optional(I) : find_if_impl&lt;N - 1u&gt;(std::forward&lt;decltype(pred)&gt;(pred), std::forward&lt;decltype(t)&gt;(t)); } } template &lt;typename Predicate, typename Tuple&gt; constexpr std::optional&lt;std::size_t&gt; find_if(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { return find_if_impl&lt;std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt;&gt;( std::forward&lt;decltype(pred)&gt;(pred), std::forward&lt;decltype(t)&gt;(t)); } template &lt;std::size_t N, typename Predicate, typename Tuple&gt; constexpr std::optional&lt;std::size_t&gt; find_if_not_impl(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { constexpr std::size_t I = std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt; - N; if constexpr (N == 0u) { return std::nullopt; } else { return pred(std::get&lt;I&gt;(t)) ? find_if_not_impl&lt;N - 1u&gt;(std::forward&lt;decltype(pred)&gt;(pred), std::forward&lt;decltype(t)&gt;(t)) : std::make_optional(I); } } template &lt;typename Predicate, typename Tuple&gt; constexpr std::optional&lt;std::size_t&gt; find_if_not(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept { return find_if_not_impl&lt;std::tuple_size_v&lt;std::decay_t&lt;decltype(t)&gt;&gt;&gt;( std::forward&lt;decltype(pred)&gt;(pred), std::forward&lt;decltype(t)&gt;(t)); } </code></pre> <p>Some tests: </p> <pre><code>auto print = [](auto x) { std::cout &lt;&lt; x &lt;&lt; '\n'; }; constexpr auto id = [](auto x) constexpr noexcept { return x; }; int main() { static_assert(all_of(id, std::make_tuple(true, true, true)), "assert 0"); static_assert(any_of(id, std::make_tuple(false, false, true)), "assert 1"); static_assert(none_of(id, std::make_tuple(false, false, false)), "assert 2"); for_each(print, std::make_tuple(1, 2, 3)); for_each_n&lt;2u&gt;(print, std::make_tuple(1, 2, 3)); static_assert(count(std::make_tuple(true, true, true), true) == 3u, "assert 3"); static_assert(count_if(id, std::make_tuple(false, false, false)) == 0u, "assert 4"); static_assert( mismatch(std::make_tuple(1, 2, 3), std::make_tuple(1, 3, 3)).value() == 1u, "assert 5"); static_assert(mismatch(std::equal_to&lt;int&gt;{}, std::make_tuple(1, 2, 3), std::make_tuple(1, 2, 4)) .value() == 2u, "assert 6"); static_assert(find(std::make_tuple(1, 2, 3), 3).value() == 2u, "assert 7"); static_assert(find_if([](auto x) constexpr noexcept { return x == 2; }, std::make_tuple(1, 2, 3)) .value() == 1u, "assert 8"); static_assert(find_if_not([](auto x) constexpr noexcept { return x != 1; }, std::make_tuple(1, 2, 3)) .value() == 0u, "assert 9"); } </code></pre> <p>Instead of iterators to the elements in a sequence, optional index values are returned based on whether or not the tuple elements satisfied the criteria. I'd like some feedback on the implementation, in particular I was wondering if there is a way around that ugly "impl"-pattern (namespaces are one option). I am also not checking whether or not tuple element types posses different operators, e.g. equality, which can lead to some nasty errors. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T14:50:53.170", "Id": "407766", "Score": "0", "body": "maybe returning the element itself would be better, cause you can't access a tuple without a compile time constant ( at least not with some hackery )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T09:15:39.897", "Id": "407932", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question instead." } ]
[ { "body": "<p>Looks good to me!</p>\n\n<p>I'm pretty sure you don't need the <code>constexpr noexcept</code> clutter on all your lambdas: lambdas are <em>at least</em> <code>constexpr(auto)</code> and I think also <code>noexcept(auto)</code>.</p>\n\n<p>It is surprising, but I think technically reasonable, for you to take <code>Pred&amp;&amp; pred</code> by forwarding reference and then <em>not</em> forward it when you call it. This means that you can take either const or non-const predicates (always by reference), and call them with the appropriate constness, but always as an lvalue. Personally I would probably take <code>const Pred&amp; pred</code> and screw anyone trying to pass in a mutable lambda; or take <code>Pred pred</code> and screw anyone trying to pass in an expensive-to-copy lambda without <code>std::ref</code>. Your way seems better, with the only downside being that it <em>looks</em> like a misuse of perfect forwarding until the reader studies it really hard. Perhaps a block comment is in order.</p>\n\n<hr>\n\n<p>I can technically break your <code>count</code> by passing in types whose <code>operator==</code> returns a type which is <code>BooleanLike</code> but happens to have a wacky conversion to <code>size_t</code>. It would be better for you to explicitly cast the result of <code>value == xs</code> to <code>bool</code> before doing anything else with it:</p>\n\n<pre><code>template&lt;class Tuple, class T&gt;\nconstexpr size_t count(Tuple&amp;&amp; t, const T&amp; value) noexcept {\n return std::apply(\n [&amp;](auto&amp;&amp;... xs) {\n return (0 + ... + size_t(bool(value == xs)));\n },\n std::forward&lt;decltype(t)&gt;(t));\n}\n</code></pre>\n\n<p>Stylistically I think your <code>0u</code> was unnecessarily confusing: If you just mean \"zero\" and don't care about the type, then <code>0</code> is fine. If you're trying to avoid surprising implicit type-conversions and do all the math in <code>size_t</code>, then <code>size_t(0)</code> would be best.</p>\n\n<hr>\n\n<p>It's interesting that your <code>mismatch</code> is the <em>one</em> function you didn't do with either <code>std::apply</code> or fold-expressions.</p>\n\n<p>You seem to have forgotten that <code>std::forward&lt;T&gt;(t)</code> is the more common way to write <code>std::forward&lt;decltype(t)&gt;(t)</code> when <code>T</code> is known.</p>\n\n<pre><code>template &lt;typename TupleZero, typename TupleOne&gt;\nconstexpr std::optional&lt;std::size_t&gt; mismatch(TupleZero&amp;&amp; t0,\n TupleOne&amp;&amp; t1) noexcept {\n static_assert(std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt; &lt;=\n std::tuple_size_v&lt;std::decay_t&lt;decltype(t1)&gt;&gt;);\n return mismatch_impl&lt;std::tuple_size_v&lt;std::decay_t&lt;decltype(t0)&gt;&gt;&gt;(\n std::forward&lt;decltype(t0)&gt;(t0), std::forward&lt;decltype(t1)&gt;(t1));\n}\n</code></pre>\n\n<p>I would write this as:</p>\n\n<pre><code>template&lt;class T0, class T1&gt;\nconstexpr std::optional&lt;size_t&gt; mismatch(T0&amp;&amp; t0, T1&amp;&amp; t1) noexcept {\n constexpr size_t N = std::tuple_size_v&lt;std::decay_t&lt;T0&gt;&gt;;\n static_assert(N &lt;= std::tuple_size_v&lt;std::decay_t&lt;T1&gt;&gt;);\n return mismatch_impl&lt;N&gt;(std::forward&lt;T0&gt;(t0), std::forward&lt;T1&gt;(t1));\n}\n</code></pre>\n\n<p>And I would maybe look for a way to write it in terms of</p>\n\n<pre><code>size_t result = 0;\nFOREACH...(\n [&amp;]() {\n if (result == 0)\n if (std::get&lt;Is&gt;(t0) == std::get&lt;Is&gt;(t1))\n result = I + 1;\n }() ...\n)\nif (result != 0) {\n return result - 1;\n}\nreturn std::nullopt;\n</code></pre>\n\n<p>instead of the recursion you've got. But the <code>FOREACH...</code> part would have to use a helper function anyway to generate the <code>Is</code>; I don't think there's any way to coerce <code>std::apply</code> to do what you want here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:02:53.900", "Id": "407804", "Score": "1", "body": "Yes to `constexpr(auto)`, unfortunately no for `noexcept(auto)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:57:43.920", "Id": "407809", "Score": "0", "body": "Actually, `0u` is more robust than simple `0`: `std::size_t` is not guaranteed to rank above `int`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T12:21:07.403", "Id": "407836", "Score": "0", "body": "did not know that about lambdas, thanks! your point on breaking my count function is plausible, I made a type_trait for checking that a while ago https://codereview.stackexchange.com/questions/165856/type-trait-for-checking-whether-or-not-2-types-are-nothrow-comparable-to-each and I am going to try to implement your other ideas" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T20:19:31.820", "Id": "210945", "ParentId": "210934", "Score": "5" } }, { "body": "<p>Well, it's workable. There are just a few things:</p>\n\n<ol>\n<li><p>You mark most of your functions unconditionally <code>noexcept</code>. Woe befall anyone passing a callable which might throw. Or if comparing does so. Yes, fixing that is tedious if you don't use an evil macro.</p></li>\n<li><p>You should be aware that predicates are generally allowed to return anything they want, as long as it can be contextually converted to <code>bool</code>. Unless you like brittle code, when you don't use a construct doing that contextual conversion, do an explicit cast.</p></li>\n<li><p>One uses <code>decltype(t)</code> for forwarding in lambdas for a simple reason: The argument-type doesn't have a known name yet. If it has a simple name, that's doing things the hard way.</p></li>\n<li><p>You don't leverage your own functions to implement the rest. Some examples for inspiration:</p>\n\n<pre><code>template &lt;typename Predicate, typename Tuple&gt;\nconstexpr bool none_of(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept {\n return all_of(std::not_fn(std::ref(pred)), std::forward&lt;Tuple&gt;(t));\n}\n\ntemplate &lt;typename Predicate, typename Tuple&gt;\nconstexpr bool any_of(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept {\n return !none_of(pred, std::forward&lt;Tuple&gt;(t));\n}\n\ntemplate &lt;typename Predicate, typename Tuple&gt;\nconstexpr std::size_t count_if(Predicate&amp;&amp; pred, Tuple&amp;&amp; t) noexcept {\n std::size_t r = 0;\n for_each(\n [&amp;](auto&amp;&amp; x){ r += (bool)pred(std::forward&lt;decltype(x)&gt;(x)); },\n std::forward&lt;Tuple&gt;(t)\n );\n}\n\ntemplate &lt;typename Tuple, typename T&gt;\nconstexpr std::size_t count(Tuple&amp;&amp; t, const T&amp; value) noexcept {\n return count_if([&amp;](auto&amp;&amp; x){ return value == x; }, std::forward&lt;Tuple&gt;(t));\n}\n</code></pre></li>\n<li><p>Consider rewriting your <code>for_each_n()</code> in terms of a generic <code>static_for()</code>.</p></li>\n<li><p>Anyway, <code>for_each_n()</code> should either more closely follow the standard-library, by making <code>n</code> a runtime-argument (then best implement in terms of <code>all_of()</code>), or get a different name, like <code>for_first_n()</code>.</p></li>\n<li><p><code>mismatch()</code> and <code>find()</code> have completely separate implementations for using a predicate and not using one. Why?<br>\nThe case without predicate is trivially implemented by cooking up the appropriate predicate and delegating.</p></li>\n<li><p>Why does <code>mismatch()</code> expect the first tuple to not be longer than the second?<br>\nThat restriction is baffling, and will be vexing for any user.</p></li>\n<li><p><code>mismatch()</code> can also be easily implemented in terms of <code>static_for()</code>. Though should you maybe skip elements which cannot be compared?</p></li>\n<li><p><code>find()</code> is unusable if any tuple-member is not comparable to your needle / cannot be fed to your lambda. Shouldn't those members just be skipped?</p></li>\n<li><p><code>find_if_not()</code> should delegate to <code>find_if()</code> using <code>std::not_fn()</code>.</p></li>\n<li><p>As you wanted to get around the need for helper-functions, let me emphasize yet again that leveraging all the related functions you build and the standard-library helps there.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T12:15:42.067", "Id": "407835", "Score": "0", "body": "regarding your first point, I already made a type_trait for checking equality comparabilty, and the stl has the is_invocable traits which i can use! https://codereview.stackexchange.com/questions/165856/type-trait-for-checking-whether-or-not-2-types-are-nothrow-comparable-to-each I am going to work on your other points" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T01:53:38.187", "Id": "210955", "ParentId": "210934", "Score": "5" } } ]
{ "AcceptedAnswerId": "210955", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T12:36:16.853", "Id": "210934", "Score": "6", "Tags": [ "c++", "c++17" ], "Title": "STL-Style algorithms on tuples" }
210934
<p>I am writing the code for my EPQ project and am aiming to produce a graphic showing the collapse of a particle cloud with around 10^5/6 particles. </p> <p>My current code will spawn a specified number of particles in a uniform distribution across a specified area. It will then calculate the acceleration of the particles using a Barnes-Hutt tree and integrate this to find the new position of each particle. I currently have no graphics but the program will print to the console upon each movement.</p> <p>Unfortunately, each iteration takes around half a minute (running with 35000 particles) which is way too slow for a graphic. So i am looking for a way to improve my algorithm(s) to make it faster.</p> <p>Here is some of my code:</p> <p><strong>Tree class:</strong></p> <pre><code>class tree { public: obj* body; // obj class stores the mass, velocity, position ans acceleration of an object bool parent = false; double total_mass; region R; // region class defines boundaaries and can check if an object is in them vect moment; tree* nw, *ne, *sw, *se; // the children nodes of the tree tree(vect corner, double length) : R(length, corner), total_mass(0), moment(vect(0, 0)), body(nullptr) {} tree(cloud&amp; a) : R(a.size + 1, vect(0,0)), total_mass(0), moment(vect(0, 0)), body(nullptr) { for (int i = 0; i &lt; a.chest.size(); i++) { insert(a.chest[i]); // this constructer id called for the root node only } } ~tree() { delete nw; delete sw; delete ne; delete se; } void insert(obj* i) { if (!R.in(i-&gt;pos)) // cant insert into a region its not in { return; } else { if (body == nullptr) // no other bodies in this region { if (!parent) { body = i; // region is not divides so you can insert particle here } else { nw-&gt;insert(i); //region is divided so try to insert into children nodes ne-&gt;insert(i); sw-&gt;insert(i); se-&gt;insert(i); } } else // trying to have more than one particle in a node { divide(); // splits node into its childrem nw-&gt;insert(i); ne-&gt;insert(i); sw-&gt;insert(i); se-&gt;insert(i); nw-&gt;insert(body); // insert current object and the object that was previouly in the parent node into the children nodes ne-&gt;insert(body); sw-&gt;insert(body); se-&gt;insert(body); body = nullptr; // no longer bodies in the node } total_mass += i-&gt;mass; moment += (i-&gt;pos) * (i-&gt;mass); } } void divide() { double l = R.length / 2; nw = new tree(R.point + vect(0, l), l); ne = new tree(R.point + vect(l, l), l); sw = new tree(R.point + vect(0, 0), l); se = new tree(R.point + vect(l, 0), l); parent = true; } vect COM() { return moment / total_mass; } }; </code></pre> <p><strong>Accelerator:</strong></p> <pre><code>constexpr double theta = 0.5; //theta criterion double G = 1 * pow(10,-11); // gravitational constant void accelerate(obj&amp; i, tree&amp; t) { vect r = t.COM() - i.pos; // vector between the position of the particle and the center of mass of the node if (!t.parent) //checks if node is undivided { i.a += (t.body == nullptr || t.R.in(i.pos)) ? vect(0, 0) : r.norm() * G * t.total_mass / r.mag2(); }//if there are also no bodys or the object being accelerated is in the node then there is no effect on the particle else { if (t.R.in(i.pos) || t.R.length / r.mag() &gt; theta) { accelerate(i, *t.nw); //object is in the node or the node does not meet the theta criterion so try the nodes children accelerate(i, *t.ne); accelerate(i, *t.sw); accelerate(i, *t.se); } else { i.a += r.norm() * G * t.total_mass / r.mag2(); } } } </code></pre> <p><strong>RK4:</strong></p> <pre><code>void move(cloud&amp; a) // cloud class stores an array of pointers to objects { tree* t1 = new tree(a); //adds objects in cloud to a new tree for (obj* i : a.chest) //chest is the array of pointer to objects { accelerate(*i, *t1); //uses tree to refresh the accelration of the particle i-&gt;tpos = i-&gt;ppos = i-&gt;pos; // tpos/v/a stores the value of the new pos/v/a, ppos stores the value from the previous itteration i-&gt;tv = i-&gt;pv = i-&gt;v; i-&gt;ta = i-&gt;pa = i-&gt;a; vect dr1 = i-&gt;v * h; vect dv1 = i-&gt;a * h; i-&gt;pos = i-&gt;ppos + dr1 / 2; i-&gt;v = i-&gt;pv + dv1 / 2; i-&gt;tpos += dr1 / 6; i-&gt;tv += dv1 / 6; } delete t1; tree* t2 = new tree(a); // deletes previous tree and creates a new one to culculate the new acceleration for (obj* i : a.chest) { accelerate(*i, *t2); vect dr2 = i-&gt;v * h; vect dv2 = i-&gt;a * h; i-&gt;pos = i-&gt;ppos + dr2 / 2; i-&gt;v = i-&gt;pv + dv2 / 2; i-&gt;tpos += dr2 / 3; i-&gt;tv += dv2 / 3; } delete t2; tree* t3 = new tree(a); for (obj* i : a.chest) { accelerate(*i, *t3); vect dr3 = i-&gt;v * h; vect dv3 = i-&gt;a * h; i-&gt;pos = i-&gt;ppos + dr3; i-&gt;v = i-&gt;pv + dv3; i-&gt;tpos += dr3 / 3; i-&gt;tv += dv3 / 3; } delete t3; tree* t4 = new tree(a); for (obj* i : a.chest) { accelerate(*i, *t4); vect dr4 = i-&gt;v * h; vect dv4 = i-&gt;a * h; i-&gt;tpos += dr4 / 6; i-&gt;tv += dv4 / 6; i-&gt;pos = i-&gt;tpos; i-&gt;v = i-&gt;tv; i-&gt;a = i-&gt;pa; } delete t4; } </code></pre> <p>Would half a minute be normal when simulating this many particles? If not how could I improve this code to make it run faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T15:15:23.283", "Id": "407768", "Score": "2", "body": "There's a lot of dynamic memory allocation going on here - might be worth profiling how much time that takes. If it's significant, you could try to avoid that (by reusing objects via some kind of pool and/or a custom allocator)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T19:09:18.130", "Id": "407775", "Score": "0", "body": "(Welcome to Code Review!) While your question is [on topic](https://codereview.stackexchange.com/help/on-topic) as far as you are ready for *open-ended feedback*, there are bound to be more promising places to ask `Would half a minute be normal when simulating [10^5…6] particles?`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T19:39:14.823", "Id": "407782", "Score": "0", "body": "`Would half a minute be normal when simulating this many particles?` No. The target framers for most games is 60 FPS. I'm not sure how most particles systems achieve that though I suspect an object pool could be the answer. Be sure to head over to [gamedev.se] and see if they've seen this before. I bet they have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T20:29:11.053", "Id": "407786", "Score": "1", "body": "Please include the `cloud` class and a `main` with some test data so we can run the code. Incomplete code snippets are hard to review, and make it impossible for us to help you improve the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T20:45:34.407", "Id": "407787", "Score": "0", "body": "The rest of the code required for it to run is pages and pages so I wont dump it all on here. I have looked into object pools though which is promising and i will post a similar question on Game Development at some point. Thanks for all your advice :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T06:55:55.453", "Id": "407814", "Score": "0", "body": "What does \"EPQ\" stand for? Also, is \"10^5/6\" supposed to mean \"10^5 or 10^6\" (so 100,000 to 1,000,000 particles)? Just want to make sure I understand fully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T07:02:54.573", "Id": "407815", "Score": "0", "body": "@bruglesco There's a big difference between particle systems in a game where the particles in general don't interact with one another, and often don't interact with any other geometry, and in this case, which is an n-body simulation where the mass of each particle gravitationally attracts all other particles in the system. I don't know that game development techniques are enough for this situation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T07:04:56.693", "Id": "407816", "Score": "0", "body": "@user1118321 ahh I did not fully understand the complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T18:49:39.313", "Id": "407869", "Score": "0", "body": "@user1118321 EPQ stands for extended project qualification, and yeah I should have been more clear that I meant 100,000 to 1,000,000 particles." } ]
[ { "body": "<p>This looks like a really fascinating project. I've only played with toy particle systems – never anything as useful as this! But I do have some thoughts that might be helpful.</p>\n<h1>Performance</h1>\n<p>It's hard to say for sure where the slowdown is because it's not possible for me to profile the code based just on what's here. But that's something you should do. Run it in a profiler and see where the slowdowns are rather than guessing.</p>\n<p>That said, I see some things that I frequently find to be performance issues. As mentioned in the comments, the number of allocations that the code does might be an issue. Stack allocations may be faster in some cases than heap allocations. So if you break up the code in <code>move()</code> into 4 different functions, you can allocate <code>t1</code>-<code>t4</code> on the stack rather than the heap. It might improve the speed since a stack allocation is generally just a pointer addition.</p>\n<p>Your <code>accelerate()</code> function is recursive. You might be able to increase the speed by making it loop instead of recursing.</p>\n<p>But if you want to get real performance gains I recommend one or more of the following:</p>\n<ol>\n<li>Write a <a href=\"https://en.wikipedia.org/wiki/SIMD\" rel=\"nofollow noreferrer\">SIMD</a> version of the code that operates on more than one particle at a time.</li>\n<li>Write a multi-threaded version of the code that does the calculations for multiple particles on different threads. (You can do this along with #1 to get even more speed.)</li>\n<li>Run the simulation on the GPU. This is likely to yield even better performance than combining 1 &amp; 2 as GPUs have thousands of cores instead of just dozens.</li>\n</ol>\n<h1>Data Hiding</h1>\n<p>All the members of your <code>tree</code> class are <code>public</code>. That's usually a bad idea because it means that any other code in your application can reach in and change values inside the object, potentially leaving it in an invalid state. It also make debugging harder because you can't narrow down where a member variable was changed. Traditionally, it makes sense to make your member variables private and have accessors to retrieve or change them. The accessors can be written in the header so they get inlined and are just as fast as if they were public. But by having accessors you can, for example, put a breakpoint in a single place and figure out where a variable is changed. It would appear that your <code>cloud</code> and <code>obj</code> classes suffer from the same problem.</p>\n<p>Also, if you make the objects immutable (so they can be read but not changed or written to), it makes moving to multiple threads much easier. But there are other implications to doing that, such as needing to create new values rather than updating existing ones, which may or may not be a performance issue.</p>\n<h1>Naming</h1>\n<p>You really need to expand on your variable names. 1 and 2 letter names are too hard to read. You get it exactly right with names like <code>moment</code> and <code>total_mass</code>, so it's a little odd that arguments to your functions have names like <code>a</code> and <code>i</code>. Why do that?</p>\n<p>Your class names are better than 1 character variable names, but could be expanded. For example, <code>tree</code> is a Barnes-Hutt tree. Why not call it that (or at least something like <code>BHTree</code>) to distinguish it from a typical binary search tree or a red-black tree?</p>\n<p>The class name <code>obj</code> is exceedingly unhelpful. Every piece of data in your program is either a <a href=\"https://en.wikipedia.org/wiki/Passive_data_structure\" rel=\"nofollow noreferrer\">POD</a> or an object, so as a class name <code>obj</code> is entirely free from meaning. Why not call it <code>particle</code>? Or <code>body</code>?</p>\n<p>Most of your function names are pretty good with the exception of <code>COM()</code>. It's only called in one place, so there's no excuse for not just writing out <code>center_of_mass()</code>.</p>\n<h1>Data Structures</h1>\n<p>It looks like there are several bits of data within a particle that need to be updated in sync and that go together. For example, the position, velocity and acceleration of the particle. That should be a <code>struct</code> or <code>class</code> unto itself. And instead of manually keeping all three in sync by doing this:</p>\n<pre><code> i-&gt;tpos = i-&gt;ppos = i-&gt;pos; // tpos/v/a stores the value of the new pos/v/a, ppos stores the value from the previous itteration\n i-&gt;tv = i-&gt;pv = i-&gt;v;\n i-&gt;ta = i-&gt;pa = i-&gt;a;\n</code></pre>\n<p>You could do something like this:</p>\n<pre><code>struct movement {\n float3 pos;\n float3 velocity;\n float3 acceleration;\n};\n...\nnew_movement = movement;\nprev_movement = movement;\n</code></pre>\n<p>So now you only have 2 assignments instead of 6. It's easier to read and it makes clear that position, velocity, and acceleration are all properties of the same object and that you have a next, current, previous relationship between them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T08:07:36.353", "Id": "210961", "ParentId": "210936", "Score": "3" } } ]
{ "AcceptedAnswerId": "210961", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T13:50:17.490", "Id": "210936", "Score": "3", "Tags": [ "c++", "algorithm", "tree", "simulation", "physics" ], "Title": "Very slow frame rate in C++ N-body simulation using Barnes-Hutt and RK4" }
210936
<p>This started as a simple exercise in sorting an array. I wanted to make it a bit more complex which is why I made it a 2D array.</p> <p>I then noticed that each pass that checked and swapped values, it was checking all ten values. This seemed unnecessary because with each pass the highest value gets moved all the way to its final position. So I made it check one less element each pass until it finished.</p> <p>I did not want to use <code>std::sort</code>, this was an exercise in finding my own solution.</p> <p>The program was "falling off" the end of the array, and although I managed to work around it, I'm not sure I did it in the right way, or even why it was doing it in the first place.</p> <p>The program seems to work as intended but would like some feedback on how it can be improved, or any issues etc.</p> <pre><code>#include "stdafx.h" #include&lt;iostream&gt; using std::cout; using std::cin; using std::endl; int main() { const int ROWS = 10; const int COLUMNS = 2; int person[ROWS][COLUMNS] = { { 1,100 }, { 2,20 }, { 3,80 }, { 4,10 }, { 5,50 }, { 6,150 }, { 7,30 }, { 8,60 }, { 9,40 }, { 10,1 } }; for (int i = 0; i &lt; ROWS; ++i) { cout &lt;&lt; "Person " &lt;&lt; person[i][0] &lt;&lt; " ate: " &lt;&lt; person[i][1] &lt;&lt; " pancakes"; { cout &lt;&lt; endl; } } // Sort lowest to highest int loop = 1; int count; // for counting the number of loops int limit = ROWS; // reduced by 1 each loop to skip uneceassary checks for (int j = ROWS - 1; j &gt; 0; --j, loop++, limit--) { cout &lt;&lt; "Loop " &lt;&lt; loop &lt;&lt; endl; cout &lt;&lt; "Loop limit: " &lt;&lt; limit &lt;&lt; endl; count = 0; for (int i = 0; i &lt; ROWS; ++i, ++count ) { if (loop + count == ROWS + 1) // skips unnecessary checks { break; } if (person[i][1] &gt; person[i + 1][1] &amp;&amp; i != ROWS - 1) // The &amp;&amp; condition stopped the program falling off the end of the array // but not sure why it was in the first place { int temp = person[i][1]; person[i][1] = person[i + 1][1]; person[i + 1][1] = temp; } //cout &lt;&lt; person[i][0] &lt;&lt; " " &lt;&lt; person[i][1] &lt;&lt; endl; //un-comment ^ to display inner loop passes } cout &lt;&lt; "Number of inner loops: " &lt;&lt; count &lt;&lt; "\n" &lt;&lt; endl; } // display final order for (int i = 0; i &lt; ROWS; ++i) { cout &lt;&lt; person[i][0] &lt;&lt; " " &lt;&lt; person[i][1] &lt;&lt; endl; } int pause; cin &gt;&gt; pause; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T19:11:42.260", "Id": "407776", "Score": "1", "body": "(Welcome to Code Review!) `wanted to make it a bit more complex` say *challenging*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T19:29:57.663", "Id": "407780", "Score": "0", "body": "Making the array \"2 Dimensional\" does not make the sorting harder (or more interesting)." } ]
[ { "body": "<p>The are lots of different sorting algorithms out there. You seem to have re-implemented \"Bubble Sort\". This is one of my favorite algorithms as it is very easy to write and sufficient (or even preferable) for very small data sets.</p>\n\n<p>The problem with bubble sort is that it has a very bad complexity so when the data sets become large it becomes very expensive and there are other much better algorithms for large data sets.</p>\n\n<h3>Overview</h3>\n\n<blockquote>\n <p>This started as a simple exercise in sorting an array.</p>\n</blockquote>\n\n<p>Good thing to work on when you are a beginner.</p>\n\n<blockquote>\n <p>I wanted to make it a bit more complex which is why I made it a 2D array.</p>\n</blockquote>\n\n<p>I don't think this adds anything to the problem. One of the main concepts of computer science is abstraction. In sorting we usually abstract the comparison out so that it simply becomes a comparison operation (usually <code>less than</code> i.e. <code>operator&lt;</code>). If you abstract out the comparison you are simply left with the sorting algorithm (which then is the same for every type). So you should have written a less than operation and then you could have re-used the sorting algorithm for any type.</p>\n\n<blockquote>\n <p>I then noticed that each pass that checked and swapped values, it was checking all ten values. This seemed unnecessary because with each pass the highest value gets moved all the way to its final position. So I made it check one less element each pass until it finished.</p>\n</blockquote>\n\n<p>This is a standard optimization for \"Bubble Sort\". Unfortunately it does not reduce the complexity that much. Still making this the worst sort for large data sets.</p>\n\n<p>One other optimization (which is a very make Bubble Sort great) is that if you do a full inner loop and there was not a single swap then the array is sorted. You can not break out of the outer loop. This optimization is great as it turns the best case situation (where the data is already sorted (or very close to sorted)) into an O(n) (i.e. linear) operation.</p>\n\n<blockquote>\n <p>I did not want to use <code>std::sort</code>, this was an exercise in finding my own solution.</p>\n</blockquote>\n\n<p>Yes. Experimenting with sorting is good. But you should read up on the different types of algorithm and try and re-implement them. Doing this is great experience and will teach you the advantages of the different types.</p>\n\n<blockquote>\n <p>The program was \"falling off\" the end of the array, and although I managed to work around it, I'm not sure I did it in the right way, or even why it was doing it in the first place.</p>\n</blockquote>\n\n<p><strike>Can't help with that unless I see the code from before your fix. But even if you did this is the wrong site for that. We only review working code.</strike></p>\n\n<p>OK. I found the the bug you mentioned (and fixed). It seems like a common one so I will talk about that below.</p>\n\n<blockquote>\n <p>The program seems to work as intended but would like some feedback on how it can be improved, or any issues etc.</p>\n</blockquote>\n\n<p>OK. Lets have a look.</p>\n\n<h2>Code Review</h2>\n\n<h3>Your Bug:</h3>\n\n<pre><code> if (person[i][1] &gt; person[i + 1][1] &amp;&amp; i != ROWS - 1)\n // The &amp;&amp; condition stopped the program falling off the end of the array\n // but not sure why it was in the first place\n</code></pre>\n\n<p>So you have a loop:</p>\n\n<pre><code> for (int i = 0; i &lt; ROWS; ++i)\n</code></pre>\n\n<p>This will allow you to loop over the array so you can accesses all the elements with <code>person[i]</code>. Where <code>ROWS</code> is the number of rows in the array. So this allows you to access all the valid rows. Remember that valid rows in an array are counted from 0 so the last valid row is <code>ROWS - 1</code> (this is why most loops use less than <code>operator&lt;</code> as you do in the loop test.</p>\n\n<p>The problem is that you also accesses the element <code>person[i + 1]</code>. The largest value of <code>i</code> is <code>ROW-1</code> so the largest element accessed is <code>person[ROW-1+1]</code> or <code>person[ROW]</code> that is one past the end of the array.</p>\n\n<pre><code>int array[3] = {1,2,3};\nstd::cout &lt;&lt; array[0]; // first element\nstd::cout &lt;&lt; array[1]; // second element\nstd::cout &lt;&lt; array[2]; // third element\n// Only 3 elements in the array\nstd::cout &lt;&lt; array[3]; // This is one beyond the end.\n</code></pre>\n\n<h3>Abstraction and self documenting code</h3>\n\n<p>Pull out simple pieces of code into their own well named function. This documents what you are doing and makes the underlying algorithm easier to read.</p>\n\n<pre><code> {\n int temp = person[i][1];\n person[i][1] = person[i + 1][1];\n person[i + 1][1] = temp;\n }\n</code></pre>\n\n<p>This is obviously a swap. Why not write a function called <code>swapPerson(person[i], person[i+1]);</code> that swaps the values of two people. This will make the sort algorithm easier to read. This also moves the actual swapping processes out of the algorithm allowing you to more easily replace it with another one when you use a different type.</p>\n\n<p>Note: This is so common that the standard library has a <code>std::swap()</code> that swaps two values of a the same type.</p>\n\n<p>Now looking at the comparison:</p>\n\n<pre><code> if (person[i][1] &gt; person[i + 1][1])\n</code></pre>\n\n<p>Your code is comparing two elements adding the extra <code>[1]</code> on the end does not change much. But I would change it so that I was comparing two people.</p>\n\n<pre><code> if (lessPerson(person[i + 1], person[i]) {\n }\n</code></pre>\n\n<p>Still looks a bit ugly. But it shows you can use a function to do the test. But C++ lets you define functions that look like maths operations. So you can change the named <code>lessPerson()</code> function into <code>operator&lt;()</code> function that allows you to compare two people.</p>\n\n<pre><code> if (person[i + 1] &lt; person[i]) {\n }\n</code></pre>\n\n<h3>Optimizing the loop</h3>\n\n<pre><code> for (int i = 0; i &lt; ROWS; ++i, ++count )\n {\n if (loop + count == ROWS + 1) // skips unnecessary checks\n {\n break;\n }\n</code></pre>\n\n<p>This seems like a very complex way of writing:</p>\n\n<pre><code> for (int i = 0; i &lt; j; ++i) {\n</code></pre>\n\n<p>Now if we look at your sort Algorithm after these changes:</p>\n\n<pre><code> for (int j = ROWS - 1; j &gt; 0; --j) {\n for (int i = 0; i &lt; j; ++i) {\n if (person[i + 1] &lt; person[i + 1]) {\n std::swap(person[i], person[i+1]);\n }\n }\n }\n</code></pre>\n\n<h3>Boiled Down Code.</h3>\n\n<p>We seem to have boiled down your code to the absolute minimum. I would add the optimization I mentioned above and wrap this in its own function to make it:</p>\n\n<pre><code>void sort(Person person[], int const ROWS)\n{\n for (int j = ROWS - 1; j &gt; 0; --j) {\n bool swapped = false;\n for (int i = 0; i &lt; j; ++) {\n if (person[i + 1] &lt; person[i + 1]) {\n swapped = true\n std::swap(person[i], person[i+1]);\n }\n }\n if (!swapped) {\n break;\n }\n }\n}\n</code></pre>\n\n<p>Notice I have added the type <code>Person</code> so can explicitly write functions to swap and compare objects of type <code>Person</code>. Now you can write a less than (<code>operator&lt;</code>) and assignment (<code>operator=</code> used by <code>std::swap</code>) specifically for people that would allow the algorithm to work without having to be specific to the algorithm.</p>\n\n<p>The next step is then to make the sort work for any type. Usually we do this with templates. So we can pass any type into the sort function and allow it to be sorted (as long as the type has an <code>operator&lt;</code> and an <code>operator=</code>).</p>\n\n<pre><code>template&lt;typename T&gt;\nvoid sort(T array[], int const ROWS)\n{\n for (int j = ROWS - 1; j &gt; 0; --j) {\n bool swapped = false;\n for (int i = 0; i &lt; j; ++) {\n if (array[i + 1] &lt; array[i + 1]) {\n swapped = true\n std::swap(array[i], array[i+1]);\n }\n }\n if (!swapped) {\n break;\n }\n }\n}\n</code></pre>\n\n<p>The next step is to learn about the concepts of <code>Iterators</code> and how that can make the above function even more useful. But I will leave that as an exercise for now.</p>\n\n<h3>Bad Habits</h3>\n\n<p>Please don't do this:</p>\n\n<pre><code>using std::cout;\nusing std::cin;\nusing std::endl;\n</code></pre>\n\n<p>Is it that much harder to write <code>std::cout</code> over <code>cout</code>? This is a kind of habit that will get you into a lot of trouble. Especially when you put <code>using</code> at the top level of a file. If you must do this, do it inside a function so it does not pollute the code.</p>\n\n<p>Not sure what the extra level of braces is for.</p>\n\n<pre><code> {\n cout &lt;&lt; endl;\n }\n</code></pre>\n\n<p>But prefer to use <code>'\\n'</code> rather than <code>std::endl</code>. The only difference is that <code>std::endl</code> performs a forced flush of the stream. The stream will auto flush so there is no need to force a flush to start with. Also manually flushing the stream (by the programmer) is nearly always going to cause sub optimal flushing and lead to performance degradation.</p>\n\n<p>You don't need a <code>return 0</code> in main().</p>\n\n<pre><code> return 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T00:09:04.047", "Id": "407800", "Score": "0", "body": "Thank you Martin, that was the type of response I was hoping for. I know a 2D array isn't really that much more complicated, but I suppose it's hard to remember what it feels like to be a beginner ;) Wait... No \"return 0\"? That's a new one to me, you'll have to expand on that one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T02:02:57.013", "Id": "407907", "Score": "1", "body": "@MrSteve In `main()` as it is special (for C++ only). The compiler automatically plants a `return 0` at the end. Thus it is common when an application has no other error states to **NOT** explicitly put a `return 0` to indicate that that the application has no error state. Conversely if you see a manual `return 0` at the end of main you are implying there are other error states and programmers will look for other returns in the `main()` function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T20:17:18.237", "Id": "210943", "ParentId": "210938", "Score": "6" } } ]
{ "AcceptedAnswerId": "210943", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T14:26:24.580", "Id": "210938", "Score": "4", "Tags": [ "c++", "beginner", "array", "sorting", "reinventing-the-wheel" ], "Title": "Sorting an array in C++" }
210938
<p>The task (also found at <a href="https://www.youtube.com/watch?v=10WnvBk9sZc" rel="nofollow noreferrer">https://www.youtube.com/watch?v=10WnvBk9sZc</a>):</p> <blockquote> <p>Write a function that takes two strings, s1 and s2, and returns the longest common subsequence of s1 and s2.</p> <ul> <li>"ABAZDC", "BACBAD" → "ABAD"</li> <li>"AGGTAB", "GXTXAYB" → "GTAB"</li> </ul> <p>The longest common subsequence is defined such as all of them appear in the same sequence in both strings, possiblywith other characters in between.</p> </blockquote> <p>This is the solution I managed to come up with. I utilise the fact that once a full subsequence as been found, any subsequences that start within the boundaries of that subsequence will always be smaller in length, so I skip ahead.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const findFirstSequence = (s1, s2) =&gt; { let subsequence = "" let s1Idx = 0 let s2Idx = 0 for (; s1Idx &lt; s1.length; ++s1Idx) { const s1Char = s1[s1Idx] for (let j = s2Idx; j &lt; s2.length; ++j, ++s2Idx) { const s2Char = s2[j] if (s1Char === s2Char) { subsequence += s1Char ++s2Idx break } } } return subsequence } const removeDistinctChars = (s1, s2) =&gt; s1.split("").filter(c =&gt; s2.includes(c)).join("") const removeDuplicates = (arr) =&gt; Array.from(new Set(arr)) const findAllSubsequences = (s1, s2) =&gt; { const s1NoDistinct = removeDistinctChars(s1, s2) const s2NoDistinct = removeDistinctChars(s2, s1) let i = 0 const sequences = [] while (i &lt; s1NoDistinct.length) { const sequence = findFirstSequence(s1NoDistinct.slice(i), s2NoDistinct) i += sequence.length sequences.push(sequence) } return sequences } const findLongestSubsequence = (s1, s2) =&gt; { const a = findAllSubsequences(s1, s2) const b = findAllSubsequences(s2, s1) console.log('candidates:', [...a, ...b]) return removeDuplicates([...a, ...b].sort((s1, s2) =&gt; s2.length - s1.length).filter((el, idx, arr) =&gt; el.length === arr[0].length)) } const test = (s1, s2) =&gt; console.log(findLongestSubsequence(s1, s2)) test("ABAZDC", "BACBAD") test("AGGTAB", "GXTXAYB") test("ALSKJDHJASLDH", "HNGFLKSHRADSKLASDJ") test("aaaa", "aa")</code></pre> </div> </div> </p>
[]
[ { "body": "<h1>Find the current max</h1>\n<p>There are some very simple improvements you can make to reduce the run time and the complexity.</p>\n<p>Your code looks for sequences, puts them all in an array and then sorts and filters that array to find the longest. However if you check the length of each sequence as you find it and compare it against the longest you have found to that point you no longer need to keep an array of sequences, only the current longest.</p>\n<p>This also helps reduce the amount of processing. When you know the length of the current longest sequence, you are able to know before calling <code>findFirstSequence(s1,s2)</code> if it will find a longer one. The function can not find a sequence longer than the shortest string you pass it so if either is shorter than the current max then skip the call.</p>\n<p>Also in the function <code>findFirstSequence(s1,s2)</code> as you build the sequence you can workout how long it can possibly get well before you get the sequence. You can thus exit early from that function as well just by knowing the current longest sequence.</p>\n<p>There are also two more places that you can exit early. When you first enter the function 'findLongestSubsequence` you can check if the string are the same. If they are ether one is thus the answer.</p>\n<p>The same after the calls to <code>removeDistinctChars(s1, s2)</code> if <code>s1NoDistinct === s2NoDistinct</code> then you have the answer and can return the result then.</p>\n<h2>Some style points</h2>\n<ul>\n<li><p>Use semiColons, Javascript requires them, and if you dont add them it inserts them automatically. Unfortunately it does not always put them where you may think it will. If you can not list all the times ASI (Automatic Semicolon Insertion) can ignore the line end than you are best to put them in manually.</p>\n</li>\n<li><p>Watch your indentation. It's not bad, just one line is 2 space in too far. But good code does not have style errors.</p>\n</li>\n<li><p>Don't leave for loop segments empty. You have <code>for (; s1Idx &lt; s1.length; ++s1Idx) {</code> which is poor style. <code>for (s1Idx = 0; s1Idx &lt; s1.length; ++s1Idx) {</code> lets you know at a glance what the loop is starting at, rather than having to find where you set the value. In this case I would also say use <code>i</code> rather than <code>s1Idx</code> but that is more a personal preference.</p>\n</li>\n</ul>\n<h2>A rewrite</h2>\n<p>So using your approach and just finding some early exits and avoiding repeated processing the following rewrite keeps track of the current longest sequence. Returning the first longest sequence found.</p>\n<pre><code>const findLongest = (s1, s2) =&gt; {\n const removeDistinct = (s1, s2) =&gt; s1.split(&quot;&quot;).filter(c =&gt; s2.includes(c)).join(&quot;&quot;);\n const findFirstSeq = (s1, s2) =&gt; {\n var seq = &quot;&quot;, i, j = 0;\n for (i = 0; i &lt; s1.length; i++) {\n const c = s1[i];\n while (j++ &lt; s2.length) {\n if (seq.length + (s2.length - j - 2) &lt; max) { return &quot;&quot; }\n if (c === s2[j - 1]) {\n seq += c;\n break;\n }\n }\n }\n return seq\n }\n const findSubseq = (s1, s2) =&gt; {\n if (s2.length &lt;= max || s1.length &lt;= max) { return maxSeq }\n while (s1.length &amp;&amp; s1.length &gt; max) {\n const seq = findFirstSeq(s1, s2);\n if (seq.length &gt; max) {\n max = seq.length;\n s1 = s1.slice(max);\n maxSeq = seq;\n } else { s1 = s1.slice(1) }\n }\n return maxSeq;\n } \n var max = 0, maxSeq;\n if (s1 === s2) { return s1 }\n const s1D = removeDistinct(s1, s2);\n const s2D = removeDistinct(s2, s1);\n if (s1D === s2D) { return s1D }\n findSubseq(s1D, s2D);\n return findSubseq(s2D, s1D);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T23:46:36.853", "Id": "210950", "ParentId": "210940", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T16:00:49.897", "Id": "210940", "Score": "5", "Tags": [ "javascript", "algorithm", "strings" ], "Title": "Find longest common string subsequence" }
210940
<pre><code>package main import ( "fmt" ) type LinkedList struct { first, last *node } type node struct { item int next *node } func (l *LinkedList) add (val int) { n := node { item: val, next: nil, } if l.first == nil { l.last = &amp;n l.first = &amp;n } else { l.last.next = &amp;n l.last = &amp;n } } func (l *LinkedList) traverse () { for n := l.first; n != nil; n = n.next { fmt.Printf("%v ", n.item) } fmt.Println() } func (l *LinkedList) swapLL () { if l.first == nil { panic("First element cannot be null") } if l.first.next == nil { return } ptr1 := l.first var ptr2 *node var ptr3 *node var prev *node for ; ptr1 != nil &amp;&amp; ptr1.next != nil; { //Allocate resources ptr2 = ptr1.next ptr3 = ptr2.next //swap ptr2.next = ptr1 ptr1.next = ptr3 //hook to the previous pair if prev == nil { l.first = ptr2 } else { prev.next = ptr2 } //advance prev = ptr1 ptr1 = ptr3 } } func main () { l := LinkedList { first: nil, last: nil, } l.add(10) l.add(20) l.add(30) l.add(40) l.traverse() l.swapLL() l.traverse() } </code></pre> <hr> <h3>Input:</h3> <pre class="lang-none prettyprint-override"><code>Linkedlist: 10 -&gt; 20 -&gt; 30 -&gt; 40 -&gt; null </code></pre> <h3>Output:</h3> <pre class="lang-none prettyprint-override"><code>Linkedlist: 20 -&gt; 10 -&gt; 40 -&gt; 30 -&gt; null </code></pre> <h3>Question:</h3> <p>Here 10 and 20 are adjacent thus they were swapped. Likewise, 30 and 40 are adjacent thus they were swapped.</p> <p>I am looking for suggestions for improving my code, any optimizations, or anything to make my code more readable and elegant.</p>
[]
[ { "body": "<p>Welcome!</p>\n\n<p>You may be interested in viewing <a href=\"https://golang.org/src/container/list/list.go\" rel=\"nofollow noreferrer\">the Go API implementation of a linked list</a>. Their implementation is not restricted to just integer node data.</p>\n\n<h2>Use <code>go fmt</code></h2>\n\n<p>A few of your lines have trailing whitespace. Likewise, some of your formatting isn't standard for Go.</p>\n\n<p>If you run <code>go fmt</code> on the source code, it cleans all that up for you.</p>\n\n<h2>Don't unnecessarily export things</h2>\n\n<p>Your type <code>LinkedList</code> is exported. If this is for a library, you should add a comment explaining it's usage (used to generate documentation: see <a href=\"https://blog.golang.org/godoc-documenting-go-code\" rel=\"nofollow noreferrer\">Godoc</a>). If it's not for a library, it shouldn't be exported.</p>\n\n<p>Going forward, I'll assume it's not meant for a library. Otherwise the fields of <code>LinkedList</code> also need to be exported, and the <code>node</code> type as well.</p>\n\n<h2>Avoid extra typing when initializing a <code>struct</code></h2>\n\n<p>When initializing a <code>struct</code>, you don't have to initialize the fields to values that would already be the default.</p>\n\n<p>See <a href=\"https://golang.org/ref/spec#Composite_literals\" rel=\"nofollow noreferrer\">§Composite Literals</a> in the language specification for more details.</p>\n\n<pre><code>n := node{\n item: val,\n next: nil,\n}\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code>n := node{\n item: val,\n}\n</code></pre>\n\n<p>And</p>\n\n<pre><code>l := linkedList{\n first: nil,\n last: nil,\n}\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>l := linkedList{}\n</code></pre>\n\n<h2>Combine variable declarations:</h2>\n\n<p>We <a href=\"https://golang.org/ref/spec#Variable_declarations\" rel=\"nofollow noreferrer\">can combine</a> multiple variable declarations under one <code>var</code> keyword.</p>\n\n<pre><code>var ptr2 *node\nvar ptr3 *node\nvar prev *node\n</code></pre>\n\n<p>Becomes either</p>\n\n<pre><code>var ptr2, ptr3, prev *node\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>var (\n ptr2 *node\n ptr3 *node\n prev *node\n)\n</code></pre>\n\n<p>I prefer the shorter notation most times when the variables are of the same type, but either is better.</p>\n\n<h2>Use the specific <code>Printf</code> verb</h2>\n\n<p>You use the <code>%v</code> verb, but here we know at compile time that we're printing integers. You can safely use <code>%d</code> instead.</p>\n\n<h2>Return an <code>error</code> instead of <code>panic()</code>ing</h2>\n\n<p>Unless you expect to always <code>recover()</code> from the <code>panic()</code>, you should return an <code>error</code> value instead. This is more common.</p>\n\n<pre><code>func (l *linkedList) swapLL() {\n if l.first == nil {\n panic(\"First element cannot be null\")\n }\n\n if l.first.next == nil {\n return\n }\n\n //...\n}\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>func (l *linkedList) swapLL() error {\n if l.first == nil {\n return fmt.Errorf(\"List cannot be empty\")\n }\n\n if l.first.next == nil {\n return nil\n }\n\n //...\n\n return nil\n}\n</code></pre>\n\n<p>This now makes it easy to check for the error:</p>\n\n<pre><code>if err := l.swapLL(); err != nil {\n log.Fatal(err)\n}\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Here is the final source I ended up with.</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"log\"\n)\n\ntype linkedList struct {\n first, last *node\n}\n\ntype node struct {\n item int\n next *node\n}\n\nfunc (l *linkedList) add(val int) {\n n := node{\n item: val,\n }\n\n if l.first == nil {\n l.last = &amp;n\n l.first = &amp;n\n } else {\n l.last.next = &amp;n\n l.last = &amp;n\n }\n}\n\nfunc (l *linkedList) traverse() {\n for n := l.first; n != nil; n = n.next {\n fmt.Printf(\"%d \", n.item)\n }\n\n fmt.Println()\n}\n\nfunc (l *linkedList) swapLL() error {\n if l.first == nil {\n return fmt.Errorf(\"List cannot be empty\")\n }\n\n if l.first.next == nil {\n return nil\n }\n\n ptr1 := l.first\n\n var ptr2, ptr3, prev *node\n\n for ptr1 != nil &amp;&amp; ptr1.next != nil {\n //Allocate resources\n ptr2 = ptr1.next\n ptr3 = ptr2.next\n\n //swap\n ptr2.next = ptr1\n ptr1.next = ptr3\n\n //hook to the previous pair\n if prev == nil {\n l.first = ptr2\n } else {\n prev.next = ptr2\n }\n\n //advance\n prev = ptr1\n ptr1 = ptr3\n }\n\n return nil\n}\n\nfunc main() {\n l := linkedList{}\n\n l.add(10)\n l.add(20)\n l.add(30)\n l.add(40)\n\n l.traverse()\n\n if err := l.swapLL(); err != nil {\n log.Fatal(err)\n }\n\n l.traverse()\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T00:13:12.220", "Id": "210952", "ParentId": "210947", "Score": "2" } } ]
{ "AcceptedAnswerId": "210952", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T21:18:55.853", "Id": "210947", "Score": "1", "Tags": [ "algorithm", "linked-list", "go" ], "Title": "Swapping alternate nodes of linkedlist" }
210947
<p>I have a question about my implementation of a "special" Next-Button.<br/> First I want to show you my AfterEffects file:<br/><br/> <a href="https://i.stack.imgur.com/h4cTR.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h4cTR.gif" alt="GIF Button Animation"></a></p> <p><br/> So This Animation has 3 parts<br/></p> <ul> <li>Green: Entry correct</li> <li>Red: Entry incorrect</li> <li>Blue: Button has been pressed (visual feedback)</li> </ul> <p><br/> As I could not work this out with AVD and states I decided to use the Lottie library and play the different segments. <br/><br/> <strong>Main Activity - Only TestMethod, nothing really to review actually</strong></p> <pre><code>private void initButtonTwo(){ mNext = findViewById(R.id.next); mNextButton = new CancelCheckButton(mNext, new NextButtonListener() { @Override public void onClick() { if(enableVibration){ vibrateFeedback(); } switch (mNextCounter){ //This is just a Test-Method, i want Tick and Cross to alternate case 1: case 3: mNextButton.showTick(); break; case 2: case 4: mNextButton.showCross(); break; case 5: mNextButton.showTickEnd(); break; } if(mNextCounter &gt;= 5){ mNextCounter = 1; }else{ mNextCounter = mNextCounter + 1; } } }); } </code></pre> <p><br/><br/> <strong>Interface for Communication Main -> Custom Button C</strong><br/></p> <pre><code>public interface NextButtonListener { public void onClick(); } </code></pre> <p><br/><br/> <strong>Custom Class CancelCheckButton</strong><br/></p> <pre><code>public class CancelCheckButton implements View.OnTouchListener, Animator.AnimatorListener { private LottieAnimationView mAnimationView; private NextButtonListener mListener; private final String LOG_TAG = this.getClass().getSimpleName(); public CancelCheckButton(LottieAnimationView mView, final NextButtonListener mListener){ this.mAnimationView = mView; this.mListener = mListener; this.setTouchListener(); this.setAnimatorListener(); Log.d(LOG_TAG, "CancelCheckButton: called"); } private void setAnimatorListener(){ mAnimationView.addAnimatorListener(this); Log.d(LOG_TAG, "CancelCheckButton: AnimatorListener called"); } private void setTouchListener(){ mAnimationView.setOnTouchListener(this); Log.d(LOG_TAG, "CancelCheckButton: TouchListener called"); } /*****TOUCH INTERACTION ANIMATION*****/ public void showPressed(){ mAnimationView.setMinAndMaxFrame(452,462); mAnimationView.setSpeed(1.8f); mAnimationView.playAnimation(); Log.d(LOG_TAG, "CancelCheckButton: PressAnimation played"); } public void showReleased(){ mAnimationView.setMinAndMaxFrame(485,495); mAnimationView.setSpeed(1.8f); mAnimationView.playAnimation(); Log.d(LOG_TAG, "CancelCheckButton: RelleaseAnimation played"); } /*****FEDBACK CONTROL ANIMATION*****/ public void showTick(){ mAnimationView.setOnTouchListener(null); mAnimationView.setMinAndMaxFrame(58,181); mAnimationView.setSpeed(1.8f); mAnimationView.playAnimation(); Log.d(LOG_TAG, "CancelCheckButton: TickAnimation played, Touchlistener deactivated"); } public void showTickEnd(){ mAnimationView.setOnTouchListener(null); mAnimationView.setMinAndMaxFrame(58,94); mAnimationView.setSpeed(1.8f); mAnimationView.playAnimation(); Log.d(LOG_TAG, "CancelCheckButton: TickEndAnimation played, Touchlistener deactivated"); } public void showCross(){ mAnimationView.setOnTouchListener(null); mAnimationView.setMinAndMaxFrame(300,431); mAnimationView.setSpeed(2.0f); mAnimationView.playAnimation(); Log.d(LOG_TAG, "CancelCheckButton: CrossAnimation played, Touchlistener deactivated"); } /*****LISTENER*****/ @Override public boolean onTouch(View v, MotionEvent event) { if(v.getId() == mAnimationView.getId()){ switch(event.getAction()){ case MotionEvent.ACTION_DOWN: showPressed(); Log.d(LOG_TAG, "CancelCheckButton: View is touched"); break; case MotionEvent.ACTION_UP: showReleased(); v.performClick(); mListener.onClick(); Log.d(LOG_TAG, "CancelCheckButton: View is relleased, OnClick is fired"); break; } } return true; } @Override public void onAnimationStart(Animator animation) { Log.d(LOG_TAG, "CancelCheckButton: Called Animation is STARTED and Touchlistener deactivated"); } @Override public void onAnimationEnd(Animator animation) { setTouchListener(); Log.d(LOG_TAG, "CancelCheckButton: Called Animation is FINISHED and Touchlistener reset"); } @Override public void onAnimationCancel(Animator animation) { Log.d(LOG_TAG, "CancelCheckButton: Called Animation is CANCELED and Touchlistener reset"); } @Override public void onAnimationRepeat(Animator animation) { } } </code></pre> <p><br/><br/> <strong>Notes</strong><br/> When you click on the button I want the blue part to appear and disappear when the finger is released. As it is a very short animation I decided to not deactivate the OnTouchListener. No matter how fast I tipped I could not see a difference.<br/><br/> For the green or red part I deactivated the onTouchListener to avoid an accidental restart of the animation.<br/><br/> It actually works perfectly but even though I tried to keep the code clean I am not happy with it. Is there a more effective or at least a more common way to do it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-05T21:51:45.403", "Id": "210949", "Score": "1", "Tags": [ "java", "android", "animation" ], "Title": "Animated Button on Android using AfterEffects and Lottie" }
210949
<p>I just finished coding a Tic Tac Toe game for my first Python project. Everything seems to be running correctly, but I wanted to get some advice on things I can improve. The main loop is pretty messy and I'm sure there is a way I can clean that up. Also I have many repetitive if statements that I think can be looped somehow.</p> <pre><code>import sys import time def check_position(the_position): if the_position not in taken_positions: return True else: return False def get_position(): position = int(input("Enter a position : ")) return position def draw_position_x(location): if location == 1: game_board[0][0] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 2: game_board[1][0] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 3: game_board[2][0] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 4: game_board[0][1] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 5: game_board[1][1] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 6: game_board[2][1] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 7: game_board[0][2] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 8: game_board[1][2] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 9: game_board[2][2] = 'x' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") def draw_position_o(location): if location == 1: game_board[0][0] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 2: game_board[1][0] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 3: game_board[2][0] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 4: game_board[0][1] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 5: game_board[1][1] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 6: game_board[2][1] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 7: game_board[0][2] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 8: game_board[1][2] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") if location == 9: game_board[2][2] = 'o' print("|" + game_board[0][0] + "|" + game_board[1][0] + "|" + game_board[2][0] + "|") print("|" + game_board[0][1] + "|" + game_board[1][1] + "|" + game_board[2][1] + "|") print("|" + game_board[0][2] + "|" + game_board[1][2] + "|" + game_board[2][2] + "|") def win_check(): if game_board[0][0] == 'x' and game_board[1][0] == 'x' and game_board[2][0] == 'x' or \ (game_board[0][0] == 'o' and game_board[1][0] == 'o' and game_board[2][0] == 'o'): # 1 HORIZONTAL return True if game_board[0][1] == 'x' and game_board[1][1] == 'x' and game_board[2][1] == 'x' or \ (game_board[0][1] == 'o' and game_board[1][1] == 'o' and game_board[2][1] == 'o'): # 2 HORIZONTAL return True if game_board[0][2] == 'x' and game_board[1][2] == 'x' and game_board[2][2] == 'x' or \ (game_board[0][2] == 'o' and game_board[1][2] == 'o' and game_board[2][2] == 'o'): # 3 HORIZONTAL return True if game_board[0][0] == 'x' and game_board[0][1] == 'x' and game_board[0][2] == 'x' or \ (game_board[0][0] == 'o' and game_board[0][1] == 'o' and game_board[0][2] == 'o'): # 1 VERTICAL return True if game_board[1][0] == 'x' and game_board[1][1] == 'x' and game_board[1][2] == 'x' or \ (game_board[1][0] == 'o' and game_board[1][1] == 'o' and game_board[1][2] == 'o'): # 2 VERTICAL return True if game_board[2][0] == 'x' and game_board[2][1] == 'x' and game_board[2][2] == 'x' or \ (game_board[2][0] == 'o' and game_board[2][1] == 'o' and game_board[2][2] == 'o'): # 3 VERTICAL return True if game_board[0][0] == 'x' and game_board[1][1] == 'x' and game_board[2][2] == 'x' or \ (game_board[0][0] == 'o' and game_board[1][1] == 'o' and game_board[2][2] == 'o'): # 1 DIAGONAL return True if game_board[0][2] == 'x' and game_board[1][1] == 'x' and game_board[2][0] == 'x' or \ (game_board[0][2] == 'o' and game_board[1][1] == 'o' and game_board[2][0] == 'o'): # 2 DIAGONAL return True else: return False intro_board = [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']] print("Welcome to TIC TAC TOE!") print("You can pick location by identifying the position on the board. (There are 9 positions)") print("The player who plays first will be using 'x' and the second player will be using 'o'.") print("|" + intro_board[0][0] + "|" + intro_board[1][0] + "|" + intro_board[2][0] + "|") print("|" + intro_board[0][1] + "|" + intro_board[1][1] + "|" + intro_board[2][1] + "|") print("|" + intro_board[0][2] + "|" + intro_board[1][2] + "|" + intro_board[2][2] + "|") game_board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] taken_positions = [] which_turn = 'P1' win = False num_moves = 0 running = True isValid = True while running: while num_moves &lt; 9 and not win: which_position = get_position() if which_turn == 'P1': isValid = check_position(which_position) if isValid: which_turn = 'P2' num_moves = num_moves + 1 taken_positions.append(which_position) draw_position_x(which_position) break if not isValid: print("Position taken, try again.") break if which_turn == 'P2': isValid = check_position(which_position) if isValid: which_turn = 'P1' num_moves = num_moves + 1 taken_positions.append(which_position) draw_position_o(which_position) break if not isValid: print("Position taken, try again.") break win = win_check() if win: print("We have a winner!!!") print("Exiting in 10 seconds") time.sleep(10) running = False if num_moves == 9 and not win: print("Draw!") print("Exiting in 10 seconds") time.sleep(10) running = False if not running: print("Exiting Game") sys.exit() </code></pre>
[]
[ { "body": "<p><code>draw_position_x</code> and <code>draw_position_o</code> do two things currently - they add a move to the board and they draw it. You should separate those into two functions, one to add a move and one to draw the board, because drawing the board doesn't depend on the move that was just played. A separate draw function won't need any if statements, eliminating a lot of the duplication currently in the code.</p>\n\n<p>You do also do not need a separate functions for placing an 'x' move and placing an 'o' move; use a single function and pass the move 'x' or 'o' as a parameter.</p>\n\n<pre><code>while running:\n while num_moves &lt; 9 and not win:\n</code></pre>\n\n<p>You should be able to eliminate one of these two <code>while</code> statements. You can have a single <code>while num_moves &lt; 9 and not win</code> which is sufficient to keep execution in the main game loop until the game is over, and remove all the <code>break</code> statements within the loop. If you need or want to jump back to the top of the loop (for this program, perhaps after bad input) you can use <code>continue</code> instead of <code>break</code>.</p>\n\n<p>The three <code>VERTICAL</code> cases and three <code>HORIZONTAL</code> cases in <code>win_check</code> could be tested with a for loop over columns/rows, instead of repetition.</p>\n\n<p>You don't need to <code>sys.exit()</code> at the end of the program — the program exits when it reaches the end of the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:38:03.470", "Id": "210968", "ParentId": "210958", "Score": "3" } }, { "body": "<p>Welcome to the site, and welcome to programming! I've recently implemented tic tac toe for console as a practice exercise, so hopefully I can provide some helpful advice in improving your program. If you have any questions about my answer, please feel free to ask them in a comment below my answer.</p>\n\n<p>In general, <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">avoid global variables</a> like <code>intro_board</code>, <code>game_board</code>, etc., with rare exception. It is much better to have each of those variables be part of <code>play_game</code> function that then passes variables as arguments to the other functions when necessary, instead of having unrestricted access to the variables from any Python function. It will make your functions more generic and will make the program flow easier to understand, in turn reducing the chance of errors.</p>\n\n<p>The other main thing I would say about your program is <strong>don't repeat yourself</strong> (known as the <a href=\"https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY principle</a>). Avoiding repetition is an important step in making your programs easier to maintain. Of course, other design elements can significantly impact the effectiveness of your program, but I think learning to reduce duplication is one of the most important skills one can learn to advance their craft as a programmer. Therefore, I'm going to spend the rest of my answer walking through duplicated code and demonstrating how to fix the duplication.</p>\n\n\n\n<h1>Duplication</h1>\n\n<h2>Case study: repeated <code>\"|\"</code></h2>\n\n<p>To start, I want to focus on just one line:</p>\n\n<pre><code>print(\"|\" + game_board[0][0] + \"|\" + game_board[1][0] + \"|\" + game_board[2][0] + \"|\")\n</code></pre>\n\n<p>Looking at this line, you may notice <code>\"|\"</code> is duplicated. We can fix that! Instead of duplicating <code>\"|\"</code>, you could just write a function to surround game tiles with <code>\"|\"</code>:</p>\n\n<pre><code>def surround_tiles(sep, tile1, tile2, tile3):\n \"\"\"Surround and intersperse three tiles with sep.\"\"\"\n return sep + tile1 + sep + tile2 + sep + tile3 + sep\n</code></pre>\n\n<p>At this point, I will mention that Python already provides a function that is appealing for avoiding string repetition: it's called <a href=\"https://docs.python.org/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\">str.join</a> (where \"<code>str</code>\" represents an object of type <code>str</code>). We could use it as follows:</p>\n\n<pre><code>print(\"|\" + \"|\".join([game_board[0][0], game_board[1][0], game_board[2][0]]) + \"|\")\n</code></pre>\n\n<p>However, we <em>still</em> retain the repetition of <code>\"|\"</code>, so unfortunately <code>str.join</code> is not quite right for our situation. A better solution would be:</p>\n\n<pre><code>def intersperse(sep, lst):\n \"\"\"Surround and intersperse an iterable with sep.\"\"\"\n output = sep\n for i in lst:\n output += i + sep\n return output\n</code></pre>\n\n<p>Mind, this is probably not the <em>fastest</em> solution, but that is a topic for another question. This solution is simply an example of removing the duplicated <code>\"|\"</code> from that single line.</p>\n\n<h2>The larger duplication</h2>\n\n<p>These three lines are repeated verbatim <strong>18 times</strong> in your program:</p>\n\n<pre><code> print(\"|\" + game_board[0][0] + \"|\" + game_board[1][0] + \"|\" + game_board[2][0] + \"|\")\n print(\"|\" + game_board[0][1] + \"|\" + game_board[1][1] + \"|\" + game_board[2][1] + \"|\")\n print(\"|\" + game_board[0][2] + \"|\" + game_board[1][2] + \"|\" + game_board[2][2] + \"|\")\n</code></pre>\n\n<p>This is easily avoidable: simply remove the printing code from the printing code out of the conditional changing of a board position, and do it after that task is accomplished (I'll show how in a moment).</p>\n\n<p>Looking ahead, <code>draw_position_x</code> and <code>draw_position_o</code> are the same function with one letter different! We could halve our lines of code between the two functions by just making a generic <code>draw_position</code> function with a <code>symbol</code> parameter that determines the character that is inserted into the game board.</p>\n\n<p>Using all the knowledge we've gathered so far in this section, we can turn the original 94 lines into just 24 lines:</p>\n\n<pre><code>def draw_position(location, symbol):\n if location == 1:\n game_board[0][0] = symbol\n if location == 2:\n game_board[1][0] = symbol\n if location == 3:\n game_board[2][0] = symbol\n if location == 4:\n game_board[0][1] = symbol\n if location == 5:\n game_board[1][1] = symbol\n if location == 6:\n game_board[2][1] = symbol\n if location == 7:\n game_board[0][2] = symbol\n if location == 8:\n game_board[1][2] = symbol\n if location == 9:\n game_board[2][2] = symbol\n print(\"|\" + game_board[0][0] + \"|\" + game_board[1][0] + \"|\" + game_board[2][0] + \"|\")\n print(\"|\" + game_board[0][1] + \"|\" + game_board[1][1] + \"|\" + game_board[2][1] + \"|\")\n print(\"|\" + game_board[0][2] + \"|\" + game_board[1][2] + \"|\" + game_board[2][2] + \"|\")\n</code></pre>\n\n<p>But we can do even better! The input translation conditional is unnecessarily repetitive with the <code>if</code> statements, having an individual conditional check for each number from <code>1</code> to <code>9</code>. We could make a dictionary with each input value and its resultant coordinates:</p>\n\n<pre><code>NUM_TO_COORD = {\n 1: (0, 0)\n 2: (1, 0)\n 3: (2, 0)\n 4: (0, 1)\n 5: (1, 1)\n 6: (2, 1)\n 7: (0, 2)\n 8: (1, 2)\n 9: (2, 2)\n}\n\ndef draw_position(location, symbol):\n coord = NUM_TO_COORD[location]\n game_board[coord[0]][coord[1]] = symbol\n\n # ...\n</code></pre>\n\n<p>But we don't <em>actually</em> need such a dictionary. We could simply translate the coordinate on the fly, and avoid hard-coding something that could easily have a typographical error somewhere. To do this we, use a process of translating our one dimensional user input into two dimensional coordinates with the modulus and division operators (this is basically doing a <a href=\"https://en.wikipedia.org/wiki/Positional_notation#Base_conversion\" rel=\"nofollow noreferrer\">base conversion</a> process):</p>\n\n<pre><code>def num_to_coord(num):\n # 0-index num\n num -= 1\n coord = []\n while True:\n curr_coord = num % 3\n coord.append(curr_coord)\n if len(coord) &gt;= 2:\n break\n num -= curr_coord\n num //= 3\n return coord\n\ndef draw_position(location, symbol):\n coord = num_to_coord(location)\n game_board[coord[0]][coord[1]] = symbol\n\n # ...\n</code></pre>\n\n<p>And finally, we can come back to the game board printing code:</p>\n\n<pre><code> print(\"|\" + game_board[0][0] + \"|\" + game_board[1][0] + \"|\" + game_board[2][0] + \"|\")\n print(\"|\" + game_board[0][1] + \"|\" + game_board[1][1] + \"|\" + game_board[2][1] + \"|\")\n print(\"|\" + game_board[0][2] + \"|\" + game_board[1][2] + \"|\" + game_board[2][2] + \"|\")\n</code></pre>\n\n<p>It can be printed with much less repetition by doing two loops to print it, and using the <code>intersperse</code> function from before:</p>\n\n<pre><code> for y in range(3):\n print(intersperse('|', [game_board[x][y] for x in range(3)]))\n</code></pre>\n\n<p>There are more improvements that can be made, but I've demonstrated the general principle. If you apply this methodology to your coding, you will have much better code. You could even try revising this code and post a new question!</p>\n\n<h2>Addendum</h2>\n\n<p>Based on the <a href=\"https://chat.stackexchange.com/transcript/87932\">conversation we had</a>, there are a few things I'll add:</p>\n\n<p>It <em>is</em> better to have everything* in a function because it allows the module to be imported without running the program. However, there is a standard way that Python programmers run code directly from the module: by conditioning any run code with:</p>\n\n<pre><code>if __name__ == '__main__':\n # ...\n</code></pre>\n\n<p>Generally, this code block is placed at the bottom of the program. It is good to put the code in a main function, because it allows one to import the main running code. Also, splitting things into smaller function parts is called procedural programming.</p>\n\n<p>* However, I have asterisked the word \"everything\" because there is another aspect of programming that may be new to you: object oriented programming (abbreviated OOP). It uses something (unsurprisingly) called objects, which are basically date types. Python is a bit special because every data type and everything in Python is an object. And by everything, I mean pretty much <em>everything</em>, not just variable values!</p>\n\n<p>In modern programming, procedural programming and OOP are generally used together, though it depends on the program.</p>\n\n<p>But don't worry about taking in all the subtle nuances now, it will come with time, and having a greater context. I personally find that practicing programming and reviewing your work is the most effective way to improve as a programmer, though it does depend on what you're programming.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T19:29:50.240", "Id": "407876", "Score": "0", "body": "@BobPage Whoops. I've never linked to chat before, so I didn't realize it would automatically do that previous comment. I think we're done talking for now, but the chat transcript is [here](https://chat.stackexchange.com/transcript/87932), in case a moderator comes around and deletes comments (since comments are designed to be temporary on Stack Exchange sites)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:18:42.400", "Id": "407884", "Score": "0", "body": "I don't know what happened but I accidentally deleted the comments... I've got the transcript so no big deal." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:43:46.370", "Id": "210983", "ParentId": "210958", "Score": "3" } }, { "body": "<h2>Use boolean expressions directly</h2>\n\n<p>This:</p>\n\n<pre><code>if the_position not in taken_positions:\n return True\nelse:\n return False\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>return the_position not in taken_positions\n</code></pre>\n\n<h2>Use generators</h2>\n\n<p>This:</p>\n\n<pre><code>game_board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>game_board = [[' ']*3 for _ in range(3)]\n</code></pre>\n\n<h2>Avoid sleep</h2>\n\n<p>This:</p>\n\n<pre><code>print(\"Exiting in 10 seconds\")\ntime.sleep(10)\n</code></pre>\n\n<p>is generally not a good idea. The convention for console programs is that they run in a persistent console that doesn't vanish after the program exits. As such, drop the sleep.</p>\n\n<h2>Indentation bug?</h2>\n\n<p>This code:</p>\n\n<pre><code>if not running:\n print(\"Exiting Game\")\n sys.exit()\n</code></pre>\n\n<p>seems out-of-place. If it belongs in the loop, indent it. Also, you don't need an <code>exit</code> here; simply break out of the loop.</p>\n\n<p>If it does belong at the top level, it doesn't do anything that wouldn't already happen by the program exiting normally (other than the <code>print</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T18:42:22.297", "Id": "210987", "ParentId": "210958", "Score": "2" } } ]
{ "AcceptedAnswerId": "210983", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T05:30:22.360", "Id": "210958", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "tic-tac-toe" ], "Title": "My first Python project: Tic Tac Toe" }
210958
<h1>Min Heap Implementation</h1> <p>As an exercise, I wanted to implement a min heap using JavaScript. </p> <p>I'm not terribly familiar with JavaScript best practices, so I wanted to get feedback on my approach.</p> <h2>Notes</h2> <ul> <li>I decided to implement the min heap using an array. <ul> <li>I filled the first element with a <code>null</code> value to make some of the math a little easier (in my opinion) - I know this is slightly more memory, but I thought the tradeoff was worth it</li> </ul></li> <li>The actual <code>MinHeap</code> function is effectively a factory function (and <em>not</em> a constructor) that creates objects representing min heaps that wraps the underlying array implementation in closure. <ul> <li>The idea here was to minimize the public API (i.e. "privatize" as much of the internal implementation details as possible).</li> <li>I explicitly named functions so that if any errors occurred, it would be easier to identify in the stack trace - I don't know if this preferred / matters</li> </ul></li> <li>In the future, I could see this heap implementation expanding past a min heap to take a custom comparator, but I decided to keep it simple for the time being and simply use <code>&lt;</code>.</li> <li>I decided to write this in <code>ES5</code> - I'll probably refactor this to use <code>ES6</code> conventions in the future.</li> </ul> <h2>Questions</h2> <p>The questions I have are</p> <ol> <li>Is the factory function approach sound?</li> <li>Are there any JavaScript best practices that I've violated or ignored?</li> <li>Is my implementation flawed in any way?</li> </ol> <h1>Implementation</h1> <pre class="lang-js prettyprint-override"><code>var MinHeap = function() { var values = [null]; function getParentIndex(childIndex) { return Math.floor(childIndex / 2); } function getChildIndices(parentIndex) { var leftChild = parentIndex * 2; return { leftChild: leftChild, rightChild: leftChild + 1, }; } function swap(firstIndex, secondIndex) { var firstValue = values[firstIndex]; values[firstIndex] = values[secondIndex]; values[secondIndex] = firstValue; } function getSmallestNode(firstIndex, secondIndex) { var firstValue = values[firstIndex]; var secondValue = values[secondIndex]; if (firstValue &gt; secondValue) { return { value: secondValue, index: secondIndex, }; } return { value: firstValue, index: firstIndex, }; } function add(value) { var valueIndex, parentIndex, parentValue; values.push(value); valueIndex = getSize(); parentIndex = getParentIndex(valueIndex); parentValue = values[parentIndex]; while (parentValue &gt; value &amp;&amp; parentIndex &gt;= 1) { swap(parentIndex, valueIndex); valueIndex = parentIndex; parentIndex = getParentIndex(valueIndex); parentValue = values[parentIndex]; } } function remove() { var firstValue = values[1], lastValueIndex = values.length - 1, lastValue = values.splice(lastValueIndex, 1)[0]; if (getSize() &gt; 0) { values[1] = lastValue; lastValueIndex = 1; var childIndices = getChildIndices(lastValueIndex); var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild); while (lastValue &gt; smallestNode.value) { swap(lastValueIndex, smallestNode.index); lastValueIndex = smallestNode.index; var childIndices = getChildIndices(lastValueIndex); smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild); } } return firstValue; } function getFirst() { return values[1]; } function getSize() { return values.length - 1; } return { add: add, remove: remove, getFirst: getFirst, getSize: getSize, }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T07:14:07.347", "Id": "407817", "Score": "0", "body": "Is `.add()` expected to handle only integer input?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T07:45:54.633", "Id": "407819", "Score": "0", "body": "well, when implementing I had mainly numbers in mind, though I guess any value could theoretically be added...right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T08:10:21.240", "Id": "407823", "Score": "0", "body": "When a string is passed to `.add()`, `.getFirst()` returns a different result. Consider the test case input `[ \"5\", \"14\", \"23\", \"32\", \"41\", \"87\", \"90\", \"50\", \"64\", \"53\" ]` for which each element is passed to `.add()`. `.getFirst() // \"14\"`. Where input to `.add()` are the values as integers `.getFirst() // 5`. Only noting that the expected type of input (string, integer, or either) could be specified explicitly in comments at the code, or the code could be adjusted to handle string or integer input without explicitly stating that in comments." } ]
[ { "body": "<h1>Questions</h1>\n\n<blockquote>\n <p>Is the factory function approach sound?</p>\n</blockquote>\n\n<p>Yes it is by far the best for objects that will have more than one long lived instance. Not so good for many short lived instances in which case use prototyped factory to reduce instantiation overheads, but lose some flexibility when protecting state.\nFor single instance object use a singleton.</p>\n\n<h2>Freeze</h2>\n\n<p>For added state safety freeze the returned object so that it can not have its state mutated</p>\n\n<pre><code>return Object.freeze({add, remove, getFirst, getSize});\n</code></pre>\n\n<h2>Internal reference</h2>\n\n<p>It is often the case that you need to reference the factory object from within the factory function. We can think of the factory functions closure as the object state and the returned object as the interface.</p>\n\n<p>Because in JS the token <code>this</code> is unsafe we need to create a safe reference to the returned object that can be used from within the factory.</p>\n\n<p>What that name is, is up to you, I would personally have called it <code>interface</code> however that is a reserved token in JS so I have taken to standardize the returned object name to <code>API</code> which works well and replaces the <code>this</code> token with the visually easier capitalized name.</p>\n\n<p>Thus you can use the following (see below for details on getters)</p>\n\n<pre><code>const API = Object.freeze({\n add, remove,\n get first() { return values[1] },\n get size() { return values.length - 1 },\n});\n\nreturn API;\n</code></pre>\n\n<p>Then from within the factory you can acess the interface as follows</p>\n\n<pre><code>// you had\nif (getSize() &gt; 0) {\n// becomes\nif (API.size &gt; 0) {\n</code></pre>\n\n<hr>\n\n<h2>Q2</h2>\n\n<blockquote>\n <p>Are there any JavaScript best practices that I've violated or ignored?</p>\n</blockquote>\n\n<ul>\n<li>Use const for variables that do not change.</li>\n<li>Use object shorthand property notation. See below</li>\n<li>Reduce GC overhead and by using preallocation and result object as optional argument. See below</li>\n<li>Hoist var declarations to the top of the function.</li>\n<li>Don't use line seperated declarations. See below</li>\n<li>Use getters and setters to simplify the interface.</li>\n<li>Protect state and freeze the returned factory object.</li>\n<li><code>null</code> is to be avoided. <code>undefined</code> is better. Ignoring the DOM <code>null</code> is seldom used in JS and represents a defined placeholder.</li>\n<li>Use shorter function form that is arrow functions.</li>\n<li>The JS author's regret was to tokenize <code>function</code> rather than <code>func</code> which spurred the push and adoption of arrow functions. Use common abbreviations when possible, less to read is quicker to read and easier to comprehend. Source code is not an english literature dissertation, you don't need to double space for examiners notes.</li>\n<li>JS has one number type (double AKA 64 bit floating point), however almost all implementations have a variety of under the hood number types. Signed 32 integer is the fastest and can be forced by using any of the bitwise operators. If working with known integer types (eg indices) use bitwise operations to ensure internal number type is <code>int32</code></li>\n<li>Don't add inferable names to variable names. You had <code>function getParentIndex(childIndex) { return Math.floor(childIndex / 2); }</code> is just as effective as <code>const parentIdx = idx =&gt; idx &gt;&gt; 1;</code> and makes one wonder why you need a function to perform a single operator?</li>\n</ul>\n\n<hr>\n\n<h1>Q3</h1>\n\n<blockquote>\n <p>Is my implementation flawed in any way?</p>\n</blockquote>\n\n<p>Not if the user of it is careful. </p>\n\n<p>I do know that you can implement it without the need for the first item in the heap without adding complexity.</p>\n\n<p>You do need to prevent your code from creating invalid states. Such as if you add a string as a number <code>heap.add(\"1\")</code> your determination as to which is greater will false eg <code>\"11\" &gt; \"2\"</code> evaluates to false. To prevent that from happening you need to convert added values to Number type. (see rewrite) </p>\n\n<p>Also you do not want to accept values that are not numbers. You can throw a range error or ignore such values.</p>\n\n<p>You do not protect against removing more than available and thus you can mutate the state to unusable. You should first check if there is anything to remove before doing so (see rewrite)</p>\n\n<hr>\n\n<h2>More info on above notes</h2>\n\n<h3>Line separated declarations</h3>\n\n<p>Bad</p>\n\n<pre><code>var valueIndex,\n parentIndex,\n parentValue;\n</code></pre>\n\n<p>Better </p>\n\n<pre><code>var valueIndex;\nvar parentIndex;\nvar parentValue;\n</code></pre>\n\n<p>Best </p>\n\n<pre><code>var valueIndex, parentIndex, parentValue;\n</code></pre>\n\n<h3>Shorthand property notation</h3>\n\n<p>Shorthand notation reduces the source code size, and thus is a major player in reducing to occurance of bugs.</p>\n\n<p>eg creating an object from defined variables</p>\n\n<pre><code>var foo = someVal();\nvar bar = someOtherVal();\n\n// old school ES notation\nvar obj = {foo : foo, bar : bar};\n\n// ES6 + shorthand property notation\nvar obj = {foo, bar};\n</code></pre>\n\n<p>When you return the factory object </p>\n\n<pre><code>return {\n add: add,\n remove: remove,\n getFirst: getFirst,\n getSize: getSize,\n};\n</code></pre>\n\n<p>You can return using shorthand </p>\n\n<pre><code>return {add, remove, getFirst, getSize};\n</code></pre>\n\n<h3>Memory smart functions.</h3>\n\n<p>Memory smart functions aim to reduce the overhead that GC (Garbage collection) incurs by reducing needless memory allocations. It also has an additional benefit as it reduces the allocation and creation overheads associated with new objects and or arrays.</p>\n\n<p>For example the function...</p>\n\n<pre><code>function getChildIndices(parentIndex) {\n var leftChild = parentIndex * 2;\n\n return {\n leftChild: leftChild,\n rightChild: leftChild + 1,\n };\n}\n</code></pre>\n\n<p>...creates and returns a new object each time it is called. You ate just interested in the 2 64bit numbers (if ints then 32bit numbers), but an object requires much more than 2 64bit values, and it need to invoke memory management, and when done with the object it is added to the GC workload.</p>\n\n<p>You call it as follows</p>\n\n<pre><code> var childIndices = getChildIndices(lastValueIndex); // creates new object\n var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);\n\n while (lastValue &gt; smallestNode.value) {\n swap(lastValueIndex, smallestNode.index);\n lastValueIndex = smallestNode.index;\n\n var childIndices = getChildIndices(lastValueIndex); // Creates it again each iteration\n smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);\n }\n</code></pre>\n\n<p>The function can be changed to be able to remove that overhead using the following pattern</p>\n\n<pre><code>function getChildIndices(parentIndex, result = {}) { // result is the returning object. If not passed it is created\n var leftChild = parentIndex * 2;\n result.leftChild = leftChild;\n result.rightChild = leftChild + 1;\n return result;\n}\n</code></pre>\n\n<p>Then your calling function uses it as follows </p>\n\n<pre><code> const childIndices = getChildIndices(lastValueIndex); // creates new object as default parameter\n var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);\n\n while (lastValue &gt; smallestNode.value) {\n swap(lastValueIndex, smallestNode.index);\n lastValueIndex = smallestNode.index;\n\n getChildIndices(lastValueIndex, childIndices); // reuses the object, saving time, memory and GC overhead\n smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);\n }\n</code></pre>\n\n<h3>Read only properties using getters</h3>\n\n<p>You have the following functions that are equivalent to getters (hint they have get at the start of the name)</p>\n\n<pre><code>function getFirst() {\n return values[1];\n}\n\nfunction getSize() {\n return values.length - 1;\n}\n\nreturn {\n add: add,\n remove: remove,\n getFirst: getFirst,\n getSize: getSize,\n};\n</code></pre>\n\n<p>Should be defined as getters </p>\n\n<pre><code>return Object.freeze({\n add, remove,\n get first() { return values[1] },\n get size() { return values.length - 1 },\n});\n</code></pre>\n\n<h2>A rewrite</h2>\n\n<p>I have added some additional state protection to the interface. Done some renaming, and reduced memory management overheads. The whole thing is now 50 lines that easily fits a display meaning the whole function can be understood without any device interaction</p>\n\n<pre><code>const MinHeap = () =&gt; {\n const heap = [undefined];\n const childIdxs = (idx, res = {}) =&gt; (res.right = (res.left = idx &lt;&lt; 1) + 1, res);\n const swap = (idxA, idxB) =&gt; {\n const temp = heap[idxA];\n heap[idxA] = heap[idxB];\n heap[idxB] = temp;\n }\n const smallestNode = (idxs, res = {}) =&gt; {\n res.idx = heap[idxs.left] &gt; heap[idxs.right] ? idxs.right : idxs.left;\n res.val = heap[res.idx];\n return res;\n }\n const API = Object.freeze({\n add(val) {\n if (isNaN(val)) { throw new RangeError(\"Can only add numeric values\") }\n var idx, parentIdx, parentVal;\n heap.push(Number(val));\n idx = API.size;\n parentIdx = idx &gt;&gt; 1;\n parentVal = heap[parentIdx];\n while (parentVal &gt; val &amp;&amp; parentIdx &gt;= 1) {\n swap(parentIdx, idx);\n parentIdx = (idx = parentIdx) &gt;&gt; 1;\n parentVal = heap[parentIdx];\n }\n },\n remove() { // returns undefined if heap is empty\n if (API.size) {\n let lastVal = heap.pop();\n const first = heap[1];\n if (API.size &gt; 0) {\n let lastIdx = 1;\n const indices = childIdxs(lastIdx);\n const smallest = smallestNode(indices);\n heap[1] = lastVal;\n while (lastVal &gt; smallest.val) {\n swap(lastIdx, smallest.idx);\n lastIdx = smallest.idx;\n smallestNode(childIdxs(lastIdx, indices), smallest);\n }\n }\n return first;\n }\n },\n get first() { return heap[1] },\n get size() { return heap.length - 1 },\n });\n return API;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:45:00.183", "Id": "210984", "ParentId": "210959", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T06:11:51.230", "Id": "210959", "Score": "3", "Tags": [ "javascript", "heap" ], "Title": "Min Heap Implementation" }
210959
<p>I want to sync the table every few minutes to a remote database. I want it to be as efficient as possible. I wrote this stored procedure that will <strong>only</strong> return rows that are added or removed after the last query.</p> <p>Basically, this stored procedure will return something like this:</p> <pre class="lang-none prettyprint-override"><code>190107080001 | REMOVED | NULL | NULL | NULL | NULL | NULL | 190107080005 | ADDED | 225545 | Name2 | 5 | Specialist2 | 26 | 190107080108 | ADDED | 230139 | Name3 | 8 | Specialist3 | 44 | </code></pre> <p>Note: the <code>[key]</code> is actually simple hashed value from the row itself, the remote database will use the <code>[key]</code> as Identity.</p> <p>Actually I do not have problem with this code until now, but I think my implementation is not effective enough considering I will execute this query 24/7.</p> <pre class="lang-sql prettyprint-override"><code>CREATE PROCEDURE [dbo].[GetMonthlySchedules] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; ---------------------------------------------------------------- -- Select new record and save it to temporary table ---------------------------------------------------------------- SELECT [key] , id , therapist , therapistId , specialist , specialistId INTO #Temp_MonthSchedule FROM doc INNER JOIN spe ON doc.specialistId = spe.Id INNER JOIN lis ON doc.Id = lis.DocId WHERE lis.Dt &gt;= DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE())) AND lis.Dt &lt;= DATEADD(mm, 1, DATEDIFF(dd, 0, GETDATE())) ---------------------------------------------------------------- -- Select the different between old and new records to return it later ---------------------------------------------------------------- SELECT ISNULL(old.[key], new.[key]) AS [key] , CASE WHEN old.Id IS NULL THEN 'ADDED' WHEN new.Id IS NULL THEN 'REMOVED' END AS operation , new.id, new.therapist, new.therapistId, new.specialist, new.specialistId INTO #Temp_MonthScheduleDiff FROM ComparerMonthSchedule AS old FULL OUTER JOIN #Temp_MonthSchedule AS new ON old.[key] = new.[key] WHERE old.id IS NULL OR new.id IS NULL ---------------------------------------------------------------- -- Replace old record with new record ---------------------------------------------------------------- DELETE FROM ComparerMonthSchedule INSERT INTO ComparerMonthSchedule SELECT * FROM #Android_Temp_MonthSchedule ---------------------------------------------------------------- -- Return records ---------------------------------------------------------------- SELECT * FROM #Temp_MonthScheduleDiff ---------------------------------------------------------------- -- Delete temporal table ---------------------------------------------------------------- IF OBJECT_ID('tempdb..#Temp_TodaySchedule') IS NOT NULL BEGIN DROP TABLE #Temp_TodaySchedule END; IF OBJECT_ID('tempdb..#Temp_TodayScheduleDiff') IS NOT NULL BEGIN DROP TABLE #Temp_TodayScheduleDiff END; END </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-11T19:48:04.080", "Id": "408678", "Score": "0", "body": "Have you read the [sql tag info](https://codereview.stackexchange.com/tags/sql/info)? \"_1) Provide context, 2) Include the schema, 3) If asking about performance, include indexes and the output of_ `EXPLAIN SELECT.`\"" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T06:44:51.997", "Id": "210960", "Score": "1", "Tags": [ "performance", "sql", "sql-server" ], "Title": "Syncing a table to a remote database" }
210960
<h2>What is does</h2> <p>I'm reading <a href="https://www.gopl.io/" rel="nofollow noreferrer">The Go Programming Language</a>. Below is my code for the <a href="https://www.gopl.io/ch1.pdf#page=42" rel="nofollow noreferrer">last exercise</a> in the first chapter, which is to create a webserver, generate an image, and serve the image via the server, allowing modifications of the image via query string parameters, eg: <code>localhost:8000/?cycles=25&amp;bgcolor=0,255,255</code>.</p> <h2>My Concerns</h2> <p>I'm open to any and all suggestions, but any advice specifically concerning these points would be especially helpful.</p> <p><strong>Duplicated code</strong>. There's just enough duplication to trigger my OCD, but each one is slightly different so I'm not sure how I could delegate to a function without creating a bunch of very similar functions. In particular, the two <code>for</code> loops where I'm parsing colors really bother me.</p> <p><strong>Type Juggling</strong>. <a href="https://golang.org/pkg/strconv/#ParseInt" rel="nofollow noreferrer"><code>strconv.ParseInt</code></a> has a third argument to specify the bit size but always returns <code>int64</code> anyway, so I still have to explicitly cast then to unsigned 8 bit integers. Take a look at my <code>img.SetColorIndex</code> call where I'm doing all sorts of casting just for some simple arithmetic. </p> <p><strong>Concision</strong>. I am baffled at the fact that I can write a simple server using the standard library with about 4 lines of code, but turning a string into an array of numbers took me 19 lines of code. And I had to use basically the same 19 lines twice because I couldn't figure out what to specify as the type when passing a <a href="https://golang.org/pkg/image/color/#RGBA" rel="nofollow noreferrer"><code>color.RGBA</code></a> as a function parameter.</p> <pre><code>package main import ( "log" "net/http" "io" "image" "image/color" "image/gif" "math" "math/rand" "strconv" "strings" ) var bgcolor = color.RGBA{0, 0, 0, 255} var fgcolor = color.RGBA{255, 255, 255, 255} func main() { http.HandleFunc("/", serveImage) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } func serveImage(w http.ResponseWriter, r* http.Request) { if err := r.ParseForm(); err != nil { log.Print(err) } cycles := 10.0 res := 0.001 size := 100 frames := 64 delay := 8 if value, exists := r.Form["cycles"]; exists { if v, err := strconv.ParseFloat(value[0], 64); err == nil { cycles = v } } if value, exists := r.Form["res"]; exists { if v, err := strconv.ParseFloat(value[0], 64); err == nil { res = v } } if value, exists := r.Form["size"]; exists { if v, err := strconv.ParseFloat(value[0], 64); err == nil { size = int((v-1)/2) } } if value, exists := r.Form["frames"]; exists { if v, err := strconv.ParseInt(value[0], 10, 0); err == nil { frames = int(v) } } if value, exists := r.Form["delay"]; exists { if v, err := strconv.ParseInt(value[0], 10, 0); err == nil { delay = int(v) } } if value, exists := r.Form["bgcolor"]; exists { BGColorLoop: for { parts := strings.Split(value[0], ",") if len(parts) != 3 { break BGColorLoop } for _, val := range parts { if v, err := strconv.ParseInt(val, 10, 0); err != nil || int(v) &gt; 255 || int(v) &lt; 0 { break BGColorLoop } } r, _ := strconv.ParseInt(parts[0], 10, 8) g, _ := strconv.ParseInt(parts[1], 10, 8) b, _ := strconv.ParseInt(parts[2], 10, 8) bgcolor = color.RGBA{uint8(r), uint8(g), uint8(b), 255} break BGColorLoop } } if value, exists := r.Form["fgcolor"]; exists { FGColorLoop: for { parts := strings.Split(value[0], ",") if len(parts) != 3 { break FGColorLoop } for _, val := range parts { if v, err := strconv.ParseInt(val, 10, 0); err != nil || int(v) &gt; 255 || int(v) &lt; 0 { break FGColorLoop } } r, _ := strconv.ParseInt(parts[0], 10, 8) g, _ := strconv.ParseInt(parts[1], 10, 8) b, _ := strconv.ParseInt(parts[2], 10, 8) fgcolor = color.RGBA{uint8(r), uint8(g), uint8(b), 255} break FGColorLoop } } lissajous(w, cycles, res, size, frames, delay) } func lissajous(out io.Writer, cycles float64, res float64, size int, nframes int, delay int) { freq := rand.Float64() * 3.0 anim := gif.GIF{LoopCount: nframes} phase := 0.0 palette := []color.Color{bgcolor, fgcolor} for i := 0; i&lt;nframes; i++ { rect := image.Rect(0, 0, 2*size+1, 2*size+1) img := image.NewPaletted(rect, palette) for t:=0.0; t&lt;cycles*2*math.Pi; t+=res { x := math.Sin(t) y := math.Sin(t*freq+phase) img.SetColorIndex(size+int(x*float64(size)+0.5), size+int(y*float64(size)+0.5), 1) } phase += 0.1 anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } gif.EncodeAll(out, &amp;anim) } </code></pre>
[]
[ { "body": "<p>Code must be correct. To be sure that code is correct, code must be readable.</p>\n\n<hr>\n\n<p>I took some of your baffling code:</p>\n\n<pre><code>var bgcolor = color.RGBA{0, 0, 0, 255}\nvar fgcolor = color.RGBA{255, 255, 255, 255}\n\nif value, exists := r.Form[\"bgcolor\"]; exists {\nBGColorLoop:\n for {\n parts := strings.Split(value[0], \",\")\n if len(parts) != 3 {\n break BGColorLoop\n }\n for _, val := range parts {\n if v, err := strconv.ParseInt(val, 10, 0); err != nil || int(v) &gt; 255 || int(v) &lt; 0 {\n break BGColorLoop\n }\n }\n r, _ := strconv.ParseInt(parts[0], 10, 8)\n g, _ := strconv.ParseInt(parts[1], 10, 8)\n b, _ := strconv.ParseInt(parts[2], 10, 8)\n bgcolor = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n break BGColorLoop\n }\n}\nif value, exists := r.Form[\"fgcolor\"]; exists {\nFGColorLoop:\n for {\n parts := strings.Split(value[0], \",\")\n if len(parts) != 3 {\n break FGColorLoop\n }\n for _, val := range parts {\n if v, err := strconv.ParseInt(val, 10, 0); err != nil || int(v) &gt; 255 || int(v) &lt; 0 {\n break FGColorLoop\n }\n }\n r, _ := strconv.ParseInt(parts[0], 10, 8)\n g, _ := strconv.ParseInt(parts[1], 10, 8)\n b, _ := strconv.ParseInt(parts[2], 10, 8)\n fgcolor = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n break FGColorLoop\n }\n}\n</code></pre>\n\n<p>I rewrote it (a first draft) in Go:</p>\n\n<pre><code>bgcolor, err := formColor(r, \"bgcolor\")\nif err != nil {\n bgcolor = color.RGBA{0, 0, 0, 255}\n}\nfgcolor, err := formColor(r, \"fgcolor\")\nif err != nil {\n fgcolor = color.RGBA{255, 255, 255, 255}\n}\n</code></pre>\n\n<p>Where</p>\n\n<pre><code>var errFormColor = errors.New(\"invalid form color\")\n\nfunc formColor(r *http.Request, colorKey string) (color.RGBA, error) {\n var rgb [3]uint8\n\n value := r.Form[colorKey]\n if len(value) &lt;= 0 {\n return color.RGBA{}, errFormColor\n }\n parts := strings.SplitN(value[0], \",\", len(rgb)+1)\n if len(parts) != len(rgb) {\n return color.RGBA{}, errFormColor\n }\n for i, part := range parts {\n p, err := strconv.ParseUint(part, 10, 8)\n if err != nil {\n return color.RGBA{}, errFormColor\n }\n rgb[i] = uint8(p)\n }\n\n return color.RGBA{rgb[0], rgb[1], rgb[2], 255}, nil\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T21:52:31.593", "Id": "407889", "Score": "0", "body": "After fixing a few minor errors your code compiled, which surprised me because originally I had tried to delegate the same block of code to a function but it would not allow me to return the color. The compiler kept saying \"color.RGBA is not a type.\" Eventually I gave up. I will try to duplicate that error later to see if I can figure out where I went wrong.\n\nThanks for your input!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T19:48:38.010", "Id": "210991", "ParentId": "210962", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T08:38:34.660", "Id": "210962", "Score": "1", "Tags": [ "formatting", "go", "type-safety" ], "Title": "Generating Image & Serving via HTTP with Go" }
210962
<p>As a beginner in Rust i am trying to practice Rust with some little programs so here is my implementation of Decimal to Binary.</p> <pre><code>use std::io; pub fn run() { let number = input("Enter an input"); println!("{}", to_binary(number)); } fn input(msg: &amp;str) -&gt; i32 { println!("{}", msg); let mut number = String::new(); io::stdin() .read_line(&amp;mut number) .expect("Failed to read input"); match number.trim().parse() { Ok(num) =&gt; num, Err(_e) =&gt; panic!("Not a number"), } } fn to_binary(mut decimal: i32) -&gt; i32 { if decimal == 0 { decimal } else { let mut bits = String::new(); while decimal &gt; 0 { if decimal % 2 == 0 { bits.push_str("0"); } else { bits.push_str("1"); } decimal /= 2; } // reverse the bits match bits.chars().rev().collect::&lt;String&gt;().parse() { Ok(num) =&gt; num, Err(_e) =&gt; panic!("Something went wrong"), } } } </code></pre> <p>so feel free to advice anything you consider. i just have three questions in particular</p> <ol> <li><p>isn't it better to write <code>input</code> as a macro ?</p></li> <li><p>how can i write <code>to_binary</code> as pure function ?</p></li> <li><p>wouldn't be better to return binary type from <code>to_binary</code> instead i32</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:16:56.490", "Id": "407827", "Score": "0", "body": "Just to make sure: when you say you're a \"beginner in Rust\", are you also a beginner in general programming, or do you have previous programming experience?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:38:23.453", "Id": "407829", "Score": "0", "body": "i have a little experience in general programing" } ]
[ { "body": "<blockquote>\n <p>isn't it better to write input as a macro ?</p>\n</blockquote>\n\n<p>No. At best it might work as a generic function.</p>\n\n<blockquote>\n <p>how can i write to_binary as pure function ?</p>\n</blockquote>\n\n<p>It already is a pure function, it doesn't mutate or depend on external state</p>\n\n<blockquote>\n <p>wouldn't be better to return binary type from to_binary instead i32</p>\n</blockquote>\n\n<p>You should return a <code>String</code>. Converting to i32 is pretty weird. The numbers inside i32 are already in binary. The point of a to_binary function is pretty much always because you for some reason want a textual representation in binary.</p>\n\n<p>As a quick side note, Rust already has the ability to convert values to binary:</p>\n\n<pre><code>format!(\"{:b}\", value);\n</code></pre>\n\n<p>Your to_binary function would be a bit simpler if build a Vec or Vec and then converted that instead of building a String.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:58:08.220", "Id": "211126", "ParentId": "210967", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T09:12:13.820", "Id": "210967", "Score": "4", "Tags": [ "beginner", "rust", "number-systems" ], "Title": "Decimal to Binary in Rust" }
210967
<p>I'm new to PHP OOP programming and I'm trying to make a user class with login, register, logout and some other methods. I'm concentrating in the login method that will be used with Ajax.</p> <p><strong>Session class</strong></p> <pre><code>class Session { // these are global variables defined in the config file private $lifetime = LIFETIME; private $path = PATH; private $domain = DOMAIN; private $secure = SECURE; private $http_only = HTTPONLY; public function __construct($name) { // method colled everytime an instance is called // $lifetime, $path, $domain, $secure, $http_only session_set_cookie_params($this-&gt;lifetime, $this-&gt;path, $this-&gt;domain, $this-&gt;secure, $this-&gt;http_only); session_name($name); session_start(); } public function setVariable($name, $sv) { // Sets the session variable $_SESSION[$name] = $sv; } public function getVariables() { // gets the session array with all variables return $_SESSION; } public function getSingle($name) { // displays the session variable return $_SESSION[$name]; } public function removeSessionVariable($name) { // removes session variable unset($_SESSION[$name]); } public function regenerate() { // regenerates the id of session session_regenerate_id(); } public function killSession() { // kills the sessions. // to be used on logouts for example. $_SESSION = array(); session_destroy(); } } </code></pre> <p><strong>User class</strong></p> <pre><code>class User extends Session { private $error = false; private $msg = ''; private $fields = array(); private $result = array(); private $type = ''; private $db; private $stmt; public function __construct($dbh) { $this-&gt;db = $dbh; } // verifies login form inputs public function verifyLoginFields($username, $password, $token, $bot, $sv) { if (strlen($username) &lt; 3) { $this-&gt;error = true; array_push($this-&gt;fields, 'username'); } if (strlen($password) &lt; 3) { $this-&gt;error = true; array_push($this-&gt;fields, 'password'); } if (strlen($bot) !== 0) { $this-&gt;error = true; array_push($this-&gt;fields, 'bot'); } if ($token !== $sv) { $this-&gt;error = true; array_push($this-&gt;fields, 'token'); } if ($this-&gt;error) { return false; } else { return true; } } // if no errors, proceed with login system public function login($username, $password, $token, $bot, $sv) { if($this-&gt;verifyLoginFields($username, $password, $token, $bot, $sv)) { $query = "SELECT id, username, password, role FROM users WHERE username = :un"; $this-&gt;stmt = $this-&gt;db-&gt;prepare($query); $this-&gt;stmt-&gt;bindParam(':un', $username, PDO::PARAM_STR); if($this-&gt;stmt-&gt;execute()) { if($this-&gt;stmt-&gt;rowCount() == 1) { $row = $this-&gt;stmt-&gt;fetch(); $pass = htmlentities($row['password'], ENT_QUOTES, 'utf-8'); if(!password_verify($password, $pass)) { $this-&gt;error = true; array_push($this-&gt;fields, 'password'); $this-&gt;msg = 'Existem erros no formul&amp;aacute;rio!'; $this-&gt;type = 'error'; } else { $this-&gt;type = 'success'; $this-&gt;msg = 'Redirecting...'; $this-&gt;setVariable('username', htmlentities($row['username'], ENT_QUOTES, 'utf-8')); $this-&gt;setVariable('id', htmlentities($row['id'], ENT_QUOTES, 'utf-8')); $this-&gt;setVariable('role', htmlentities($row['role'], ENT_QUOTES, 'utf-8')); } } else { $this-&gt;error = true; array_push($this-&gt;fields, 'username'); $this-&gt;msg = 'Existem erros no formulario!'; $this-&gt;type = 'error'; } } else { $this-&gt;type = 'error'; $this-&gt;msg = 'Fatal Error!'; } } else { $this-&gt;type = 'error'; $this-&gt;msg = 'Existem erros no formulário!'; } // Sets a new token value $this-&gt;setVariable('token', bin2hex(random_bytes(32))); $this-&gt;result = [ 'type' =&gt; $this-&gt;type, 'msg' =&gt; $this-&gt;msg, 'fields' =&gt; $this-&gt;fields, 'token' =&gt; $this-&gt;getsingle('token') ]; echo json_encode($this-&gt;result); } } </code></pre> <p>The way I'm using this is this:</p> <pre><code>include_once('includes/config.php'); include_once('includes/session.class.php'); include_once('includes/login.class.php'); $session = new Session('login'); if (!isset($_SESSION['token'])) { $session-&gt;setVariable('token', bin2hex(random_bytes(32))); } // $dbh comes from config file $user = new User($dbh); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $password = $_POST['password']; $token = $_POST['token']; $bot = $_POST['user']; $user-&gt;login($username, $password, $token, $bot, $session-&gt;getSingle('token')); } </code></pre> <p>Right now, I'm only testing but this will be used with Ajax request. Am I on the right track? Any advice on how I can improve this class?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T11:39:47.650", "Id": "407834", "Score": "0", "body": "I am afraid there is not enough code in this question to be compliant with the site rules. Although empty methods are borderline possible, but such blocks as `... here goes the database code ...` are not allowed at all. It should be a fully working code to be reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T12:24:52.867", "Id": "407837", "Score": "0", "body": "@YourCommonSense did some changes in the code. removed all empty methods and completed the login method." } ]
[ { "body": "<p>The main problem here is violation of the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single responsibility principle</a>. A User class has too much responsibilities. It interacts with the client, verifies a CSRF token, decides what kind of response will be sent, etc. An top of that, User extends Session which is outright wrong. Classes must be related to each other. An Apple class could extend a Fruit class, because an apple is a fruit. But a user is not a session. That's completely different entities that have nothing in common. Moreover, they belong to different realms, a user belongs to the Business logic and a session belongs to the Client interaction. There are PHP applications that do not interact with a client, what would they do with a session?</p>\n\n<p>The login() function should just return a boolean value, whereas all interactions with the client should be done elsewhere.</p>\n\n<p>On a side note, you are seem under the impression that regular variables are not used in classes. Well, you are wrong. On the contrary, a variable that is used only in one method <strong>must be not</strong> a class variable, but just a regular variable. Such as $type, $msg, $stmt. </p>\n\n<p>In the end, there should be a distinction between a code that does the business logic and a code that interacts with a client. And MVC pattern does it perfectly. According to it, all form verifications must be done in the Controller (I've got <a href=\"https://phpdelusions.net/articles/mvc\" rel=\"nofollow noreferrer\">an article that explains MVC</a>, you may find it helpful). Assuming your \"I'm using this is this\" code is sort of a Controller, all the client interaction should be moved there. So, login() method should accept only username and password, and verify them against a database like this (the code is taken from my canonical <a href=\"https://phpdelusions.net/pdo_examples/password_hash\" rel=\"nofollow noreferrer\">PDO authentication example</a>):</p>\n\n<pre><code>class User\n{\n private $db;\n\n public function __construct($dbh) {\n $this-&gt;db = $dbh;\n }\n public function login($username, $password)\n\n {\n $sql = \"SELECT id, username, password, role FROM users WHERE username = ?\";\n $stmt = $this-&gt;db-&gt;prepare($sql);\n $stmt-&gt;execute([$username]);\n $user = $stmt-&gt;fetch();\n\n if ($user &amp;&amp; password_verify($password, $user['password']))\n return $user;\n }\n }\n}\n</code></pre>\n\n<p>as you can see, a lot of useless and even harmful code is removed. For example,</p>\n\n<ul>\n<li><code>if($this-&gt;stmt-&gt;execute())</code> makes no sense at all as in case of error an exceptjion will be thrown and therefore this condition will never be evaluated to false. </li>\n<li><code>if($this-&gt;stmt-&gt;rowCount() == 1)</code> is useless as well, as the fetched row could serve as such a flag </li>\n<li><code>htmlentities($row['password']</code> is just weird. There is not a single reason to do so, while it could do a severe harm changing the password so it will return false for the correct password. </li>\n<li>all client interaction including session handling are also removed for the reasons explained above.</li>\n</ul>\n\n<p>So all the client interaction must be written in the controller. If you want to encapsulate the form verification routines, it should be a distinct class (as you are going to use it with other forms as well, aren't you?):</p>\n\n<pre><code>class Form()\n{\n public function verify($sessionToken, $inputToken)\n {\n return hash_equals($sessionToken, $inputToken)\n }\n}\n</code></pre>\n\n<p>and then finally you are ready to process the user input. </p>\n\n<pre><code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {\n $user = new User($dbh);\n $form = new Form();\n\n if (!$form-&gt;verify($session-&gt;getSingle('token'), $_POST['token'])) {\n $result = [\n 'type' =&gt; 'error',\n 'msg' =&gt; 'Existem erros no formulário!',\n 'token' =&gt; $this-&gt;getsingle('token')\n ];\n echo json_encode($result);\n exit;\n }\n\n if ($user = $user-&gt;login($username, $password)\n {\n $session-&gt;setVariable('username', ($user['username']);\n $session-&gt;setVariable('id', $user['id']);\n $session-&gt;setVariable('role', $user['role']);\n $result = [\n 'type' =&gt; 'success',\n 'msg' =&gt; 'Redirecting...',\n 'token' =&gt; $this-&gt;getsingle('token')\n ];\n echo json_encode($result);\n exit;\n } else {\n // a response saying that login or password are incorrect\n }\n}\n</code></pre>\n\n<p>This is not the full code as I don't know some of your internal considerations such as what is $this->fields or $bot but just to give you an idea. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:04:52.337", "Id": "407850", "Score": "0", "body": "Tks. you answered one of my concerns perfectly with your example. i'll study your \"links\". once again, thanks..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T08:14:10.827", "Id": "407926", "Score": "0", "body": "Out of curiosity, what concern it was?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T13:44:01.040", "Id": "210975", "ParentId": "210970", "Score": "2" } } ]
{ "AcceptedAnswerId": "210975", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T11:20:56.530", "Id": "210970", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "PHP user class usability" }
210970
<p>I wanted to write a transpose function for N*N mat without it getting literals or <code>#define</code> values and I want it to compile with <code>gcc -ansi -pedantic -Wall -Werror</code> </p> <pre><code>#include&lt;stdio.h&gt; /*printf */ /*function to transpose a N*N 2D mat */ void TransposeOf2DArray(int* mat, size_t n) { int i = 0; int j = 0; if(NULL == mat) { return; } for(i= 0; i&lt; n; ++i) { for(j = i ; j&lt; n; ++j) { int temp = mat[(n*i)+j]; mat[(n*i)+j] = mat[(n*j)+i]; mat[(n*j)+i] = temp; } } } /*print function for int mat n*n */ void printMat(const int* mat, int n) { int i = 0; if(NULL == mat) { return; } for(i = 0 ; i&lt; n*n ;++i) { printf("%d| ", mat[i]); if((1+i)%n == 0) { printf("\n"); } } } int main() { int mat[][3] = {{0,1,2},{3,4,5},{6,7,8}}; printf("Before transpose: \n"); printMat((int*)mat, 3); TransposeOf2DArray((int*)mat, 3); printf("\nAfter transpose: \n"); printMat((int*)mat, 3); return 0; } </code></pre>
[]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Declare variables only where needed</h2>\n\n<p>Old-style C required all variables to be declared at the top of the function in which they were used, but modern C has not required this for many years. For that reason, you can remove the declarations of <code>i</code> and <code>j</code> and incorporate them into the <code>for</code> loops instead, as in the following suggestion. (Note that this requires C99 or later.)</p>\n\n<h2>Use <code>size_t</code> instead of <code>int</code> where appropriate</h2>\n\n<p>My version of <code>gcc</code> complains because <code>size_t</code> is unsigned and <code>int</code> is unsigned. To address that, we can change the types of <code>i</code> and <code>j</code>:</p>\n\n<pre><code>for (size_t i = 0; i &lt; n; ++i) {\n for (size_t j = i; j &lt; n; ++j) {\n</code></pre>\n\n<h2>Think carefully about the algorithm</h2>\n\n<p>The diagonal of the matrix doesn't really need to be touched. This can easily be addressed by starting the inner loop from <code>i + 1</code> instead of <code>i</code>.</p>\n\n<h2>Consider using pointers</h2>\n\n<p>It might be a bit more clear within the inner loop if pointers were used. Here's one way to do that:</p>\n\n<pre><code>int *a = &amp;mat[(n*i)+j];\nint *b = &amp;mat[(n*j)+i];\n// swap *a and *b\nint temp = *a;\n*a = *b;\n*b = temp;\n</code></pre>\n\n<h2>Consider adding testing</h2>\n\n<p>Since the transpose of a transpose of any matrix should equal itself, this suggests one method of testing the results. I'd suggest testing a few matrices with small size and manually worked answers and then a larger number of matrices with varying sizes using the double-transpose and checking for equality.</p>\n\n<h2>Omit <code>return 0</code> in main</h2>\n\n<p>Since C99, the <code>return 0</code> at the end of main is implicit and may be omitted.</p>\n\n<p><strong>Note:</strong> when I make this suggestion, it's almost invariably followed by one of two kinds of comments: \"I didn't know that.\" or \"That's bad advice!\" My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:</p>\n\n<blockquote>\n <p>[...] a return from the initial call to the <code>main</code> function is equivalent to calling the <code>exit</code> function with the value returned by the <code>main</code> function as its argument; reaching the <code>}</code> that terminates the <code>main</code> function returns a value of 0.</p>\n</blockquote>\n\n<p>For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:</p>\n\n<blockquote>\n <p>If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;</p>\n</blockquote>\n\n<p>All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit <code>return;</code> statements at the end of a <code>void</code> function. Reasons against omitting seem to boil down to <a href=\"http://stackoverflow.com/questions/2581993/what-the-reasons-for-against-returning-0-from-main-in-iso-c/2582015#2582015\">\"it looks weird\"</a>. If, like me, you're curious about the rationale for the change to the C standard <a href=\"http://stackoverflow.com/questions/31394171/what-was-the-rationale-for-making-return-0-at-the-end-of-main-optional\">read this question</a>. Also note that in the early 1990s this was considered \"sloppy practice\" because it was undefined behavior (although widely supported) at the time. </p>\n\n<p>So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:25:38.250", "Id": "407840", "Score": "4", "body": "Omitting `return 0` is an option, but one I generally disagree with - it's a quirk of the language that breaks uniformity, and may confuse beginners." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:28:40.570", "Id": "407841", "Score": "1", "body": "*De gustibus non est disputandum.* Whether one prefers to *use* it or not, it's useful for programmers to *know* of this provision in the standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:32:37.910", "Id": "407842", "Score": "1", "body": "I'll agree with that. However, it's also important to note that your answer contains C99 features, but the OP wants ansi (C89). Whereas I think you should keep the C99 recommendations, you need to mention the version difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:47:06.903", "Id": "407845", "Score": "0", "body": "@Edward thank you, as it is now- I want the strictness of 89, so the return and value declarations are not avoided. will change to size_t and try to improve the algorithm. I have made more tests, but I omitted them. I thought about making a static switch function, but the code as a hole is short so I wasn't sure if its appropriate. Thank you so much for your time and input!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:49:16.387", "Id": "407846", "Score": "1", "body": "I've updated my answers to point out which features requires C99 or later. It would be a shame to ignore the last 20 years of language evolution, but if one is restricted to only the 30-year-old language version, it should now be clear which features that affects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:53:59.927", "Id": "407848", "Score": "0", "body": "@Edward well, if i was not restricted by them I could have just declared the function as: \nvoid Transpose(size_t siz, int mat[][siz]). So it's kind of the point in my case :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T23:45:06.210", "Id": "407901", "Score": "0", "body": "Yes `return 0;` may be omitted in C99, C11, C18. Hardy a significant concern to recommend and it is reasonable to include it. As with such minor style concern, follow your group's coding standard." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T13:10:36.843", "Id": "210974", "ParentId": "210971", "Score": "8" } }, { "body": "<h2>Reconsider <code>ansi</code></h2>\n\n<p><code>-ansi</code> is equivalent to C89, which is many versions behind the current standard (C99 -> C11 -> C17). C99 is popular and will buy you some great language features. C17 is supported by gcc, though, so you should use that.</p>\n\n<h2>Clean up your whitespace</h2>\n\n<p>You should add one or two blank lines between each of your functions.</p>\n\n<p>Your tabs are non-uniform - they seem to vary between two and three spaces. Generally 3-4 spaces is standard; choose a standard and apply it with an IDE or advanced text editor.</p>\n\n<h2>Use <code>const</code></h2>\n\n<p><code>printMat</code> does not modify <code>mat</code>, so declare it <code>const</code>.</p>\n\n<h2>Don't double-initialize</h2>\n\n<p>@Edward correctly indicated that variable declarations should be pulled into the loop. One other thing: you initialize <code>i=0</code> twice, so the first one has no effect. The <code>j=0</code> will also have no effect. Avoid doing effect-less assignment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:01:32.180", "Id": "407849", "Score": "0", "body": "Thank you for your time and input, I will add lines, my white spaces shifted when I moved my code to this platform, I'll be sure to pay more attention to it next time. the const for the print function- is it not enough to state the const int* mat? Would Also want to know about the var initiation - in 89 they must be declared as I did, but I was led to believe it is good practice to init them at declaration - is it not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:27:34.003", "Id": "407853", "Score": "2", "body": "Yes - `const int *mat` will do. As for combined declaration and initialization - yes, this is generally a good idea (if you're in C99 and you can postpone declaration). If you're stuck in C89, it still seems like nicer form to only initialize your loop variables once you get to the beginning of the `for`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:37:06.633", "Id": "210980", "ParentId": "210971", "Score": "8" } }, { "body": "<p><strong>2D array or not?</strong></p>\n\n<p>A \"2D array\" in common parlance is loosely something like the following</p>\n\n<pre><code>int a[4][5];\nint **b;\nint *c[x];\n</code></pre>\n\n<p>For me, I prefer the only calling <code>a</code> a 2D array.</p>\n\n<p>Yet I would not call <code>int* mat</code> a 2D array. It is a pointer and code-wise, used as a pointer to a single dimension array of <code>int</code>.</p>\n\n<pre><code>/*function to transpose a N*N 2D mat */ // ??\nvoid TransposeOf2DArray(int* mat, size_t n) // `int*` is a 1D\n</code></pre>\n\n<p>As code called the function with a cast implies <em>something</em><sup>1</sup> unnecessary is happening. </p>\n\n<pre><code>printMat((int*)mat, 3);\n</code></pre>\n\n<p>Consider</p>\n\n<pre><code>printMat(&amp;mat[0][0], 3);\nTransposeOf2DArray(&amp;mat[0][0], 3);\n// or \nprintMat(mat[0], 3);\nTransposeOf2DArray(mat[0], 3);\n</code></pre>\n\n<p>And re-word <code>void TransposeOf2DArray()</code> description.</p>\n\n<p><strong>White space before <code>'\\n'</code></strong></p>\n\n<p>Trailing white-space (not <code>'\\n'</code>) at the end of the line, too often causes problems. Consider avoiding that.</p>\n\n<p><strong>Return value from print</strong></p>\n\n<p>Not too often code checks the return value of print, primarily to detect errors. Yet <code>printMat()</code> still could provide a useful return.</p>\n\n<pre><code>int printMat(const int* mat, size_t n) {\n retval = 0;\n if (NULL) {\n size_t nn = n*n;\n size_t i = 0;\n for(i = 0 ; i &lt; nn; ++i) {\n const char *sep = ((1+i)%n) ? \"| \" : \"\\n\"; // No WS before \\n\n int r = printf(\"%d%s\", mat[i], sep);\n if (r) {\n retval = r;\n // Perhaps break here\n }\n }\n }\n return retval;\n}\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> Casting often indicate something amiss. Avoid it as able. I do find casting reluctantly needed in some <code>printf()</code> and some assignments between different types, but rarely with specified function argument.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T00:00:56.973", "Id": "211003", "ParentId": "210971", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T11:44:42.763", "Id": "210971", "Score": "8", "Tags": [ "c", "matrix" ], "Title": "Transpose function" }
210971
<p>I wrote this class a few months ago and noticed from a few examples that it's better to break down these classes and separate them. I am not so sure what is the proper way to break if to parts. </p> <p>It currently includes a creation of a System_user obj based on user id (fetching user data), login validation, logout, storing user data to session, and I think that's all. </p> <p>This is my working code: </p> <pre><code>&lt;?php namespace MyApp\Models; use \Exception; use MyApp\Core\Database; use MyApp\Core\Config; use MyApp\Helpers\Session; use MyApp\Helpers\Cookie; use MyApp\Helpers\Token; use MyApp\Helpers\General; use MyApp\Helpers\Hash; /** * * System User Class * */ class System_user { /*================================= = Variables = =================================*/ # @object database Database instance private $db; # Users data private $data; # User user ID name public $user_id; # User first name public $first_name; # User last name public $last_name; # Username public $user_name; # User Email public $email; # User Last logged in public $last_login; # is user logged in public $isLoggedIn; # is user logged in public $login_timestamp; # is user IP private $user_ip; /*=============================== = Methods = ================================*/ /** * * Construct * */ public function __construct($system_user = NULL) { # Get database instance $this-&gt;db = Database::getInstance(); # If system_user isn't passed as a variable if ( !$system_user ) { # ...so check if there is a session user id set if (Session::exists(Config::$session_name)) { # Insert session data to system_user variable $system_user = Session::get(Config::$session_name); # Get user data $this-&gt;find($system_user); } } else { $this-&gt;find($system_user); } } /** * * Find method: Find user by id or by username * @param $user String/Init A username or user ID * */ public function find($system_user = NULL) { if ($system_user) { // Enable search for a system_user by a string name or if numeric - so by id. $field = ( is_numeric($system_user) ) ? 'system_user_id' : 'uname'; // Search for the system_user in the Database 'system_users' table. $data = $this-&gt;db-&gt;row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' =&gt; $system_user)); // If there is a result if ( $data ) { // Set data $this-&gt;setUserData($data); return $this; } else { return false; } } else{ return false; } } /** * * Check if user exist in 'system_users' table * @param $username String Get a username user input * @param $password String Get a password user input * @throws Array/Boolian Is this a signed System user? * */ private function system_user_login_validation($username, $password) { $user_data = $this-&gt;db-&gt;row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' =&gt; $username, 'password' =&gt; sha1($password))); if ($user_data) return $user_data; else return false; } /** * * Login method * @param $customer_name String Get a customer_name user input * @param $username String Get a username user input * @param $password String Get a password user input * @throws Boolian Is this a signed System user? * */ public function login($customer_name, $username, $password) { # Create a Customer Obj $customer = new \MyApp\Models\Customer($customer_name); try { # Check if the result is an array # OR there is no row result: if ( (!isset($customer)) || (!isset($customer-&gt;dbName)) || (!isset($customer-&gt;host)) ) throw new \MyApp\Core\Exception\Handler\LoginException("Bad company name: {$customer_name}"); # Change localhost string to 127.0.0.1 (prevent dns lookup) $customer-&gt;host = ($customer-&gt;host === 'localhost') ? '127.0.0.1' : $customer-&gt;host; # Connect to new database $new_connection = $this-&gt;db-&gt;customer_connect($customer-&gt;host, $customer-&gt;dbName); # If status is connected if ($new_connection) { # Check for user credentials data $user_data = $this-&gt;system_user_login_validation($username, $password); # If the result isn't a valid array - EXEPTION if ( (!is_array($user_data)) || (empty($user_data)) ) throw new \MyApp\Core\Exception\Handler\LoginException("Customer: '{$customer_name}' - Invalid username ({$username}) or password ({$password})"); # Store Customer in the sesison Session::put(Config::$customer, serialize($customer)); # Update host and db for the db object # $this-&gt;db-&gt;update_host_and_db($customer-&gt;host, $customer-&gt;dbName); # Set data for this System_user object $this-&gt;setUserData($user_data); # Set a login session for the user id: Session::put(Config::$session_name, $this-&gt;user_id); # Set logged in user sessions $this-&gt;set_loggedin_user_sessions(); return $this; } else { # Connect back to backoffice (current db set) $this-&gt;db-&gt;connect_to_current_set_db(); throw new \MyApp\Core\Exception\Handler\LoginException('User does not exist'); return false; } } catch (\MyApp\Core\Exception\Handler\LoginException $e) { $e-&gt;log($e); return false; // die(General::toJson(array( 'status' =&gt; false, 'message' =&gt; 'Bad login credentials.' ))); } } /** * * Set sessions for the logged in user. * Tutorial: http://forums.devshed.com/php-faqs-stickies/953373-php-sessions-secure-post2921620.html * */ public function set_loggedin_user_sessions() { # Generate security sessions $this-&gt;generate_security_sessions(); # Set login timestamp Session::put(Config::$login_timestamp, $this-&gt;login_timestamp); # Set login flag to true Session::put(Config::$is_logged_in, true); # Set login IP Session::put(Config::$login_user_ip, $this-&gt;user_ip); } /** * * Generate system user security sessions * @param $new_session Boolean (optinal) Dedices if to delete the cookie session id [default is set to true] * */ public function generate_security_sessions($new_session = true) { if ($new_session) # Generate a new session ID session_regenerate_id(true); # Fetch cookie session ID $session_id = session_id(); # Set the session id to the session Session::put(Config::$session_id, $session_id); # Create a secret token # Set it in session (does them both) $secret = Token::generate_login_token(); # Combine secret and session_id and create a hash $combined = Hash::make_from_array(array($secret, $session_id, $this-&gt;user_ip)); # Add combined to session Session::put(Config::$combined, $combined); } /** * * Check if there is a logged in user * */ public function check_logged_in() { if ( Session::exists(Config::$secret) &amp;&amp; # Secret session exists Session::exists(Config::$session_id) &amp;&amp; # Session_id session exists Session::exists(Config::$session_name) &amp;&amp; # User session exists Session::exists(Config::$is_logged_in) &amp;&amp; # Check if 'logged in' session exists Session::exists(Config::$session_name) # Check if sys_user id is set in session ) { # Get users ip $ip = $this-&gt;get_system_user_ip(); # if the saved bombined session if ( (Session::get(Config::$combined) === Hash::make_from_array(array(Session::get(Config::$secret), session_id()), $ip)) &amp;&amp; (Session::get(Config::$is_logged_in) === true ) ) { # Set ip to system user object $this-&gt;user_ip = $ip; return true; } else { return false; } } else { return false; } } /** * * Check if loggin session is timeout * */ public function check_timeout() { if (Session::exists(Config::$login_timestamp)){ # Calculate time $session_lifetime_seconds = time() - Session::get(Config::$login_timestamp) ; if ($session_lifetime_seconds &gt; Config::MAX_TIME){ $this-&gt;logout(); return true; } else { return false; } } else { $this-&gt;logout(); return false; } } /** * * Get user IP * */ private function get_system_user_ip() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP']; elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; else $ip = $_SERVER['REMOTE_ADDR']; return $ip; } /** * * Set User data to (this) System_user object * @param $user_data Array User data fetched from the db (usually by the find method) * */ private function setUserData($user_data) { // Set data for this user object $this-&gt;user_id = $user_data['system_user_id']; $this-&gt;first_name = $user_data['fname']; $this-&gt;last_name = $user_data['lname']; $this-&gt;user_name = $user_data['uname']; $this-&gt;email = $user_data['email']; $this-&gt;last_login = $user_data['last_login']; $this-&gt;isLoggedIn = true; $this-&gt;user_ip = $this-&gt;get_system_user_ip(); $this-&gt;login_timestamp = time(); } /** * * Logout: Now guess what this method does.. * */ public function logout() { $this-&gt;isLoggedIn = false; Cookie::eat_cookies(); Session::kill_session(); session_destroy(); session_write_close(); } } </code></pre> <p>I would like to get suggestions about my current code, and if possible, about structuring it differently with more than one class. (<code>class SystemUser</code>, <code>class systemUserLogin</code>, <code>class systemUserAuthenticator</code>, ect') </p> <p><em>ps: In general, the webapp by default logs in to a general database. when a user inserts his company_name, username and password, I check if the company name actually exist, if if does, I disconnect from the general db and connect to the customers database and validate his username &amp; password.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:49:49.900", "Id": "407857", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question instead, although I'd recommend waiting at least a day before doing so. More answers might be incoming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:54:20.310", "Id": "407859", "Score": "0", "body": "@Mast I was composing a meta question ask about this as, being a new member here, I wasn't sure what the proper protocol was. Thank you for clarifying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:59:57.907", "Id": "407861", "Score": "0", "body": "@JohnConde No problem. Feel free to ask if anything else is unclear, me and other regulars can usually be found in [The 2nd Monitor](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T08:19:03.560", "Id": "407927", "Score": "0", "body": "@Mast I didn't edit my original code (which is a working code) - I have just added an other code (the one i started to write, which I didn't test and don't know if it works). the questions still refers to the first code. the second code block is just for ref." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T09:23:55.373", "Id": "407933", "Score": "0", "body": "I know, but that doesn't change anything. Don't add/change code after the first answer comes in, so all answerers see the same code. Should you have improved code, feel free to post a follow-up question linking back to this one. Make sure you tell a bit about what you changed and why." } ]
[ { "body": "<p>Interestingly enough we just had <a href=\"//codereview.stackexchange.com/q/210970\">another question</a> where there was a large user class doing a lot. It was correctly pointed out that is not a good thing as it violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. To summarize it, a class should have one and only one responsibility. If your user class is handling the user properties, login, and other actions it is doing too much.</p>\n\n<p>You should familiarize yourself with <a href=\"http://php-di.org/doc/understanding-di.html\" rel=\"nofollow noreferrer\">Dependency Injection</a>. In your constructor you instantiate a database class and then use it to get your database abstraction object. Now you cannot unit test this class because you cannot mock that object. (You can still do an integration test, though). \"Dependency injection allows a client to remove all knowledge of a concrete implementation that it needs to use. This helps isolate the client from the impact of design changes and defects. It promotes reusability, testability and maintainability\". (<a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">source</a>) In other words, your user class has a dependency on the Database class and is at risk if backwards incompatible changes are made to it.</p>\n\n<p>A high level explanation of what you would want to do here to improve this is:</p>\n\n<ol>\n<li>Create an <a href=\"http://php.net/manual/en/language.oop5.interfaces.php\" rel=\"nofollow noreferrer\">interface</a> that your database implements. This will enforce that any database objects in your code will adhere to the same contract (assuming they all implemnt this interface).</li>\n<li>Instantiate the database object in the client code (the code that calls the user class).</li>\n<li>Pass it as a parameter to your constructor and then assign it to your User::db property. Make sure you type hint that parameter using the name of the interface you created in step 1 so if a different database object is created and used it will have to adhere to the same contract or else your code will blow up (in testing before it ever goes live).</li>\n</ol>\n\n<p>Here's some simple code to get you started:</p>\n\n<h3>The Database Interface</h3>\n\n<p><em>This is just a stub. You will need to complete it.</em></p>\n\n<pre><code>interface iDatabase\n{\n public function row($sql);\n public function customer_connect($host, $dbName);\n}\n</code></pre>\n\n<h3>Implement the interface</h3>\n\n<pre><code>class Database implements iDatabase\n</code></pre>\n\n<h3>Make your database object a parameter of your contstructor</h3>\n\n<pre><code>// Put optional parameters after required parameters\npublic function __construct(iDatabase $db, $system_user = NULL)\n</code></pre>\n\n<h3>Instantiate your class passing the database object as a parameter</h3>\n\n<pre><code>$db = Database::getInstance();\n$this-&gt;user = new User($db);\n</code></pre>\n\n<p>You would follow the same example above for any other logic that you pull out of your user class and into its own object. Now your User class does only one thing and does it well and it testable. </p>\n\n<h3>Some little stuff</h3>\n\n<p><strong>Put a line between your <code>namespace</code> and <code>use</code> statements</strong></p>\n\n<p><a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2 coding standards</a> say there should be a line between the <code>namespace</code> declaration and your <code>use</code> statements. </p>\n\n<pre><code>namespace MyApp\\Models;\n\nuse \\Exception;\n</code></pre>\n\n<p><strong>Class names should be camel case</strong></p>\n\n<p>The <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1 standards say class names should be camel case</a> and should not use underscores:</p>\n\n<pre><code>class SystemUser\n</code></pre>\n\n<p><strong>The PHP community prefers <code>//</code> to <code>#</code> for comments</strong></p>\n\n<p>Although <code>#</code> is a valid syntax for a one line comment in PHP, it is common practice to use <code>//</code>. This came out as a result of the <a href=\"https://pear.php.net/manual/en/standards.comments.php\" rel=\"nofollow noreferrer\">PEAR coding standards</a>.</p>\n\n<p><strong>No need to point out your class' \"variables\"</strong></p>\n\n<p>Besides the fact that they aren't technically variables but \"class members\", convention says they go at the top of the class so it is already clear what they are. No need to add unnecessary comments pointing out the obvious. Save your comments for anything that might be ambiguous or needs explanation because it isn't clear from reading the code.</p>\n\n<p><strong>Don't mix coding styles</strong></p>\n\n<p>Your class properties you use both underscores and camel case in your names. Use one or the other but not both.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:44:37.803", "Id": "407844", "Score": "1", "body": "Hello John Conde and thankyou so much for your attention. It's weird for me to pass the DB variable to every class which uses it, are you sure this the the best practice in these situations? I didn't really understand why it's not right from your explanation. + I added my current attempt to re-write this class following a different post from the one you have mentioned. I would be glad if I can get your opinion about it too. ~ still didn't finish the last class..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:50:02.197", "Id": "407847", "Score": "0", "body": "Yes, I am sure. It seems like a lot but it is very common. This promotes test-ability and re-usability. If you wanted to take it a step further, and make life easier for yourself, you can use a container like [Pimple](https://pimple.symfony.com/), create all of your shared objects once, and then pass that container to your other objects. That way you only have to write it once and if you add other shared objects to it any classes that need them will get them automatically since they already have that container. This is how enterprise applications are coded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T16:50:57.673", "Id": "407858", "Score": "1", "body": "I have rolled back both the question and answer to avoid a big mess being created. Should a follow-up question arise, feel free to move the comments you've made to the new question instead. They are still accessible in the edit history." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:04:48.887", "Id": "210978", "ParentId": "210972", "Score": "3" } } ]
{ "AcceptedAnswerId": "210978", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T12:45:41.050", "Id": "210972", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "System_user Class - all in one class including login functions" }
210972
<p>I started with Python and Tkinter and am trying to make my first steps by creating a simple UI with a header, sidebar (currently just a label) and a few labels and entries. </p> <p>Before I go on I want to ask you all if the way I do this is correct and a common one. Also if you see potential to make this better, please let me know! </p> <pre><code>import tkinter as tk from tkinter import messagebox import tkinter.ttk as ttk class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent root.geometry('1280x768') root.configure(background='#0E2F47') root.grid_rowconfigure(20, weight=1) s = ttk.Style() s.theme_use('classic') s.configure('SOExample.TEntry', relief='flat') s.layout('SOExample.TEntry', [ ('Entry.highlight', { 'sticky': 'nswe', 'children': [('Entry.border', { 'border': '1', 'sticky': 'nswe', 'children': [('Entry.padding', { 'sticky': 'nswe', 'children': [('Entry.textarea', {'sticky': 'nswe'})] })] })] })]) # GUI elements header_img = tk.PhotoImage(file='Header.png') header_label = tk.Label(root, bg='#191E31', image=header_img) header_label.image = header_img header_label.grid(column=1, row=0, columnspan=20) sidebar_label = tk.Label(root, bg='#191E31', width=25) sidebar_label.grid(column=1, row=1, rowspan=20, sticky="nws") # Input Section adress_input_label = tk.Label(root, bg='#0E273B', fg='#CEDEEE', text="Adress", font=("Century Gothic", 12), anchor='w') adress_input_label.grid(column=2, columnspan=3, row=1, pady=25, sticky='new') adress_input_entry = ttk.Entry(root, style='SOExample.TEntry') adress_input_entry.grid(row=1, column=3, sticky='e') message_input_label = tk.Label(root, bg='#0E273B', fg='#CEDEEE', text="Message", font=("Century Gothic", 12), anchor='w') message_input_label.grid(column=2, columnspan=3, row=2, pady=25, sticky='new') message_input_entry = ttk.Entry(root, style='SOExample.TEntry') message_input_entry.grid(row=2, column=3, sticky='e') def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy() if __name__ == "__main__": root = tk.Tk() MainApplication(root).grid(column=0, row=0) root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:41:06.397", "Id": "407843", "Score": "2", "body": "If your label and entry layout is incorrect, then unfortunately this is not a question for CodeReview, but rather StackOverflow. In my opinion, if you deem that behaviour \"acceptable for now\" and cut that part of the question out of your text, then the review request can remain." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T12:51:04.717", "Id": "210973", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "gui", "tkinter" ], "Title": "Python UI with Tkinter" }
210973
<p>I've written an infix to postfix converter in Haskell using the <a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm" rel="nofollow noreferrer">Shunting-yard algorithm</a>. Example of how it works:</p> <pre><code>$ ./in2post 2 + 2 2 2 + $ ./in2post 1 + 2 * 3 1 2 3 * + $ ./in2post (5 - 4) * 3+1005/(12-6*(12 -8) ) 5 4 - 3 * 1005 12 6 12 8 - * - / + $ ./in2post (2 + 45 2 45 + ERROR </code></pre> <p>And the source code:</p> <p><strong>Main.hs</strong></p> <pre><code>module Main (main) where import System.IO import InToPost main :: IO () main = do line &lt;- getLine let tokens = tokenise line newexpr = shuntYard [] [] tokens putStrLn $ untokenise newexpr </code></pre> <p><strong>InToPost.hs</strong></p> <pre><code>module InToPost ( Token(TNum, TOp) , Operator , splitTok , tokenise , untokenise , shuntYard ) where import Data.Char (isSpace, isDigit) import Data.List (groupBy) data Token = TNum Int | TOp Operator deriving (Show) data Operator = Add | Sub | Mult | Div | LBrace | RBrace deriving (Show, Eq) splitTok :: String -&gt; [String] splitTok = groupBy (\x y -&gt; isDigit x &amp;&amp; isDigit y) . filter (not . isSpace) str2tok :: String -&gt; Either String Token str2tok tkn@(c:_) | isDigit c = Right $ TNum $ read tkn | otherwise = case tkn of "+" -&gt; Right $ TOp Add "-" -&gt; Right $ TOp Sub "*" -&gt; Right $ TOp Mult "/" -&gt; Right $ TOp Div "(" -&gt; Right $ TOp LBrace ")" -&gt; Right $ TOp RBrace _ -&gt; Left $ "No such operator: \"" ++ tkn ++ "\"" tok2str :: Token -&gt; String tok2str (TNum t) = show t tok2str (TOp t) = case t of Add -&gt; "+" Sub -&gt; "-" Mult -&gt; "*" Div -&gt; "/" _ -&gt; "ERROR" precedence :: Operator -&gt; Int precedence Add = 1 precedence Sub = 1 precedence Mult = 2 precedence Div = 2 precedence LBrace = 3 precedence RBrace = 3 -- shuntYard (Operator stack) (Token Queue) (Token Buffer) = new Token Queue shuntYard :: [Operator] -&gt; [Token] -&gt; [Either String Token] -&gt; Either String [Token] shuntYard _ _ (Left s:_) = Left s shuntYard stack queue [] = Right $ queue ++ map TOp stack shuntYard stack queue (Right (TNum t):ts) = shuntYard stack (queue ++ [TNum t]) ts shuntYard stack queue (Right (TOp t):ts) = shuntYard ustack uqueue ts where (ustack, uqueue) = case t of LBrace -&gt; (t : stack, queue) RBrace -&gt; (stail srest, queue ++ map TOp sstart) _ -&gt; (t : ssend, queue ++ map TOp ssops) (sstart, srest) = break (==LBrace) stack currprec = precedence t (ssops, ssend) = span (\op -&gt; precedence op &gt; currprec &amp;&amp; op /= LBrace) stack stail :: [a] -&gt; [a] stail (x:xs) = xs stail [] = [] tokenise :: String -&gt; [Either String Token] tokenise = map str2tok . splitTok untokenise :: Either String [Token] -&gt; String untokenise (Left s) = s untokenise (Right ts) = unwords . map tok2str $ ts </code></pre> <p>Please tell me, what are my bad practices here? For example, the use of <code>Either</code> felt really awkward and I'm sure it can be done better. Also, the <code>case</code> expression in <code>str2tok</code> is quite ugly.</p>
[]
[ { "body": "<pre><code>main :: IO ()\nmain = do\n line &lt;- getLine\n putStrLn $ case traverse str2tok $ splitTok line of\n Left s -&gt; s\n Right ts -&gt; unwords $ map tok2str $ shuntYard ts\n\n-- shuntYard (Token Buffer) = new Token Queue\nshuntYard :: [Token] -&gt; [Token]\nshuntYard ts = concat queue ++ stack where\n (queue, stack) = (`runState` []) $ for ts $ state . \\case\n TNum t -&gt; ([TNum t],)\n TOp LBrace -&gt; ([],) . (LBrace :)\n TOp RBrace -&gt; (map TOp *** drop 1) . break (==LBrace)\n TOp t -&gt; (map TOp *** (t:)) . span (\\op -&gt; precedence op &gt; precedence t &amp;&amp; op /= LBrace)\n</code></pre>\n\n<p>Or perhaps:</p>\n\n<pre><code>(queue, stack) = (`runState` []) $ for ts $ \\case\n TNum t -&gt; return [TNum t]\n TOp LBrace -&gt; [] &lt;$ modify (LBrace:)\n TOp RBrace -&gt; do\n sstart &lt;- state $ break (==LBrace)\n modify (drop 1)\n return $ map TOp sstart\n TOp t -&gt; do\n ssops &lt;- state $ span $ \\op -&gt; precedence op &gt; precedence t &amp;&amp; op /= LBrace\n modify (t:)\n return $ map TOp ssops\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T22:06:07.800", "Id": "408217", "Score": "0", "body": "Hey, thank you for your answer, but I can't get this code to compile. I've pasted it into the `InToPost.hs` file and compiled with `ghc -dynamic -XLambdaCase -O2 InToPost.hs`, but ghc spits out errors: `Illegal tuple section: use TupleSections`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T14:37:25.600", "Id": "408366", "Score": "0", "body": "You'll need to enable the TupleSections language extension. Also LambdaCase and I didn't list the imports - hoogle unknown identifiers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:25:59.950", "Id": "211075", "ParentId": "210976", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T14:05:50.117", "Id": "210976", "Score": "3", "Tags": [ "algorithm", "parsing", "haskell", "math-expression-eval" ], "Title": "Infix to postfix notation in Haskell (Shunting-yard algorithm)" }
210976
<p>The following is my binary search implementation in Java:</p> <pre><code>package com.solo.workouts.collections.Tree; import com.solo.workouts.Implementors.Util; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; /* @author soloworld @since 1.o */ public class BinarySearchTree&lt;T&gt; { private Comparator comparator; private Node&lt;T&gt; root; private BinarySearchTree(Comparator comparator , T type) { this.comparator = comparator; } private BinarySearchTree(Comparator comparator) { this(comparator,null); } public static BinarySearchTree plantTree(Comparator comparator) { Objects.requireNonNull(comparator ,"requires an comparator . compartor canot be null"); return new BinarySearchTree(comparator); } public void add(T element){ Node&lt;T&gt; node =null; if(root==null) { node = new Node&lt;&gt;(element); root = node; } else { Node&lt;T&gt; currentnode = root; while(currentnode !=null) { int result = compare(currentnode, new Node&lt;&gt;(element)); if (result &lt;= 0) { if (currentnode.leftNode == null) { currentnode.leftNode = new Node&lt;&gt;(element); currentnode = null; } else currentnode = currentnode.leftNode; } else { if (currentnode.rightNode == null) { currentnode.rightNode = new Node&lt;&gt;(element); currentnode = null; } else currentnode = currentnode.rightNode; } } } } public boolean containsElement(Object e){ Objects.requireNonNull(e); Node&lt;T&gt; currentnode = new Node&lt;&gt;((T) e); return contains(currentnode); } private boolean contains(Node&lt;T&gt; node) { Objects.requireNonNull(node); Node&lt;T&gt; searchnode=null; Node&lt;T&gt; currentnode =root; while(searchnode==null &amp;&amp; currentnode!=null) { int value = compare(currentnode, node); if(value ==0) searchnode = currentnode; else if(value&lt;0) currentnode = currentnode.leftNode; else currentnode = currentnode.rightNode; } return searchnode !=null; } private int compare(Node&lt;T&gt; currentnode, Node&lt;T&gt; element) { Objects.requireNonNull(currentnode); Objects.requireNonNull(element); Objects.requireNonNull(comparator); return comparator.compare(element.element,currentnode.element); } private Node&lt;T&gt; getnode(T element) { Objects.requireNonNull(element); Node&lt;T&gt; node = new Node&lt;&gt;(element,null,null); Node&lt;T&gt; currentnode = root; while (currentnode!=null &amp;&amp; 0!= compare(currentnode,node)) { int value = compare(currentnode,node); if(value &lt;0) { currentnode = currentnode.leftNode; }else { currentnode = currentnode.rightNode; } } return currentnode; } private &lt;T&gt; Node&lt;T&gt; getpredecessoe(Node&lt;T&gt; node) { Node&lt;T&gt; predecessor = null; return predecessor; } public T getsuccessor(T element) { Objects.requireNonNull(element); var node = getnode(element); var successor = getsuccessor(node); if(successor!=null) return successor.element; return null; } private Node&lt;T&gt; getsuccessor(Node&lt;T&gt; node) { Node&lt;T&gt; successor = root; if(node.rightNode!=null) { successor = node.rightNode; while (successor.leftNode != null) { successor = successor.leftNode; } } else { successor = null; Node&lt;T&gt; cureentnode = root; while (cureentnode!= null &amp;&amp;0!= compare(cureentnode,node) ) { int compare = compare(cureentnode,node); if(compare &lt;=0){ successor = cureentnode; cureentnode = cureentnode.leftNode; } else cureentnode = cureentnode.rightNode; } } return successor; } public boolean deleteNode(T element) { var node =getnode(element); if(node== null) return false; if(node.leftNode ==null &amp;&amp; node.rightNode == null) unlinkNode(node); else if(node.leftNode!=null &amp;&amp; node.rightNode!=null) { var parent = getParent(node); var successor = getsuccessor(node); unlinkSuccessor(successor); successor.leftNode = node.leftNode; successor.rightNode = node.rightNode; linkSuccessorWithParent(parent,successor); } else { var parentNode = getParent(node); var childNode = node.leftNode!= null ? node.leftNode : node.rightNode; int compare = compare(parentNode,childNode); if(compare &lt;=0) parentNode.leftNode = childNode; else parentNode.rightNode = childNode; node = null; } return node == null; } private void linkSuccessorWithParent(Node&lt;T&gt; parent, Node&lt;T&gt; successor) { int compare = compare(parent,successor); if(compare&lt;=0) parent.leftNode = successor; else parent.rightNode = successor; } public void unlinkNode(Node&lt;T&gt; node) { var parent = getParent(node); Objects.requireNonNull(parent); Objects.requireNonNull(node); int compare = compare(parent,node); if(compare &lt;=0) parent.leftNode = null; else parent.rightNode = null; } private void unlinkSuccessor(final Node&lt;T&gt; successor) { var parent = getParent(successor); unlinkNode( successor); if(successor.rightNode != null) parent.leftNode = successor.rightNode; } private Node&lt;T&gt; getParent(Node&lt;T&gt; childnode) { var parentnode = root; var currentnode = root; Objects.requireNonNull(childnode); while (0!= compare(currentnode,childnode)) { parentnode = currentnode; int compare = compare(currentnode,childnode); if(compare&lt;0) currentnode = currentnode.leftNode; else if(compare &gt;0) currentnode = currentnode.rightNode; } return parentnode; } public void morrisTreewalk() { } private static class Node&lt;T&gt; { T element; Node&lt;T&gt; leftNode ; Node&lt;T&gt; rightNode; Node(T element, Node&lt;T&gt; leftNode, Node&lt;T&gt; rightNode) { this.element = element; this.leftNode = leftNode; this.rightNode = rightNode; } Node(T element) { this(element,null,null); } } } </code></pre> <p>Even though this data structure passes basic test cases I was not sure what will be the performance if the amount of input is high. Also, if there is any optimisation, please tell.</p>
[]
[ { "body": "<p>If you are using a binary search tree, you may want to \"balance\" it, so that the tree does not get too deep, and searches are fast.</p>\n\n<p>I suggest having a look at <a href=\"https://en.wikipedia.org/wiki/Tree_rotation\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Tree_rotation</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T15:25:57.707", "Id": "210979", "ParentId": "210977", "Score": "2" } }, { "body": "<p>In this answer I'll comment on things like style, robustness or API design, not analyzing your algorithm.</p>\n\n<pre><code>package com.solo.workouts.collections.Tree;\n</code></pre>\n\n<p>The uppercase package name <code>Tree</code> doesn't follow the Java naming conventions, and this will confuse any colleage that you might cooperate with. 99% of the Java folks follow these conventions, so any deviation irritates.</p>\n\n<pre><code>private Comparator comparator;\n</code></pre>\n\n<p>You surely got a warning from your IDE about using a raw type. This declaration can benefit from generics, so the compiler already checks that the comparator is capable of comparing objects of type T:</p>\n\n<pre><code>private Comparator&lt;? super T&gt; comparator;\n</code></pre>\n\n<p>You need a comparator that can compare objects of type T, e.g. if you want a <code>BinarySearchTree&lt;Double&gt;</code>, a <code>Comparator&lt;Double&gt;</code> or a <code>Comparator&lt;Number&gt;</code> will do, but a <code>Comparator&lt;String&gt;</code> won't. And that's what <code>&lt;? super T&gt;</code> says.</p>\n\n<pre><code>private BinarySearchTree(Comparator comparator , T type) { ... }\n</code></pre>\n\n<p>I'd delete this constructor. The <code>T type</code> argument has a confusing name (you have to pass a concrete instance of T and not a type like <code>Double.class</code>) and isn't used at all. Let the <code>private BinarySearchTree(Comparator comparator) { ... }</code> constructor directly do the work.</p>\n\n<pre><code>private BinarySearchTree(Comparator comparator) { ... }\n</code></pre>\n\n<p>As already said for the field, add the generics specification here:</p>\n\n<pre><code>private BinarySearchTree(Comparator&lt;? super T&gt; comparator) {\n</code></pre>\n\n<p>In the <code>add()</code> method, you have numerous places where you create a new node for the new element: <code>new Node&lt;&gt;(element)</code>. Especially the ones that you create just for the <code>compare()</code> call immediatelay after the comparison become garbage, and it happens repeatedly in the while loop. As all these nodes get exactly the same contents, it's enough to create one <code>Node</code> in the very beginning of the <code>add()</code> method, and use it in all the places instead of creation.</p>\n\n<p>You use <code>Objects.requireNonNull(e);</code> quite often, probably to avoid getting a NullPointerException later, deep inside some method call stack. Of course, this also throws a NullPointerException, but from a controlled place (I'm typically too lazy to do that). It would be even better to always add a descriptive text which variable was null.</p>\n\n<p>Consider rewriting the <code>contains()</code> method like this:</p>\n\n<pre><code>private boolean contains(Node&lt;T&gt; node) {\n Objects.requireNonNull(node);\n\n Node&lt;T&gt; currentnode = root;\n while(currentnode != null) {\n int value = compare(currentnode, node);\n\n if(value == 0) {\n return true;\n } else if(value &lt; 0) {\n currentnode = currentnode.leftNode;\n } else {\n currentnode = currentnode.rightNode;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>I'm using an early return nested inside the <code>while</code> and <code>if</code> constructs. Some developers don't like that, but I think it makes the code clearer. But it's a metter of taste.</p>\n\n<p>And I added curly braces, which I highly recommend to always do. It's too easy to think you can add a second statement to dependent block, but without the braces it's just one conditional statement, and the next one will be executed unconditionally.</p>\n\n<p>One hint on formatting: your formatting is somewhat inconsistent. You're probably formatting your code by hand. IDEs like Eclipse have automated formatting tools, e.g. Ctrl-I corrects the indentation of the block you marked in the source file, and Ctrl-Shift-F completely reformats the code. Very useful, makes formatting easy.</p>\n\n<p>Documentation: for such a general-use class, you should write Javadocs for the public constructors and methods. Your IDE will create the boilerplate, and you have to write down what the methods and their arguments do (not how they do it). Have a look at the Java API specification to get an idea of rather good Javadocs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T17:54:40.207", "Id": "210985", "ParentId": "210977", "Score": "2" } }, { "body": "<p>Java uses camelCasing. Every word after the first (or including the first if it's a class name) should be a capital. This make names easier to read, since it's clearer where the words start and end. All your names should follow this convention. For example: <code>getSuccessor</code> and <code>getNode</code>. You use proper camel casing in a couple places, but you're inconsistent.</p>\n\n<hr>\n\n<p>Be more careful with your spacing.</p>\n\n<pre><code>while (currentnode!=null &amp;&amp; 0!= compare(currentnode,node)) {\n</code></pre>\n\n<p>has a lot of inconsistent style that's making it harder to read than necessary. Putting spaces around operators is the cleanest way to go in my opinion. I also prefer to add spaces after commas:</p>\n\n<pre><code>while (currentnode != null &amp;&amp; 0 != compare(currentnode, node)) {\n</code></pre>\n\n<p>Just be consistent.</p>\n\n<hr>\n\n<p>While your indentation for <code>containsElement</code> is poor, the idea behind the function is good. You've put most of the logic away in a general function <code>contains</code> that could be reused elsewhere if needed, then just delegate to it in <code>containsElement</code>. This is much better than the alternative of duplicating logic.</p>\n\n<hr>\n\n<hr>\n\n<p>Overall, there's nothing glaringly wrong with your logic, but your code is quite messy. You should practice making sure that your code is readable, for your own and other's sake. Have more consistent spacing after methods and <code>if</code> lines, ensure that your indentation is correct, and make sure your spacing around operators is less haphazard. Ideally, I should be able to glance at your code and \"break it down\" in my head easily using spacing alone. That's not as possible when there isn't a convention that can be relied on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T21:03:55.337", "Id": "210994", "ParentId": "210977", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T14:08:09.450", "Id": "210977", "Score": "3", "Tags": [ "java", "tree", "generics" ], "Title": "Generic implementation of binary search tree in Java" }
210977
<p>I want to make fizzbuzz method return the resolved value and then pass it to println!. Been having quite a problem with &amp;str vs String. Wanted to use &amp;str as return value as it's immutable so I tought it fit nicely though I couldn't get it right.</p> <p>Here is my String impl:</p> <pre><code>fn main() { let ss = "FizzBuzz"; for i in 1..100 { println!("{}", fizzbuzz(i)) } } fn fizzbuzz(value: i32) -&gt; String { return match (value % 3, value % 5) { (0, 0) =&gt; "FizzBuzz".into(), (0, _) =&gt; "Fizz".into(), (_, 0) =&gt; "Buzz".into(), (_, _) =&gt; value.to_string() }; } </code></pre> <p>Is there a way to make it simpler without calling straight <code>println!("Fizzbuzz")</code> and so on?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:04:43.333", "Id": "407877", "Score": "0", "body": "This code is very \"simple\" to me. Can you define what would make it \"simpler\" to you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:07:34.140", "Id": "407878", "Score": "0", "body": "Please also read https://stackoverflow.com/questions/43079077/proper-way-to-return-a-new-string-in-rust" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:08:13.150", "Id": "407879", "Score": "0", "body": "I don't like those into() calls - it seems as it's unnecessary but can't find a way to do that properly. Also would prefer to use &str instead of mutable String as I'm not gonna change that return value - just want to print it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:10:47.077", "Id": "407880", "Score": "1", "body": "See also [Simplest way to write FizzBuzz in Rust](https://codereview.stackexchange.com/questions/127485/simplest-way-to-write-fizzbuzz-in-rust)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:12:21.593", "Id": "407881", "Score": "2", "body": "See also [FizzBuzz in Rust](https://chrismorgan.info/blog/rust-fizzbuzz.html)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:13:24.533", "Id": "407882", "Score": "2", "body": "And that's not how &str vs String works" } ]
[ { "body": "<blockquote>\n <p>Wanted to use &amp;str as return value as it's immutable</p>\n</blockquote>\n\n<p>That is not possible because the function may produce a new, owned string out of <code>value</code>, in this line:</p>\n\n<pre><code> (_, _) =&gt; value.to_string()\n</code></pre>\n\n<p>All other match arms could return a <code>&amp;'static str</code> since they are string literals, but the output of this one is a <code>String</code>. And the fact that you will not mutate the string doesn't change things here, because a new string needs to be constructed anyway.</p>\n\n<p>For cases where a value may either borrow or own the data, you may consider using a <a href=\"https://doc.rust-lang.org/stable/std/borrow/enum.Cow.html\" rel=\"noreferrer\"><code>Cow</code></a>.</p>\n\n<pre><code>fn fizzbuzz(value: i32) -&gt; Cow&lt;'static, str&gt; {\n match (value % 3, value % 5) {\n (0, 0) =&gt; \"FizzBuzz\".into(),\n (0, _) =&gt; \"Fizz\".into(),\n (_, 0) =&gt; \"Buzz\".into(),\n (_, _) =&gt; value.to_string().into()\n }\n}\n</code></pre>\n\n<p>This function will be slightly more efficient memory-wise: the first three guards will return a borrowed static string (<code>Cow::Borrowed</code>), whereas the last one will own a string (<code>Cow::Owned</code>). The <code>.into()</code> calls are necessary for the conversion from the base type (either <code>&amp;str</code> or <code>String</code>) to a <code>Cow</code>.</p>\n\n<p>Other issues:</p>\n\n<ul>\n<li><code>return</code> statements at the end of a function are redundant. You can just write the expression without a semi-colon at the end.</li>\n<li>you are not using the variable <code>ss</code> in <code>main</code>.</li>\n<li>although entirely subjective, <code>u32</code> may be used instead of <code>i32</code> when negative numbers are never considered in your program logic.</li>\n</ul>\n\n<blockquote>\n <p>Is there a way to make it simpler without calling straight <code>println!(\"Fizzbuzz\")</code> and so on?</p>\n</blockquote>\n\n<p>Other than the given suggestions, I'm afraid that the given code appears simple and readable enough. That function does not hold a very complex logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T20:12:41.103", "Id": "210992", "ParentId": "210989", "Score": "6" } } ]
{ "AcceptedAnswerId": "210992", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T19:33:51.897", "Id": "210989", "Score": "0", "Tags": [ "rust", "fizzbuzz" ], "Title": "FizzBuzz in Rust" }
210989
<p>I have solved <a href="https://www.hackerrank.com/challenges/attribute-parser/problem" rel="nofollow noreferrer">a task</a> which takes input in a unique markup language. In this language each element consists of a starting and closing tag. Only starting tags can have attributes. Each attribute has a corresponding name and value.</p> <p>For example:</p> <pre><code>&lt;tag-name attribute1-name = "Value" attribute2-name = "Value2" ... &gt; </code></pre> <p>A closing tag follows this format:</p> <pre><code>&lt;/tag-name&gt; </code></pre> <p>The tags may also be nested. For example:</p> <pre><code>&lt;tag1 value = "HelloWorld"&gt; &lt;tag2 name = "Name1"&gt; &lt;/tag2&gt; &lt;/tag1&gt; </code></pre> <p>Attributes are referenced as:</p> <pre><code>tag1~value tag1.tag2~name </code></pre> <p>The source code of the markup language is given in <code>n</code> lines of input, the number of attribute references or queries is <code>q</code>.</p> <p>I am seeking any improvements to my code and any bad practices I may be using.</p> <pre><code> #include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; typedef vector &lt; string &gt; VS; typedef vector &lt; VS &gt; VVS; //Takes numberOfLines of input and splits the lines into strings VS Split(int numberOfLines) { VS myVec; string x; for (int i = 0; i &lt; numberOfLines; i++) { getline(cin, x); string::size_type start = 0; string::size_type end = 0; while ((end = x.find(" ", start)) != string::npos) { myVec.push_back(x.substr(start, end - start)); start = end + 1; } myVec.push_back(x.substr(start)); } return myVec; } //removes unnecessary characters in this case they are: " , // &gt; (if it is the final element of the tag), and " string Remove(string s) { string c = s; c.erase(c.begin()); auto x = c.end() - 1; if ( * x == '&gt;') { c.erase(x); x = c.end() - 1; } c.erase(x); return c; } int main() { VS HRML, attributes, values, t, validTags; VVS Tags, ValidAttributes, ValidValues; int n, q; cin &gt;&gt; n &gt;&gt; q; HRML = Split(n); //does the heavy lifting for (int i = 0; i &lt; HRML.size(); i++) { string x = HRML[i]; //checks if x contains the beginning of the starting tag if (x[0] == '&lt;' &amp;&amp; x[1] != '/') { //checks if x contains the end of the starting tag if (x[x.size() - 1] == '&gt;' &amp;&amp; x[1] != '/') { ValidAttributes.push_back(attributes); attributes.clear(); ValidValues.push_back(values); values.clear(); } auto c = x.end() - 1; if ( * c == '&gt;') { x.erase(c); } x.erase(x.begin()); t.push_back(x); Tags.push_back(t); } // checks if x contains the end of the starting tag if (x[x.size() - 1] == '&gt;' &amp;&amp; x[1] != '/') { ValidAttributes.push_back(attributes); attributes.clear(); ValidValues.push_back(values); values.clear(); } //checks if x contains the ending tag else if (x[1] == '/') { x.erase(x.begin()); x.erase(x.begin()); x.erase(x.end() - 1); for (int i = 0; i &lt; t.size(); i++) { if (x == t[i]) { t.erase(t.begin() + i); } } } //checks to see if an attribute has been assigned a value else if (x == "=") { attributes.push_back(HRML[i - 1]); values.push_back(Remove(HRML[i + 1])); } } string x = ""; //makes valid(user-usable) tags from all the tags // passed into vector&lt;string&gt; Tags for (int i = 0; i &lt; Tags.size(); i++) { for (int j = 0; j &lt; Tags[i].size(); j++) { if (Tags[i].size() &gt; 1) { string begin = Tags[i][j] + '.'; x += begin; if (j == (Tags[i].size() - 1)) { x.erase(x.end() - 1); validTags.push_back(x + '~'); x = ""; } } else { validTags.push_back(Tags[i][0] + '~'); } } } //iterates through each query given by the user and checks if it is valid for (int i = 0; i &lt; q + 1; i++) { string output = ""; if (i == 0) { string x; getline(cin, x); } else { string x; getline(cin, x); int c = 0; for (int j = 0; j &lt; validTags.size(); j++) { for (int p = 0; p &lt; ValidAttributes[c].size(); p++) { if (x == validTags[j] + ValidAttributes[c][p]) { output = ValidValues[c][p]; /*if a valid attribute reference has been found then there is no need to check the rest of validAttribute[c] */ goto endOfLoop; } else { output = "Not Found!"; } } if (c &lt; (ValidAttributes.size() - 1)) { c++; } } endOfLoop: cout &lt;&lt; output &lt;&lt; endl; } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T21:29:48.070", "Id": "407885", "Score": "0", "body": "You could use Yacc to generate the parser, rather than use custom error-prone parsing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T21:31:14.817", "Id": "407887", "Score": "3", "body": "This was just a task I decided to do for fun." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:37:06.867", "Id": "408021", "Score": "1", "body": "You have a `goto` in your code. Most coding standards consider this bad just by itself. I would consider it bad only if you can't justify it. But there is no comment explaining why you need a goto." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:38:30.183", "Id": "408022", "Score": "0", "body": "Your indentation is horrible and makes the code nearly unreadable. I'll come back and review it if you fix the indentation. But otherwise I'll just ignore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:23:04.690", "Id": "408040", "Score": "0", "body": "@MartinYork I have re-formatted the code. If it is sill unreadable, please let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T10:58:34.300", "Id": "408330", "Score": "1", "body": "It looks like your input is well-formed XML, in which case you could use one of the many XML parsers that are available instead of creating your own from scratch." } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Don't abuse <code>using namespace std</code></h2>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid.</p>\n<h2>Be careful with signed and unsigned</h2>\n<p>In multiple places in this code an <code>int</code> <code>i</code> with an unsigned <code>size_t</code> returned from <code>size()</code>. It would be better to declare <code>i</code> to also be <code>size_t</code>.</p>\n<h2>Use all of the required <code>#include</code>s</h2>\n<p>The type <code>std::string</code> is used but its declaration is in <code>#include &lt;string&gt;</code> which is not actually in the list of includes.</p>\n<h2>Prefer <code>using</code> over <code>typedef</code></h2>\n<p>When you make more use of templates, you will likely encounter the reason many people prefer <code>using</code> over <code>typedef</code> in modern C++. So your declarations become:</p>\n<pre><code>using VS = std::vector&lt;std::string&gt;;\nusing VVS = std::vector&lt;VS&gt;;\n</code></pre>\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rt-using\" rel=\"nofollow noreferrer\">T.43</a> for details.</p>\n<h2>Use &quot;range <code>for</code>&quot; and simplify your code</h2>\n<p>The code currently uses this:</p>\n<pre><code>for (int i = 0; i &lt; HRML.size(); i++) {\n string x = HRML[i];\n</code></pre>\n<p>There is a much simpler and more efficient way to do this:</p>\n<pre><code>for (auto x : HRML) {\n</code></pre>\n<p>This won't work without further modification to the details of the loop, but for help on that, see the next suggestion.</p>\n<h2>Use a state machine</h2>\n<p>The logic of this code could be expressed as a state machine. If that were done, one could process the stream &quot;on the fly&quot; character at a time with little difficulty.</p>\n<h2><code>goto</code> still considered harmful</h2>\n<p>Generally speaking, the use of <code>goto</code> is not recommended. Using it as you have, for breaking out nested loops is about the only accepted use. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-goto\" rel=\"nofollow noreferrer\">ES.76</a> for details. In this case, however, you can avoid it entirely as shown in the next suggestion.</p>\n<h2>Use appropriate data structures</h2>\n<p>The use of vectors of vectors of strings is not a very efficient structure for this program. I would suggest that using an <code>unordered_map</code> would be a better choice and would allow you change the convoluted triple loop at the end of the program to this:</p>\n<pre><code>for(std::string query; q &gt; 0 &amp;&amp; std::getline(std::cin, query); --q) {\n auto search = tagValue.find(query);\n if (search == tagValue.end()) {\n std::cout &lt;&lt; &quot;Not Found!\\n&quot;;\n } else {\n std::cout &lt;&lt; search-&gt;second &lt;&lt; '\\n';\n }\n}\n</code></pre>\n<h2>Parse input carefully</h2>\n<p>On my machine, your posted code segfaulted and crashed when run with the sample input provided at the code challenge site. The reason is that this code is not reading input correctly. Specifically, after this line:</p>\n<pre><code>std::cin &gt;&gt; n &gt;&gt; q;\n</code></pre>\n<p>there is still a newline character in the input stream. Get rid of it like this:</p>\n<pre><code>constexpr std::size_t maxlinelen{200};\nstd::cin.ignore(maxlinelen, '\\n');\n</code></pre>\n<p>The value of <code>maxlinelen</code> is from the problem description, but generically one could use this:</p>\n<pre><code>std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n');\n</code></pre>\n<p>Also, this line is not safe because it assumes that there are at least two characters in the string, which isn't guaranteed.</p>\n<pre><code>if (x[0] == '&lt;' &amp;&amp; x[1] != '/') {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-04T14:50:05.960", "Id": "247476", "ParentId": "210995", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T21:19:28.187", "Id": "210995", "Score": "3", "Tags": [ "c++", "parsing", "reinventing-the-wheel" ], "Title": "C++ program that processes unique markup language similar to HTML" }
210995
<p>Decided to make a small C# console based rhythm game finger trainer with lots of user definable options. I'm very much a beginning programmer, so thought I might learn a lot from it. Especially when you guys could give me some advice.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Runtime.InteropServices; using System.Media; using System.IO; namespace _10kTrainer2point0 { class Program { [DllImport("user32.dll")] public static extern bool ShowWindow(System.IntPtr hWnd, int cmdShow); static Random rnd = new Random(); static void Shuffle&lt;T&gt;(T[] array) { int n = array.Length; for (int i = 0; i &lt; n; i++) { int r = i + rnd.Next(n - i); T t = array[r]; array[r] = array[i]; array[i] = t; } } static void Main() { //assiging of the variables bool check = true; bool displayKeybinds = true; bool repeatOnce = true; string strTemp = String.Empty; string strTemp2 = String.Empty; string noteAmount = String.Empty; string soundEffect = String.Empty; string answer = String.Empty; string[] strArrTemp; List&lt;string&gt; strListTemp = new List&lt;string&gt;(); int keyAmount = 0; int intNoteAmount = 0; int score = 0; int[] numbers; List&lt;int&gt; notePositions = new List&lt;int&gt;(); List&lt;ConsoleKeyInfo&gt; keyBinds = new List&lt;ConsoleKeyInfo&gt;(); List&lt;ConsoleColor&gt; noteColors = new List&lt;ConsoleColor&gt;(); ConsoleColor backgroundColor = ConsoleColor.Black; Process p = Process.GetCurrentProcess(); System.Media.SoundPlayer player = new SoundPlayer(); //makes the console the size of the screen ShowWindow(p.MainWindowHandle, 3); Thread.Sleep(25); //if the settings files already exist, read them and assign the variables to them. Otherwise go trough the settings methodes if (File.Exists(Environment.CurrentDirectory + "\\settings\\values.txt") &amp;&amp; File.Exists(Environment.CurrentDirectory + "\\settings\\keyBinds.txt") &amp;&amp; File.Exists(Environment.CurrentDirectory + "\\settings\\noteColors.txt")) { //reads values.txt which has "keyAmount", "noteAmount" and "soundEffect" in it strListTemp = System.IO.File.ReadAllLines(Environment.CurrentDirectory + "\\settings\\values.txt").ToList(); keyAmount = Convert.ToInt16(strListTemp[0]); noteAmount = strListTemp[1]; soundEffect = strListTemp[2]; //reads keyBinds.txt, converts the lines to ConsoleKeyInfos and adds them to ConsoleKeyInfo List keyBinds strListTemp = System.IO.File.ReadAllLines(Environment.CurrentDirectory + "\\settings\\keyBinds.txt").ToList(); for (int i = 0; i &lt; keyAmount; i++) { strTemp = strListTemp[i]; strArrTemp = strTemp.Split(' '); strTemp = strArrTemp[0]; strTemp2 = strArrTemp[1]; keyBinds.Add(new ConsoleKeyInfo(Convert.ToChar(strTemp), (ConsoleKey)Enum.ToObject(typeof(ConsoleKey), Convert.ToInt16(strTemp2)), false, false, false)); } //reads noteColors.txt converts the colors to ConsoleColors and adds them to ConsoleColor List noteColors strListTemp = System.IO.File.ReadAllLines(Environment.CurrentDirectory + "\\settings\\noteColors.txt").ToList(); for (int i = 0; i &lt; strListTemp.Count; i++) { noteColors.Add((ConsoleColor)Enum.Parse(typeof(ConsoleColor), strListTemp[i])); } } else { //goes trough most settings keyAmountMethode(check, strTemp, ref keyAmount); keyBindMethode(ref keyBinds, keyAmount, check, answer, repeatOnce); noteAmountMethode(check, ref noteAmount, keyAmount); soundEffectMethode(check, ref soundEffect, player, answer); noteColorMethode(keyAmount, strTemp, ref noteColors, backgroundColor); valuesToFile(keyAmount, noteAmount, soundEffect, strListTemp); keyBindsToFile(keyBinds, strListTemp); noteColorsToFile(noteColors, strListTemp); } //makes a list with jumps of 5 notePositions.Add(0); for (int i = 0; i &lt; keyAmount; i++) { notePositions.Add(notePositions[i]+5); } //makes a list of numbers (0, 1, 2,...) numbers = Enumerable.Range(0, keyAmount).ToArray(); if (soundEffect != "silent") { player = new System.Media.SoundPlayer(soundEffect); } //if noteAmount is not "random" then intNoteAmount will be assigned to it. //I need this because when it is, I need a different variable to not overwrite the text "random" if (noteAmount != "random") { intNoteAmount = Convert.ToInt16(noteAmount); } //the main program, that loops everytime certain keys corresponding to the keybinds with the indexes of the scrambled list numbers are pressed while (true) { Console.Clear(); if (noteAmount == "random") { intNoteAmount = rnd.Next(1, keyAmount); } //displays the keybinds underneath the keys for reference if (displayKeybinds) { for (int i = 0; i &lt; keyAmount; i++) { Console.SetCursorPosition(notePositions[i] + 2, 27); Console.Write(keyBinds[i].Key); } } check = true; Console.SetCursorPosition(0, 0); //displays the keybinds to change settings Console.WriteLine("1 - Change the key amount\n" + "2 - Change the key binds\n" + "3 - Change the note amount\n" + "4 - Change the sound effect\n" + "5 - Change the note colors\n" + "6 - Change the background color\n" + "7 - Toggle the keybind display"); Console.SetCursorPosition(Console.WindowWidth / 2 - 7, Console.WindowHeight / 2 - 20); //displays the score(amount of times, notes have been pressed correctly) Console.WriteLine("Score: " + score++); //this schuffle makes so random notes\keybinds get chosen every loop Shuffle(numbers); //notes are basically spaces with a position and a bg color //here the amount given by the user (noteAmount) are created for (int i = 0; i &lt; intNoteAmount; i++) { Console.SetCursorPosition(notePositions[numbers[i]], 25); Console.BackgroundColor = noteColors[numbers[i]]; Console.Write(" "); } Console.WriteLine(); //checks if the right keybinds are pressed (key by key, because I couldn't find any better way) for (int i = 0; i &lt; intNoteAmount; i++) { Console.BackgroundColor = backgroundColor; while (!(keyBinds[numbers[i]].Key == Console.ReadKey(true).Key)) { //this is the only while loop in the main loop, so here I check if the keybinds to change settings are pressed if (Console.ReadKey().Key == ConsoleKey.D1) { //different settings need a different amount of changes. If the user wan't to change the key amount, he will have to change a lot of other settings as well keyAmountMethode(check, strTemp, ref keyAmount); keyBindMethode(ref keyBinds, keyAmount, check, answer, repeatOnce); noteColorMethode(keyAmount, strTemp, ref noteColors, backgroundColor); numbers = Enumerable.Range(0, keyAmount).ToArray(); valuesToFile(keyAmount, noteAmount, soundEffect, strListTemp); keyBindsToFile(keyBinds, strListTemp); noteColorsToFile(noteColors, strListTemp); } else if (Console.ReadKey().Key == ConsoleKey.D2) { keyBindMethode(ref keyBinds, keyAmount, check, answer, repeatOnce); keyBindsToFile(keyBinds, strListTemp); } else if (Console.ReadKey().Key == ConsoleKey.D3) { noteAmountMethode(check, ref noteAmount, keyAmount); if (noteAmount != "random") { intNoteAmount = Convert.ToInt16(noteAmount); } valuesToFile(keyAmount, noteAmount, soundEffect, strListTemp); } else if (Console.ReadKey().Key == ConsoleKey.D4) { soundEffectMethode(check, ref soundEffect, player, answer); if (soundEffect != "silent") { player = new System.Media.SoundPlayer(soundEffect); } valuesToFile(keyAmount, noteAmount, soundEffect, strListTemp); } else if (Console.ReadKey().Key == ConsoleKey.D5) { noteColorMethode(keyAmount, strTemp, ref noteColors, backgroundColor); noteColorsToFile(noteColors, strListTemp); } else if (Console.ReadKey().Key == ConsoleKey.D6) { bakcgroundColorMethode(check, ref backgroundColor, strTemp); for (int I = 0; i &lt; noteColors.Count; i++) { if (noteColors[i] == backgroundColor) { check = false; } } if (!check) { noteColorMethode(keyAmount, strTemp, ref noteColors, backgroundColor); } } else if (Console.ReadKey().Key == ConsoleKey.D7) { if (displayKeybinds) { displayKeybinds = false; } else { displayKeybinds = true; } } } } //if the right keys are pressed and soundEffect is not "silent", a sound effect will play if (soundEffect != "silent") { player.Play(); } } } //the next methodes are the user assigned settings, most have if statements with bool checks that loop untill the input is valid static void keyAmountMethode(bool check, string strTemp, ref int keyAmount) { Console.Clear(); while (check) { //assigns keyAmount Console.WriteLine("How many keys do you play with? \"1-20\""); strTemp = Console.ReadLine().ToLower(); //if it is between 1 and 20 if (strTemp != "" &amp;&amp; strTemp.All(char.IsDigit) &amp;&amp; Convert.ToInt32(strTemp) &gt;= 1 &amp;&amp; Convert.ToInt32(strTemp) &lt;= 20) { keyAmount = Convert.ToInt16(strTemp); check = false; } else { Console.Clear(); Console.WriteLine("The input was invalid!"); } } Console.Clear(); } static void keyBindMethode(ref List&lt;ConsoleKeyInfo&gt; keyBinds, int keyAmount, bool check, string answer, bool repeatOnce) { Console.Clear(); bool repeatKeyBinder = true; while (repeatKeyBinder) { //adds keys to keyBinds untill it has the same amount as keyAmount because every keybind should represent a key Console.WriteLine("What are your preffered keybinds?"); for (int i = 0; i &lt; keyAmount; i++) { Console.WriteLine("\nKey" + (i + 1) + ":"); keyBinds.Add(Console.ReadKey()); Console.SetCursorPosition(0, i * 2 + 2); Console.Write(new string(' ', Console.WindowWidth)); Console.Write(keyBinds[i].Key); } //asks if the keybinds are right while still displaying them and repeats the binding if they are not while (check) { //repeat once is so "Are these keybinds correct?" and "The input was invalid!" aren't spammed if (repeatOnce) { Console.WriteLine("\n\nAre these keybinds correct? \"yes\" or \"no\""); Console.SetCursorPosition(0, keyAmount * 2 + 5); } answer = Console.ReadLine().ToLower(); Console.SetCursorPosition(0, keyAmount * 2 + 5); Console.Write(new string(' ', Console.WindowWidth)); if (answer == "yes" || answer == "no") { check = false; } else { if (repeatOnce) { Console.SetCursorPosition(0, keyAmount * 2 + 4); Console.WriteLine("The input was invalid!"); repeatOnce = false; } } } check = true; if (answer == "yes") { repeatKeyBinder = false; } else { //if the keybinding is repeated, keyBinds should be reset keyBinds = new List&lt;ConsoleKeyInfo&gt;(); } repeatOnce = true; Console.Clear(); } } static void noteAmountMethode(bool check, ref string noteAmount, int keyAmount) { Console.Clear(); while (check) { //assigns noteAmount (the amount of 'notes' displayed simultanieusly\the amount of keys to press) Console.WriteLine("How many notes should come on the screen simultaneously? \"equal or lower to your key amount\" or \"random\""); noteAmount = Console.ReadLine().ToLower(); //if its "random" or between 1 and keyAmount if (noteAmount == "random" || noteAmount != "" &amp;&amp; noteAmount.All(char.IsDigit) &amp;&amp; Convert.ToInt32(noteAmount) &gt;= 1 &amp;&amp; Convert.ToInt32(noteAmount) &lt;= keyAmount) { check = false; } else { Console.Clear(); Console.WriteLine("The input was invalid!"); } } Console.Clear(); } static void soundEffectMethode(bool check, ref string soundEffect, System.Media.SoundPlayer player, string answer) { Console.Clear(); bool previeuw = true; while (check) { //assigns soundEffect Console.WriteLine("What sound effect would you like to hear? \"clap\", \"drop\", \"pop\", \"tik\" or \"silent\""); soundEffect = Console.ReadLine().ToLower(); if (soundEffect == "clap" || soundEffect == "drop" || soundEffect == "pop" || soundEffect == "tik") { soundEffect = Environment.CurrentDirectory + "\\sounds\\" + soundEffect + ".wav"; check = false; } else if (soundEffect == "silent") { check = false; previeuw = false; } else { Console.Clear(); Console.WriteLine("The input was invalid!"); } } Console.Clear(); check = true; //asks if the user wants to hear it while (previeuw) { Console.WriteLine("Would you like a previeuw of the sound effect? \"yes\" or \"no\""); answer = Console.ReadLine().ToLower(); if (answer == "yes" || answer == "no") { previeuw = false; } else { Console.Clear(); Console.WriteLine("The input was invalid!"); } } Console.Clear(); previeuw = true; //if so, asks the user if he wants to keep it(ends the methode) or not(repeats the methode) if (answer == "yes") { player = new System.Media.SoundPlayer(soundEffect); player.Play(); while (check) { Console.WriteLine("Would you like to keep this sound effect? \"yes\" or \"no\""); answer = Console.ReadLine().ToLower(); if (answer == "yes" || answer == "no") { check = false; } else { Console.Clear(); Console.WriteLine("The input was invalid!"); } } check = true; if (answer == "no") { soundEffectMethode(check, ref soundEffect, player, answer); } } Console.Clear(); } static void noteColorMethode(int keyAmount, string strTemp, ref List&lt;ConsoleColor&gt; noteColors, ConsoleColor backgroundColor) { Console.Clear(); Console.WriteLine("What are your preffered note colors? for example \"Blue\" or \"DarkGray\""); //adds colors to noteColors for (int i = 0; i &lt; keyAmount; i++) { Console.WriteLine("\nNote" + (i + 1) + ":"); strTemp = Console.ReadLine(); if (Enum.TryParse(strTemp, out ConsoleColor result) &amp;&amp; strTemp != Convert.ToString(backgroundColor)) { noteColors.Add((ConsoleColor)Enum.Parse(typeof(ConsoleColor), strTemp)); } else { Console.Clear(); i--; Console.WriteLine("What are your preffered note colors? for example \"Blue\" or \"DarkGray\""); Console.WriteLine("The input was invalid!"); } } Console.Clear(); } static void bakcgroundColorMethode(bool check, ref ConsoleColor backgroundColor, string strTemp) { //changes the backgroundcolor Console.Clear(); while (check) { Console.WriteLine("What color do you want the background to have? \"Blue\" or \"DarkGray\""); strTemp = Console.ReadLine().ToLower(); if (Enum.TryParse(strTemp, out ConsoleColor result) &amp;&amp; strTemp != "White" &amp;&amp; strTemp != "Red") { backgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), strTemp); Console.BackgroundColor = backgroundColor; check = false; } else { Console.Clear(); Console.WriteLine("The input was invalid!"); } } Console.Clear(); } //these methodes save most of the settings to text files static void valuesToFile(int keyAmount, string noteAmount, string soundEffect, List&lt;string&gt; strListTemp) { strListTemp = new List&lt;string&gt;(); strListTemp = new List&lt;string&gt; { Convert.ToString(keyAmount), noteAmount, soundEffect }; System.IO.File.WriteAllLines(Environment.CurrentDirectory + "\\settings\\values.txt", strListTemp); } static void keyBindsToFile(List&lt;ConsoleKeyInfo&gt; keyBinds, List&lt;string&gt; strListTemp) { strListTemp = new List&lt;string&gt;(); for (int i = 0; i &lt; keyBinds.Count; i++) { //ConsoleKeyInfos need a .KeyChar, the value of a .Key and modifiers, but I want the modifiers to always be false, so I don't need to save them strListTemp.Add(Convert.ToString(keyBinds[i].KeyChar) + " " + Convert.ToString((int)keyBinds[i].Key)); } System.IO.File.WriteAllLines(Environment.CurrentDirectory + "\\settings\\keyBinds.txt", strListTemp); } static void noteColorsToFile(List&lt;ConsoleColor&gt; noteColors, List&lt;string&gt; strListTemp) { strListTemp = new List&lt;string&gt;(); for (int i = 0; i &lt; noteColors.Count; i++) { strListTemp.Add(Convert.ToString(noteColors[i])); } System.IO.File.WriteAllLines(Environment.CurrentDirectory + "\\settings\\noteColors.txt", strListTemp); } } } </code></pre> <p>Especially the performance of the check if every right key is pressed is not too great. It works but you have to be precise. If anything is unclear, be sure to give me a comment. I would be thankful for every tip you guys can throw at me.</p>
[]
[ { "body": "<p>Here's a few of the things I noticed:</p>\n\n<p>Start learning OOP(Object Oriented Programming). The .net library and the languages that use it are designed to follow OOP. With that in mind, the game itself should be in a separate class and many of your functions can be broken down into smaller ones.</p>\n\n<p>The file names. You are concatenating them on the fly each time you need one, which is at least twice for each one. Put them in variables and concatenate them once.</p>\n\n<p>Try to get into the habit of using the interpolation operator(<code>$</code>) to concatenate strings. It is much easier to use and maintain.</p>\n\n<p>The block to check which key is pressed is at best kludgy. I'm surprised it even works. You're checking the console for a new key press on each condition that you're checking for. It seems to me it would make more sense to store a key press then check it against each condition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T15:54:53.890", "Id": "211116", "ParentId": "210996", "Score": "3" } }, { "body": "<p>A small contribution. I noticed that you would have blocks of code like this...</p>\n\n<pre><code>if (File.Exists(\"settings.txt\")\n{\n string settings = System.IO.File.ReadAllLines(\"settings.txt\");\n ...\n}\n</code></pre>\n\n<p>I'm quite a big hater of nesting, if it can be avoided so I would suggest to do it this way instead</p>\n\n<pre><code>// check to see if the file exists. If not, throw an exception.\nif (!File.Exists(\"settings.txt\") throw new Exception(\"The settings file could not be found.\");\n\n// grab the contents of the file\nstring setttings = System.IO.File.ReadAllLines(\"settings.txt\");\n</code></pre>\n\n<p>I would also continue on this block and say that you should notj just blindly accept the contents of the <code>settings.txt</code> file and you should always lean towards not trusting external input, especially if it has the opportunity to be tampered with (like in this case a malformed settings file).</p>\n\n<p>At the bare minimum you can do</p>\n\n<pre><code>// check if the settings file is empty\nif (String.IsNullOrEmpty(settings) throw new Exception(\"The settings file is empty.\");\n</code></pre>\n\n<p>In order to reduce the complexity of dealing with formatting, parsing and validation there are plenty of string formats to represent objects and configurations (JSON, XML, INF, etc)</p>\n\n<ul>\n<li>INF has been a long standing \"Windows\" format</li>\n<li>XML is basically frowned upon these days but used to be very popular</li>\n<li>JSON is becoming very popular (I would recommend to go with this at a beginner level)</li>\n</ul>\n\n<p>Just as an example the string would appear like</p>\n\n<pre><code>\"Settings\":\n{\n \"Console\":\n {\n \"ForegroundColor\": \"Grey\",\n \"BackgroundColor\": \"Black\",\n \"Encoding\": \"UTF-8\"\n }\n \"Game\":\n {\n \"Difficulty\": 10.5,\n \"Autosave\": false\n }\n}\n</code></pre>\n\n<p>and this would be very easily turned into an object in C# (just grab the library for it), which would then allow you write easy to read code like so...</p>\n\n<pre><code>boolean autosave = settings.Game.Autosave;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T23:27:35.580", "Id": "211230", "ParentId": "210996", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T21:32:28.750", "Id": "210996", "Score": "2", "Tags": [ "c#", "beginner", "game", "console", "audio" ], "Title": "Rhythm game finger trainer" }
210996
<p>Below is a piece of code that uses <strong>a promise for sending a request</strong> to a server, and to <strong>wait for an answer</strong>. Under normal conditions the server will always respond immediately, </p> <p>But of course you don't want your code to be stuck forever if a response is missed (e.g. a network issue). So for that reason, <strong>it needs a timeout</strong> as well.</p> <p>I usually write this as follows. But it takes quiet a lot of code. Any sugestions ?</p> <pre><code>new Promise( (resolve, reject) =&gt; { // the promise is resolved when a predefined response is received. const listener = (msg) =&gt; { const { command } = msg; if (command === "pong") resolve(); }; try { this.addListener(listener); // write the command this.sendMessage( { command: "ping" }); // there should be an answer within x seconds await new Promise(() =&gt; setTimeout(reject, timeout)); } finally { this.removeListener(listener); } } </code></pre> <p>I have been using this as a pattern for nodejs, angular and react code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:36:04.947", "Id": "407936", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Next time, don't leave anything out. Not a good tactic at Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:38:19.917", "Id": "407938", "Score": "0", "body": "@Mast, So, yeah, so we leave the bug in it ? - And I make a duplicate question without the bug ? Is that what you are proposing (it seems kind of silly)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:40:58.317", "Id": "407939", "Score": "1", "body": "That wouldn't be a duplicate question, but a follow-up. It might be silly, but the alternative is creating a mess of no-longer applicable answers to multiple states of the same question. We can't have that." } ]
[ { "body": "<p><code>await</code> is only applicable in <code>async</code> functions. The executor function passed to <code>Promise</code> constructor at the code at the question is not defined as <code>async</code>. </p>\n\n<p>The second <code>Promise</code> constructor is not necessary. <code>resolve</code> and <code>reject</code> defined at the single <code>Promise</code> executor can be used.</p>\n\n<p>Include <code>.catch()</code> or function at second parameter of <code>.then()</code> chained to <code>Promise</code> constructor to avoid <code>Uncaught in Promise</code> error and handle potential error within <code>Promise</code> constructor function body.</p>\n\n<pre><code>new Promise((resolve, reject) =&gt; {\n try {\n const complete = () =&gt; !clearTimeout(time) \n &amp;&amp; this.removeListener(listener);\n const listener = ({command}) =&gt; command === \"pong\" \n &amp;&amp; !complete() &amp;&amp; resolve();\n this.addListener(listener);\n this.sendMessage({ command: \"ping\" });\n const time = setTimeout(() =&gt; !complete() &amp;&amp; reject(), timeout);\n } catch (e) {\n throw e\n }\n})\n// handle resolved `Promise`, handle error\n.then(() =&gt; {}, e =&gt; console.error(e));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:30:34.347", "Id": "407935", "Score": "0", "body": "just for clarity, I also added the wrapping function of which my code was part. That function is indeed marked as async. (I left it out initially for brevity)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:43:25.370", "Id": "407940", "Score": "0", "body": "Good point about the unnecessary promise that wrapped the `setTimeout`. - My intent was to make it wait until the timeout was finished. (which isn't stricly necessary, and which wasn't even working properly)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T06:10:29.430", "Id": "211010", "ParentId": "211000", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-06T22:53:08.050", "Id": "211000", "Score": "1", "Tags": [ "ecmascript-6", "promise", "timeout" ], "Title": "Promise for request/response with timeout" }
211000
<h2>Problem</h2> <p>I want to read in the data to dictionary</p> <pre><code>person = { 'name': 'John Doe', 'email': 'johndoe@email.com', 'age': 50, 'connected': False } </code></pre> <p>The data comes from different formats:</p> <p><strong>Format A.</strong></p> <pre><code>dict_a = { 'name': { 'first_name': 'John', 'last_name': 'Doe' }, 'workEmail': 'johndoe@email.com', 'age': 50, 'connected': False } </code></pre> <p><strong>Format B.</strong></p> <pre><code>dict_b = { 'fullName': 'John Doe', 'workEmail': 'johndoe@email.com', 'age': 50, 'connected': False } </code></pre> <p>There will be additional sources added in the future with additional structures.</p> <h2>Background</h2> <p>For this specific case, I'm building a Scrapy spider that scrapes the data from different APIs and web pages. Scrapy's recommended way would be to use their <code>Item</code> or <code>ItemLoader</code>, but it's ruled out in my case.</p> <p>There could be potentially 5-10 different structures from which the data will be read from.</p> <h2>Implementation</h2> <h3><code>/database/models.py</code></h3> <pre><code>""" Database mapping declarations for SQLAlchemy """ from sqlalchemy import Column, Integer, String, Boolean from database.connection import Base class PersonModel(Base): __tablename__ = 'Person' id = Column(Integer, primary_key=True) name = Column(String) email = Column(String) age = Column(Integer) connected = Column(Boolean) </code></pre> <h3><code>/mappers/person.py</code></h3> <pre><code>""" Data mappers for Person """ # Abstract class for mapper class Mapper(object): def __init__(self, data): self.data = data # Data mapper for format A, maps the fields from dict_a to Person class MapperA(Mapper): def __init__(self, data): self.name = ' '.join(data.get('name', {}).get(key) for key in ('first_name', 'last_name')) self.email = data.get('workEmail') self.age = data.get('age') self.connected = data.get('connected') @classmethod def is_mapper_for(cls, data): needed = {'name', 'workEmail'} return needed.issubset(set(data)) # Data mapper for format B, maps the fields from dict_b to Person class MapperB(Mapper): def __init__(self, data): self.name = data.get('fullName') self.email = data.get('workEmail') self.age = data.get('age') self.connected = data.get('connected') @classmethod def is_mapper_for(cls, data): needed = {'fullName', 'workEmail'} return needed.issubset(set(data)) # Creates a Person instance base on the input data mapping def Person(data): for cls in Mapper.__subclasses__(): if cls.is_mapper_for(data): return cls(data) raise NotImplementedError if __name__ == '__main__': from database.connection import make_session from database.models import PersonModel # Sample data for example dict_a = { 'name': { 'first_name': 'John', 'last_name': 'Doe' }, 'workEmail': 'johndoe@email.com', 'age': 50, 'connected': False } dict_b = { 'fullName': 'John Doe', 'workEmail': 'johndoe@email.com', 'age': 50, 'connected': False } # Instantiate Person from data persons = [PersonModel(**Person(data).__dict__ for data in (dict_a, dict_b)] with make_session() as session: session.add_all(persons) session.commit() </code></pre> <h2>Question</h2> <p>I have limited experience in Python programming and I'm building my first scraper application for a data engineering project that needs to scale to storing hundreds of thousands of Persons from tens of different structures. I was wondering if:</p> <ol> <li>This is a good solution? What could be the drawbacks and problems down the line?</li> <li>Currently I've implemented different subclasses for the mapping. Is there a convention or industry standard for these types of situations?</li> </ol> <p><em>Update</em></p> <ul> <li>For question 2, I found <a href="https://stackoverflow.com/questions/456672/class-factory-in-python">this</a> question to be useful, but would still want to know if this approach in general is good.</li> <li>Added style improvement suggestions from @Reinderien</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:46:42.133", "Id": "408080", "Score": "0", "body": "I'm happy that you're taking my feedback into account, but it's against site policy for you to edit your question's code as suggestions come in. A new question should be issued with the revised code. Before that, I'm going to edit my answer with more info." } ]
[ { "body": "<h2>Don't abuse inner lists</h2>\n\n<p>This:</p>\n\n<pre><code>self.name = ' '.join([data.get('name').get(key) for key in ['first_name', 'last_name']])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>self.name = ' '.join(data.get('name', {}}.get(key) for key in ('first_name', 'last_name'))\n</code></pre>\n\n<p>Note the following:</p>\n\n<ul>\n<li>Generators don't need to go in a list if they're just being passed to a function (<code>join</code>) that needs an iterable</li>\n<li>Give an empty dictionary as the default for the first get so that the second get doesn't explode</li>\n<li>Use a tuple instead of the last list because the data are immutable</li>\n</ul>\n\n<h2>Use set logic</h2>\n\n<p>This:</p>\n\n<pre><code>return all(key in data for key in ('name', 'workEmail'))\n</code></pre>\n\n<p>is effectively asking \"are both 'name' and 'workEmail' in <code>data</code>?\" There's a better way to ask this - with a <code>set</code>.</p>\n\n<pre><code>needed = {'name', 'workEmail'}\nreturn needed.issubset(set(data))\n</code></pre>\n\n<p>If <code>data</code> can be stored as a <code>set</code> once outside of this function, it will increase efficiency.</p>\n\n<p>Read more here: <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"nofollow noreferrer\">https://docs.python.org/3/tutorial/datastructures.html#sets</a></p>\n\n<h2>Don't needlessly materialize generators</h2>\n\n<p>This:</p>\n\n<pre><code># Instantiate Person from data\npersons = [Person(data) for data in [dict_a, dict_b]]\n\n# Store persons that fit the database model\npersons = [PersonModel(**person.__dict__) for person in persons]\n</code></pre>\n\n<p>makes a generator, saves it to a list in memory, consumes that list, makes a second generator, and stores that generator in a second list in memory. Instead:</p>\n\n<pre><code>persons = [PersonModel(**Person(data).__dict__)\n for data in (dict_a, dict_b)]\n</code></pre>\n\n<p>Again, the last inner list should be a tuple.</p>\n\n<h2>Parsing heuristics</h2>\n\n<p>It's not useful to write separate parsing classes for formats A and B in this case, because they aren't declared by the API so have no meaning. Write a translation routine for every member you extract from the JSON. Do a series of attempts against known paths in the data to get the members out. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T02:09:52.203", "Id": "408065", "Score": "0", "body": "Thanks for the suggestions! Makes sense as well. However, my core question is more on a higher level: is this kind of approach optimal for this challenge or perhaps there is a better or easier way to solve this kind of data mapping from sources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T03:15:54.497", "Id": "408069", "Score": "0", "body": "@maivel How do you detect which format the data will follow? Do you know by filename, or does the user specify, or do you need to autodetect it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:40:16.797", "Id": "408078", "Score": "1", "body": "I would need to autodetect it. The API that provides me the `.json` which I will convert to `dict` is prone to changing their response layouts and naming conventions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:52:12.290", "Id": "408081", "Score": "1", "body": "@maivel refer to edited answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:08:09.350", "Id": "211045", "ParentId": "211007", "Score": "1" } } ]
{ "AcceptedAnswerId": "211045", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T03:48:39.660", "Id": "211007", "Score": "4", "Tags": [ "python", "design-patterns", "scrapy" ], "Title": "Sourcing data format from multiple different structures" }
211007
<p>I've been learning JS for a few months now and I've just finished creating a small image slider for a website. The sliders functionality is as follows:</p> <ul> <li>Continuously cycle through images and loop back to the start</li> <li>Allow the user to click through to a certain section</li> <li>When clicked, the cycle timer must reset and the loop must continue from that point <ul> <li>cycle through a corresponding DOM element (in this case it's a testimonial quote)</li> </ul></li> </ul> <p>I'm mainly looking for pointers on how to make my code more efficient or if I've used bad practice. Any help would be appreciated.</p> <pre class="lang-js prettyprint-override"><code>var container = document.getElementById('slide-container'); var button = document.getElementById('slider-buttons'); var quote = document.getElementById('quote-container'); var interval = 0; sliderMove = function(position){ // Move container to next image container.style.left = -(350 * position) + 'px'; // Remove active classes from all children for (var i = 0; i &lt; quote.children.length; i++) { quote.children[i].classList.remove("quote-active"); button.children[i].classList.remove('active'); }; // Add active classes to specified children quote.children[position].classList.add("quote-active"); button.children[position].classList.add('active'); // Increase global interval variable by 1 interval++; // Set interval back to 0 if it exceeds the amount of quotes if (interval &gt;= quote.children.length) { interval = 0; }; }; // Add event listener to buttons button.addEventListener('click', function(event){ clearInterval(timer); // Resets timer when user clicks on an image autoMove(); // Restarts timer if (event.target.id &gt; -1) { // Ensures the target is valid interval = event.target.id; sliderMove(interval); }; }); // Auto Rotate function autoMove(index) { timer = setInterval(function(){ index = interval; sliderMove(index); },5000); } autoMove(0); sliderMove(0); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:44:51.413", "Id": "407965", "Score": "0", "body": "Have you checked your code with javascript lint (plugins would be available , you can use with VSCode or your favourite editor). Please check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T14:55:22.423", "Id": "407981", "Score": "1", "body": "Welcome to Code Review, Lachlan! Could you include a working example of your HTML and CSS in the post as well? It looks like the JavaScript is dependent on the HTML and CSS to function as expected. Note that you can use the JavaScript/HTML/CSS Snippet function (Ctrl+M) to add \"live\" HTML/JS to your post." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T04:32:36.123", "Id": "211008", "Score": "2", "Tags": [ "javascript" ], "Title": "Learning Javascript - Is this a messy implementation of a Javascript Slider?" }
211008
<p>I've been working on a bot that records the result of matches on SaltyBet.com. It uses that data to calculate the probability of winning for fighters of a given match. A fighters probability is based on the Elo rating system. I'm posting this here to share the code.</p> <p><strong>Repo:</strong> <a href="https://github.com/zakarh/salt-bot" rel="nofollow noreferrer">https://github.com/zakarh/salt-bot</a></p> <pre><code>import json import selenium from selenium import webdriver from selenium.common import exceptions from selenium.webdriver.common.keys import Keys class SaltBot(): def __init__(self): self.data = {} def watch(self, browser, source="data.json", output="data.json", matches=1): """ Watch matches, make predictions, and record the results. :type browser: selenium.webDriver, Example: selenium.webdriver.Chrome(). :type source: str, directory to source file. :type target: str, directory to output file. :type matches: int, No. matches to watch. """ if type(browser) != selenium.webdriver.chrome.webdriver.WebDriver: raise TypeError( "type(browser) != selenium.webdriver.chrome.webdriver.WebDriver, type(browser) == {}".format(type(browser))) if type(source) != str: raise TypeError( "type(source) != str, type(source) == {}".format(type(source))) if type(output) != str: raise TypeError( "type(output) != str, type(output) == {}".format(type(output))) if type(matches) != int: raise TypeError( "type(matches) != int, type(matches) == {}".format(type(matches))) if matches &lt;= 0: raise ValueError( "matches &lt;= 0, matches == {}, matches must be &gt; 0".format(matches)) # Load data from source: self.load_data(source) # Navigate to SaltyBet.com using the browser. url_address = "https://www.saltybet.com/" browser.get(url_address) print("Salt Bot is now watching {} matches.\n".format(matches)) # Handle operations performed in the while loop: bet_status = "" # Handle control flow. recorded = False # Decide when to record the result of matches. red = "" # Fighter. blue = "" # Fighter. match = 0 print("{}/{} matches watched.".format(match, matches)) while match &lt;= matches: try: # Get bet status: current_bet_status = browser.find_element_by_id( "betstatus").text if len(current_bet_status) == 0: continue elif bet_status == "": bet_status = current_bet_status elif bet_status != current_bet_status: bet_status = current_bet_status except exceptions.StaleElementReferenceException: pass except Exception: pass try: # Get fighter names: red_current = browser.find_element_by_id( "sbettors1").find_element_by_tag_name("strong").text blue_current = browser.find_element_by_id( "sbettors2").find_element_by_tag_name("strong").text # Calculate probability for fighters: if len(red_current) == 0 or len(blue_current) == 0: continue elif red == "" or blue == "": red = self.extract_name(red_current) blue = self.extract_name(blue_current) self.display(red, blue) elif red != red_current or blue != blue_current: red = self.extract_name(red_current) blue = self.extract_name(blue_current) self.display(red, blue) except exceptions.StaleElementReferenceException: pass except Exception: pass # Record the results of a match. try: if "win" in bet_status: if recorded is False: if red in bet_status: s = "Winner: {}, Loser: {}\n".format(red, blue) print(s) self.save_data("data.json", red, blue) self.log_data(s) elif blue in bet_status: s = "Winner: {}, Loser: {}\n".format(blue, red) print(s) self.save_data("data.json", blue, red) self.log_data(s) recorded = True match += 1 print( "{}/{} matches watched.".format(match, matches)) else: recorded = False except exceptions.StaleElementReferenceException: pass except Exception: pass def get_probability(self, red, blue): """ Calculate the probability of red and blue winning the match using the Elo Rating System. :type red: str, name of fighter. :type blue: str, name of fighter. :rtype: tuple, respective probability of red and blue winning the match. TODO: Account for win:loss ratio of red's opponents against blue vice versa. """ # Validate input: if type(red) != str: raise TypeError("type(red) != str") if type(blue) != str: raise TypeError("type(blue) != str") # Insufficient data return (0.5, 0.5) if red not in self.data or blue not in self.data: return (0.5, 0.5) else: # Compute the sum of matches won by both fighters: red_rating = sum([self.data[red][loser] for loser in self.data[red]]) blue_rating = sum([self.data[blue][loser] for loser in self.data[blue]]) # Decremenet fighter rating by their total losses against the other fighter: if red in self.data[blue]: red_rating -= self.data[blue][red] if blue in self.data[red]: blue_rating -= self.data[red][blue] # Transform fighter rating: red_rating = pow(10, max(0, red_rating) / 400) blue_rating = pow(10, max(0, blue_rating) / 400) # Calculate red and blue's probability of winning: red_probability = red_rating / (red_rating + blue_rating) blue_probability = blue_rating / (red_rating + blue_rating) return (red_probability, blue_probability) def save_data(self, file_path, winner, loser): """ Open the target file and update the winner and loser data. :type file_path: str, directory path to target file. :type winner: str, name of fighter. :type loser: str, name of fighter. """ # Validate input: if type(file_path) != str: raise TypeError("type(file_path) != str") if type(winner) != str: raise TypeError("type(winner) != str") if type(loser) != str: raise TypeError("type(loser) != str") # Open the target file and write the results. with open(file=file_path, mode="w+") as f: # Add winner and loser if they don't exist in self.data: self.data.setdefault(winner, {}) self.data.setdefault(loser, {}) self.data[winner].setdefault(loser, 0) self.data[loser].setdefault(winner, 0) # Increment the number of wins winner has against the loser: self.data[winner][loser] += 1 f.write(json.dumps(self.data)) def load_data(self, file_path): """ Open the target file and load its contents as JSON. :type file_path: str, directory path to target file. :rtype: None """ # Validate input: if type(file_path) != str: raise TypeError("type(file_path) != str") # Open the target file and load contents as json. with open(file=file_path, mode="r+") as f: data = json.load(f) self.data = data def log_data(self, data): file_path = "data.txt" with open(file=file_path, mode="a+") as f: f.write(data) def extract_name(self, raw_name): return str(raw_name).strip(" ") def display(self, red, blue): s = "\n{} vs. {}\n{}".format( red, blue, self.get_probability(red, blue)) print(s) def main(): sb = SaltBot() sb.watch(browser=webdriver.Chrome(), source="data.json", output="data.json", matches=100) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:43:31.133", "Id": "407984", "Score": "0", "body": "Have you read https://www.giantbomb.com/profile/tycobb/blog/automating-saltybet-my-live-and-ongoing-adventure-/102462/ ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T04:46:40.467", "Id": "408070", "Score": "1", "body": "Thanks for linking the article it was a good read. I expected other bots to exists but not at that level of automation. Anywho it has made me consider possible features I might add to salt bot." } ]
[ { "body": "<h2>Use f-strings</h2>\n\n<p>This:</p>\n\n<pre><code>\"Salt Bot is now watching {} matches.\\n\".format(matches)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'Salt Bot is now watching {matches} matches\\n'\n</code></pre>\n\n<p>and so on for your other <code>format</code> calls.</p>\n\n<h2>Use more subroutines</h2>\n\n<p><code>watch()</code> is quite long. You should break it up into multiple functions.</p>\n\n<h2>Redundant <code>else</code></h2>\n\n<p>This:</p>\n\n<pre><code> if len(current_bet_status) == 0:\n continue\n elif bet_status == \"\":\n bet_status = current_bet_status\n</code></pre>\n\n<p>should use <code>if</code> instead of <code>elif</code>, due to the previous <code>continue</code>. Similar instances elsewhere.</p>\n\n<h2>Don't swallow exceptions</h2>\n\n<p>This:</p>\n\n<pre><code> except Exception:\n pass\n</code></pre>\n\n<p>is really dangerous, and asking for trouble. If this is in a loop that you never ever want to die, you should <em>still</em> at least be outputting the exception to the console when it occurs. Otherwise, debugging is going to be much more difficult.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T04:58:37.110", "Id": "408073", "Score": "0", "body": "@Reinderein, is it best practices to use the latest features of a programming language? Given that I used the format() method instead of the f-strings for backward compatibility.\n\nTips on subroutines, redundant else's, and exceptions duly noted. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:36:52.143", "Id": "408077", "Score": "2", "body": "@ZakarH. Language level depends on a lot of things. If you're writing an application and this is not in a business context where you're told which versions of Python you need to support, then yes, you should be using the latest version. If (for instance) you're writing a library and you want it to have broader compatibility, then your language choices will be different." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:54:48.490", "Id": "211044", "ParentId": "211017", "Score": "3" } }, { "body": "<p>In Python 3.5 type annotations were introduced. These let you add annotations to variables and functions to denote which type they should be. This is not enforced on its own, but you can get access to these annotations with the <code>__anotations__</code> property:</p>\n\n<pre><code>def f(a: str) -&gt; str:\n return a\nf.__annotations__\n# {'a': str, 'return': str}\n</code></pre>\n\n<p>With this it is relatively easy to write a decorator that checks all specified types:</p>\n\n<pre><code>from functools import wraps\nimport inspect\n\ndef check_types(func):\n annotations = func.__annotations__\n params = inspect.signature(func).parameters\n @wraps(func)\n def wrapper(*args, **kwargs):\n # positional arguments\n for value, (name, param) in zip(args, params.items()):\n if param.annotation is inspect._empty:\n continue\n if not isinstance(value, param.annotation):\n raise TypeError(f\"type({name}) != {param.annotation}, type({name}) == {type(value)}\")\n # keyword arguments\n for name, value in kwargs.items():\n try:\n required_type = annotations[name]\n except KeyError:\n continue\n if not isinstance(value, required_type):\n raise TypeError(f\"type({name}) != {required_type}, type({name}) == {type(value)}\")\n return func(*args, **kwargs)\n return wrapper\n</code></pre>\n\n<p>Your methods would then simply look like this:</p>\n\n<pre><code>Chrome = selenium.webdriver.chrome.webdriver.WebDriver\n\nclass SaltBot:\n ...\n\n @check_types\n def watch(self, browser: Chrome, source: str = \"data.json\", output: str = \"data.json\", matches: int = 1):\n \"\"\"\n Watch matches, make predictions, and record the results.\n :type browser: selenium.webDriver, Example: selenium.webdriver.Chrome(). \n :type source: str, directory to source file.\n :type target: str, directory to output file.\n :type matches: int, No. matches to watch.\n \"\"\"\n if matches &lt;= 0:\n raise ValueError(\n \"matches &lt;= 0, matches == {}, matches must be &gt; 0\".format(matches))\n\n ...\n</code></pre>\n\n<p>This is of course only a dynamic type checking at run time and can probably be improved itself (I don't use type hints regularly). It does not conform to <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a> in that you can't e.g. use strings as types. You might want to go the full way and use the <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\"><code>typing</code> module</a> and a static type checker, as described e.g. <a href=\"https://medium.com/@ageitgey/learn-how-to-use-static-type-checking-in-python-3-6-in-10-minutes-12c86d72677b\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T05:06:51.427", "Id": "408074", "Score": "0", "body": "that article you linked on Medium \"How to Use Static Type Checking in Python 3.6\" was a fantastic read. I'm going to start using typing in my programs. Question, how have you determined use cases that require typing?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T17:21:39.557", "Id": "211051", "ParentId": "211017", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T09:05:51.983", "Id": "211017", "Score": "2", "Tags": [ "python", "web-scraping" ], "Title": "A bot for SaltyBet that watches and records matches" }
211017
<p>I have created a little framework for my work to manage loading and unloading plugins by using a modular tree structure that is based on Promises.</p> <p>I would like to be able to create the tree structure, but execute the async functions in order from the root node down, or more precisely execute the affects of the async function in order, the execution of the promises is not really important.</p> <p>The way nested Promises work is the parent will not resolve until the child has first resolved eg.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let order = 0 const promiseTree = (name, children) =&gt; Promise.all([ new Promise(res =&gt; res(`${name} order:${order++}`)), children &amp;&amp; Promise.all(children) ]) promiseTree('root', [ promiseTree('child', [ promiseTree('grandchild', [ promiseTree('great grandchild') ]) ]) ]) .then(console.log)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://codepen.io/synthet1c/pen/KyQQmL.js?concise=true"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>If you resolve a closure, then recursively call the callbacks once all promises are complete the order can be corrected.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let order = 0 const promiseTree = (name, children) =&gt; Promise.all([ new Promise(res =&gt; res(() =&gt; `${name} order:${order++}`)), children &amp;&amp; Promise.all(children) ]) const recursivelyCall = x =&gt; Array.isArray(x) ? x.map(recursivelyCall) : typeof(x) === 'function' ? x() : x promiseTree('root', [ promiseTree('child', [ promiseTree('grandchild', [ promiseTree('great grandchild') ]) ]) ]) // traverse the returned values and call the functions in declared order .then(recursivelyCall) .then(console.log)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://codepen.io/synthet1c/pen/KyQQmL.js?concise=true"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>If I create a sample Promise tree it will execute from the inside out. see the first example below.</p> <p>To achieve running the resolved promises in order, I have propagated a closure that contains the affects I want to perform up to the root Promise, which recursively calls the embedded closures in order that they were defined within the Promise tree.</p> <p>For the framework I have made I would prefer not to have to return a closure as in increases the complexity for users.</p> <p>Is there a better way to achieve the desired result? or should I continue with the second way?</p> <p>The examples will show the order the promises are executed and the value they return. The second example is the same accept it recursively calls each closure in the response once it propagates to the root Promise.</p> <h3>First example</h3> <p>this shows the problem with the initial code. The child promises resolve before the parent promises</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const trace = name =&gt; x =&gt; (console.log(name + ' promise'), x) // resolve the test promise immediately const testPromise = (id) =&gt; new Promise(res =&gt; { const time = Math.floor(Math.random() * 100) setTimeout(() =&gt; { res(`resolved promise ${id} after ${time} milliseconds`) }, time) }) // first example Promise.resolve( Promise.resolve( Promise.resolve( Promise.all([ Promise.all([testPromise(1)]), Promise.all([testPromise(2), testPromise(3)]), // Promise.reject('something went wrong!') ]).then(trace('fourth')) ).then(trace('third')) ).then(trace('second')) .then(result =&gt; { console.log('resolved testPromise', result) return result }) .catch(result =&gt; { console.error('failed testPromise') return result }) ).then(trace('first'))</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://codepen.io/synthet1c/pen/KyQQmL.js?concise=true"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <h3>Second example</h3> <p>This shows a possible solution of delaying the action using a closure to delay performing the action from the entire tree before the entire tree has resolved. This requires recursively calling each promise, then recursively running each returned closure once the entire tree has resolved successfully.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const trace = name =&gt; x =&gt; (console.log(name + ' promise'), x) // resolve the test promise, but return a closure to delay the action // until all promises are resolved const testPromiseReturnClosure = (id) =&gt; new Promise(res =&gt; { const time = Math.floor(Math.random() * 100) setTimeout(() =&gt; { res(() =&gt; `resolved closure ${id} after ${time} milliseconds`) }, time) }) // flatMap over the returned values in the resolved promises values, // if the value is a function call it. const recursivelyCallResolvedClosures = x =&gt; Array.isArray(x) ? x.forEach(recursivelyCallResolvedClosures) : typeof(x) === 'function' ? console.log(x()) : null Promise.resolve( Promise.resolve( Promise.resolve( Promise.all([ Promise.all([testPromiseReturnClosure(1)]), Promise.all([testPromiseReturnClosure(2), testPromiseReturnClosure(3)]), // Promise.reject('something went wrong!') ]).then(trace('fourth')) ).then(trace('third')) ).then(trace('second')) .then(result =&gt; { console.log('resolved testPromiseReturnClosure', result) return result }) .catch(result =&gt; { console.error('failed testPromiseReturnClosure') return result }) ) .then(trace('first')) .then(x =&gt; (console.log('--------------------------------------'), x)) .then(recursivelyCallResolvedClosures)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://codepen.io/synthet1c/pen/KyQQmL.js?concise=true"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <blockquote> <p>From replies below regarding the purpose of using a complex tree structure, here is a little example of the api that the framework uses.</p> </blockquote> <p>The basic concept is that everything inherit's from a base class Node that provides <code>init</code> and <code>destroy</code> methods. The framework extends off this base class allowing each <code>Node</code> to perform some possibly asynchronous action then send a signal to it's children to do the same.</p> <p>There are 5 different Node types that perform some function within the tree to allow you to simulate a router, lazy module loader, decision tree. </p> <ul> <li><code>Core</code> - the base engine</li> <li><code>Predicate</code> - function to test if the signal should propagate to it's children</li> <li><code>Module</code> - intermediate object to house <code>Plugins</code> to represent a website module</li> <li><code>Import</code> - es6 async module loader</li> <li><code>Plugin</code> - functionality to bind events and plugins to the current page</li> </ul> <p>The tree will be run when the page loads, the internal state is updated or the page history is changed through <code>history.pushState</code></p> <p>The lifecycle is run init when the page is loaded, when another page is loaded, run the <code>destroy</code> method and pass the signal to each initialized <code>Node</code>. Once each node has removed it's functionality from the page, run the <code>init</code> cycle.</p> <h3>Basic api</h3> <pre><code>class Node { nodes = [] constructor(nodes = []) { this.nodes = nodes } init(request) { return Promise.all(this.nodes.map(node =&gt; node.init(request))) } destroy(request) { return Promise.all(this.nodes.map(node =&gt; node.destroy(request))) } } // example of extending the base Node class to do something then propagate the message to it's children conditionally. class Predicate extends Node { constructor(predicate, nodes) { super(nodes) this.predicate = predicate } init(request) { // preform some action on init, then pass the message to any child `nodes` if (this.predicate(request)) return super.init(request) return super.destroy(request) } } </code></pre> <h3>index.js</h3> <pre><code>export default new Core([ // Predicate could be related to the url, an element in the page, really anything that can be tested new Predicate(() =&gt; true, [ // import asynchronously loads a module new Import(() =&gt; import('./somemodule')) ]), new Predicate(() =&gt; false, [ new Plugin(/* this won't run because the predicate function is false */) ]) ]) </code></pre> <h3>somemodule.js</h3> <pre><code>export default new Module([ // plugins initialize and destroy functionality on a page new Plugin(/* config options */) ]) </code></pre> <p>It's kind of complex on the surface I guess, but simplifies the process of managing functionality for a website, and as it's a consistent api it's becomes very simple to manage functionality and state. But at the heart of it internally it's a <code>Promise</code> tree the same as the examples above. </p> <p>Essentially I just want to fold the promises and perform them in their declared order. everything else works in terms of the tree.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T13:11:55.627", "Id": "408354", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/88048/discussion-on-question-by-synthet1c-execute-promise-tree-in-order-of-declaration)." } ]
[ { "body": "<p>Nesting of the function calls</p>\n\n<pre><code>promiseTree('root', [\n promiseTree('child', [\n promiseTree('grandchild', [\n promiseTree('great grandchild')\n ])\n ])\n])\n</code></pre>\n\n<p>is one issue with the code at the question relevant to the expected result. The innermost nested function (argument) is executed first. See and highlight line 15 at <a href=\"https://astexplorer.net/#/gist/777805a289e129cd29706b54268cfcfc/5a2def5def7d8ee91c052d9733bc7a37c63a6f67\" rel=\"nofollow noreferrer\">https://astexplorer.net/#/gist/777805a289e129cd29706b54268cfcfc/5a2def5def7d8ee91c052d9733bc7a37c63a6f67</a>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function promiseTree (name, children) {\n console.log(name, children, arguments[0], arguments); // arguments[0] is \"great grandchild\"\n}\n\npromiseTree('root', [\n promiseTree('child', [\n promiseTree('grandchild', [\n promiseTree('great grandchild')\n ])\n ])\n])</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If necessary, can link to a primary resource for verification of the fact that the innermost (argument) function is expected to be expected to be executed first in JavaScript.</p>\n\n<hr>\n\n<p>The pattern at the question which uses multiple <code>Promise.resolve()</code> and <code>Promise.all()</code> is unnecessary. </p>\n\n<p>Either recursion, <code>Array.prototype.reduce()</code> or <code>async/await</code> can be used to handle <code>Promise</code> execution in sequential order. </p>\n\n<p>Note that <code>Promise</code> constructor or functions passed to <code>Promise.all()</code> do not necessarily execute in sequential order.</p>\n\n<p>The array returned from <code>Promise.all()</code> will be in the same order as the elements in the iterable passed to <code>Promise.all()</code>, that is, for example, if the fifth element of the iterable is resolved before the first element of the iterable passed, the resulting array of values will still be in the exact order of indexes of the input iterable.</p>\n\n<p>The logging of the times is not entirely accurate, as <code>Promise.all()</code> does not resolve until all elements of the iterable (whether the element is a <code>Promise</code> value or not a <code>Promise</code>) are resolved.</p>\n\n<p>Given that <code>Promise</code> all is being used without <code>Array.prototype.map()</code> and using a reflect pattern, any rejected <code>Promise</code> will result in halting the <code>Promise</code> chain and <code>.catch()</code> being executed.</p>\n\n<p>If there is a nested array structure, that array can be flattened (for example, using <code>Array.prototype.flat())</code> before performing sequential operations.</p>\n\n<pre><code>const flatten = arr =&gt; {\n arr = arr.flat();\n return arr.find(a =&gt; Array.isArray(a)) ? flatten(arr) : arr\n}\n\nflatten([1,[2, [3, [4]]]]) // [1, 2, 3, 4]\n</code></pre>\n\n<p></p>\n\n<p>An an example of using both <code>Array.prototype.reduce()</code> and <code>async/await</code> to perform operations in sequential order, accepting a function, <code>Promise</code> or other value</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const testPromise = (id) =&gt; new Promise((res, rej) =&gt; {\n const time = Math.floor(Math.random() * 1000)\n setTimeout(() =&gt; {\n console.log(`resolved promise '${id}' after ${time} milliseconds`);\n res(id)\n }, time)\n});\nconst fn = (...arr) =&gt; {\n const res = [];\n return arr.reduce((promise, next) =&gt; {\n return promise.then(() =&gt; testPromise(next).then(data =&gt; {\n console.log(data);\n res.push(data)\n }).catch(err =&gt; err))\n }, Promise.resolve())\n .then(async() =&gt; {\n for (let value of res) {\n console.log(await (typeof value === 'function' ? value() : value))\n }\n return 'done'\n })\n}\n\nfn(1, () =&gt; 2, 3, Promise.resolve(4), testPromise(5)).then(data =&gt; console.log(data))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>An approach using <code>async/await</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const fn = async() =&gt; {\n let order = 0\n const promiseTree = name =&gt;\n new Promise(res =&gt; res(`${name} order:${order++}`))\n\n const res = [await promiseTree('root'), [\n await promiseTree('child'), [\n await promiseTree('grandchild'), [\n await promiseTree('great grandchild')\n ]\n ]\n ]];\n return res;\n}\n\nfn()\n.then(console.log)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <p>I would like to be able to create the tree structure, but execute the\n async functions in order from the root node down, or more precisely\n execute the affects of the async function in order, the execution of\n the promises is not really important.</p>\n</blockquote>\n\n<p>To 1) execute N asynchronous operations in parallel (return a <code>Promise</code> object) which resolves to a value 2) create the data structure in order of input</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// do asynchronous stuff, resolve `props`: Array of `[index, value]`\nconst fn = (...props) =&gt; \n new Promise(resolve =&gt; \n setTimeout(resolve, Math.floor(Math.random() * 1000), props));\n\n// accepts string of characters delimited by space or array\n// returns Array\nconst promiseTree = tree =&gt; \n Promise.all(\n // check if `tree` is String or Array\n [...(!Array.isArray(tree) &amp;&amp; typeof tree === 'string' \n ? tree.split` ` \n : tree).entries()] // use `.entries()` method of Array\n .map(([index, prop]) =&gt; fn(index, prop))) // do asynchronous stuff\n .then((result, res = [], t = []) =&gt; // define `res`, `t` Arrays\n result.map(([index, prop]) =&gt; \n !res.length // first iteration\n ? res.push(prop, t) // push first value\n : index &lt; result.length-1 // check index\n ? t.push(prop, t = []) // `.push()` to `t`, re-declare `t` as `[]`\n : t.push(prop)) // `.push()` last value `prop` to `t`\n &amp;&amp; res) // return `res`\n\nPromise.all(\n[\n // space delimited String passed to `promiseTree`\n promiseTree('root child grandchild greatgrandchild') \n .then(console.log)\n // Array passed to `promiseTree`\n, promiseTree([...Array(4).keys()])\n .then(console.log)\n]);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:16:12.723", "Id": "408025", "Score": "0", "body": "Thanks for the example. This is not the problem I am trying to solve as your Promises are not nested in a tree structure they are flat and your are synchronously resolving the promises. I want them parallel, but to have the parents effect to update the page before the child. I have added two more basic examples that should outline the problem and potential solution more clearly. I need to get some sleep as I start work in a couple of hours, but I'll try to get back to you if you reply. Cheers for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:18:13.237", "Id": "408026", "Score": "0", "body": "@synthet1c _\"and your are synchronously resolving the promises\"_ ? Flatten any \"tree\" structure before performing any further tasks. _\"I want them parallel\"_ The question specifically states that the requirement is to perform potentially asynchronous operations in a sequential order, not in parallel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:20:27.817", "Id": "408027", "Score": "0", "body": "I will update. I mean to say execute the parent before executing the child. Eg the parent may be an ajax request to get some html from the server, the child may be some jQuery plugin to attach to the html from the parent. At the sibling level it doesn't matter the order, but parent to child must be consecutive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:21:09.877", "Id": "408028", "Score": "0", "body": "@synthet1c That is precisely what the code at the answer achieves." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:28:08.430", "Id": "408029", "Score": "0", "body": "it doesn't look like it's a hierarchical tree structure, it looks like a flat list of promises. Could you clarify if it's possible to execute an Array of promises inside it? I can't see you recursively calling `fn` to flat map the returned values. I am doing that however, I don't flatten the list, I just traverse it calling the functions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:35:41.917", "Id": "408031", "Score": "0", "body": "Consider the example input at `flatten` function. Flatten any \"tree\" structure first. The result must be a sequential ordering of any \"tree\" structure. See also [Return a result from nested animation](https://stackoverflow.com/q/35807287); [Execute function queue in javascript](https://stackoverflow.com/q/32028368); [multiple, sequential fetch() Promise](https://stackoverflow.com/q/38034574)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:41:55.790", "Id": "408034", "Score": "0", "body": "The thing is that the promises just start resolving as soon as they are declared, so you can't flatten the effects of the promises without containing them in a closure. Thanks for your help, but as this is a code review site. I believe my solution is more elegant with no side effects, but I wanted to know if there was some better way to structure the Promise tree to have it automatically execute the tree consecutively. Explaining the problem has helped me understand it more clearly and failing any object like a `Task` from a library like ramda it seems that I must return a closure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:44:00.657", "Id": "408035", "Score": "0", "body": "You have been a great help thank you. I might put a question on stackoverflow to get some more exposure with the basic examples I recently added." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:44:39.067", "Id": "408036", "Score": "0", "body": "_\"The thing is that the promises just start resolving as soon as they are declared, so you can't flatten the effects of the promises without containing them in a closure.\"_ Not sure what you mean? The code at the answer proves that is not the case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:45:30.750", "Id": "408037", "Score": "0", "body": "@synthet1c Do not be shocked by the response you might receive at SO when users view the nested use of `Promise.resolve()` and `Promise.all()` used, as it is one of several \"anti-pattern\"s. Be sure to include the `promise` tag at your prospective question. Is your question to demonstrate the \"elegance\" of the approaches that you use, or to get feedback, even where that feedback states the approach is not necessary? If you are satisfied by your approach, then use it. Expecting others to concur with your assessment that your approaches are \"more elegant\" than flattening a \"tree\" is fallacy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:47:31.870", "Id": "408038", "Score": "1", "body": "lol, cheers for the warning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:32:02.517", "Id": "411129", "Score": "0", "body": "@synthet1c Does the answer resolve the question?" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:07:13.563", "Id": "211056", "ParentId": "211018", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:07:49.873", "Id": "211018", "Score": "2", "Tags": [ "javascript", "tree", "functional-programming", "promise" ], "Title": "Execute promise tree in order of declaration" }
211018
<p>I wrote a commit message validator + CLI in NodeJS.</p> <p>Notes:</p> <ul> <li><p>My greatest concern is that the patten I use to represent the results of a validation is inadequate. Options:</p> <ul> <li>Use adhoc enums</li> <li>Create a <code>ValidationResult</code> class (?)</li> <li>Extend <code>Error</code> and return an array of those. In this case, how would the <code>--verbose</code> option, which shows passed rules and informational rules work?</li> </ul></li> <li><p>Is the pattern I use in <code>lib/rules.js</code> to represent each of the rules adequate?</p></li> <li><p>Is there a better (performance and/or readability-wise) way of stripping commit messages than the approach I use in <code>lib/strip.js</code>?</p></li> <li><p>Other feedback is welcome too, of course. </p></li> </ul> <p><code>index.js</code>:</p> <pre><code>const strip = require('./lib/strip'); const rules = require('./lib/rules'); function validate(commitMessage) { const strippedMessage = strip(commitMessage); const results = []; for (const rule of rules) { let outcome; if (rule.test === undefined) { outcome = 'info'; results.push({ type: outcome, message: rule.message }); continue; } if (rule.test(strippedMessage)) { outcome = 'pass'; } else { outcome = 'fail'; } results.push({ type: outcome, message: rule.message }); } return results; } module.exports = validate; </code></pre> <p><code>cli.js</code>:</p> <pre><code>#!/usr/bin/env node const meow = require('meow'); const fs = require('fs'); const stdin = require('get-stdin'); const validate = require('.'); const log = require('./lib/log'); const cli = meow({ description: 'Validate commit messages against the seven rules of commit messages.', flags: { silent: { type: 'boolean', alias: 's' }, verbose: { type: 'boolean', alias: 'v' }, // TODO: Work with --file flag file: { type: 'string', alias: 'f' } // TODO: If nothing else, read stdin } }); log(); // Leading new line if (cli.input.length === 0) { // TODO: Cry } const [commitMessage] = cli.input; const results = validate(commitMessage); let exitCode = 0; for (const result of results) { switch (result.type) { case 'fail': if (!cli.flags.silent) { log.error(result.message); } if (exitCode === 0) { exitCode = 1; } break; case 'pass': case 'info': if (!cli.flags.silent &amp;&amp; cli.flags.verbose) { log[result.type](result.message); } break; default: throw new Error(`Internal Error: Invalid result type '${result.type}'`); } } process.exit(exitCode); </code></pre> <p><code>lib/</code></p> <p> <code>lib/rules.js</code>:</p> <pre><code>const one = { message: 'Separate subject from body with a blank line', test: (commitMessage) =&gt; { const separatedByLf = /^.+(\n\n(?:.|\n)+|\n?)$/g; return separatedByLf.test(commitMessage); } }; const two = { message: 'Limit the subject line to 50 characters', test: (commitMessage) =&gt; { const subjectLine = getSubjectLine(commitMessage); const cutOff = 50; return subjectLine.length &lt; cutOff; } }; const three = { message: 'Capitalize the subject line', test: (commitMessage) =&gt; { const subjectLine = getSubjectLine(commitMessage); const firstCharacter = subjectLine[0]; return !isLowerCase(firstCharacter); } }; const four = { message: 'Do not end the subject line with a period', test: (commitMessage) =&gt; { const subjectLine = getSubjectLine(commitMessage); const lastCharacter = subjectLine.substr(-1); return !(lastCharacter === '.'); } }; const five = { message: 'Use the imperative mood in the subject line' // We could, in theory, use NLP to check for this rule, // ...but it would take effort and would be error prone }; const six = { message: 'Wrap the body at 72 characters', test: (commitMessage) =&gt; { const bodyLines = getBody(commitMessage).split('\n'); return bodyLines.every(line =&gt; line.length &lt; 72); } }; const seven = { message: 'Use the body to explain _what_ and _why_ vs. _how_' // This is obviously not detectable programtically }; const rules = [ one, two, three, four, five, six, seven ]; module.exports = rules; function getSubjectLine(commitMessage) { return commitMessage.split('\n')[0]; } function getBody(commitMessage) { const [, ...body] = commitMessage.split('\n'); return body.join('\n'); } function isLowerCase(char) { return !(char.toUpperCase() === char); } </code></pre> <p><code>lib/log.js</code>:</p> <pre><code>const chalk = require('chalk'); const logSymbols = require('log-symbols'); function log(...args) { args = args.join(' '); console.log(args); } log.error = (...args) =&gt; { console.error(chalk.red(logSymbols.error, args)); }; log.success = (...args) =&gt; { log(chalk.green(logSymbols.success, args)); }; log.warn = (...args) =&gt; { console.warn(chalk.yellow(logSymbols.warn, args)); }; log.info = (...args) =&gt; { console.info(chalk.blue(logSymbols.info, args)); }; module.exports = log; </code></pre> <p><code>lib/strip.js</code>:</p> <pre><code>// See: https://git-scm.com/docs/git-commit#git-commit-strip // TODO: Respect git's core.commentchar function strip(rawCommitMessage) { const trailingWhitespace = /[ \t\f\v]+$/gm; const commentary = /^#.*/gm; const consecutiveEmptyLines = /\n{3,}/g; const leadingTrailingEmptyLines = /^\n+|\n+$/g; return rawCommitMessage .replace(trailingWhitespace, '') .replace(commentary, '') .replace(consecutiveEmptyLines, '\n\n') .replace(leadingTrailingEmptyLines, ''); } module.exports = strip; </code></pre> <p></p>
[]
[ { "body": "<p>Your code looks mostly good, but here are some things:</p>\n\n<ul>\n<li><code>lib/log.js</code>: You don't need the <code>log</code> function. <code>console.log</code> does exactly what you do in that function (well not exactly, but it shouldn't make a difference in this context). You can just set <code>log = (...args) =&gt; console.log(...args)</code> or <code>function log(...args) {console.log(...args)}</code></li>\n<li><code>lib/rules.js</code> In the <code>isLowerCase</code> function, you are checking <code>!(char.toUpperCase() === char)</code>. You should use <code>!==</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T14:16:16.573", "Id": "211030", "ParentId": "211019", "Score": "1" } } ]
{ "AcceptedAnswerId": "211030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T10:55:59.950", "Id": "211019", "Score": "1", "Tags": [ "javascript", "node.js", "console" ], "Title": "NodeJS commit message validator" }
211019
<p>I wrote a script that gives a "generalized" function of an arbitrary dice. Is this any good? How can it improve so to make it cleaner?</p> <pre><code>import random def roll(die): number = random.randint(0,len(die)-1) b = die[number] return b Die1 = [1,2,3,4] Die2 = [1,2,3,4,5,6] #num lists def inptchacc(): ending_conditions = ['stop','Stop','quit','Quit'] end = False inpu = input('what number would you like to add to the new face of the Die? (to end the die please type "stop or Stop or quit or Quit to finish the DIE" )') while end == False: if not(inpu in ending_conditions): try: retr = int(inpu) return retr except: string = 'invalid input please try again' inpu = input('invalid input please try again ') else: stop = 'stop' return stop def deeper(IDie): list = [] Adding = True while Adding: print('The Die ' + IDie + ' is currently ' + str(list) ) toadd = inptchacc() if toadd != 'stop': list.append(toadd) else: Adding = False return list def chance_overlap(Die1,Die2): highnumber = 1000 counter = 0 for n in range(highnumber): x = roll(Die1) y = roll(Die2) if x == y: counter += 1 chance = counter/highnumber return chance chance = chance_overlap(Die1,Die2) print(chance) Doing = True while Doing: try: IDie1 = deeper('IDie1') IDie2 = deeper('IDie1') chance2 = chance_overlap(IDie1,IDie2) Doing = False except: print ('incompatible options selected returning....... ') print(chance2) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:15:10.403", "Id": "407951", "Score": "0", "body": "What is the overall function of this, just rolling some arbitrary dice? It looks awfully complicated for such a simple task if that's it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:22:14.787", "Id": "407953", "Score": "0", "body": "\"\nThe assignment deals with a game in which two players both have a set of dice. In the game, each player casts his/her dice and sums the outcomes of the dice. The player with the highest sum wins. If the sums are equal, it's a draw. Usually the dice within one set are equal, but different from the kind of dice in the other set.\" This is the assignment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:24:09.370", "Id": "407955", "Score": "1", "body": "As we all want to make our code more efficient or improve it in one way or another, **try to write a title that summarizes what your code does**, not what you want to get out of a review. Please see [How to get the best value out of Code Review - Asking Questions](https://CodeReview.meta.StackExchange.com/a/2438/41243) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:28:23.330", "Id": "407968", "Score": "3", "body": "@Beginner-Coder123: You should add that description to the question body." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T19:07:18.877", "Id": "408194", "Score": "2", "body": "Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted." } ]
[ { "body": "<h2>The right functions</h2>\n\n<pre><code>def roll(die):\n number = random.randint(0,len(die)-1)\n b = die[number]\n return b\n</code></pre>\n\n<p>Can be:</p>\n\n<pre><code>def roll(die):\n return random.choice(die)\n</code></pre>\n\n<h2><code>inptchacc()</code></h2>\n\n<p>You could instead check only the first character of the input (case insensitive), rather than expecting the whole keyword.</p>\n\n<p>Your return variable <code>stop</code> isn't needed. Just return directly.</p>\n\n<pre><code>stop = 'stop'\nreturn stop\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>return 'stop'\n</code></pre>\n\n<p>Likewise elsewhere in your code.</p>\n\n<h2>Use <code>__main__</code></h2>\n\n<p>Rather than putting code between functions and also at the end of the file, instead use:</p>\n\n<pre><code>if __name__ == '__main__':\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/q/419163/6789498\">here</a> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:51:26.740", "Id": "211027", "ParentId": "211022", "Score": "8" } }, { "body": "<h2>Make the computer count</h2>\n\n<p>These:</p>\n\n<pre><code>Die1 = [1,2,3,4]\nDie2 = [1,2,3,4,5,6]\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>die1 = list(range(1, 5))\ndie2 = list(range(1, 7))\n</code></pre>\n\n<h2>Only compare once</h2>\n\n<p>This list:</p>\n\n<pre><code>ending_conditions = ['stop','Stop','quit','Quit']\n</code></pre>\n\n<p>has two problems. First, don't store multiple cases for one word - just store lower (or upper) case - I prefer lower, because no shouting.</p>\n\n<p>Also, it shouldn't be a list. It's getting tested for membership, so make it a set. In other words,</p>\n\n<pre><code>ending_conditions = {'stop', 'quiet'}\n</code></pre>\n\n<p>then for use, write \"not in\", instead of \"not x in\"; i.e.</p>\n\n<pre><code>if inpu.lower() not in ending_conditions:\n</code></pre>\n\n<h2>PEP8</h2>\n\n<p>Run your code through a linter. It will catch several things, including</p>\n\n<ul>\n<li>Don't capitalize your variables (<code>Die1</code>, <code>Die2</code>, <code>Adding</code>, <code>Doing</code>) if they're local. If they're global constants, they need to be all-uppercase. In the case of <code>Die*</code>, they probably shouldn't be global at all.</li>\n<li>Add a couple of newlines after your <code>import</code>s</li>\n</ul>\n\n<h2>Grammar</h2>\n\n<p>Write:</p>\n\n<pre><code>print('Incompatible options selected. Returning...')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:41:15.193", "Id": "211039", "ParentId": "211022", "Score": "3" } }, { "body": "<p>Since you need to roll many times in the <code>chance_overlap</code> function, you might want to optimize making <code>n</code> rolls, using <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a> (Python 3.6+):</p>\n\n<pre><code>from itertools import groupby\n\ndef roll(die, n=1):\n if n == 1:\n return random.choice(die)\n return random.choices(die, k=n)\n\ndef all_equal(iterable):\n \"Returns True if all the elements are equal to each other\"\n g = groupby(iterable)\n return next(g, True) and not next(g, False)\n\ndef overlap_chance(*dice, n=1000):\n rolls = [roll(die, n) for die in dice]\n equal_rolls = sum(all_equal(roll) for roll in zip(*rolls))\n return equal_rolls / n\n</code></pre>\n\n<p>Here I chose to include it in your <code>roll</code> function, which is nice because you only have on function, but you do have different return types depending on the value of <code>k</code>, which is not so nice. If you want to you can make it into two separate functions instead.</p>\n\n<p>I made <code>chance_overlap</code> take a variable number of dice so it even works for more than two (and also for one, which is a bit boring).</p>\n\n<p>In addition, I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> for variable names (<code>lower_case</code>).</p>\n\n<p>The <code>all_equal</code> function is directly taken from the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipes</a>.</p>\n\n<hr>\n\n<p>Using a Monte-Carlo method to determine the chance for the dice to get the same values is fine, but you could just use plain old math.</p>\n\n<p>Each distinct value <span class=\"math-container\">\\$j\\$</span> on each die <span class=\"math-container\">\\$i\\$</span> has probability <span class=\"math-container\">\\$p^i_j = n^i_j / k_i\\$</span>, where <span class=\"math-container\">\\$k_i\\$</span> is the number of faces of die <span class=\"math-container\">\\$i\\$</span> and <span class=\"math-container\">\\$n^i_j\\$</span> the number of times the value <span class=\"math-container\">\\$j\\$</span> appears on that die. Then the chance to have an overlap is simply given by</p>\n\n<p><span class=\"math-container\">$$\nP(overlap) = \\sum\\limits_j \\prod\\limits_i p^i_j = \\sum\\limits_j \\prod\\limits_i n^i_j / k_i,\n$$</span></p>\n\n<p>where <span class=\"math-container\">\\$i\\$</span> goes over all dice and <span class=\"math-container\">\\$j\\$</span> over all values present on any dice (with <span class=\"math-container\">\\$n^i_j = 0\\$</span> if value <span class=\"math-container\">\\$j\\$</span> does not appear on die <span class=\"math-container\">\\$i\\$</span>).</p>\n\n<p>In other words dice rolls are independent events and e.g. the chance to get two heads or two tails with a fair coin (<code>dice = [[\"H\", \"T\"], [\"H\", \"T\"]]</code>) are <span class=\"math-container\">\\$P(HH \\vee TT) = P_1(H)\\cdot P_2(H) + P_1(T) \\cdot P_2(T) = 0.5\\cdot0.5 + 0.5\\cdot0.5 = 0.5\\$</span>.</p>\n\n<pre><code>from collections import Counter\nfrom functools import reduce\nfrom itertools import chain\nfrom operator import mul\n\ndef overlap_chance_real(*dice):\n all_values = set(chain.from_iterable(dice))\n counters = [Counter(die) for die in dice]\n lengths = [len(die) for die in dice]\n return sum(reduce(mul, [counter[val] / length\n for counter, length in zip(counters, lengths)])\n for val in all_values)\n</code></pre>\n\n<p>The nice thing about this is that we don't need to worry if not all dice have the same values, since <code>Counter</code> objects return a count of zero for non-existing keys.</p>\n\n<p>For <code>dice = [[1,2,3], [1,1,1]]</code> it returns the correct (and precise) value of <code>0.3333333333333333</code>. and <code>0.5</code> for <code>dice = [[\"H\", \"T\"], [\"H\", \"T\"]]</code>.</p>\n\n<p>The execution time of the first function (<code>overlap_chance</code>) increases linearly with the number of dice (all six sided) and it is in general slower than the second function (<code>overlap_chance_real</code>):</p>\n\n<p><a href=\"https://i.stack.imgur.com/ocKrB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ocKrB.png\" alt=\"enter image description here\"></a></p>\n\n<p>With two dice with increasing number of faces the first function is slower but basically constant in time while the second function is faster but the time increases with the number of faces. This plot also contains your function (since it can only deal with two dice it was not included in the previous plot), which is slower than both:</p>\n\n<p><a href=\"https://i.stack.imgur.com/RY4u5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RY4u5.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:24:22.940", "Id": "408019", "Score": "1", "body": "What did you use to make those graphs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:38:51.183", "Id": "408023", "Score": "1", "body": "@esote `timeit` and `matplotlib`, as detailed in [this question](https://codereview.stackexchange.com/questions/165245/plot-timings-for-a-range-of-inputs) (and it's answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T16:56:28.850", "Id": "408170", "Score": "0", "body": "I tried to implement this, but I broke the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:01:23.967", "Id": "408172", "Score": "0", "body": "I just don't seem to know what functions you're specifying with the \"all_equal\", and \"overlap_chance_real\" If I intend to replace them with some of my written functions, it doesn't work :/. What changes have to be made exactly when reviewing the answer from you? I'm a newbie to be honest" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:04:17.023", "Id": "408174", "Score": "0", "body": "@Beginner-Coder123: The \"he\" is me. For the function `overlap_chance` to work, you need to copy all code in the first codeblock (it has the `all_equal` function defined in there and should also include all necessary imports). For `overlap_chance_real` to work you need to copy everything in the second code block. Both functions can be called e.g. as `overlap_chance(Die1, Die2)` (so just like your function). Both functions assume you have Python 3." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:05:48.220", "Id": "408175", "Score": "1", "body": "Haha, yes I made the mistake with specifying who it was. but alright, I'll give it a try. Much appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:12:32.243", "Id": "408176", "Score": "0", "body": "@Graipher I believe I got it? I updated the code so you can take a look at it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:16:24.560", "Id": "408177", "Score": "0", "body": "@Beginner-Coder123: Please have a look at [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) (especially the second part). If you have changed code or updated code and think there are further improvements possible, you can always ask a follow-up question, linking to this one. I have rolled back your edit. This is so that the answers you already got (including this one) are not invalidated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:20:04.417", "Id": "408178", "Score": "0", "body": "@Graipher I have changed the code. But it is still giving me an error code, what should I do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T17:21:00.847", "Id": "408179", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/88015/discussion-between-graipher-and-beginner-coder123)." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:44:12.077", "Id": "211041", "ParentId": "211022", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:11:39.807", "Id": "211022", "Score": "5", "Tags": [ "python", "python-3.x", "dice" ], "Title": "Arbitrary Dice with Probability" }
211022
<p>I was bored the other day and got to wondering how I would implement a circular FIFO buffer in Rust. My goal was to create an implementation I could use on a bare metal microcontroller. This means no dynamic allocation and a fixed size known at compile time, so I used a <a href="https://doc.rust-lang.org/std/primitive.array.html" rel="noreferrer">primitive fixed size array</a> instead of a vector as a backing store.</p> <p>My next pass at this will be to make the type stored in the FIFO buffer generic and to find a way to specify the capacity, but I wanted to get some feedback before doing so. Am I missing any test cases? What can I improve here?</p> <h3>src/lib.rs</h3> <pre><code>const FIFO_CAPACITY: usize = 32; pub struct Fifo { size: usize, read_idx: usize, write_idx: usize, buffer: [u8; FIFO_CAPACITY] } impl Fifo { pub fn new() -&gt; Fifo { Fifo { size: 0, read_idx: 0, write_idx: 0, buffer: [0; FIFO_CAPACITY] } } pub fn push(&amp;mut self, item: u8) -&gt; Result&lt;(), &amp;'static str&gt; { if self.buffer_full() { Err("Buffer full.") } else { self.buffer[self.write_idx] = item; self.write_idx = Fifo::increment_index(self.write_idx); self.size = self.size + 1; Ok(()) } } pub fn pop(&amp;mut self) -&gt; Option&lt;u8&gt; { if self.size == 0 { None } else { let result = self.buffer[self.read_idx]; self.read_idx = Fifo::increment_index(self.read_idx); self.size = self.size - 1; Some(result) } } pub fn buffer_full(&amp;self) -&gt; bool { self.size == FIFO_CAPACITY } fn increment_index(idx: usize) -&gt; usize { (idx + 1) % FIFO_CAPACITY } } #[cfg(test)] mod tests { use super::*; #[test] fn pop_item_that_was_pushed_to_buffer() { let mut buffer = Fifo::new(); assert!(buffer.push(5).is_ok()); let pop_result = buffer.pop(); assert_eq!(Some(5), pop_result); } #[test] fn popping_empty_buffer_returns_none() { let mut buffer = Fifo::new(); assert_eq!(None, buffer.pop()); } #[test] fn popping_returns_first_pushed_first() { let mut buffer = Fifo::new(); assert!(buffer.push(1).is_ok()); assert!(buffer.push(2).is_ok()); assert_eq!(Some(1), buffer.pop()); assert_eq!(Some(2), buffer.pop()); } #[test] fn pop_beyond_write_index_returns_none() { let mut buffer = Fifo::new(); assert!(buffer.push(1).is_ok()); assert_eq!(Some(1), buffer.pop()); assert_eq!(None, buffer.pop()); } #[test] fn pop_beyond_write_index_continuing_on_works() { let mut buffer = Fifo::new(); assert!(buffer.push(1).is_ok()); assert_eq!(Some(1), buffer.pop()); assert_eq!(None, buffer.pop()); assert!(buffer.push(2).is_ok()); assert_eq!(Some(2), buffer.pop()); } #[test] fn buffer_wraps_around() { let mut buffer = Fifo::new(); let capacity = FIFO_CAPACITY as u8; for x in 0..=(capacity * 3) { assert!(buffer.push(x).is_ok()); assert_eq!(Some(x), buffer.pop()); } } #[test] fn push_fails_if_buffer_is_full() { let mut buffer = Fifo::new(); let capacity = FIFO_CAPACITY as u8; for x in 0..(capacity) { assert!(buffer.push(x).is_ok()); } assert!(buffer.push(capacity + 1).is_err()) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:09:26.687", "Id": "408039", "Score": "1", "body": "Bare metal FIFO usually implies access from ISRs. Any concerns about concurrency?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T20:58:56.017", "Id": "408043", "Score": "0", "body": "The systems I typically work with are single core and ISRs queue, so let’s say no @vnp. Not a real concern, but I’d be happy to learn something anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T07:12:28.837", "Id": "408085", "Score": "0", "body": "FIFO is a communication device. If we rule out ISRs, what does communicate with what on a bare metal? Mainline to itself seems rather strange. Thread to thread, perhaps, then what is the scheduling policy? The detailed use case would be utterly helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:54:45.243", "Id": "408112", "Score": "0", "body": "@vnp I didn't say ISRs wouldn't be involved. I said they're single core, single thread devices where ISRs queue, so only one ISR can be executing at any point in time." } ]
[ { "body": "<p>Your code looks pretty decent. My two cents:</p>\n\n<ol>\n<li><p>Implement <code>Default</code></p>\n\n<pre><code>impl Default for Fifo {\n fn default() -&gt; Fifo {\n Fifo {\n size: 0,\n read_idx: 0,\n write_idx: 0,\n buffer: [0; FIFO_CAPACITY],\n }\n }\n}\n</code></pre>\n\n<p>Then you could simplify your <code>new</code> to:</p>\n\n<pre><code>pub fn new() -&gt; Fifo {\n Fifo::default()\n}\n</code></pre></li>\n<li><p>Simplify expressions</p>\n\n<p>L27: <code>self.size = self.size + 1</code> will become <code>self.size += 1</code><br>\nL40: <code>self.size = self.size - 1</code> will become <code>self.size -= 1</code></p></li>\n<li><p>Replace str error with enums</p>\n\n<pre><code>pub enum FifoError {\n FifoFull,\n}\n\npub fn push(&amp;mut self, item: u8) -&gt; Result&lt;(), FifoError&gt; {\n if self.buffer_full() {\n Err(FifoError::FifoFull)\n } else {\n ...\n}\n</code></pre></li>\n<li><p>Add <code>assert_eq!(None, buffer.pop());</code> to the end of every test where feasible, e,g.</p>\n\n<ul>\n<li><code>pop_item_that_was_pushed_to_buffer</code></li>\n<li><code>popping_returns_first_pushed_first</code></li>\n<li><code>pop_beyond_write_index_continuing_on_works</code></li>\n<li><code>buffer_wraps_around</code></li>\n</ul></li>\n</ol>\n\n<p>For further exercices I would recommend:</p>\n\n<ol>\n<li>Implement <code>Iterator</code>/<code>IntoIterator</code>/<code>FromIterator</code></li>\n<li>Next, implement Debug, which is fairly easy (Hint: Take a look at the implementation of Debug for <a href=\"https://doc.rust-lang.org/std/primitive.slice.html\" rel=\"noreferrer\"><code>slice</code></a>)</li>\n<li>Make it accept a generic type</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:20:29.657", "Id": "407966", "Score": "0", "body": "Nice review! I think I might actually implement a custom error type instead of the enum. Would you mind explaining the benefit of implementing `Default` for the struct? I think I understand what it does, but don't quite see how that helps me in this particular case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:35:39.197", "Id": "407969", "Score": "0", "body": "Some traits or methods require Default, e.g. [`Vec::resize_default`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize_default), which is a more convenient way of `resize`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:40:36.540", "Id": "407971", "Score": "0", "body": "It's getting even more fancy if you do something like [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d8e25d09507a63d7e7139153c3f0a3e8)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:45:36.887", "Id": "407972", "Score": "5", "body": "Quoting [Matthieu](https://chat.stackoverflow.com/transcript/message/45000109#45000109): *\"There's no introspection in Rust, you can't try to invoke a constructor with no parameter and hope it works in generic code: a trait MUST describe the available functionality. Using Default is the way to ensure that whoever wishes to use the struct where Default is required will be able to without wrapping it.\"*" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:14:12.243", "Id": "211025", "ParentId": "211023", "Score": "12" } }, { "body": "<p>As a generic remark, note that your FIFO always satisfies the invariant:</p>\n\n<pre><code>write_idx == (read_idx + size) % FIFO_CAPACITY\n</code></pre>\n\n<p>Thus, if you wanted to save some space, you could get rid of the <code>write_idx</code> property entirely and rewrite your <code>push</code> method as:</p>\n\n<pre><code>pub fn push(&amp;mut self, item: u8) -&gt; Result&lt;(), &amp;'static str&gt; {\n if self.buffer_full() {\n Err(\"Buffer full.\")\n } else {\n let write_idx = Fifo::wrap_around(self.read_idx + self.size);\n self.buffer[write_idx] = item;\n\n self.size = self.size + 1;\n\n Ok(())\n }\n}\n\nfn wrap_around(idx: usize) -&gt; usize {\n idx % FIFO_CAPACITY\n}\n</code></pre>\n\n<p>Note that storing <em>only</em> <code>read_idx</code> and <code>write_idx</code> and getting rid of <code>size</code> instead would <em>not</em> work, since there are two different situations where <code>read_idx == write_idx</code>: when the buffer is empty, and when it is full. Storing <code>size</code> explicitly lets you differentiate between those two cases, since an empty FIFO has <code>size == 0</code> while a full one has <code>size == FIFO_CAPACITY</code>.</p>\n\n<p>I would also replace the line</p>\n\n<pre><code>self.read_idx = Fifo::increment_index(self.read_idx);\n</code></pre>\n\n<p>in your <code>pop</code> method with</p>\n\n<pre><code>self.read_idx = Fifo::wrap_around(self.read_idx + 1);\n</code></pre>\n\n<p>and get rid of the <code>increment_index</code> method entirely, since it's kind of redundant with the more general-purpose <code>wrap_around</code> method above.</p>\n\n<hr>\n\n<p>One interesting side effect of the <code>push</code> rewrite I suggested above is that (as seen below) it allows the compiler omit the array bounds check, since it can tell that the index returned by the <code>wrap_around</code> method is always within the bounds of the array. We can enable the same optimization for <code>pop</code> by moving the <code>wrap_around</code> call before the array access, e.g. like this:</p>\n\n<pre><code>pub fn pop(&amp;mut self) -&gt; Option&lt;u8&gt; {\n if self.size == 0 {\n None\n } else {\n self.read_idx = Fifo::wrap_around(self.read_idx); \n let result = self.buffer[self.read_idx];\n self.read_idx = self.read_idx + 1;\n self.size = self.size - 1;\n Some(result) \n }\n}\n</code></pre>\n\n<p>Note that, with this change, it becomes possible for <code>self.read_idx</code> to be equal to <code>FIFO_CAPACITY</code> after a call to <code>pop</code>. But that doesn't matter, since any values there will still be correctly wrapped before being used to access the buffer (but see the note at the end of the next section below!).</p>\n\n<hr>\n\n<p>Also, since you say this code is intended for a microcontroller, it's worth keeping in mind that division and remainder can be rather slow operations on low-end microcontrollers.</p>\n\n<p>If your FIFO capacity is always a power of two (like it is in your example code), and given that you're working with unsigned integers, it's likely that the compiler will be able to optimize the <code>idx % FIFO_CAPACITY</code> operation into a bitwise AND, in which case your current code is probably optimal. Otherwise, however, you may want to consider manually replacing the remainder operation with a comparison, something like this:</p>\n\n<pre><code>fn wrap_around(idx: usize) -&gt; usize {\n if idx &lt; FIFO_CAPACITY {\n idx\n } else {\n idx - FIFO_CAPACITY\n }\n}\n</code></pre>\n\n<p>The compiler will not be able to make this optimization automatically, since this function will behave differently than your original if <code>idx &gt;= 2 * FIFO_CAPACITY</code>. We know that can never actually happen in this code, but the compiler (probably) isn't that smart.</p>\n\n<p>Unfortunately, this version of <code>wrap_around</code> is more efficient than the original for non-power-of-two buffer sizes, it's likely to be <em>less</em> efficient when the capacity <em>is</em> a power of two. But with a bit of cleverness and trust in the compiler's optimization (specifically, constant folding and dead code elimination) skills, we can actually get optimal code for both cases, like this:</p>\n\n<pre><code>fn wrap_around(idx: usize) -&gt; usize {\n if Fifo::is_power_of_2(FIFO_CAPACITY) {\n idx &amp; (FIFO_CAPACITY - 1) // faster when capacity is a power of 2\n } else if idx &lt; FIFO_CAPACITY {\n idx\n } else {\n idx - FIFO_CAPACITY\n }\n}\n\nfn is_power_of_2(num: usize) -&gt; bool {\n num &amp; (num - 1) == 0\n}\n</code></pre>\n\n<p>The expression <code>num &amp; (num - 1)</code> evaluates to zero <a href=\"https://stackoverflow.com/questions/108318/whats-the-simplest-way-to-test-whether-a-number-is-a-power-of-2-in-c\">if and only if <code>num</code> is a power of two</a> (or zero, but that's not a valid capacity anyway). Since <code>FIFO_CAPACITY</code> is a constant, the compiler will evaluate <code>Fifo::is_power_of_2(FIFO_CAPACITY)</code> at compile time, and optimize away the branch that isn't taken. Thus, we get both highly efficient code for power-of-two sizes, and nearly as fast code for sizes that are <em>not</em> powers of two.</p>\n\n<p>Ps. The combination of all these optimizations does create a somewhat subtle edge case: with the optimized <code>pop</code> implementation, it's possible for both <code>self.read_idx</code> and <code>self.size</code> to equal <code>FIFO_CAPACITY</code> when the buffer is full, potentially causing <code>Fifo::wrap_around(self.read_idx + self.size)</code> <em>not</em> to be a valid index into the buffer if the buffer size is not a power of two. (This can happen e.g. after pushing <code>FIFO_CAPACITY</code> items into a new FIFO, popping them all off and then pushing <code>FIFO_CAPACITY</code> more items again.) Fortunately, this can <em>only</em> occur when the buffer is full, in which case pushing more items will fail anyway, so the invalid array access will never actually be attempted. (And of course we're still using Rust, so the compiler does add bounds checks to make sure of that!) But it's a case that should definitely be tested.</p>\n\n<hr>\n\n<p><strong>Addendum:</strong> It turns out that <a href=\"https://rust.godbolt.org/\" rel=\"nofollow noreferrer\">godbolt.org supports Rust</a>, so we can do some experiments to see how these changes affect the generated assembly.</p>\n\n<p>First, <a href=\"https://rust.godbolt.org/z/XLCZer\" rel=\"nofollow noreferrer\">let's take a look at your original code</a>, with <code>FIFO_CAPACITY</code> set to 32. I'll compile it with the <code>-O</code> switch, which enables a moderate level of compiler optimization, and with <code>--target=arm-unknown-linux-gnueabi</code> to produce ARM instead of x86 assembly (<a href=\"https://codereview.stackexchange.com/posts/comments/408088\">thanks, hellow</a>!).</p>\n\n<p>Here's what your <code>push</code> and <code>pop</code> methods looks like in ARM assembly, with some manual annotations for readers not so familiar with the syntax. Note how the calls to <code>buffer_full</code> and <code>increment_index</code> have been inlined:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>example::Fifo::push:\n ldr r2, [r0] @ r2 = self.size\n cmp r2, #32 @ r2 == FIFO_CAPACITY?\n\n ldreq r0, .LCPI1_0 @ Err(\"Buffer full.\")\n moveq r1, #12\n addeq r0, pc, r0\n bxeq lr\n\n ldr r2, [r0, #8] @ r2 = self.write_idx\n cmp r2, #31 @ [array bounds check]\n\n addls r2, r0, r2 @ self.buffer[r2] = r1\n strbls r1, [r2, #12]\n\n ldrls r1, [r0] @ r1 = self.size\n ldrls r2, [r0, #8] @ r2 = self.write_idx\n addls r1, r1, #1 @ r1 = r1 + 1\n strls r1, [r0] @ self.size = r1\n\n addls r1, r2, #1 @ r1 = r2 + 1\n andls r1, r1, #31 @ r1 = r1 &amp; (FIFO_CAPACITY-1)\n strls r1, [r0, #8] @ self.write_idx = r1\n\n movls r1, #0 @ Ok(())\n movls r0, #0\n bxls lr\n\n push {r11, lr} @ [array bounds check failed]\n ldr r0, .LCPI1_1\n mov r1, r2\n mov r2, #32\n add r0, pc, r0\n bl core::panicking::panic_bounds_check\n\nexample::Fifo::pop:\n ldr r3, [r0] @ r3 = self.size\n cmp r3, #0 @ if (r3 == 0) goto .LBB2_2 \n beq .LBB2_2\n\n ldr r2, [r0, #4] @ r2 = self.read_idx\n cmp r2, #31 @ [array bounds check]\n\n addls r1, r0, r2 @ r1 = self.buffer[r2] (interleaved...)\n\n addls r2, r2, #1 @ r2 = r2 + 1\n subls r3, r3, #1 @ r3 = r3 - 1\n andls r2, r2, #31 @ r2 = r2 &amp; (FIFO_CAPACITY-1)\n\n ldrbls r1, [r1, #12] @ r1 = self.buffer[r2] (...interleaved)\n\n strls r3, [r0] @ self.size = r3\n strls r2, [r0, #4] @ self.read_idx = r2\n\n movls r0, #1 @ Some(r1)\n bxls lr\n\n push {r11, lr} @ [array bounds check failed]\n ldr r0, .LCPI2_0\n mov r1, r2\n mov r2, #32\n add r0, pc, r0\n bl core::panicking::panic_bounds_check\n\n.LBB2_2:\n mov r0, #0 @ None\n bx lr\n</code></pre>\n\n<p>In general, this doesn't look too bad. For <code>push</code> there are four loads (one of which the compiler <em>could</em> have optimized out, but didn't), three stores and no branches (due to the use of conditional code instead), while <code>pop</code> has three loads, two stores and one branch (for the <code>self.size == 0</code> case) that the compiler for some reason didn't replace with conditional code. There's no particularly slow arithmetic (since the <code>%</code> operation was optimized into a bitwise <code>&amp;</code>), and while the unnecessary array bounds checks bloat the code a little bit, their effect on execution time should be negligible.</p>\n\n<p>Now let's see how the same code would look <a href=\"https://rust.godbolt.org/z/908R4o\" rel=\"nofollow noreferrer\">with the modifications I suggested</a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>example::Fifo::push:\n ldr r2, [r0] @ r2 = self.size\n cmp r2, #32 @ r2 == FIFO_CAPACITY?\n\n ldreq r0, .LCPI1_0 @ Err(\"Buffer full.\")\n moveq r1, #12\n addeq r0, pc, r0\n bxeq lr\n\n ldr r3, [r0, #4] @ r3 = self.read_idx\n add r3, r3, r2 @ r3 = r3 + r2\n and r3, r3, #31 @ r3 = r3 &amp; (FIFO_CAPACITY-1)\n\n add r3, r0, r3 @ self.buffer[r3] = r1\n strb r1, [r3, #8]\n\n add r1, r2, #1 @ r1 = r2 + 1\n str r1, [r0] @ self.size = r1\n\n mov r1, #0 @ Ok(())\n mov r0, #0\n bx lr\n\nexample::Fifo::pop:\n ldr r2, [r0] @ r2 = self.size\n cmp r2, #0 @ if (r2 == 0) goto .LBB2_2\n beq .LBB2_2\n\n ldr r1, [r0, #4] @ r1 = self.read_idx\n sub r2, r2, #1 @ r2 = r2 - 1\n and r3, r1, #31 @ r3 = r1 &amp; (FIFO_CAPACITY-1)\n\n add r1, r0, r3 @ r1 = self.buffer[r3] (interleaved...)\n add r3, r3, #1 @ r3 = r3 + 1\n ldrb r1, [r1, #8] @ r1 = self.buffer[r3] (...interleaved)\n\n stm r0, {r2, r3} @ self.size = r2, self.read_idx = r3\n\n mov r0, #1 @ Some(r1)\n bx lr\n\n.LBB2_2:\n mov r0, #0 @ None\n bx lr\n</code></pre>\n\n<p>The first six instructions in <code>push</code> (which implement the buffer fullness check) are exactly the same. The rest, however, looks a bit simpler: now we have only two loads and two stores, and the unnecessary array bounds check is also gone (because the compiler can now tell that the wrapped index can never overflow the array).</p>\n\n<p>In the <code>pop</code> method, the <code>self.size == 0</code> check is compiled into the exact same code as before (still with an explicit branch, for some reason), and we still have the same number of loads and stores (although this time the compiler managed to merge the two stores into a single <code>stm</code> instruction). Here, as well, avoiding the array bounds check makes the code shorter and simpler.</p>\n\n<hr>\n\n<p>OK, but what about non-power-of-two buffer sizes? Well, ideally, you'd probably want to avoid them entirely, if you want to maximize performance. But what if you just <em>had to</em> use a buffer capacity that wasn't a power of two?</p>\n\n<p>Well, here's what the <code>increment_index</code> call in your <code>push</code> method compiles to <a href=\"https://rust.godbolt.org/z/F1H2LP\" rel=\"nofollow noreferrer\">with <code>FIFO_CAPACITY</code> set to 37</a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> addls r1, r2, #1 @ r1 = self.write_idx + 1\n ldrls r2, .LCPI1_0 @ r2 = 3134165325 (!)\n umullls r2, r3, r1, r2 @ r3 = (r1 * r2) &gt;&gt; 32 \n subls r2, r1, r3 @ r2 = r1 - r3\n addls r2, r3, r2, lsr #1 @ r2 = r3 + (r2 &gt;&gt; 1)\n movls r3, #37 @ r3 = FIFO_CAPACITY\n lsrls r2, r2, #5 @ r2 = r2 &gt;&gt; 5\n mulls r2, r2, r3 @ r2 = r2 * r3\n subls r1, r1, r2 @ r1 = r1 - r2\n\n.LCPI1_0:\n .long 3134165325\n</code></pre>\n\n<p>Wait, what the heck is going on here?</p>\n\n<p>Well, what's going on is <a href=\"https://homepage.divms.uiowa.edu/~jones/bcd/divide.html\" rel=\"nofollow noreferrer\">reciprocal multiplication</a>. Basically, since division is one of the slowest arithmetic operations on any modern CPU, compilers use <a href=\"https://stackoverflow.com/questions/41183935/why-does-gcc-use-multiplication-by-a-strange-number-in-implementing-integer-divi\">clever arithmetic tricks</a> to <a href=\"https://reverseengineering.stackexchange.com/questions/1397/how-can-i-reverse-optimized-integer-division-modulo-by-constant-operations\">replace division (and modulo) by a constant</a> with a combination of multiplications and shifts.</p>\n\n<p>So, basically, instead of calculating <code>idx = idx % 37</code> directly, the assembly code generated by the compiler effectively calculates</p>\n\n<pre><code>tmp = (3134165325 * idx) &gt;&gt; 32;\navg = tmp + ((idx - tmp) &gt;&gt; 1);\nidx = idx - (avg &gt;&gt; 5) * 37\n</code></pre>\n\n<p>using unsigned 32-bit arithmetic (except with the first multiplication calculated as a 64-bit result, the lower half of which is immediately discarded). If you want, you can verify that this indeed produces the same results as the normal remainder calculation!</p>\n\n<p>(It may be illustrative to do the calculation step by step for <code>idx</code> = 37. You'll find that <code>tmp</code> works out to 27, and their average <code>avg</code> to 32, which when shifted right by 5 bits yields 1. If <code>idx</code> = 36, however, then <code>tmp</code> = 26 and <code>avg</code> = 31, which yields 0 when shifted right. Clever!)</p>\n\n<p>Meanwhile, however, in <a href=\"https://rust.godbolt.org/z/COp6tZ\" rel=\"nofollow noreferrer\">my optimized version</a> the equivalent code (sans increment) compiles to just this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> subs r2, r3, #37 @ r2 = r3 - 37\n movlo r2, r3 @ if (r2 &lt; 0) r2 = r3\n</code></pre>\n\n<p>Not nearly as clever and enigmatic, perhaps, but a lot simpler and faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:32:04.623", "Id": "408049", "Score": "1", "body": "The write index is not a function of read index. If I write twice, but never pop, the write index moves while the read index stays stationary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:33:22.433", "Id": "408050", "Score": "0", "body": "I’m also extremely dubious of the “optimization” you propose. I’m willing to bet the assembly is nearly identical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:39:49.083", "Id": "408052", "Score": "2", "body": "@RubberDuck The write index is a function of read index *and size*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T22:59:20.857", "Id": "408056", "Score": "1", "body": "Its more a question of consistency (as the invariance states in the answer always holds) as a question of space optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T07:29:49.997", "Id": "408088", "Score": "1", "body": "You can choose the target architecture by using `--target=arm-unknown-linux-gnueabi`. To get a list of known targets use `--print target-list`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T12:50:16.463", "Id": "408108", "Score": "0", "body": "I appreciate the effort, but it does nothing to convince me. A) This makes the code harder to read, and until/unless I use it in a real situation where I can prove this is an actual bottleneck, this makes the code worse. B) I'm not targeting x86_64, so it's likely the assembly would be different for my target. C) If I was interested in this kind of micro optimization, I would inline the assembly code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T19:31:44.293", "Id": "211057", "ParentId": "211023", "Score": "6" } } ]
{ "AcceptedAnswerId": "211025", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T12:45:31.923", "Id": "211023", "Score": "13", "Tags": [ "rust", "circular-list" ], "Title": "Circular FIFO Buffer" }
211023
<p>I have the following Qt class:<br> <strong>mainwindow.h</strong></p> <pre><code>class MainWindow : public QWidget { Q_OBJECT QPushButton* m_button; public: explicit MainWindow(); }; </code></pre> <p><strong>mainwindow.cpp</strong></p> <pre><code>MainWindow::MainWindow() { auto main_layout = new QHBoxLayout; m_button = new QPushButton("Press me"); main_layout-&gt;addWidget(m_button); setLayout(main_layout); connect(m_button, &amp;QPushButton::pressed, [this] { m_button-&gt;setText("Presse me again"); }); } </code></pre> <p>It features a button which once pressed will change its text to "Press me again". I use a lambda function and I am capturing by copy <code>this</code> to access the button inside the lambda.</p> <p>As the QPushButton is allocated on the heap, I think that making it a class member is an unnecessary step. My question: Are there any drawbacks if I instead use it as a local pointer which I would capture by copy in the <code>connect</code> lambda ? It would look like this: </p> <p><strong>mainwindow.h</strong></p> <pre><code>class MainWindow : public QWidget { Q_OBJECT public: explicit MainWindow(); }; </code></pre> <p><strong>mainwindow.cpp</strong></p> <pre><code>MainWindow::MainWindow() { auto main_layout = new QHBoxLayout; auto button = new QPushButton("Press me"); main_layout-&gt;addWidget(button); setLayout(main_layout); connect(button, &amp;QPushButton::pressed, [button] { // I am copying the button's address here button-&gt;setText("Presse me again"); }); } </code></pre> <p>One thing to note: Qt manages the destruction of all Qt classes automatically, so no need to call the button's destructor later if I understood correctly <a href="https://forum.qt.io/topic/24451/when-to-call-destructor" rel="nofollow noreferrer">this conversation</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T13:42:50.127", "Id": "211026", "Score": "3", "Tags": [ "c++", "comparative-review", "pointers", "heap", "qt" ], "Title": "Basic Qt5 UI with button" }
211026
<p>I've made a simple function, this time in jQuery rather than <a href="https://codereview.stackexchange.com/questions/210883/a-simple-function-that-removes-empty-or-tags-containing-just-nbsp">JS</a>, that just removes empty <code>&lt;p&gt;&lt;/p&gt;</code>, span and strong tags. I'm curious to see what everyone thinks about my solution as I'm relatively new to jQuery, and whether it could be improved. My original solution is as follows:</p> <pre><code>$('p').filter(function() { return ($(this).html().trim() == '&amp;nbsp;'); }).remove(); $('span').filter(function() { return ($(this).html().trim() == '&amp;nbsp;'); }).remove(); $('span').filter(function() { return ($(this).html().trim() == ''); }).remove(); $('strong').filter(function() { return ($(this).html().trim() == ''); }).remove(); $('p').filter(function() { return ($(this).html().trim() == ''); }).remove(); </code></pre> <p>This isn't exactly dry... So I made a couple of other solutions:</p> <pre><code>/* MY DRIER SOLUTION 1 */ $.fn.jCleaner = function() { return $(this).filter(function() { return ($(this).text().trim() === '&amp;nbsp;' || $(this).text().trim() === ''); }).remove(); } $('p, span, strong').jCleaner(); /* MY DRIER SOLUTION 2 */ function jCleaner() { return $(this).filter(function() { return ($(this).text().trim() == '&amp;nbsp;' || $(this).text().trim() === ''); }).remove(); } $('p, span, strong').each(jCleaner); </code></pre> <p>And the original HTML is:</p> <pre><code>/* ORIGINAL HTML */ &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id='test'&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;text&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;span&gt;text&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;text&lt;/p&gt; &lt;/div&gt; </code></pre> <p>So my questions are essentially how can my solutions be improved (if at all)? I had to write an entire function and then call it on each element. Thanks for any advice here.</p> <p>Note: here's the solution in JS:</p> <pre><code>document.querySelectorAll("span, p, strong") .forEach(el =&gt; el.textContent.trim() === "" &amp;&amp; el.parentNode.removeChild(el)) </code></pre>
[]
[ { "body": "<p>\"This isn't exactly DRY\" is pretty much what I think about</p>\n\n<blockquote>\n<pre><code>$(this).text().trim() == '&amp;nbsp;' || $(this).text().trim() === ''\n</code></pre>\n</blockquote>\n\n<p><code>text()</code> can be a very expensive call: I would refactor to only do <code>$(this).text().trim()</code> once.</p>\n\n<hr>\n\n<p>As a minor concern, the use of <code>trim()</code> suggests that you want to remove nodes whose text is purely whitespace. So shouldn't a node whose text is <code>&amp;nsbp; &amp;nbsp;</code> be removed? Perhaps you should be using a regex match instead of <code>trim()</code>? Something like (warning: untested) <code>$(this).text().match(/^(\\s|&amp;nbsp;)*$/)</code>.</p>\n\n<p>And then you could take it further: <code>&amp;nbsp;</code> isn't the only way of escaping <code>U+00a0</code>, and the other whitespace characters can also be escaped in various ways...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T09:52:04.200", "Id": "211088", "ParentId": "211035", "Score": "2" } } ]
{ "AcceptedAnswerId": "211088", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T14:54:18.437", "Id": "211035", "Score": "1", "Tags": [ "javascript", "jquery", "html", "dom" ], "Title": "A simple jQuery function that removes empty or tags containing just '&nbsp;'" }
211035
<p>Today I just completed a personal POST function that emulates jQuery's using $.ajax, but also implementing a possible redirect. I just finished up and it looks like it is functional, but since this is something I want to keep long term and integrate in many projects, I want to make sure it is as functional as possible. </p> <pre><code>function postR(url, params, redir = false, callback = null) { if(redir){ var form = document.createElement('form'); form.method = 'post'; form.action = url; for (var key in params) { var input = document.createElement('input'); input.type = 'hidden'; input.name = key; input.value = params[key]; form.appendChild(input); } document.body.appendChild(form); form.submit(); }else{ if(callback &amp;&amp; typeof(callback) === "function"){ $.ajax({ type: "POST", url: url, data: params, success: function(data){ callback(data) } }); }else{ $.ajax({ type: "POST", url: url, data: params }); } } } </code></pre> <p>The purpose for building this was because I wanted to use jQuery's post function to do some JS work with a form before it was submitted, but also wanted to redirect alongside the POST request, like a natural form.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T17:33:44.113", "Id": "408008", "Score": "0", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>I would:</p>\n\n<ul>\n<li>Use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData\" rel=\"nofollow noreferrer\">FormData</a> instead of creating a form element. </li>\n<li>Give it a name better than \"postR\", like... simply \"post\"?</li>\n<li>Add an error handler to the $.ajax call</li>\n<li>Unify both $.ajax calls</li>\n</ul>\n\n<p>Pseudo code (Not tested):</p>\n\n<pre><code>function post(url, params, redir = false, callback = null) {\n var formData = new FormData();\n\n for (var key in params) {\n formData.append(key, value);\n }\n\n $.ajax({\n type: \"POST\",\n url: url,\n data: formData,\n success: function(data) {\n typeof(callback) === \"function\" &amp;&amp; callback(data);\n redir &amp;&amp; window.location.reload();\n }\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T17:52:00.850", "Id": "408011", "Score": "0", "body": "I have it as postR to signify post Redirect, but that's just for me, not worried about keeping it lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T18:00:54.300", "Id": "408012", "Score": "1", "body": "Looking at the redirect, does window.location.reload bring you to the destination of the POST request? To me it looks like it will just reload that page after sending the data, where I am trying to redirect WITH the POST data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:05:22.827", "Id": "408044", "Score": "0", "body": "@guest271314 Yes - Fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:07:04.073", "Id": "408045", "Score": "0", "body": "@NebulaCoding Yes, it will reload, but only after the POST was sent successfully. It have the same effects, try it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:13:20.763", "Id": "408048", "Score": "0", "body": "Understood. If for whatever reason I couldn't achieve my desired functionality with my other setup, I would use this." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T17:11:47.153", "Id": "211050", "ParentId": "211036", "Score": "3" } }, { "body": "<p>I have incorporated some of the things suggested, but I still don't understand exactly how I should do error reporting. I got rid of the second If..Else statement, and also swapped to not use .ajax but XmlHttpRequest(). I did swap to using FormData as well.</p>\n\n<pre><code>function postR(url, params, redir = false, callback = null) {\n if(redir){\n var form = document.createElement('form');\n form.method = 'post';\n form.action = url;\n for (var key in params) {\n var input = document.createElement('input');\n input.type = 'hidden';\n input.name = key;\n input.value = params[key];\n form.appendChild(input);\n }\n\n document.body.appendChild(form);\n form.submit();\n }else{\n let xhttp, formData;\n xhttp = new XMLHttpRequest();\n formData = new FormData();\n\n xhttp.onreadystatechange = function(){\n if(this.readyState == 4){\n if(this.status == 200){\n if(callback){\n callback(this.responseText);\n }else{\n console.log(`POST succeeded`);\n }\n }else{\n console.log(`Some error has occurred, error status: ${this.status}, text: ${this.statusText}`);\n }\n }\n };\n xhttp.open('POST', url, true);\n for(let key in params){\n if(params.hasOwnProperty(key)) {\n formData.append(key, params[key]);\n }\n }\n xhttp.send(formData);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T17:54:36.943", "Id": "211052", "ParentId": "211036", "Score": "0" } }, { "body": "<p>Your <code>XMLHttpRequest</code> example looks good, as well as the redirection part. However, to avoid confusion and improve readability, I would divide it into two different functions.</p>\n\n<p><strong>1)</strong> Overwriting <code>$.post</code> is not an easy task as it may seem, but as a basic example you can use something similar to the following, which supports <code>error</code> and <code>success</code> callbacks:</p>\n\n<pre><code>/**\n * Send a POST request\n * @param {String} url\n * @param {Object} params\n * @param {Function} success\n * @param {Function} error\n * @returns {XMLHttpRequest}\n */\nfunction post(url, params, success, error) {\n let xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n success &amp;&amp; success(xhr.responseText);\n } else {\n error &amp;&amp; error(xhr.responseText);\n }\n }\n };\n\n let formData = new FormData();\n for (let p in params) {\n formData.append(p, params[p]);\n }\n\n xhr.open('POST', url);\n xhr.send(formData);\n return xhr;\n}\n</code></pre>\n\n<p><strong>2)</strong> As I mentioned, the redirection part from your function is good. However, you have an additional option to simulate the redirection. The idea is to load HTML via a XHR request and use it to replace the current document. </p>\n\n<pre><code>/**\n * Simulate a redirection\n * @param {String} url\n * @param {Object} params\n * @returns {XMLHttpRequest}\n */\nfunction postR(url, params) {\n let success = error = function (data) {\n history.pushState('', '', url);\n document.open().write(data);\n document.close();\n };\n return post(url, params, success, error);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:11:52.253", "Id": "408046", "Score": "0", "body": "Got it. I do have some questions though, like why are we returning xhr at the end? Usually I call the function on its own, and not setting it equal to anything. Would this impact it at all, or is it just additional functionality?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T02:59:58.560", "Id": "408067", "Score": "0", "body": "@NebulaCoding You can safely remove it, since it does not affect anything. On the other hand, it does not interfere with anything, but sometimes it may seem useful. For example, you can get all HTTP headers in this way: `var xhr=post('?',{},function(){console.log(xhr.getAllResponseHeaders())});` (or modify the function and pass the `xhr` object to the callbacks). By the way, the jQuery always returns the `jqXHR` object as result of `$.post`, `$.get`, or `$.ajax`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T03:05:52.410", "Id": "408068", "Score": "0", "body": "Ah, see I didn't know jQuery did that. I figured it would be fine, but just wanted to make sure." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T21:00:08.713", "Id": "211061", "ParentId": "211036", "Score": "1" } }, { "body": "<p>It's really not a good idea to \"simulate\" a page change by messing with the history like is shown in the chosen answer. It might work for one case but as a general function it is a bad idea. I would however employ a helper function for generating DOM elements, and I would use fetch instead of xhr.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function post(url, params, redir = false, callback = null) {\n if (redir) {\n const mkele = (tag, props, parent) =&gt; {\n var ele = document.createElement(tag);\n for(prop in props) ele.setAttribute(prop, props[prop]);\n parent.appendChild(ele);\n return ele;\n };\n const form = mkele('form', {method:\"POST\", action:url}, document.body);\n for (let k in params) mkele('input', {name:k, value:params[k], type:'hidden'}, form);\n form.submit();\n } else {\n const fd = new FormData();\n for (let param in params) fd.append(param, params[param])\n fetch(url, {method:\"POST\", body:fd}).then(callback);\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-08T21:57:54.190", "Id": "211143", "ParentId": "211036", "Score": "0" } } ]
{ "AcceptedAnswerId": "211061", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:08:33.130", "Id": "211036", "Score": "2", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Replacement function for jQuery .post" }
211036