body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have written a pair of programs in Python that can be used to encrypt, decrypt, and crack Caesar and Vigenere Ciphered text. I am fairly new to Python and I wrote these programs largely to try and test myself on what I had learned so far with a practical problem, although I cannot claim that every line of these programs is my own. I would appreciate feedback related to any aspect of my program: Efficiency of my algorithms, efficiency of my implementation, quality of my Python, overlooked features, bugs, etc.</p> <p>I have included a sample of text I used for testing below.</p> <p><strong>vigenere.py</strong></p> <pre><code>#!/usr/bin/python3 """ vigenere.py - Vigenere tool, can use statistical analysis to guess keys of varying length for enciphered text Options: --encrypt - enable encryption mode --decrypt - enable decryption mode --preserve-spacing - preserve the spacing of the input in the output --key - specify the encryption key --spacing - specify the output spacing --guess - attempt to guess the encryption key by statistical analysis Todo: - Implement n-gram analysis to improve accuracy of key guesses - Perform frequency analysis of deciphered text to improve accuracy of key guesses Future: - Add support for multiple languages - Include standard deviations for each letter frequency - Get better numbers for frequency analysis """ import argparse import re import string from itertools import cycle def buildSubStrings(string, seperation): # Build all substrings required to analyse the polyalphabetic cipher return [string[i::seperation] for i in range(seperation)] def frequencyAnalysis(string): # Normalised frequency analysis freq = [0] * 26 for c in string: freq[ord(c) - ord('A')] += 1 total = sum(freq) for i in range(0, len(freq)): freq[i] /= (float(total) / 100) return freq def initialiseParser(): parser = argparse.ArgumentParser(description = "Encrypt or decrpyt a string using the Caesar Cipher") parser.add_argument("--encrypt", "--enc", "-e", help = "encryption mode (default)", action = "store_true") parser.add_argument("--decrypt", "--dec", "-d", help = "decryption mode", action = "store_true") parser.add_argument("--preserve-spacing", "--preserve", "-p", help = "use same spacing as the input text", action = "store_true", dest = "preserveSpacing") parser.add_argument("--key", "-k", help = "encryption key for vigenere cipher", type = str) parser.add_argument("--spacing", "-s", help = "specify the spacing in output", type = int) parser.add_argument("--guess", "-g", help = "Attempt to guess the most likely key value", action = "store_true") return parser def scoreCalculator(frequencyAnalysis, shift): # Calculates a weighted score for a given shift value englishFrequencies = [ 8.167, 1.492, 2.782, 4.253, 12.702, 2.228, 2.015, 6.094, 6.966, 0.153, 0.772, 4.025, 2.406, 6.749, 7.507, 1.929, 0.095, 5.987, 6.327, 9.056, 2.758, 0.978, 2.360, 0.150, 1.974, 0.074 ] score = 0 for index in range(0, 26): shiftIndex = (index + shift) % 26 score += abs(frequencyAnalysis[index] - englishFrequencies[shiftIndex]) return score / 26 def shiftCalculator(frequencyAnalysis): # Calculates the most likely shift value for a substring by comparing weighted scores of different shift values bestGuess = '' bestGuessScore = float('inf') for shift in range(1, 27): score = scoreCalculator(frequencyAnalysis, shift) if score &lt; bestGuessScore: bestGuessScore = score bestGuess = chr(ord('Z') - shift + 1) return bestGuess def stringPrepare(string, preserveSpacing): # Strip all non alphabetic characters from a string and convert to upper case if preserveSpacing == True: regex = '[^A-Z\s]' else: regex = '[^A-Z]' return re.compile(regex).sub('', string).upper() def vigenere(plaintext, key, encrypt): alphabet = string.ascii_uppercase output = '' shift = 1 if encrypt == False: shift = -1 for x, y in zip(stringPrepare(plaintext, False).upper(), cycle(key.upper())): output += alphabet[(alphabet.index(x) + alphabet.index(y) * shift) % 26] return output def main(): parser = initialiseParser() args = parser.parse_args() rawText = stringPrepare(str.upper(input('')), True) strippedText = stringPrepare(rawText, False) if args.decrypt or args.encrypt: if(args.key != None): output = vigenere(strippedText, args.key, args.encrypt) else: print("Error: No key given!") elif args.guess: maxGuess = 30 if len(strippedText) &gt; 30 else len(strippedText) keyList = list() for guess in range(2, maxGuess): substringList = buildSubStrings(strippedText, guess) frequencyAnalysisList = list() key = '' for subString in substringList: frequencyAnalysisList.append(frequencyAnalysis(subString)) for frequency in frequencyAnalysisList: key += shiftCalculator(frequency) keyList.append(key) bestGuess = '' bestGuessScore = float('inf') for key in keyList: score = scoreCalculator(frequencyAnalysis(str.upper(vigenere(strippedText, key, False))), 0) if score &lt; bestGuessScore: bestGuessScore = score bestGuess = key print("Best key guess: %s\nAttepting decryption..." % bestGuess) output = vigenere(strippedText, bestGuess, False) if args.preserveSpacing: for x in range(0, len(rawText)): if rawText[x] == ' ': output = output[:x] + ' ' + output[x:] # Reinsert the stripped spaces back into the output elif args.spacing: if args.spacing &gt; 0: output = ' '.join([output[i:i + args.spacing] for i in range(0, len(output), args.spacing)]) print(output) if __name__ == "__main__": main() </code></pre> <p><strong>caesar.py</strong></p> <pre><code>#!/usr/bin/python3 """ caesar.py - Caesar Cipher tool, can use statistical analysis to guess the shift value of Caesar Ciphered text Options: --bruteforce - attempt to bruteforce the shift value --encrypt - enable encryption mode --decrypt - enable decryption mode --preserve-spacing - preserve the spacing of the input in the output --shift - specify the shift value --spacing - specify the output spacing --guess - attempt to guess the shift value by statistical analysis Todo: - Implement n-gram analysis to improve accuracy of key guesses Future: - Add support for multiple languages - Include standard deviations for each letter frequency - Get better numbers for frequency analysis """ import argparse import re def caesar(string, shift): return "".join(chr(((ord(char) - 65 + shift) % 26) + 65) if not char.isspace() else " " for char in string) def frequencyAnalysis(string): # Normalised frequency analysis freq = [0] * 26 for c in string: if c.isalpha(): freq[ord(c) - ord('A')] += 1 total = sum(freq) for i in range(0, len(freq)): freq[i] /= (float(total) / 100) return freq def initialiseParser(): parser = argparse.ArgumentParser(description = "Encrypt or decrpyt a string using the Caesar Cipher") parser.add_argument("--bruteforce", "--brute", "-b", help = "bruteforce mode", action = "store_true") parser.add_argument("--encrypt", "--enc", "-e", help = "encryption mode (default)", action = "store_true") parser.add_argument("--decrypt", "--dec", "-d", help = "decryption mode", action = "store_true") parser.add_argument("--preserve-spacing", "--preserve", "-p", help = "use same spacing as original string", action = "store_true") parser.add_argument("--shift", "-s", help = "value for the Caesar shift", type = int, choices = range(1, 26)) parser.add_argument("--spacing", "-x", help = "specify the spacing in output", type = int) parser.add_argument("--guess", "-g", help = "use statistical analysis to guess the most likely shift value", action = "store_true") return parser def shiftScoreCalculator(frequencyAnalysis, shift): # Calculates a weighted score for a given shift value englishFrequencies = [ 8.167, 1.492, 2.782, 4.253, 12.702, 2.228, 2.015, 6.094, 6.966, 0.153, 0.772, 4.025, 2.406, 6.749, 7.507, 1.929, 0.095, 5.987, 6.327, 9.056, 2.758, 0.978, 2.360, 0.150, 1.974, 0.074 ] score = 0 for index in range(0, 26): shiftIndex = (index + shift) % 26 score += abs(frequencyAnalysis[index] - englishFrequencies[shiftIndex]) return score / 26 def shiftCalculator(frequencyAnalysis): # Calculates the most likely shift value for a substring by comparing weighted scores of different shift values bestGuess = '' bestGuessVal = float('inf') for shift in range(1, 27): score = shiftScoreCalculator(frequencyAnalysis, shift) if score &lt; bestGuessVal: bestGuessVal = score bestGuess = 26 - shift return bestGuess def main(): parser = initialiseParser() args = parser.parse_args() if args.bruteforce: bruteforce = True else: bruteforce = False shift = args.shift if args.decrypt: shift = -shift if args.preserve_spacing: regex = '[^A-Z\s]' else: regex = '[^A-Z]' string = re.compile(regex).sub('', input().upper()) if args.spacing: string = ' '.join([string[i:i + args.spacing] for i in range(0, len(string), args.spacing)]) if args.guess: shift = shiftCalculator(frequencyAnalysis(string)) print("Best shift value guess: %d (%c)\nAttempting decryption...\n%s" % (shift, chr(shift + ord('A') - 1), caesar(string, -shift))) return if bruteforce: for shift in range(1, 26): print("%d:\t%s" %(shift, caesar(string, -shift))) else: print(caesar(string, shift)) if __name__ == "__main__": main() </code></pre> <p><strong>rainbow-passage.txt</strong></p> <blockquote> <p>When the sunlight strikes raindrops in the air, they act as a prism and form a rainbow. The rainbow is a division of white light into many beautiful colors. These take the shape of a long round arch, with its path high above, and its two ends apparently beyond the horizon. There is , according to legend, a boiling pot of gold at one end. People look, but no one ever finds it. When a man looks for something beyond his reach, his friends say he is looking for the pot of gold at the end of the rainbow. Throughout the centuries people have explained the rainbow in various ways. Some have accepted it as a miracle without physical explanation. To the Hebrews it was a token that there would be no more universal floods. The Greeks used to imagine that it was a sign from the gods to foretell war or heavy rain. The Norsemen considered the rainbow as a bridge over which the gods passed from earth to their home in the sky. Others have tried to explain the phenomenon physically. Aristotle thought that the rainbow was caused by reflection of the sun’s rays by the rain. Since then physicists have found that it is not reflection, but refraction by the raindrops which causes the rainbows. Many complicated ideas about the rainbow have been formed. The difference in the rainbow depends considerably upon the size of the drops, and the width of the colored band increases as the size of the drops increases. The actual primary rainbow observed is said to be the effect of super-imposition of a number of bows. If the red of the second bow falls upon the green of the first, the result is to give a bow with an abnormally wide yellow band, since red and green light when mixed form yellow. This is a very common type of bow, one showing mainly red and yellow, with little or no green or blue</p> </blockquote> <p><strong>Example Vigenere Encryption</strong></p> <pre><code>./vigenere.py -e -k RAINBOW &lt; rainbow-passage.txt </code></pre> <p><strong>Output</strong></p> <blockquote> <p>NHMAUVAJUVYJUDKSBEJYAJRIVORNFPAVOHDVAQEUVAPAKGBGWGRQFNOJUFWENONRIVOPKPYEZNJBXFWQFBREMIAVPBKWWPVUSHZGPGJBPFMIAZPARUBVGIHTOTBSGPYEARUOGVTPRTVWGEWSBZKEGZBVBZRRKUXWPYIBFQOPYHQTIOXFVMNOREKSBJPSJUSICQONVNBYZPAPOVQUVAYOZVACJKHMEFWORCKBSREEGBBMSCVNLNCCECIVTQCPFFOBMRWKOVRFBZGEWCMSHFOSOVHJFOVRFJAIFQAEGEKWPROOIRNTBPYOWOZFPAAKHQAHPAPOVQIWOIEIPIVEJFZVFBZJSILISEJLWBLWJXFWEUVAGOBBGUKCDIGUVAVNLBGHDVRIVOPKNTPEPICYOCGUVATEVGVFEVSXRPDHVHIIFSTGLIVOSZKHMEBWJSOEVOJWIIWHTKWPSABNSDRVMNDQAGTMQJHWJAUVSOYCEEVUVKLTXUZGETATRYDHRNIGJCJKOBUFVASRMJTWPNAANUCGVNBUBHPYEZRXCQCDJROCIFRMHOWRVRANMTHFOLFUVAXRMRLGQJELGPWIRGQAFHDRTQGXOORSQTOTNFMBUFUKUSBBGCNVTMYMKWIOZUFORPRIVOHDVNWETSIVNKBOGEUEZREHDVRIVOPKNAANCFEUGMBWSNNHQPIHDVGWQTDWJSMQGFKDEIEUVPFTPRJFDFMMVOHDVSSLPHDVRAUBJAKRQREHKVXXYBWJKHMCISJFMMAPBLYYAVDOHCYIEJGPFTTRUVKLGPGUVWKTPRSOEEBWJXOOTACFFRXPRMSMSYKIWAPTPYEAHOGNRYAOZHDVRIVOGEECMGISJGHGFJQEJTAUBJAWOCAEHDRTQGJGJFTZRGZATTQBOPQKRMSSOYKIWACMPYEZNJBZIOXFXVETHKNVGAJTPRSOEEBWJTAWEYKBNDHZCIGFREUEIFBPKLTBUFFWZNJBXVWMEJRFBBFRUREHDVDQSGSNVNKRJBPYEZNJBXFWLRQSJUSKBOGEUEZNCZULPWAUVAJIHRPTPYELEPDORNLGISSZDBUPTPYEKBMCNVDJNOREECZRBGAJAAGISOZZMBGHDVDZBQGEECZRBGAJTPRBQPLATCSWIRRGEBWJSOEBCGAIVMQJGORILGPPAKHMRGTATTWSTILVRQZQCOZTQBOCBRNCZCSNFFJBXGEWTPRSSZFFBUFGATOVQCCSWATYTILFNBUFUNVEVBGHDVFQETHPYEZRTIHKIAGPUEMEIOPKSZTPNOOXEOZZBZHPWQQFMACLWJCOJUSQADSNVDIAEUNVEVYJUDKWPROAEOELSPFIPETYPKPYIAVTORVRGPPAIFNBLQSKWBWJPBAJHWJJBCDAQAMMNVDIAEMACLWJXWPYLQGUZAFRVBHFAVNWECZQV</p> </blockquote> <p><strong>Example Vigenere Cracking</strong></p> <pre><code>./vigenere -g &lt; ciphertext.txt </code></pre> <p><strong>Output</strong></p> <blockquote> <p>Best key guess: RAINBOW Attepting decryption... WHENTHESUNLIGHTSTRIKESRAINDROPSINTHEAIRTHEYACTASAPRISMANDFORMARAINBOWTHERAINBOWISADIVISIONOFWHITELIGHTINTOMANYBEAUTIFULCOLORSTHESETAKETHESHAPEOFALONGROUNDARCHWITHITSPATHHIGHABOVEANDITSTWOENDSAPPARENTLYBEYONDTHEHORIZONTHEREISACCORDINGTOLEGENDABOILINGPOTOFGOLDATONEENDPEOPLELOOKBUTNOONEEVERFINDSITWHENAMANLOOKSFORSOMETHINGBEYONDHISREACHHISFRIENDSSAYHEISLOOKINGFORTHEPOTOFGOLDATTHEENDOFTHERAINBOWTHROUGHOUTTHECENTURIESPEOPLEHAVEEXPLAINEDTHERAINBOWINVARIOUSWAYSSOMEHAVEACCEPTEDITASAMIRACLEWITHOUTPHYSICALEXPLANATIONTOTHEHEBREWSITWASATOKENTHATTHEREWOULDBENOMOREUNIVERSALFLOODSTHEGREEKSUSEDTOIMAGINETHATITWASASIGNFROMTHEGODSTOFORETELLWARORHEAVYRAINTHENORSEMENCONSIDEREDTHERAINBOWASABRIDGEOVERWHICHTHEGODSPASSEDFROMEARTHTOTHEIRHOMEINTHESKYOTHERSHAVETRIEDTOEXPLAINTHEPHENOMENONPHYSICALLYARISTOTLETHOUGHTTHATTHERAINBOWWASCAUSEDBYREFLECTIONOFTHESUNSRAYSBYTHERAINSINCETHENPHYSICISTSHAVEFOUNDTHATITISNOTREFLECTIONBUTREFRACTIONBYTHERAINDROPSWHICHCAUSESTHERAINBOWSMANYCOMPLICATEDIDEASABOUTTHERAINBOWHAVEBEENFORMEDTHEDIFFERENCEINTHERAINBOWDEPENDSCONSIDERABLYUPONTHESIZEOFTHEDROPSANDTHEWIDTHOFTHECOLOREDBANDINCREASESASTHESIZEOFTHEDROPSINCREASESTHEACTUALPRIMARYRAINBOWOBSERVEDISSAIDTOBETHEEFFECTOFSUPERIMPOSITIONOFANUMBEROFBOWSIFTHEREDOFTHESECONDBOWFALLSUPONTHEGREENOFTHEFIRSTTHERESULTISTOGIVEABOWWITHANABNORMALLYWIDEYELLOWBANDSINCEREDANDGREENLIGHTWHENMIXEDFORMYELLOWTHISISAVERYCOMMONTYPEOFBOWONESHOWINGMAINLYREDANDYELLOWWITHLITTLEORNOGREENORBLUE</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T01:43:19.307", "Id": "415855", "Score": "1", "body": "Off topic: have you heard of CryptoPals? If not, I encourage you to Google it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T06:39:04.300", "Id": "415867", "Score": "0", "body": "@enedil No I haven't, I'll check it out, thanks" } ]
[ { "body": "<p>The first thing which strikes me is that the Caesar code is far too long. It's just a special case of Vigenère with a key that's one character long: I would expect that in <code>caesar.py</code> you can <code>from vigenere import *</code> and then just write a <code>main</code> method.</p>\n\n<hr>\n\n<p>The second thing which strikes me is that it's good work for a newbie. There's a good docstring at the top; there's a <code>__name__ == \"__main__\"</code> check.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def buildSubStrings(string, seperation): # Build all substrings required to analyse the polyalphabetic cipher\n return [string[i::seperation] for i in range(seperation)]\n</code></pre>\n</blockquote>\n\n<p>Minor point: it's <em>separation</em> with two 'a's.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def frequencyAnalysis(string): # Normalised frequency analysis\n freq = [0] * 26\n</code></pre>\n</blockquote>\n\n<p>Magic number. For the time being I'd pull it out as a top-level constant. When you get round to handling other languages you'll need to consider passing it around, possibly implicitly (as the length of an <code>alphabet</code> object).</p>\n\n<blockquote>\n<pre><code> for c in string:\n freq[ord(c) - ord('A')] += 1\n</code></pre>\n</blockquote>\n\n<p>There's a special class for that: <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code></a>.</p>\n\n<blockquote>\n<pre><code> total = sum(freq)\n\n for i in range(0, len(freq)):\n freq[i] /= (float(total) / 100)\n\n return freq\n</code></pre>\n</blockquote>\n\n<p>You shouldn't need the explicit coercion to <code>float</code>: float division will do that for you. Python 3 has a different operator (<code>//</code>) for integer division. Also, it's probably more Pythonic to use a comprehension:</p>\n\n<pre><code> scale = sum(freq) / 100\n return [f / scale for f in freq]\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>def initialiseParser():\n parser = argparse.ArgumentParser(description = \"Encrypt or decrpyt a string using the Caesar Cipher\")\n</code></pre>\n</blockquote>\n\n<p>Typo in <em>decrypt</em>. Also, this is quoted from the Vigenère code, so looks like a copy-pasta error.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def scoreCalculator(frequencyAnalysis, shift): # Calculates a weighted score for a given shift value\n englishFrequencies = [ 8.167, 1.492, 2.782,\n 4.253, 12.702, 2.228,\n 2.015, 6.094, 6.966,\n 0.153, 0.772, 4.025,\n 2.406, 6.749, 7.507,\n 1.929, 0.095, 5.987,\n 6.327, 9.056, 2.758,\n 0.978, 2.360, 0.150,\n 1.974, 0.074 ]\n</code></pre>\n</blockquote>\n\n<p>I'd like to see a comment giving the source for these frequencies.</p>\n\n<blockquote>\n<pre><code> score = 0\n\n for index in range(0, 26):\n shiftIndex = (index + shift) % 26\n score += abs(frequencyAnalysis[index] - englishFrequencies[shiftIndex])\n\n return score / 26\n</code></pre>\n</blockquote>\n\n<p>See previous notes on the magic number and on using comprehensions.</p>\n\n<p>Is the normalisation necessary? Surely you'll just be comparing scores against each other?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def shiftCalculator(frequencyAnalysis): # Calculates the most likely shift value for a substring by comparing weighted scores of different shift values\n bestGuess = ''\n bestGuessScore = float('inf')\n\n for shift in range(1, 27):\n score = scoreCalculator(frequencyAnalysis, shift)\n\n if score &lt; bestGuessScore:\n bestGuessScore = score\n bestGuess = chr(ord('Z') - shift + 1)\n\n return bestGuess\n</code></pre>\n</blockquote>\n\n<p>There's a builtin <code>max</code> and tuples have implicit comparison, so this can be something like</p>\n\n<pre><code> bestShift = max((scoreCalculator(frequencyAnalysis, shift), shift) for shift in range(1, 27))\n return chr(ord('Z') - bestShift[1] + 1)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> elif args.guess:\n maxGuess = 30 if len(strippedText) &gt; 30 else len(strippedText)\n</code></pre>\n</blockquote>\n\n<p>What's the point of guessing <code>len(strippedText)</code>? I haven't seen anything which takes into account bigram frequencies, so I would think that the most plausible guess would be the key which decrypts the plaintext to <code>EEE...EEE</code>.</p>\n\n<hr>\n\n<p>I've refactored the next section a bit to understand what it's doing:</p>\n\n<pre><code> keyList = [\n ''.join(shiftCalculator(frequencyAnalysis(subString))\n for subString in buildSubStrings(strippedText, guess))\n for guess in range(2, maxGuess)\n ]\n</code></pre>\n\n<p>Given the granularity of a lot of the functions, I'm slightly surprised you didn't factor out a <code>guessKey(text, guess)</code>.</p>\n\n<blockquote>\n<pre><code> bestGuess = ''\n bestGuessScore = float('inf')\n\n for key in keyList:\n score = scoreCalculator(frequencyAnalysis(str.upper(vigenere(strippedText, key, False))), 0)\n</code></pre>\n</blockquote>\n\n<p>Is the <code>str.upper</code> necessary? If so, why not apply it to <code>strippedText</code> earlier and consider in which other functions it becomes unnecessary?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if args.preserveSpacing:\n for x in range(0, len(rawText)):\n if rawText[x] == ' ':\n</code></pre>\n</blockquote>\n\n<p>The regex used <code>\\s</code>, which catches a lot more than just <code>' '</code>, so that looks like a bug to me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T10:39:23.993", "Id": "415993", "Score": "0", "body": "Thanks a lot, this was really helpful! There was one part that I wasn't sure about, namely your comment on how I calculate maxGuess. I did it that way to ensure that the program didn't try and guess keys that were longer than the input text, and to limit how long a key could be for performance reasons. Is there a better way of achieving this? Am I missing something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T18:19:32.277", "Id": "416041", "Score": "0", "body": "I think you've understood the opposite of what I intended to say. Certainly there's no point considering key lengths longer than the ciphertext, but my point was that there's not much point considering key lengths longer than, perhaps, a third of the length of the ciphertext." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:24:16.517", "Id": "215018", "ParentId": "214945", "Score": "2" } } ]
{ "AcceptedAnswerId": "215018", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T19:24:44.883", "Id": "214945", "Score": "5", "Tags": [ "python", "python-3.x", "caesar-cipher", "vigenere-cipher" ], "Title": "Cracking Vigenere and Caesar Ciphered Text in Python" }
214945
<p>I've written a function to prettify a json object, as if it were using JSON.stringify.</p> <p>I'm only focused on strings and other objects, nothing else.</p> <p>Is there a better way of doing this? perhaps using a data structure?</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 exampleJson = {"name":"Jon","facts":{"car":"Ford","address":{"city":"New York"},"watch":"Casio","other": {}}}; function prettyPrint(data) { let tabbify = n =&gt; Array(n).fill(' ').join(''); let traverse = (data, tab = 1) =&gt; { let output = "", open = `{\n`, close = `\n${tabbify(tab - 1)}}`; output += open; Object.entries(data).forEach(([key, val], i, {length}) =&gt; { if (typeof val === 'string') { output += `${tabbify(tab)} "${key}": "${val}"`; } else if (typeof val === 'object') { if (Object.keys(val).length &gt; 0) { output += `,\n${tabbify(tab)} "${key}": ${traverse(val, tab+2)}${i === length - 1 ? '' : ',\n'}`; } else { output += `,\n${tabbify(tab)} "${key}": {}`; } } }) output += close; return output; } return traverse(data); }</code></pre> </div> </div> </p> <p>Output</p> <pre><code>{ "name": "Jon", "facts": { "car": "Ford", "address": { "city": "New York" }, "watch": "Casio", "other": {} } } </code></pre>
[]
[ { "body": "<p>I am prejudiced against variables named <code>data</code>.</p>\n\n<p>You need to escape literal <code>\"</code>, <code>\\</code>, and <code>\\n</code> characters in quoted strings. It's good form to do tabs too.</p>\n\n<p>Using a dispatch table for types (instead of <code>if/else</code>) makes it easy to handle all the types.</p>\n\n<p>Instead of passing <code>tab</code> up and down the call stack, wrap the calls in a function that indents a block of text. Nested <code>traverse</code> will be nested in <code>indent</code> too and get indented the right number of times. </p>\n\n<p>Instead of checking whether you're at the end of a delimited list (to decide whether to add a delimiter), use <code>arr.join(delimiter)</code>. It puts delimiters on inner boundaries only.</p>\n\n<p><code>Array(n).fill(' ').join('');</code> is the same as <code>' '.repeat(n)</code>.</p>\n\n<p>It would be nice to omit the quotes on property names that don't need them. Doing this perfectly <a href=\"https://stackoverflow.com/questions/1661197/what-characters-are-valid-for-javascript-variable-names/9337047#9337047\">happens to be really laborious</a>&mdash;the regex is 11 kilobytes long!! It's manageable if we limit the exceptions to 7-bit ASCII, which is probably a good idea anyway.</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 prettyPrint(obj) {\n const stringify = {\n \"undefined\": x =&gt; \"undefined\",\n \"boolean\": x =&gt; x.toString(),\n \"number\": x =&gt; x,\n \"string\": x =&gt; enquote(x),\n \"object\": x =&gt; traverse(x),\n \"function\": x =&gt; x.toString(),\n \"symbol\": x =&gt; x.toString()\n },\n indent = s =&gt; s.replace(/^/mg, \" \"),\n keywords = `do if in for let new try var case else enum eval null this true \n void with await break catch class const false super throw while \n yield delete export import public return static switch typeof \n default extends finally package private continue debugger \n function arguments interface protected implements instanceof`\n .split(/\\s+/)\n .reduce( (all, kw) =&gt; (all[kw]=true) &amp;&amp; all, {} ),\n keyify = s =&gt; ( !(s in keywords) &amp;&amp; /^[$A-Z_a-z][$\\w]*$/.test(s) ? s : enquote(s) ) + \": \",\n enquote = s =&gt; s.replace(/([\\\\\"])/g, '\\\\$1').replace(/\\n/g,\"\\\\n\").replace(/\\t/g,\"\\\\t\").replace(/^|$/g,'\"'),\n traverse = obj =&gt; [ \n `{`,\n indent( Object.keys(obj) \n .map( k =&gt; indent( keyify(k) + stringify[ typeof obj[k] ](obj[k]) ) )\n .join(\",\\n\")\n ),\n `}`\n ]\n .filter( s =&gt; /\\S/.test(s) )\n .join(\"\\n\")\n .replace(/^{\\s*\\}$/,\"{}\");\n return traverse(obj);\n}\n\nconsole.log(prettyPrint( \n {\n \"name\":\"Jon\",\n \"facts\":{\n \"car\":\"Ford\",\n \"address\":{\n \"city\":\"New York\"\n },\n \"watch\":\"Casio\",\n \"other\": { \n \"true\":false, \n blargh:undefined, \n \"111number\":1e5, \n method:function(x){x++} \n }\n }\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-03-08T00:51:33.450", "Id": "214978", "ParentId": "214947", "Score": "3" } }, { "body": "<h2>A quick warning.</h2>\n<p>Javascript objects are referenced and that means objects can contain cyclic references. You function does not check for cyclic references. Cyclic references are very common in JavascripT so you should protect against the potential error.</p>\n<h2>Some solutions.</h2>\n<ul>\n<li>You can use a <code>Set</code> to track which objects have already been processed and step over repeats.</li>\n<li>Add a depth argument that limits the recursion depth.</li>\n</ul>\n<p>You can just let it throw a call stack overflow when the recursion gets too deep. However a warning, some browsers support tail call optimization and can recurse infinitely. Your function is not currently a tail call, but be aware as it could force the user to crash / close the page.</p>\n<p>Example of cyclic object</p>\n<pre><code> const A = {A: &quot;Prop B be will reference Self&quot; };\n A.B = A;\n\n \n\n\n \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:52:43.527", "Id": "214994", "ParentId": "214947", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T19:48:34.927", "Id": "214947", "Score": "1", "Tags": [ "javascript", "json", "reinventing-the-wheel", "formatting" ], "Title": "Pretty print an object - JavaScript" }
214947
<p>I made myself a smallish template for practice writing some characters, see below. The objective for me was to have an easy way to enter a couple of characters, set the parameters (how many pre-drawn characters, how many columns, etc.) and then get a print-ready PDF.</p> <p><a href="https://i.stack.imgur.com/fC1H6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fC1H6.png" alt="example PDF output"></a></p> <p>It's written against TikZ and LuaLaTeX (I'm not sure it will run with other configurations), but I'm only using TikZ features, no Lua (yet).</p> <p>I'm looking for feedback especially regarding maintainability, feature configuration (at the moment I'm simply editing the file, but it's not really convenient; I'm thinking more of how to do this easily from the command line?) and ease of use (the dimensions are manually specified - how should I structure this to have it usable for a multi-page setup without too much hassle?) - I've also been thinking of how to drive this from a web service, passing in options file paper size etc. since not everyone might use A4.</p> <p>What's not added yet is settings with respect to. the drawing style (I'd possibly like to toggle some of the background grid lines) — are there established conventions how to do the background grid, not manually, basically? Note that I'm overdrawing significantly in order to keep the logic simple.</p> <p>Small edit: I'd be especially grateful for advice explaining how to get rid of the horrible equations — defining new names for simply subtracting a number is, uh, awful.</p> <pre class="lang-latex prettyprint-override"><code>\documentclass[a4paper]{article} \usepackage[cm]{fullpage} \usepackage{fontspec} \usepackage[utf8]{luainputenc} \usepackage{fontenc} \usepackage{lmodern} \usepackage[german]{babel} \usepackage{luatexja-fontspec} % https://ctan.org/tex-archive/fonts/fandol?lang=en \setmainjfont{FandolKai} \usepackage{tikz} \usepackage{xcolor} \usepackage{xstring} \begin{document} \def\c{gray!50} \def\chars{我,你,您,也,很,他,们,好,吗,再,见,是,累,俄,渴,不,谢,用,爱,咖,啡,这,欧,雅,福} \def\w{17} \def\wFull{1} \def\wHalf{2} \StrCount{\chars}{,}[\h] \pgfmathsetmacro{\h}{\h+1} \pgfmathsetmacro{\hMinusOne}{\h-1} \pgfmathsetmacro{\wMinusOne}{\w-1} \pgfmathsetmacro{\wFullMinusOne}{\wFull+1} \pgfmathsetmacro{\wAll}{\wFull+\wHalf} \pgfmathsetmacro{\wPlusH}{\w+\h} \begin{center} \begin{tikzpicture} \draw[step=1cm,dashed,gray,thin] (0,0) grid (\w,\h); \foreach \x in {0,...,\wMinusOne} { \pgfmathsetmacro{\a}{\x+0.5} \draw[dashed,\c,very thin] (\a,0) -- (\a,\h); } \foreach \y in {0,...,\hMinusOne} { \pgfmathsetmacro{\a}{\y+0.5} \draw[dashed,\c,very thin] (0,\a) -- (\w,\a); } \begin{scope} \clip(0,0) rectangle(\w,\h); \foreach \x in {1,...,\wPlusH} { \pgfmathsetmacro{\xh}{\x-\h} \draw[dashed,\c,very thin] (\xh,\h) -- (\x,0); } \foreach \x in {0,...,\wPlusH} { \pgfmathsetmacro{\xMinusH}{\x-\h} \pgfmathsetmacro{\xh}{\x+\h} \draw[dashed,\c,very thin] (\xMinusH,0) -- (\x,\h); } \end{scope} \newcounter{counter}\setcounter{counter}{0} \foreach \char in \chars { \pgfmathsetmacro{\y}{\h-1-\thecounter+0.55} \foreach \x in {0,...,\wFullMinusOne} { \pgfmathsetmacro{\xo}{\x+0.5} \node at (\xo,\y) {\huge\char}; } \foreach \x in {\wFull,...,\wAll} { \pgfmathsetmacro{\xo}{\x+0.5} \node[gray] at (\xo,\y) {\huge\char}; } \stepcounter{counter} } \end{tikzpicture} \end{center} \end{document} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:17:48.820", "Id": "415842", "Score": "1", "body": "First thing without testing the code: remove the call to `luainputenc`." } ]
[ { "body": "<p>You can just start your loops from 1 to <code>\\w</code>, instead of 0 and ending to <code>\\wMinusOne</code>: just subtract 0.5, instead of adding it.</p>\n\n<p>Using <code>\\c</code> for a color is not the best idea: properly define a color, here I used the name <code>grid</code>.</p>\n\n<p>Also the counter is not necessary, as there's a <code>\\foreach</code> feature for it.</p>\n\n<p>I also put all <code>\\def</code> inside <code>tikzpicture</code> and changed <code>\\char</code> into <code>\\character</code>, as <code>\\char</code> is a TeX primitive connected to character printing and there's high risk of conflict.</p>\n\n<p>Don't use <code>luainputenc</code>: it is aimed at compatibility of older documents. Also loading <code>fontenc</code> and <code>lmodern</code> is useless.</p>\n\n<pre class=\"lang-latex prettyprint-override\"><code>\\documentclass[a4paper]{article}\n\\usepackage[cm]{fullpage}\n\\usepackage{fontspec}\n\\usepackage[german]{babel}\n\\usepackage{luatexja-fontspec}\n% https://ctan.org/tex-archive/fonts/fandol?lang=en\n\\setmainjfont{FandolKai}\n\\usepackage{tikz}\n\\usepackage{xcolor}\n\\usepackage{xstring}\n\n\\begin{document}\n\n\\begin{center}\n\\begin{tikzpicture}\n\n\\colorlet{grid}{gray!50}\n\\def\\chars{我,你,您,也,很,他,们,好,吗,再,见,是,累,俄,渴,不,谢,用,爱,咖,啡,这,欧,雅,福}\n\\def\\w{17}\n\\def\\wFull{1}\n\\def\\wHalf{2}\n\n\\StrCount{\\chars}{,}[\\h]\n\\pgfmathsetmacro{\\h}{\\h+1}\n\n\\pgfmathsetmacro{\\wAll}{\\wFull+\\wHalf}\n\\pgfmathsetmacro{\\wPlusH}{\\w+\\h}\n\n\n\\draw[step=1cm,dashed,gray,thin] (0,0) grid (\\w,\\h);\n\n\\foreach \\x in {1,...,\\w}\n {\n \\pgfmathsetmacro{\\a}{\\x-0.5}\n \\draw[dashed,grid,very thin] (\\a,0) -- (\\a,\\h);\n }\n\\foreach \\y in {0,...,\\h}\n {\n \\pgfmathsetmacro{\\a}{\\y-0.5}\n \\draw[dashed,grid,very thin] (0,\\a) -- (\\w,\\a);\n }\n\n\\begin{scope}\n\n\\clip(0,0) rectangle(\\w,\\h);\n\n\\foreach \\x in {1,...,\\wPlusH}\n {\n \\pgfmathsetmacro{\\xh}{\\x-\\h}\n \\draw[dashed,grid,very thin] (\\xh,\\h) -- (\\x,0);\n }\n\n\\foreach \\x in {0,...,\\wPlusH}\n {\n \\pgfmathsetmacro{\\xMinusH}{\\x-\\h}\n \\pgfmathsetmacro{\\xh}{\\x+\\h}\n \\draw[dashed,grid,very thin] (\\xMinusH,0) -- (\\x,\\h);\n }\n\n\\end{scope}\n\n\\foreach \\character [count=\\charcount from 0] in \\chars \n {\n \\pgfmathsetmacro{\\y}{\\h-1-\\charcount+0.55}\n \\foreach \\x in {1,...,\\wFull}\n {\n \\pgfmathsetmacro{\\xo}{\\x-0.5}\n \\node at (\\xo,\\y) {\\huge\\character};\n }\n \\foreach \\x in {\\wFull,...,\\wAll}\n {\n \\pgfmathsetmacro{\\xo}{\\x+0.5}\n \\node[gray] at (\\xo,\\y) {\\huge\\character};\n }\n }\n\n\\end{tikzpicture}\n\\end{center}\n\n\\end{document}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/lmGVX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lmGVX.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T16:03:52.507", "Id": "417676", "Score": "0", "body": "Thanks, I'd hoped to get this smaller, I suppose another option would be to go via Lua then? Any suggestion about the background or how to apply this to multiple pages, or is this reasonable to do as it is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T17:01:12.557", "Id": "417682", "Score": "0", "body": "@ferada I can't see how to shorten it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T23:16:43.500", "Id": "215061", "ParentId": "214949", "Score": "4" } } ]
{ "AcceptedAnswerId": "215061", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T19:57:35.947", "Id": "214949", "Score": "4", "Tags": [ "tex" ], "Title": "Hanzi grid template" }
214949
<p>I have some data which I want to filter. I have a collection of things to include and a second one of things to exclude.</p> <p>Currently I'm looping my data and filter once for the including and a second time for the excluding.</p> <p>Example coding:</p> <pre><code>#[derive(Debug)] pub struct Dataset { pub data: Vec&lt;String&gt; } fn main() { //setup test data let mut ds1_data : Vec&lt;String&gt; = Vec::with_capacity(2); ds1_data.push("a".to_string()); ds1_data.push("b".to_string()); let ds1 = Dataset{data: ds1_data}; let mut ds2_data : Vec&lt;String&gt; = Vec::with_capacity(2); ds2_data.push("a".to_string()); ds2_data.push("c".to_string()); let ds2 = Dataset{data: ds2_data}; let mut datasets : Vec&lt;Dataset&gt; = Vec::with_capacity(2); datasets.push(ds1); datasets.push(ds2); let mut include : Vec&lt;String&gt; = Vec::with_capacity(2); include.push("a".to_string()); let mut exclude : Vec&lt;String&gt; = Vec::with_capacity(1); exclude.push("b".to_string()); //filter datasets for ds in datasets { if ds.data.iter().find(|d| include.contains(d)).is_none() { //skip not included continue; } if ds.data.iter().find(|d| exclude.contains(d)).is_some() { //skip excluded continue; } println!("{:?}", ds); } } </code></pre> <p>Also available in the rust playground: <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=29c13f2b7ab3a50fbcd12b88b59f4b74" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=29c13f2b7ab3a50fbcd12b88b59f4b74</a></p> <p>Is there way to combine the filter statements so I don't need to iterate ds.data two times?</p> <hr> <p>To clarify: The above coding is working as expected. I get datasets containing at least one element of include but no element of exclude</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T21:49:07.703", "Id": "415705", "Score": "0", "body": "Please clarify what you're trying to filter. Do you want to keep only datasets that have all elements of `include` and no elements of `exclude`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T06:51:31.343", "Id": "415731", "Score": "0", "body": "I want to get datasets containing at least one element of include, but no element of exclude." } ]
[ { "body": "<h1>The <code>vec!</code> macro</h1>\n\n<p>Before we have a look at including and excluding, we should note that</p>\n\n<pre><code>let mut myvec: Vec&lt;T&gt; = Vec::with_capacity(2);\nmyvec.push(a);\nmyvec.push(b);\nmyvec.push(c);\n</code></pre>\n\n<p>can be written with the <a href=\"https://doc.rust-lang.org/std/macro.vec.html\" rel=\"nofollow noreferrer\"><code>vec!</code> macro</a> as</p>\n\n<pre><code>let myvec: Vec&lt;T&gt; = vec![a,b,c];\n</code></pre>\n\n<p>This has the nice side-effect that <code>myvec</code> doesn't need to be <code>mut</code> anymore. If we apply this too all your code, we end up with </p>\n\n<pre><code>#[derive(Debug)]\npub struct Dataset {\n pub data: Vec&lt;String&gt;,\n}\nfn main() {\n //setup test data\n let ds1_data = vec![\"a\".to_string(), \"b\".to_string()];\n let ds1 = Dataset { data: ds1_data };\n\n let ds2_data = vec![\"a\".to_string(), \"c\".to_string()];\n let ds2 = Dataset { data: ds2_data };\n\n let datasets = vec![ds1, ds2];\n\n let include = vec![\"a\".to_string()];\n let exclude = vec![\"b\".to_string()];\n\n //filter datasets\n for ds in datasets {\n if ds.data.iter().find(|d| include.contains(d)).is_none() {\n continue;\n }\n if ds.data.iter().find(|d| exclude.contains(d)).is_some() {\n continue;\n }\n\n println!(\"{:?}\", ds);\n }\n}\n</code></pre>\n\n<p>That's a lot less noise, perfect to concentrate on the original problem.</p>\n\n<h1>Including and excluding</h1>\n\n<p>First of all, instead of <code>find(…).is_some()</code>, we can use <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.any\" rel=\"nofollow noreferrer\"><code>any</code></a>, and instead of <code>find(…).is_none()</code> too. We could use that to simplify the expressions, but we would still traverse the set twice.</p>\n\n<pre><code>for ds in datasets {\n if !ds.data.iter().any(|d| include.contains(d)) {\n //skip not included\n continue;\n } \n if ds.data.iter().any(|d| exclude.contains(d)) {\n //skip excluded\n continue;\n }\n\n println!(\"{:?}\", ds);\n}\n</code></pre>\n\n<p>Instead, let's think about the elements we have to look at. The answer is all, as <code>exclude</code> might match the last element in our dataset, even if <code>include</code> matched the first.</p>\n\n<p>As we have to look at all elements either way, we might as well traverse them by hand:</p>\n\n<pre><code> for ds in datasets {\n let mut included = false;\n let mut excluded = false;\n for d in &amp;ds.data {\n if included == false &amp;&amp; include.contains(d) {\n included = true;\n }\n if exclude.contains(d) {\n excluded = true;\n break;\n }\n }\n if included == false || excluded == true {\n continue;\n }\n\n println!(\"{:?}\", ds);\n }\n</code></pre>\n\n<p>Now that we have this as a blueprint, we can check the <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html\" rel=\"nofollow noreferrer\">iterators</a> for a fitting method. We need to</p>\n\n<ul>\n<li>check that at least one <code>include</code> matches</li>\n<li>check that no <code>exclude</code> matches</li>\n<li>stop as soon as soon as <em>any</em> <code>exclude</code> matches.</li>\n</ul>\n\n<p>Unfortunately it's not possible to quick exit from a closure, so the last requirement cannot be done with <code>fold</code> or similar. However, we can use <code>inspect</code> and <code>all</code> to get something like our previous loop:</p>\n\n<pre><code> for ds in datasets {\n let mut included = false;\n\n if !ds\n .data\n .iter()\n .inspect(|d| {\n if included == false || include.contains(d) {\n included = true\n }\n })\n .all(|d| !exclude.contains(d))\n || !included\n {\n continue;\n }\n println!(\"{:?}\", ds);\n }\n</code></pre>\n\n<p>But that's a lot less readable than our previous loop, which did the same. We could increase readablity if we introduced a function, but that's left as an exercise. In the end, we would need a <code>fold</code>-like function that supports an early exit, but such a function does not exist. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:25:02.853", "Id": "215019", "ParentId": "214952", "Score": "2" } } ]
{ "AcceptedAnswerId": "215019", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T20:09:39.543", "Id": "214952", "Score": "1", "Tags": [ "rust" ], "Title": "Combine Filter to include and Exclude" }
214952
<p>I have the following class for 2D points:</p> <pre><code>class Point { private: double _x, _y; public: Point(double x, double y) : _x(x), _y(y); double x() const { return _x; } double y() const { return _y; } }; </code></pre> <p>I wanted to add a few comparison functions that compared objects of this class in different ways.</p> <p>One of them is just a simple function:</p> <pre class="lang-cpp prettyprint-override"><code>/// Returns whether A has a smaller y-coordinate than B /// (and smaller x-coordinate in case of equality). bool yComp(const Point &amp;A, const Point &amp;B) { if (A.y() != B.y()) return A.y() &lt; B.y(); return A.x() &lt; B.x(); } </code></pre> <p>The other is a <code>struct</code> with <code>operator()</code> defined on it:</p> <pre class="lang-cpp prettyprint-override"><code>struct angleComp { Point origin; angleComp(const Point &amp;P); bool operator()(const Point &amp;A, const Point &amp;B); }; // Constructs a new angle comparison with P as origin angleComp::angleComp(const Point &amp;P) : origin(P) {} // Compares according to the angles that the lines joining each point // to a given origin form with the x-axis. bool angleComp::operator()(const Point &amp;A, const Point &amp;B) { GeometricVector u = A - origin, v = B - origin; return u.x()*u.x()*u.sqrNorm() &lt; v.x()*v.x()*v.sqrNorm(); } </code></pre> <p>Do I put the comparisons inside the class definition? The first function could be made a static method, but the problem is I can't put <code>angleComp</code> inside the class (as a static member) since one of its fields is of type <code>Point</code> itself, which would be an incomplete type (inside the class declaration). And I would prefer these comparison functions to be grouped together (instead of one being a static member, and the other being a top-level thing).</p> <p>So, an alternative would be to put both outside the class, but to retain some grouping, putting all of them in a <code>namespace</code>:</p> <pre><code>namespace PointComp { bool yComp(const Point &amp;A, const Point &amp;B); struct angleComp { Point origin; angleComp(const Point &amp;P); bool operator()(const Point &amp;A, const Point &amp;B); }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T21:42:06.070", "Id": "415702", "Score": "1", "body": "The code is about 2D points. On Code Review, we mainly classify questions according to the task accomplished by the code rather than by your primary concern about the code, because feedback on any aspect of the code is fair game for answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T21:48:24.100", "Id": "415704", "Score": "1", "body": "No, Code Review reviews concrete code. Answers will suggest better practices, but asking for best practices in general is both off-topic and redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T22:23:10.337", "Id": "415708", "Score": "4", "body": "Answers will talk about whether how well your code follows best practices and patterns. Questions should not ask about best practices and design patterns, since they are implicit topics for every review. Also, if your question is specifically about a best practice or design pattern (and not a general critique of your code), then it should go on [softwareengineering.se] instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:08:59.707", "Id": "415784", "Score": "2", "body": "It's easy to misread the page like that, I agree. But that's not what it says. 200 is absolutely correct here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:10:16.880", "Id": "415785", "Score": "0", "body": "Does the code provided work and are you sure you want a review on it instead of finding out the answer to your original question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T16:07:35.473", "Id": "415814", "Score": "2", "body": "Feel free to make a suggestion on our [Meta site](https://codereview.meta.stackexchange.com) if you have a suggestion on how to avoid confusion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T08:33:00.330", "Id": "422956", "Score": "0", "body": "@Mast I have tried to edit the question to clean the products of my previous misunderstandings about the site, and salvage it into a real CR question. Is it suitable for reopening now? If not, what should I change? (By the way, I did follow your suggestion of [posting on Meta](https://codereview.meta.stackexchange.com/questions/9114/proposal-to-clarify-on-topic-help-page))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T16:30:06.720", "Id": "423043", "Score": "0", "body": "Do you think the comments by @200 are fully addressed? Because I have my doubts about it. I strongly advice against further touching this question since it got answered and for you to post improved code, if you can fit it within the scope of CR as outlined in the [help/on-topic], as a *new* question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-24T16:34:35.303", "Id": "423046", "Score": "0", "body": "@Mast Yes, I specifically tried to fix the matters addressed in 200's comments, to the best of my ability. **I'm not posting improved code**, I'm just putting in what I had before the question got answered in a format suitable for CR, without skipping over details, and without hypothetical or incomplete code. And without asking for \"best practices\". If you read it in its last revision, without knowledge of its past history, it is an on-topic question for CR, right? Otherwise, what else can I change?" } ]
[ { "body": "<p>The overall design seems a bit complicated to me. Setters and getters are often more of an hindrance than a real asset, and the benefits of having a simple <code>struct</code> should not be under-estimated. In particular, it reminds you that you don't have to encapsulate everything, and that defining functions at the point of use is often the most convenient way to proceed:</p>\n\n<pre><code>struct Point { float x, y; };\n\n// ...\n\n// here I need to compare points by y and then x\nauto best = std::max_element(v.begin(), v.end(), [](auto point_a, auto point_b) {\n return std::tie(point_a.y, point_a.x) &lt; std::tie(point_b.y, point_b.x);\n // -&gt; tie gives you the lexicographic comparison for free\n});\n\n// and there by angle with etc.\nauto widest = std::max_element(v.begin(), v.end(), [origin](auto point_a, auto point_b) {\n // ...\n});\n</code></pre>\n\n<p>In a nutshell, why having a <code>namespace</code> and custom classes where you can simply use a lambda? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:01:05.590", "Id": "215016", "ParentId": "214953", "Score": "3" } } ]
{ "AcceptedAnswerId": "215016", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T20:32:41.030", "Id": "214953", "Score": "1", "Tags": [ "c++", "comparative-review", "coordinate-system" ], "Title": "Comparison functions for 2D points" }
214953
<p>In the last couple of days I've tried to play around with some scraping using XPATHs and Python to consolidate my knowledge (since it's been some time). I did this on a simple website which doesn't provide an API.</p> <p><strong>Scope:</strong></p> <p>Get all the information about every product on <a href="http://www.crlaurence.com/" rel="noreferrer">crlaurence</a> without using <a href="https://scrapy.org" rel="noreferrer">Scrapy</a> (which I know would have a huge impact on the speed but would take too much time to learn at the moment), and save the result in a JSON file.</p> <p><strong>Code:</strong></p> <pre><code>import json import re import requests from time import sleep from lxml import html URL = 'http://www.crlaurence.com' SITEMAP_URL = f'{URL}/apps/contentloader/default.aspx?content=www.crlaurence.com/adv/sitemap/sitemap_us.html' SITEMAP_URLS_XPATH = '//div[@class="sitemapContent"]//a/@href' CATEGORIES_XPATH = '//div[@class="divCell"]/a/@href' PRODUCT_CATALOG_NUMBER_XPATH = '//div[@id="ctl00_ContentPlaceHolder1_lblMoreDetails"]//b/text()' PRODUCT_TITLE_XPATH = '//span[@class="lblProductDesc"]//text()' PRODUCT_SPECIFICATION_XPATH = '//div[@id="ctl00_ContentPlaceHolder1_lblBulletList"]//text()' PRODUCT_DESCRIPTION_XPATH = '//div[@id="ctl00_ContentPlaceHolder1_lblProdDetails"]/h1//text()' PRODUCT_SMALL_IMAGES_XPATH = [ '//input[@id="ctl00_ContentPlaceHolder1_imgbtnPrint"]/@src', '//input[@id="ctl00_ContentPlaceHolder1_imgbtnEmail"]/@src', ] PRODUCT_SMALL_IMAGES_1_XPATH = [ '//img[@id="imgProp65Btn"]/@src', '//div[@id="ctl00_ContentPlaceHolder1_lblNotices"]/a/img/@src' ] PRODUCT_ADDITIONAL_INFO_XPATH = '//div[@id="ctl00_ContentPlaceHolder1_lblMoreDescription"]/text()' PRODUCT_IMPORTANT_NOTES_XPATH = '//div[@id="ctl00_ContentPlaceHolder1_lblNotes"]//text()' PRODUCT_OTHER_PRODUCTS_XPATH = '//table[@class="table_color"]/tr' PRODUCT_DETAILS_XPATH = '//div[@id="ctl00_ContentPlaceHolder1_lblMoreDetails"]/table//tr//text()' PRODUCT_RELATED_ITEMS_XPATH = '//div[@class="divRelatedTxt"]//text()' class Product: def __init__(self, tree, url): self.tree = tree self.url = url def get_image(self): product_id = re.match(r'.*ProductID=(\d+).*', self.url).group(1) if product_id: return f'{URL}/crlapps/showline/largerimage.aspx?productid={product_id}' return 'Could not get image URL.' def get_catalog_number(self): catalog_number = self.tree.xpath(PRODUCT_CATALOG_NUMBER_XPATH) if catalog_number: return catalog_number[0] return 'Could not get product number.' def get_product_name(self): product_name = self.tree.xpath(PRODUCT_TITLE_XPATH) if product_name: return product_name[0] return 'Could not get product name.' def get_product_specification(self): specifications = self.tree.xpath(PRODUCT_SPECIFICATION_XPATH) if specifications: return specifications return 'Could not get product specification.' def get_product_description(self): description = self.tree.xpath(PRODUCT_DESCRIPTION_XPATH) if description: return ' '.join(description) return 'Could not get product description.' def get_small_images(self): images = [] for xpath in PRODUCT_SMALL_IMAGES_XPATH: image = self.tree.xpath(xpath) if image: images.append(image[0]) if images: return images return 'Could not get product images.' def get_small_images_1(self): images = [] for xpath in PRODUCT_SMALL_IMAGES_1_XPATH: image = self.tree.xpath(xpath) if image: images.append(image[0]) if images: return images return 'Could not get product images.' def get_product_additional_info(self): info = self.tree.xpath(PRODUCT_ADDITIONAL_INFO_XPATH) if info: return info[0] return 'Could not get product additional info' def get_product_important_notes(self): notes = self.tree.xpath(PRODUCT_IMPORTANT_NOTES_XPATH) if notes: return ''.join(notes) return 'Could not get product important notes' def get_product_details(self): details = self.tree.xpath(PRODUCT_DETAILS_XPATH) if details: result = [] for k, v in zip(details[::2], details[1::2]): result.append({ 'key': k, 'value': v }) return result return 'Could not get product details.' def get_product_related_items(self): rel_items = self.tree.xpath(PRODUCT_RELATED_ITEMS_XPATH) if rel_items: result = [] for cn, n in zip(rel_items[::2], rel_items[1::2]): result.append({ 'catalogNumber': cn.strip(), 'name': n }) return result return 'Could not get product related items.' def to_json(self): return { 'catalogNumber': self.get_catalog_number(), 'Name': self.get_product_name(), 'specification': self.get_product_specification(), 'description': self.get_product_description(), 'logos': self.get_small_images(), 'logos1': self.get_small_images_1(), 'additionalInfo': self.get_product_additional_info(), 'importantNotes': self.get_product_important_notes(), 'image': self.get_image(), 'details': self.get_product_details(), 'relatedItems': self.get_product_related_items() } def retry(url): try: return requests.get(url).text except Exception as e: print('Retrying product page in {} seconds because: {}'.format(wait, e)) return retry(url) def get_sitemap_url(): raw_html_page = retry(SITEMAP_URL) tree = html.fromstring(raw_html_page) for sitemap_url in tree.xpath(SITEMAP_URLS_XPATH): if 'GroupID' in sitemap_url: yield f'{URL}{sitemap_url}' def get_product_page(url): raw_html_page = retry(url) tree = html.fromstring(raw_html_page) for category_link in tree.xpath(CATEGORIES_XPATH): yield from get_product_page(f'{URL}/crlapps/showline/{category_link}') for category_link in tree.xpath(CATEGORIES_XPATH): link = f'{URL}/crlapps/showline/{category_link}' if 'ProductID' in link: yield link def main(): for sitemap_url in get_sitemap_url(): for product_link in get_product_page(sitemap_url): raw_html_page = retry(product_link) tree = html.fromstring(raw_html_page) product = Product(tree, product_link).to_json() with open('crlaurence.json') as result_json_file: existing_data = json.load(result_json_file) existing_data.append(product) with open('crlaurence.json', 'w') as result_json_file: json.dump(existing_data, result_json_file, indent=4) if __name__ == '__main__': main() </code></pre> <p><strong>Concerns:</strong></p> <ul> <li>while I'm aware of PEP8 I'd like the reviews to be mostly focused on improving the speed of the program (although any suggestion is welcome!). The program takes more than 20 hours to run and I'm wondering if there're any ways to improve on that.</li> </ul>
[]
[ { "body": "<p>You should probably start with a profiler whenever you have unexplained\nperformance problems, that should quickly point you to the functions or\nareas that take most of the runtime.</p>\n\n<p>That said, I immediately noticed the <code>json.load</code> and <code>json.dump</code> are\ncalled more than once. That seems to be at least a first candidate for\noptimisation. Either start keeping everything in RAM until you're ready\nto write it to disk, or perhaps write it to disk while you're still\nscraping (if you need any postprocessing: do it all at once when all\ndata has been collected).</p>\n\n<p>The program also doesn't run without a previously set up JSON output\nfile, that's definitely worth fixing.</p>\n\n<p>Yeah, so after a few seconds I've got like 100kb already. If this runs\nfor 20 hours, the amount of time spent on parsing and dumping this data\nover and over and over is gonna be quite a bit - and it's going get slower the further on this is running, so while at the start the impact measured might not be that much, it's just gonna increase.</p>\n\n<p>There's no logging, so of course it's also hard to see what the program\nis doing. Consider putting in maybe the URLs, or a dot every 100 pages,\nor whatever thing to make it easier to spot progress (or the lack\nthereof).</p>\n\n<p>Come to think of it, unless you've ruled out that possibility, the\nscraping might get throttled by the website.</p>\n\n<p>Edit: That reminds me, each page is fetched sequentially and there'll be a lot of waiting for network I/O. The next obvious thing would be to do the fetching concurrently. Have a couple of worker threads / processes and fetch multiple pages at the same time, getting new work items from a shared queue or so, then write results to disk in another thread.</p>\n\n<hr>\n\n<p>I'm gonna suggest using <code>cProfile</code> here, but just take a look at\n<a href=\"https://docs.python.org/3/library/debug.html\" rel=\"noreferrer\">the reference</a> too.</p>\n\n<p>In particular, try this:</p>\n\n<pre><code>python3 -m cProfile -o profile laurence.py\n</code></pre>\n\n<p>Wait a moment, then abort the run. Next, inspect the output:</p>\n\n<pre><code>python3 -m pstats profile\n</code></pre>\n\n<p>Use <code>sort</code> and <code>stats</code>, like <code>sort time</code> and <code>stats 10</code> or so to get an\noverview.</p>\n\n<p>And it really looks like the I/O is the biggest reason from the very small\nsample.</p>\n\n<hr>\n\n<p>Lastly, parsing via <code>lxml</code> into a full DOM tree might be slow too, plus\nevaluation of the XPath queries (convenient as they might be). You\ncould always explore a SAX or similar streaming parser. In Python\nthat's for example\n<a href=\"https://docs.python.org/3/library/html.parser.html\" rel=\"noreferrer\"><code>html.parser</code></a> -\nnot sure how it looks like from the compatibility perspective of course.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T08:34:33.960", "Id": "415740", "Score": "2", "body": "Nice answer! Worth adding though that [lxml](http://lxml.de/) is generally considered to be the fastest among existing Python parsers, though the parsing speed depends on multiple factors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T15:08:10.963", "Id": "415804", "Score": "0", "body": "Yeah, I'd focus on the network latencies first, it's just one of the easy things to check in case of a scraper. It also looks like the memory consumption could be reduced, but all of those will probably be secondary." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T22:04:27.947", "Id": "214962", "ParentId": "214955", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T20:37:38.400", "Id": "214955", "Score": "7", "Tags": [ "python", "performance", "python-3.x", "json", "web-scraping" ], "Title": "Web-scraping C.R. Laurence product catalog" }
214955
<p>I have a Spring Boot application and I wrote a piece of code to manage relationships between two entities.</p> <p>The code consists mostly in these two methods:</p> <pre><code>@Override public void associateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) { PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null); if (personRecord == null) return; for (Long documentId : associationDTO.getDocumentsId()) documentRepository .findById(documentId) .ifPresent(document -&gt; personRecord.getDocuments().add(document)); personRecordRepository.save(personRecord); } @Override public void removeAssociateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) { PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null); if (personRecord == null) return; for (Long documentId : associationDTO.getDocumentsId()) documentRepository .findById(documentId) .ifPresent(document -&gt; personRecord.getDocuments().remove(document)); personRecordRepository.save(personRecord); } </code></pre> <p>One method is for adding relations, the other is to remove them.</p> <p>I definitely get the smell of duplicated code and the only thing that changes is <code>remove</code> or <code>add</code> between the two methods. How could I refactor this code in the most elegant way?</p>
[]
[ { "body": "<p>You may extract the action part as a method parameter (I am using BiConsumer in this case).</p>\n\n<pre><code>@Override\npublic void performActionOnRecords(Long personRecordId, AssociationDTO associationDTO, BiConsumer&lt;PersonRecord,Document&gt; action) {\n PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);\n if (personRecord == null)\n return;\n\n for (Long documentId : associationDTO.getDocumentsId())\n documentRepository\n .findById(documentId)\n .ifPresent(document -&gt; action.accept(personRecord,document));\n\n personRecordRepository.save(personRecord);\n}\n</code></pre>\n\n<p>and call the methods as </p>\n\n<pre><code>performActionOnRecords(personId, associationDTO, (personRecord, document) -&gt; personRecord.getDocuments().add(document)); // To add document\n</code></pre>\n\n<p>and,</p>\n\n<pre><code>performActionOnRecords(personId, associationDTO, (personRecord, document) -&gt; personRecord.getDocuments().remove(document)); // To remove document\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T22:29:08.380", "Id": "214964", "ParentId": "214958", "Score": "1" } } ]
{ "AcceptedAnswerId": "214964", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T21:17:32.670", "Id": "214958", "Score": "0", "Tags": [ "java", "spring", "spring-mvc" ], "Title": "Spring Boot methods to add and remove relationships" }
214958
<p><a href="https://projecteuler.net/problem=27" rel="nofollow noreferrer">Problem 27</a> The Goal of the problem is to find the quadratic (n^2+an+b) that can generate the most consecutive primes, such that |a|&lt;1000 and |b|&lt;1001</p> <p>So I decided to brute force it using python. However, the script I wrote it quite slow. What did I do wrong and how can I improve it?</p> <pre><code>primes=[] #prime list prime_multiples = set() for i in range(2, 3000000): if i not in prime_multiples: primes.append(i) prime_multiples.update(range(i, 3000000, i)) bm=-1000 n=0 am=-999 count=40 a=-999 while a&lt;=999: b=1 while b&lt;=1000 : n=0 n_c=1 while n_c==1 : attemp = n**2 +a*n +b if all(-i**2 -i*a&lt;=b for i in range(0, 40)) and b in primes: if attemp in primes: n+=1 if n&gt;=count: count=n am=a bm=b prod=am*bm print(f"a={am} with b={bm} gave {count} consecutive primes") print(f"the pruduct is {prod}") else: n_c=2 else: n_c=2 b+=1 a+=1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T10:17:03.163", "Id": "415758", "Score": "4", "body": "Could you please summarize the requirement? Although the link may help readers now, we need some description in the body of the question, so that it's still meaningful when the link can't be followed (if the other site disappears, or when the question is printed)." } ]
[ { "body": "<p>Inside the <code>while n_c == 1:</code> loop, is <code>b</code> constant? If <code>b in primes</code> is false, does it make sense to even bother entering the <code>while n_c == 1:</code> loop? And if it is prime before entering the loop, does it make sense to test if it is true every iteration of that loop? Avoid wasting time by moving invariant expressions and conditions out of loops!</p>\n\n<p>Your first two while loops would be better written as <code>for variable in range(lower_limit, upper_limit+1):</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T04:12:31.640", "Id": "214982", "ParentId": "214961", "Score": "1" } }, { "body": "<blockquote>\n<pre><code>primes=[] #prime list\nprime_multiples = set()\nfor i in range(2, 3000000):\n if i not in prime_multiples:\n primes.append(i)\n prime_multiples.update(range(i, 3000000, i))\n</code></pre>\n</blockquote>\n\n<p>It's conventional to do the sieve of Eratosthenes with an array of booleans, not a set. You probably get better cache coherence that way, and you can do fast checks afterwards whether something is a prime. <code>in</code> checks against a list are <em>slow</em>, because they are <em>linear</em>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>bm=-1000\nn=0\nam=-999\n</code></pre>\n</blockquote>\n\n<p>What purpose do these variables serve?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>a=-999\nwhile a&lt;=999:\n ....\n a+=1\n</code></pre>\n</blockquote>\n\n<p>The Pythonic approach would be</p>\n\n<pre><code>for a in range(-999, 1000):\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> n=0\n n_c=1\n while n_c==1 :\n attemp = n**2 +a*n +b\n if all(-i**2 -i*a&lt;=b for i in range(0, 40)) and b in primes:\n if attemp in primes:\n n+=1\n if n&gt;=count:\n count=n\n am=a\n bm=b\n prod=am*bm\n print(f\"a={am} with b={bm} gave {count} consecutive primes\")\n print(f\"the pruduct is {prod}\")\n else:\n n_c=2\n else:\n n_c=2\n</code></pre>\n</blockquote>\n\n<p>What is this code doing? The task (which, as an aside, it would have been very helpful to find in the question alongside the code) is</p>\n\n<blockquote>\n <p>Considering quadratics of the form: <span class=\"math-container\">\\$n^2+an+b\\$</span>, where <span class=\"math-container\">\\$|a|&lt;1000\\$</span> and <span class=\"math-container\">\\$|b|\\le 1000\\$</span> find the product of the coefficients, <span class=\"math-container\">\\$a\\$</span> and <span class=\"math-container\">\\$b\\$</span>, for the quadratic expression that produces the maximum number of primes for consecutive values of <span class=\"math-container\">\\$n\\$</span>, starting with <span class=\"math-container\">\\$n=0\\$</span>.</p>\n</blockquote>\n\n<p>So what I would expect to find in the loop is a simple count: what is the largest <span class=\"math-container\">\\$n\\$</span> for which the quadratic gives a prime? Instead there are nested loops and control flow which looks like it's from the 50s, from a language which doesn't have subroutines. Consider</p>\n\n<pre><code>n = next(iter(i for i in itertools.count() if (i**2 + a*i + b) not in primes))\nif n &gt; count:\n count = n\n printf(f\"a={a} with b={b} gave {count} consecutive primes with product {a*b}\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T10:04:05.267", "Id": "215012", "ParentId": "214961", "Score": "3" } } ]
{ "AcceptedAnswerId": "215012", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T21:55:55.413", "Id": "214961", "Score": "-1", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Brute forcing Project Euler Problem 27" }
214961
<p>The problem I'm referring to is available <a href="https://leetcode.com/problems/triangle/" rel="nofollow noreferrer">here</a>. In quick summary, the problem gives a list of lists such as [[2],[3,4],[6,5,7],[4,1,8,3]] and we must find the minimum path sum: 2 + 3 + 5 + 1 = 11. I took the obvious DP approach:</p> <pre><code>def minimumTotal(self, triangle): # make a memo with n rows and i columns # where i is the number of elements in the last row n, i = len(triangle), len(triangle[-1]) memo = [[0] * i for _ in range(n)] # add the base case memo[0][0] = triangle[0][0] for m in range(1, n): for k in range(m + 1): if (k == 0): memo[m][k] = triangle[m][k] + (memo[m-1][0] if m - 1 &gt;= 0 else float("inf")) elif (m == k): memo[m][k] = triangle[m][k] + (memo[m-1][k-1] if m - 1 &gt;= k - 1 else float("inf")) else: memo[m][k] = triangle[m][k] + min(memo[m-1][k-1] if m - 1 &gt;= k - 1 else float("inf"), memo[m-1][k] if m - 1 &gt;= k else float("inf")) # now loop through the last row and choose the min answer = memo[-1][0] for l in range(1,i): if (memo[-1][l] &lt; answer): answer = memo[-1][l] return answer </code></pre> <p>This code is faster than 95% of the other submission times so I'm satisfied with run time. However, what I am interested in is how to (a.) make this code more "Pythonic" and (b.) how to improve the memory usage. This code is more memory efficient than only 8% of submissions so I'm curious on how to better improve this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:50:31.040", "Id": "415727", "Score": "0", "body": "Drop the parens around your if conditions." } ]
[ { "body": "<p>Your memo array is pretty inefficient, as it is of size <span class=\"math-container\">\\$n^2\\$</span>. There's a lot of wasted cells there, right? So one idea to improve the space complexity would be for each <code>memo[i]</code> to be just the right length. For example, <code>memo[0]</code> would be an array of length 1 instead of length n.. This would reduce space complexity from <span class=\"math-container\">\\$n^2\\$</span> to <span class=\"math-container\">\\$n(n+1)/2\\$</span>. Still quadratic, but a small improvement.</p>\n\n<p>But you can see that you don't need to keep all that information. All you care about is the previous row, so there's no need to keep more history than that. You could have an array of length n that represents the previous state and reuse it as you go through the triangle. This would result in a space complexity of <span class=\"math-container\">\\$O(n)\\$</span>, a big improvement. Of course, if you could change the input in place you could do a space complexity of <span class=\"math-container\">\\$O(1)\\$</span> - no extra space required :)</p>\n\n<p>I also like to use a bottom up approach to these problems. It's more beautiful, as it makes the solution just bubble up. It would rid you of the last <code>for</code> loop as well, which would make it just a bit faster. </p>\n\n<p>Here's a sketch: </p>\n\n<pre><code>t = [v for v in triangle[-1]]\nfor i in range(len(triangle) - 2, -1 , -1):\n for j in range(len(triangle[i])):\n t[j] = min(t[j], t[j + 1]) + triangle[i][j]\n\nreturn t[0]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T23:05:52.060", "Id": "214967", "ParentId": "214963", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T22:09:22.280", "Id": "214963", "Score": "2", "Tags": [ "python", "algorithm", "memory-optimization" ], "Title": "Writing a more Pythonic solution to the min triangle path" }
214963
<p><a href="https://i.stack.imgur.com/qldty.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qldty.gif" alt="enter image description here"></a></p> <p>I stumbled on the idea of a <a href="http://rosettacode.org/wiki/Forest_fire" rel="nofollow noreferrer">Forest Fire simulating cellular automata</a>, and decided to try making a version using a full <a href="https://github.com/daveray/seesaw" rel="nofollow noreferrer">Seesaw</a> UI (a Clojure wrapper over Java's Swing). A short sample of it running is above.</p> <p>It ended up being fairly straightforward; although I've written a fair number of CA's before, so this was more just applying a specific rule-set, and designing a quick UI.</p> <p>It can be used in the console too using <code>format-world</code>. <code>T</code>'s are trees, and <code>#</code>s are fire squares:</p> <pre><code>(let [r (g/new-rand-gen 99) w (new-empty-world [10 10] (new-chance-settings 0.3 0.1)) worlds (-&gt;&gt; w (iterate #(advance % r)) (take 5))] (doseq [world worlds] (println (format-world world) "\n"))) T T T T T T T T T T T T T T T T T T T T T T T T T T # T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T # T T T T # # T T T T T T T # # # # T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T # T T T T T T T T # T T T T # T T # # # T T T T # # # # T T T T T T T T T T T T T T T T T # T T # T # T T T T # T T # T T T T # # # T T T T T T </code></pre> <p>I'd like any general suggestions. I'm not very organized, so my UI tends to become a mess. Any suggestions for improvements there especially would be appreciated.</p> <hr> <p>Helper functions for dealing with 2D vectors</p> <pre><code>(ns forest-fire.grid (:require [clojure.string :as s])) (defn new-grid [dimensions initial-cell] (let [[w h] dimensions] (vec (repeat h (vec (repeat w initial-cell)))))) (defn set-cell [grid position new-cell] (let [[x y] position] (assoc-in grid [y x] new-cell))) (defn get-cell [grid position] (let [[x y] position] (get-in grid [y x]))) (defn dimensions-of [grid] [(count (first grid)) (count grid)]) (defn positions-of "Returns a lazy list of every integer coordinate in the grid." [grid] (let [[w h] (dimensions-of grid)] (for [y (range h) x (range w)] [x y]))) (defn format-grid "Gives each cell to str-map to decide what str is used in formating. Uses \" \" if str-map returns nil" [grid str-map] (-&gt;&gt; grid (map (fn [row] (map #(or (str-map %) " ") row))) (map #(s/join " " %)) (s/join "\n"))) </code></pre> <p>An abridged part of my personal library used in the project</p> <pre><code>(ns helpers.general-helpers) (defn new-rand-gen ([seed] (Random. seed)) ([] (Random.))) (defn random-perc "Returns true perc-chance percent of the time." [^double perc-chance, ^Random rand-gen] (&lt;= (.nextDouble rand-gen) perc-chance)) (defn map-range "Maps a value from the range [start1 stop1] to a value in the range [start2 stop2]." [value start1 stop1 start2 stop2] (+ start2 (* (- stop2 start2) (/ (- value start1) (- stop1 start1))))) (defn parse-double "Returns nil on bad input." [str-n] (try (Double/parseDouble str-n) (catch NumberFormatException _ nil))) </code></pre> <p>The main state of the simulation</p> <pre><code>(ns forest-fire.world (:require [forest-fire.grid :as gr] [helpers.general-helpers :as g])) (def cell-types #{::empty, ::tree, ::burning}) (defn new-chance-settings [grow-chance burn-chance] {:grow-chance grow-chance, :burn-chance burn-chance}) (defn new-empty-world [dimensions settings] {:grid (gr/new-grid dimensions ::empty) :settings settings}) (defn dimensions-of [world] (-&gt; world :grid (gr/dimensions-of))) (defn- positions-around "Returns the coordinates around a cell representing the Moore neighborhood of the cell (when (= depth 1))." ([position dimensions depth] (let [[cx cy] position [w h] dimensions] (for [y (range (max 0 (- cy depth)) (min h (+ cy depth 1))) x (range (max 0 (- cx depth)) (min w (+ cx depth 1))) :let [neigh-pos [x y]] :when (not= neigh-pos position)] neigh-pos))) ([position dimensions] (positions-around position dimensions 1))) (defn- neighbors-of "Returns the cells in the Moore neighborhood of a cell." [grid position] (let [dims (gr/dimensions-of grid)] (-&gt;&gt; (positions-around position dims) (map #(gr/get-cell grid %))))) (defn- has-burning-neighbor? [grid position] (-&gt;&gt; (neighbors-of grid position) (some #(= % ::burning)))) (defn- advance-cell [new-grid old-grid position chance-settings rand-gen] (let [contents (gr/get-cell old-grid position) {:keys [grow-chance burn-chance]} chance-settings] (case contents ::burning (gr/set-cell new-grid position ::empty) ::empty (if (g/random-perc grow-chance rand-gen) (gr/set-cell new-grid position ::tree) new-grid) ::tree (cond ; Doing this check first since it'll be much cheaper (g/random-perc burn-chance rand-gen) (gr/set-cell new-grid position ::burning) (has-burning-neighbor? old-grid position) (gr/set-cell new-grid position ::burning) :else new-grid)))) (defn- advance-grid [grid chance-settings rand-gen] (reduce (fn [acc-grid pos] (advance-cell acc-grid grid pos chance-settings rand-gen)) grid (gr/positions-of grid))) (defn advance "Advances the forest fire world by 1 \"tick\"" [world rand-gen] (let [{:keys [settings]} world] (update world :grid advance-grid settings rand-gen))) (defn format-world "Formats the world into a String to be printed." [world] (let [format-f {::empty " ", ::burning "#", ::tree "T"}] (gr/format-grid (:grid world) format-f))) </code></pre> <p>The main UI</p> <pre><code>(ns forest-fire.seesaw-ui (:require [seesaw.core :as sc] [seesaw.graphics :as sg] [forest-fire.world :as fw] [forest-fire.grid :as gr] [helpers.general-helpers :as g]) (:import [java.awt Component] [javax.swing Timer])) (def settings-font {:name "Arial", :size 40}) (def global-rand-gen (g/new-rand-gen 99)) (def default-advance-delay 100) (defn component-dimensions [^Component c] [(.getWidth c), (.getHeight c)]) (defn world-&gt;canvas-position [world-position world-dimensions canvas-dimensions] (let [[x y] world-position [ww wh] world-dimensions min-canvas-dim (apply min canvas-dimensions)] [(g/map-range x, 0 ww, 0 min-canvas-dim) (g/map-range y, 0 wh, 0 min-canvas-dim)])) (defn square-size [world-dimensions canvas-dimensions] (double (/ (apply min canvas-dimensions) (apply min world-dimensions)))) (defn paint [world-atom canvas g] (let [{:keys [grid] :as world} @world-atom world-dims (fw/dimensions-of world) canvas-dims (component-dimensions canvas) sq-width (square-size world-dims canvas-dims) w-&gt;c #(world-&gt;canvas-position % world-dims canvas-dims)] (doseq [world-pos (gr/positions-of grid)] (let [cell (gr/get-cell grid world-pos)] (when-not (= cell ::fw/empty) (let [[cx cy] (w-&gt;c world-pos) col (case cell ::fw/tree :green ::fw/burning :red)] (sg/draw g (sg/rect cx cy sq-width sq-width) (sg/style :background col, :foreground :black)))))))) (defn new-canvas [state-atom] (let [canvas (sc/canvas :paint (partial paint state-atom), :id :canvas)] canvas)) (defn new-input-pair [label-text settings-key state-atom] (let [current-world @state-atom initial-value (get-in current-world [:settings settings-key]) label (sc/label :text (str label-text), :font settings-font) input (sc/text :text (str initial-value), :font settings-font)] (sc/listen input :key-released (fn [_] (when-let [parsed (g/parse-double (sc/text input))] (swap! state-atom assoc-in [:settings settings-key] parsed)))) (sc/horizontal-panel :items [label input]))) (defn new-main-panel [state-atom] (let [canvas (new-canvas state-atom) settings-bar (sc/horizontal-panel :items [(new-input-pair "Burn Chance" :burn-chance state-atom) (new-input-pair "Grow Chance" :grow-chance state-atom)])] (sc/border-panel :center canvas, :south settings-bar))) (defn world-advancer "Advances the world and repaints the canvas every advance-delay ms. Returns a 0-arity function that stops the timer when called." [state-atom canvas advance-delay] (let [t (sc/timer (fn [_] (swap! state-atom fw/advance global-rand-gen) (sc/repaint! canvas)) :delay advance-delay)] (fn [] (.stop ^Timer t)))) (defn new-frame [starting-world] (let [state-atom (atom starting-world) main-panel (new-main-panel state-atom) canvas (sc/select main-panel [:#canvas]) frame (sc/frame :content main-panel, :size [1000 :by 1000]) stop-advancer (world-advancer state-atom canvas default-advance-delay)] (sc/listen frame :window-closing (fn [_] (stop-advancer))) frame)) (defn -main [] (let [w (-&gt; (fw/new-empty-world [100 100] (fw/new-chance-settings 0.9 0.0001)) (fw/advance global-rand-gen) (fw/advance global-rand-gen))] (-&gt; (new-frame w) (sc/show!)))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T22:56:18.900", "Id": "214966", "Score": "3", "Tags": [ "swing", "animation", "clojure", "cellular-automata" ], "Title": "Forest Fire Cellular Automata" }
214966
<p>I profiled a library I'm writing that uses vector transposes and found that I am spending a good bit of time doing the following transpose. I am using a <code>std::vector</code> of <code>std::vector&lt;double&gt;</code>s to represent the column vectors.</p> <p>What are some ways to optimize this function?</p> <pre><code>std::vector&lt;double&gt; transpose_vector(const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;column_vec) { // take a column vector: // |x1| // |x2| // |x3| // and return a row vector |x1, x2, x3| std::vector&lt;double&gt; row_vector; for (auto c : column_vec) { for (auto r : c) { row_vector.push_back(r); } } return row_vector; } </code></pre>
[]
[ { "body": "<p>There's not really much here. The only thing I can think of is it may prove faster to pre-allocate the destination vector using <a href=\"http://www.cplusplus.com/reference/vector/vector/reserve/\" rel=\"noreferrer\"><code>reserve</code></a>. <code>push_back</code> has the potential to cause several re-allocations per call to <code>transpose</code>, which will be slow. Try:</p>\n\n<pre><code>std::vector&lt;double&gt; transpose_vector(const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;column_vec) {\n std::vector&lt;double&gt; row_vector;\n row_vector.reserve(total_entries(column_vec)); // Pre-allocate the space we need\n\n for (auto c : column_vec) {\n for (auto r : c) {\n row_vector.push_back(r);\n }\n }\n return row_vector;\n}\n</code></pre>\n\n<p>Where <code>total_entries</code> is a function that finds how many cells there are in the 2D vector. If each row is the same length, you could use math to figure this out. If it's ragged though, you may need to iterate <code>column_vector</code> summing the row lengths.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T23:52:28.020", "Id": "214973", "ParentId": "214971", "Score": "7" } }, { "body": "<p>Change your column loop to use a reference.</p>\n\n<pre><code>for (const auto &amp;c : column_vec)\n</code></pre>\n\n<p>Without the reference, a copy will be made of each vector. This will involve a memory allocation. Using the reference you avoid all that, which should save a good deal of time since each <code>c</code> will be a single element vector.</p>\n\n<p><code>auto r</code> can stay since <code>r</code> will be a <code>double</code>.</p>\n\n<p>Combine this with using <code>reserve</code> on <code>row_vector</code> will eliminate all but one memory allocation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T04:31:47.453", "Id": "214983", "ParentId": "214971", "Score": "16" } }, { "body": "<p>Is the vector-of-vectors representation imposed on you, or can you change it? It's going to be more efficient to allocate a single vector, and use simple arithmetic to convert row/column representation into a linear index. It's then possible to provide a transpose <em>view</em> without needing to move all the elements, which may be useful in some circumstances (in others, you'll want to actually perform the transpose, to keep rows contiguous in cache).</p>\n\n<p>If you have a <em>square</em> matrix, a simpler way to transpose (which may or may not be faster - but you'll be benchmarking anyway, to confirm) is to take a copy of the input, and then <code>swap()</code> the elements across the leading diagonal. This is likely to be most advantageous when the elements are trivially copyable, such as the <code>double</code> you're using here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T10:27:57.747", "Id": "215014", "ParentId": "214971", "Score": "12" } }, { "body": "<p>Given that you say this is to transpose <em>vectors</em> and not matrices in general, you can initialize the row vector with the inner vector, for gcc and clang compiler explorer shows differing results between using the iterators or just the inner array. </p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;cassert&gt;\n\nstd::vector&lt;double&gt; transpose_vector(const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;column_vec) {\n // take a column vector:\n // |x1|\n // |x2|\n // |x3|\n // and return a row vector |x1, x2, x3|\n assert(column_vec.size() == 1);\n return std::vector&lt;double&gt;(column_vec[0].cbegin(), column_vec[0].cend());\n}\n</code></pre>\n\n<p>As @TobySpeight mentioned the question is if you chose this representation yourself or if you were given in. For example you could probably be more flexible if you separated the storage from the dimension of the data being transported. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T19:11:34.707", "Id": "215053", "ParentId": "214971", "Score": "2" } }, { "body": "<p>The most important point is the name and contract.</p>\n\n<p>And your function doesn't really do any transposing, it just flattens a vector of vectors into a vector, creating spurious temporaries on the way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T23:45:36.250", "Id": "215063", "ParentId": "214971", "Score": "0" } } ]
{ "AcceptedAnswerId": "214983", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-07T23:27:43.897", "Id": "214971", "Score": "7", "Tags": [ "c++", "performance", "c++11", "vectors" ], "Title": "Vector-transposing function" }
214971
<blockquote> <h2><a href="https://vjudge.net/problem/HihoCoder-1223" rel="nofollow noreferrer">Inequality</a></h2> <p>Given <em>n</em> inequalities about <em>X</em>, how many of them can hold at the same time at most?</p> <p>The inequalities are in the following forms:</p> <ul> <li><p>X &lt; C</p> </li> <li><p>X &lt;= C</p> </li> <li><p>X = C</p> </li> <li><p>X &gt; C</p> </li> <li><p>X &gt;= C</p> </li> </ul> <h3>input</h3> <ul> <li><p>First line with an integer <code>n</code>.</p> </li> <li><p>Following <code>n</code> lines, each line with an inequality.</p> </li> <li><p>Data Limit:</p> <p>1 ≤ N ≤ 50, 0 ≤ C ≤ 1000</p> </li> </ul> <h3>output</h3> <ul> <li>One line with an integer, denoting the answer.</li> </ul> <h3>Sample Input</h3> <pre><code>4 X = 1 X = 2 X = 3 X &gt; 0 </code></pre> <h3>Sample Output</h3> <pre><code>2 </code></pre> </blockquote> <p>Here is my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;set&gt; using namespace std; int main() { //cout&lt;&lt;&quot;请输入:&quot;&lt;&lt;endl; int T; cin &gt;&gt; T; int count = T; vector&lt;float&gt; arrayOne(T, 0); vector&lt;int&gt; arrayTwo(T, 0); map&lt;string, int&gt; symbols = { pair&lt;string, int&gt;(&quot;&gt;&quot;, 1), pair&lt;string, int&gt;(&quot;&gt;=&quot;, 2), pair&lt;string, int&gt;(&quot;=&quot;, 3), pair&lt;string, int&gt;(&quot;&lt;=&quot;, 4), pair&lt;string, int&gt;(&quot;&lt;&quot;, 5) }; while(T--) { string sOne; cin &gt;&gt; sOne; string sThree; cin &gt;&gt; sThree; arrayTwo[count-T-1] = symbols.find(sThree)-&gt;second; std::string sTwo; std::cin &gt;&gt; sTwo; float num = stof(sTwo); arrayOne[count-T-1] = num; } set&lt;float&gt; answerSet; for (float numPiece: arrayOne){ answerSet.insert(numPiece-0.5); answerSet.insert(numPiece); answerSet.insert(numPiece+0.5); } int answer = 0; for (set&lt;float&gt;::iterator testNum=answerSet.begin(); testNum != answerSet.end(); ++testNum){ // cout&lt;&lt;*testNum; int passNum = 0; int i = 0; for (int numTwo: arrayTwo){ switch (numTwo) { case 1: { if (*testNum &gt; arrayOne[i]) { passNum += 1; } } break; case 2: { if (*testNum &gt;= arrayOne[i]) { passNum += 1; } } break; case 3: { if (*testNum == arrayOne[i]) { passNum += 1; } } break; case 4: { if (*testNum &lt;= arrayOne[i]) { passNum += 1; } } break; case 5: { if (*testNum &lt; arrayOne[i]) { passNum += 1; } } break; default: break; } i++; } answer = max(answer, passNum); } cout&lt;&lt;answer&lt;&lt;endl; return 0; } </code></pre> <p>Very intuitive , just get all the boundary numbers, then find the max passes.</p> <p>How to make it more efficient?</p>
[]
[ { "body": "<p>One easy change...</p>\n\n<p>If you have <code>N</code> inequalities, you add up to <code>3N</code> test numbers to your set.</p>\n\n<p>You only need <code>2N+1</code> test numbers: say, <code>numPiece</code> and <code>numPiece+0.5</code> ... and say <code>-inf</code> for the last point.</p>\n\n<hr>\n\n<p>With <code>N</code> inequalities and <code>3N</code> test values, your algorithm is <span class=\"math-container\">\\$O(N^2)\\$</span>. </p>\n\n<p>If you sorted your inequalities by <code>C</code> values, you could move over the inequalities in order, and keep a running total of passing inequalities, and recording the maximum, for an overall <span class=\"math-container\">\\$O(N \\log N)\\$</span> time complexity</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:41:46.827", "Id": "214993", "ParentId": "214976", "Score": "3" } }, { "body": "<h1>Avoid <code>using namespace std;</code></h1>\n\n<p>Bringing all names in from a namespace is problematic; <code>namespace std</code> particularly so. See <a href=\"//stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>.</p>\n\n<h1>Don't do everything in <code>main()</code></h1>\n\n<p>Putting all the code into the <code>main()</code> function makes it harder to test parts of the program separately. If we at least create a function that can read from an arbitrary <code>std::istream</code>, then we're able to do more repeatable testing (by passing suitable <code>std::istringstream</code> objects with our test data in).</p>\n\n<h1>Always test that input was successfully read</h1>\n\n<p>When we read values from an input stream, we <em>must</em> check that the read was successful before using those values. A simple way to do that is to set the stream to throw exceptions on failures.</p>\n\n<p>We also need to be more robust when we've read the inequality type, rather than just assuming it will be found in <code>symbols</code>.</p>\n\n<h1>Consider using unsigned types</h1>\n\n<p>We know that <em>N</em> can't be negative, and the answer is a count of results, which must necessarily be non-negative, too.</p>\n\n<h1>Magic numbers</h1>\n\n<p>The magic numbers <code>1</code>..<code>5</code> used for the different inequalities should be given names. But there's something better that we can do: we can change their type to be the actual functions:</p>\n\n<pre><code>#include &lt;functional&gt;\n\n///...\n{\n\n using inequality = std::function&lt;bool(float,float)&gt;;\n\n vector&lt;float&gt; arrayOne(T, 0);\n vector&lt;inequality&gt; arrayTwo(T);\n static const std::map&lt;string, inequality&gt; symbols =\n {\n { \"&gt;\", std::greater&lt;float&gt;() },\n { \"&gt;=\", std::greater_equal&lt;float&gt;() },\n { \"=\", std::equal_to&lt;float&gt;() },\n { \"&lt;=\", std::less_equal&lt;float&gt;() },\n { \"&lt;\", std::less&lt;float&gt;() },\n };\n</code></pre>\n\n<p>Then the big <code>switch</code> becomes much simpler:</p>\n\n<pre><code> for (auto const&amp; numTwo: arrayTwo){\n passNum += numTwo(*testNum, arrayOne[i]);\n i++;\n }\n</code></pre>\n\n<p>(I must point out in passing that those names - <code>arrayOne</code>, <code>arrayTwo</code>, <code>numTwo</code> - are really uninformative and unhelpful; you really do need to spend some time thinking of better names if you want to be able to understand your code again later.)</p>\n\n<h1>Reconsider the algorithm</h1>\n\n<p>Instead of performing all the comparisons on a selection of values (which is O(<em>n</em>²) unless there's many duplicate <code>C</code> values), let's consider what happens to the number of satisfied inequalities as we move <code>X</code> from -∞ to +∞:</p>\n\n<ul>\n<li>each <code>&lt;</code> changes the count by -1 infinitesimally before <code>C</code></li>\n<li>each <code>&lt;=</code> changes the count by -1 infinitesimally after <code>C</code></li>\n<li><code>&gt;=</code> and <code>&gt;</code> change the count by +1 before or after <code>C</code>, respectively</li>\n<li><code>=</code> changes the count by +1 before and -1 after.</li>\n</ul>\n\n<p>So we can keep an ordered map of those changes:</p>\n\n<pre><code>struct delta\n{\n int before;\n int after;\n\n delta&amp; operator+=(const delta&amp; other)\n {\n before += other.before;\n after += other.after;\n return *this;\n }\n};\n</code></pre>\n\n<p>Then, just add the appropriate delta values for each inequality:</p>\n\n<pre><code>static const std::map&lt;string, delta&gt; symbol_delta =\n {\n { \"&gt;\", { 0, 1 } },\n { \"&gt;=\", { 1, 0 } },\n { \"=\", { 1, -1 } },\n { \"&lt;=\", { 0, -1 } },\n { \"&lt;\", { -1, 0 } },\n };\n\nfor (auto i = 0u; i &lt; lines; ++i) {\n std::string var;\n std::string symbol;\n double value;\n\n in &gt;&gt; var &gt;&gt; symbol &gt;&gt; value;\n if (var != \"X\") {\n throw std::invalid_argument(var);\n }\n\n auto entry = symbol_delta.find(symbol);\n if (entry == symbol_delta.end()) {\n throw std::invalid_argument(symbol);\n }\n\n const delta&amp; d = entry-&gt;second;\n changes[value] += d;\n if (d.before + d.after &lt; 0) {\n // it's a less-than relation, so true at -∞\n ++count;\n }\n}\n</code></pre>\n\n<p>When that's done, start with a count of the number of inequalities that are true at -∞, (i.e. the total number of <code>&lt;</code> and <code>&lt;=</code> we've seen) and update that count as we walk the map, keeping track of the maximum:</p>\n\n<pre><code>auto max_count = count;\n// now, advance to +∞; updating count as we go\nfor (auto&amp; entry: changes) {\n const delta&amp; d = entry.second;\n count += d.before;\n if (count &gt; max_count) { max_count = count; }\n count += d.after;\n if (count &gt; max_count) { max_count = count; }\n}\n</code></pre>\n\n<p>The complexity of this algorithm is O(<em>n</em> log <em>n</em>), because we're doing a O(log <em>n</em>) insertion into the map <em>n</em> times.</p>\n\n<h1>Full working alternative</h1>\n\n<pre><code>#include &lt;istream&gt;\n#include &lt;map&gt;\n#include &lt;string&gt;\n\nstruct delta\n{\n int before;\n int after;\n\n delta&amp; operator+=(const delta&amp; other)\n {\n before += other.before;\n after += other.after;\n return *this;\n }\n};\n\nunsigned int max_inequalities(std::istream&amp; in)\n{\n // ensure stream '&gt;&gt;' succeeds or throws\n in.exceptions(std::ios_base::badbit | std::ios_base::failbit);\n\n unsigned int lines;\n in &gt;&gt; lines;\n\n std::map&lt;double,delta&gt; changes;\n unsigned int count = 0; // count of satisfied inequalities at -∞\n\n static const std::map&lt;std::string, delta&gt; deltas =\n {\n { \"&gt;\", { 0, 1 } },\n { \"&gt;=\", { 1, 0 } },\n { \"=\", { 1, -1 } },\n { \"&lt;=\", { 0, -1 } },\n { \"&lt;\", { -1, 0 } },\n };\n\n for (auto i = 0u; i &lt; lines; ++i) {\n std::string var_name;\n std::string comparison;\n double value;\n\n in &gt;&gt; var_name &gt;&gt; comparison &gt;&gt; value;\n if (var_name != \"X\") {\n throw std::invalid_argument(var_name);\n }\n\n auto entry = deltas.find(comparison);\n if (entry == deltas.end()) {\n throw std::invalid_argument(comparison);\n }\n\n const delta&amp; d = entry-&gt;second;\n changes[value] += d;\n if (d.before + d.after &lt; 0) {\n // it's a less-than relation, so true at -∞\n ++count;\n }\n }\n\n auto max_count = count;\n // now, advance to +∞; updating count as we go\n for (auto&amp; entry: changes) {\n const delta&amp; d = entry.second;\n count += d.before;\n if (count &gt; max_count) { max_count = count; }\n count += d.after;\n if (count &gt; max_count) { max_count = count; }\n }\n\n return max_count;\n}\n</code></pre>\n\n\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n\nint main()\n{\n auto input = std::istringstream{\"4\\n\"\n \"X = 1\\n\"\n \"X = 2\\n\"\n \"X = 3\\n\"\n \"X &gt; 0\\n\"\n };\n\n std::cout &lt;&lt; max_inequalities(input) &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:48:53.933", "Id": "215021", "ParentId": "214976", "Score": "6" } } ]
{ "AcceptedAnswerId": "214993", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T00:29:28.647", "Id": "214976", "Score": "3", "Tags": [ "c++", "performance", "programming-challenge" ], "Title": "Find how many inequalities can be simultaneously satisfied" }
214976
DOT is both a mathematical graph description language and a particular graph rendering engine (dot). As a graph description language, DOT uses a simple plain text mapping syntax to describe the relationships between nodes and edges (e.g. `nodeA -> nodeB`), and a plain text markup syntax to add style, annotations, and constrain the rendered layout.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:18:54.723", "Id": "214986", "Score": "0", "Tags": null, "Title": null }
214986
<p>I am trying to stop an executing runnable instance after the run method has been called.</p> <p>I have come up with the below approach</p> <pre><code> public class StoppableWorkflowTask implements Runnable { volatile Thread runner = null; @Override public void run() { runner = Thread.currentThread(); try { while (true) { System.out.println("Stop Thread " + Thread.currentThread().getId()); } } catch (Exception ex) { ex.printStackTrace(); } } void stop() { runner.stop(); } } public class StoppableWorkflowTaskTest { public static void main(String[] args) { StoppableWorkflowTask stoppableTask = new StoppableWorkflowTask(); Thread thread = new Thread(stoppableTask); thread.start(); System.out.println(thread.currentThread().getId()); try { stoppableTask.stop(); } catch (Exception ex) { ex.printStackTrace(); } } } </code></pre> <p>As per Java documention it is unsafe to call thread.stop(). I have checked few examples , but all either use thread.sleep() which can be terminated on interrupt.</p>
[]
[ { "body": "<p>The recommended way from <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html\" rel=\"nofollow noreferrer\">Oracle</a> is <code>Thread.interrupt()</code>. For example:</p>\n\n<pre><code>public void stop() {\n Thread thread = runner;\n runner = null;\n thread.interrupt();\n}\n\npublic void run() {\n runner = Thread.currentThread();\n while (runner != null) {\n System.out.println(\"Stop Thread \" + Thread.currentThread().getId());\n }\n System.out.println(\" Done \");\n}\n</code></pre>\n\n<p>It is true that <code>sleep()</code> can be interrupted (which will raise an <code>InterruptedException</code>), which is what the <code>interrupt()</code> will do. However, afterwards the <code>Thread</code> can continue doing whatever it wants after being “interrupted”, so you must also check for a stop-condition of some kind. Above, we check <code>runner != null</code>. But as you can see above, you don’t need a <code>sleep()</code> in the worker thread.</p>\n\n<p>If you don’t want to run the <code>Thread</code> in a loop, or you have many different loops where the task may spin, you will have to make the stop check in each of those places.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T06:20:27.800", "Id": "214997", "ParentId": "214988", "Score": "3" } } ]
{ "AcceptedAnswerId": "214997", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:21:17.447", "Id": "214988", "Score": "0", "Tags": [ "java", "multithreading" ], "Title": "Stopping a running thread" }
214988
XQuery is a functional language designed to query and manipulate XML data. It is a superset of XPath, to which it adds features such as the creation of new nodes and more powerful FLWOR expressions. Although it shares its data model with XSLT, XQuery is optimized for querying rather than transforming data, and as such it has a different design inspired by SQL.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:25:30.507", "Id": "214990", "Score": "0", "Tags": null, "Title": null }
214990
Allegro is a game programming library for C and C++ developers distributed freely, supporting the following platforms: Unix (Linux, FreeBSD, etc.), Windows, macOS, iOS, and Android.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T05:26:40.927", "Id": "214992", "Score": "0", "Tags": null, "Title": null }
214992
<p>I am learning Rust. I have build a simple game (Blackjack) to get acquainted. The following code is the code which runs the game logic. The code is part of the larger codebase and works. In the rest of the code base I implemented the Player trait, Card trait, and the main.rs.</p> <p>I am looking for improvements etc. to get better at programming Rust.</p> <pre class="lang-rust prettyprint-override"><code>use crate::cards::*; use crate::player::*; use std::cmp; use std::collections::HashMap; use std::ptr; // BlackJack and Table structures pub struct Table&lt;'a&gt; { pub players: HashMap&lt;usize, &amp;'a Player&gt;, pub cards: HashMap&lt;usize, Deck&gt;, } impl&lt;'a&gt; Table&lt;'a&gt; { pub fn new(seats: usize) -&gt; Table&lt;'a&gt; { Table { players: HashMap::with_capacity(seats), cards: HashMap::with_capacity(seats), } } } pub struct BlackJack&lt;'a&gt; { max_number_of_players: usize, table: Table&lt;'a&gt;, } // Game logic impl&lt;'a&gt; BlackJack&lt;'a&gt; { pub fn new(max_number_of_players: usize) -&gt; BlackJack&lt;'a&gt; { BlackJack { max_number_of_players: cmp::min(7, cmp::max(1, max_number_of_players)), table: Table::new(max_number_of_players), } } pub fn add_player(&amp;mut self, player: &amp;'a Player, seat: usize) -&gt; usize { if self.table.players.contains_key(&amp;seat) { // Seat is taken return 0; } if self.max_number_of_players &lt; seat { // Seat does not exist return 0; } let free_seats = (1..self.max_number_of_players + 1) .filter(|x| !self.table.players.contains_key(&amp;x)) .collect::&lt;Vec&lt;usize&gt;&gt;(); if free_seats.is_empty() { // There are no free seats available (this should not be possible) return 0; } let player_seat = if seat == 0 { // Select the players seat free_seats.first().unwrap() } else { &amp;seat }; self.table.players.insert(player_seat.to_owned(), player); self.table .cards .insert(player_seat.to_owned(), Deck::new_empty()); player_seat.to_owned() } pub fn remove_player(&amp;mut self, player: &amp;'a Player, seat: usize) { if 0 == seat { // No seat provided, remove the player from all seats self.table .players .retain(|_, player_value| ptr::eq(player, *player_value)) } else { // Location provided, remove all items from specific location if self.table.players.contains_key(&amp;seat) { let found_player = self.table.players.get(&amp;seat).unwrap(); if ptr::eq(found_player, &amp;player) { self.table.players.remove(&amp;seat); } } } } pub fn play_game(&amp;mut self, start_bet: f32) { // Check if there are players present if self.table.players.len() &lt; 1 { return; } // Shuffle cards let dealer_deck = Deck::new(3); self._play_game(dealer_deck, start_bet) } fn _play_game(&amp;mut self, mut dealer_deck: Deck, start_bet: f32) { let mut seats = Vec::new(); // Only play with players who have sufficient funds for seat in 1..self.max_number_of_players + 1 { if self.table.players.contains_key(&amp;seat) { // Take the credits if self.table.players.get_mut(&amp;seat).unwrap().credits() &gt;= start_bet { // self.table.players.get_mut(&amp;seat).unwrap().take_credits(&amp;start_bet); seats.push(seat); } } } // Deal first cards (dealer last) let mut dealer = Deck::new_empty(); for seat in &amp;seats { self.table .cards .get_mut(&amp;seat) .unwrap() .push(dealer_deck.pop().unwrap()); } dealer.push(dealer_deck.pop().unwrap()); for seat in &amp;seats { self.table .cards .get_mut(&amp;seat) .unwrap() .push(dealer_deck.pop().unwrap()); } dealer.push(dealer_deck.pop().unwrap()); // Players play for seat in &amp;seats { let mut quit = false; while !quit { if self.table.cards.get(&amp;seat).unwrap().score() &gt;= 21 { quit = true; } else { match self .table .players .get(&amp;seat) .unwrap() .action(seat, &amp;self.table) { PlayerAction::Hit =&gt; { self.table .cards .get_mut(&amp;seat) .unwrap() .push(dealer_deck.pop().unwrap()); } PlayerAction::Stand =&gt; { quit = true; } } } } } // Dealers play while dealer.score() &lt;= 17 { dealer.push(dealer_deck.pop().unwrap()); } // Evaluate all scores and pay bets let dealer_score = dealer.score(); for seat in &amp;seats { let mut win_factor = 0; let player_score = self.table.cards.get(seat).unwrap().score(); println!("{:?}", player_score); if 21 &lt; player_score { // Player busted, no wins // table[seat]['player'].message('Busted! You loose.') win_factor = 0; } else { if 21 &lt; dealer_score { // Dealer busted, player wins self.table .players .get(&amp;seat) .unwrap() .message("Dealer busted. You win!"); win_factor = 2; } else if dealer_score == player_score { // Tie self.table .players .get(&amp;seat) .unwrap() .message("You have the same score as the dealer. No winner."); win_factor = 1; } else if dealer_score &lt; player_score { // Player wins self.table.players.get(&amp;seat).unwrap().message("You win!"); win_factor = 2; } else { // Dealer wins self.table .players .get(&amp;seat) .unwrap() .message("Dealer wins!"); } } // self.table.players.get_mut(&amp;seat).unwrap().give_credits(&amp;(start_bet * win_factor as f32)); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T08:39:02.303", "Id": "415742", "Score": "0", "body": "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." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T09:10:20.457", "Id": "415745", "Score": "0", "body": "That being said, if you leave out the request for adding a feature and stick to the \"generic feedback\" part, the post will be on-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T09:10:32.400", "Id": "415746", "Score": "0", "body": "You are right. Still, I am also looking at possible code improvements. The code which is pasted, works. I am not sure how to edit the question and remove the last part, so please ignore that part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:28:09.580", "Id": "415766", "Score": "0", "body": "You can click on the link in this comment if you want to [edit] your question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T08:34:14.280", "Id": "215001", "Score": "1", "Tags": [ "beginner", "rust", "playing-cards", "immutability" ], "Title": "Rust trait implementations for a Blackjack game" }
215001
<p>I have binary files containing sparse matrices. Their format is:</p> <pre><code>number of rows int length of a row int column index int value float </code></pre> <p>Reading each row with a single struct call instead of looping through each row with single struct calls gave me roughly a 2-fold speedup. I'm parsing 1 GB sized matrices and I would like to speed this proces up even further.</p> <pre><code>from scipy.sparse import coo_matrix import struct def read_sparse_matrix(handle): cols = [] rows = [] weights = [] numrows = struct.unpack('i' , handle.read(4))[0] shape = numrows for rownum in range(numrows): rowlen = struct.unpack('i', handle.read(4))[0] row = list(struct.unpack("if" * rowlen, handle.read(8 * rowlen))) cols += row[::2] weights += row[1::2] rows += [rownum] * rowlen return coo_matrix((weights, (rows, cols)), shape=(shape, shape)) </code></pre> <p>A file contains multiple of these matrices, and other informatinon, so the size of the file is not informative about the structure of the matrix.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:07:26.507", "Id": "416287", "Score": "2", "body": "Can you change the format? If so (and you don't need it to be human readable), you should probably just serialize the data. That should be faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T22:58:11.303", "Id": "416380", "Score": "1", "body": "Have you tried reading (or `mmap`ping) the entire file into a buffer, and using `struct.unpack_from` to decode the data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T18:27:12.920", "Id": "445488", "Score": "2", "body": "Can you link a sample file?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T09:15:58.240", "Id": "215006", "Score": "6", "Tags": [ "python", "performance", "matrix", "serialization", "scipy" ], "Title": "Reading sparse matrix from binary file" }
215006
<p>After learning some basic concepts of ReactJs I tried to create a form. Now I'm not sure if I'm using props the way they are intented so here is sample of my relevant code:</p> <pre><code>&lt;Input type={"text"} placeholder={"Username"} id={"registerUsername"} class={"input"} /&gt; &lt;Input type={"password"} placeholder={"Password"} id={"registerPassword"} class={"input"} /&gt; </code></pre> <p>Input class:</p> <pre><code>export class Input extends React.Component{ render(){ return ( &lt;input type={this.props.type} placeholder={this.props.placeholder} id={this.props.id} className={this.props.class} /&gt; ) } } </code></pre> <p>When passing many props in one component for whatever reason it feels like I'm overusing them, but maybe that's just me?</p>
[]
[ { "body": "<h2>Use Props !</h2>\n\n<p>Using props to highly customize your component is good practice, but too many props isn't always good ! You need to ask yourself:</p>\n\n<ol>\n<li>Am I trying to overly handle every situation possible ?</li>\n<li>Is it ok if a second component handles different cases ?</li>\n<li>Are these props absolutely required for my component to work as intended ?</li>\n</ol>\n\n<p>If 1. and/or 2. is a <strong>yes</strong> and/or 3. is a <strong>no</strong> then you should probably rethink your component logic.</p>\n\n<p><em>For your example, you're <strong>not overly using props</strong>.</em></p>\n\n<h2>Don't assume your props exist !</h2>\n\n<p><code>&lt;input type={this.props.type} .../&gt;</code></p>\n\n<p>Get the props and set default values for them if they are undefined. Use destructuring for this:</p>\n\n<pre><code>render(){\n const {\n type = \"text\", \n placeholder = \"Type something\",\n id = null,\n className = null\n } = this.props;\n\n return (\n &lt;input type={type} placeholder={placeholder} id={id} className={className} /&gt;\n )\n }\n</code></pre>\n\n<h2><a href=\"https://www.npmjs.com/package/prop-types\" rel=\"nofollow noreferrer\">Use PropTypes</a> !</h2>\n\n<blockquote>\n <p>You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.</p>\n</blockquote>\n\n<p>Using many props gets messy and it's easy to forget which props are being used and which props are required for your components.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>export class Input extends React.Component{\n /** code here */\n}\n\nInput.propTypes = {\n id: PropTypes.number.isRequired, //required will throw error if id is not set\n placeholder: PropTypes.string,\n className: PropTypes.string, //optional\n type: PropTypes.string, //optional\n}\n</code></pre>\n\n<h2>When to use classes and when not to use classes</h2>\n\n<p>Keep in mind that all your components don't <em>need</em> to be a class. Only use a class if the object becomes complex.</p>\n\n<p>Keep things simple like so:</p>\n\n<pre><code>export const Input = props =&gt; {\n\n const {\n type = \"text\", \n placeholder = \"Type something\",\n id = null,\n className = null\n } = props;\n\n return (\n &lt;input \n type={type} \n placeholder={placeholder} \n id={id} \n className={className} /&gt;\n )\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T10:07:41.040", "Id": "415756", "Score": "1", "body": "thanks a lot, thats plenty of good tips I will try to implement :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T10:02:01.047", "Id": "215011", "ParentId": "215007", "Score": "4" } } ]
{ "AcceptedAnswerId": "215011", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T09:18:20.063", "Id": "215007", "Score": "1", "Tags": [ "javascript", "react.js" ], "Title": "React - am i overusing props or is it exactly how they are suppoused to be used?" }
215007
<p>I have a business logic layer class for creating and updating work orders, it also retrieves existing work order details from the database and displays it to the user on a form. The business logic layer class uses DTOs defined in a separate Class Library</p> <p>Inspiration for using DTOs was found <a href="http://rlacovara.blogspot.com/2009/02/high-performance-data-access-layer.html" rel="nofollow noreferrer">here</a>, although I am sticking to using DataSets and DataTables (which linked article strongly disagrees with). I have taken replies to my previous code review question in consideration while coding up this form in hopes of reusing the pattern in other parts of my project.</p> <p>Here are the samples from the front end for creating, updating and retrieving.</p> <pre><code> //INSERT/UPDATE WORK ORDER public void btnFinish_Click(object sender, EventArgs e) { try { //hardcoded values for PLANT and SITE to be fetched from user login controller properties. //LoginController.UserLocation + LoginController.UserSite AuxController woc = new AuxController(); if (FormChecker.IsValidForm(Controls.Cast&lt;Control&gt;().ToList())) { //NB NB NB PERCENTAGE SMYS DURATION: //STRING BUILDING: "BAR VALUE FROM txtBAR" + " @ " + "COMBOBOX SELECTED SECONDS" + " seconds" woc.CreateNewWorkOrder(txtSysproOrderNum.Text, txtContractNo.Text, PT_BLL.Controllers.Login.LoginController.UserPlant, txtSysproStockCode.Text, txtCustomerName.Text, Convert.ToInt32(numQty.Value), numMeters.Value, cmbType.SelectedItem.ToString(), cmbSpec.SelectedItem.ToString(), cmbSteelGrade.SelectedItem.ToString(), dtpOrderDate.Value, dtpDueDate.Value, numLength.Value, PT_BLL.Controllers.Login.LoginController.UserSite, numDiameter.Value, numThickness.Value, "N/A", "N/A", "N/A", "N/A", txtBar.Text + " @ " + cmbSeconds.SelectedItem.ToString() + " seconds", PT_BLL.Controllers.Login.LoginController.UserNameLoggedIn, chkHydroTest.Checked, numLengthPlus.Value, numLengthMinus.Value, numShortLengthPerc.Value, numBevMin.Value, numBevMax.Value, numBodDiaMin.Value, numBodDiaMax.Value, numPEDiaMin.Value, numPEDiaMax.Value, chkExport.Checked.ToString(), btnFinish.BackColor != System.Drawing.Color.ForestGreen); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } //RETRIEVE A JOB NUMBER/ENTER NOW JOB NUMBER AFTER USER LEAVES TEXTBOX private void txtSysproOrderNum_Leave(object sender, EventArgs e) { try { AuxController woc = new AuxController(); var existingWorkOrder = woc.GetJobDetails(txtSysproOrderNum.Text); if (!existingWorkOrder.IsNew) { //IF EXISTING DATA, DISPLAY LABEL WITH DATE AND USER WHO CAPTURED EXISTING WOP DATA. //ALSO CHANGE BUTTON COLOUR TO ORANGERED FOR UPDATE CASE //change button colour btnFinish.BackColor = System.Drawing.Color.OrangeRed; lblWOPStatus.Text = "WOP STATUS: CAPTURED ON " + existingWorkOrder.OrderDateCreated + " BY " + existingWorkOrder.Operator; txtSysproStockCode.Text = existingWorkOrder.SysproStockCode; txtCustomerName.Text = existingWorkOrder.Customer; chkExport.Checked = existingWorkOrder.OrderType.Contains("EXPORT"); numQty.Value = existingWorkOrder.Quantity; dtpOrderDate.Value = existingWorkOrder.OrderDate; dtpDueDate.Value = existingWorkOrder.DueDate; txtContractNo.Text = existingWorkOrder.ContractNumber; cmbType.SelectedItem = existingWorkOrder.PipeType; cmbSpec.SelectedItem = existingWorkOrder.SpecificationERW; cmbSteelGrade.SelectedItem = existingWorkOrder.SteelGrade; chkHydroTest.Checked = Convert.ToBoolean(existingWorkOrder.HydroTest); numDiameter.Value = existingWorkOrder.OuterDiameterERW; numThickness.Value = existingWorkOrder.WallThicknessERW; numLength.Value = existingWorkOrder.Length; numMeters.Value = existingWorkOrder.Length * existingWorkOrder.Quantity; numLengthMinus.Value = existingWorkOrder.VarianceLengthMinus; numLengthPlus.Value = existingWorkOrder.VarianceLengthPlus; numShortLengthPerc.Value = existingWorkOrder.ShortLengthVariance; numBevMin.Value = existingWorkOrder.BevelAnglesMin; numBevMax.Value = existingWorkOrder.BevelAnglesMax; numBodDiaMin.Value = existingWorkOrder.BodyDiameterMin; numBodDiaMax.Value = existingWorkOrder.BodyDiameterMax; numPEDiaMin.Value = existingWorkOrder.PipeEndDiameterMin; numPEDiaMax.Value = existingWorkOrder.PipeEndDiameterMax; txtBar.Text = existingWorkOrder.Bar.ToString(); cmbSeconds.SelectedItem = existingWorkOrder.HoldingTime.ToString(); } else { string preserveText = txtSysproOrderNum.Text; //GENERAL CLASS FOR CLEARING WINFORMS. FormChecker.ClearAll(this); txtSysproOrderNum.Text = preserveText; btnFinish.BackColor = System.Drawing.Color.ForestGreen; //LABEL CHANGES WHEN USER ACCESS EXISTING RECORD AND FORM POPULATES WITH EXISTING DATA. //SET LABEL BACK TO ORIGINAL VALUE lblWOPStatus.Text = "WOP Status: NOT CAPTURED "; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } </code></pre> <p>Here is my business layer class structure for above actions taken in the front end/ UI:</p> <pre><code> public void CreateNewWorkOrder(string SysproOrderNumber, string ContractNumber, string Plant, string SysproStockCode, string Customer, int Quantity, decimal Meters, string PipeType, string SpecificationERW, string SteelGrade, DateTime OrderDate, DateTime DueDate, decimal Length, string Site, decimal OuterDiameterERW, decimal WallThicknessERW, string Coating, string Lining, string CutBack, string CutBackType, string PercentageSMYSDuration, string Operator, bool HydroTest, decimal VarianceLengthPlus, decimal VarianceLengthMinus, decimal ShortLengthVariance, decimal BevelAnglesMin, decimal BevelAnglesMax, decimal BodyDiameterMin, decimal BodyDiameterMax, decimal PipeEndDiameterMin, decimal PipeEndDiameterMax, string OrderType, bool UpdateWOP) { dto_WorkOrder wop = new dto_WorkOrder(); try { wop.SysproOrderNumber = SysproOrderNumber; wop.ContractNumber = ContractNumber; wop.Plant = Plant; wop.SysproStockCode = SysproStockCode; wop.Customer = Customer; wop.Quantity = Quantity; wop.Meters = Meters; wop.PipeType = PipeType; wop.SpecificationERW = SpecificationERW; wop.SteelGrade = SteelGrade; wop.OrderDate = OrderDate; wop.DueDate = DueDate; wop.Length = Length; wop.Site = Site; wop.OuterDiameterERW = OuterDiameterERW; wop.WallThicknessERW = WallThicknessERW; wop.Coating = Coating; wop.Lining = Lining; wop.CutBack = CutBack; wop.CutBackType = CutBackType; wop.PercentageSMYSDuration = PercentageSMYSDuration; wop.Operator = Operator; wop.HydroTest = HydroTest; wop.VarianceLengthPlus = VarianceLengthPlus; wop.VarianceLengthMinus = VarianceLengthMinus; wop.ShortLengthVariance = ShortLengthVariance; wop.BevelAnglesMin = BevelAnglesMin; wop.BevelAnglesMax = BevelAnglesMax; wop.BodyDiameterMin = BodyDiameterMin; wop.BodyDiameterMax = BodyDiameterMax; wop.PipeEndDiameterMin = PipeEndDiameterMin; wop.PipeEndDiameterMax = PipeEndDiameterMax; wop.OrderType = Convert.ToBoolean(OrderType) ? "EXPORT" : "LOCAL"; if (UpdateWOP) { bool successUpdate = UpdateWorkOrder(wop); MessageBox.Show(successUpdate ? "SUCCESS: WORKORDER " + wop.SysproOrderNumber + " HAS BEEN UPDATED." : "FAIL: RECORD WAS NOT UPDATED"); } else { bool successInsert = InsertWorkOrder(wop); MessageBox.Show(successInsert ? "SUCCESS: WORKORDER " + wop.SysproOrderNumber + " HAS BEEN INSERTED." : "FAIL: RECORD WAS NOT INSERTED"); } //TO DO: Should implement dialogresult for capturing new record, to conditionally clear screen or review data inserted. } catch (Exception ex) { MessageBox.Show(ex.Message); } } private WorkOrderTableAdapter _wop = null; protected WorkOrderTableAdapter AdapterWop { get { if (_wop == null) _wop = new WorkOrderTableAdapter(); _wop.ConnectionString = Login.LoginController.UserConnString; return _wop; } } public dto_WorkOrder GetJobDetails(string jobnumber) { tblWorkOrderPlanningDataSet.WorkOrderDataTable jobDt; dto_WorkOrder workorder = new dto_WorkOrder(); jobDt = AdapterWop.GetData(jobnumber); if (jobDt.Rows.Count &gt; 0) { //set bool to control/ be aware of existing data in front end. workorder.IsNew = false; workorder.SysproOrderNumber = jobDt[0].Syspro_Order_Number; workorder.ContractNumber = jobDt[0].Contract_Number; workorder.Plant = jobDt[0].Plant; workorder.SysproStockCode = jobDt[0].Syspro_Stock_Code; workorder.CustomerPurchaseOrderNumber = jobDt[0].Customer_Purchase_Order_Number; workorder.CoilNumbers = jobDt[0].Coil_Number.Split(',').ToList&lt;string&gt;(); workorder.Customer = jobDt[0].Customer; workorder.Quantity = jobDt[0].Quantity; workorder.Meters = Convert.ToDecimal(jobDt[0].Meters); workorder.PipeType = jobDt[0].Pipe_Type; workorder.SpecificationERW = jobDt[0].Specification_ERW; workorder.SteelGrade = jobDt[0].Steel_Grade; workorder.OrderDate = Convert.ToDateTime(jobDt[0].Order_Date); workorder.DueDate = Convert.ToDateTime(jobDt[0].Due_Date); workorder.Length = Convert.ToDecimal(jobDt[0].Length); workorder.Site = jobDt[0].Site; workorder.OuterDiameterERW = Convert.ToDecimal(jobDt[0].Outer_Diameter_ERW.ToString()); workorder.WallThicknessERW = Convert.ToDecimal(jobDt[0].Wall_Thickness_ERW.ToString()); workorder.Coating = jobDt[0].Coating; workorder.Lining = jobDt[0].Lining; workorder.CutBack = jobDt[0].Cut_Back; workorder.CutBackType = jobDt[0].Cut_Back_Type; //BREAK UP STRING PERCENTAGESMYSDURATION TO GET HOLDING TIME + BAR/PRESSURE INTO SEPERATE BOXES/DROPDOWNS/CHECKBOXES workorder.PercentageSMYSDuration = jobDt[0].Percentage_SMYS_Duration; try { int ixBar = workorder.PercentageSMYSDuration.IndexOf('@'); int ixSecond = workorder.PercentageSMYSDuration.IndexOf('s'); workorder.Bar = Convert.ToDecimal(workorder.PercentageSMYSDuration.Substring(0, ixBar - 1)); workorder.HoldingTime = Convert.ToDecimal(workorder.PercentageSMYSDuration.Trim().Substring(ixBar + 1, ixSecond - ixBar - 1).Trim()); } catch (Exception ex) { MessageBox.Show("HYDRO PERCENTAGE WAS CAPTURED INCORRECTLY." + " \r\n" + "PLEASE SEE BOX NEXT TO %SMYS DURATION FOR FULL HYDRO PRESSURE/HOLDING TIME" + "\r\n" + "THIS IS EXPECTED TO HAPPEN FOR OLDER JOBS." + "\r\n" + ex.Message); } workorder.Operator = jobDt[0].Operator; workorder.Remaining = Convert.ToDecimal(jobDt[0].Remaining); workorder.HydroTest = Convert.ToBoolean(jobDt[0].HydroTest); workorder.VarianceLengthPlus = Convert.ToDecimal(jobDt[0].Variance_Length_Plus); workorder.VarianceLengthMinus = Convert.ToDecimal(jobDt[0].Variance_Length_Minus); workorder.ShortLengthVariance = Convert.ToDecimal(jobDt[0].ShortLength_Variance); workorder.BevelAnglesMin = Convert.ToDecimal(jobDt[0].Bevel_Angles_Min); workorder.BevelAnglesMax = Convert.ToDecimal(jobDt[0].Bevel_Angles_Max); workorder.BodyDiameterMin = Convert.ToDecimal(jobDt[0].Body_Diameter_Min); workorder.BodyDiameterMax = Convert.ToDecimal(jobDt[0].Body_Diameter_Max); workorder.PipeEndDiameterMin = Convert.ToDecimal(jobDt[0].Pipe_End_Diameter_Min); workorder.PipeEndDiameterMax = Convert.ToDecimal(jobDt[0].Pipe_End_Diameter_Max); workorder.OrderType = jobDt[0].Order_Type; if (String.IsNullOrEmpty(workorder.OrderType)) { workorder.OrderType = "UNKNOWN"; } else { if (workorder.OrderType.Contains("LOCAL")) { workorder.OrderType = jobDt[0].Order_Type; } else { if (workorder.OrderType.Contains("EXPORT")) { workorder.OrderType = jobDt[0].Order_Type; } //probably an unneccessary else, user selects checkboxes so shouldn't end up here at all. //cater for old data which may have bad characteristics l0cal exp0rt or incorrect spelling. else { workorder.OrderType = "UNKNOWN"; } } } } else { workorder.IsNew = true; } return workorder; } public bool InsertWorkOrder(dto_WorkOrder wop) { bool successInsert = true; try { AdapterWop.Insert(wop.SysproOrderNumber, wop.ContractNumber, wop.Plant, wop.SysproStockCode, wop.Customer, wop.Quantity, wop.Meters, wop.PipeType, wop.SpecificationERW, wop.SteelGrade, wop.OrderDate, wop.DueDate, wop.Length, wop.Site, wop.OuterDiameterERW, wop.WallThicknessERW, wop.Coating, wop.Lining, wop.CutBack, wop.CutBackType, wop.PercentageSMYSDuration, wop.Operator, wop.HydroTest, wop.VarianceLengthPlus, wop.VarianceLengthMinus, wop.ShortLengthVariance, wop.BevelAnglesMin, wop.BevelAnglesMax, wop.BodyDiameterMin, wop.BodyDiameterMax, wop.PipeEndDiameterMin, wop.PipeEndDiameterMax, wop.OrderType); successInsert = true; return successInsert; } catch (SqlException ex) { MessageBox.Show(ex.Message + "\r\n PLEASE CONTACT BRENDAN."); successInsert = false; return successInsert; } } private bool UpdateWorkOrder(dto_WorkOrder wop) { bool successUpdate = true; try { AdapterWop.Update(wop.SysproStockCode, wop.Customer, wop.Quantity, wop.Meters, wop.PipeType, wop.SpecificationERW, wop.SteelGrade, wop.OrderDate, wop.DueDate, wop.Length, wop.OuterDiameterERW, wop.WallThicknessERW, wop.PercentageSMYSDuration, wop.Operator, wop.HydroTest, wop.VarianceLengthPlus, wop.VarianceLengthMinus, wop.ShortLengthVariance, wop.BevelAnglesMin, wop.BevelAnglesMax, wop.BodyDiameterMin, wop.BodyDiameterMax, wop.PipeEndDiameterMin, wop.PipeEndDiameterMax, wop.OrderType, wop.SysproOrderNumber, wop.ContractNumber); return successUpdate; } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n PLEASE CONTACT BRENDAN."); successUpdate = false; return successUpdate; } } </code></pre> <p>My WorkOrder_DTO class:</p> <pre><code> public class dto_WorkOrder : dto_Base { public string SysproOrderNumber { get; set; } public string ContractNumber { get; set; } public string Plant { get; set; } public string SysproStockCode { get; set; } public string CustomerPurchaseOrderNumber { get; set; } public List&lt;string&gt; CoilNumbers { get; set; } public string Customer { get; set; } public int Quantity { get; set; } public decimal Meters { get; set; } public string PipeType { get; set; } public string SpecificationERW { get; set; } public string SteelGrade { get; set; } public DateTime OrderDate { get; set; } public DateTime DueDate { get; set; } public decimal Length { get; set; } public string Site { get; set; } public decimal OuterDiameterERW { get; set; } public decimal WallThicknessERW { get; set; } public string Coating { get; set; } public string Lining { get; set; } public string CutBack { get; set; } public string CutBackType { get; set; } public string PercentageSMYSDuration { get; set; } public decimal Bar { get; set; } public decimal HoldingTime { get; set; } public string Operator { get; set; } public decimal Remaining { get; set; } public bool? HydroTest { get; set; } public decimal VarianceLengthPlus { get; set; } public decimal VarianceLengthMinus { get; set; } public decimal ShortLengthVariance { get; set; } public decimal BevelAnglesMin { get; set; } public decimal BevelAnglesMax { get; set; } public decimal BodyDiameterMin { get; set; } public decimal BodyDiameterMax { get; set; } public decimal PipeEndDiameterMin { get; set; } public decimal PipeEndDiameterMax { get; set; } public string OrderType { get; set; } public DateTime OrderDateCreated { get; set; } public dto_WorkOrder() { SysproOrderNumber = String_NullValue; ContractNumber = String_NullValue; Plant = String_NullValue; SysproStockCode = String_NullValue; CustomerPurchaseOrderNumber = String_NullValue; CoilNumbers = List_NullValue; Customer = String_NullValue; Quantity = Int_NullValue; Meters = Decimal_NullValue; PipeType = String_NullValue; SpecificationERW = String_NullValue; SteelGrade = String_NullValue; OrderDate = DateTime_NullValue; DueDate = DateTime_NullValue; Length = Decimal_NullValue; Site = String_NullValue; OuterDiameterERW = Decimal_NullValue; WallThicknessERW = Decimal_NullValue; Coating = String_NullValue; Lining = String_NullValue; CutBack = String_NullValue; CutBackType = String_NullValue; PercentageSMYSDuration = String_NullValue; Operator = String_NullValue; Remaining = Decimal_NullValue; HydroTest = Bool_NullValue; VarianceLengthPlus = Decimal_NullValue; VarianceLengthMinus = Decimal_NullValue; ShortLengthVariance = Decimal_NullValue; BevelAnglesMin = Decimal_NullValue; BevelAnglesMax = Decimal_NullValue; BodyDiameterMin = Decimal_NullValue; BodyDiameterMax = Decimal_NullValue; PipeEndDiameterMin = Decimal_NullValue; PipeEndDiameterMax = Decimal_NullValue; OrderType = String_NullValue; Bar = Decimal_NullValue; HoldingTime = Decimal_NullValue; OrderDateCreated = DateTime_NullValue; } } </code></pre> <p>I appreciate the feedback and as far as I can tell, this seems like a good way of going about wiring up the rest of the application to ensure single responsibility and achieve 3 tier architecture. </p> <p>TLDR: The DAL (DataSets) runs queries and returns DataTables to the BLL (Business Logic Layer). The BLL accepts basic arguments from the front end in its methods to get/insert/update data using constructed DTOs from the resulting DataTables. Good Practice?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T09:30:12.847", "Id": "415750", "Score": "0", "body": "Edits: Forgot to add method CreateNewWorkOrder in BLL code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T13:51:48.377", "Id": "415779", "Score": "1", "body": "What's with all the `_NullValue`s? What is this?" } ]
[ { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Quite frankly, I see no point for <code>CreateNewWorkOrder</code> and its 30-something parameters (a maintenance nightmare). Simply create the <code>dto_WorkOrder</code> where you call <code>CreateNewWorkOrder</code> and then pass that dto on to a method that performs an insert or an update.</p></li>\n<li><p>You also can't claim that something is part of the business layer when that method has calls to <code>MessageBox.Show</code> inside it. Let that method (for instance) return a custom class featuring a boolean (to indicate success or failure) and an optional error message.</p></li>\n<li><p>Move away from DataTables etc. Instead use an ORM like <a href=\"https://github.com/StackExchange/Dapper\" rel=\"nofollow noreferrer\">Dapper</a>.</p></li>\n<li><p>Class names and property names etc. should not contain underscores. Please <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">follow Microsoft's guidelines</a>.</p></li>\n<li><p>What are <code>String_NullValue</code> and <code>List_NullValue</code> and <code>Int_NullValue</code> etc.? Please do not pollute your constructors with needlessly complex default values.</p></li>\n<li><p>Much of this code feels \"ancient\". You're not even using <code>String.Format</code>, and that is already usually replaced by <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\"><code>$</code> - string interpolation</a>.</p></li>\n<li><p>Take a look at the <a href=\"https://markheath.net/post/model-view-presenter-winforms\" rel=\"nofollow noreferrer\">Model View Presenter Pattern</a> to write cleaner WinForms code.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T12:44:29.823", "Id": "215028", "ParentId": "215009", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T09:24:49.463", "Id": "215009", "Score": "0", "Tags": [ "c#", "winforms", "dto" ], "Title": "Business Layer Using DTOs and DataTables" }
215009
<p>Below is my Python 3.7 code for a Tic-Tac-Toe game I made as a programming challenge. I want to know if I could make this code less janky, more readable or improve it in any way.</p> <pre><code># Defining Main Game Functions, variables, etc. board = [0,1,2, 3,4,5, 6,7,8] win_con = [[0,1,2],[3,4,5],[6,7,8], [0,3,6],[1,4,7],[2,5,8], [0,4,8],[2,4,6]] # possible 3-in-a-rows def show(): print(board[0],'|',board[1],'|',board[2]) print('----------') print(board[3],'|',board[4],'|',board[5]) print('----------') print(board[6],'|',board[7],'|',board[8]) def x_move(i): if board[i] == 'X' or board[i] == 'O': return print('Already taken!') else: del board[i] board.insert(i,'X') def o_move(i): if board[i] == 'X' or board[i] == 'O': return print('Already taken!') else: del board[i] board.insert(i,'O') # Main Game Loop while True: turn_num = 1 board = [0,1,2,3,4,5,6,7,8] print('Welcome to Tic-Tac-Toe!') print('AI not implemented yet.') while True: for list in win_con: # check if someone's won xnum = 0 onum = 0 for num in list: if board[num] == 'X': xnum += 1 elif board[num] == 'O': onum += 1 else: pass if xnum == 3 or onum == 3: break if xnum == 3 or onum == 3: # break out of all loops break if turn_num &gt; 9: # check if board is full break show() if turn_num % 2 == 1: print('X\'s turn.') else: print('O\'s turn.') move = int(input('Choose a space. ')) if turn_num % 2 == 1: x_move(move) else: o_move(move) turn_num += 1 if xnum == 3: # After game is over print('X Won!') elif onum == 3: print('O Won!') else: print('Draw!') play_again = input('Play again? Y or N ') if play_again == 'Y' or play_again == 'y': continue else: break </code></pre>
[]
[ { "body": "<p>You probably forgot to test for this, but there's a bug in your program.</p>\n\n<pre><code>def x_move(i):\n if board[i] == 'X' or board[i] == 'O':\n return print('Already taken!')\n else:\n del board[i]\n board.insert(i,'X')\ndef o_move(i):\n if board[i] == 'X' or board[i] == 'O':\n return print('Already taken!')\n else:\n del board[i]\n board.insert(i,'O')\n</code></pre>\n\n<p>For starters, you should move this into a single function which takes the player as argument. This way a single function can be used for both players and this will save you from having to fix the bug twice. Code duplication is bad.</p>\n\n<p>An obvious, not necessarily pretty, solution:</p>\n\n<pre><code>def any_move(i, player_character):\n if not isinstance(board[i], int):\n return print('Already taken!')\n else:\n del board[i]\n board.insert(i, player_character)\n</code></pre>\n\n<p>This checks whether the value picked on the board is an integer. If it's not, it has already been taken by either X, O or whatever player characters you're using at that moment.</p>\n\n<p>But the real problem is this will skip a turn on invalid input. If I pick 4 with X in one turn and pick the same tile with O a turn later, O will be missing out a turn. I imagine there should be a loop in there checking whether valid input has been inserted yet. If not, stay in the loop. If valid input is inserted, make the actual move.</p>\n\n<p>I'm talking about valid input here, not just whether the input is 0 - 8. Your program will crash if I enter something invalid, like <code>b</code> or <code>11</code>. The first is not an integer and the second is out of range. It crashes on no input (just hit enter) as well. You should at least capture those exceptions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:50:55.923", "Id": "215022", "ParentId": "215020", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T11:25:49.947", "Id": "215020", "Score": "3", "Tags": [ "python", "python-3.x", "tic-tac-toe" ], "Title": "2-player Tic-Tac-Toe game" }
215020
<p>I am wondering if it's possible to avoid looping. I want to make the function faster. The function is to find how many times a particular value is lower in the overall data. For example:</p> <pre><code>Value &lt;- c(0,10,5,1,0,0,11,0,0,7,3,2,5) # length =13 </code></pre> <p>The 1st value is 0 and 0 is NOT lower in any of the values. Therefore the value I would like to return from the function would be 0.</p> <p>Something like this:</p> <pre><code>sum(Values &lt; 0) 0 </code></pre> <p>The 2nd value is 10:</p> <pre><code>sum(Values &lt; 10) 11 </code></pre> <p>I make a function something like below:</p> <pre><code>fun_num &lt;- function(Value){ gg &lt;- vector() for (i in seq_along(Value)){ x &lt;- Value[i] y &lt;- sum(Value &lt; x) gg[i] &lt;- y } return(gg) } </code></pre> <p>Applying the function:</p> <pre><code>fun_num(Value) [1] 0 11 8 5 0 0 12 0 0 10 7 6 8 </code></pre> <p>Just wondering, is there a way to speed this function up using <code>sapply</code> and avoid using for loop?</p>
[]
[ { "body": "<p>This should suffice </p>\n\n<pre><code>fun_2 &lt;- function(x) sapply(x, function(y) sum(x &lt; y))\nfun_2(Value)\n# [1] 0 11 8 5 0 0 12 0 0 10 7 6 8\n</code></pre>\n\n<p>P.S. <code>sapply</code>/<code>lapply</code> are the same loops, just masked and a little bit faster.</p>\n\n<p>Or if your data is very large we can do it a lot faster using <code>data.table</code>, aggregating the data and counting:</p>\n\n<pre><code>require(data.table)\nfun_3 &lt;- function(Value) {\n d &lt;- data.table(x = Value) # creates 1 column data.table\n # setkey(d, x) # not needed here keyby sets the key\n d &lt;- d[, .N, keyby = x] # calculate count of each unique x value\n # and sorts the results\n d[, a := c(0, cumsum(N)[-.N])] # calculate lagged cumsum from N (counts)\n # a represents element count that is smaller than x\n d[.(Value), a] # using datatable-keys-fast-subset get a(result) for each Value\n}\n\nset.seed(42)\nValue2 &lt;- sample.int(1e5)\n\nsystem.time(r2 &lt;- fun_2(Value2)) # 36.64 \nsystem.time(r3 &lt;- fun_3(Value2)) # 0.03 \nall.equal(r2, r3)\n# [1] TRUE\n</code></pre>\n\n<p>OR with base R:</p>\n\n<pre><code>fun_4 &lt;- function(x) {\n xorder &lt;- order(x)\n xsorted &lt;- x[xorder]\n xsdifs &lt;- c(0, diff(xsorted))\n m &lt;- seq_along(xsdifs) - 1L\n m[xsdifs == 0L] &lt;- 0L\n m &lt;- cummax(m)\n m[order(xorder)]\n}\n</code></pre>\n\n<p>For reverse (<code>Value &gt; x</code>):</p>\n\n<pre><code>fun_2r &lt;- function(x) sapply(x, function(y) sum(x &gt; y))\nfun_3r &lt;- function(Value) {\n d &lt;- data.table(x = Value)\n d &lt;- d[, .N, keyby = x]\n setorder(d, -x)\n d[, a := c(0, cumsum(N)[-.N])]\n setkey(d, x) # need to reset key for sub setting,\n # because reordering d removes it\n d[.(Value), a]\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:06:00.560", "Id": "415783", "Score": "0", "body": "Thanks you very much minem. I am trying to understand fun_3 better, but hopefully I will get it. Specifically if I wanted to do the reverse, ie sum(x > y) rather than sum(x < y). Its easy to edit fun_2, but if you could help explain fun_3 better it would be wonderful.\n\nAnd could you point out some resource to learn more advance resource about programming in R. I'd like to improve my current 'programming' in R. \n\nThanks in advance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:27:54.423", "Id": "415788", "Score": "0", "body": "@Zak I like: https://github.com/Rdatatable/data.table/wiki/Getting-started" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:43:41.713", "Id": "415795", "Score": "0", "body": "@Zak added some comments. I advise that you run the code line by line and inspect the results, to get better feeling of whats happening." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T16:15:03.507", "Id": "415815", "Score": "1", "body": "`findInterval(Value, sort(Value) + 0.1)`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T12:15:50.830", "Id": "215027", "ParentId": "215024", "Score": "2" } }, { "body": "<p>Consider also <code>colSums</code> wrapping <code>outer</code> where you compare the vector with itself:</p>\n\n<pre><code>less_than &lt;- function (vec)\n colSums(outer(vec, vec, function (x, y) x &lt; y))\n\nless_than(Value)\n# [1] 0 11 8 5 0 0 12 0 0 10 7 6 8\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T22:44:29.210", "Id": "215382", "ParentId": "215024", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T12:08:49.313", "Id": "215024", "Score": "3", "Tags": [ "r" ], "Title": "Finding values below a threshold" }
215024
<p>For an assignment to study up on an incoming exam, I have to make these little functions. These are review style functions that make sure we know the algorithms and code necessary to do well on the test. I'm looking for anything I can improve upon in my code, so I can get the best grade possible.</p> <blockquote> <ol> <li>Write a method called evens that will receive a 2-D array of integers and return the sum of all the even integers in the array.</li> </ol> </blockquote> <pre><code>public int evens(int[][] arr) { int sum = 0; for(int[] row : arr) { for(int item : row) { if(item % 2 == 0) { sum += item; } } } return sum; } </code></pre> <blockquote> <ol start="2"> <li>Write a method called check that will receive a 2-D array of String and a single letter (character). The method will return true if any of the strings start with the letter that is passed in (ignoring cases)</li> </ol> </blockquote> <pre><code>public boolean check(String[][] arr, char c) { for(String[] row : arr) { for(String item : row) { if(item.charAt(0) == c) { return true; } } } return false; } </code></pre> <blockquote> <ol start="3"> <li>Write a method called getColumn which receives a 2-D array of doubles, and an integer parameter n. The method returns a one-dimensional array which contains the elements in the nth column of the 2-D array.</li> </ol> </blockquote> <pre><code>public double[] getColumn(double[][] arr, int col) { // row by column double[] newarr = new double[arr.length]; for(int i = 0; i &lt; arr.length; i++) { newarr[i] = arr[i][col]; } return newarr; } </code></pre> <blockquote> <ol start="4"> <li>Write a method called populate that takes two parameters, m and n. The method creates and returns an m x n matrix filled with the counting numbers in row-major order starting with one.</li> </ol> </blockquote> <pre><code>public int[][] populate(int m, int n) { int[][] arr = new int[m][n]; int count = 1; for(int i = 0; i &lt; arr.length; i++) { for(int j = 0; j &lt; arr[i].length; j++) { arr[i][j] = count; count++; } } return arr; } </code></pre> <p><strong>My tester class (test.java)</strong></p> <pre><code>import java.util.Arrays; public class test { public static void main(String[] args) { test t = new test(); int[][] array = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10} }; String[][] array2 = { {"abc", "def", "ghi"}, {"jkl", "lmn", "opq"}, {"rst", "uvw", "xyz"} }; double[][] array3 = { {1.1, 1.2, 1.3, 1.4, 1.5}, {1.6, 1.7, 1.8, 1.9, 2.0}, {2.1, 2.2, 2.3, 2.4, 2.5}, {2.6, 2.7, 2.8, 2.9, 3.0} }; System.out.println("30 =&gt; " + t.evens(array)); System.out.println(); System.out.println("true =&gt; " + t.check(array2, 'd')); System.out.println(); System.out.println("[1.1, 1.6, 2.1, 2.6] =&gt; " + Arrays.toString(t.getColumn(array3, 0))); System.out.println(); System.out.println(Arrays.deepToString(t.populate(2, 5))); } } </code></pre>
[]
[ { "body": "<p>Your code looks well done. Just a couple of tweaks to make it better:</p>\n\n<ol>\n<li><p>Your <code>check()</code> method could fail if passed an empty string, <code>\"\"</code>, since <code>.charAt(0)</code> will raise an <code>IndexOutOfBoundsException</code>. Using the following to protect against the exception: </p>\n\n<pre><code>if ( ! item.isEmpty() &amp;&amp; item.charAt(0) == c ) {\n</code></pre></li>\n<li><p>In <code>populate()</code>, you loop up to <code>arr.length</code> and <code>arr[i].length</code>. But you have just created that array of known dimensions <code>m</code> and <code>n</code>, so it would be clearer, simpler and slightly faster to use those variables for the loop limits. </p></li>\n<li><p>Your variable names could be better: perhaps <code>array</code> instead of <code>arr</code>, and <code>column</code> instead of <code>newarr</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T04:30:06.523", "Id": "215395", "ParentId": "215034", "Score": "1" } } ]
{ "AcceptedAnswerId": "215395", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:00:36.093", "Id": "215034", "Score": "2", "Tags": [ "java", "homework" ], "Title": "Java homework exercises working with 2D arrays" }
215034
<p>I made a simple and non recursive Android Java Sudoku solver implementing Algorithm X with links inspired from dancing links. The code is <a href="https://github.com/pc1211/SUDOKU_A/tree/3db4ac8450b76d3271c71becd6e2e85cef3b984a" rel="nofollow noreferrer">on Github</a> (start with the Solver class and the SatsNodesHandler class).</p> <p>The "dancing links" implementation seemed to me too tricky as it implies a lot of unlink and relink operations between nodes to cover or uncover the same rows and columns in the way.</p> <p>That's why I implemented links, but with these properties:</p> <ul> <li>Only right and down links in the nodes (connecting the "1" in the 729x324 matrix)</li> <li>Row and column headers featuring a “cover ID” equal to the depth level reached when covered (0 if uncovered)</li> <li>A stack of candidate nodes fed by the non recursive solver algorithm</li> </ul> <p><strong>Here is the Solver class:</strong></p> <pre><code>package com.example.pgyl.sudoku_a; public class Solver { public interface onSolveEndListener { void onSolveEnd(); } public void setOnSolveEndListener(onSolveEndListener listener) { mOnSolveEndListener = listener; } private onSolveEndListener mOnSolveEndListener; //region Constantes public enum SOLVE_STATES { UNKNOWN, SOLUTION_FOUND, IMPOSSIBLE } //endregion //region Variables private SatsNodesHandler satsNodesHandler; private SOLVE_STATES solveState; private SatsNode candidate; //endregion public Solver(SatsNodesHandler satsNodesHandler) { this.satsNodesHandler = satsNodesHandler; init(); } private void init() { solveState = SOLVE_STATES.UNKNOWN; } public void close() { satsNodesHandler = null; } public void reset() { satsNodesHandler.reset(); candidate = null; resetSolveState(); } public void resetSolveState() { solveState = SOLVE_STATES.UNKNOWN; } public SOLVE_STATES getSolveState() { return solveState; } public void solve() { if (solveState.equals(SOLVE_STATES.IMPOSSIBLE)) { reset(); } else { if (solveState.equals(SOLVE_STATES.SOLUTION_FOUND)) { // Pour continuer satsNodesHandler.discardLastSolution(); satsNodesHandler.uncoverRowsAndCols(); candidate = satsNodesHandler.getNextCandidate(); if (candidate != null) { solveState = SOLVE_STATES.UNKNOWN; } else { solveState = SOLVE_STATES.IMPOSSIBLE; } } while (solveState.equals(SOLVE_STATES.UNKNOWN)) { SatsNode colHeader = satsNodesHandler.chooseColumn(); if (colHeader != null) { if (colHeader.rowCount &gt; 0) { if (candidate != null) { satsNodesHandler.appendSolution(candidate); } satsNodesHandler.setNextCandidates(colHeader); } else { satsNodesHandler.uncoverRowsAndCols(); } candidate = satsNodesHandler.getNextCandidate(); if (candidate == null) { solveState = SOLVE_STATES.IMPOSSIBLE; } } else { satsNodesHandler.appendSolution(candidate); satsNodesHandler.solutionsToCells(); solveState = SOLVE_STATES.SOLUTION_FOUND; } } } if (mOnSolveEndListener != null) { mOnSolveEndListener.onSolveEnd(); } } } </code></pre> <p><strong>Here is the SatsNodesHandler class:</strong></p> <pre><code>package com.example.pgyl.sudoku_a; import java.util.ArrayList; import java.util.Arrays; public class SatsNodesHandler { //region Variables private ArrayList&lt;SatsNode&gt; nodes; private ArrayList&lt;SatsNode&gt; candidateStack; private ArrayList&lt;Integer&gt; solutionStack; private SatsNode rootHeader; private CellsHandler cellsHandler; private boolean[][] sats; private Cell[] cells; private int gridSize; private int gridRows; private int squareRows; private int level; //endregion public SatsNodesHandler(CellsHandler cellsHandler) { this.cellsHandler = cellsHandler; init(); } private void init() { cells = cellsHandler.getCells(); gridSize = cellsHandler.getGridSize(); gridRows = cellsHandler.getGridRows(); squareRows = cellsHandler.getSquareRows(); candidateStack = new ArrayList&lt;SatsNode&gt;(); solutionStack = new ArrayList&lt;Integer&gt;(); nodes = new ArrayList&lt;SatsNode&gt;(); } public void close() { candidateStack.clear(); candidateStack = null; solutionStack.clear(); solutionStack = null; nodes.clear(); nodes = null; cells = null; } public void reset() { cellsHandler.deleteAllUnprotectedCells(); nodes.clear(); candidateStack.clear(); solutionStack.clear(); createSatsMatrix(); mergeCellsIntoSatsMatrix(); satsMatrixToSatsNodes(); level = 0; } public void setNextCandidates(SatsNode colHeader) { level = level + 1; SatsNode nc = colHeader.down; while (!nc.equals(colHeader)) { if (nc.rowHeader.coverId == 0) { // Ligne non couverte nc.level = level; // On inscrit le niveau actuel dans le noeud simple pushCandidate(nc); } nc = nc.down; } } public SatsNode getNextCandidate() { SatsNode ret = popCandidate(); if (ret != null) { if (ret.level &lt; level) { // Le noeud simple date d'un niveau antérieur level = ret.level; discardLastSolution(); // Enlever la dernière solution car on doit revenir à un niveau antérieur uncoverRowsAndCols(); // Restaurer parfois plusieurs niveaux en une fois si (level - ret.level) &gt; 1 } coverRowsAndCols(ret); } return ret; } public SatsNode chooseColumn() { SatsNode ret = null; int min = Integer.MAX_VALUE; SatsNode ch = rootHeader.right; while (!ch.equals(rootHeader)) { if (ch.coverId == 0) { // Colonne non couverte int rc = rowCount(ch); if (rc &lt; min) { // Chercher la colonne avec le minimum de 1 (parmi ses lignes non couvertes) min = rc; ret = ch; if (min == 0) { // Plus bas impossible break; } } } ch = ch.right; } if (ret != null) { ret.rowCount = min; } return ret; } public void appendSolution(SatsNode satsNode) { solutionStack.add(satsNode.rowHeader.satsRow); } public void discardLastSolution() { int size = solutionStack.size(); if (size &gt; 0) { solutionStack.remove(size - 1); } } public void solutionsToCells() { int size = solutionStack.size(); if (size &gt; 0) { for (int i = 0; i &lt;= (size - 1); i = i + 1) { int satsRow = solutionStack.get(i); int row = (satsRow / gridSize); int col = (satsRow % gridSize) / gridRows; int cellIndex = gridRows * row + col; cells[cellIndex].value = (satsRow % gridRows) + 1; } } } public void uncoverRowsAndCols() { // Découvrir les lignes et colonnes nécessaires pour revenir à un niveau antérieur SatsNode rh = rootHeader.down; while (!rh.equals(rootHeader)) { if (rh.coverId &gt;= level) { rh.coverId = 0; // Découvrir la ligne } rh = rh.down; } SatsNode ch = rootHeader.right; while (!ch.equals(rootHeader)) { if (ch.coverId &gt;= level) { ch.coverId = 0; // Découvrir la colonne } ch = ch.right; } } private void coverRowsAndCols(SatsNode satsNode) { // Couvrir les lignes et colonnes liées au noeud SatsNode rh = satsNode.rowHeader; SatsNode nr = rh.right; while (!nr.equals(rh)) { SatsNode ch = nr.colHeader; if (ch.coverId == 0) { // Colonne non couverte ch.coverId = level; // Couvrir la colonne (en utilisant le niveau actuel comme Id) SatsNode nc = ch.down; while (!nc.equals(ch)) { SatsNode rhc = nc.rowHeader; if (rhc.coverId == 0) { // Ligne non couverte rhc.coverId = level; // Couvrir la ligne (en utilisant le niveau actuel comme Id) } nc = nc.down; } } nr = nr.right; } } private int rowCount(SatsNode colHeader) { // Compter le nombre de 1 d'une colonne (parmi ses lignes non couvertes) int ret = 0; SatsNode nc = colHeader.down; while (!nc.equals(colHeader)) { if (nc.rowHeader.coverId == 0) { // Ligne non couverte ret = ret + 1; } nc = nc.down; } return ret; } private void pushCandidate(SatsNode SatsNode) { candidateStack.add(SatsNode); } private SatsNode popCandidate() { SatsNode ret = null; int size = candidateStack.size(); if (size &gt; 0) { ret = candidateStack.get(size - 1); candidateStack.remove(size - 1); } return ret; } private void satsMatrixToSatsNodes() { int candidates = sats.length; int constraints = sats[0].length; SatsNode[] colHeaders = new SatsNode[constraints]; SatsNode[] lastRowNodes = new SatsNode[constraints]; SatsNode lastColNode = new SatsNode(); rootHeader = new SatsNode(); nodes.add(rootHeader); rootHeader.right = rootHeader; // Pas encore d'entêtes de colonne =&gt; L'entête des entêtes pointe vers elle-même rootHeader.down = rootHeader; // Pas encore d'entêtes de ligne =&gt; L'entête des entêtes pointe vers elle-même SatsNode lastRowHeader = rootHeader; SatsNode lastColHeader = rootHeader; for (int i = 0; i &lt;= (candidates - 1); i = i + 1) { SatsNode rowHeader = null; for (int j = 0; j &lt;= (constraints - 1); j = j + 1) { if (sats[i][j]) { SatsNode node = new SatsNode(); nodes.add(node); // Création noeud simple if (rowHeader == null) { rowHeader = new SatsNode(); // Le noeud simple est le 1er de sa ligne =&gt; Création Entête de ligne nodes.add(rowHeader); rowHeader.right = node; // L'entête de ligne pointe vers le 1er noeud simple de sa ligne rowHeader.satsRow = i; if (rootHeader.down.equals(rootHeader)) { rootHeader.down = rowHeader; // L'entête des entêtes pointe vers la 1e entête de ligne } } else { lastColNode.right = node; // Le noeud simple précédent (de la même ligne) pointe vers celui-ci } if (colHeaders[j] == null) { colHeaders[j] = new SatsNode(); // Le noeud simple est le 1er de sa colonne =&gt; Création Entête de colonne nodes.add(colHeaders[j]); colHeaders[j].down = node; // L'entête de colonne pointe vers le 1er noeud simple de sa colonne if (rootHeader.right.equals(rootHeader)) { rootHeader.right = colHeaders[j]; // L'entête des entêtes pointe vers la 1e entête de colonne } lastRowNodes[j] = new SatsNode(); } else { lastRowNodes[j].down = node; // Le noeud simple précédent (de la même colonne) pointe vers celui-ci } node.rowHeader = rowHeader; node.colHeader = colHeaders[j]; lastColNode = node; // Le dernier noeud simple (de la même ligne) est celui-ci lastRowNodes[j] = node; // Le dernier noeud simple (de la même colonne) est celui-ci } } if (rowHeader != null) { lastColNode.right = rowHeader; // Le dernier noeud simple de la ligne pointe vers l'entête de ligne lastRowHeader.down = rowHeader; // La précédente entête de ligne pointe vers celle-ci lastRowHeader = rowHeader; // La dernière entête de ligne est celle-ci } } for (int j = 0; j &lt;= (constraints - 1); j = j + 1) { if (colHeaders[j] != null) { lastRowNodes[j].down = colHeaders[j]; // Le dernier noeud simple de la colonne pointe vers l'entête de colonne lastColHeader.right = colHeaders[j]; // La précédente entête de colonne pointe vers celle-ci lastColHeader = colHeaders[j]; // La dernière entête de colonne est celle-ci } } if (lastRowHeader != rootHeader) { lastRowHeader.down = rootHeader; // La dernière entête de ligne pointe vers l'entête des entêtes } if (lastColHeader != rootHeader) { lastColHeader.right = rootHeader; // La dernière entête de colonne pointe vers l'entête des entêtes } lastColNode = null; colHeaders = null; lastRowNodes = null; sats = null; } private void mergeCellsIntoSatsMatrix() { for (int i = 0; i &lt;= (gridSize - 1); i = i + 1) { if (!cells[i].isEmpty()) { int r = cellsRowColValueToSatsRow((i / gridRows), (i % gridRows), 0); // 0 = 1e ligne (pour le chiffre 1) for (int k = 0; k &lt;= (gridRows - 1); k = k + 1) { if (k != (cells[i].value - 1)) { Arrays.fill(sats[r + k], false); // Ne garder que les contraintes concernant le chiffre cells[i] } } } } } private void createSatsMatrix() { final int CONSTRAINT_TYPES = 4; // (RiCj#, Ri#, Ci#, Bi#) int candidates = gridSize * gridRows; // 729 candidats (R1C1#1 -&gt; R9C9#9) int constraints = CONSTRAINT_TYPES * gridSize; // 81 contraintes x 4 types de contrainte sats = new boolean[candidates][constraints]; int satsCol = 0; for (int i = 0; i &lt;= (gridRows - 1); i = i + 1) { for (int j = 0; j &lt;= (gridRows - 1); j = j + 1) { for (int k = 0; k &lt;= (gridRows - 1); k = k + 1) { sats[cellsRowColValueToSatsRow(i, j, k)][satsCol + 0 * gridSize] = true; // RiCj# valeur unique dans la cellule sats[cellsRowColValueToSatsRow(i, k, j)][satsCol + 1 * gridSize] = true; // Ri# valeur unique dans la ligne sats[cellsRowColValueToSatsRow(k, i, j)][satsCol + 2 * gridSize] = true; // Ci# valeur unique dans la colonne int p = squareRows * (i / squareRows) + (k / squareRows); // i = n° de carré dans la grille int q = squareRows * (i % squareRows) + (k % squareRows); // k = n° de cellule dans le carré sats[cellsRowColValueToSatsRow(p, q, j)][satsCol + 3 * gridSize] = true; // Bi# valeur unique dans le carré } satsCol = satsCol + 1; } } } private int cellsRowColValueToSatsRow(int cellsRow, int cellsCol, int cellValueIndex) { // cellValueIndex cad cell.value - 1 return (gridSize * cellsRow + gridRows * cellsCol + cellValueIndex); } } </code></pre> <p><strong>Here is the SatsNode class:</strong></p> <pre><code>package com.example.pgyl.sudoku_a; public class SatsNode { //region Variables public SatsNode right; // Nnoeud simple ou entête de ligne situé à sa droite public SatsNode down; // Noeud simple ou entête de colonne situé en-dessous de lui public SatsNode rowHeader; // Si Noeud simple: Entête de sa ligne public SatsNode colHeader; // Si Noeud simple: Entête de sa colonne public int level; // Si Noeud simple: niveau auquel le noeud simple a été retenu comme candidat (pour sa ligne, dans la colonne choisie) public int coverId; // Si Entête de ligne (ou de colonne): Identifiant utilisé pour la couverture de sa ligne (ou de sa colonne) public int satsRow; // Si Entête de ligne: Index de ligne dans la matrice-mère (satsMatrix) public int rowCount; // Si Entête de colonne: Nombre de lignes non couvertes dans la colonne //endregion public SatsNode() { init(); } private void init() { right = null; down = null; rowHeader = null; colHeader = null; level = 0; coverId = 0; satsRow = 0; rowCount = 0; } } </code></pre> <p>The answer comes after a fraction of a second ... What do you think of it ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:55:50.080", "Id": "415827", "Score": "1", "body": "Please provide the entirety of the classes you wish to have reviewed. Links to external source repositories are discouraged because of link rot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-11T11:54:18.003", "Id": "438843", "Score": "0", "body": "For which puzzle does it come after a fraction of a second? Could you add test cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T09:58:44.550", "Id": "439076", "Score": "0", "body": "The Algorithm X is fast by design, wether with or without dancing links, so all puzzles are solved after a fraction of a second. No need to wait :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T12:30:58.520", "Id": "439405", "Score": "0", "body": "I am looking for online puzzle generators that use a flat layout _1..437..348..._ do you know where I can find this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T14:11:47.597", "Id": "215036", "Score": "3", "Tags": [ "java", "algorithm", "android", "sudoku" ], "Title": "Java Android Sudoku solver" }
215036
<p>Consider the following crossfilter / dc.js app (<a href="https://i.stack.imgur.com/KxEdG.png" rel="nofollow noreferrer">screenshot</a>):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Data Exploration Tool MVP&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/&gt; &lt;link rel="stylesheet" href="http://unpkg.com/dc@3/dc.css"/&gt; &lt;style&gt; #data-count { margin-top: 0; text-align: left; float: none; } table { table-layout: fixed; } td { width: 1%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container-fluid" style="margin: 10px;"&gt; &lt;div class="row"&gt; &lt;h2&gt;Data Exploration Tool&lt;/h2&gt; &lt;div class="col-md-3 well well-sm"&gt; &lt;div class="dc-data-count" id="data-count"&gt; &lt;span class="filter-count"&gt;&lt;/span&gt; selected out of &lt;span class="total-count"&gt;&lt;/span&gt; points | &lt;a href="javascript:dc.filterAll(); dc.renderAll();"&gt;Reset All&lt;/a&gt;&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-12"&gt; &lt;!-- First row of charts --&gt; &lt;div class="row"&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-11" style="width:100%;"&gt; &lt;div id="chart-11-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;range: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_11.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-12" style="width:100%;"&gt; &lt;div id="chart-12-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;selected: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_12.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-13" style="width:100%;"&gt; &lt;div id="chart-13-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;selected: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_13.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-14" style="width:100%;"&gt; &lt;div id="chart-14-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;selected: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_14.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Second row of chart --&gt; &lt;div class="row"&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-21" style="width:100%;"&gt; &lt;div id="chart-21-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;selected: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_21.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-22" style="width:100%;"&gt; &lt;div id="chart-22-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;range: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_22.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-23"style="width:100%;"&gt; &lt;div id="chart-23-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;selected: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_23.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3"&gt; &lt;div id="chart-24"style="width:100%;"&gt; &lt;div id="chart-24-title"&gt;&lt;/div&gt; &lt;div class="reset" style="visibility: hidden;"&gt;selected: &lt;span class="filter"&gt;&lt;/span&gt; &lt;a href="javascript:chart_24.filterAll();dc.redrawAll();"&gt;reset&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.1/d3.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.js"&gt;&lt;/script&gt; &lt;script src="http://unpkg.com/dc@3/dc.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; 'use strict'; dc.config.defaultColors(d3.schemeSet1); var chart_11 = dc.barChart("#chart-11"), chart_12 = dc.barChart("#chart-12"), chart_13 = dc.barChart("#chart-13"), chart_21 = dc.barChart("#chart-21"), chart_22 = dc.barChart("#chart-22"), chart_23 = dc.barChart("#chart-23"), data_count = dc.dataCount(".dc-data-count"); d3.csv("https://gist.githubusercontent.com/JasonAizkalns/32ece5c815f9ac5d540c41dc0825bbab/raw/362050300ddcb99f195044c00d9f26b0d7d489ca/data.csv").then(function(data) { var var_names = ["x", "y", "z", "a", "b", "c"]; $("#chart-11-title").append(["&lt;h5&gt;", var_names[0], "&lt;br&gt;Subtitle&lt;/h5&gt;"].join("")); $("#chart-12-title").append(["&lt;h5&gt;", var_names[1], "&lt;br&gt;Subtitle&lt;/h5&gt;"].join("")); $("#chart-13-title").append(["&lt;h5&gt;", var_names[2], "&lt;br&gt;Subtitle&lt;/h5&gt;"].join("")); $("#chart-21-title").append(["&lt;h5&gt;", var_names[3], "&lt;br&gt;Subtitle&lt;/h5&gt;"].join("")); $("#chart-22-title").append(["&lt;h5&gt;", var_names[4], "&lt;br&gt;Subtitle&lt;/h5&gt;"].join("")); $("#chart-23-title").append(["&lt;h5&gt;", var_names[5], "&lt;br&gt;Subtitle&lt;/h5&gt;"].join("")); var c11_bin = 10, c12_bin = 10, c13_bin = 500, c21_bin = 100, c22_bin = 20, c23_bin = 1000; var ndx = crossfilter(data), chart_11_dim = ndx.dimension(function(d) { return +d[var_names[0]]; }), chart_12_dim = ndx.dimension(function(d) { return +d[var_names[1]]; }), chart_13_dim = ndx.dimension(function(d) { return +d[var_names[2]]; }), chart_21_dim = ndx.dimension(function(d) { return +d[var_names[3]]; }), chart_22_dim = ndx.dimension(function(d) { return +d[var_names[4]]; }), chart_23_dim = ndx.dimension(function(d) { return +d[var_names[5]]; }), chart_11_grp = chart_11_dim.group(function(d) { return Math.floor(d / c11_bin) * c11_bin }).reduceCount(), chart_12_grp = chart_12_dim.group(function(d) { return Math.floor(d / c12_bin) * c12_bin }).reduceCount(), chart_13_grp = chart_13_dim.group(function(d) { return Math.floor(d / c13_bin) * c13_bin }).reduceCount(), chart_21_grp = chart_21_dim.group(function(d) { return Math.floor(d / c21_bin) * c21_bin }).reduceCount(), chart_22_grp = chart_22_dim.group(function(d) { return Math.floor(d / c22_bin) * c22_bin }).reduceCount(), chart_23_grp = chart_23_dim.group(function(d) { return Math.floor(d / c23_bin) * c23_bin }).reduceCount(); var all = ndx.groupAll(); data_count.dimension(ndx) .group(all); var chart_11_min = +chart_11_dim.bottom(1)[0][var_names[0]], chart_11_max = +chart_11_dim.top(1)[0][var_names[0]], chart_12_min = +chart_12_dim.bottom(1)[0][var_names[1]], chart_12_max = +chart_12_dim.top(1)[0][var_names[1]], chart_13_min = +chart_13_dim.bottom(1)[0][var_names[2]], chart_13_max = +chart_13_dim.top(1)[0][var_names[2]], chart_21_min = +chart_21_dim.bottom(1)[0][var_names[3]], chart_21_max = +chart_21_dim.top(1)[0][var_names[3]], chart_22_min = +chart_22_dim.bottom(1)[0][var_names[4]], chart_22_max = +chart_22_dim.top(1)[0][var_names[4]], chart_23_min = +chart_23_dim.bottom(1)[0][var_names[5]], chart_23_max = +chart_23_dim.top(1)[0][var_names[5]]; var breathing_room = 0.05; chart_11 .dimension(chart_11_dim) .group(chart_11_grp) .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scaleLinear().domain([chart_11_min - ((chart_11_max - chart_11_min) * breathing_room), chart_11_max + ((chart_11_max - chart_11_min) * breathing_room)])) .xUnits(function(start, end, xDomain) { return (end - start) / c11_bin; }) .controlsUseVisibility(true); chart_12 .dimension(chart_12_dim) .group(chart_12_grp) .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scaleLinear().domain([chart_12_min - ((chart_12_max - chart_12_min) * breathing_room), chart_12_max + ((chart_12_max - chart_12_min) * breathing_room)])) .xUnits(function(start, end, xDomain) { return (end - start) / c12_bin; }) .controlsUseVisibility(true); chart_13 .dimension(chart_13_dim) .group(chart_13_grp) .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scaleLinear().domain([chart_13_min - ((chart_13_max - chart_13_min) * breathing_room), chart_13_max + ((chart_13_max - chart_13_min) * breathing_room)])) .xUnits(function(start, end, xDomain) { return (end - start) / c13_bin; }) .controlsUseVisibility(true); chart_21 .dimension(chart_21_dim) .group(chart_21_grp) .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scaleLinear().domain([chart_21_min - ((chart_21_max - chart_21_min) * breathing_room), chart_21_max + ((chart_21_max - chart_21_min) * breathing_room)])) .xUnits(function(start, end, xDomain) { return (end - start) / c21_bin; }) .controlsUseVisibility(true); chart_22 .dimension(chart_22_dim) .group(chart_22_grp) .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scaleLinear().domain([chart_22_min - ((chart_22_max - chart_22_min) * breathing_room), chart_22_max + ((chart_22_max - chart_22_min) * breathing_room)])) .xUnits(function(start, end, xDomain) { return (end - start) / c22_bin; }) .controlsUseVisibility(true); chart_23 .dimension(chart_23_dim) .group(chart_23_grp) .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scaleLinear().domain([chart_23_min - ((chart_23_max - chart_23_min) * breathing_room), chart_23_max + ((chart_23_max - chart_23_min) * breathing_room)])) .xUnits(function(start, end, xDomain) { return (end - start) / c23_bin; }) .controlsUseVisibility(true); dc.renderAll(); }); &lt;/script&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I am specifically looking for advice on how to cleanup and better scale the javascript / dc.js code:</p> <ol> <li>How to make the <code>chart_11</code>, <code>chart_12</code>, ..., <code>chart_23</code> variables dynamically?</li> <li>Is there a way to automatically calculate natural bin sizes (e.g. <code>c11_bin</code>, <code>c12_bin</code>, ..., <code>c23_bin</code>?</li> <li>Better ways of setting <code>.x()</code> and <code>.xUnits</code> for each <code>dc.js</code> chart object -- the code is not very DRY. </li> </ol> <p>Any other improvements / suggestions for making this code easier to scale and maintain. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T23:41:53.117", "Id": "415950", "Score": "0", "body": "do you have control over the HTML?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T23:02:37.817", "Id": "416074", "Score": "0", "body": "@ohmygoodness yes, I have control over the HTML" } ]
[ { "body": "<p>Here's the Computer Science 101 answer: put the parameters that change between charts into an array, and then loop over that array.</p>\n\n<p>I want to include your code and data as a dc.js example (if you will permit it?) so I started porting it to the standard format used by those examples.</p>\n\n<p>The full example is here:\n<a href=\"https://github.com/dc-js/dc.js/blob/compare-unfiltered-example/web/examples/compare-unfiltered.html\" rel=\"nofollow noreferrer\">https://github.com/dc-js/dc.js/blob/compare-unfiltered-example/web/examples/compare-unfiltered.html</a></p>\n\n<p>I started from my fork of your fiddle, which answers the SO question <a href=\"https://stackoverflow.com/questions/55066391/display-original-conditional-brushed-unbrushed-crossfilter-bars-with-dc-js-wit\">Display original (conditional) brushed unbrushed crossfilter bars with dc.js with different colors</a></p>\n\n<p>You can look through the history to see all the changes from that point, but the big idea is just to put all the chart specifications into an array:</p>\n\n<pre><code> var chart_specs = [\n {\n variable: 'x',\n selector: '#chart-11',\n resolution: 10\n },\n {\n variable: 'y',\n selector: '#chart-12',\n resolution: 10\n },\n {\n variable: 'z',\n selector: '#chart-13',\n resolution: 500\n },\n {\n variable: 'a',\n selector: '#chart-21',\n resolution: 100\n },\n {\n variable: 'b',\n selector: '#chart-22',\n resolution: 20\n },\n {\n variable: 'c',\n selector: '#chart-23',\n resolution: 1000\n }\n ];\n</code></pre>\n\n<p>The three things we need to know about a chart are:</p>\n\n<ul>\n<li>what field or variable in the data to look at</li>\n<li>the CSS selector of the div to put the chart in</li>\n<li>what resolution to bin the data in this chart</li>\n</ul>\n\n<p>You also had unique selectors for the chart titles, but those were redundant, so I removed them.</p>\n\n<p>Let's walk through the rest of the code.</p>\n\n<h3>Cleaning the data</h3>\n\n<p>It's more efficient to convert all the strings to numbers before giving the data to crossfilter:</p>\n\n<pre><code> data.forEach(function(d) {\n chart_specs.forEach(function(spec) {\n d[spec.variable] = +d[spec.variable];\n });\n });\n</code></pre>\n\n<p>This is the first of many places where you'll see <code>chart_specs.forEach()</code>. That's the essence of the \"CS 101\" answer!</p>\n\n<h3>Creating the charts</h3>\n\n<p>Here's it's <code>chart_specs.map()</code> but the same idea:</p>\n\n<pre><code> var charts = chart_specs.map(function(spec) {\n return dc.compositeChart(spec.selector);\n });\n</code></pre>\n\n<p>We'll get an array of charts back.</p>\n\n<h3>Initializing the charts</h3>\n\n<p>It's just one big loop over all the chart specs:</p>\n\n<pre><code> chart_specs.forEach(function(spec, i) {\n</code></pre>\n\n<h3>Title each chart</h3>\n\n<pre><code> d3.select(spec.selector).select('h5.chart-title').text(spec.variable);\n</code></pre>\n\n<p>For simplicity I changed the <code>div</code>s to <code>h5</code>s and gave them the class <code>chart-title</code>. Now we can change the titles with a simple generic D3 call. Otherwise it's the same idea as your old jQuery calls.</p>\n\n<h3>Create the dimension and group for each chart</h3>\n\n<p>We'll read <code>spec.variable</code> and <code>spec.resolution</code> in order to create appropriate dimensions and groups. We'll also make a static copy of the group data</p>\n\n<pre><code> var dim = cf.dimension(function(d) { return d[spec.variable]; }),\n group = dim.group(function(d) {\n return Math.floor(d / spec.resolution) * spec.resolution;\n }).reduceCount(),\n static_group = static_copy_group(group);\n</code></pre>\n\n<h3>Hiding the red bars if no filters are active</h3>\n\n<p>See <a href=\"https://stackoverflow.com/questions/55066391/display-original-conditional-brushed-unbrushed-crossfilter-bars-with-dc-js-wit\">the original answer</a> for the purpose of this code.</p>\n\n<pre><code> charts[i].on('pretransition', function(chart) {\n var any_filters = charts.some(chart =&gt; chart.filters().length);\n chart.select('.sub._1')\n .attr('visibility', any_filters ? 'visible' : 'hidden')\n });\n</code></pre>\n\n<p>The only interesting here is using <code>charts[i]</code>. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\">Array.forEach</a> supplies us not just the current item but the index, which we can use to access the chart in the charts array.</p>\n\n<h3>Finish the initialization</h3>\n\n<p>Same idea with all of the rest of the code. We just look at <code>spec.variable</code> and <code>spec.resolution</code> instead of having special variables for every chart and every value.</p>\n\n<pre><code> charts[i]\n .compose([\n dc.barChart(charts[i])\n .dimension(dim)\n .group(static_group)\n .controlsUseVisibility(true),\n dc.barChart(charts[i])\n .dimension(dim)\n .group(group)\n .colors('red')\n .controlsUseVisibility(true)\n .brushOn(false)\n ]);\n\n var min = dim.bottom(1)[0][spec.variable],\n max = dim.top(1)[0][spec.variable];\n\n charts[i]\n .dimension(dim)\n .group(group)\n .round(dc.round.floor)\n .x(d3.scaleLinear().domain([min - ((max - min) * breathing_room), max + ((max - min) * breathing_room)]))\n .xUnits(function(start, end, xDomain) { return (end - start) / spec.resolution; })\n .controlsUseVisibility(true);\n</code></pre>\n\n<p>Please let me know if I can publish this example and data. It will be useful to a lot of people! (I have no idea if this data is publishable - looks suitably anonymous, hopefully...)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T16:02:38.380", "Id": "417828", "Score": "0", "body": "this is fantastic! Yes, this data is totally random / fake -- just wanted some variety. I agree, this is a great example...get it posted to the dc.js page!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T16:00:09.253", "Id": "215942", "ParentId": "215041", "Score": "3" } } ]
{ "AcceptedAnswerId": "215942", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T15:51:47.523", "Id": "215041", "Score": "4", "Tags": [ "javascript", "template", "data-visualization", "d3.js" ], "Title": "dc.js and crossfilter app to display multiple charts" }
215041
<pre><code>&lt;div id="form-0"&gt; &lt;a class="remove-form-0"&gt;X&lt;/a&gt; form 0 &lt;/div&gt; &lt;div id="form-1"&gt; &lt;a class="remove-form-1"&gt;X&lt;/a&gt; form 1 &lt;/div&gt; &lt;div id="form-2"&gt; &lt;a class="remove-form-2"&gt;X&lt;/a&gt; form 2 &lt;/div&gt; &lt;div id="form-3"&gt; &lt;a class="remove-form-3"&gt;X&lt;/a&gt; form 3 &lt;/div&gt; </code></pre> <p>I would like to hide the parent div, when it clicks on the remove element. </p> <pre><code> $(".remove-form-0").on("click", function(){ $("#form-0").css("display", "none"); }); </code></pre> <p>I do not want to duplicate this for 4 times. What is the best solution for this ?</p> <p>Any helps would be highly appreciated. </p>
[]
[ { "body": "<p>In general classes are used for collections of things that should exhibit the same behaviour. Your buttons here are perfect candidates for this, so you should give them the same class name - <code>remove-form-btn</code></p>\n\n<p>Then give your divs a class name of <code>form</code> and you can write just one handler:</p>\n\n<pre><code>$('.remove-form-btn').click((event) =&gt; { \n $(event.target).parents('.form').hide();\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:34:29.387", "Id": "215047", "ParentId": "215044", "Score": "1" } }, { "body": "<p>If you want to treat a bunch of elements all in the same way, then you should make a class for them, all with the same name.</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>$(\"a.remove-form\").bind(\"click\", function(e) {\n $(e.target).closest(\".form\").css(\"display\", \"none\");\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\n&lt;div class=\"form\"&gt;\n &lt;a class=\"remove-form\"&gt;X&lt;/a&gt;\n form 0\n&lt;/div&gt;\n\n&lt;div class=\"form\"&gt;\n &lt;a class=\"remove-form\"&gt;X&lt;/a&gt;\n form 1\n&lt;/div&gt;\n\n&lt;div class=\"form\"&gt;\n &lt;a class=\"remove-form\"&gt;X&lt;/a&gt;\n form 2\n&lt;/div&gt;\n\n&lt;div class=\"form\"&gt;\n &lt;a class=\"remove-form\"&gt;X&lt;/a&gt;\n form 3\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-03-08T17:39:17.540", "Id": "215048", "ParentId": "215044", "Score": "0" } }, { "body": "<p>Without touching your HTML markup... The use of <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors\" rel=\"nofollow noreferrer\">attribute selector</a> would help achieve this.</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>$(\"[class^='remove-form-']\").on(\"click\", function() {\n $(this).parents(\"[id^='form']\").hide();\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\n&lt;div id=\"form-0\"&gt;\n &lt;a class=\"remove-form-0\"&gt;X&lt;/a&gt; form 0\n&lt;/div&gt;\n\n&lt;div id=\"form-1\"&gt;\n &lt;a class=\"remove-form-1\"&gt;X&lt;/a&gt; form 1\n&lt;/div&gt;\n\n&lt;div id=\"form-2\"&gt;\n &lt;a class=\"remove-form-2\"&gt;X&lt;/a&gt; form 2\n&lt;/div&gt;\n\n&lt;div id=\"form-3\"&gt;\n &lt;a class=\"remove-form-3\"&gt;X&lt;/a&gt; form 3\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><hr>\n<strong>Alternative:</strong></p>\n\n<p>Instead of having a different class for each remove icon, I would use a single class... And same for the forms.</p>\n\n<p>It is exactly the same result... But the way to lookup elements is different... And makes the code a bit more readable.</p>\n\n<p>Notice that I left the original class/id there... In case it's already used elsewhere. The fun with classes is you can have many.</p>\n\n<p>That would be:</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>$(\".remove\").on(\"click\", function() {\n $(this).parents(\".form\").hide();\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\n&lt;div id=\"form-0\" class=\"form\"&gt;\n &lt;a class=\"remove-form-0 remove\"&gt;X&lt;/a&gt; form 0\n&lt;/div&gt;\n\n&lt;div id=\"form-1\" class=\"form\"&gt;\n &lt;a class=\"remove-form-1 remove\"&gt;X&lt;/a&gt; form 1\n&lt;/div&gt;\n\n&lt;div id=\"form-2\" class=\"form\"&gt;\n &lt;a class=\"remove-form-2 remove\"&gt;X&lt;/a&gt; form 2\n&lt;/div&gt;\n\n&lt;div id=\"form-3\" class=\"form\"&gt;\n &lt;a class=\"remove-form-3 remove\"&gt;X&lt;/a&gt; form 3\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><hr>\n<strong>In both cases</strong></p>\n\n<p>Depending on your structure... To <em>traverse</em> the DOM elements from <code>$(this)</code>, you may prefer to use <a href=\"https://api.jquery.com/closest/\" rel=\"nofollow noreferrer\"><code>.closest()</code></a>, <a href=\"https://api.jquery.com/parent/\" rel=\"nofollow noreferrer\"><code>.parent</code></a> or <a href=\"https://api.jquery.com/parents/\" rel=\"nofollow noreferrer\"><code>parents</code></a>. Your choice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T01:02:25.390", "Id": "215159", "ParentId": "215044", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T16:37:32.767", "Id": "215044", "Score": "2", "Tags": [ "javascript", "jquery", "event-handling", "dom" ], "Title": "Remove the parent element when user clicks on the remove icon" }
215044
<p>I wanted to design a state machine with a few goals in mind:</p> <ul> <li>Encapsulate state logic within individual classes to keep them decoupled. (I'm very curious what the community thinks about this in particular.)</li> <li>Support multithreading, allowing a thread to fire up a stateful but blocking series of steps and watch them progress.</li> <li>Catch exceptions that occur within, transition to an error state, and eventually exit the state machine gracefully.</li> <li>Use the C++11 standard.</li> </ul> <p>How would you improve this? Do my design goals sound reasonable?</p> <pre><code>#include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;unistd.h&gt; #include &lt;iostream&gt; #include "Immutable.h" struct NotImplementedException : public std::logic_error { NotImplementedException () : std::logic_error("Function not yet implemented.") {} }; struct StateName : ImmutableString&lt;StateName&gt; { StateName(const std::string &amp; name) : ImmutableString(name) {} }; template &lt;typename T&gt; struct Callable { virtual T run(void) = 0; }; struct State; typedef std::shared_ptr&lt;State&gt; NextState; class State : Callable&lt;NextState&gt; { const StateName _name; public: State(StateName name) : _name(name) {} State(const std::string &amp; name) : _name(name) {} virtual NextState run(void) { throw NotImplementedException(); }; virtual bool isTerminalState() const { return false; } StateName getName() const { return _name; } }; struct EndState : public State { EndState() : State("EndState") {} bool isTerminalState() const { return true; } }; struct BarState : public State { BarState() : State("BarState") {} NextState run() { std::cout &lt;&lt; "Now in " &lt;&lt; getName() &lt;&lt; std::endl; sleep(2); throw std::runtime_error("oopsie!"); return NextState(new EndState()); } }; struct FooState : public State { FooState() : State("FooState") {} NextState run() { std::cout &lt;&lt; "Now in " &lt;&lt; getName() &lt;&lt; std::endl; sleep(2); std::cout &lt;&lt; "Going to BarState" &lt;&lt; std::endl; return NextState(new BarState()); } }; struct StartState : public State { StartState() : State("StartState") {} NextState run() { std::cout &lt;&lt; "Now in " &lt;&lt; getName() &lt;&lt; std::endl; sleep(2); std::cout &lt;&lt; "Going to FooState" &lt;&lt; std::endl; return NextState(new FooState()); } }; struct AbortState : public State { AbortState() : State("AbortState") {} bool isTerminalState() const { return true; } }; class StateManager : Callable&lt;void&gt; { NextState _current_state; std::mutex _mutex; public: StateManager(State * start_state) : _current_state(start_state), _mutex() {} std::string getStateName() { std::lock_guard&lt;std::mutex&gt; lock(_mutex); return std::string(_current_state-&gt;getName().getValue()); } bool isRunning() { std::lock_guard&lt;std::mutex&gt; lock(_mutex); return !_current_state-&gt;isTerminalState(); } void setCurrentState(NextState next) { std::lock_guard&lt;std::mutex&gt; lock(_mutex); _current_state = next; } void run(void) { while(isRunning()) { try { auto next_state = _current_state-&gt;run(); setCurrentState(next_state); } catch (...) { std::cout &lt;&lt; "Caught an exception in " &lt;&lt; _current_state-&gt;getName() &lt;&lt; std::endl; std::cout &lt;&lt; "StateManager terminating" &lt;&lt; std::endl; setCurrentState(NextState(new AbortState())); return; } } } }; int main() { StateManager state_manager(new StartState); std::thread thread(&amp;StateManager::run, &amp;state_manager); while(state_manager.isRunning()) { std::cout &lt;&lt; state_manager.getStateName() &lt;&lt; std::endl; usleep(250000); } thread.join(); } </code></pre> <hr> <p>Here's Immutable.h:</p> <pre><code>#ifndef LCC_IMMUTABLE_H #define LCC_IMMUTABLE_H template&lt;typename T&gt; class AbstractImmutable { private: const T _value; public: AbstractImmutable(const T &amp; value) : _value(value) {} const T &amp; getValue() const { return _value; } inline friend bool operator&lt;(const AbstractImmutable&lt;T&gt; &amp; a, const AbstractImmutable&lt;T&gt; &amp; b) { return a.getValue() &lt; b.getValue(); } inline friend bool operator&gt;(const AbstractImmutable&lt;T&gt; &amp; a, const AbstractImmutable&lt;T&gt; &amp; b) { return a.getValue() &gt; b.getValue(); } inline friend bool operator==(const AbstractImmutable&lt;T&gt; &amp; a, const AbstractImmutable&lt;T&gt; &amp; b) { return a.getValue() == b.getValue(); } const AbstractImmutable&lt;T&gt; operator+(const AbstractImmutable&lt;T&gt; &amp; that) const { return AbstractImmutable&lt;T&gt;(getValue() + that.getValue()); } const AbstractImmutable&lt;T&gt; operator-(const AbstractImmutable&lt;T&gt; &amp; that) const { return AbstractImmutable&lt;T&gt;(getValue() - that.getValue()); } const AbstractImmutable&lt;T&gt; operator/(const AbstractImmutable&lt;T&gt; &amp; that) const { return AbstractImmutable&lt;T&gt;(getValue() / that.getValue()); } const AbstractImmutable&lt;T&gt; operator*(const AbstractImmutable&lt;T&gt; &amp; that) const { return AbstractImmutable&lt;T&gt;(getValue() * that.getValue()); } inline friend std::ostream &amp; operator&lt;&lt;(std::ostream &amp; out, const AbstractImmutable&lt;T&gt; &amp; that) { out &lt;&lt; that.getValue(); return out; } }; template&lt;typename T&gt; class ImmutableString : public AbstractImmutable&lt;std::string&gt; { using AbstractImmutable::AbstractImmutable; }; #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T16:55:37.237", "Id": "415821", "Score": "0", "body": "@Tom _\"Catch exceptions that occur within and exit the state machine gracefully.\"_ Shouldn't such rather automatically make a transition to some _ErrorState_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:00:09.627", "Id": "415822", "Score": "0", "body": "@πάνταῥεῖ I attempted to do that above. The `catch` block causes the next state to be `AbortState`, which then causes the machine to exit because it is marked as a terminal state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:00:10.257", "Id": "415823", "Score": "1", "body": "@Tom I did some work on a [state machine framework](https://github.com/makulik/sttcl) you might want to have a look at." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:00:31.263", "Id": "415824", "Score": "0", "body": "Fantastic, I'll take a look at it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:01:28.013", "Id": "415825", "Score": "0", "body": "@Tom _\"causes the next state to be `AbortState`\"_ I probably misunderstood your prose." } ]
[ { "body": "<p><code>AbstractImmutable</code> doesn't seem to do anything except provide operators to the underlying type. However, many of the operators aren't necessarily relevant (e.g. dividing a <code>std::string</code>). </p>\n\n<p>When adding another <code>ImmutableFoo</code> object to the hierarchy (e.g. an <code>ImmutableUInt</code>), would we add all the operators to the base class? Why support addition, subtraction, multiplication, and division, but not the remainder, or bitwise operators? Note that none of these operators will make sense for <code>std::string</code> either.</p>\n\n<p>There seems no reason to prefer the <code>StateName : ImmutableString : AbstractImmutable&lt;T&gt;</code> hierarchy over a simple <code>(const) std::string</code> member in <code>State</code>.</p>\n\n<hr>\n\n<p>What is the purpose of <code>Callable</code>? Using <code>State</code> as a base class seems sufficient - there is no reason for <code>Callable</code> to exist in the provided code, since it isn't used.</p>\n\n<p>(Note that <code>Callable&lt;NextState&gt;</code> is a different type from <code>Callable&lt;void&gt;</code>, as used by the <code>StateManager</code>. So they can't be stored by a common base class (if that's the intent), because there isn't one.)</p>\n\n<hr>\n\n<p><code>State::run</code> should probably be an abstract function (<code>virtual NextState run() = 0;</code>), to force derived classes to implement it and remove the need for the <code>NotImplementedException</code>.</p>\n\n<p><code>isTerminalState()</code> should probably also be abstract to prevent mistakes (forgetting to override it would be quite easy).</p>\n\n<p>Note that <code>AbortState</code> would throw a <code>NotImplementedException</code> with a somewhat misleading message if run. \"Function must not be called\" would be more accurate.</p>\n\n<hr>\n\n<p>We should use the <code>override</code> keyword to indicate overriding virtual functions in derived classes (if not also the <code>virtual</code> keyword).</p>\n\n<hr>\n\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_for\" rel=\"nofollow noreferrer\"><code>std::this_thread::sleep_for()</code></a> as a cross-platform solution, instead of <code>sleep</code> or <code>usleep</code>.</p>\n\n<hr>\n\n<p>Note that it's <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr\" rel=\"nofollow noreferrer\">possible to create a <code>std::shared_ptr</code> directly from a <code>std::unique_ptr</code></a>. <code>StateManager</code> could therefore take the starting state by <code>unique_ptr</code> in the constructor (enforcing transfer of ownership) rather than the ambiguous raw pointer.</p>\n\n<p><code>State::run()</code> should probably also return a <code>std::unique_ptr</code>.</p>\n\n<p>... In fact, is there a reason to use <code>std::shared_ptr</code> here at all?</p>\n\n<hr>\n\n<p>I believe it is generally preferred to make mutex data-members <code>mutable</code>, allowing for const-correctness (e.g. for <code>StateManager::isRunning()</code> and <code>StateManager::getStateName()</code>).</p>\n\n<hr>\n\n<p>Should <code>StateManager::setCurrentState()</code> really be public?</p>\n\n<hr>\n\n<p>We should use <a href=\"https://en.cppreference.com/w/cpp/error/exception_ptr\" rel=\"nofollow noreferrer\"><code>std::exception_ptr</code></a> to propagate an exception to the main thread. This removes the need for the <code>AbortState</code>.</p>\n\n<hr>\n\n<p>Instead of (presumably) looping in the <code>EndState</code> until the main thread checks on us, why not return an empty <code>NextState</code> pointer in <code>State::run</code>? If we check for this and return in the <code>StateManager</code>, then we don't need the <code>EndState</code> or the <code>isTerminalState()</code> functions either.</p>\n\n<hr>\n\n<p><em>Some other things to maybe try:</em></p>\n\n<ul>\n<li><p>It might be useful to keep track of whether a given state is currently-running, has-been-created-and-is-waiting-to-be-run, or has-ended-and-is-waiting-to-be-destroyed.</p>\n\n<p>This system is perhaps somewhat contrary to C++ principles of RAII. Perhaps it could be re-worked so that <code>State</code> objects exist only while they are being run. This could be done by changing the <code>State::run()</code> to return a factory-function used to create the next state, rather than the created state itself.</p></li>\n<li><p>Perhaps the <code>State</code> class-hierarchy could be entirely eliminated in favor of something like:</p>\n\n<pre><code>struct State {\n std::string _name;\n std::function&lt;std::unique_ptr&lt;State&gt;()&gt; _function;\n};\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:18:46.397", "Id": "415843", "Score": "0", "body": "Thanks so much for the extremely thorough response! I'm learning a lot already. A little background on AbstractImmutable: I'm experimenting with this pattern as a means of preventing the \"primitive obsession\" code smell, and using immutability to reduce the likelihood of initialization errors or bugs that result from using mutable types in a multithreaded environment. You've given me a lot to think about though and I'll see how I can incorporate some of your advice.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T02:18:32.833", "Id": "415857", "Score": "0", "body": "I was able to implement almost all of your recommendations and the code feels a lot cleaner and intuitive. Thanks again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T20:10:14.220", "Id": "215055", "ParentId": "215045", "Score": "3" } } ]
{ "AcceptedAnswerId": "215055", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T16:46:19.833", "Id": "215045", "Score": "8", "Tags": [ "c++", "object-oriented", "state-machine" ], "Title": "Designing yet another a state machine" }
215045
<p>I chanced upon this question and came up with the following algorithm, looking for criticisms and advice on how to improve my algorithm efficiency.</p> <blockquote> <p>You are given 3 arguments:</p> <ul> <li><p>A &amp; B are integers within the range (0 to 100,000)</p></li> <li><p>M is an array of integers within the range (0 to 2)</p></li> </ul> <p>Return an output (as a string) that describes matrix M in the following format:</p> <ul> <li><p>The first part of the string should contain a description of the upper row using only the <code>1</code> and <code>0</code> characters and should add up to the integer A</p></li> <li><p>The second part of the string should contain a description of the lowerrow using only the <code>1</code> and <code>0</code> characters and should add up to the integer B</p></li> <li><p>The sum of integers at K index of the output<code>(string1</code>, <code>string2)</code> should be equal to M[K] so like: <code>string1[K] + string2[K] == M[K]</code></p></li> </ul> <p>So for example,</p> <p>Given <code>A = 2, B = 2, M = [2, 0, 2, 0]</code>, your function should return a string like <code>"1010, 1010"</code> </p> <p>Given <code>A = 3, B = 2, M = [2, 1, 1, 0, 1]</code>, your function should return <code>"11001, 10100"</code></p> <p>Given <code>A = 2, B = 3, M = [0, 0, 1, 1, 2]</code>, your function should return <code>0</code>, because no matrix can be constructed that satisfies such conditions.</p> </blockquote> <pre><code>def convert(A, B, M): if (A+B) != sum(M) or max(A, B) &gt; len(M): return 0 ''' logic: set 2 arrays if value in matrix = 2, array1 &amp; array2 at index where 2 occurs will be [1] and [1] if value in matrix = 0, array1 &amp; array2 at index where 0 occurs will be [0] and [0] Then, we only need to handle 1s in matrix... same logic as above, however, we handle position of 1 by checking whether A &gt; B or vice versa ''' array1 = [""] * len(M) array2 = [""] * len(M) # first check for 2's and 0's: for index, value in enumerate(M): if value == 2: array1[index] = 1 array2[index] = 1 A -= 1 B -= 1 elif value == 0: array1[index] = 0 array2[index] = 0 # then check for 1's: elif value == 1 and A&gt;B: array1[index] = 1 array2[index] = 0 A -= 1 elif value == 1 and A&lt;=B: array1[index] = 0 array2[index] = 1 B -= 1 array1 = ''.join(str(x) for x in array1) array2 = ''.join(str(x) for x in array2) return array1 + ', ' + array2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T01:29:17.063", "Id": "415853", "Score": "1", "body": "For me it isn't clear how is this function supposed to work." } ]
[ { "body": "<p>First thing I notice is that you initialize your lists to contain strings</p>\n\n<pre><code>array1 = [\"\"] * len(M)\narray2 = [\"\"] * len(M)\n</code></pre>\n\n<p>but later assign integer values to these. This is misleading, and so I would instead do</p>\n\n<pre><code>array1 = [0] * len(M)\narray2 = [0] * len(M)\n</code></pre>\n\n<p>This has the added benefit that we get one case for free- if we want the value to be zeros (<code>value == 0</code>) we don't have to do anything. </p>\n\n<p>Another issue I see with these variables is that they are named <code>arrayX</code>, but are in fact lists. In general, its best to leave out the type in the variable name, and just provide a descriptive name for its purpose. I would name these something like <code>bitsA</code> and <code>bitsB</code>, which also follows suite in A/B vs 1/2 naming.</p>\n\n<p>Moving into your for loop, I would first reorder these conditionals to check <code>value</code> in numerical order (zero case first, then one, etc.), however as mentioned before we can now skip case zero, and so with only two cases (one or two) its not as big of a deal in my opinion. There is still one problem though. In one conditional you check <code>A&gt;B</code> and then in the other you check the exact opposite. This added redundancy is unnecessary, and if you later edit one to be <code>A&lt;B</code>, neither case will cover <code>A==B</code>. For this reason, it should be removed.</p>\n\n<p>Normally I argue for reducing nested if statements, but in this case it seems like a logical separation, since the two subcases for <code>value == 1</code> really mirror each other and deserve distinguishing from the <code>value == 2</code> case. I would rewrite the loop as:</p>\n\n<pre><code>for index, value in enumerate(M):\n if value == 2:\n array1[index] = 1\n array2[index] = 1\n A -= 1\n B -= 1\n\n elif value == 1:\n if A &gt; B:\n array1[index] = 1\n array2[index] = 0\n A -= 1\n else:\n array1[index] = 0\n array2[index] = 1\n B -= 1\n</code></pre>\n\n<p>However, there is one other route we could take, which would remove the remaining repeated logic.</p>\n\n<pre><code>for index, value in enumerate(M):\n if value == 2 or value == 1 and A &gt; B:\n array1[index] = 1\n A -= 1\n if value == 2 or value == 1 and A &lt;= B:\n array2[index] = 1\n B -= 1\n</code></pre>\n\n<p>Note this does break that rule I just mentioned about not including both <code>A &gt; B</code> and <code>A &lt;= B</code>, because our if statements are independent- both can execute. It becomes a trade off of bug resistance vs reducing redundancy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T03:01:34.407", "Id": "215164", "ParentId": "215046", "Score": "0" } } ]
{ "AcceptedAnswerId": "215164", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:19:54.187", "Id": "215046", "Score": "3", "Tags": [ "python", "algorithm", "strings", "matrix" ], "Title": "Decomposing a matrix as a sum of two bitstrings" }
215046
<p>I'm trying to reword the code below to avoid using the Select and Selection terms. I tried to Range("S"...).Copy instead of .Select but that didn't work for some reason. Does anyone know a way I can reword this to avoid Select and Selection statements and why my change .Select to .Copy wouldn't have worked?</p> <p>The code below looks in Column A for the identifiers Tango and Alpha. Then it uses those identifiers to figure out the range between rows to select in Column S and copies and pastes them as values. I can confirm the code does run as is.</p> <pre><code>Sub copy_paste() Dim wb As Workbook Dim ws As Worksheet Dim FoundCell1 As Range Dim FoundCell2 As Range Set wb = ActiveWorkbook Set ws = ActiveSheet Const WHAT_TO_FIND1 As String = "Tango" Set FoundCell1 = ws.Range("A:A").Find(What:=WHAT_TO_FIND1) Const WHAT_TO_FIND2 As String = "Alpha" Set FoundCell2 = ws.Range("A:A").Find(What:=WHAT_TO_FIND2) Range("S" &amp; FoundCell1.Row + 1 &amp; ":S" &amp; FoundCell2.Row - 1).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:58:45.890", "Id": "415828", "Score": "3", "body": "Welcome to CR! It's not clear whether the code you're presenting is working or not... and since code that doesn't work as intended isn't ready for a peer review and is therefore off-topic on this site, reviewers are more likely to vote to close and move on - please [edit] your post to clarify, and note that you'll get much better/thorough feedback if you include the whole procedure, rather than just a snippet taken out of its context. I really hope you edit & clarify - there's a lot of enhancement opportunities (and hidden bugs) in there!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T18:03:00.337", "Id": "415829", "Score": "3", "body": "@MathieuGuindon Hi Mathieu, thank you for your feedback. I've edited the post the clarify what the code does and can confirm that it does run." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T18:26:11.013", "Id": "415830", "Score": "1", "body": "Why are you doing the `.PasteSpecial`? Are `Tango` and `Alpha` (or the rows between them) the result of formulas and you're trying to overwrite the formulas with the actual values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T18:59:00.593", "Id": "415834", "Score": "0", "body": "@FreeMan The .PasteSpecial is just from me recording my macro and that's what it spit out. Tango and Alpha are the unique identifiers that are located on the row numbers I want to pull. The rows can shift so that's why I have those there so that it can dynamically determine between which rows to perform on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T23:06:24.537", "Id": "415846", "Score": "1", "body": "Named ranges can be your friend. Your code will then become `<Qualified>.Range(\"MyNamedRange\").Value = <Qualified>.Range(\"MyNamedRange\").Value`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:33:49.517", "Id": "416092", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:46:50.280", "Id": "416137", "Score": "0", "body": "@TinMan: Please post answers as answers and not as comments. Especially not as links to some external document in the comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:25:59.817", "Id": "416143", "Score": "0", "body": "@JDoe the macro recorder would not have spit out a `.PasteSpecial` unless that's what you did when you recorded it. If you don't need to `Paste Values`, but can accept formulas in your destination, that can significantly change the code (and the results)." } ]
[ { "body": "<p>To start with: You are currently not using the <code>wb</code> Workbook object after setting it. Is it needed in other code, or can it be removed?</p>\n\n<p>\nIf you are just trying to 'flatten' the range to get rid of any formula, you can just use <code>&lt;Range&gt;.Value = &lt;Range&gt;.Value</code>, instead of Copy / PasteSpecial</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Range(\"S\" &amp; FoundCell1.Row + 1 &amp; \":S\" &amp; FoundCell2.Row - 1).Select\n'Selection.Copy\n'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=False, Transpose:=False\nSelection.Value = Selection.Value\n</code></pre>\n\n<p>You can also use a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/with-statement\" rel=\"nofollow noreferrer\"><code>With</code> Statment</a> to replace the requirement for a Select or Selection.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>'Range(\"S\" &amp; FoundCell1.Row + 1 &amp; \":S\" &amp; FoundCell2.Row - 1).Select\nWith w.Range(\"S\" &amp; FoundCell1.Row + 1 &amp; \":S\" &amp; FoundCell2.Row - 1)\n .Value = .Value\nEnd With\n'Selection.Copy\n'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=False, Transpose:=False\n</code></pre>\n\n<p>And, this is personal preference, but you <em>could</em> use <code>.Offset</code>, <code>.EntireRow</code> and <code>.Column</code> to define the range instead of building a text string address:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>With ws.Range(FoundCell1.Offset(1, 0), FoundCell2.Offset(-1, 0)).EntireRow.Columns(\"S\")\n .Value = .Value\nEnd With\n</code></pre>\n\n<p>(This only requires \"Column S\" to be defined once, in case you need to change it later - the other option would be to have it in a <code>Const</code> at the start of the Sub)</p>\n\n<p>As yet-another-alternative, you could use <code>WorksheetFunction.Match</code> to retrieve the Rows directly (<code>TangoRow = WorksheetFunction.Match(WHAT_TO_FIND1, ws.Columns(\"A\"), 0)</code> would give the same result as <code>FoundCell1.Row</code>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:36:19.543", "Id": "215262", "ParentId": "215049", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T17:50:43.987", "Id": "215049", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Optimizing VBA Select Code" }
215049
<p>I have an <code>event_loop</code> implementation (basically an event/command queue and an <code>exec</code> function). I have added <code>interrupt</code> functionality that should end the event processing as soon as possible (i.e. it puts an "exit" command at the front of the queue). In practice, everything seems to work just fine (I use it to interrupt pending redraw calls on a UI window, which it seems to do well).</p> <p>I cannot seem to write a solid unit test for this code. I have made two attempts: one first, maybe naive version, and one I thought long about to ensure I am gridlocking/synchronizing the scenario everywhere it is necessary. The result is a test that hangs sometimes, and (what else) only on CI, and on one platform (Windows + Visual Studio). All other tested platforms (Mac OS X, Linux, Windows with any combination of GCC/Clang) haven't shown any signs of deadlock issues.</p> <p>Without further ado, the code is available in full form on <a href="https://github.com/skui-org/skui/" rel="nofollow noreferrer">my project's git repository</a>. To build and run the test from there, you run only that test (this will prevent ~95% of the other code in the project from being compiled):</p> <pre><code>ctest -R core/event_loop </code></pre> <p>This should build the <code>core</code> library and the <code>event_loop</code> test executable, and execute it.</p> <p>The sometimes deadlocking test code is as follows, after my mental image of what the test should be doing in what order:</p> <pre><code>//thread 1 | thread 2 // start | // | start // lock mutex | // ready = false | // *add command1* | // unlock mutex/wait condition | // | [command1] lock mutex // | [command1] ready = true // | [command1] unlock mutex // | [command1] notify condition // [condition] locks mutex | // *add command 2* | // *add interrupt command* | // unlock mutex2 | // | [command1] lock mutex2 // | [command1] finish // | [interrupt command] exit = false before command2 // join // check 2 commands executed void test_execute_interrupt() { skui::core::event_loop event_loop; int exit_code {0}; std::thread thread([&amp;event_loop, &amp;exit_code] { exit_code = event_loop.execute(); }); std::mutex mutex, mutex2; std::condition_variable condition; std::atomic_bool ready; std::unique_lock lock{mutex}; // block command until we wait on condition std::unique_lock lock2{mutex2}; // block part 2 of command event_loop.push(std::make_unique&lt;skui::core::command&gt;([&amp;mutex, &amp;mutex2, &amp;condition, &amp;ready] { // block command until wait on condition has been called std::unique_lock thread_lock{mutex}; ready = true; thread_lock.unlock(); condition.notify_one(); // block command until main thread has requested interrupt std::unique_lock thread_lock2{mutex2}; })); condition.wait(lock, [&amp;ready] { return ready.load(); }); event_loop.push(std::make_unique&lt;skui::core::command&gt;([this] { f(); })); event_loop.interrupt(1); lock2.unlock(); thread.join(); // wait for event_loop to exit check(count == 0, "Interrupt prevents further command execution."); check(exit_code == 1, "Interrupt returns proper exit code."); } </code></pre> <p>I haven't ensured that this is the code causing the hang (it only happens on CI and haven't toyed around with debug prints). <strong>The unabridged test executable code can be found in a standalone form <a href="http://coliru.stacked-crooked.com/a/9b2e76f6ac2995c3" rel="nofollow noreferrer">here</a></strong>. I "preprocessed" the file, but left all namespaces in. If I can/need to further improve this code, let me know what I can do.</p> <p>The test failing and succeeding can be seen in e.g. the last build of this project on its <a href="https://ci.appveyor.com/project/RubenVanBoxem/skui/builds/22920277" rel="nofollow noreferrer">Appveyor</a>, where it hangs once out of four Visual Studio build configurations. As far as I can tell, which one it fails on is random.</p> <p>I'm looking for suggestions and/or solutions specifically for the deadlock issue. All the test needs to do is check that if <code>interrupt</code> is called, it puts an exit event in the front of the queue (i.e. the queued events at the time <code>interrupt</code> is called, are not executed). Any other comments are of course welcome, but surely I'm not asking to review all this code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T19:21:08.080", "Id": "415837", "Score": "0", "body": "It's hard to review a possible deadlock without seeing the code on the other side. You should at least post the event cue or a runnable stub that simulates that. Does the first mutex protect anything else besides writing to the atomic ? Its not really necessary for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T10:48:32.807", "Id": "415879", "Score": "0", "body": "The full code is available at the link in my post (http://coliru.stacked-crooked.com/a/9b2e76f6ac2995c3). The first mutex should ensure the event_loop has actually started processing and has started the first command pushed to it. Without it, the interrupt might be called before the event loop thread has actually started." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T18:00:46.950", "Id": "215050", "Score": "0", "Tags": [ "c++", "multithreading", "unit-testing", "thread-safety", "c++17" ], "Title": "threaded event loop \"interrupt\" unit test without deadlocks" }
215050
<p>Review for optimization, code standards, missed validation and dependency checks.</p> <p>Review version 3. What's new:</p> <ul> <li>apply previous code review</li> <li>input arguments and validation</li> <li>MySQL management (optional)</li> <li>install option (.desktop file), what allows some input values be predefined</li> <li>attempt to install dependency when no choice to get user input (GUI version without zenity)</li> </ul> <p>I'm a web programmer, don't known things to make system GUI. So, that's why use bash with zenity. It was interesting to learn bash features. Answers are good, new version to come. Web is unsuitable for task more as bash.</p> <p><a href="https://github.com/LeonidMew/CreateVirtualHost/blob/master/a2createhost.sh" rel="nofollow noreferrer">GitHub</a></p> <pre><code>#!/bin/bash webmaster="$(id -un)" # user who access web files. group is www-data webgroup="www-data" # apache2 web group, does't need to be webmaster group. SGID set for folder. maindomain=".localhost" # domain for creating subdomains, leading dot required virtualhost="*" # ip of virtualhost in case server listen on many interfaces or "*" for all virtualport="80" # port of virtualhost. apache2 must listen on that ip:port serveradmin="webmaster@localhost" # admin email # declare -a webroots=("/home/<span class="math-container">\${webmaster}/Web/\$</span>{host}" # "/var/www/<span class="math-container">\${host}" # "/var/www/\$</span>{webmaster}/\${host}") # declared below, after a chanse to edit inlined variadles webroot=0 # folder index in webroots array a2ensite="050-" # short prefix for virtualhost config file apachehost="/etc/apache2/sites-available/${a2ensite}" # prefix for virtualhost config file tmphost=$(mktemp) # temp file for edit config trap 'rm "$tmphost"' EXIT # rm temp file on exit host="" # no default subdomain skipmysql="" mysqladmin="root" mysqladminpwd="" have_command() { type -p "$1" &gt;/dev/null } in_terminal() { [ -t 0 ] } in_terminal &amp;&amp; start_in_terminal=1 info_user() { local msg=$1 local windowicon="info" # 'error', 'info', 'question' or 'warning' or path to icon [ "$2" ] &amp;&amp; windowicon="$2" if in_terminal; then echo "$msg" else zenity --info --text="$msg" --icon-name="${windowicon}" \ --no-wrap --title="Virtualhost" 2&gt;/dev/null fi } notify_user () { echo "$1" &gt;&amp;2 in_terminal &amp;&amp; return local windowicon="info" # 'error', 'info', 'question' or 'warning' or path to icon local msgprefix="" local prefix="Virtualhost: " [ "$2" ] &amp;&amp; windowicon="$2" &amp;&amp; msgprefix="$2: " if have_command zenity; then zenity --notification --text="${prefix}$1" --window-icon="$windowicon" return fi if have_command notify-send; then notify-send "${prefix}${msgprefix}$1" else xmessage -buttons Ok:0 -nearmouse "${prefix}${msgprefix}$1" -timeout 10 fi } # sudo apt hangs when run from script, thats why terminal needed install_zenity() { have_command gnome-terminal &amp;&amp; gnome-terminal --title="$1" --wait -- $1 have_command zenity &amp;&amp; exit 0 exit 1 } # check if zenity must be installed or text terminal can be used # if fails = script exit # to install zenity, run: ./script.sh --gui in X terminal # ask user to confirm install if able to ask check_gui() { local msg="Use terminal or install zenity for gui. '$ sudo apt install zenity'" local cmd="sudo apt install zenity" local notfirst=$1 if ! have_command zenity;then notify_user "$msg" "error" # --gui set and input/output from terminal possible if [[ "${gui_set}" &amp;&amp; "${start_in_terminal}" ]]; then read -p "Install zenity for you? sudo required.[y/N]" -r autozenity reg="^[yY]$" if [[ "$autozenity" =~ $reg ]]; then $(install_zenity "$cmd") || exit exit 0 else exit 1 fi else if [[ "${gui_set}" ]]; then $(install_zenity "$cmd") || exit exit 0 else if ! in_terminal;then $(install_zenity "$cmd") || exit exit 0 fi fi fi fi exit 0 } $(check_gui) || exit validate_input() { local msg="$1" local var="$2" local reg=$3 if ! [[ "$var" =~ $reg ]]; then notify_user "$msg" "error" exit 1 fi exit 0 } validate_domain() { $(LANG=C; validate_input "Bad domain with leading . (dot)" "$1" \ "^\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9\.])*$") || exit 1 exit 0 } validate_username() { $(LANG=C; validate_input "Bad username." "$1" \ "^[[:lower:]_][[:lower:][:digit:]_-]{2,15}$") || exit 1 if ! id "$1" &gt;/dev/null 2&gt;&amp;1; then notify_user "User not exists" "error" exit 1 fi exit 0 } validate_group() { getent group "$1" &gt; /dev/null 2&amp;&gt;1 [ $? -ne 0 ] &amp;&amp; notify_user "Group $1 not exists" "error" &amp;&amp; exit 1 exit 0 } validate_email() { $(LANG=C; validate_input "Bad admin email." "$1" \ "^[a-z0-9!#<span class="math-container">\$%&amp;'*+/=?^_\`{|}~-]+(\.[a-z0-9!#$%&amp;'*+/=?^_\`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\$</span>") || exit 1 exit 0 } validate_subdomain() { $(LANG=C; validate_input "Bad subdomain" "$1" \ "^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$") || exit 1 exit 0 } getopt --test &gt; /dev/null if [ "$?" -gt 4 ];then echo 'I’m sorry, `getopt --test` failed in this environment.' else OPTIONS="w:d:a:ghi" LONGOPTS="webmaster:,domain:,adminemail:,gui,help,webroot:,webgroup:,install,subdomain:,skipmysql,mysqlauto" ! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@") if [[ ${PIPESTATUS[0]} -ne 0 ]]; then # e.g. return value is 1 # then getopt has complained about wrong arguments to stdout exit 2 fi # read getopt’s output this way to handle the quoting right: eval set -- "$PARSED" while true; do case "$1" in "--skipmysql") skipmysql=1 shift ;; "--mysqlauto") mysqlauto=1 shift ;; "-w"|"--webmaster") webmaster="$2" webmaster_set=1 shift 2 ;; "--webgroup") webgroup="$2" webgroup_set=1 shift 2 ;; "--subdomain") host="$2" host_set=1 shift 2 ;; "-d"|"--domain") maindomain="$2" maindomain_set=1 shift 2 ;; "-a"|"--adminemail") serveradmin="$2" serveradmin_set=1 shift 2 ;; "--webroot") declare -i webroot="$2" webroot_set=1 shift 2 ;; "-g"|"--gui") if [ -z "$DISPLAY" ];then notify_user "GUI failed. No DISPLAY." "error" exit 1 else gui_set=1 # GUI can be enabled at this point, when run from terminal / # with --gui, so check again $(check_gui) || exit in_terminal() { false } fi shift ;; "-i"|"--install") install_set=1 shift ;; "-h"|"--help") cat &lt;&lt; EOF usage: ./${0} # if some arguments specified in command # line, script will not ask to input it value # --install of script makes some values predefined [--webmaster="userlogin"] # user with permissions to edit www # files. group is 'www-data' [--webgroup="www-data"] # group of apache2 service user [--domain=".localhost"] # leading dot required [--subdomain="Example"] # Subdomain and webroot folder name # (folder case censetive) [--adminemail="admin@localhost"] [--webroot="0"] # documentroot of virtualhost, zero based index # webroots[0]="/home/<span class="math-container">\${webmaster}/Web/\$</span>{subdomain}" # webroots[1]="/var/www/<span class="math-container">\${subdomain}" # webroots[2]="/var/www/\$</span>{webmaster}/\${subdomain}" [--skipmysql] # don't create mysql db and user [--mysqlauto] # use subdomain as mysql db name, username, empty password [--gui] # run gui version from terminal else be autodetected without this. # attemps to install zenity ${0} --help # this help ${0} --gui --install # install .desktop shortcut for current user # and optionally copy script to $home/bin # --install requires --gui # shortcut have few options to run, without mysql for example ${0} "without arguments" # will read values from user EOF exit 0 ;; --) shift break ;; *) echo "Error" &gt;&amp;2 exit 3 ;; esac done if [ "$install_set" ]; then ! [ "$gui_set" ] &amp;&amp; notify_user "--gui must be set with --install" &amp;&amp; exit 1 homedir=$( getent passwd "$(id -un)" | cut -d: -f6 ) source="${BASH_SOURCE[0]}" while [ -h "$source" ]; do # resolve $SOURCE until the file is no longer a symlink dir="$( cd -P "$( dirname "$source" )" &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )" source="$(readlink "$source")" [[ $source != /* ]] &amp;&amp; source="$dir/$source" # ^ if $SOURCE was a relative symlink, we need to resolve it relative to # the path where the symlink file was located done dir="$( cd -P "$( dirname "$source" )" &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )" scriptname=$( basename "$source" ) # make a form where script args can be predefined, so not needed every launch pipestring=$(zenity --forms --add-entry="Domain(leading dot)(Default .localhost)" \ --add-entry="Webmaster(default: current username)" \ --add-entry="Webgroup(Default: www-data)" \ --add-entry="Server admin(Default: webmaster@localhost)" \ --text="Predefined values(empty=interactive edit)" --title="Desktop shortcut" \ --add-combo="Install path" --combo-values="${homedir}/bin/|${dir}/" 2&gt;/dev/null) # zenity stdout if like value1|value2|etc IFS='|' read -r -a form &lt;&lt;&lt; "$pipestring" args="" if [ "${form[0]}" ]; then $(validate_domain "${form[0]}") || exit 60; fi if [ "${form[1]}" ]; then $(validate_username "${form[1]}") || exit 61; fi if [ "${form[2]}" ]; then $(validate_group "${form[2]}") || exit 62; fi if [ "${form[3]}" ]; then $(validate_email "${form[3]}") || exit 63; fi if [ "${form[4]}" ]; then mkdir -p "${form[4]}"; fi [ "${form[0]}" ] &amp;&amp; args="$args --domain='${form[0]}'" [ "${form[1]}" ] &amp;&amp; args="$args --webmaster='${form[1]}'" [ "${form[2]}" ] &amp;&amp; args="$args --webgroup='${form[2]}'" [ "${form[3]}" ] &amp;&amp; args="$args --adminemail='${form[3]}'" installpath="${dir}/${scriptname}" if [ "${form[4]}" != " " ]; then installpath="${form[4]}${scriptname}"; fi cp "${dir}/${scriptname}" "$installpath" &gt;/dev/null 2&gt;&amp;1 chmod u+rx "$installpath" desktop="$homedir/.local/share/applications/virtualhost.desktop" cat &gt;"$desktop" &lt;&lt;EOF [Desktop Entry] Version=1.0 Name=Create Virtualhost Comment=Easy to create new virtualhost for apache2 server Keywords=Virtualhost;Apache;Apache2 Exec=/bin/bash ${installpath} ${args} Terminal=false X-MultipleArgs=true Type=Application Icon=network-wired Categories=GTK;Development; StartupNotify=false Actions=without-arguments;new-install [Desktop Action without-arguments] Name=Clean launch Exec=/bin/bash ${installpath} [Desktop Action without-mysql] Name=Without mysql config Exec=/bin/bash ${installpath} ${args} --skipmysql [Desktop Action new-install] Name=Reinstall (define new configuration) Exec=/bin/bash ${installpath} --install --gui X-MultipleArgs=true EOF exit 0 fi # if arguments passed - validate them. msg="" if [ "$maindomain_set" ]; then $(validate_domain "$maindomain") \ || msg="Bad value for --domain. Should have leading dot. \".localhost\"\n" fi if [ "$serveradmin_set" ]; then $(validate_email "$serveradmin") || msg="Bad value for --adminemail\n$msg" fi if [ "$host_set" ]; then $(validate_subdomain "$host") || msg="Bad value for --subdomain\n$msg" fi if [ "$webmaster_set" ]; then $(validate_username "$webmaster") || msg="Bad value for --webmaster\n$msg" fi if [ "$webgroup_set" ]; then $(validate_group "$webgroup") || msg="Bad value for --webgroup\n$msg" fi have_command apache2 || msg="Apache2 not installed\n$msg" if [ "$msg" ];then [ "$gui_set" ] &amp;&amp; info_user "$msg" "error" exit 1 fi fi if [ "$(id -un)" == "root" ];then notify_user "You should not run this script as root but as user with 'sudo' rights." "error" exit 1 fi get_text_input() { if in_terminal; then defaulttext="" [ "$3" ] &amp;&amp; defaulttext="[Default: ${3}]" read -p "${2}$defaulttext" -r input # default [ "$3" ] &amp;&amp; [ -z "$input" ] &amp;&amp; input="$3" else input=$(zenity --entry="$1" --title="Virtualhost" --text="$2" --entry-text="$3" 2&gt;/dev/null) if [ "$?" == "1" ]; then echo "[$1]Cancel button" 1&gt;&amp;2 exit 1 # Cancel button pressed fi fi if [ -z "$4" ]; then case "$input" in "") notify_user "[$1]Bad input: empty" "error" ; exit 1 ;; *"*"*) notify_user "[$1]Bad input: wildcard" "error" ; exit 1 ;; *[[:space:]]*) notify_user "[$1]Bad input: whitespace" "error" ; exit 1 ;; esac fi echo "$input" } # get input and validate it if [ -z "$host" ]; then host=$(get_text_input "Subdomain" "Create virtualhost (= Folder name,case sensitive)" "") || exit; fi $(validate_subdomain "$host") || exit if [ -z "$maindomain_set" ]; then maindomain=$(get_text_input "Domain" "Domain with leading dot." "$maindomain") || exit; fi $(validate_domain "$maindomain") || exit if [ -z "$webmaster_set" ]; then webmaster=$(get_text_input "Username" "Webmaster username" "$webmaster") || exit; fi $(validate_username "$webmaster") || exit if [ -z "$serveradmin_set" ]; then serveradmin=$(get_text_input "Admin email" "Server admin email" "$serveradmin") || exit; fi $(validate_email "$serveradmin") || exit homedir=$( getent passwd "$webmaster" | cut -d: -f6 ) # webroot is a choise of predefined paths array declare -a webroots=("${homedir}/Web/${host}" "/var/www/${host}" "/var/www/${webmaster}/${host}") zenitylistcmd="" # zenily list options is all columns of all rows as a argument, one by one for (( i=0; i&lt;${#webroots[@]}; i++ ));do if in_terminal; then echo "[${i}] ${webroots[$i]}" # reference for text read below else zenitylistcmd="${zenitylistcmd}${i} ${i} ${webroots[$i]} " fi done dir="" [ -z "$webroot_set" ] &amp;&amp; if in_terminal; then webroot=$(get_text_input 'Index' 'Website folder' "$webroot") || exit else webroot=$(zenity --list --column=" " --column="Idx" --column="Path" --hide-column=2 \ --hide-header --radiolist --title="Choose web folder" $zenitylistcmd 2&gt;/dev/null) fi if [ -z "${webroots[$webroot]}" ]; then notify_user "Invalid webroot index"; exit 1; fi dir="${webroots[$webroot]}" # folder used as document root for virtualhost hostfile="${apachehost}${host}.conf" # apache virtualhost config file # virtualhost template cat &gt;"$tmphost" &lt;&lt;EOF &lt;VirtualHost ${virtualhost}:${virtualport}&gt; ServerAdmin $serveradmin DocumentRoot $dir ServerName ${host}${maindomain} ServerAlias ${host}${maindomain} &lt;Directory "$dir"&gt; AllowOverride All Require local &lt;/Directory&gt; # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. LogLevel error &lt;/VirtualHost&gt; # vim: syntax=apache ts=4 sw=4 sts=4 sr noet EOF find_editor() { local editor=${VISUAL:-$EDITOR} if [ "$editor" ]; then echo "$editor" return fi for cmd in nano vim vi pico; do if have_command "$cmd"; then echo "$cmd" return fi done } if in_terminal; then # edit virtualhost config editor=$(find_editor) if [ -z "$editor" ];then echo "$tmphost:" cat $tmphost echo "edit '$tmphost' to your liking, then hit Enter" read -p "I'll wait ... " else "$editor" "$tmphost" fi else # edit virtualhost config GUI text=$(zenity --text-info --title="Virtualhost config" --filename="$tmphost" --editable 2&gt;/dev/null) if [ -z "$text" ];then # cancel button pressed exit 0 fi echo "$text" &gt; "$tmphost" fi # probably want some validating here that the user has not broken the config # apache will not reload config if incorrect mysqlskip="$skipmysql" # skip if --skipmysql set [ -z "$mysqlskip" ] &amp;&amp; if have_command mysqld; then if [ -z "$mysqlskip" ]; then mysqladminpwd=$(get_text_input "Admin password" "Admin password (${mysqladmin})" "" "skipcheck") || mysqlskip=1; fi if [ "$mysqlauto" ]; then mysqldb="$host" mysqluser="$host" mysqlpwd="" else if [ -z "$mysqlskip" ]; then mysqldb=$(get_text_input "Database" "Database name(Enter for default)" "$host") || mysqlskip=1 fi if [ -z "$mysqlskip" ]; then mysqluser=$(get_text_input "Username" "Mysql user for db:$mysqldb host:localhost(Enter for default)" "$mysqldb") || mysqlskip=1 fi if [ -z "$mysqlskip" ]; then mysqlpwd=$(get_text_input "Password" "Mysql password for user:$mysqluser db:$mysqldb host:localhost(Enter for empty)" "" "skipcheck") || mysqlskip=1 fi fi if [ -z "$mysqlskip" ]; then tmpmysqlinit=$(mktemp) trap 'rm "$tmpmysqlinit"' EXIT cat &gt;"$tmpmysqlinit" &lt;&lt;EOF CREATE USER '${mysqluser}'@'localhost' IDENTIFIED BY '${mysqlpwd}'; GRANT USAGE ON *.* TO '${mysqluser}'@'localhost'; CREATE DATABASE IF NOT EXISTS \`${mysqldb}\` CHARACTER SET utf8 COLLATE utf8_general_ci; GRANT ALL PRIVILEGES ON \`${mysqldb}\`.* TO '${mysqluser}'@'localhost'; FLUSH PRIVILEGES; EOF fi fi getsuperuser () { if in_terminal;then echo "sudo" else echo "pkexec" fi } notify_user "execute root commands with $(getsuperuser) to create virtualhost" "warning" tmpresult=$(mktemp) trap 'rm "$tmpresult"' EXIT tmpmysqlresult=$(mktemp) trap 'rm "$tmpmysqlresult"' EXIT $(getsuperuser) /bin/bash &lt;&lt;EOF mkdir -p "$dir" chown ${webmaster}:${webgroup} "$dir" chmod u=rwX,g=rXs,o= "$dir" cp "$tmphost" "$hostfile" chown root:root "$hostfile" chmod u=rw,g=r,o=r "$hostfile" a2ensite "${a2ensite}${host}.conf" systemctl reload apache2 echo "<span class="math-container">\$?" &gt; "$tmpresult" if [ -z "${mysqlskip}" ]; then systemctl start mysql mysql --user="$mysqladmin" --password="$mysqladminpwd" &lt;"$tmpmysqlinit" echo "\$</span>?" &gt; "$tmpmysqlresult" fi EOF if [ $(cat "$tmpmysqlresult") ]; then $mysqlresult="\nMysql db,user created"; fi if [ $(cat "$tmpresult") ]; then notify_user "Virtualhost added. Apache2 reloaded.${mysqlresult}"; fi </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T19:19:59.460", "Id": "415836", "Score": "2", "body": "`apt` has a warning (somewhere) about an unstable CLI that's optimized for interactive use and not recommended for scripts. `apt-get` is a good choice for a script, and may solve your hanging problem." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Because of length and complexity alone I would say <strong>Bash is not a good fit for this purpose.</strong> A language like Python will be much better at validating strings, argument parsing, escaping SQL and especially error handling. Case in point:</li>\n<li><p><strong>Your traps are clobbering each other.</strong> See this example:</p>\n\n<pre><code>$ trap echo EXIT\n$ trap ls EXIT\n$ trap -p\ntrap -- 'ls' EXIT\n</code></pre></li>\n<li>\".localhost\" is not a domain - \"localhost\" is, and the dot is the <em>separator</em> between the hostname and domain.</li>\n<li>The exit trap should be set up <em>before</em> creating the temporary directory, to avoid a race condition.</li>\n<li><strong>Shell scripts should not be interactive</strong> unless absolutely required (such as <code>top</code> or <code>vim</code>). Instead of asking the user to install some software I would make Zenity an optional dependency of this script, and possibly warn the user about it being missing if necessary. This will shorten and simplify your script considerably.</li>\n<li><strong>Shell scripts should not run <code>sudo</code></strong> (or equivalent). Privilege escalation should <em>always</em> be at the discretion of the user, so the script should simply fail with a useful message if it can't do what it needs to because of missing privileges.</li>\n<li><code>notify_user</code> could just as well <code>echo \"$@\"</code> to support any number of arguments, or could also include useful information such as the time of the message if you use <code>printf</code> instead.</li>\n<li>A more <a href=\"https://stackoverflow.com/a/10383546/96588\">portable shebang line</a> is <code>#!/usr/bin/env bash</code>.</li>\n<li><a href=\"https://stackoverflow.com/a/669486/96588\">Use <code>[[</code> rather than <code>[</code></a>.</li>\n<li>Run the script through <code>shellcheck</code> to get more linting tips.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T15:54:22.027", "Id": "417954", "Score": "0", "body": "Quote \"Shell scripts should not run `sudo` (or equivalent).\". Only few commands need root permissions, may be add an option to elevate privileges inside script?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T19:32:07.150", "Id": "417979", "Score": "1", "body": "That makes the script break if you don't specify the option as a normal user, and makes it more complicated than it has to be. You could split this into *two* scripts, one which does the root work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:54:16.523", "Id": "215060", "ParentId": "215051", "Score": "3" } }, { "body": "<p>As bash scripts go, this is well done. You've made pretty good use of bash features and the code clearly reflects time spent debugging and refining. </p>\n\n<p>There are two big things I would do differently: </p>\n\n<ol>\n<li>I wouldn't use bash. As the number of code paths and lines of code increase, access to a real debugger and static syntax checking outweigh the convenience of a shell.</li>\n<li>I'd separate the heavy lifting from the GUI. A lot of the complexity and sheer bulk of this script arises from its constant jumping between performing the task and checking in with the user. Develop a solid non-interactive tool, then build a GUI on top of it.</li>\n</ol>\n\n<p>What's done is done, though, and here are some changes I'd recommend to the code as-is:</p>\n\n<h3>refactor the death pattern</h3>\n\n<p>There's a lot of code like this:</p>\n\n<pre><code>if [ -z \"$DISPLAY\" ];then\n notify_user \"GUI failed. No DISPLAY.\" \"error\"\n exit 1\nfi\n</code></pre>\n\n<p>That could be shortened by using an error-handling function:</p>\n\n<pre><code>[ -n $DISPLAY ] || die \"GUI failed. No DISPLAY.\"\n</code></pre>\n\n<p>This makes it easy to add cleanup or other functionality to fatal errors. The function can be as simple as:</p>\n\n<pre><code>die() {\n notify_user \"$1\" \"${2:-error}\"\n exit ${3:-1}\n}\n</code></pre>\n\n<h3>tempfiles considered harmful</h3>\n\n<p>Most tempfile contents are better stored in a variable. Variables avoid all kinds of failure modes&mdash;disk full, no permission, file deleted from /tmp by cleanup job&mdash;and save you having to worry about if anyone can read the password saved in the mysql temp file.</p>\n\n<p>The only real drawback is that you're limited by memory; variables are unsuitable for gigabytes of data. </p>\n\n<pre><code>mysqlinit=\"CREATE USER '${mysqluser}'@'localhost' IDENTIFIED BY '${mysqlpwd}';\nGRANT USAGE ON *.* TO '${mysqluser}'@'localhost';\nCREATE DATABASE IF NOT EXISTS \\`${mysqldb}\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\nGRANT ALL PRIVILEGES ON \\`${mysqldb}\\`.* TO '${mysqluser}'@'localhost';\nFLUSH PRIVILEGES;\"\n…\nmysql --user=\"$mysqladmin\" --password=\"$mysqladminpwd\" &lt;&lt;&lt;$mysqlinit\n</code></pre>\n\n<p>If the quoting is hairy, you can <code>cat</code> a heredoc and capture with <code>$( … )</code>:</p>\n\n<pre><code>foo=$( \n cat &lt;&lt;EOF\n…\nEOF\n)\n</code></pre>\n\n<h3><code>find_editor()</code> could be a lot shorter</h3>\n\n<p>Instead of:</p>\n\n<pre><code>find_editor() {\n local editor=${VISUAL:-$EDITOR}\n if [ \"$editor\" ]; then\n echo \"$editor\"\n return\n fi\n\n for cmd in nano vim vi pico; do\n if have_command \"$cmd\"; then\n echo \"$cmd\"\n return\n fi\n done\n}\n</code></pre>\n\n<p>Just:</p>\n\n<pre><code>find_editor() { \n type -P $VISUAL $EDITOR nano vim vi pico | head -1\n}\n</code></pre>\n\n<h3>refactor the \"if I have\" pattern</h3>\n\n<p>Instead of:</p>\n\n<pre><code>if have_command zenity; then\n zenity --notification --text=\"${prefix}$1\" --window-icon=\"$windowicon\"\n return\nfi\n</code></pre>\n\n<p>How about:</p>\n\n<pre><code>try() { \n have_command \"$1\" &amp;&amp; \"$@\"\n}\n…\ntry zenity --notification --text=\"${prefix}$1\" --window-icon=\"$windowicon\" &amp;&amp; return\n</code></pre>\n\n<h3>check for errors</h3>\n\n<p>What happens if <code>cp \"${dir}/${scriptname}\" \"$installpath\"</code> only copies half of the script before the disk fills up? Probably nothing good.</p>\n\n<p>Consider <code>set -e</code> to have bash terminate on error. It's going to be a bit of work, because you'll need to mask ignorable errors (usually by adding <code>|| true</code> to the command). The benefit comes when you get to the end of the script and start doing system configuration, you know that there isn't some early error messing everything up. </p>\n\n<h3>some of these <code>$( )</code> invocations are weird</h3>\n\n<p>You have a bunch of <code>$(function)</code> as the first argument on a command line, which runs the <em>output</em> of <code>function</code> as a second command. That's hacky but kind-of okay, except <code>function</code> doesn't produce any output. So it's just weird and it's going to break if <code>function</code> ever writes anything to stdout.</p>\n\n<p>If you want to contain the effects of an <code>exit</code>, use plain <code>()</code> without the dollar sign. Better yet, use <code>return</code> in the function, instead of <code>exit</code>, and omit the parens altogether.</p>\n\n<h3>little stuff</h3>\n\n<pre><code>$(LANG=C; validate_input \"Bad subdomain\" \"$1\" \\\n \"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$\") || exit 1\n</code></pre>\n\n<p>A domain can't start with a digit. If this is for internal use, consider disallowing caps (or folding them to lowercase).</p>\n\n<p><code>&gt;&amp; /dev/null</code> is bash shorthand for <code>&gt; /dev/null 2&gt;&amp;1</code>.</p>\n\n<p><code>args=\"$args --domain='${form[0]}'\"</code> can be replaced by <code>args+=\" --domain=${form[0]}\"</code></p>\n\n<p>Declare your read-only globals as such (<code>declare -r x=y</code>) to avoid accidentally clobbering them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T03:52:01.120", "Id": "415959", "Score": "0", "body": "I'm going this way: \"quote: Develop a solid non-interactive tool, then build a GUI on top of it\", but have difficulty to pass password from GUI tool to script, question related to it: https://stackoverflow.com/questions/55084251/bash-how-to-pass-arguments-to-my-script-by-stdin-optionally" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T10:46:05.970", "Id": "415995", "Score": "0", "body": "I don't understand that question at all. If password is unset on command line, then read a line from stdin. Sounds easy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T13:04:10.840", "Id": "416006", "Score": "0", "body": "I'm going to make non interactive tool(and separate GUII script on top of it), so password should be set by arguments or somehow else" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T13:17:28.597", "Id": "416007", "Score": "1", "body": "read it from an environment variable or file. Let the user specify which with a command-line option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T15:49:57.953", "Id": "417953", "Score": "0", "body": "Is it temporally files more harmful then running whole script as root, not just few lines of it? I'm try to avoid asking for root permissions by `pkexec` more then once thats why use temp file, then use heredoc to run root commands." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T01:07:20.593", "Id": "215068", "ParentId": "215051", "Score": "2" } } ]
{ "AcceptedAnswerId": "215068", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T18:22:03.460", "Id": "215051", "Score": "2", "Tags": [ "bash" ], "Title": "Create Apache virtualhost, MySQL db and user, install option - desktop shortcut for GUI version" }
215051
<p>New to Python, learned a couple things. I'm trying to make a text based game and was told to come here for a review. Any tips would be appreciated to improve my code. I would like to expand this the more I learn.</p> <pre><code>import time import random def game(): #intro text print('******************************') print(' Welcome to the game!') print('*******************************') time.sleep(1) print('You awaken in a cave, unable to see. Darkness surrounds you.') time.sleep(1) print('\nSuddenly a small flickering light is seen in the distance.') time.sleep(1) print('\nyou get on your feet and decide wether you should head towards the light or wait where you are and hope help finds its way.') #first question def firstquestion(): while True: print('\nDo you get up and see what could be the source of this light? \nOr do you wait?') Answer = input() if Answer == 'get up' or Answer == 'I get up': print('You begin to walk towards the light.') break elif Answer == 'wait': print('you wait, no one comes and you die...') break else: print('try again...') #second question def secondquestion(): while True: print('\nThe light turns out to be a torch. Do you take this torch? enter y / n. ') Answer = input() if Answer == 'y': print('good choice, you pick up the torch and walk the out of the cave.') break elif Answer == 'n': print('well now your blind and dead...') break else: print('try again...') game() firstquestion() secondquestion() print() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:44:46.377", "Id": "415845", "Score": "0", "body": "This is not working code. Please at least format it to be executable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T02:52:30.470", "Id": "415859", "Score": "2", "body": "Welcome to Code Review. We would be glad to help you improve the code, but as per the rules in the [help/on-topic], the code must work correctly before we can review it. Since the game continues after you \"die\", I would consider this to be broken code, and thus off-topic for Code Review." } ]
[ { "body": "<p>As @l0b0 pointed out, you probably messed up your indents upon copying. Assuming they work:</p>\n\n<p>First, looking at your question() functions, you can see a pattern, they prompt the user with a question. The user then has only two choices (binary like). If the user fails to enter a valid answer, they get prompted again. So why not create a function that gets passed the question and the binary answers? This also allows for easier expansion down the line like so:</p>\n\n<pre><code>def binary_question(question, answers):\n while True:\n print(question)\n Answer = input()\n if Answer in answers:\n print(answers[Answer])\n break\n else:\n print('try again...')\n\n\nQuestions = [\n '\\nDo you get up and see what could be the source of this light? \\nOr do you wait?',\n '\\nThe light turns out to be a torch. Do you take this torch? enter y / n.',\n]\n\nAnswers = [\n {\n 'get up': 'You begin to walk towards the light.',\n 'I get up': 'You begin to walk towards the light.',\n 'wait': 'you wait, no one comes and you die...',\n },\n {\n 'y': 'good choice, you pick up the torch and walk the out of the cave.',\n 'n': 'well now your blind and dead...',\n },\n]\n\ngame()\nfor que, ans in zip(Questions, Answers):\n binary_question(que, ans)\n</code></pre>\n\n<p>If you are not familiar with dictionaries or zip() look them up.</p>\n\n<p>Second, you can allow for more choices by changing the user input strings to lower case and populating your Answers list to be only lower case. That way the user can enter \"I get up\" or \"i get up\", or \"I GET UP\", etc, and still get a valid response. Like so:</p>\n\n<pre><code>def binary_question(question, answers):\n while True:\n print(question)\n Answer = input()\n Answer = Answer.lower()\n if Answer in answers:\n print(answers[Answer])\n break\n else:\n print('try again...')\n\n\nQuestions = [\n '\\nDo you get up and see what could be the source of this light? \\nOr do you wait?',\n '\\nThe light turns out to be a torch. Do you take this torch? enter y / n.',\n]\n\nAnswers = [\n {\n 'get up': 'You begin to walk towards the light.',\n 'i get up': 'You begin to walk towards the light.',\n 'wait': 'you wait, no one comes and you die...',\n },\n {\n 'y': 'good choice, you pick up the torch and walk the out of the cave.',\n 'n': 'well now your blind and dead...',\n },\n]\n\ngame()\nfor que, ans in zip(Questions, Answers):\n binary_question(que, ans)\n</code></pre>\n\n<p>As you can see, we made use of str.lower() function and wrote lowercase only answers in our Answers dict.</p>\n\n<p>Third, I just realized that if the player dies in question one, question two still gets asked. You need a return value to your main loop so you can break in case you are dead:</p>\n\n<pre><code>def binary_question(question, answers):\n while True:\n print(question)\n Answer = input()\n Answer = Answer.lower()\n if Answer in answers:\n print(answers[Answer][0])\n return answers[Answer][1]\n print('try again...')\n\n\nQuestions = [\n '\\nDo you get up and see what could be the source of this light? \\nOr do you wait?',\n '\\nThe light turns out to be a torch. Do you take this torch? enter y / n.',\n]\n\n# can use named tuples here to make code more readable\n# read about it if interested.\nAnswers = [\n {\n 'get up': ('You begin to walk towards the light.', True),\n 'i get up': ('You begin to walk towards the light.', True),\n 'wait': ('you wait, no one comes and you die...', False),\n },\n {\n 'y': ('good choice, you pick up the torch and walk the out of the cave.', True),\n 'n': ('well now your blind and dead...', False),\n },\n]\n\ngame()\nfor que, ans in zip(Questions, Answers):\n alive = binary_question(que, ans)\n if not alive:\n break\n</code></pre>\n\n<p>The new boolean values in Answers[] signify if that answer kills the player. In this case, True = alive and False = dead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T19:29:44.187", "Id": "415929", "Score": "0", "body": "so would i be able to make the whole program in this structure. Listing the questions, the answers. having the values set and a break for a false answer. then later on as i learn more then expand it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T22:32:53.320", "Id": "415943", "Score": "0", "body": "If you only want to ask these type of questions, then this may work for now. However, as you can imagine, creating a game, even a text based game, can get complex fairly quickly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T23:57:58.310", "Id": "215066", "ParentId": "215052", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T19:10:27.967", "Id": "215052", "Score": "0", "Tags": [ "python", "game" ], "Title": "Python text-based game" }
215052
<p>I am looking to get some feedback on <strong>Python 3.6</strong>+ project. Specifically I'm looking to improve my skills and make myself a more attractive prospective employee. I plan to use my Github repo(s) as a demonstration of my skills and knowledge.</p> <p>Summary: </p> <p>It's a 'bot' which connects to the Twitch.tv IRC, retrieves a list of the top streamers from the Twitch API, joins their chat channel, and logs the messages sent by users. It should be completely PEP8 complaint aside from the line lengths. Do you believe it's critical to adhere to the line length, I was seeing mixed opinions of 'yes absolutely' and 'no just make sure it's consistent and readable'?</p> <p><a href="https://github.com/disabledtech/Twitch-IRC-Logger" rel="nofollow noreferrer">Github repo</a></p> <p><strong>twitch_irc_bot.py</strong></p> <pre><code>import socket import time import requests from codecs import decode import os import logging import logging.handlers logging.getLogger("urllib3").setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) # Set our logger's time format to UTC logging.Formatter.converter = time.gmtime # Where logs will be stored. logs_folder = os.path.join(os.getcwd(), 'logs/') # Make the folder if it does not exist. if not os.path.exists(logs_folder): os.mkdir(logs_folder) # Set up the logger. Log files will rotated saved every 10 minutes. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s — %(message)s', datefmt='%Y-%m-%d_%H:%M:%S', handlers=[logging.handlers.TimedRotatingFileHandler(logs_folder + 'chat.log', # Active log name when='M', interval=10, # Log rotation in min. encoding='utf-8')]) class TwitchBot(object): """ A bot which joins multiple Twitch IRC channels and records their messages to a rotating log file. The channels it joins are from a list of the streams with the most current viewers retrieved from the Twitch API. The number of streams to log can be configured up to a max. of 100. """ def __init__(self, username, token, client_id, game='', refresh_interval=60, limit=25): """ Initializes TwitchBot :param username: What the bot will call itself when joining the IRC server. Do not use the same name as a popular streamer, it will break the script. :param token: The OAuth token used to join the Twitch IRC. :param client_id: The client_id of your Twitch dev. application. See: https://dev.twitch.tv/docs/v5 :param game: The game that you want all streams to be playing. e.g. 'Overwatch'. Default: Any game (''). :param refresh_interval: How often (in seconds) to call __update() and get a new list of top streams. Default: 60 :param limit: The maximum numbers of streams to join. Default: 25 Max: 100 """ self.__server = 'irc.chat.twitch.tv' # Twitch IRC IP Address self.__port = 6667 # Twitch IRC Port self.username = username self.token = token self.client_id = client_id self.refresh_interval = refresh_interval self.game = game self.limit = limit # Get an initial list of streams. self.channel_list = self.__get_top_streamers() # Connect to the Twitch IRC. self.__connect() def __connect(self): """ Connect to the twitch.tv IRC server and then JOIN each IRC channel in self.channel_list :return: None """ self.sock_connection = socket.socket() self.sock_connection.connect((self.__server, self.__port)) self.sock_connection.send('PASS {}\n'.format(self.token).encode('utf-8')) self.sock_connection.send('NICK {}\n'.format(self.username).encode('utf-8')) # Call __join_channel() for all channels in the channel_list for channel in self.channel_list: self.__join_channel(channel) def __join_channel(self, channel): """ Joins the specified twitch.tv IRC channel :param channel: The twitch.tv IRC channel to join. Usually (always?) the caster's channel name. :return: None """ self.sock_connection.send('JOIN #{}\n'.format(channel).encode('utf-8')) def __leave_channel(self, channel): """ Leaves the specified twitch.tv IRC channel :param channel: The twitch.tv IRC channel to leave. Usually (always?) the caster's channel name. :return: None """ self.sock_connection.send('PART {}\n'.format(channel).encode('utf-8')) def __update(self): """ Updates which channels we're logging. Fetches a new list of streams from __get_top_streamers() and compares it with our current list of streams. Compares the lists to get which streams have entered/left the top 100. Calls __leave_channel/__join_channel on these lists as needed. :return: None """ new_channels = self.__get_top_streamers() old_channels = self.channel_list # Compares the stream lists to find which streams to join/leave. channels_to_leave = list(set(old_channels) - set(new_channels)) channels_to_join = list(set(new_channels) - set(old_channels)) # Leave streams in not in top 100 for channel in channels_to_leave: self.__leave_channel(channel) # Join streams new to the top 100 for channel in channels_to_join: self.__join_channel(channel) # Update the list of channels we're currently in. self.channel_list = new_channels def __get_top_streamers(self): """ Gets the 100 channels with the most current viewers. Uses the param settings from initialization (self.game, self.limit) to determine which and how many streams to grab. :return: A list of channels in the top *self.limit* system currently. """ # Parameters for the Twitch API request twitch_api_params = { 'client_id': self.client_id, # Required 'api_version': 5, # Required 'game': self.game, # Optional 'limit': self.limit # Optional, defaults to 25. Max is 100. } names = [] # Request the JSON data from twitch. channel_list = requests.get('https://api.twitch.tv/kraken/streams/', params=twitch_api_params).json() # Extract channel names from the JSON data. for name in channel_list['streams']: names.append(name['channel']['name']) return names def __close_connection(self): """ Close our socket connection. :return: """ print('Exiting...') self.sock_connection.close() exit(0) def __log_message(self, response): """ Save a valid message to your logs. A valid message is one that is NOT a PING from the server, IS greater than 0 in length, and does NOT contain our own name (such as those from the IRC server when we first join). Choosing the same *username* for the bot as a popular streamer will probably (100%) break the logging for said streamer's channel at best. I have no idea what a worst-case-scenario would be (disabled for 'impersonation'?). Investigate at your own discretion. :param response: A single message response from the server. :return: """ # Send a PONG if the server sends a PING if response.startswith('PING'): self.sock_connection.send('PONG\n'.encode('utf-8')) elif len(response) &gt; 0 and self.username not in response: logging.info(response.rstrip('\r\r\n')) def run(self): """ Run the script until user interruption. :return: None """ # A flag used to determine if it'stime to call __update(). top_100_check = time.time() while True: try: # Get response from the IRC server try: response = decode(self.sock_connection.recv(2048), encoding='utf-8') except UnicodeDecodeError: # TODO Handle this better # Sometimes this exception is raised, however it happens extremely # rarely (&lt; ~0.1%) and is not significant unless it is absolutely critical # you do not miss anything. At the moment we simply skip over these errors. continue # Sometimes in a busy channel many messages are received # in one 'response' and we need to split them apart. See # https://stackoverflow.com/q/28859961 for a longer and # more detailed explanation by someone else with the # same issue. # # All message end with '\r\n' so we can reliably count/split # them this way. line_count = response.count("\r\n") if line_count &gt; 1: messages = response.split("\r\n") for single_msg in messages: self.__log_message(single_msg) else: self.__log_message(response) # Check if the time now is more than the refresh_interval + the # last time we checked the top 100. if time.time() &gt; top_100_check + self.refresh_interval: # Update the time we last checked to now. top_100_check = time.time() # Update our channel list. self.__update() # Shut down 'gracefully' on keyboard interrupt. except KeyboardInterrupt: self.__close_connection() </code></pre> <p><strong>run_bot.py</strong></p> <pre><code>from twitch_irc_bot import TwitchBot from configparser import ConfigParser import os def main(): config = ConfigParser() # Try to find the config file, if it does not exist, create one. if not os.path.exists(os.path.join(os.getcwd(), 'config.ini')): print("Config file not found. Creating one...") __create_config(config) print("Config file created. Please fill out the settings.") exit(0) config.read('config.ini') username = config['TWITCH_BOT_SETTINGS']['username'] token = config['TWITCH_BOT_SETTINGS']['token'] client_id = config['TWITCH_BOT_SETTINGS']['client_id'] channel_limit = config['TWITCH_BOT_SETTINGS'].getint('channel_limit') # Initialize bot. bot = TwitchBot(username=username, token=token, client_id=client_id, limit=channel_limit) # Runs the bot until user interrupts it. bot.run() def __create_config(config): """ Creates a fresh config file with the needed parameters. :param config: a ConfigParser() object. """ config['TWITCH_BOT_SETTINGS'] = {'username': '', 'token': '', 'client_id': '', 'channel_limit': ''} with open('config.ini', 'w') as new_config_files: config.write(new_config_files) if __name__ == '__main__': main() </code></pre> <p><strong>config.ini</strong></p> <pre><code>[TWITCH_BOT_SETTINGS] username = token = client_id = channel_limit = </code></pre> <p>Thanks for your time everyone, I appreciate it. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:39:55.833", "Id": "415844", "Score": "2", "body": "Hello, just to tell you, I guess your Github repo is *private* so the link you provided result in a 404 error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T10:31:03.407", "Id": "415878", "Score": "1", "body": "To simply react to one of your first question, one of the first statement of PEP8 boils down to \"these are not hard rules, if you need/want to deviate, just make sure it's consistent and readable\". That being said, PEP8 compliant code looks more like Python than others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T23:36:35.817", "Id": "415949", "Score": "0", "body": "Thanks, Ced. It was private, fixed it now.\n\nThanks for your input, Mathias, that makes sense." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:04:08.050", "Id": "215057", "Score": "3", "Tags": [ "python" ], "Title": "Script that logs chat data from Twitch.tv" }
215057
<p>I wanted to ask if this project is valid to state on a resume for entry-level python developer and if the code is presentable to say a job interviewer.</p> <p>github link: <a href="https://github.com/basvdvelden/Origin" rel="nofollow noreferrer">full project</a></p> <p>(If this is not the place to ask this, I will remove above part of this post. By all means let me know)</p> <p>The code needing most attention is a method(moves_safety_check()) in a match class checking the legality of the pseudo legal moves. Code doesn't have to change but I think the function is too long and over complicated, thus I would like tips for condensing the function with readability. Also, is the way i'm writing docstrings acceptable?</p> <pre><code>from chess.board import Board from copy import deepcopy from chess.moves import * from chess.king_attacking_line import KingTargetingPseudoLine, DangerLines, SquaresTargeted import json all_ps_moves = ps_moves_per_loc() # dict with all board locations as keys and # dictionaries as values having keys for each direction # with a list of moves from that location in that # direction as values. class Match: def __init__(self, state=Board().board, turn='white', wcks=True, wcqs=True, bcks=True, bcqs=True): self.white_can_castle = {'ks': wcks, 'qs': wcqs} self.black_can_castle = {'ks': bcks, 'qs': bcqs} self.state = state self.fen = convert_to_fen(self.state, turn, wcks, wcqs, bcks, bcqs) self.black_pieces_locations = {} self.white_pieces_locations = {} self.board_locations_occupied_by_black = {} self.board_locations_occupied_by_white = {} self.ps_black_moves = {} self.ps_white_moves = {} self.black_moves = {} self.white_moves = {} self.set_piece_locations() self.continuous_non_capped_turns = 0 try: self.black_king_targeting_ps_lines = DangerLines(self.board_locations_occupied_by_black, self.board_locations_occupied_by_white, self.black_pieces_locations['K']) self.white_king_targeting_ps_lines = DangerLines(self.board_locations_occupied_by_white, self.board_locations_occupied_by_black, self.white_pieces_locations['K']) except KeyError: for row in self.state: print(row) raise KeyError('King is not in board!') self.king_attacking_line = [] self.white_non_iterative = SquaresTargeted() # keeps track of pseudo legal moves belonging to a pawn, knight or king. self.black_non_iterative = SquaresTargeted() self.b_check = False self.w_check = False self.turn = turn self.king_attackers_locations = [] self.check_mate = False self.winner = None self.draw = False self.moves_keys_history = {'wcc': deepcopy(self.white_can_castle), 'bcc': deepcopy(self.black_can_castle), 'keys': [], 'moves': [], 'state': self.state, 'fen': self.fen} self.key = None self.trace = [] self.set_all_ps_moves() def is_in_black_ps_moves(self, move): """ Goes through black's pseudo moves and checks if given move is in the black's pseudo moves. :param move: see if it is in black pseudo moves :type move: tuple :return: True if move is in black pseudo moves else False :rtype: bool """ for key in self.ps_black_moves: if 'Q' in key or 'B' in key or 'R' in key: for direction in self.ps_black_moves[key]: if move in self.ps_black_moves[key][direction]: return True return False def is_in_white_ps_moves(self, move): """ Goes through white's pseudo moves and checks if given move is in the white's pseudo moves. :param move: see if it is in white pseudo moves :type move: tuple :return: True if move is in white pseudo moves else False :rtype: bool """ for key in self.ps_white_moves: if 'Q' in key or 'B' in key or 'R' in key: for direction in self.ps_white_moves[key]: if move in self.ps_white_moves[key][direction]: return True return False def legal_line(self, moves, color, per_mov=False, board=False): """ Returns legal moves. :param moves: pseudo moves :param color: side of pseudo moves given, must be 'black' or 'white' :param per_mov: set to True if moves given are of a pawn king or knight :param board: board to use check the moves given, default is self.state :type moves: list :type color: str :type per_mov: bool :type board: tuple :return: legal moves :rtype: list """ board = self.state if not board else board new_moves = [] if color == 'white': me, opp = 'w', 'b' else: me, opp = 'b', 'w' if not per_mov: for move in moves: if me in str(board[move[0]][move[1]]): moves = new_moves return moves elif opp in str(board[move[0]][move[1]]): new_moves.append(move) return new_moves elif me not in str(board[move[0]][move[1]]): new_moves.append(move) else: for move in moves: if me not in str(board[move[0]][move[1]]): new_moves.append(move) return new_moves def set_piece_locations(self): """ Called one time at initialisation, sets locations for pieces of both sides. :return: """ for num in range(2): pieces = {} locations_occupied = {} me = 'w' if num == 0 else 'b' for i, row in enumerate(self.state): for j, sq in enumerate(row): if me in str(sq): key = sq.replace(me, '') pieces[key] = (i, j) locations_occupied['({}, {})'.format(i, j)] = key if num == 0: self.white_pieces_locations = pieces self.board_locations_occupied_by_white = locations_occupied else: self.black_pieces_locations = pieces self.board_locations_occupied_by_black = locations_occupied def get_king_targeting_lines(self, color, loc=False, get_direction=False): """ Returns the pieces and their lines that target the given location, also returns their direction at index 1* if get_direction is set to True. :param color: side who needs the targeting lines, must be 'white' or 'black' :param loc: location to use as the target :param get_direction: True if the direction key is also needed :type color: str :type loc: tuple :type get_direction: bool :return: a tuple of keys, directions*, lines that target the given location :rtype: tuple """ if color == 'white': ps_move_dict = self.ps_black_moves if not loc: king = self.white_pieces_locations['K'] else: king = loc else: ps_move_dict = self.ps_white_moves if not loc: king = self.black_pieces_locations['K'] else: king = loc keys = [] directions = [] lines = [] for key in ps_move_dict: if 'Q' in key or 'B' in key or 'R' in key: for direction in ps_move_dict[key]: if king in ps_move_dict[key][direction]: if get_direction: directions.append(direction) keys.append(key) lines.append(ps_move_dict[key][direction]) if get_direction: return keys, directions, lines else: return keys, lines def moves_safety_check(self, color): # self.state is a tuple of 8 lists with length 8 as chess board. # k_targeting_ps_lines is a list containing data of pieces(only queens, bishops or rooks) targeting the king # with their pseudo legal moves. # # As an example say the black king is at position (3, 3) and a black pawn at (3, 4). # If a rook or queen in this case is at position (3, 5) or (3, 6) or (3, 7), then that rook or queen is pseudo- # targeting the king. # if no piece is pseudo targeting the king when this method is called, then we don't have to check for any # move except for the king's moves if that move would result in check. # If however the king is targeted, then we check for each piece belonging to the side of aforementioned king if # that piece is in a pseudo legal line targeting it's king. If so, we see if it would result in check if that # piece moved to the location provided. # # If not in a pseudo legal line targeting the king, then we know it's safe for that piece to move since it's not # protecting their king. Unless of course it's check, this means we only add moves which captures the piece # having king in check or which would protect the king. # The line targeting the king when it's check is self.king_attacking_line """ Checks if legal moves will cause check in which case the move is removed from legal moves. :param color: side to have moves checked, either 'black' or 'white' :type color: str """ def kings_move_is_dangerous(): """ Is called if the move is in the opponent's pseudo moves. If move would result in check, does not add to leg_moves. """ attackers, lines = self.get_king_targeting_lines(color, loc=move) row = piece_locations[key][0] col = piece_locations[key][1] safe = True for attacker, line in zip(attackers, lines): sim_board = deepcopy(self.state) sim_board[row][col] = 1 sim_board[move[0]][move[1]] = me + key if move[1] == col - 3: sim_board[row][0] = 1 sim_board[row][2] = me + 'R1' elif move[1] == col + 2: sim_board[row][7] = 1 sim_board[row][5] = me + 'R2' if move in self.legal_line(line, opp_color, board=sim_board): safe = False break if safe: safe_moves.append(move) if color == 'white': move_dict = self.white_moves k_targeting_ps_lines = self.white_king_targeting_ps_lines opp_non_iter_moves = self.black_non_iterative is_in_opp_moves = self.is_in_black_ps_moves opp, me = 'b', 'w' opp_color = 'black' check = self.w_check piece_locations = self.white_pieces_locations pawn_one_step_two_steps, start_row = (-1, -2), 6 else: move_dict = self.black_moves k_targeting_ps_lines = self.black_king_targeting_ps_lines opp_non_iter_moves = self.white_non_iterative is_in_opp_moves = self.is_in_white_ps_moves opp, me = 'w', 'b' opp_color = 'white' check = self.b_check piece_locations = self.black_pieces_locations pawn_one_step_two_steps, start_row = (1, 2), 1 for key in move_dict: if 'Q' in key or 'R' in key or 'B' in key: if check: if len(self.king_attackers_locations) &gt; 1: move_dict[key] = None continue if k_targeting_ps_lines.is_targeted(piece_locations[key]): for direction in move_dict[key]: safe_moves = [] for move in move_dict[key][direction]: if k_targeting_ps_lines.would_be_check(piece_locations[key], move, already_check=check): break elif move in self.king_attacking_line or move in self.king_attackers_locations: safe_moves.append(move) move_dict[key][direction] = safe_moves else: for direction in move_dict[key]: safe_moves = [] for move in move_dict[key][direction]: if move in self.king_attacking_line or move in self.king_attackers_locations: safe_moves.append(move) move_dict[key][direction] = safe_moves elif k_targeting_ps_lines: if k_targeting_ps_lines.is_targeted(piece_locations[key]): for direction in move_dict[key]: safe_moves = [] for move in move_dict[key][direction]: if k_targeting_ps_lines.would_be_check(piece_locations[key], move): break safe_moves.append(move) move_dict[key][direction] = safe_moves bad_directions = [] for direction in move_dict[key]: if not move_dict[key][direction]: bad_directions.append(direction) for direction in bad_directions: del move_dict[key][direction] elif 'N' in key: if not move_dict[key]: continue if check: if len(self.king_attackers_locations) &gt; 1: move_dict[key] = None continue if k_targeting_ps_lines.is_targeted(piece_locations[key]): if k_targeting_ps_lines.would_be_check(piece_locations[key], move_dict[key][0], already_check=check): move_dict[key] = None continue safe_moves = [] for move in move_dict[key]: if move in self.king_attacking_line or move in self.king_attackers_locations: safe_moves.append(move) move_dict[key] = safe_moves if safe_moves else None continue else: safe_moves = [] for move in move_dict[key]: if move in self.king_attacking_line or move in self.king_attackers_locations: safe_moves.append(move) move_dict[key] = safe_moves if safe_moves else None continue elif k_targeting_ps_lines: if k_targeting_ps_lines.is_targeted(piece_locations[key]): if k_targeting_ps_lines.would_be_check(piece_locations[key], move_dict[key][0]): move_dict[key] = None continue elif 'P' in key: if piece_locations[key][0] + pawn_one_step_two_steps[0] not in range(8): move_dict[key] = None continue one_step = (piece_locations[key][0] + pawn_one_step_two_steps[0], piece_locations[key][1]) safe_moves = [] if check: if len(self.king_attackers_locations) &gt; 1: move_dict[key] = None continue danger = False if k_targeting_ps_lines.is_targeted(piece_locations[key]): danger = True for move in move_dict[key]: if k_targeting_ps_lines.would_be_check(piece_locations[key], move, already_check=check): continue if move in self.king_attackers_locations: safe_moves.append(move) else: for move in move_dict[key]: if move in self.king_attackers_locations: safe_moves.append(move) if danger: if str(self.state[one_step[0]][one_step[1]]) == '1': if k_targeting_ps_lines.would_be_check(piece_locations[key], one_step): move_dict[key] = safe_moves if safe_moves else None continue if one_step in self.king_attacking_line: safe_moves.append(one_step) if piece_locations[key][0] == start_row: two_steps = (piece_locations[key][0] + pawn_one_step_two_steps[1], piece_locations[key][1]) if str(self.state[two_steps[0]][two_steps[1]]) == '1': if two_steps in self.king_attacking_line: safe_moves.append(two_steps) else: if str(self.state[one_step[0]][one_step[1]]) == '1': if one_step in self.king_attacking_line: safe_moves.append(one_step) if piece_locations[key][0] == start_row: two_steps = (piece_locations[key][0] + pawn_one_step_two_steps[1], piece_locations[key][1]) if str(self.state[two_steps[0]][two_steps[1]]) == '1': if two_steps in self.king_attacking_line: safe_moves.append(two_steps) elif k_targeting_ps_lines: danger = False if k_targeting_ps_lines.is_targeted(piece_locations[key]): danger = True for move in move_dict[key]: if k_targeting_ps_lines.would_be_check(piece_locations[key], move): continue else: if opp in str(self.state[move[0]][move[1]]): safe_moves.append(move) else: for move in move_dict[key]: if opp in str(self.state[move[0]][move[1]]): safe_moves.append(move) if str(self.state[one_step[0]][one_step[1]]) == '1': if danger: if k_targeting_ps_lines.would_be_check(piece_locations[key], one_step): move_dict[key] = safe_moves if safe_moves else None continue else: safe_moves.append(one_step) if piece_locations[key][0] == start_row: two_steps = (piece_locations[key][0] + pawn_one_step_two_steps[1], piece_locations[key][1]) if str(self.state[two_steps[0]][two_steps[1]]) == '1': safe_moves.append(two_steps) else: safe_moves.append(one_step) if piece_locations[key][0] == start_row: two_steps = (piece_locations[key][0] + pawn_one_step_two_steps[1], piece_locations[key][1]) if str(self.state[two_steps[0]][two_steps[1]]) == '1': safe_moves.append(two_steps) else: for move in move_dict[key]: if opp in str(self.state[move[0]][move[1]]): safe_moves.append(move) if str(self.state[one_step[0]][one_step[1]]) == '1': safe_moves.append(one_step) if piece_locations[key][0] == start_row: two_steps = (piece_locations[key][0] + pawn_one_step_two_steps[1], piece_locations[key][1]) if str(self.state[two_steps[0]][two_steps[1]]) == '1': safe_moves.append(two_steps) move_dict[key] = safe_moves if safe_moves else None else: safe_moves = [] if check: for move in move_dict[key]: if move in self.king_attacking_line or move in opp_non_iter_moves.move_set: continue elif is_in_opp_moves(move): kings_move_is_dangerous() else: safe_moves.append(move) move_dict[key] = safe_moves if safe_moves else None else: for move in move_dict[key]: if move in opp_non_iter_moves.move_set: continue elif is_in_opp_moves(move): kings_move_is_dangerous() else: safe_moves.append(move) move_dict[key] = safe_moves keys_to_del = [] for key in move_dict: if not move_dict[key]: keys_to_del.append(key) for key in keys_to_del: del move_dict[key] if not move_dict: self.check_mate = True self.winner = 'black' if color == 'white' else 'white' def set_all_ps_moves(self): """ Is called one time at initialisation, sets all the pseudo-legal moves for both sides. """ for key in self.white_pieces_locations: if 'Q' in key or 'R' in key or 'B' in key: self.ps_white_moves[key] = {} self.update_ps_iterative_moves(key, 'white') elif 'P' in key or 'N' in key: self.update_ps_non_iterative_moves(key, 'white') else: self.update_king_moves('white') for key in self.black_pieces_locations: if 'Q' in key or 'R' in key or 'B' in key: self.ps_black_moves[key] = {} self.update_ps_iterative_moves(key, 'black') elif 'P' in key or 'N' in key: self.update_ps_non_iterative_moves(key, 'black') else: self.update_king_moves('black') if self.turn == 'white': self.moves_safety_check(color='black') self.moves_safety_check(color='white') else: self.moves_safety_check(color='white') self.moves_safety_check(color='black') def check_or_king_ps_targeted(self, key, loc, color): """ Checks if it is check or if the opponent's king is targeted by the pseudo moves of the given piece. :param key: piece, cannot be a pawn, knight or king :param loc: location of given key :param color: side of given key must be 'black' or 'white' :type key: str :type loc: tuple :type color: str """ if color == 'white': try: king_loc = self.black_pieces_locations['K'] except KeyError: self.save_game(fn='king_loc_key_error.json') raise opp_k_targeting_ps_lines = self.black_king_targeting_ps_lines move_dict = self.white_moves ps_move_dict = self.ps_white_moves else: try: king_loc = self.white_pieces_locations['K'] except KeyError: self.save_game(fn='king_loc_key_error.json') raise opp_k_targeting_ps_lines = self.white_king_targeting_ps_lines move_dict = self.black_moves ps_move_dict = self.ps_black_moves ps_moves = [] for direction in ps_move_dict[key]: ps_moves.append(ps_move_dict[key][direction]) if 'Q' in key: directions = ('tr', 'tl', 'br', 'bl', 'u', 'd', 'r', 'l') elif 'R' in key: directions = ('u', 'd', 'r', 'l') else: directions = ('tr', 'tl', 'br', 'bl') if len(ps_moves) == 4: leg_moves = (self.legal_line(ps_moves[0], color), self.legal_line(ps_moves[1], color), self.legal_line(ps_moves[2], color), self.legal_line(ps_moves[3], color)) else: leg_moves = (self.legal_line(ps_moves[0], color), self.legal_line(ps_moves[1], color), self.legal_line(ps_moves[2], color), self.legal_line(ps_moves[3], color), self.legal_line(ps_moves[4], color), self.legal_line(ps_moves[5], color), self.legal_line(ps_moves[6], color), self.legal_line(ps_moves[7], color)) move_dict[key] = {} for index, direction in enumerate(directions): if leg_moves[index]: move_dict[key][direction] = leg_moves[index] i = 0 for ps_line, leg_line in zip(ps_moves, leg_moves): if king_loc in ps_line: opp_k_targeting_ps_lines.append_x(KingTargetingPseudoLine(key, loc, directions[i], ps_line)) if king_loc in leg_line: self.king_attackers_locations.append(loc) self.king_attacking_line.extend(leg_line) self.w_check = True if color == 'black' else self.w_check self.b_check = True if color == 'white' else self.b_check i += 1 def update_legal_iterative_moves(self, key, color): """ This sets the reachable squares a.k.a legal moves. ps_moves must already be set! :param key: piece to have legal moves updated, cannot be a pawn, knight or king :param color: side of the piece, must be 'black' or 'white' :type key: str :type color: str """ ps_move_dict = self.ps_white_moves if color == 'white' else self.ps_black_moves leg_move_dict = self.white_moves if color == 'white' else self.black_moves leg_move_dict[key] = {} if 'Q' in key: tr, tl = ps_move_dict[key]['tr'], ps_move_dict[key]['tl'] br, bl = ps_move_dict[key]['br'], ps_move_dict[key]['bl'] u, d = ps_move_dict[key]['u'], ps_move_dict[key]['d'] r, l = ps_move_dict[key]['r'], ps_move_dict[key]['l'] leg_move_dict[key]['tr'], leg_move_dict[key]['tl'] = self.legal_line(tr, color), self.legal_line(tl, color) leg_move_dict[key]['br'], leg_move_dict[key]['bl'] = self.legal_line(br, color), self.legal_line(bl, color) leg_move_dict[key]['u'], leg_move_dict[key]['d'] = self.legal_line(u, color), self.legal_line(d, color) leg_move_dict[key]['r'], leg_move_dict[key]['l'] = self.legal_line(r, color), self.legal_line(l, color) elif 'B' in key: tr, tl = ps_move_dict[key]['tr'], ps_move_dict[key]['tl'] br, bl = ps_move_dict[key]['br'], ps_move_dict[key]['bl'] leg_move_dict[key]['tr'], leg_move_dict[key]['tl'] = self.legal_line(tr, color), self.legal_line(tl, color) leg_move_dict[key]['br'], leg_move_dict[key]['bl'] = self.legal_line(br, color), self.legal_line(bl, color) else: u, d = ps_move_dict[key]['u'], ps_move_dict[key]['d'] r, l = ps_move_dict[key]['r'], ps_move_dict[key]['l'] leg_move_dict[key]['u'], leg_move_dict[key]['d'] = self.legal_line(u, color), self.legal_line(d, color) leg_move_dict[key]['r'], leg_move_dict[key]['l'] = self.legal_line(r, color), self.legal_line(l, color) def update_ps_iterative_moves(self, key, color): """ This sets the pseudo legal lines. :param key: piece to have pseudo legal moves updated, cannot be a pawn, knight or king :param color: side of the piece, must be 'black' or 'white' :type key: str :type color: str """ loc = self.white_pieces_locations[key] if color == 'white' else self.black_pieces_locations[key] ps_move_dict = self.ps_white_moves if color == 'white' else self.ps_black_moves ps_move_dict[key] = {} pmk = str(loc) if 'Q' in key: ps_move_dict[key]['tr'], ps_move_dict[key]['tl'] = all_ps_moves[pmk]['tr'], all_ps_moves[pmk]['tl'] ps_move_dict[key]['br'], ps_move_dict[key]['bl'] = all_ps_moves[pmk]['br'], all_ps_moves[pmk]['bl'] ps_move_dict[key]['u'], ps_move_dict[key]['d'] = all_ps_moves[pmk]['u'], all_ps_moves[pmk]['d'] ps_move_dict[key]['r'], ps_move_dict[key]['l'] = all_ps_moves[pmk]['r'], all_ps_moves[pmk]['l'] elif 'B' in key: ps_move_dict[key]['tr'], ps_move_dict[key]['tl'] = all_ps_moves[pmk]['tr'], all_ps_moves[pmk]['tl'] ps_move_dict[key]['br'], ps_move_dict[key]['bl'] = all_ps_moves[pmk]['br'], all_ps_moves[pmk]['bl'] else: ps_move_dict[key]['u'], ps_move_dict[key]['d'] = all_ps_moves[pmk]['u'], all_ps_moves[pmk]['d'] ps_move_dict[key]['r'], ps_move_dict[key]['l'] = all_ps_moves[pmk]['r'], all_ps_moves[pmk]['l'] self.check_or_king_ps_targeted(key, loc, color) def update_legal_non_iterative_moves(self, key, color): """ This sets the legal moves. ps_moves must already be set! :param key: piece to have legal moves updated, must be a pawn, knight or king :param color: side of the piece, must be 'black' or 'white' :type key: str :type color: str """ if key == 'K': self.update_king_moves(color) return moves = self.ps_white_moves[key] if color == 'white' else self.ps_black_moves[key] leg_move_dict = self.white_moves if color == 'white' else self.black_moves leg_move_dict[key] = self.legal_line(moves, color, per_mov=True) def update_ps_non_iterative_moves(self, key, color): """ This sets pseudo legal moves. :param key: piece to have legal moves updated, must be a pawn, knight or king :param color: side of the piece, must be 'black' or 'white' :type key: str :type color: str """ if color == 'white': loc = self.white_pieces_locations[key] try: king_loc = self.black_pieces_locations['K'] except KeyError: self.save_game(fn='king_loc_non_it.json') raise ps_moves = self.ps_white_moves move_dict = self.white_moves non_it_moves = self.white_non_iterative else: loc = self.black_pieces_locations[key] try: king_loc = self.white_pieces_locations['K'] except KeyError: self.save_game(fn='king_loc_non_it.json') raise ps_moves = self.ps_black_moves move_dict = self.black_moves non_it_moves = self.black_non_iterative if 'P' in key: moves = ps_pawn_cap_moves(loc, color) else: moves = ps_knight_moves(loc) non_it_moves.assign(key, moves) ps_moves[key] = moves leg_moves = self.legal_line(moves, color, per_mov=True) move_dict[key] = leg_moves if king_loc in moves: if color == 'white': self.b_check = True else: self.w_check = True self.king_attackers_locations.append(loc) def king_moved(self, color): """ Updates king_targeting_ps_lines of the side whose king moved. :param color: side whose king moved, must be 'black' or 'white' :type color: str """ if color == 'white': loc = self.white_pieces_locations['K'] is_in_opp_moves = self.is_in_black_ps_moves danger_lines = self.white_king_targeting_ps_lines opp_pieces = self.black_pieces_locations else: loc = self.black_pieces_locations['K'] is_in_opp_moves = self.is_in_white_ps_moves danger_lines = self.black_king_targeting_ps_lines opp_pieces = self.white_pieces_locations danger_lines.king_moved(loc) if is_in_opp_moves(loc): keys, dirs, lines = self.get_king_targeting_lines(color, loc=loc, get_direction=True) for key, direction, line in zip(keys, dirs, lines): if key in danger_lines.keys: continue attacker_loc = opp_pieces[key] danger_lines.append_x(KingTargetingPseudoLine(key, attacker_loc, direction, line)) def update_king_moves(self, color): """ Updates moves for given color's king, checks if can castle. :param color: side of king to have moves updated """ if color == 'white': loc = self.white_pieces_locations['K'] can_castle = self.white_can_castle ps_moves = self.ps_white_moves move_dict, pieces = self.white_moves, self.white_pieces_locations non_it_moves = self.white_non_iterative else: loc = self.black_pieces_locations['K'] can_castle = self.black_can_castle ps_moves = self.ps_black_moves move_dict, pieces = self.black_moves, self.black_pieces_locations non_it_moves = self.black_non_iterative moves = ps_king_moves(loc, color) ps_moves['K'] = moves non_it_moves.assign('K', moves) leg_moves = self.legal_line(moves, color, per_mov=True) if can_castle['ks']: ps_moves['K'].append((pieces['K'][0], 6)) for col in range(5, 7): if self.state[pieces['K'][0]][col] != 1: break if col == 6: leg_moves.append((pieces['K'][0], 6)) if can_castle['qs']: ps_moves['K'].append((pieces['K'][0], 1)) for col in range(3, 0, -1): if self.state[pieces['K'][0]][col] != 1: break if col == 1: leg_moves.append((pieces['K'][0], 1)) move_dict['K'] = None if leg_moves: move_dict['K'] = leg_moves else: del move_dict['K'] def update_logs(self, key, move, old_loc, castled): """ Updates classes whose definitions are located in king_attacking_line.py. These check if certain moves are allowed and won't cause check. Also checks if pawns reached the final rank. :param key: last moved piece :param move: last move made :param old_loc: old location of last moved piece :param castled: did a king castle, only True if piece is king """ if self.turn == 'white': opp_k_targeting_ps_lines, opp_non_iter_moves = self.black_king_targeting_ps_lines, self.black_non_iterative pieces_locations, inv_pieces = self.white_pieces_locations, self.board_locations_occupied_by_white ps_moves, moves = self.ps_white_moves, self.white_moves pawn_edge_row = 0 can_castle = self.white_can_castle else: opp_k_targeting_ps_lines, opp_non_iter_moves = self.white_king_targeting_ps_lines, self.white_non_iterative pieces_locations, inv_pieces = self.black_pieces_locations, self.board_locations_occupied_by_black ps_moves, moves = self.ps_black_moves, self.black_moves pawn_edge_row = 7 can_castle = self.black_can_castle if key == 'R1': can_castle['qs'] = False elif key == 'R2': can_castle['ks'] = False elif key == 'K': can_castle['ks'], can_castle['qs'] = False, False if castled: if move[1] == 1: pieces_locations['R1'] = (move[0], 2) inv_pieces[str((move[0], 2))] = 'R1' try: del inv_pieces[str((move[0], 0))] except KeyError: self.save_game(fn='castled_r1_.json') raise KeyError("couldn't delete old location of R1") opp_k_targeting_ps_lines.delete_line('R1') self.update_ps_iterative_moves('R1', self.turn) elif move[1] == 6: pieces_locations['R2'] = (move[0], 5) inv_pieces[str((move[0], 5))] = 'R2' try: del inv_pieces[str((move[0], 7))] except KeyError: self.save_game(fn='castled_r2_.json') raise KeyError("couldn't delete old location of R2") opp_k_targeting_ps_lines.delete_line('R2') self.update_ps_iterative_moves('R2', self.turn) else: raise ValueError('Castled was passed as true but the move is not a legal castle move.') elif 'P' in key and move[0] == pawn_edge_row: non_it_moves = self.white_non_iterative if self.turn == 'white' else self.black_non_iterative non_it_moves.piece_died(key) del pieces_locations[key], ps_moves[key], moves[key] self.key = 'Q' + key[1] key = self.key ps_moves[key] = {} self.state[move[0]][move[1]] = self.turn[0] + key pieces_locations[key] = move inv_pieces[str(move)] = key try: del inv_pieces[str(old_loc)] except KeyError: self.save_game(fn='del_inv_pieces.json') raise if opp_k_targeting_ps_lines.is_king_attacker(key): opp_k_targeting_ps_lines.delete_line(key) if opp_k_targeting_ps_lines.is_targeted(old_loc): def is_check(): attacker = opp_k_targeting_ps_lines.get_attacker() self.king_attackers_locations.append(attacker[0]) try: att_key = inv_pieces[str(attacker[0])] except KeyError: print(opp_k_targeting_ps_lines.keys) self.save_game(fn='att_key_error.json') raise KeyError('Something went wrong!') ps_line = ps_moves[att_key][attacker[1]] self.king_attacking_line.extend(self.legal_line(ps_line, self.turn)) if self.turn == 'white': self.b_check = opp_k_targeting_ps_lines.will_be_check(old_loc) if self.b_check: is_check() else: self.w_check = opp_k_targeting_ps_lines.will_be_check(old_loc) if self.w_check: is_check() def is_piece_capped(self, move): """ Checks if a piece was captured, and updates data in response. :param move: last move made """ if self.turn == 'white': danger_lines = self.white_king_targeting_ps_lines opp_ps_moves, opp_moves, opp_non_it_moves = self.ps_black_moves, self.black_moves, self.black_non_iterative opp_pieces, opp_inv_pieces = self.black_pieces_locations, self.board_locations_occupied_by_black opp_can_castle = self.black_can_castle else: danger_lines = self.black_king_targeting_ps_lines opp_ps_moves, opp_moves, opp_non_it_moves = self.ps_white_moves, self.white_moves, self.white_non_iterative opp_pieces, opp_inv_pieces = self.white_pieces_locations, self.board_locations_occupied_by_white opp_can_castle = self.white_can_castle if self.state[move[0]][move[1]] != 1: self.continuous_non_capped_turns = 0 capped = self.state[move[0]][move[1]][1:] if 'P' not in capped and 'N' not in capped: if 'R1' in capped: opp_can_castle['qs'] = False elif 'R2' in capped: opp_can_castle['ks'] = False if danger_lines.is_king_attacker(capped): danger_lines.delete_line(capped) else: opp_non_it_moves.piece_died(capped) try: del opp_pieces[capped], opp_ps_moves[capped], opp_inv_pieces[str(move)], opp_moves[capped] except KeyError: if capped not in opp_moves.keys() or capped not in opp_ps_moves.keys(): pass else: self.save_game(fn='del_key_error_301.json') raise else: self.continuous_non_capped_turns += 1 def save_game(self, fn='match.json'): """ Saves full match in match.json with starting board, all moves made including the pieces and whether black and white could castle. loading a file with data for a match can be played using rerun_game(fn=fn). :param fn: default is match.json, file to have match stored in :type fn: str """ with open(fn, 'w') as f: json.dump(self.moves_keys_history, f, indent=1) def make_move(self, move, key): """ Places piece in new location and updates data: self.is_piece_capped(...), self.update_logs(...) and updates moves for pieces needing it. :param move: move to be made :param key: piece to move :type move: tuple :type key: str """ self.key = key self.moves_keys_history['keys'].append(key) self.moves_keys_history['moves'].append(move) if self.turn == 'white': ps_moves, pieces_locations = self.ps_white_moves, self.white_pieces_locations opp_ps_moves = self.ps_black_moves old_loc = pieces_locations[self.key] opp = 'black' else: ps_moves, pieces_locations = self.ps_black_moves, self.black_pieces_locations opp_ps_moves = self.ps_white_moves old_loc = pieces_locations[self.key] opp = 'white' self.is_piece_capped(move) if self.continuous_non_capped_turns == 50: self.draw, self.winner = True, None return piece = self.state[old_loc[0]][old_loc[1]] self.state[old_loc[0]][old_loc[1]] = 1 self.state[move[0]][move[1]] = piece castled = False if self.key == 'K': if move[1] == pieces_locations[self.key][1] - 3: castled = True rook1, self.state[move[0]][0] = self.state[move[0]][0], 1 self.state[move[0]][2] = rook1 elif move[1] == pieces_locations[self.key][1] + 2: castled = True rook2, self.state[move[0]][7] = self.state[move[0]][7], 1 self.state[move[0]][5] = rook2 self.update_logs(self.key, move, old_loc, castled) def update_moves(_key, _color): if 'P' not in _key and 'N' not in _key and 'K' not in _key: self.update_ps_iterative_moves(_key, _color) elif 'K' not in _key: self.update_ps_non_iterative_moves(_key, _color) else: if self.key == 'K': self.king_moved(_color) self.update_king_moves(_color) def update_legal_moves(_key, _color): if 'P' not in _key and 'N' not in _key and 'K' not in _key: self.update_legal_iterative_moves(_key, _color) else: self.update_legal_non_iterative_moves(_key, _color) for key_2 in ps_moves: if key_2 == self.key: update_moves(key_2, self.turn) continue update_legal_moves(key_2, self.turn) for key_2 in opp_ps_moves: update_legal_moves(key_2, opp) self.moves_safety_check(opp) if len(self.black_pieces_locations) == 1 and len(self.white_pieces_locations) == 1: self.draw = True self.winner = None self.turn = 'black' if self.turn == 'white' else 'white' self.w_check = False self.b_check = False self.king_attackers_locations = [] self.king_attacking_line = [] </code></pre> <p>This class is by far the largest, I'm not sure how to make this understandable. Feel free to dive in all the relevant code at the link above.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T08:34:03.530", "Id": "415871", "Score": "2", "body": "Since this is part of a class and you actually use other parts of that class within this method, I think that this is not really reviewable without those other parts (what is `self.state`, `self.get_king_targeting_lines`, `self.white_moves`, `self.white_king_targeting_ps_lines`, `self.black_non_iterative`, `self.is_in_black_ps_moves`, `self.w_check`...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T13:18:32.903", "Id": "415899", "Score": "1", "body": "I agree with Graipher, we need to see the rest of the class at least. A usage example of the class with it would be preferred as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T17:34:15.163", "Id": "415919", "Score": "0", "body": "@Mast What do you mean with a usage example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T05:36:57.097", "Id": "415964", "Score": "0", "body": "Well, this is a library. How would it be used? How would an actual program be implemented with this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T07:39:23.213", "Id": "415976", "Score": "0", "body": "Your link is broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T14:20:56.147", "Id": "416019", "Score": "0", "body": "@OscarSmith The link seems to be working for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T14:24:00.590", "Id": "416021", "Score": "0", "body": "@Mast it's being used by my machine learning project, which performs simulations using this chess program. That's why it's in a subfolder. to run the full program, please run the main.py file at [link](https://github.com/basvdvelden/origin) Hope this makes it clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T00:05:28.450", "Id": "416075", "Score": "0", "body": "Oops, not sure what happened" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-08T22:22:38.800", "Id": "215058", "Score": "1", "Tags": [ "python", "python-3.x", "game", "machine-learning", "chess" ], "Title": "Chess Agent using reinforcement learning with monte carlo tree search" }
215058
<p>The interview question is:</p> <blockquote> <p>Write a function <code>isMatch</code> (without using <code>java.util.Regex</code>) that takes two strings as arguments:</p> <ul> <li><code>s</code> (a string to match), and</li> <li><code>p</code> (a regular expression pattern).</li> </ul> <p>It should return a Boolean denoting whether <code>s</code> matches <code>p</code>.</p> <p><code>p</code> can be composed of alphabetic characters and '*' (denoting that the previous character matches 0 or more times).</p> </blockquote> <p>This is the code I have written:</p> <pre><code> private boolean isNextCharStarred(String s) { return s.length() &gt;= 2 &amp;&amp; s.charAt(1) == '*'; } private boolean recIsMatch(String s, String p, boolean hasPatternBeenEaten) { if (p.length() == 0) { return true; } if (s.length() == 0) { if (isNextCharStarred(p)) { return recIsMatch(s, p.substring(2), true); } return p.length() == 0; } if (isNextCharStarred(p)) { if (s.charAt(0) != p.charAt(0)) { return recIsMatch(s, p.substring(2), true); } return recIsMatch(s.substring(1), p, hasPatternBeenEaten) || recIsMatch(s, p.substring(2), true); } if (s.charAt(0) == p.charAt(0)) { return recIsMatch(s.substring(1), p.substring(1), true); } if (hasPatternBeenEaten) { return false; } return recIsMatch(s.substring(1), p, hasPatternBeenEaten); } public boolean isMatch(String s, String p) { return recIsMatch(s, p, false); } </code></pre> <p>Are there any bugs? How could it be improved?</p>
[]
[ { "body": "<h3>Empty pattern should only match empty text</h3>\n\n<p><code>isMatch(\"aa\", \"a\")</code> returns <code>true</code>, when it should be <code>false</code>.\nThe problem is with this condition: </p>\n\n<blockquote>\n<pre><code> if (p.length() == 0) {\n return true;\n }\n</code></pre>\n</blockquote>\n\n<p>An empty pattern should match only an empty text:</p>\n\n<pre><code> if (p.isEmpty()) {\n return s.isEmpty();\n }\n</code></pre>\n\n<p>Notice that I replaced <code>s.length() == 0</code> with <code>s.isEmpty()</code>.\nThis is a more natural way to check if a string is empty.</p>\n\n<h3>Use better variable names</h3>\n\n<p>Instead of <code>s</code> and <code>p</code> it would be more natural to call them <code>text</code> and <code>pattern</code>.</p>\n\n<p>The function <code>isNextCharStarred</code> is always used on the pattern,\nbut its parameter is called <code>s</code>, which is the same name as the variable used for text in the other function. Even <code>p</code> would have been less confusing. <code>pattern</code> would be nice and natural.</p>\n\n<h3>Eliminate <code>hasPatternBeenEaten</code></h3>\n\n<p>The parameter <code>hasPatternBeenEaten</code> looked a bit suspicious to me.\nLet's take a closer look.</p>\n\n<p>The value of the variable is only read in one place in the code.\nLet's look at the piece code just before that:</p>\n\n<blockquote>\n<pre><code> if (isNextCharStarred(p)) {\n // will always return from this block\n }\n if (s.charAt(0) == p.charAt(0)) {\n return ...\n }\n if (hasPatternBeenEaten) {\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>That is:</p>\n\n<ul>\n<li>If the pattern starts with <code>X*</code> (where <code>X</code> is any letter), the first <code>if</code> block will return.</li>\n<li>If the pattern doesn't start with <code>X*</code>, and the first characters match, the second <code>if</code> block will return.</li>\n<li>If the pattern doesn't start with <code>X*</code>, and the first characters don't match, then we need not look further: the pattern doesn't match, we can <code>return false</code>.</li>\n</ul>\n\n<p>Therefore, the <code>hasPatternBeenEaten</code> is unnecessary, and can be safely eliminated.</p>\n\n<h3>Simplify</h3>\n\n<p>With the above changes, the code will look more like this:</p>\n\n<pre><code> private boolean isMatch(String text, String pattern) {\n if (pattern.isEmpty()) {\n return text.isEmpty();\n }\n\n if (text.isEmpty()) {\n if (isNextCharStarred(pattern)) {\n return isMatch(text, pattern.substring(2));\n }\n return pattern.isEmpty();\n }\n\n if (isNextCharStarred(pattern)) {\n if (text.charAt(0) != pattern.charAt(0)) {\n return isMatch(text, pattern.substring(2));\n }\n return isMatch(text.substring(1), pattern)\n || isMatch(text, pattern.substring(2));\n }\n\n if (text.charAt(0) == pattern.charAt(0)) {\n return isMatch(text.substring(1), pattern.substring(1));\n }\n\n return false;\n }\n</code></pre>\n\n<p>This can probably be written simpler, by rearranging the conditions and extracting common patterns.</p>\n\n<p>First of all the second <code>pattern.isEmpty()</code> condition is redundant,\nbecause at that point we already know that <code>pattern</code> is not empty,\ndue to the very first condition in the method.</p>\n\n<p>Next, we can extract the common condition <code>text.charAt(0) == pattern.charAt(0)</code> to a variable <code>firstMatch</code>, and flatten the <code>if</code> conditions to direct <code>return</code> statements, like this:</p>\n\n<pre><code>if (pattern.isEmpty()) {\n return text.isEmpty();\n}\n\nif (text.isEmpty()) {\n return isNextCharStarred(pattern) &amp;&amp; isMatch(text, pattern.substring(2));\n}\n\nboolean firstMatch = text.charAt(0) == pattern.charAt(0);\n\nif (isNextCharStarred(pattern)) {\n return firstMatch &amp;&amp; isMatch(text.substring(1), pattern)\n || isMatch(text, pattern.substring(2));\n}\n\nreturn firstMatch &amp;&amp; isMatch(text.substring(1), pattern.substring(1));\n</code></pre>\n\n<p>Lastly, we can generalize <code>firstMatch</code> to include the case of empty text,\nwhich will make the second <code>if</code> redundant:</p>\n\n<pre><code>if (pattern.isEmpty()) {\n return text.isEmpty();\n}\n\nboolean firstMatch = !text.isEmpty() &amp;&amp; text.charAt(0) == pattern.charAt(0);\n\nif (isNextCharStarred(pattern)) {\n return firstMatch &amp;&amp; isMatch(text.substring(1), pattern)\n || isMatch(text, pattern.substring(2));\n}\n\nreturn firstMatch &amp;&amp; isMatch(text.substring(1), pattern.substring(1));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T21:35:16.273", "Id": "215380", "ParentId": "215067", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T00:33:47.770", "Id": "215067", "Score": "2", "Tags": [ "java", "strings", "interview-questions", "reinventing-the-wheel" ], "Title": "Simple pattern matching between two string inputs using Java (Google interview challenge)" }
215067
<p><strong>Note</strong>: If you googled this by the title of this question, don't use this script unless you know what it is supposed to do.</p> <p>This is a script in <code>bash</code> 3+ that I have used for long for preventing <code>rm *</code> and <code>rm -rf *</code> from accidentally invoked and removing important files by mistake. I put it in my <code>~/.bash_aliases</code>.</p> <pre><code>alias rm='set -f;rm' rm(){ if [[ "$-" == *i* ]] then if [ "$1" = "*" ] || [ "$2" = "*" ] || [ "$1" = "./*" ] || [ "$2" = "./*" ] then echo "Abort: refusing to remove *, please go to the parent folder and do rm &lt;folder_name&gt;/*" 1&gt;&amp;2 set +f return 1 fi fi set +f /bin/rm -i $@ } set +f </code></pre> <p>I would like to know whether there are any vulnerabilities and whether it can be improved.</p>
[]
[ { "body": "<p>The vulnerability I see is that only the first two arguments are checked. You could check all of them:</p>\n\n<pre><code>rm() { \n [[ $- == *i* ]] &amp;&amp; for arg\n do \n if [[ $arg = \"*\" || $arg = \"./*\" ]]\n then\n # abort\n fi\n done\n # do the rm\n</code></pre>\n\n<p>This kind of checking will miss other dangerous wildcards like <code>**</code> or <code>?*</code>. You can get safer checking by expanding <code>*</code> yourself, then see if the expanded arguments contain that same list of files:</p>\n\n<pre><code># alias not needed here; we want globs to be expanded\nrm() {\n declare -a star=(*)\n declare -a dotslashstar=(./*)\n if [[ \"$@\" == *\"${star[@]}\"* || \"$@\" == *\"${dotslashstar[@]}\"* ]]\n then\n # abort\n</code></pre>\n\n<p>... but then you can't (for example) empty a directory full of temp files with <code>rm *.tmp</code>, if <code>*.tmp</code> and <code>*</code> match the same thing. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T03:20:21.930", "Id": "415862", "Score": "2", "body": "I love your idea of expanding `*` myself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T03:18:06.473", "Id": "215072", "ParentId": "215069", "Score": "11" } }, { "body": "<h3>Double-quote variables used in command parameters</h3>\n\n<p>This is a bug:</p>\n\n<blockquote>\n<pre><code>/bin/rm -i $@\n</code></pre>\n</blockquote>\n\n<p>What will happen if you try to delete file <code>a b</code> (with space in the name)?\nMost likely this:</p>\n\n<blockquote>\n<pre><code>rm: a: No such file or directory\nrm: b: No such file or directory\n</code></pre>\n</blockquote>\n\n<p>Always write <code>\"$@\"</code> instead of unquoted <code>$@</code>.</p>\n\n<p>Unfortunately, as you pointed out in a comment,\nthis will cause another problem:\narguments containing globs will be taken literally.\nIn short, it's difficult to have the cake and eat it too.</p>\n\n<p>You could mitigate the problem by looping over the arguments,\nand if you detect a glob, then expand it yourself:</p>\n\n<pre><code>for arg; do\n if [[ $arg == *[*?]* ]]; then\n expanded=($arg)\n echo rm -i \"${expanded[@]}\"\n else\n echo rm -i \"$arg\"\n fi\ndone\n</code></pre>\n\n<p>This still won't be perfect, because it doesn't handle the case when an argument contains both spaces and globs. A robust solution would take more effort, and not worth doing in Bash. (See <a href=\"https://stackoverflow.com/a/48526731/641955\">this example</a> delegating the hard work to Python.)</p>\n\n<h3>Use <code>command</code> to bypass aliases</h3>\n\n<p>Don't worry about the absolute path of commands. Use <code>command</code> to bypass aliases:</p>\n\n<pre><code>command rm -i \"$@\"\n</code></pre>\n\n<h3>Redundant file descriptors</h3>\n\n<p>In <code>echo \"Abort: ...\" 1&gt;&amp;2</code>, the file descriptor <code>1</code> is redundant, you can safely omit it.</p>\n\n<h3>Preserving the user's environment</h3>\n\n<p>This is a minor nitpick.\nWhen the alias is executed, it will do <code>set +f</code>,\nregardless of whatever was the original setting in the shell,\nwhich may not be the same.\nThis is really just a minor nitpick, for the record.\nI wouldn't care about this tiny impractical detail either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T15:34:49.007", "Id": "415910", "Score": "1", "body": "I had an issue with patterns containing asterisk (e.g. `rm -f .*.swp`) and that's why I didn't quote `$@`. Your other advices are taken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T07:21:26.150", "Id": "415974", "Score": "1", "body": "@WeijunZhou That's a good point. See my updated answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T12:37:20.000", "Id": "215089", "ParentId": "215069", "Score": "8" } }, { "body": "<h2>Don't call your function <code>rm</code></h2>\n<p>If you start depending on this safety net, you'll eventually have an accident on a system with a standard <code>rm</code> (e.g. when you become root and find yourself using <code>dash</code> for admin tasks).</p>\n<p>I'd suggest</p>\n<pre><code>weijun_rm() {\n # your safer implementation\n}\n\nrm() {\n echo &quot;Disabled - please use weijun_rm instead&quot; &gt;&amp;2\n return 1\n}\n</code></pre>\n<p>This will train you not to use <code>rm</code> for deleting files. When your function isn't available and you have to use the real <code>rm</code>, you will be on alert and extra careful to check the arguments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:06:18.607", "Id": "416132", "Score": "0", "body": "Thank you for your suggestion. This is just an extra protection. I don't depend on this and I know what I am doing in most cases. Just in case I didn't get enough sleep and do sth silly ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:45:30.920", "Id": "416136", "Score": "1", "body": "I guess anyone can accidentally brush Enter when typing `rm *~` or `rm *.o` or the like (I normally write `echo`, and only type the `rm` when I'm happy with the rest). But perhaps my advice might be useful for others who aren't so disciplined." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:17:29.380", "Id": "215182", "ParentId": "215069", "Score": "4" } }, { "body": "<p>This is the version I am using after taking the advance of above answers. Only the core <code>if</code> is written.</p>\n\n<pre><code>if [[ $- == *i* ]]\nthen\n set +f\n for arg in \"$@\"\n do # We want to abort the whole command even if only some of the arguments contain dangerous patterns\n if [[ \"$arg\" == \"*\" || \"$arg\" == \"./*\" ]] # Can be replaced by a custom program written in Python etc. to detect dangerous patterns\n then\n #abort\n return 1\n fi\n done\n declare -a all\n for arg in \"$@\"\n do #We need to collect all arguments instead of `rm`-ing one by one otherwise `rm -rf file` does not work properly\n if [[ \"$arg\" == *[*?]* ]]\n then\n expanded=($arg)\n all+=(\"${expanded[@]}\")\n else\n all+=(\"$arg\") \n fi\n done\n command rm -i \"${all[@]}\"\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T01:03:51.717", "Id": "215226", "ParentId": "215069", "Score": "0" } }, { "body": "<h1>Restore options properly</h1>\n\n<p>Instead of <code>set -f</code> in our alias and unconditional <code>set +f</code> in the function, we can save the current shell options using <code>set +o</code> to print them as commands:</p>\n\n<pre><code>fun() {\n restore=$(set +o)\n\n set -f \n # ... and any other option changes\n # and perform the task\n\n # finally (instead of set +f)\n eval \"$restore\"\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T10:25:00.750", "Id": "215249", "ParentId": "215069", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T02:32:08.580", "Id": "215069", "Score": "9", "Tags": [ "bash" ], "Title": "Disallow `rm` to remove `*`" }
215069
<p>So yet another Sieve of Eratosthenes in Python 3.</p> <p>The function returns a list of all primes smaller but not equal <code>max_n</code>.</p> <p>The motivation is, as a practice, a simple implementation of the algorithm that is faithful, short, readable and transparent, while still getting a reasonable performance. </p> <pre><code>def primes(max_n): """Return a list of primes smaller than max_n.""" sieve = [True] * max_n # p contains the largest prime yet found. p = 2 # Only for p &lt; sqrt(max_n) we check, # i.e. p ** 2 &lt; max_n, to avoid float issues. while p ** 2 &lt; max_n: # Cross-out all true multiples of p: for z in range(2 * p, max_n, p): sieve[z] = False # Find the next prime: for z in range(p + 1, max_n): if sieve[z]: p = z break # 0 and 1 are not returned: return [z for z in range(2, max_n) if sieve[z]] </code></pre> <p>IMHO it would be preferable to avoid <code>p ** 2 &lt; max_n</code> and instead use <code>p &lt; max_n ** 0.5</code>. Can we do this? It surprisingly <em>seems</em> to work as long as <code>max_n ** 0.5</code> fits into the float mantissa, even if <code>max_n</code> doesn’t.</p> <p>The second <code>for</code>-loop doesn’t look very nice with the <code>break</code> but I don’t have any idea how to do it otherwise…</p> <p>Do you have any suggestions? </p> <p>Are there still any simplifications possible? Or non-hackish ways to increase performance?</p>
[]
[ { "body": "<blockquote>\n <p>The second for-loop doesn’t look very nice with the break ...</p>\n</blockquote>\n\n<p>You can remove that for-loop if you test <code>p</code> for being prime in the while-loop:</p>\n\n<pre><code>while p ** 2 &lt; max_n:\n if sieve[p]:\n # p is prime: cross-out all true multiples of p:\n for z in range(2 * p, max_n, p):\n sieve[z] = False\n p += 1\n</code></pre>\n\n<blockquote>\n <p>Are there still any simplifications possible? Or non-hackish ways to increase performance?</p>\n</blockquote>\n\n<p>Here are two simple changes which increase the performance:\nFirst, since 2 is the only even prime, you can increment <code>p</code> by two after the first iteration:</p>\n\n<pre><code> p = p + 2 if p &gt; 2 else 3\n</code></pre>\n\n<p>Second, it suffices to “cross-out” the multiples of <code>p</code> starting at <code>p*p</code> (instead of <code>2*p</code>) because all lesser multiples have been handled before:</p>\n\n<pre><code> for z in range(p * p, max_n, p):\n sieve[z] = False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T07:28:41.220", "Id": "415868", "Score": "0", "body": "`It suffices to “cross-out” the multiples of p starting at p*p` how could I not see this!!! ;-) . Now it’s 8 lines of actual code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T06:43:02.957", "Id": "215076", "ParentId": "215074", "Score": "2" } } ]
{ "AcceptedAnswerId": "215076", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T03:50:26.250", "Id": "215074", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "sieve-of-eratosthenes" ], "Title": "Simple Sieve of Eratosthenes in Python 3" }
215074
<p>What is best way to implement thread-safe LRUCache in java? Please review this one. Is there any better approach which can be taken here?</p> <pre><code>package cache; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LRUCache&lt;K,V&gt; { private ConcurrentLinkedQueue&lt;K&gt; concurrentLinkedQueue = new ConcurrentLinkedQueue&lt;K&gt;(); private ConcurrentHashMap&lt;K,V&gt; concurrentHashMap = new ConcurrentHashMap&lt;K, V&gt;(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private Lock readLock = readWriteLock.readLock(); private Lock writeLock = readWriteLock.writeLock(); int maxSize=0; public LRUCache(final int MAX_SIZE){ this.maxSize=MAX_SIZE; } public V getElement(K key){ readLock.lock(); try { V v=null; if(concurrentHashMap.contains(key)){ concurrentLinkedQueue.remove(key); v= concurrentHashMap.get(key); concurrentLinkedQueue.add(key); } return v; }finally{ readLock.unlock(); } } public V removeElement(K key){ writeLock.lock(); try { V v=null; if(concurrentHashMap.contains(key)){ v=concurrentHashMap.remove(key); concurrentLinkedQueue.remove(key); } return v; } finally { writeLock.unlock(); } } public V addElement(K key,V value){ writeLock.lock(); try { if(concurrentHashMap.contains(key)){ concurrentLinkedQueue.remove(key); } while(concurrentLinkedQueue.size() &gt;=maxSize){ K queueKey=concurrentLinkedQueue.poll(); concurrentHashMap.remove(queueKey); } concurrentLinkedQueue.add(key); concurrentHashMap.put(key, value); return value; } finally{ writeLock.unlock(); } } } </code></pre>
[]
[ { "body": "<p><strong>Advice 1</strong></p>\n\n<pre><code>public class LRUCache&lt;K,V&gt;\n</code></pre>\n\n<p>You have <em>two</em> spaces between <code>class</code> and <code>LRUCache</code>.</p>\n\n<p><strong>Advice 2</strong></p>\n\n<p><code>v=null</code></p>\n\n<p>In professional Java programming, it is customary to have a single space <strong><em>before</em></strong> and <strong><em>after</em></strong> each <strong><em>binary</em></strong> operator.</p>\n\n<p><strong>Advice 3</strong></p>\n\n<pre><code>public V getElement(K key){\n\n readLock.lock();\n try { ... } ...\n</code></pre>\n\n<p>Looks strange to me. Why not have instead the following:</p>\n\n<pre><code>public V getElement(K key){\n readLock.lock();\n\n try { ... } ...\n</code></pre>\n\n<p><strong>Advice 4</strong></p>\n\n<pre><code>int maxSize=0;\n</code></pre>\n\n<p>First of all, I suggest you make it <code>private</code>. Also, there is no need to initialize member <code>int</code>s with zero, that is done by Java by default. Other fundamental types are initialized to zero too.</p>\n\n<p><strong>Advice 5</strong></p>\n\n<pre><code>public LRUCache(final int MAX_SIZE)\n</code></pre>\n\n<p>It is idiomatic to name only constants with <code>UPPER CASE</code>. Constructor (and method) parameters are advised to be in <code>camelCase</code>.</p>\n\n<p><strong>Advice 6</strong></p>\n\n<pre><code>private ConcurrentHashMap&lt;K,V&gt; concurrentHashMap = new ConcurrentHashMap&lt;K, V&gt;();\n</code></pre>\n\n<p>You could omit type parameters in <code>new ConcurrentHashMap&lt;K, V&gt;</code> thanks to <strong><em>diamond inference</em></strong>. Also, you could declare all the members instead of <code>maxSize</code> to <code>final</code>:</p>\n\n<pre><code>private final ConcurrentHashMap&lt;K,V&gt; concurrentHashMap = new ConcurrentHashMap&lt;&gt;();\n</code></pre>\n\n<p><strong>Advice 7</strong></p>\n\n<pre><code>ConcurrentHashMap&lt;K,V&gt;\n</code></pre>\n\n<p>It is also customary to have a single space <strong><em>after</em></strong> each comma character: <code>&lt;K,_V&gt;</code>.</p>\n\n<p><strong>Advice 8</strong></p>\n\n<p><code>concurrentLinkedQueue</code> and <code>concurrentHashMap</code>. These are not the best possible names for the two data structures. Instead of naming them according to their type I instead suggest to name them according to what they do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T07:37:47.407", "Id": "215077", "ParentId": "215075", "Score": "2" } }, { "body": "<p><strong>Advice 1</strong></p>\n\n<p>This implementation is not thread safe. For example, if two threads invoked <code>getElement(key1)</code> simultaneously, they may runs to <code>concurrentLinkedQueue.add(key)</code> at same times(they both performed delete and get, but delete will fail the second time or just do nothing), then two same keys will be added.</p>\n\n<p><strong>Advice 2</strong></p>\n\n<p>Maybe <code>capacity</code> is more suitable than <code>maxSize</code>.</p>\n\n<p><strong>Advice 3</strong></p>\n\n<p><code>LinkedHashMap</code> is often used as LRU cache. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:02:48.007", "Id": "416088", "Score": "0", "body": "Why does the number 1 happen? Doesn't the key get removed and added? Isn't concurrent containers thread safe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:33:41.933", "Id": "416091", "Score": "0", "body": "@422_unprocessable_entity the three operations inside if block is not atomic. If two threads running to `concurrentLinkedQueue.add(key);` at same times(they both performed delete and get, but delete will fail the second time or just do nothing), two same keys will be added." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:50:16.993", "Id": "416097", "Score": "0", "body": "Yes you are correct. Well done on catching it. :) Can you insert the explanation in the answer as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T04:10:14.507", "Id": "215165", "ParentId": "215075", "Score": "4" } }, { "body": "<h3>Advice 1</h3>\n<p>Rename concurrentHashMap to internalCache</p>\n<h3>Advice 2</h3>\n<p>Rename concurrentLinkedQueue to trackingQueue</p>\n<h3>Advice 3</h3>\n<p>Declare using Queue Interface:</p>\n<pre><code>Queue&lt;K&gt; trackingQueue = new ConcurrentLinkedQueue&lt;&gt;();\n</code></pre>\n<h3>Advice 4</h3>\n<p>Your get API implementation is not thread safe as pointed out in one of the comments above.\nYou can do the getElement implementation as follows to make sure that a simultaneaous remove from queue for same element does not result in adding back duplicate element to queue:</p>\n<pre><code>public V getElement(K key){\n readLock.lock();\n try {\n V value = internalCache.get(key);\n if(value != null){\n if (trackingQueue.remove(key)) {\n trackingQueue.add(key);\n }\n }\n return value;\n } finally {\n readLock.unlock();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T08:37:57.467", "Id": "252809", "ParentId": "215075", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T05:45:59.317", "Id": "215075", "Score": "6", "Tags": [ "java", "multithreading", "concurrency", "cache" ], "Title": "java Thread-safe LRUCache implementation" }
215075
<p>Sometimes I have the date as part of the file name. And then when Emacs autocompletes the file name, it puts the part of the date. In these situations I have to write the rest of the date manually. Here is a solution, so that I can press <kbd>Super</kbd>+<kbd>d</kbd> and the suffix of today's date is written in the buffer. For example, if point is after "2019", when I press <kbd>Super</kbd>+<kbd>d</kbd> it becomes "2019-03-09".</p> <pre><code>(defun make-suffix (word1 word2) (cl-labels ((is-prefix (prefix list) (cond ((null prefix) t) ((null list) nil) ((equal (car prefix) (car list)) (is-prefix (cdr prefix) (cdr list))) (t nil))) (delete-x-elements (x list) (cond ((= x 0) list) ((null list) list) (t (delete-x-elements (- x 1) (cdr list))))) (make-suffix-rec (l1 l2) (cond ((null l1) l2) ((is-prefix l1 l2) (delete-x-elements (length l1) l2)) (t (make-suffix-rec (cdr l1) l2))))) (concat (make-suffix-rec (string-to-list word1) (string-to-list word2))))) (global-set-key (kbd "s-d") (lambda () (interactive) (let ((cw (current-word)) (ds (format-time-string "%Y-%m-%d"))) (insert (make-suffix cw ds))))) </code></pre> <p>So what do you think? Is it a good solution? Is it the right way to use elisp and Emacs?</p>
[]
[ { "body": "<p>I'm concerned that <code>make-suffix</code> is sufficiently general that we'll have name collisions with other packages - or even new Emacs versions. Perhaps prefix with some tag (I tend to begin names with my initials to disambiguate my own functions, for example; that would give you something like <code>an/make-suffix</code>).</p>\n\n<p>Instead of binding a lambda to the keystroke, prefer to give it a name. That makes it easier to bind to other keys (perhaps interactively) and for <kbd>Control</kbd>+<kbd>h</kbd> <kbd>k</kbd> to give the best output.</p>\n\n<p>Talking of which, let's have some docstrings, please!</p>\n\n<p>Finally, since the function will work only on writable buffers, we should have <strong><code>(interactive \"*\")</code></strong> to avoid wasting effort when used in a read-only context.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:45:45.267", "Id": "215185", "ParentId": "215078", "Score": "1" } } ]
{ "AcceptedAnswerId": "215185", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T07:47:57.167", "Id": "215078", "Score": "2", "Tags": [ "datetime", "elisp", "autocomplete" ], "Title": "Get the suffix for the date string" }
215078
<p>I work in the training department of a captioning agency, where I spend a lot of time grading trainee's dictation transcripts.</p> <p>We receive the transcripts of trainee's dictation of test audios and then compare them with Microsoft&nbsp;Word to the original transcript, highlighting incorrect words yellow, omitted words blue, and added words green. At the end, we itemize the number of errors in each category, and then calculate the accuracy.</p> <p>I made a short macro that, once I've highlighted the errors appropriately, will count and print the itemized error counts, total errors, and accuracy percentage along with the grader's name, and finally copy the score to clipboard. In the original that I'm comparing to, I've bolded the transcript and italicized the total word count that's printed at the end so the macro can identify them.</p> <p>We use Office 2016 on Windows 7, just in case that's relevant.</p> <p>I have some experience programming but am new to VBA, and would really like to have somebody with more experience look over my code to see what I can correct and improve, with syntax and function, before I show it to my supervisors. So far it works just as I would like it to but I'm sure it could be improved and made to be more efficient and reliable.</p> <p>I've also included <a href="https://i.stack.imgur.com/sXIg1.png" rel="nofollow noreferrer">a sample of a graded transcript</a> to give a clearer picture of what the final output is.</p> <pre><code>Sub CountErrorsByColor() Dim objDoc As Document Dim objWord As Object Dim nHighlightedYellow As Long Dim nHighlightedBlue As Long Dim nHighlightedGreen As Long Dim nHighlightedTotal As Long Dim wTotal As Long Dim oRng As Word.Range Dim mystring As New DataObject Application.ScreenUpdating = False 'Count errors by highlight color and total errors. Set objDoc = ActiveDocument For Each objWord In objDoc.Words If objWord.HighlightColorIndex = wdYellow And objWord.Font.Bold Then nHighlightedYellow = nHighlightedYellow + 1: nHighlightedTotal = nHighlightedTotal + 1 ElseIf objWord.HighlightColorIndex = wdTurquoise Then nHighlightedBlue = nHighlightedBlue + 1: nHighlightedTotal = nHighlightedTotal + 1 ElseIf objWord.HighlightColorIndex = wdBrightGreen Then nHighlightedGreen = nHighlightedGreen + 1: nHighlightedTotal = nHighlightedTotal + 1 End If Next objWord 'Find total word count ActiveDocument.Range.Select Selection.Find.Font.Italic = True With Selection.Find .ClearFormatting .Font.Italic = True .Wrap = wdFindStop .Execute If .Found = True Then italText = Selection.Range.Text End If End With wTotal = Selection.Text Application.Selection.EndOf 'Calculate and format score score = (wTotal - nHighlightedTotal) / wTotal formattedScore = Format(score, "Percent") pasteScore = Format(score * 100, "Standard") 'Print error counts, score, and name Set oRng = Selection.Range With oRng .Text = "Incorrect: " &amp; nHighlightedYellow .HighlightColorIndex = wdYellow .Font.Bold = True .Collapse wdCollapseEnd .Select .Text = vbNewLine &amp; _ "Omitted: " &amp; nHighlightedBlue .HighlightColorIndex = wdTurquoise .Font.Bold = True .Collapse wdCollapseEnd .Select .Text = vbNewLine &amp; _ "Added: " &amp; nHighlightedGreen .HighlightColorIndex = wdBrightGreen .Font.Bold = True .Collapse wdCollapseEnd .Select .Text = vbNewLine &amp; _ "Total: " &amp; nHighlightedTotal .HighlightColorIndex = wdNoHighlight .Font.Bold = True .Collapse wdCollapseEnd .Select .Text = vbNewLine &amp; _ "Score: " &amp; formattedScore .HighlightColorIndex = wdNoHighlight .Font.Bold = True .Collapse wdCollapseEnd .Select .Text = vbNewLine &amp; _ "Grader's Name" .HighlightColorIndex = wdNoHighlight .Font.Bold = True .Collapse wdCollapseEnd .Select End With 'Copy score to clipboard my_var = pasteScore mystring.SetText my_var mystring.PutInClipboard End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T05:37:59.970", "Id": "415965", "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)*. Please consider posting a follow-up question instead, indicated by the repost suggestion in the answer provided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T06:33:50.017", "Id": "415968", "Score": "0", "body": "My fault, I'll do my best to adhere more closely to the site rules in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T07:48:58.717", "Id": "415979", "Score": "0", "body": "Didn't RubberDuck complain about the usage of`Selection/Select`? They can be removed most times, by just concating the expression before`.Select`with the part after`Selection.`like' ActiveDocument.Range.Find.Font.Italic = True` Also you should try to sray DRY. Everytime you see repeating code with just minor diffs you should create s loop and a procedure that do tge same with less code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T08:36:09.013", "Id": "415984", "Score": "0", "body": "At the moment code inspection doesn't have any errors/warnings/suggestions/hints for the module, but I see how that would be more efficient that way. I'll definitely look into it. Regarding staying DRY you are totally right. My knowledge of VBA and truthfully programming in general is definitely bottle-necking me, but I'll look to make those sections more efficient. Presumably the font and paragraph formatting in the printScore section would be an example of where that would be most beneficial?" } ]
[ { "body": "<p>There are 5 steps you could take after which you could repost your code here.</p>\n\n<ol>\n<li><p>Use 'Option Explicit' in each module and address the errors that this will show.</p></li>\n<li><p>If you are able, install the RubberDuck addin. Use the 'RubberDuck' addin to do a code inspection and then address all the issues you find.</p></li>\n<li><p>Split your code into simple functions/subs. At the moment your macro does a number of tasks. You should aim to separate your code into a set of small and simple subs and functions.</p></li>\n<li><p>Use RubberDuck to write some unit tests for your newly created subs and functions. This will be extremely useful for the person who inherits your code.</p></li>\n<li><p>Use meaningful names. At the moment you have a tendency towards a naming convention called systems Hungarian (e.g. objWord). This style of naming is deprecated as such names are not useful because they say nothing about the purpose of the variable or function/sub. Try using names that mean something in the context of the task in hand. e.g. test_doc.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T15:08:45.783", "Id": "415909", "Score": "0", "body": "Welcome to Code Review! +1 for RD, but provide the link to. You should add advice to keep DRY (Don't Repeat Yourself) and Identifiers should be CamelCase (Improves readbility and typos are recognized at once if you type them lowercase outside declaration and they stay lowercase)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T04:23:23.713", "Id": "415962", "Score": "0", "body": "Thank you so much! I'd never heard of RubberDuckVBA, what a great tool. I did my best to follow your advice. I'm now using 'Option Explicit' and declared the variables I'd missed, did a code inspection and resolved all the errors/warnings, and did my best to use more descriptive variable names. There were a few places where I was unsure how to best replace the Hungarian Notation with more meaningful variable names such as with oRng, as I don't know that I completely understand it's usage. I've edited the post with the revised code if you have any additional suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T06:26:43.607", "Id": "415966", "Score": "0", "body": "Regarding your advice to split my code into multiple functions/subs, are you saying it would be better to have a sub for each of the individual functions of the macro that I have commented, and then call each of those within another function? I've seen that advice from others now that I look around, but to clarify what is the benefit of doing that? Just to make the macro more modular and easier to troubleshoot?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T09:28:21.090", "Id": "415988", "Score": "1", "body": "It makes it much easier to check that your code works as it should. The smaller functions can be given meaningful names so that you code becomes self documenting." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T13:45:58.503", "Id": "215094", "ParentId": "215080", "Score": "7" } }, { "body": "<p>Well that's great progress. I now have some more comments.</p>\n\n<ol>\n<li>Brute force rather than precision</li>\n</ol>\n\n<p>Your search for highlighted words is using a 'brute force' approach as you are examining every word rather than using the Word search function to search for words with a specific highlight.</p>\n\n<p>2 Multiple variables rather than grouped data</p>\n\n<p>Your are using multiple variables for a set of grouped data. You can simplify your code by declaring a Type (simple) or object (slightly more complicated). e.g you could declare a type called 'Scorecard' which has fields of Incorrect, Omitted, Added, Total and Percent. In fact if I were doing this problem Scorecard would be an object with the searching and summing routines encapsulated in the class.</p>\n\n<ol start=\"3\">\n<li>Find total word count comment.</li>\n</ol>\n\n<p>This is an example of useless commenting. Sorry to be so rude. But the comment requires us to know that you have encoded the total words already in the document and that it is the only italicised word on the page. A much better comment would be to say exactly that. ' The total word count is located at the foot of the document and is the only italicised word in the document'. BUT this is also possibly a waste of time because you document structure is not taking advantage of templates.</p>\n\n<ol start=\"4\">\n<li>Coding rather than template.</li>\n</ol>\n\n<p>You insert the report of the score by creating the text programatically. This is where words Template system comes to our aid. A better starting position might be that you have a Template with a Table that contains the report details. One column for the labels and one column for the scores. Even if you didn't want or can't use a template I'd still prefer to insert a table as this would make the subsequent programming much easier to follow.</p>\n\n<ol start=\"5\">\n<li>Screen updating. </li>\n</ol>\n\n<p>You turn it off but never turn it back on again.</p>\n\n<ol start=\"6\">\n<li>Unnecessary calculations</li>\n</ol>\n\n<p>When you are calculating the totals for each highlight you also update the overall total. This isn't necessary, you can add the totals for the green, blue and yellow highlights at the end of the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T13:21:28.587", "Id": "416008", "Score": "0", "body": "Appreciate the feedback. I'm only about 2 1/2 weekends deep in VBA at this point so this kind of direction is exactly what I'm looking for. You're right about the 'brute force' approach. Would the Find.Execute method be more suitable? Scorecard I've not encountered yet, I'll look into that. My commenting at this point is mostly so that I can organize and navigate the code more easily, but admittedly it does little to help the reader. I'll look into using a template and table, as well as fixing the screen updating and calculations. I've got a lot to read up on here, thanks very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:20:33.003", "Id": "416034", "Score": "0", "body": "Use the macro recorder to see how VBA would achieve a task but be aware that the macro recorder produces rather bad code. You can get help on any keyword by placing the cursor on the keyword and pressing F1. For word objects putting the cursor on the keyword and pressing Shift F2 will take you to the object browser with the object displayed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T12:07:33.080", "Id": "215136", "ParentId": "215080", "Score": "5" } }, { "body": "<p>As this is a code review request, some of my comments may be considered \"best practices\" by me and not by others (though most of my habits I've picked up from sites and reviews such as this one). Your code is successful already because it accomplishes the task for which you have designed. Most of the improvements I can suggest are in terms of software design and presentation.</p>\n\n<ol>\n<li>It is far less desirable to present a \"wall of declarations\" at the beginning of a method because it forces the reader to constantly refer back and forth between the logic and the declaration to figure out which variable is declared as what. It also makes it easier to declare a variable and then never use it. So... always declare your variables as close as practical to where they are first used.</li>\n<li>Always keep a wary eye out of repetitive-seeming steps or logic. When you find yourself cutting and pasting the same code with some tweaks to perform a nearly identical action, breaking it out into a separate method makes your logic much easier to read, PLUS it isolates your logic in a single location. This way if you have to modify that logic, you only do it once. In your code, you need to count the number of highlighted words of several different colors. </li>\n</ol>\n\n<p>Breaking that out into its own <code>Sub</code> helps to keep the focus on how this is done:</p>\n\n<pre><code>Private Function CountFormattedWords(ByVal checkIndex As WdColorIndex, _\n Optional ByRef checkDoc As Document = Nothing) As Long\n '--- counts the number of words in the document highlighted with\n ' the given highlight color index\n Dim thisDoc As Document\n If checkDoc Is Nothing Then\n Set thisDoc = ThisDocument\n Else\n Set thisDoc = checkDoc\n End If\n\n Dim checkWord As Variant\n For Each checkWord In thisDoc.Words\n If checkWord.HighlightColorIndex = checkIndex Then\n CountFormattedWords = CountFormattedWords + 1\n End If\n Next checkWord\nEnd Function\n</code></pre>\n\n<p>Notice the <code>Optional ByRef checkDoc As Document = Nothing</code> parameter. This is something I'll throw into the parameter list of a method based on long experience, knowing that I just might want to reuse this sub for a different <code>Document</code>. Clearly you can easily assume you're accessing the local document, but it might not always be the case.</p>\n\n<p>Also, note that I used <code>ThisDocument</code> instead of <code>ActiveDocument</code>. The difference here is important. By specifying <code>ThisDocument</code> here, I'm telling the code to refer to the MS Word document in which the VBA code resides. If I used <code>ActiveDocument</code>, then I would be referring to whichever MS Word document is currently \"on top\" or actively being viewed/edited by the user. So in the case of this parameter, I'm giving myself the option to default it one way, but use it in a different way if I need to (<em>see below</em>).</p>\n\n<p>So now the beginning of your logic can look like this</p>\n\n<pre><code> Dim testDoc As Document\n Dim yellowErrors As Long\n Dim blueErrors As Long\n Dim greenErrors As Long\n Dim totalErrors As Long\n Set testDoc = ActiveDocument\n yellowErrors = CountFormattedWords(wdYellow, testDoc)\n blueErrors = CountFormattedWords(wdTurquoise, testDoc)\n greenErrors = CountFormattedWords(wdBrightGreen, testDoc)\n totalErrors = yellowErrors + blueErrors + greenErrors\n</code></pre>\n\n<p>You can note that here is where I slip in the reference to the <code>ActiveDocument</code>, which overrides the default of my parameter.</p>\n\n<ol start=\"3\">\n<li><p>Avoid using <code>Select</code>. This is a major point when programming VBA for Excel, but less rigorous when using VBA in MS Word. With all the examples on the webz showing <code>Select</code>, you might find it hard to avoid. Since I started my VBA journey in Excel, I still stick with this rule though. So for using <code>Find</code> on a range to look for your word count, I created a <code>Range</code> variable called <code>wordCount</code>. Initially, you can see the range is set to encompass the entire document. After executing the <code>Find</code> however, this variable collapses to <em>only</em> the found text (in this case the text that is italic). A simple cast/conversion from <code>String</code> to <code>Long</code> gets me the integer word count.</p>\n\n<pre><code>'--- total word count should be the only text in the document\n' using Italic format\nDim wordTotal As Long\nDim wordCount As Range\nSet wordCount = testDoc.Content\nWith wordCount.Find\n .Font.Italic = True\n .Wrap = wdFindStop\n .Execute\n If .Found Then\n wordTotal = CLng(wordCount)\n Else\n '--- do something if we didn't find it\n MsgBox \"ERROR! Can't find the Total Words count!\"\n Exit Sub\n End If\nEnd With\n</code></pre></li>\n<li><p>Your longest section of code is creating/appending the various details of the score to the end of the document. Again, it's pretty repetitive and pretty much the same. So... we have a separate sub to isolate the logic. This logic avoids using <code>Select</code> and simplifies some of what you were doing. Because it's nicely isolated, you can add any additional paragraph formatting you like here (and only do it once!).</p>\n\n<pre><code>Private Sub AppendScoreDetail(ByVal thisText As String, _\n ByVal thisHighlight As WdColorIndex, _\n Optional ByRef checkDoc As Document = Nothing)\n Dim thisDoc As Document\n If checkDoc Is Nothing Then\n Set thisDoc = ThisDocument\n Else\n Set thisDoc = checkDoc\n End If\n\n Dim newText As Paragraph\n Set newText = thisDoc.Content.Paragraphs.Add\n With newText.Range\n .Text = thisText\n .Font.Italic = False\n .Font.Underline = False\n .Font.Bold = True\n .Font.Name = \"Arial Black\"\n .Font.Size = 11\n .HighlightColorIndex = thisHighlight\n .Paragraphs.Add\n End With\nEnd Sub\n</code></pre>\n\n<p>Now adding your score details is simply</p>\n\n<pre><code>'--- add totals and overall score at the end of the document\nAppendScoreDetail \"Incorrect: \" &amp; yellowErrors, wdYellow, testDoc\nAppendScoreDetail \"Omitted: \" &amp; blueErrors, wdTurquoise, testDoc\nAppendScoreDetail \"Added: \" &amp; greenErrors, wdBrightGreen, testDoc\nAppendScoreDetail \"Total: \" &amp; totalErrors, wdNoHighlight, testDoc\nAppendScoreDetail \"Score: \" &amp; Format$(score, \"00.00%\"), wdNoHighlight, testDoc\nAppendScoreDetail \"Grader's Name: \", wdNoHighlight, testDoc\n</code></pre></li>\n<li><p>I left the logic for copying your score to the clipboard largely intact since there is no real way to improve that. However, as I'm reading the code I don't understand <strong>why</strong> you're copying it to the clipboard or if a specific format is required. The comments you have in your code are redundant because the code itself is documenting what you're doing (especially if you continue to use descriptive variable names). The comments I appreciate are the ones that tell me why something is being done. You might always be the only person ever to look at your code, but I guarantee you'll forget why you did things a certain way three years from now.</p></li>\n<li><p>Don't forget to re-enable <code>Application.ScreenUpdating = True</code> at the end of your logic.</p></li>\n</ol>\n\n<p>For convenience, here is the entire module in a single block:</p>\n\n<pre><code>Option Explicit\n'@Folder(\"Grading Macro\")\n\nPublic Sub GradingMacro()\n Application.ScreenUpdating = False\n\n Dim testDoc As Document\n Dim yellowErrors As Long\n Dim blueErrors As Long\n Dim greenErrors As Long\n Dim totalErrors As Long\n Set testDoc = ActiveDocument\n yellowErrors = CountFormattedWords(wdYellow, testDoc)\n blueErrors = CountFormattedWords(wdTurquoise, testDoc)\n greenErrors = CountFormattedWords(wdBrightGreen, testDoc)\n totalErrors = yellowErrors + blueErrors + greenErrors\n\n '--- total word count should be the only text in the document\n ' using Italic format\n Dim wordTotal As Long\n Dim wordCount As Range\n Set wordCount = testDoc.Content\n With wordCount.Find\n .Font.Italic = True\n .Wrap = wdFindStop\n .Execute\n If .Found Then\n wordTotal = CLng(wordCount)\n Else\n '--- do something if we didn't find it\n MsgBox \"ERROR! Can't find the Total Words count!\"\n Exit Sub\n End If\n End With\n\n Dim score As Double\n score = (wordTotal - totalErrors) / wordTotal\n\n '--- add totals and overall score at the end of the document\n AppendScoreDetail \"Incorrect: \" &amp; yellowErrors, wdYellow, testDoc\n AppendScoreDetail \"Omitted: \" &amp; blueErrors, wdTurquoise, testDoc\n AppendScoreDetail \"Added: \" &amp; greenErrors, wdBrightGreen, testDoc\n AppendScoreDetail \"Total: \" &amp; totalErrors, wdNoHighlight, testDoc\n AppendScoreDetail \"Score: \" &amp; Format$(score, \"00.00%\"), wdNoHighlight, testDoc\n AppendScoreDetail \"Grader's Name: \", wdNoHighlight, testDoc\n\n '--- but WHY are you copying the score to the clipboard (the code\n ' says what you're doing)\n Dim clipboard As DataObject\n Dim textToClip As String\n Dim formattedScore As Variant\n Dim pasteScore As Variant\n formattedScore = Format$(score, \"Percent\")\n pasteScore = Format$(score * 100, \"Standard\")\n Set clipboard = New DataObject\n textToClip = pasteScore\n clipboard.SetText textToClip\n clipboard.PutInClipboard\n\n Application.ScreenUpdating = True\nEnd Sub\n\nPrivate Function CountFormattedWords(ByVal checkIndex As WdColorIndex, _\n Optional ByRef checkDoc As Document = Nothing) As Long\n '--- counts the number of words in the document highlighted with\n ' the given highlight color index\n Dim thisDoc As Document\n If checkDoc Is Nothing Then\n Set thisDoc = ThisDocument\n Else\n Set thisDoc = checkDoc\n End If\n\n Dim checkWord As Variant\n For Each checkWord In thisDoc.Words\n If checkWord.HighlightColorIndex = checkIndex Then\n CountFormattedWords = CountFormattedWords + 1\n End If\n Next checkWord\nEnd Function\n\nPrivate Sub AppendScoreDetail(ByVal thisText As String, _\n ByVal thisHighlight As WdColorIndex, _\n Optional ByRef checkDoc As Document = Nothing)\n Dim thisDoc As Document\n If checkDoc Is Nothing Then\n Set thisDoc = ThisDocument\n Else\n Set thisDoc = checkDoc\n End If\n\n Dim newText As Paragraph\n Set newText = thisDoc.Content.Paragraphs.Add\n With newText.Range\n .Text = thisText\n .Font.Italic = False\n .Font.Underline = False\n .Font.Bold = True\n .Font.Name = \"Arial Black\"\n .Font.Size = 11\n .HighlightColorIndex = thisHighlight\n .Paragraphs.Add\n End With\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T02:19:47.900", "Id": "416571", "Score": "0", "body": "This is amazing! I have a few follow-up questions. What is the best way to print the score details? If I'm reading this correctly this does everything up to that but doesn't print the itemized score. Second, I realized currently the percentage rounds up to the hundreth, which we cannot. I searched for a way to display the non-rounded percentage and all I've found that seems to work is something like this: 'score = ((wordTotal - totalErrors) / wordTotal) * 100\nscoreNoRound = (Int(score * 100)) / 100 ' Can I add this into the existing code declaring scoreNoRound as Variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T02:48:10.080", "Id": "416573", "Score": "0", "body": "The code above does print the score, at least in the same format as shown in your graded transcript image. That's what the `AppendScoreDetail` routine is doing (I created a test document identical to your image, and the code worked to append the score details). To change the format of the score display, don't worry about rounding. It's all in how it's formatted. Change the format string in the above code from `\"00.00%\"` to what you need, e.g. `\"00.0%\"` or `\"00%\"`. You don't need an extra variable or anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T04:13:41.157", "Id": "416576", "Score": "0", "body": "Hmm, you're right but somehow it's not printing it into the document I'm using it in, but when I open a new blank document it is printed there. I inserted the module under the Normal Project, is that the correct place to add it? Concerning the formatting if I need it to show 2 digits before and 2 digits after the decimal, using 00.00% seems to still be rounding the thousands place. I feel like I'm being dense here but I'm too dense to know how haha." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T15:26:18.073", "Id": "416653", "Score": "0", "body": "This is my mistake, code is corrected in the answer above. For the call to `AppendScoreDetail` I should have included the `testDoc` parameter. So the call should be similar to `AppendScoreDetail \"Incorrect: \" & yellowErrors, wdYellow, testDoc`. Add that to each call and it should work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T01:25:08.920", "Id": "416753", "Score": "1", "body": "Great answer as always! One thing though, in Word the `Selection` is a full-fledged object with an early-bound public interface, ...very different than in Excel where it could be anything... if the selection is a `Chart` and you set it to a `Worksheet` object, boom. Declaring it as a variant will only defer the bug further down, where a late-bound member call is made for e.g. a `Range` property that a `Chart` object doesn't have. Word's selection invokes are early-bound and blow up at *compile time* if invalid, before any code gets to run. Word wins the `Selection` battle, in spades ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T14:06:40.623", "Id": "416841", "Score": "0", "body": "@MathieuGuindon That's very good information about `Select` in MS Word. While almost all examples of Word VBA will use `Select`, I hadn't realized the difference in implementation of the object under the hood. As I've been conditioned to avoid it when working in Excel, I was knowingly (but uneducatedly) following the same principles in Word. Thanks for the useful knowledge!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T06:53:15.653", "Id": "417406", "Score": "0", "body": "I've been fiddling with the macro this last week, and your version of the macro with a few tweaks is working almost perfectly, but I was hoping you could help clear one issue up for me. Unless I manually enter a new line after the Total Words: ### at the end of the document, the macro will replace the Total Words: ### line when it runs. If I go back into the original transcript before comparing and enter a new line it won't replace it, but I can't figure out how to fix the problem with the code. Any thoughts on resolving this issue would be much appreciated!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:59:06.600", "Id": "215266", "ParentId": "215080", "Score": "5" } }, { "body": "<p>Having provided so much comment I thought it was only fair to post what my version of your code would be. There is a deliberate error in the code. I wonder what your thoughts are on how easy it is to spot? I also can't guarantee that the code will work as intended(although it does compile) as a don't have a sample document to test it on.</p>\n\n<pre><code>Option Explicit\n\nPublic Enum ErrorType\n ' Colors are selected from the Word.WdColourIndex enumeration\n Omitted = wdTurquoise\n Incorrect = wdYellow\n Added = wdBrightGreen\n\nEnd Enum\n\nPublic Type ScoreCard\n\n Omittted As Long\n Incorrect As Long\n Added As Long\n TotalErrors As Long\n TotalWords As Long\n Score As Double ' Total errors as a percent of total words\n\nEnd Type\n\nPublic Enum ReportRow\n [_First] = 1 ' The [_ and] means that the enumeration item will not appear in the intellisense\n Incorrect = 1\n Omittted = 2\n Added = 3\n TotalErrors = 4\n Score = 5\n GraderName = 6\n [_Last] = GraderName\n\nEnd Enum\n\nPublic Const TABLE_COLUMNS As Long = 2\n\nSub CountErrorsByErrorType()\n\nDim my_scorecard As ScoreCard\nDim my_score_for_pasting As DataObject\n\n With my_scorecard\n\n .TotalWords = GetTotalWordsCount\n .Added = CountWordsWithError(ErrorType.Omitted, True, True)\n .Incorrect = CountWordsWithError(ErrorType.Incorrect, this_document:=ActiveDocument)\n .Omittted = CountWordsWithError(ErrorType.Omitted)\n .TotalErrors = .Added + .Omittted + .Incorrect\n\n End With\n\n CreateReport my_scorecard\n\n Set my_score_for_pasting = New DataObject\n my_score_for_pasting.SetText = Format$(my_scorecard.Score, \"0.00% \")\n my_score_for_pasting.PutInClipboard\n\n MsgBox _\n \"Scoring completed\" _\n &amp; vbCrLf &amp; vbCrLf _\n &amp; \"Score was \" _\n &amp; CStr(my_scorecard.Score) _\n &amp; vbCrLf &amp; vbCrLf _\n &amp; \"Remeber to paste the score!!\", _\n vbOKOnly\nEnd Sub\n\nPublic Function CountWordsWithError _\n( _\n ByVal this_score_highlight_color As ErrorType, _\n Optional ByVal this_bold As Boolean = False, _\n Optional ByVal this_underline As Boolean = False, _\n Optional ByRef this_document As Word.Document _\n) As Long\n\nDim my_count As Long\nDim my_document As Word.Document\n\n Set my_document = IIf(this_document Is Nothing, ActiveDocument, this_document)\n\n With my_document.StoryRanges(wdMainTextStory)\n\n With .Find\n\n .ClearFormatting\n .Text = \"\"\n .Format = True\n .Highlight = True\n .Font.Bold = this_bold\n .Font.Underline = this_underline\n .Wrap = wdFindStop\n ' Put any other search options here\n .Execute Wrap:=wdFindStop\n\n End With\n\n Do While .Find.Found\n\n If .HighlightColorIndex = this_score_highlight_color Then\n\n my_count = my_count + 1\n\n End If\n\n .Collapse Direction:=wdCollapseEnd\n .Move unit:=wdCharacter, Count:=1\n .Find.Execute\n\n Loop\n\n End With\n\n CountWordsWithError = my_count\n\nEnd Function\n\nPublic Function GetTotalWordsCount(Optional ByRef this_document As Word.Document) As Long\n\nDim my_document As Word.Document\n\n Set my_document = IIf(this_document Is Nothing, ActiveDocument, this_document)\n\n With my_document.StoryRanges(wdMainTextStory)\n\n With .Find\n\n .ClearFormatting\n .Text = \"\"\n .Wrap = wdFindStop\n .Font.Italic = True\n .Execute\n\n If .Found Then\n\n GetTotalWordsCount = CStr(.Text)\n\n Else\n\n MsgBox \"The total word count was not found\", vbOKOnly\n End\n\n End If\n\n End With\n\n End With\n\nEnd Function\n\nPublic Sub CreateReport(ByRef this_scorecard As ScoreCard, Optional ByRef this_document As Word.Document)\n\nDim my_document As Word.Document\nDim my_range As Word.Range\n\n Set my_document = IIf(this_document Is Nothing, ActiveDocument, this_document)\n\n With this_scorecard\n\n .Score = ((.TotalWords - .TotalErrors) / .TotalWords) * 100\n\n End With\n\n If my_document.Tables.Count = 0 Then\n\n my_range = my_document.StoryRanges(wdMainTextStory)\n my_range.Collapse Direction:=wdCollapseEnd\n InsertReportTable my_range, ReportRow.[_Last], 2\n\n End If\n\n With my_document.Tables(1).Range.COLUMNS(2)\n\n .Cells(ReportRow.Incorrect).Range.Text = CStr(this_scorecard.Incorrect)\n .Cells(ReportRow.Omittted).Range.Text = CStr(this_scorecard.Omittted)\n .Cells(ReportRow.Added).Range.Text = CStr(this_scorecard.Added)\n .Cells(ReportRow.TotalErrors).Range.Text = CStr(this_scorecard.TotalErrors)\n .Cells(ReportRow.Score).Range.Text = CStr(this_scorecard.Score)\n\n End With\n\nEnd Sub\n\nSub InsertReportTable(ByRef this_range, Optional ByVal this_rows As Long = -1, Optional ByVal this_columns As Long = -1)\n\nDim my_rows As Long\nDim my_columns As Long\n\n my_rows = IIf(this_rows = -1, ReportRow.[_Last], this_rows)\n my_columns = IIf(this_columns = -1, TABLE_COLUMNS, this_columns)\n this_range.Tables.Add this_range, my_rows, my_columns\n\n With this_range.Tables(1).Range.COLUMNS(1)\n\n .Cells(ReportRow.Incorrect).Range.Text = \"Incorrect:\"\n .Cells(ReportRow.Omittted).Range.Text = \"Omitted:\"\n .Cells(ReportRow.Added).Range.Text = \"Added:\"\n .Cells(ReportRow.TotalErrors).Range.Text = \"Total Errors:\"\n .Cells(ReportRow.Score).Range.Text = \"Score:\"\n .Cells(ReportRow.GraderName).Range.Text = \"Grader's name\"\n\n End With\n\n this_range.Tables(1).Range.Paragraphs.Alignment = wdAlignParagraphLeft\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T17:33:39.820", "Id": "215438", "ParentId": "215080", "Score": "1" } } ]
{ "AcceptedAnswerId": "215266", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T08:05:38.627", "Id": "215080", "Score": "4", "Tags": [ "vba", "ms-word" ], "Title": "A Word macro that processes trainees' dictation, highlighting errors and checking accuracy" }
215080
<p>I created a Java Swing Minesweeper, for which I would like some feedback. Note : I'm just in high school so please excuse any 'dumb' ways I may have coded certain segments.</p> <p>Any tips or books on how to improve the general quality of the code, or any information that will help me become better are deeply appreciated.</p> <p>Apart from feedback, I would also like to know how to preserve colours in buttons which I have disabled. In the context that, to make an already clicked cell unclickable again, I just disabled it. Or, is there a better way to do the same task?</p> <p>The blueprint for the code is :</p> <ol> <li><p>Real Board(buttons[][] for the user to click).</p></li> <li><p>MyBoard (back-end to configure number counts of each cell, etc.</p></li> <li><p>Methods to handle each event of the game.</p></li> </ol> <p>Please excuse any ambiguity in language.</p> <pre><code>package MinesweeperGame; //Following is the implementation of Minesweeper. import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class Minesweeper extends JFrame implements ActionListener, MouseListener{ JFrame frame = new JFrame(); JButton reset = new JButton("Reset"); //Reset Button as a side. JButton giveUp = new JButton("Give Up"); //Similarly, give up button. JPanel ButtonPanel = new JPanel(); Container grid = new Container(); int[][] counts; //integer array to store counts of each cell. Used as a back-end for comparisons. JButton[][] buttons; //Buttons array to use as a front end for the game. int size,diff; final int MINE = 10; /** @param size determines the size of the board */ public Minesweeper(int size){ super("Minesweeper"); this.size = size; counts = new int[size][size]; buttons = new JButton[size][size]; frame.setSize(900,900); frame.setLayout(new BorderLayout()); frame.add(ButtonPanel,BorderLayout.SOUTH); reset.addActionListener(this); giveUp.addActionListener(this); grid.setLayout(new GridLayout(size,size)); for(int a = 0; a &lt; buttons.length; a++) { for(int b = 0; b &lt; buttons[0].length; b++) { buttons[a][b] = new JButton(); buttons[a][b].addActionListener(this); grid.add(buttons[a][b]); } } // above initializes each button in the minesweeper board and gives it functionality. ButtonPanel.add(reset); ButtonPanel.add(giveUp); // adding buttons to the panel. frame.add(grid,BorderLayout.CENTER); createMines(size); //calling function to start the game by filling mines. frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //frame stuff frame.setVisible(true); } /** * Function to check whether user has lost the game ( i.e clicked a mine). * @param m indicated whether the function has been called when user clicks a mine( m=1) * or when he clicks the give up button.(m = any other integer). * Shows a dialog box which tells the user that they have lost the game. */ public void takeTheL(int m){ for(int x = 0; x &lt; size; x++) { for(int y = 0; y &lt; size; y++) { if(buttons[x][y].isEnabled()) // when a button has been clicked, it is disabled. { if(counts[x][y] != MINE) { buttons[x][y].setText(""+ counts[x][y]); } else { buttons[x][y].setText("X"); } buttons[x][y].setEnabled(false); } } } JOptionPane.showMessageDialog(null, m==1? "You clicked a mine!":"You Gave Up", "Game Over", JOptionPane.ERROR_MESSAGE); } /** * Function to check whether user has won or not * It performs this by checking whether a cell that is NOT a mine * remains to be clicked by the user. * (Works because, when a user clicks a button, it is disabled to avoid further moves on the same cell). * Function prints a pop-up message congratulating user on victory. */ public void takeTheW() { boolean won = true; for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { if(counts[i][j] != MINE &amp;&amp; buttons[i][j].isEnabled()) { won = false; } } } if(won) { JOptionPane.showMessageDialog(null,"You have won!", "Congratulations!", JOptionPane.INFORMATION_MESSAGE); } } @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource() == reset) //resets grid { for(int x = 0; x &lt; size; x++) { for(int y = 0; y &lt; size; y++) { buttons[x][y].setEnabled(true); buttons[x][y].setText(""); } } createMines(30); //triggers a new game. } else if(ae.getSource() == giveUp) //user has given up. trigger takeTheL( m!= 1). { takeTheL(0); // anything not = 1 } else // click was on a cell { for(int x = 0; x &lt; size; x++) { for( int y = 0; y &lt; size; y++) { if(ae.getSource() == buttons[x][y]) { switch (counts[x][y]) { case MINE: buttons[x][y].setForeground(Color.RED); buttons[x][y].setIcon(new ImageIcon("")); // add bomb image takeTheL(1); //user clicked on a mine break; case 0: buttons[x][y].setText(counts[x][y] +""); buttons[x][y].setEnabled(false); ArrayList&lt;Integer&gt; clear = new ArrayList&lt;&gt;(); clear.add(x*100+y); dominoEffect(clear); // To recursively clear all surrounding '0' cells. takeTheW(); //checks win every move break; default: buttons[x][y].setText(""+counts[x][y]); buttons[x][y].setEnabled(false); takeTheW(); // its a number &gt; 0 and not a mine, so just check for win break; } } } } } } /** * Function creates mines at random positions. * @param s the size of the board(row or column count) */ public void createMines(int s){ ArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;(); //Modifiable array to store pos. of mines. for(int x = 0; x &lt; s; x++) { for(int y = 0; y &lt; s; y++) { list.add(x*100+y); // x &amp; y shall be individually retrieved by dividing by 100 and modulo 100 respectively. // refer to lines 284 and 285 for implementation } } counts = new int[s][s]; //resetting back-end array for(int a = 0; a &lt; (int)(s * 1.5); a++) { int choice = (int)(Math.random() * list.size()); counts [list.get(choice) / 100] [list.get(choice) % 100] = MINE; //Using corollary of before-last comment to set mines as well. list.remove(choice); // We don't want two mines in the same pos., so remove that pos. from list. } /* Following segment initializes 'neighbor counts' for each cell. That is, the number of mines that are present in the eight surrounding cells. IF the cell isn't a mine. Note : It is done in the back-end array as that contains the numbers (MINE or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) */ for(int x = 0; x &lt; s; x++) { for(int y = 0; y &lt; s; y++) { if(counts[x][y] != MINE) { int neighbor = 0; if( x &gt; 0 &amp;&amp; y &gt; 0 &amp;&amp; counts[x-1][y-1] == MINE) //top left { neighbor++; } if( y &gt; 0 &amp;&amp; counts[x][y-1] == MINE) //left { neighbor++; } if( y &lt; size - 1 &amp;&amp; counts[x][y+1] == MINE) //right { neighbor++; } if( x &lt; size - 1 &amp;&amp; y &gt; 0 &amp;&amp; counts[x+1][y-1] == MINE) //bottom left { neighbor++; } if( x &gt; 0 &amp;&amp; counts[x-1][y] == MINE) //up { neighbor++; } if( x &lt; size - 1 &amp;&amp; counts[x+1][y] == MINE)//down { neighbor++; } if( x &gt; 0 &amp;&amp; y &lt; size - 1 &amp;&amp;counts[x-1][y+1] == MINE) //top right { neighbor++; } if( x &lt; size - 1 &amp;&amp; y &lt; size - 1 &amp;&amp; counts[x+1][y+1] == MINE) //bottom right { neighbor++; } counts[x][y] = neighbor; //setting value } } } } /** * This function, called the domino effect, is an implementation of the idea that, * when a cell with no surrounding mines is clicked, there's no point in user clicking * all eight surrounding cells. Therefore, all surrounding * cells' counts will be displayed in corresponding cells. * The above is done recursively. * @param toClear the ArrayList which is passed to the function with positions in array * that are zero, and are subsequently clicked. */ public void dominoEffect(ArrayList&lt;Integer&gt; toClear){ if(toClear.isEmpty()) return; //base case int x = toClear.get(0) / 100; //getting x pos. int y = toClear.get(0) % 100; //getting y pos. toClear.remove(0); //remove that element from array to prevent infinite recursion. if(counts[x][y] == 0) { //similar to neighbor counts, each surrounding cell is filled if( x &gt; 0 &amp;&amp; y &gt; 0 &amp;&amp; buttons[x-1][y-1].isEnabled()) //top left { buttons[x-1][y-1].setText(counts[x-1][y-1] + ""); buttons[x-1][y-1].setEnabled(false); if(counts[x-1][y-1] == 0) { toClear.add((x-1)*100 + (y-1)); //to recursively implement, each surrounding cell is the new cell, // the surrounding cells of which we shall check and so on. } } if( y &gt; 0 &amp;&amp; buttons[x][y-1].isEnabled()) //left { buttons[x][y-1].setText(counts[x][y-1] + ""); buttons[x][y-1].setEnabled(false); if(counts[x][y-1] == 0) { toClear.add(x*100 + (y-1)); } } if( y &lt; size - 1 &amp;&amp; buttons[x][y+1].isEnabled()) //right { buttons[x][y+1].setText(counts[x][y+1] + ""); buttons[x][y+1].setEnabled(false); if(counts[x][y+1] == 0) { toClear.add(x*100 + (y+1)); } } if( x &lt; size - 1 &amp;&amp; y &gt; 0 &amp;&amp; buttons[x+1][y-1].isEnabled()) //bottom left { buttons[x+1][y-1].setText(counts[x+1][y-1] + ""); buttons[x+1][y-1].setEnabled(false); if(counts[x+1][y-1] == 0) { toClear.add((x+1)*100 + (y-1)); } } if( x &gt; 0 &amp;&amp; buttons[x-1][y].isEnabled()) //up { buttons[x-1][y].setText(counts[x-1][y] + ""); buttons[x-1][y].setEnabled(false); if(counts[x-1][y] == 0) { toClear.add((x-1)*100 + y); } } if( x &lt; size - 1 &amp;&amp; buttons[x+1][y].isEnabled())//down { buttons[x+1][y].setText(counts[x+1][y] + ""); buttons[x+1][y].setEnabled(false); if(counts[x+1][y] == 0) { toClear.add((x+1)*100 + y); } } if( x &gt; 0 &amp;&amp; y &lt; size - 1 &amp;&amp; buttons[x-1][y+1].isEnabled()) //top right { buttons[x-1][y+1].setText(counts[x-1][y+1] + ""); buttons[x-1][y+1].setEnabled(false); if(counts[x-1][y+1] == 0) { toClear.add((x-1)*100 + (y+1)); } } if( x &lt; size - 1 &amp;&amp; y &lt; size - 1 &amp;&amp; buttons[x+1][y+1].isEnabled()) //bottom right { buttons[x+1][y+1].setText(counts[x+1][y+1] + ""); buttons[x+1][y+1].setEnabled(false); if(counts[x+1][y+1] == 0) { toClear.add((x+1)*100 + (y+1)); } } } dominoEffect(toClear); //recursive call with list containing surrounding cells, for further check-and-clear of THEIR surr. cells. } //Main method. public static void main(String[] args){ new Minesweeper(20); // Can be made of any size. (For now only squares) } @Override public void mouseClicked(MouseEvent me) { if (SwingUtilities.isRightMouseButton(me)){ // TODO : Handle flagging of mines. } } @Override public void mousePressed(MouseEvent me) { // Do nothing } @Override public void mouseReleased(MouseEvent me) { // Do nothing } @Override public void mouseEntered(MouseEvent me) { // Do nothing } @Override public void mouseExited(MouseEvent me) { // Do nothing } } </code></pre>
[]
[ { "body": "<p>First step would be to study the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC</a> design pattern. Now you have all your code in one file. Separate the logic of the game into a separate \"minesweeper engine\" class that is not dependant on the Swing framework. Make the engine send events to your user interface.</p>\n\n<p>As to code style, take a look at some of the Java-tagged posts here to get an idea about how to format code and declare variables (you're not following too many known good practises).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:37:46.413", "Id": "416249", "Score": "0", "body": "Yes I admit takeTheL and takeTheW were a little naughty, for instance, but I certainly will look up the posts you pointed to, Thank you :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T07:26:47.017", "Id": "215171", "ParentId": "215081", "Score": "0" } }, { "body": "<h1>Introduction</h1>\n\n<p>Your answer reminded me of the time I was in high school, writing things like you did, with Swing and stuff. I decided to re-live that time and dedicated quite some time to write a comprehensive answer and explaining all major decisions made.</p>\n\n<h1>Points to improve upon</h1>\n\n<ol>\n<li>You implement <code>MouseListener</code> but never actually use it. I'd remove that completely. Using the <code>ActionListener</code> suffices. Unless you add the functionality for flagging mines. Which seems to be a future addition. Read on to see a more elegant solution.</li>\n<li>Minesweeper extends JFrame but ends up using a local one. What was the use of inheriting it in the first place?</li>\n<li>You maintain two separate arrays for maintaining the counts and the Buttons. You can greatly improve the general readability of the code and its ease of use (and maintenance) if you apply some OOP here. My solution is to make a class called Cell that extends JButton and adds location and count storage.</li>\n<li>The way you map <span class=\"math-container\">\\$(x, y)\\$</span> coordinate pairs to integers is non-general. Why the <span class=\"math-container\">\\$100\\$</span>? It seems arbitrary. In fact, you can achieve the same thing (unique mapping) by using <code>size</code> instead of <span class=\"math-container\">\\$100\\$</span>. It can also generalize to cases when the size of the grid extends beyond <span class=\"math-container\">\\$100\\$</span>, where using a fixed constant would stop resulting in unique numbers.</li>\n<li>There is a lot of duplication of code. Especially when you check whether a cell's neighbors are mines or zero-valued. I presented a solution where you obtain all the valid neighbors and perform operations on them.</li>\n<li>The <code>dominoEffect</code> method is not named according to the guideline of having methods named as verbs or verb phrases. <code>cascade</code> is the one I used. Also, <code>takeTheW</code> and <code>takeTheL</code> might be fine but I don't prefer them. Always prefer names which describe what the method is doing.</li>\n<li>The recursion you implemented is <em>tail-recursive</em>, which means it can be replaced by an appropriate loop, thereby avoiding a lot of overhead.</li>\n<li>The ActionLister (and later, the MouseListener) interface can be implemented anonymously and stored in a variable. This reduces the clutter.</li>\n<li>Prefer booleans when you are choosing between only two possible outcomes for an integer. Case in point: the parameter <code>m</code> in <code>takeTheL()</code>.</li>\n<li>Use better data structures when you are relying on operations that are carried out frequently to be carried out efficiently. I'd suggest replacing your array list with Sets.</li>\n<li>Swing Applications should be launched on a separate thread. Refer to my <code>main</code> method in the refactored code.</li>\n<li>There are a few more converns but I've included them all in the refactored code that I present in the next section.</li>\n</ol>\n\n<h1>The Refactored Program</h1>\n\n<p>Admittedly, I skimped on the comments, but I believe the code is readable and self-explanatory. Leave a comment if you don't understand a particular snippet.</p>\n\n<pre><code>package minesweeperimproved;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionListener;\nimport java.util.*;\n\n/**\n * This is the refactored version of the code presented in\n * this post at CodeReview.SE:\n * &lt;p&gt;\n * https://codereview.stackexchange.com/questions/215081/created-a-minesweeper-game-on-java-using-swing-gui-i-wish-to-undertake-improvem\n * &lt;p&gt;\n * Original author: greyothello (https://codereview.stackexchange.com/users/194786/greyothello)\n * Refactored by: HungryBlueDev (https://codereview.stackexchange.com/users/37479/hungry-blue-dev)\n */\npublic class Minesweeper {\n // The value assigned to cells marked as mines. 10 works\n // because no cell will have more than 8 neighbouring mines.\n private static final int MINE = 10;\n // The size in pixels for the frame.\n private static final int SIZE = 500;\n\n // The number of mines at generated is the grid size * this constant\n private static final double POPULATION_CONSTANT = 1.5;\n\n // This fixed amount of memory is to avoid repeatedly declaring\n // new arrays every time a cell's neighbours are to be retrieved.\n private static Cell[] reusableStorage = new Cell[8];\n\n private int gridSize;\n\n private Cell[][] cells;\n\n private JFrame frame;\n private JButton reset;\n private JButton giveUp;\n\n private final ActionListener actionListener = actionEvent -&gt; {\n Object source = actionEvent.getSource();\n if (source == reset) {\n createMines();\n } else if (source == giveUp) {\n revealBoardAndDisplay(\"You gave up.\");\n } else {\n handleCell((Cell) source);\n }\n };\n\n private class Cell extends JButton {\n private final int row;\n private final int col;\n private int value;\n\n Cell(final int row, final int col,\n final ActionListener actionListener) {\n this.row = row;\n this.col = col;\n addActionListener(actionListener);\n setText(\"\");\n }\n\n int getValue() {\n return value;\n }\n\n void setValue(int value) {\n this.value = value;\n }\n\n boolean isAMine() {\n return value == MINE;\n }\n\n void reset() {\n setValue(0);\n setEnabled(true);\n setText(\"\");\n }\n\n void reveal() {\n setEnabled(false);\n setText(isAMine() ? \"X\" : String.valueOf(value));\n }\n\n void updateNeighbourCount() {\n getNeighbours(reusableStorage);\n for (Cell neighbour : reusableStorage) {\n if (neighbour == null) {\n break;\n }\n if (neighbour.isAMine()) {\n value++;\n }\n }\n }\n\n void getNeighbours(final Cell[] container) {\n // Empty all elements first\n for (int i = 0; i &lt; reusableStorage.length; i++) {\n reusableStorage[i] = null;\n }\n\n int index = 0;\n\n for (int rowOffset = -1; rowOffset &lt;= 1; rowOffset++) {\n for (int colOffset = -1; colOffset &lt;= 1; colOffset++) {\n // Make sure that we don't count ourselves\n if (rowOffset == 0 &amp;&amp; colOffset == 0) {\n continue;\n }\n int rowValue = row + rowOffset;\n int colValue = col + colOffset;\n\n if (rowValue &lt; 0 || rowValue &gt;= gridSize\n || colValue &lt; 0 || colValue &gt;= gridSize) {\n continue;\n }\n\n container[index++] = cells[rowValue][colValue];\n }\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null || getClass() != obj.getClass())\n return false;\n Cell cell = (Cell) obj;\n return row == cell.row &amp;&amp;\n col == cell.col;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(row, col);\n }\n }\n\n private Minesweeper(final int gridSize) {\n this.gridSize = gridSize;\n cells = new Cell[gridSize][gridSize];\n\n frame = new JFrame(\"Minesweeper\");\n frame.setSize(SIZE, SIZE);\n frame.setLayout(new BorderLayout());\n\n initializeButtonPanel();\n initializeGrid();\n\n frame.setLocationRelativeTo(null);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n\n private void initializeButtonPanel() {\n JPanel buttonPanel = new JPanel();\n\n reset = new JButton(\"Reset\");\n giveUp = new JButton(\"Give Up\");\n\n reset.addActionListener(actionListener);\n giveUp.addActionListener(actionListener);\n\n buttonPanel.add(reset);\n buttonPanel.add(giveUp);\n frame.add(buttonPanel, BorderLayout.SOUTH);\n }\n\n private void initializeGrid() {\n Container grid = new Container();\n grid.setLayout(new GridLayout(gridSize, gridSize));\n\n for (int row = 0; row &lt; gridSize; row++) {\n for (int col = 0; col &lt; gridSize; col++) {\n cells[row][col] = new Cell(row, col, actionListener);\n grid.add(cells[row][col]);\n }\n }\n createMines();\n frame.add(grid, BorderLayout.CENTER);\n }\n\n private void resetAllCells() {\n for (int row = 0; row &lt; gridSize; row++) {\n for (int col = 0; col &lt; gridSize; col++) {\n cells[row][col].reset();\n }\n }\n }\n\n private void createMines() {\n resetAllCells();\n\n final int mineCount = (int) POPULATION_CONSTANT * gridSize;\n final Random random = new Random();\n\n // Map all (row, col) pairs to unique integers\n Set&lt;Integer&gt; positions = new HashSet&lt;&gt;(gridSize * gridSize);\n for (int row = 0; row &lt; gridSize; row++) {\n for (int col = 0; col &lt; gridSize; col++) {\n positions.add(row * gridSize + col);\n }\n }\n\n // Initialize mines\n for (int index = 0; index &lt; mineCount; index++) {\n int choice = random.nextInt(positions.size());\n int row = choice / gridSize;\n int col = choice % gridSize;\n cells[row][col].setValue(MINE);\n positions.remove(choice);\n }\n\n // Initialize neighbour counts\n for (int row = 0; row &lt; gridSize; row++) {\n for (int col = 0; col &lt; gridSize; col++) {\n if (!cells[row][col].isAMine()) {\n cells[row][col].updateNeighbourCount();\n }\n }\n }\n }\n\n private void handleCell(Cell cell) {\n if (cell.isAMine()) {\n cell.setForeground(Color.RED);\n cell.reveal();\n revealBoardAndDisplay(\"You clicked on a mine!\");\n return;\n }\n if (cell.getValue() == 0) {\n Set&lt;Cell&gt; positions = new HashSet&lt;&gt;();\n positions.add(cell);\n cascade(positions);\n } else {\n cell.reveal();\n }\n checkForWin();\n }\n\n private void revealBoardAndDisplay(String message) {\n for (int row = 0; row &lt; gridSize; row++) {\n for (int col = 0; col &lt; gridSize; col++) {\n if (!cells[row][col].isEnabled()) {\n cells[row][col].reveal();\n }\n }\n }\n\n JOptionPane.showMessageDialog(\n frame, message, \"Game Over\",\n JOptionPane.ERROR_MESSAGE\n );\n\n createMines();\n }\n\n private void cascade(Set&lt;Cell&gt; positionsToClear) {\n while (!positionsToClear.isEmpty()) {\n // Set does not have a clean way for retrieving\n // a single element. This is the best way I could think of.\n Cell cell = positionsToClear.iterator().next();\n positionsToClear.remove(cell);\n cell.reveal();\n\n cell.getNeighbours(reusableStorage);\n for (Cell neighbour : reusableStorage) {\n if (neighbour == null) {\n break;\n }\n if (neighbour.getValue() == 0\n &amp;&amp; neighbour.isEnabled()) {\n positionsToClear.add(neighbour);\n } else {\n neighbour.reveal();\n }\n }\n }\n }\n\n private void checkForWin() {\n boolean won = true;\n outer:\n for (Cell[] cellRow : cells) {\n for (Cell cell : cellRow) {\n if (!cell.isAMine() &amp;&amp; cell.isEnabled()) {\n won = false;\n break outer;\n }\n }\n }\n\n if (won) {\n JOptionPane.showMessageDialog(\n frame, \"You have won!\", \"Congratulations\",\n JOptionPane.INFORMATION_MESSAGE\n );\n }\n }\n\n private static void run(final int gridSize) {\n try {\n // Totally optional. But this applies the look and\n // feel for the current OS to the a application,\n // making it look native.\n UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n } catch (Exception ignore) { }\n // Launch the program\n new Minesweeper(gridSize);\n }\n\n public static void main(String[] args) {\n final int gridSize = 10;\n SwingUtilities.invokeLater(() -&gt; Minesweeper.run(gridSize));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:41:24.960", "Id": "416250", "Score": "0", "body": "Thank you so much for the effort taken. I go ahead of what we learn in school out of interest, and so a lot of my OOP and structuring data is rather half-baked. I learnt a lot from your refactored code. It is especially readable and consists of concise ways to do what I did. Cheers and thanks again :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:46:24.413", "Id": "416251", "Score": "0", "body": "Also, do you have any suggestions for books or online sources which could help me understand intricacies of OOP and structuring data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:48:37.667", "Id": "416252", "Score": "0", "body": "I formed a question. With regard to this program, is there any other advantage to using sets rather than lists other than the fact that sets are unordered and don't allow duplicates? Also, I just realized that I needn't stop the user from making repeated moves on a single cell, as that has no reason to be illegal. Rather, it harms the player." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:16:11.630", "Id": "416290", "Score": "0", "body": "@greyothello The more you write code, the better you will be at recognizing code that is repetitive and could be packaged neatly as an object. If you need a list of books, I'd say [this list](https://javarevisited.blogspot.com/2017/04/top-5-books-to-learn-object-oriented-programming.html) seems good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:18:41.657", "Id": "416292", "Score": "0", "body": "@greyothello The advantage of using a set here is faster insertion and deletion time. Look up the time complexities for operations on Different Data Structures. And your statement on prevent users from making repeated moves seems unclear. Once an area is cleared, you definitely can't \"unclear\" it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:21:43.450", "Id": "416309", "Score": "0", "body": "@greyothello Regarding a set versus a list, consider that the latter suggests that the order matters." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:49:58.697", "Id": "215205", "ParentId": "215081", "Score": "2" } } ]
{ "AcceptedAnswerId": "215205", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T10:14:31.037", "Id": "215081", "Score": "2", "Tags": [ "java", "swing", "minesweeper" ], "Title": "Minesweeper game in Java using Swing GUI" }
215081
<p>I want calculate RSI indicator value for multiple column in Pandas DataFrame. I am looking for a method to avoid loop, here is the code I am using:</p> <pre><code>rsi_calculations = pd.DataFrame() for column in rsi_trans.columns: rsi = ta.RSI(rsi_trans[column].values, timeperiod=30) rsi_calculations[column] = rsi </code></pre> <p>In the above code I am calculating RSI value and appending it to pandas data frame, but its taking more time.</p> <p>Is there a more efficient way to do this?</p> <p><strong>Edit:</strong></p> <p>I've imported TA-Lib as <code>ta</code> and used its <code>RSI</code> function to calculate RSI value.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T11:03:20.633", "Id": "415881", "Score": "0", "body": "yes you need to vectorise your `ta.RSI` function. You haven't said how it is implemented so either; you have to vectorise its original implementation, investigate using `numpy.vectorize`, or potentially explore using `numba` if it is compatible" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T11:06:58.023", "Id": "415883", "Score": "0", "body": "I've added in my question where `ta.RSI` comes from. It's from a module TA-Lib." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T11:46:47.370", "Id": "415884", "Score": "0", "body": "@Attack68 I think main goal of `numpy.vectorize` is to hide a `for` loop rather than enhancing performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T11:52:45.093", "Id": "415885", "Score": "0", "body": "Yes I saw that myself just now actually. Perhaps the only way is to write the function yourself with vectorised numpy, from what I recall rsi is fairly straightforward calculation. Plus might be able to use numba for parallelization or other enhancements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T11:54:59.543", "Id": "415886", "Score": "1", "body": "You might see speed ups if you only do array operations inside the loop and remove the data frame population to the end and do the whole array with one data frame creation - this might be an overhead but I am only speculating" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T11:57:08.197", "Id": "415887", "Score": "0", "body": "I'll try doing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T19:28:20.693", "Id": "416188", "Score": "0", "body": "This might be the solution you are looking for. The RSI calculated in python using only vector calculations. The full code is at the bottom. http://www.andrewshamlet.net/2017/06/10/python-tutorial-rsi/" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T10:51:02.850", "Id": "215085", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "Calculating Relative Strength Index for Multiple Pandas column" }
215085
<p>Sort of completed my bank ATM in C# console project. What do you guys think of the structure/design of this whole solution? There are 2 console projects ( Bank Admin and Bank Customer) and the third project is the back-end repository layer of this two projects. I put single-method-interface in Bank Customer project. Next, I plan to add some logging using log4net library and to add some try catch block to do run garbage collection dispose method for the dbcontext object.</p> <p>Some inconsistency now is the UI. Some UI like Third-Party-Transfer and Bank Account Add Form, I put them in UI class. But the rest are in the 'controller' class. Still find it time-consuming to split the code nicely for console project. Will be easier I guess when I use MVC project type later on.</p> <p>Apologize for those excessive comments which I have yet to clean up.</p> <p>My full source code is my Github - <a href="https://github.com/ngaisteve1/ATMConsole_WithDB" rel="nofollow noreferrer">https://github.com/ngaisteve1/ATMConsole_WithDB</a></p> <p>Below is just the 'controller' class for Bank Customer functions.</p> <pre><code>using BankATMRepository; using BankATMRepositoryInterface; using ConsoleTables; using System; using System.Collections.Generic; using System.Linq; namespace MeybankATMSystem { class MeybankATM : ILogin, IBalance, IDeposit, IWithdrawal, IThirdPartyTransfer { private static int tries; private const int maxTries = 3; private const decimal minimum_kept_amt = 20; //todo: A transaction class with transaction amount can replace these two variable. private static decimal transaction_amt; // No longer store data using list . Replace it with dbcontext ('virtual local db') object. // private static List&lt;BankAccount&gt; _accountList; //private static List&lt;Transaction&gt; _listOfTransactions; private static BankAccount selectedAccount; private static BankAccount inputAccount; // Connect to the database using db context object. //private AppDbContext db = new AppDbContext(); private static AppDbContext ctx = new AppDbContext(); private IBankAccount repoBankAccount = null; private ITransaction repoTransaction = null; public MeybankATM() { this.repoBankAccount = new RepoBankAccount(); this.repoTransaction = new RepoTransaction(); } public MeybankATM(IBankAccount repoBankAccount, ITransaction repoTransaction) { this.repoBankAccount = repoBankAccount; this.repoTransaction = repoTransaction; } public void Execute() { ATMScreen.ShowMenu1(); while (true) { switch (Utility.GetValidIntInputAmt("your option")) { case 1: CheckCardNoPassword(); //_listOfTransactions = new List&lt;Transaction&gt;(); while (true) { ATMScreen.ShowMenu2(); switch (Utility.GetValidIntInputAmt("your option")) { case (int)SecureMenu.CheckBalance: CheckBalance(selectedAccount); break; case (int)SecureMenu.PlaceDeposit: PlaceDeposit(selectedAccount); break; case (int)SecureMenu.MakeWithdrawal: MakeWithdrawal(selectedAccount); break; case (int)SecureMenu.ThirdPartyTransfer: var vMThirdPartyTransfer = new BankATMRepo.VMThirdPartyTransfer(); vMThirdPartyTransfer = ATMScreen.ThirdPartyTransferForm(); PerformThirdPartyTransfer(selectedAccount, vMThirdPartyTransfer); break; case (int)SecureMenu.ViewTransaction: ViewTransaction(selectedAccount.Id); break; case (int)SecureMenu.ChangeATMCardPIN: Console.WriteLine("This function is not ready."); break; case (int)SecureMenu.Logout: Utility.PrintMessage("You have succesfully logout. Please collect your ATM card..", true); Execute(); break; default: Utility.PrintMessage("Invalid Option Entered.", false); break; } } case 2: Console.Write("\nThank you for using Meybank. Exiting program now ."); Utility.printDotAnimation(15); System.Environment.Exit(1); break; default: Utility.PrintMessage("Invalid Option Entered.", false); break; } } } private static void LockAccount() { Console.Clear(); Utility.PrintMessage("Your account is locked.", true); Console.WriteLine("Please go to the nearest branch to unlocked your account."); Console.WriteLine("Thank you for using Meybank. "); Console.ReadKey(); System.Environment.Exit(1); } public void Initialization() { transaction_amt = 0; // Move the data to the database via seeding // Without Entity Framework //_accountList = new List&lt;BankAccount&gt; //{ // new BankAccount() { FullName = "John", AccountNumber=333111, CardNumber = 123, PinCode = 111111, Balance = 2000.00m, isLocked = false }, // new BankAccount() { FullName = "Mike", AccountNumber=111222, CardNumber = 456, PinCode = 222222, Balance = 1500.30m, isLocked = true }, // new BankAccount() { FullName = "Mary", AccountNumber=888555, CardNumber = 789, PinCode = 333333, Balance = 2900.12m, isLocked = false } //}; } public void CheckCardNoPassword() { bool pass = false; while (!pass) { inputAccount = new BankAccount(); Console.WriteLine("\nNote: Actual ATM system will accept user's ATM card to validate"); Console.Write("and read card number, bank account number and bank account status. \n\n"); inputAccount.CardNumber = Utility.GetValidIntInputAmt("ATM Card Number"); Console.Write("Enter 6 Digit PIN: "); inputAccount.PinCode = Convert.ToInt32(Utility.GetHiddenConsoleInput()); // for brevity, length 6 is not validated and data type. Console.Write("\nChecking card number and password."); Utility.printDotAnimation(); // LINQ Query // Without repository layer //var listOfAccounts = from a in db.BankAccounts // select a; // With repository layer var listOfAccounts = repoBankAccount.ViewAllBankAccount(); // Without Entity Framework //foreach (BankAccount account in _accountList) // With Entity Framework foreach (BankAccount account in listOfAccounts) { if (inputAccount.CardNumber.Equals(account.CardNumber)) { selectedAccount = account; if (inputAccount.PinCode.Equals(account.PinCode)) { if (selectedAccount.isLocked) LockAccount(); else pass = true; } else { pass = false; tries++; if (tries &gt;= maxTries) { selectedAccount.isLocked = true; LockAccount(); } } } } if (!pass) Utility.PrintMessage("Invalid Card number or PIN.", false); Console.Clear(); } } public void CheckBalance(BankAccount bankAccount) { Utility.PrintMessage($"Your bank account balance amount is: {Utility.FormatAmount(bankAccount.Balance)}", true); } public void PlaceDeposit(BankAccount account) { Console.WriteLine("\nNote: Actual ATM system will just let you "); Console.Write("place bank notes into ATM machine. \n\n"); transaction_amt = Utility.GetValidDecimalInputAmt($"amount in {ATMScreen.cur}"); System.Console.Write("\nCheck and counting bank notes."); Utility.printDotAnimation(); if (transaction_amt &lt;= 0) Utility.PrintMessage("Amount needs to be more than zero. Try again.", false); else if (transaction_amt % 10 != 0) Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false); else if (!PreviewBankNotesCount(transaction_amt)) Utility.PrintMessage($"You have cancelled your action.", false); else { // Bind transaction_amt to Transaction object // Add transaction record - Start var transaction = new Transaction() { AccountID = account.Id, BankAccountNoTo = account.AccountNumber, TransactionType = TransactionType.Deposit, TransactionAmount = transaction_amt, TransactionDate = DateTime.Now }; //InsertTransaction(transaction); repoTransaction.InsertTransaction(transaction); // Add transaction record - End // Another method to update account balance. account.Balance = account.Balance + transaction_amt; // Entity framework. To sync changes from dbcontext ('virtual local db') to physical db. ctx.SaveChanges(); Utility.PrintMessage($"You have successfully deposited {Utility.FormatAmount(transaction_amt)}", true); } } public void MakeWithdrawal(BankAccount account) { Console.WriteLine("\nNote: For GUI or actual ATM system, user can "); Console.Write("choose some default withdrawal amount or custom amount. \n\n"); transaction_amt = Utility.GetValidDecimalInputAmt($"amount {ATMScreen.cur}"); if (transaction_amt &lt;= 0) Utility.PrintMessage("Amount needs to be more than zero. Try again.", false); else if (transaction_amt &gt; account.Balance) Utility.PrintMessage($"Withdrawal failed. You do not have enough fund to withdraw {Utility.FormatAmount(transaction_amt)}", false); else if ((account.Balance - transaction_amt) &lt; minimum_kept_amt) Utility.PrintMessage($"Withdrawal failed. Your account needs to have minimum {Utility.FormatAmount(minimum_kept_amt)}", false); else if (transaction_amt % 10 != 0) Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false); else { // Bind transaction_amt to Transaction object // Add transaction record - Start var transaction = new Transaction() { AccountID = account.Id, BankAccountNoFrom = account.AccountNumber, TransactionType = TransactionType.Withdrawal, TransactionAmount = transaction_amt, TransactionDate = DateTime.Now }; //InsertTransaction(transaction); repoTransaction.InsertTransaction(transaction); // Add transaction record - End // Another method to update account balance. account.Balance = account.Balance - transaction_amt; // Entity framework. To sync changes from dbcontext ('virtual local db') to physical db. ctx.SaveChanges(); Utility.PrintMessage($"Please collect your money. You have successfully withdraw {Utility.FormatAmount(transaction_amt)}", true); } } private static bool PreviewBankNotesCount(decimal amount) { int hundredNotesCount = (int)amount / 100; int fiftyNotesCount = ((int)amount % 100) / 50; int tenNotesCount = ((int)amount % 50) / 10; Console.WriteLine("\nSummary"); Console.WriteLine("-------"); Console.WriteLine($"{ATMScreen.cur} 100 x {hundredNotesCount} = {100 * hundredNotesCount}"); Console.WriteLine($"{ATMScreen.cur} 50 x {fiftyNotesCount} = {50 * fiftyNotesCount}"); Console.WriteLine($"{ATMScreen.cur} 10 x {tenNotesCount} = {10 * tenNotesCount}"); Console.Write($"Total amount: {Utility.FormatAmount(amount)}\n\n"); string opt = Utility.GetValidIntInputAmt("1 to confirm or 0 to cancel").ToString(); return (opt.Equals("1")) ? true : false; } public void ViewTransaction(int accountID) { //Without Entity Framework - if (_listOfTransactions.Count &lt;= 0) // Before repository layer - db.Transactions.Count() // After repository layer, //if (repoTransaction.GetTransactionCount(accountNumber) == 0) if (repoTransaction.GetTransactionCount(accountID) == 0) Utility.PrintMessage($"There is no transaction yet.", true); else { var table = new ConsoleTable("Id","Type", "From", "To", "Amount", "Trans Date Time"); // Without Entity Framework - foreach (var tran in _listOfTransactions) // With Entity Framework // Without repository layer //var transactionsOrder = (from t in db.Transactions // orderby t.TransactionDate descending // select t).Take(5); // SELECT Top 5 // With repository layer, Console.WriteLine(repoTransaction.GetTransactionCount(accountID)); foreach (var tran in repoTransaction.ViewTopLatestTransactions(accountID, 5)) { table.AddRow(tran.TransactionId,tran.TransactionType, tran.BankAccountNoFrom, tran.BankAccountNoTo, Utility.FormatAmount(tran.TransactionAmount), tran.TransactionDate); } table.Options.EnableCount = false; table.Write(); //Without Entity Framework - Utility.PrintMessage($"You have performed {_listOfTransactions.Count} transactions.", true); Utility.PrintMessage($"You have performed {repoTransaction.GetTransactionCount(accountID)} transactions.", true); } } //public void InsertTransaction(Transaction transaction) //{ // // Without Entity Framework - _listOfTransactions.Add(transaction); // // With Entity Framework // db.Transactions.Add(transaction); // // With Entity Framework // db.SaveChanges(); //} public void PerformThirdPartyTransfer(BankAccount bankAccount, BankATMRepo.VMThirdPartyTransfer vMThirdPartyTransfer) { if (vMThirdPartyTransfer.TransferAmount &lt;= 0) Utility.PrintMessage("Amount needs to be more than zero. Try again.", false); else if (vMThirdPartyTransfer.TransferAmount &gt; bankAccount.Balance) // Check giver's account balance - Start Utility.PrintMessage($"Withdrawal failed. You do not have enough fund to withdraw {Utility.FormatAmount(transaction_amt)}", false); else if (bankAccount.Balance - vMThirdPartyTransfer.TransferAmount &lt; 20) Utility.PrintMessage($"Withdrawal failed. Your account needs to have minimum {Utility.FormatAmount(minimum_kept_amt)}", false); // Check giver's account balance - End else { // Check if receiver's bank account number is valid. // Without Entity framework - //var selectedBankAccountReceiver = (from b in _accountList // where b.AccountNumber == vMThirdPartyTransfer.RecipientBankAccountNumber // select b).FirstOrDefault(); // With Entity framework // Without repository layer //var selectedBankAccountReceiver = (from b in db.BankAccounts // where b.AccountNumber == vMThirdPartyTransfer.RecipientBankAccountNumber // select b).FirstOrDefault(); // With repository layer var selectedBankAccountReceiver = repoBankAccount.ViewBankAccount(vMThirdPartyTransfer.RecipientBankAccountNumber); if (selectedBankAccountReceiver == null) Utility.PrintMessage($"Third party transfer failed. Receiver bank account number is invalid.", false); else if (selectedBankAccountReceiver.FullName != vMThirdPartyTransfer.RecipientBankAccountName) Utility.PrintMessage($"Third party transfer failed. Recipient's account name does not match.", false); else { // Bind transaction_amt to Transaction object // Add transaction record - Start Transaction transaction = new Transaction() { AccountID = bankAccount.Id, BankAccountNoFrom = bankAccount.AccountNumber, BankAccountNoTo = vMThirdPartyTransfer.RecipientBankAccountNumber, TransactionType = TransactionType.ThirdPartyTransfer, TransactionAmount = vMThirdPartyTransfer.TransferAmount, TransactionDate = DateTime.Now }; // Without Entity framework - _listOfTransactions.Add(transaction); // With Entity Framework //db.Transactions.Add(transaction); repoTransaction.InsertTransaction(transaction); Utility.PrintMessage($"You have successfully transferred out {Utility.FormatAmount(vMThirdPartyTransfer.TransferAmount)} to {vMThirdPartyTransfer.RecipientBankAccountName}", true); // Add transaction record - End // Update balance amount (Giver) bankAccount.Balance = bankAccount.Balance - vMThirdPartyTransfer.TransferAmount; // Update balance amount (Receiver) selectedBankAccountReceiver.Balance = selectedBankAccountReceiver.Balance + vMThirdPartyTransfer.TransferAmount; // With Entity framework. To sync changes from dbcontext ('virtual local db') to physical db. ctx.SaveChanges(); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T17:17:42.667", "Id": "420146", "Score": "1", "body": "It seems to me your `Execute` method violates Single Responsibility and Open-Closed principle. Problem with it is when you need some extra functionality - you are going to add new code to switch statement. That's what's called modification. https://blog.bitsrc.io/solid-principles-every-developer-should-know-b3bfa96bb688" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T17:24:09.647", "Id": "420147", "Score": "1", "body": "Also, ATM functionality can be handled using Chain Of Responsibility pattern - google it, it helps to follow SOLID principles. With it your app is highly maintainable and testable. https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern#C#_example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-11T08:15:04.940", "Id": "420220", "Score": "0", "body": "Thanks a lot for the comment" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T10:52:59.890", "Id": "215086", "Score": "0", "Tags": [ "c#", "console" ], "Title": "Bank ATM in C# Console Project" }
215086
<p>This is a 2nd follow-up to my <a href="https://codereview.stackexchange.com/questions/192103/scheduler-built-with-observables-v2-follow-up">previous</a> one about a <code>Scheduler</code> built with observables.</p> <p>Although the last one was working correctly, it was only possible to see this in LINQPad which I didn't like very much. I prefer to have proper tests so I've redesigned it a little bit to make testing possible.</p> <hr /> <h2>Core</h2> <p>The <code>Scheduler</code> itself is now pretty simple. It requires an observable that produces ticks which it turns into a hot-observable. On each tick a each job's triggers are evaluated and jobs which match the trigger are executed.</p> <p>Unscheduling jobs is a blocking operation when a timeout is pecified.</p> <pre><code>public class Scheduler : IDisposable { private readonly IConnectableObservable&lt;DateTime&gt; _scheduler; private readonly IDisposable _disconnect; public Scheduler(IObservable&lt;DateTime&gt; ticks) { // Not using .RefCount here because it should be ticking regardless of subscriptions. _scheduler = ticks.Publish(); _disconnect = _scheduler.Connect(); } public IDisposable Schedule(Job job, CancellationToken cancellationToken = default) { var unschedule = _scheduler // .ToList the results so that all triggers have the chance to evaluate the tick. .Where(tick =&gt; job.Triggers.Select(t =&gt; t.Matches(tick)).ToList().Any(x =&gt; x)) .Subscribe(timestamp =&gt; job.Execute(cancellationToken)); return Disposable.Create(() =&gt; { job.Continuation.Wait(job.UnscheduleTimeout); unschedule.Dispose(); }); } public void Dispose() { // Stop ticking. _disconnect.Dispose(); } } </code></pre> <hr /> <p>The <code>Job</code> class is handling job's triggers and tasks and keeping them within the specified max-degree-of-parallelism.</p> <pre><code>public class Job { private readonly List&lt;Task&gt; _tasks = new List&lt;Task&gt;(); public Job(string name, IEnumerable&lt;Trigger&gt; trigger, Func&lt;CancellationToken, Task&gt; action) { Name = name; Triggers = trigger.ToList(); Action = action; } public string Name { get; } public IEnumerable&lt;Trigger&gt; Triggers { get; } public Func&lt;CancellationToken, Task&gt; Action { get; } public Action&lt;Job&gt; OnMisfire { get; set; } public DegreeOfParallelism MaxDegreeOfParallelism { get; set; } = 1; public TimeSpan UnscheduleTimeout { get; set; } public Task Continuation =&gt; Task.WhenAll(_tasks).ContinueWith(_ =&gt; _tasks.Clear()); public int Count =&gt; _tasks.Count; public void Execute(CancellationToken cancellationToken) { if (CanExecute()) { var jobTask = Action(cancellationToken); _tasks.Add(jobTask); jobTask.ContinueWith(_ =&gt; _tasks.Remove(jobTask), cancellationToken); } else { OnMisfire?.Invoke(this); } } private bool CanExecute() { return MaxDegreeOfParallelism.Equals(DegreeOfParallelism.Unlimited) || Count &lt; MaxDegreeOfParallelism.Value; } } </code></pre> <hr /> <p>The <code>DegreeOfParallelism</code> is an anti-primitive-obsession wrapper for <code>int</code>.</p> <pre><code>public class DegreeOfParallelism : Primitive&lt;int&gt; { private const int UnlimitedValue = -1; public DegreeOfParallelism(int value) : base(value) { } public static readonly DegreeOfParallelism Unlimited = new DegreeOfParallelism(UnlimitedValue); protected override void Validate(int value) { if (value == UnlimitedValue) { return; } if (value &lt; 1) { throw new ArgumentException(&quot;Value must be positive.&quot;); } } public static implicit operator DegreeOfParallelism(int value) =&gt; new DegreeOfParallelism(value); } </code></pre> <p>It is supported by the base class <code>Primitive&lt;T&gt;</code> which implements basic operators, equality and comparer.</p> <pre><code>[PublicAPI] [CannotApplyEqualityOperator] public abstract class Primitive&lt;T&gt; : IEquatable&lt;Primitive&lt;T&gt;&gt;, IComparable&lt;Primitive&lt;T&gt;&gt; { private static readonly IComparer&lt;Primitive&lt;T&gt;&gt; Comparable = ComparerFactory&lt;Primitive&lt;T&gt;&gt;.Create(p =&gt; p.Value); protected Primitive(T value) { // ReSharper disable once VirtualMemberCallInConstructor - it's ok to do this here because Validate is stateless. Validate(Value = value); } protected abstract void Validate(T value); [AutoEqualityProperty] public T Value { get; } #region IEquatable public bool Equals(Primitive&lt;T&gt; other) =&gt; AutoEquality&lt;Primitive&lt;T&gt;&gt;.Comparer.Equals(this, other); public override bool Equals(object obj) =&gt; obj is T other &amp;&amp; Equals(other); public override int GetHashCode() =&gt; AutoEquality&lt;Primitive&lt;T&gt;&gt;.Comparer.GetHashCode(this); #endregion #region IComparable public int CompareTo(Primitive&lt;T&gt; other) =&gt; Comparable.Compare(this, other); #endregion public static implicit operator T(Primitive&lt;T&gt; primitive) =&gt; primitive.Value; } </code></pre> <hr /> <p>Triggers that I use are currently very simple too. It's just a base class that provides a single method for checking whether the trigger <code>Matches</code>. I have two of them.</p> <pre><code>public abstract class Trigger { public abstract bool Matches(DateTime tick); } public class CronTrigger : Trigger { private readonly CronExpression _cronExpression; public CronTrigger(string cronExpression) { _cronExpression = CronExpression.Parse(cronExpression); } public string Schedule =&gt; _cronExpression.ToString(); public override bool Matches(DateTime tick) { return _cronExpression.Contains(tick); } } public class CountTrigger : Trigger { public CountTrigger(int count) { Counter = new InfiniteCounter(count); } public IInfiniteCounter Counter { get; } public override bool Matches(DateTime tick) { Counter.MoveNext(); return Counter.Position == InfiniteCounterPosition.Last; } } </code></pre> <hr /> <h2>Testing</h2> <p>So far I've created two tests for it (with <code>XUnit</code>). One testing the <code>Job</code> and a <em>bigger</em> one testing the <code>Scheduler</code>.</p> <p>The first test checks whether the max-number of tasks is not exceeded and whether the <code>Continuation</code> tasks works correctly.</p> <pre><code>public class JobTest { [Fact] public async Task Job_executes_no_more_than_specified_number_of_times() { var misfireCount = 0; var job = new Job(&quot;test&quot;, Enumerable.Empty&lt;Trigger&gt;(), async token =&gt; await Task.Delay(TimeSpan.FromSeconds(3), token)) { OnMisfire = j =&gt; misfireCount++, MaxDegreeOfParallelism = 2 }; job.Execute(CancellationToken.None); job.Execute(CancellationToken.None); job.Execute(CancellationToken.None); Assert.Equal(2, job.Count); Assert.Equal(1, misfireCount); // Wait until all jobs are completed. await job.Continuation; Assert.Equal(0, job.Count); } } </code></pre> <p>Testing <code>Scheduler</code> is now possible by using an observable that is ticking as I say:</p> <pre><code>public class SchedulerTest { [Fact] public void Executes_job_according_to_triggers() { var job1ExecuteCount = 0; var job2ExecuteCount = 0; var misfireCount = 0; var subject = new Subject&lt;DateTime&gt;(); var scheduler = new Scheduler(subject); var unschedule1 = scheduler.Schedule(new Job(&quot;test-1&quot;, new[] { new CountTrigger(2) }, async token =&gt; { Interlocked.Increment(ref job1ExecuteCount); await Task.Delay(TimeSpan.FromSeconds(3), token); }) { MaxDegreeOfParallelism = 2, OnMisfire = _ =&gt; Interlocked.Increment(ref misfireCount), UnscheduleTimeout = TimeSpan.FromSeconds(4) }); var unschedule2 = scheduler.Schedule(new Job(&quot;test-2&quot;, new[] { new CountTrigger(3) }, async token =&gt; { Interlocked.Increment(ref job2ExecuteCount); await Task.Delay(TimeSpan.FromSeconds(3), token); }) { MaxDegreeOfParallelism = 2, OnMisfire = _ =&gt; Interlocked.Increment(ref misfireCount), UnscheduleTimeout = TimeSpan.FromSeconds(4) }); // Scheduler was just initialized and should not have executed anything yet. Assert.Equal(0, job1ExecuteCount); Assert.Equal(0, job2ExecuteCount); // Tick once. subject.OnNext(DateTime.Now); // Still nothing should be executed. Assert.Equal(0, job1ExecuteCount); Assert.Equal(0, job2ExecuteCount); // Now tick twice... subject.OnNext(DateTime.Now); subject.OnNext(DateTime.Now); // Unschedule the job. This blocking call waits until all tasks are completed. unschedule1.Dispose(); unschedule2.Dispose(); // Tick once again. Nothing should be executed anymore. subject.OnNext(DateTime.Now); // ...this should have matched the two triggers. Assert.Equal(1, job1ExecuteCount); Assert.Equal(1, job2ExecuteCount); Assert.Equal(0, misfireCount); } } </code></pre> <p>The extension to fix missing seconds...</p> <pre><code>public static class ObservableExtensions { public static IObservable&lt;DateTime&gt; TruncateMilliseconds(this IObservable&lt;DateTime&gt; ticks) { return ticks.Select(DateTimeExtensions.TruncateMilliseconds); } public static IObservable&lt;DateTime&gt; FixMissingSeconds(this IObservable&lt;DateTime&gt; ticks) { var last = DateTime.MinValue; return ticks.SelectMany(tick =&gt; { if (tick.Millisecond &gt; 0) throw new InvalidOperationException($&quot;{nameof(FixMissingSeconds)} requires ticks without the millisecond part.&quot;); // We have to start somewhere so let it be one second before tick if we are currently nowhere. last = last == DateTime.MinValue ? tick.AddSeconds(-1) : last; // Calculates the gap between tick and last. In normal case it's 1. var gap = tick.DiffInSeconds(last); // If we missed one second due to time inaccuracy, // this makes sure to publish the missing second too // so that all jobs at that second can also be triggered. return Enumerable .Range(0, gap) .Select(_ =&gt; last = last.AddSeconds(1)); }); } } </code></pre> <p>can now also be tested.</p> <pre><code>public class ObservableExtensionsTest { [Fact] public void Returns_ticks_unchanged_when_no_gap() { var ticks = new[] { 0, 1, 2 }.Select(s =&gt; DateTime.Parse($&quot;2019-01-01 10:00:0{s}&quot;)).ToList(); Assert.Equal(ticks, ticks.ToObservable().TruncateMilliseconds().FixMissingSeconds().ToEnumerable().ToList()); } [Fact] public void Fixes_tick_gap() { var expected = new[] { 0, 1, 2 }.Select(s =&gt; DateTime.Parse($&quot;2019-01-01 10:00:0{s}&quot;)).ToList(); var missing = new[] { 0, 2 }.Select(s =&gt; DateTime.Parse($&quot;2019-01-01 10:00:0{s}&quot;)).ToList(); Assert.Equal(expected.ToList(), missing.ToObservable().TruncateMilliseconds().FixMissingSeconds().ToEnumerable().ToList()); } } </code></pre> <hr /> <h2>Utilities</h2> <p>There are two more classes that drive the automatic scheduler.</p> <p>One creates an observable that is ticking every-second:</p> <pre><code>public static class Tick { public static IObservable&lt;DateTime&gt; EverySecond(IDateTime dateTime) { return Observable .Interval(TimeSpan.FromSeconds(1)) .Select(_ =&gt; dateTime.Now()); } } </code></pre> <p>the other provides and extension that is fixing missing seconds due to the occasional <em>glitches</em> in the ticking clock:</p> <pre><code>public static class ObservableExtensions { public static IObservable&lt;DateTime&gt; FixMissingSeconds(this IObservable&lt;DateTime&gt; ticks) { var last = DateTime.MinValue; return ticks.SelectMany(tick =&gt; { tick = tick.TruncateMilliseconds(); // We have to start somewhere so let it be one second before tick if we are currently nowhere. last = last == DateTime.MinValue ? tick.AddSeconds(-1) : last; // Calculates the gap between tick and last. In normal case it's 1. var gap = (int)((tick - last).Ticks / TimeSpan.TicksPerSecond); // If we missed one second due to time inaccuracy, // this makes sure to publish the missing second too // so that all jobs at that second can also be triggered. return Enumerable .Range(0, gap) .Select(_ =&gt; last = last.AddSeconds(1)); }); } } public interface IDateTime { DateTime Now(); } public class DateTimeUtc : IDateTime { public DateTime Now() =&gt; DateTime.UtcNow; } </code></pre> <p>For working with <code>DateTime</code> I also have these:</p> <pre><code>public static class DateTimeExtensions { public static DateTime TruncateMilliseconds(this DateTime dateTime) { return new DateTime(dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond), dateTime.Kind); } public static int Diff(this DateTime later, DateTime earlier, long ticksPerX) { if (later &lt; earlier) throw new ArgumentException($&quot;'{nameof(later)}' must be greater or equal '{nameof(earlier)}'.&quot;); return (int)((later - earlier).Ticks / ticksPerX); } public static int DiffInSeconds(this DateTime later, DateTime earlier) { return later.Diff(earlier, TimeSpan.TicksPerSecond); } } </code></pre> <hr /> <p>This time my main focus is on testability and thread-safety. Do you think I need any locking or synchronisation anywhere? I'm not entirely sure I have thought of everythig. How about testing it? Can you see anything that cannot be tested and do you think the two tests are sane?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T12:07:48.313", "Id": "415890", "Score": "0", "body": "The code (still a little bit messy and with some other less relevant experimetal stuff) can be found in my repository [here](https://github.com/he-dev/reusable/blob/dev/Reusable.Tests.XUnit/src/Experimental/Scheduler.cs)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T15:53:50.550", "Id": "415912", "Score": "0", "body": "O-ha! Downvoted by the competition :-)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T12:07:07.723", "Id": "215088", "Score": "3", "Tags": [ "c#", "async-await", "observer-pattern", "scheduled-tasks", "integration-testing" ], "Title": "Scheduler built with observables v3 (follow-up) - now testable" }
215088
<p>I am learning Go and as an exercise I did <a href="http://codegolf.stackexchange.com/q/49671">this challenge from Code Golf</a> (without the golfing), where an ASCII art snowman is drawn from a combination of body parts, based on an 8-digit code taken as command line argument.</p> <p>For example:</p> <pre><code>$ ./snowman 12431312 _===_ (-.O) &lt;( : )\ ( : ) </code></pre> <p>As a minor extension I decided to use a random code if none is passed.</p> <p>Coming from Python, I had hoped to use the static typing to my advantage (e.&thinsp;g. by checking at compile time that the definition of body parts is valid), but I have the feeling that I am fighting it more than it helps me.</p> <p>I'd like to know how I can make the code less verbose and repetitive, and how I can use the static typing to make the code less error-prone and brittle.</p> <h3>snowman.go</h3> <pre><code>package main import ( "errors" "fmt" "math/rand" "os" "strconv" "time" ) type Snowman [5][7]rune func (s Snowman) getLine(i int) string { var line string for _, c := range s[i] { line += string(c) } return line } func (s Snowman) String() string { var result string for i := range s { if i &gt; 0 { result += "\n" } result += s.getLine(i) } return result } type Hat [2][5]rune type Nose rune type Eye rune type LeftArm [2]rune type RightArm [2]rune type Torso [3]rune type Base [3]rune var hats = [...]Hat{ {{' ', ' ', ' ', ' ', ' '}, {'_', '=', '=', '=', '_'}}, {{' ', '_', '_', '_', ' '}, {'.', '.', '.', '.', '.'}}, {{' ', ' ', '_', ' ', ' '}, {' ', '/', '_', '\\', ' '}}, {{' ', '_', '_', '_', ' '}, {'(', '_', '*', '_', ')'}}, } var noses = [...]Nose{',', '.', '_', ' '} var eyes = [...]Eye{'.', 'o', 'O', '-'} var leftArms = [...]LeftArm{{' ', '&lt;'}, {'\\', ' '}, {' ', '/'}, {' ', ' '}} var rightArms = [...]RightArm{{' ', '&gt;'}, {'/', ' '}, {' ', '\\'}, {' ', ' '}} var torsos = [...]Torso{ {' ', ':', ' '}, {']', ' ', '['}, {'&gt;', ' ', '&lt;'}, {' ', ' ', ' '}, } var bases = [...]Base{ {' ', ':', ' '}, {'"', ' ', '"'}, {'_', '_', '_'}, {' ', ' ', ' '}, } // newSnowman returns a Snowman with no hat, arms, face, torso, or base. func newSnowman() Snowman { var s Snowman for _, i := range [3]int{0, 1, 4} { s[i][0] = ' ' s[i][6] = ' ' } for i := 2; i &lt; 5; i++ { s[i][1] = '(' s[i][5] = ')' } return s } func (s *Snowman) setHat(h Hat) { for i, line := range h { for j, c := range line { s[i][j+1] = c } } } func (s *Snowman) setNose(n Nose) { s[2][3] = rune(n) } func (s *Snowman) setLeftEye(e Eye) { s[2][2] = rune(e) } func (s *Snowman) setRightEye(e Eye) { s[2][4] = rune(e) } func (s *Snowman) setLeftArm(a LeftArm) { for i, c := range a { s[i+2][0] = c } } func (s *Snowman) setRightArm(a RightArm) { for i, c := range a { s[i+2][6] = c } } func (s *Snowman) setTorso(t Torso) { for i, c := range t { s[3][i+2] = c } } func (s *Snowman) setBase(b Base) { for i, c := range b { s[4][i+2] = c } } type SnowmanCode [8]int func snowmanCodeFromString(s string) (SnowmanCode, error) { var result SnowmanCode if len(s) != 8 { return result, errors.New("expected 8 digits") } for i, digit := range s { num, err := strconv.Atoi(string(digit)) if err != nil { return result, err } result[i] = num } return result, nil } func randomCode() SnowmanCode { return SnowmanCode{ rand.Intn(len(hats)) + 1, rand.Intn(len(noses)) + 1, rand.Intn(len(eyes)) + 1, rand.Intn(len(eyes)) + 1, rand.Intn(len(leftArms)) + 1, rand.Intn(len(rightArms)) + 1, rand.Intn(len(torsos)) + 1, rand.Intn(len(bases)) + 1, } } func SnowmanFromCode(c SnowmanCode) (Snowman, error) { s := newSnowman() if !(1 &lt;= c[0] &amp;&amp; c[0] &lt;= len(hats)) { return s, errors.New("hat code out of range") } if !(1 &lt;= c[1] &amp;&amp; c[1] &lt;= len(noses)) { return s, errors.New("nose code out of range") } if !(1 &lt;= c[2] &amp;&amp; c[2] &lt;= len(eyes)) { return s, errors.New("left eye code out of range") } if !(1 &lt;= c[3] &amp;&amp; c[3] &lt;= len(eyes)) { return s, errors.New("right eye code out of range") } if !(1 &lt;= c[4] &amp;&amp; c[4] &lt;= len(leftArms)) { return s, errors.New("left arm code out of range") } if !(1 &lt;= c[5] &amp;&amp; c[5] &lt;= len(rightArms)) { return s, errors.New("right arm code out of range") } if !(1 &lt;= c[6] &amp;&amp; c[6] &lt;= len(torsos)) { return s, errors.New("right arm code out of range") } if !(1 &lt;= c[7] &amp;&amp; c[7] &lt;= len(bases)) { return s, errors.New("right arm code out of range") } s.setHat(hats[c[0]-1]) s.setNose(noses[c[1]-1]) s.setLeftEye(eyes[c[2]-1]) s.setRightEye(eyes[c[3]-1]) s.setLeftArm(leftArms[c[4]-1]) s.setRightArm(rightArms[c[5]-1]) s.setTorso(torsos[c[6]-1]) s.setBase(bases[c[7]-1]) return s, nil } func codeFromArgsOrRandom() (SnowmanCode, error) { if len(os.Args) &gt; 1 { return snowmanCodeFromString(os.Args[1]) } else { return randomCode(), nil } } func main() { rand.Seed(time.Now().UnixNano()) code, err := codeFromArgsOrRandom() if err != nil { fmt.Println(err) return } s, err := SnowmanFromCode(code) if err != nil { fmt.Println(err) return } fmt.Println(s) } </code></pre>
[]
[ { "body": "<p>Cute project ;-)</p>\n\n<hr>\n\n<p>Do you see where copy-paste coding got the better of you?</p>\n\n<blockquote>\n<pre><code>if !(1 &lt;= c[5] &amp;&amp; c[5] &lt;= len(rightArms)) {\n return s, errors.New(\"right arm code out of range\")\n}\nif !(1 &lt;= c[6] &amp;&amp; c[6] &lt;= len(torsos)) {\n return s, errors.New(\"right arm code out of range\")\n}\nif !(1 &lt;= c[7] &amp;&amp; c[7] &lt;= len(bases)) {\n return s, errors.New(\"right arm code out of range\")\n}\n</code></pre>\n</blockquote>\n\n<p>I meant the mocking jab at \"copy-paste coding\" is a joke.\nWhile in the above it may be possible to extract common elements and generalize the logic, that would be a slippery slope to over-engineering.\nAnd in any case, in Go, as far as I know, simple code with duplicated logic is preferred over complicated code.</p>\n\n<hr>\n\n<p>I think you could eliminate <code>getLine</code> by converting the rune array to a string with <code>string(line[:])</code>:</p>\n\n<pre><code>func (s Snowman) String() string {\n var result string\n for i, line := range s {\n if i &gt; 0 {\n result += \"\\n\"\n }\n result += string(line[:])\n }\n return result\n}\n</code></pre>\n\n<p>Of course this simplification with <code>line[:]</code> comes at the price of allocating a new slice. But given the scale of the task at hand, I think that's a reasonable compromise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-30T22:44:44.337", "Id": "216552", "ParentId": "215090", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T12:44:49.560", "Id": "215090", "Score": "7", "Tags": [ "beginner", "go", "ascii-art" ], "Title": "Drawing a snowman in ASCII art" }
215090
<p>Kata: <a href="https://www.codewars.com/kata/linked-lists-sorted-insert" rel="noreferrer">https://www.codewars.com/kata/linked-lists-sorted-insert</a> </p> <h2>Description</h2> <blockquote> <p>Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list.</p> <pre><code>sortedInsert(1 -&gt; 2 -&gt; 3 -&gt; null, 4) === 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; null) sortedInsert(1 -&gt; 7 -&gt; 8 -&gt; null, 5) === 1 -&gt; 5 -&gt; 7 -&gt; 8 -&gt; null) sortedInsert(3 -&gt; 5 -&gt; 9 -&gt; null, 7) === 3 -&gt; 5 -&gt; 7 -&gt; 9 -&gt; null) </code></pre> </blockquote> <hr> <h2>My Solution</h2> <pre class="lang-py prettyprint-override"><code>def sorted_insert(head, data): prev = None node_j = head node_i = Node(data) while node_j: if node_j.data &gt; data: node_i.next = node_j break prev = node_j node_j = node_j.next else: node_i.next = None if prev: prev.next = node_i return head if prev else node_i </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T01:14:24.593", "Id": "415953", "Score": "0", "body": "FWIW, a [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) (or a [balanced binary search tree](https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree), which is a more complicated but better performing subtype) may be better for this sort of thing when it's an option." } ]
[ { "body": "<p>First some minor issues with naming, then a rewrite:</p>\n\n<p><code>prev</code> could be <code>previous</code>, there is no need to skimp on characters. <code>node_j</code> and <code>node_i</code> are completely different things, yet their names suggest they are both \"moving pointers\". That is only true for <code>node_j</code>. May I suggest using <code>current</code> and <code>insert</code> instead?</p>\n\n<p>The use of <code>while..else</code> is pretty cool, but confused me at first. Take that with a grain of salt, though, I'm not usually writing a lot of python.</p>\n\n<hr>\n\n<p>Now for the meat of the problem:</p>\n\n<p>This can be simplified by inverting the logic on your traversal. Consider the following code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def sorted_insert(head, data):\n if head is None:\n return Node(data)\n if data &lt; head.data:\n new_head = Node(data)\n new_head.next = head\n return new_head\n # at this point we will always return head\n current_node = head\n # advance if next node is smaller than node to be inserted\n while current_node.next is not None and current_node.next.data &lt; data:\n current_node = current_node.next\n\n insert = Node(data)\n insert.next = current_node.next\n current_node.next = insert\n return head\n</code></pre>\n\n<p>This is an improvement over the code you presented because it separates special cases from traversal.</p>\n\n<ol>\n<li>We first handle the special case of an empty list (<code>head is None</code>).</li>\n<li>Then we handle the case where we create a new head (<code>data &lt; head.data</code>)</li>\n</ol>\n\n<p>With these special cases out of the way we now search for the insertion position, namely what you store in <code>prev</code>. The way this works is by advancing <code>current_node</code> only if the next node also has a smaller <code>data</code> than the insertion.</p>\n\n<p>This simplification allows us to eliminate a variable at the cost of a somewhat more difficult to understand loop condition. Overall this tradeoff is worth it, because we reduce the complexity of the loop body. </p>\n\n<p>After we found the insertion position, the insertion itself becomes a matter of setting the properties in the correct order to avoid dropping the tail of the list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T14:20:37.777", "Id": "215096", "ParentId": "215095", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T13:53:06.893", "Id": "215095", "Score": "6", "Tags": [ "python", "beginner", "linked-list" ], "Title": "(Codewars) Linked Lists-Sorted Insert" }
215095
<p>I often work on embedded system projects in which I have a number of documentation files, such as microprocessor datasheets, schematics, bills of materials, etc. I find it convenient to create a simple little HTML file that contains the file descriptions and a hyperlink to each file. I used to create these all by hand, but I now have an automated script that does that for me. I still have to edit the file to include the descriptions of the files, but this creates both an <code>index.html</code> and <code>style.css</code> file as a start. I'd be interested in a review of both the Python code and the HTML and Javascript and CSS that it creates. The code is intended solely for use on a Linux box.</p> <h2>Invocation and use</h2> <p>This is designed to placed in the path and invoked from the command line from within the directory to be documented. Then the resulting HTML file is invoked in the same way as with <code>firefox index.html</code>. Although it doesn't make much difference in this case, the intent is that the HTML file is <em>not</em> served from a web server but simply interpreted from the file system so that the entire project, with documentation, can be put on a CD or DVD (or other read-only media) and used without having to run a web server.</p> <h2>docdir.py</h2> <pre><code>#! /usr/bin/python3 from os import walk style = '''\ body { font-style:normal; font-family:sans-serif,Georgia, Helvetica, Arial, sans-serif; background-color:white; color:black; margin-left:5%; } div.navbar { text-align:center; } h1 { text-indent:1em; color:white; background-color:navy; } h2 { text-indent:2em; color:white; background-color:navy; } h3 { margin-left:1em; margin-right:1em; text-indent:2em; color:white; background-color:navy; } div.trailer table { width:100%; border-style:none; padding-left:0; } table { border-style:solid; } td { padding-left:20px; } caption { font-style:oblique; }''' index_tail='''\ ]; function loadLinks() { var table = document.getElementById("docTable"); links.reverse(); links.forEach(function(element, index, array) { var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "&lt;a href=\\""+element.name + "\\"&gt;" + element.name + "&lt;/a&gt;"; cell2.innerHTML = element.desc; }); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="loadLinks()"&gt; &lt;h1&gt;Documents&lt;/h1&gt; &lt;p&gt; These directories may contain &lt;b&gt;proprietary and confidential&lt;/b&gt; information. &lt;/p&gt; &lt;p&gt; &lt;table id="docTable"&gt; &lt;caption&gt;Document list&lt;/caption&gt; &lt;/table&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;a href="index.html"&gt;index.html&lt;/a&gt; &lt;/td&gt; &lt;td&gt; this file &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;''' if __name__=="__main__": title="Documents" index_head=f'''\ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;{title}&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;script&gt; var links = [''' # create style file css=open('./style.css', 'w+') print(style, file=css) css.close() # get files into array _, _, filenames = next(walk('.'), (None, None, [])) # create index file html=open('./index.html', 'w+') print(index_head, file=html) for fn in filenames: print('{{ "name":"{0:s}", "desc":"{0:s}" }},'.format(fn), file=html) print(index_tail, file=html) html.close() # sample of how each document line looks after editing: # { "name":"msp430f5438a.pdf", "desc":"MSP430F5438 datasheet" }, </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T15:43:19.433", "Id": "415911", "Score": "1", "body": "How are you running this script? Is it installed in a specific location and you use something like `~/cwd> python /path/to/file.py`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T20:41:45.573", "Id": "415933", "Score": "0", "body": "I've added more details to the question to show how I use it." } ]
[ { "body": "<p>(Warning I havn't tested the following code.)</p>\n\n<h1>Python</h1>\n\n<ol>\n<li>Offload the custom html to a template engine. <a href=\"http://jinja.pocoo.org/docs/2.10/\" rel=\"nofollow noreferrer\">Jinja2</a> can be used in both <a href=\"http://flask.pocoo.org/docs/0.12/templating/\" rel=\"nofollow noreferrer\">flask</a> and <a href=\"https://docs.djangoproject.com/en/2.1/topics/templates/\" rel=\"nofollow noreferrer\">django</a>. And so I'll change your code to use this. (I'm not affiliated)</li>\n<li>It's good to see you manually <code>.close</code>ing your files. <a href=\"https://codereview.stackexchange.com/q/158861\">But using <code>with</code> is better</a>.</li>\n<li>Use <code>'</code> or <code>\"</code> string delimiter. You can switch if the string contains your prefered one. I prefer <code>'</code>, but would use <code>\"it's\"</code> rather than <code>'it\\'s'</code>.</li>\n<li>You can move your CSS into its own file and <a href=\"https://stackoverflow.com/a/30359308\">copy the file with whatever you think is best</a>.</li>\n<li>I'd use <code>''.join</code> and a comprehension to make <code>filenames</code> a string, that can be passed to Jinja.</li>\n</ol>\n\n\n\n<pre><code>#! /usr/bin/python3\nfrom os import walk\nfrom pathlib import Path\nimport shutil\n\nfrom jinja import Environment, FileSystemLoader, select_autoescape\n\nFILE = Path(__file__).resolve()\nRESOURCES = FILE / 'name'\nCWD = Path.cwd()\n\nenv = Environment(\n loader=FileSystemLoader(str(RESOURCES / 'templates')),\n autoescape=select_autoescape(['html'])\n)\n\nif __name__ == '__main__':\n shutil.copyfileobj(\n open(RESOURCES / 'css' / 'style.css'),\n open(CWD / 'style.css', 'w+')\n )\n\n filenames = ''.join(\n '{{ \"name\":\"{0}\", \"desc\":\"{0}\" }},'.format(f.name)\n for f in CWD.iterdir()\n if f.is_file()\n )\n\n with open(CWD / 'index.html', 'w+') as html:\n page = env.get_template('index.html').render(\n title='Documents',\n links=filenames\n )\n print(page, file=html)\n</code></pre>\n\n<h1>CSS</h1>\n\n<p>From the little I've done with CSS your file looks a bit off to me:</p>\n\n<ol>\n<li>I'm used to seeing a line between each style.</li>\n<li>I'm used to seeing K&amp;R, rather than Allman, indentation style.</li>\n<li>You should keep your indentation consistant.</li>\n<li>I'm used to seing a space after <code>:</code> and <code>,</code>.</li>\n</ol>\n\n<p>New location: <code>/bin/name/css/style.css</code>.</p>\n\n<pre><code>body { \n font-style: normal;\n font-family: sans-serif, Georgia, Helvetica, Arial, sans-serif;\n background-color: white;\n color: black;\n margin-left: 5%;\n}\n\ndiv.navbar {\n text-align:center;\n}\n</code></pre>\n\n<h1>HTML</h1>\n\n<p>I'm used to seing indentation, most webdev tools also do this for you. And so I'd assume that if they're doing it then there's a good reason for it. I find your HTML code to be a bit hard to read currently because of it.</p>\n\n<p>New location: <code>/bin/name/templates/index.html</code>.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;{{ title }}&lt;/title&gt;\n &lt;link rel=\"stylesheet\" href=\"style.css\"&gt;\n &lt;script&gt;\n var links = [{{ links }}];\n\n function loadLinks() {\n var table = document.getElementById(\"docTable\");\n links.reverse();\n links.forEach(function(element, index, array) { \n var row = table.insertRow(0);\n var cell1 = row.insertCell(0);\n var cell2 = row.insertCell(1);\n cell1.innerHTML = \"&lt;a href=\\\\\"\" + element.name + \"\\\\\"&gt;\" + element.name + \"&lt;/a&gt;\";\n cell2.innerHTML = element.desc;\n });\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body onload=\"loadLinks()\"&gt;\n &lt;h1&gt;Documents&lt;/h1&gt;\n &lt;p&gt;\n These directories may contain &lt;b&gt;proprietary and confidential&lt;/b&gt; information.\n &lt;/p&gt;\n\n &lt;p&gt;\n &lt;table id=\"docTable\"&gt;\n &lt;caption&gt;Document list&lt;/caption&gt;\n &lt;/table&gt;\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;\n &lt;table&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;a href=\"index.html\"&gt;index.html&lt;/a&gt;\n &lt;/td&gt;\n &lt;td&gt;\n this file\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T21:15:13.807", "Id": "215118", "ParentId": "215097", "Score": "2" } } ]
{ "AcceptedAnswerId": "215118", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T14:33:57.567", "Id": "215097", "Score": "2", "Tags": [ "python", "javascript", "python-3.x", "html", "css" ], "Title": "Create HTML page to document contents of directory" }
215097
<p><a href="https://codereview.stackexchange.com/questions/215095/codewars-linked-lists-sorted-insert">Original Question</a>.</p> <p>So I rewrote the code for the problem described in the original question, but someone had already answered that question, and my rewrite would have invalidated their answer, so I just posted a new question.</p> <h2>Updated Solution</h2> <pre class="lang-py prettyprint-override"><code>def sorted_insert(head, data): tmp = Node(None) tmp.next = head node = Node(data) while tmp.next: if tmp.next.data &gt; data: break tmp = tmp.next node.next = tmp.next tmp.next = node return head if tmp.data else node </code></pre>
[]
[ { "body": "<p>To me it seems the purpose of this rewrite is to mitigate the special treatment for replacing the head. Like the previous solution, it also suffers from lack of separation of distinct logical elements. In this example, <code>tmp</code> is used for two purposes: traverse the list, and act as the <em>dummy</em> to check if head was replaced.</p>\n\n<p>This is one step away from a clear <code>dummy</code> node to prefix the list to eliminate the special treatment of the head, and I think this clean separation is simpler and easier to understand:</p>\n\n<pre><code>def sorted_insert(head, data):\n # a dummy node inserted in front of head\n dummy = Node(None)\n dummy.next = head\n\n # whatever happens in the rest, the new head will be dummy.next\n\n # loop until the insertion point\n node = dummy\n while node.next:\n if node.next.data &gt; data:\n break\n node = node.next\n\n # create the new node and insert it\n new_node = Node(data)\n new_node.next = node.next\n node.next = new_node\n\n # return the head. it may or may not have been replaced\n return dummy.next\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T18:06:27.287", "Id": "215109", "ParentId": "215100", "Score": "2" } } ]
{ "AcceptedAnswerId": "215109", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T16:24:11.327", "Id": "215100", "Score": "1", "Tags": [ "python", "beginner", "programming-challenge", "linked-list" ], "Title": "(Codewars) Linked Lists-Sorted Insert (2)" }
215100
<p>I know this has been done before, but I needed to brush up my Python skills. Also, I intend to publicly share this code on a blog post sometime in the near future. This is also an attempt to improve my <a href="https://codereview.stackexchange.com/questions/112121/search-for-a-pythonic-caesar">previous code</a>. So here's everything:</p> <h1>File Structure</h1> <pre><code>(project root) | +- simplesubstitution | +- Cipher.py +- main.py +- __init__.py (empty) +- data | +- input.txt +- output.txt (will be generated) +- output_decrypt.txt (will be generated) </code></pre> <h1>Cipher.py</h1> <pre><code>""" This module houses 3 classes: The Cipher base class and the two subclasses: KeyedCipher and ShiftedCipher. All of these provide convenient ways to work with mono-alphabetic simple substitution ciphers. The Cipher class takes a plaintext alphabet (string) and a corresponding mapped ciphertext alphabet (string). In other words, for a given index i (say), plaintext[i] will map to ciphertext[i], when the text is encrypted. Both the alphabet strings must have the same unique set of characters, and repetitions are not allowed. To make the generation of ciphertext alphabets easier, The KeyedCipher and the ShiftedCipher are provided. The KeyedCipher takes a keyword/key-phrase, paired with a suitable plaintext alphabet and generates a Cipher with the characters provided pushed to the beginning, with the rest of the unused characters appended at the end. Consequently, a good key will lead to better encryption/mapping. The ShiftedCipher simply shifts the entire plaintext alphabet by a given amount, with the end wrapping around to the front. The Caesar Cipher is one of the instances of this Cipher. There is also an option to get a Cipher by combining both the methods: the get_combined_cipher() Unique Behaviour: ================= When using the alphabet with all ascii letters (string.ascii_letters), the keyword is treated as case insensitive. That is, the plaintext alphabet is essentially the combination of applying the keyword separately on lowercase and uppercase letters. While this does restrict the alphabet, this makes it more convenient to use for general text contained a mixture of cases and the cipher needed is based simply on the alphabet. Subhomoy Haldar - 2019 HungryBlueDev.wordpress.com """ import string ################## # Internal stuff # ################## def _generate_keyword_based_ciphertext_alphabet(plaintext_alphabet, key): """ Attempts to create a ciphertext alphabet string by moving the (first unique occurrence) of a character of the given keyword/key-phrase to the beginning and appending the unused characters to the end. If the key contains characters not contained in the plaintext alphabet, then an error is thrown. For example, if the alphabet is "0123456789" and the key is "5158414", the the generated ciphertext alphabet would be "5184023679". :param plaintext_alphabet: The universe to draw characters from. :param key: To determine which characters are moved up. :return: A ciphertext alphabet based on the key provided. """ plaintext_list = list(plaintext_alphabet) ciphertext_list = [] for char in key: try: position = plaintext_list.index(char) ciphertext_list.append(plaintext_list.pop(position)) except ValueError: if char not in ciphertext_list: raise ValueError("Keyword contains character not contained in the alphabet: " + char) return _list_to_string(ciphertext_list + plaintext_list) def _generate_case_handled_ciphertext_alphabet(plaintext_alphabet, key): """ This method checks if the plaintext alphabet is that of all ascii letters. If it is so, the key is treated as case-insensitive. If not, it applies simple mapping. :param plaintext_alphabet: The universe to draw characters from. :param key: To determine which characters are moved up. :return: A ciphertext alphabet based on the key provided. """ if plaintext_alphabet == string.ascii_letters: lower_half = _generate_keyword_based_ciphertext_alphabet(string.ascii_lowercase, key.lower()) upper_half = _generate_keyword_based_ciphertext_alphabet(string.ascii_uppercase, key.upper()) return lower_half + upper_half else: return _generate_keyword_based_ciphertext_alphabet(plaintext_alphabet, key) def _generate_inverse(plaintext_list, ciphertext_list): """ Given an existing mapping from a plaintext alphabet to a ciphertext alphabet, generate the inverse mapping, which essentially maps from the ciphertext back to the plaintext. In this case however, the ciphertext is permuted back to the plaintext, resulting in the plaintext being permuted accordingly. The advantage of this is that only one mapping method will work for both encryption and decryption of the text. """ inverse_list = [] for char in plaintext_list: position = ciphertext_list.index(char) inverse_list.append(plaintext_list[position]) return inverse_list def _list_to_string(char_list): """ A simple utility method to help the code make sense. """ return "".join(char_list) def _apply_mapping(message_str, source_list, destination_list): """ This method maps a character from the source alphabet to the destination alphabet. This can be used for both encryption and decryption. :param message_str: The message to be mapped. :param source_list: The source alphabet. :param destination_list: The destination alphabet. :return: A mapped message. """ converted = [] for char in message_str: try: position = source_list.index(char) converted.append(destination_list[position]) except ValueError: converted.append(char) return _list_to_string(converted) def _generate_shifted_alphabet(alphabet_string, shift_amount): """ Generated a shifted alphabet for shift-based ciphers, with wrap-around. :param alphabet_string: The alphabet to be shifted. :param shift_amount: The shift amount to be shifted. May be negative. :return: The shifted alphabet. """ # Restrict the shift amount to [0, len) so that it wraps # around gracefully, instead of ignoring large values. amount = shift_amount % len(alphabet_string) return alphabet_string[amount:] + alphabet_string[:amount] ################ # Public stuff # ################ # This is the alphabet for all printable ascii characters PRINTABLE_ASCII_ALPHABET = ['\t'] + [chr(x) for x in range(32, 127)] class Cipher: """ A class that performs mono-alphabetic simple substitution on text based on a given mapping between the provided plaintext alphabet and the ciphertext alphabet. Using the encrypt() method, normal text is converted to ciphertext. Using the decrypt() method on encrypted text retrieves the normal text. Simple enough. In order to use this class, make sure you supply the proper ciphertext. It can be cumbersome to generate some frequently used styles of ciphertext by writing out explicit code, so you might look into the subclasses: KeyedCipher, and ShiftedCipher. Also, the get_get_combined_cipher() method which literally combines a KeyedCipher and a ShiftedCipher. """ def __init__(self, ciphertext_alphabet, plaintext_alphabet=string.ascii_letters): """ The ciphertext mapping provided must have the same characters as the plaintext alphabet. Also, there should not be repeated characters. Essentially, the ciphertext should be a permutation of the plaintext alphabet. :param ciphertext_alphabet: The mapped ciphertext alphabet. :param plaintext_alphabet: The plaintext alphabet. """ self.plaintext_list = list(plaintext_alphabet) # Make sure that both alphabets have the same number of characters if len(plaintext_alphabet) != len(ciphertext_alphabet): raise ValueError("The plaintext and ciphertext have different character counts.") # Ignore the keyword, even if it is present. The mapping gets preference. self.ciphertext_list = list(ciphertext_alphabet) # Make sure that both alphabets are equal when the order is ignored if set(self.plaintext_list) != set(self.ciphertext_list): raise ValueError("The plaintext and the ciphertext are not the same set of characters.") self.inverse_list = _generate_inverse(self.plaintext_list, self.ciphertext_list) def __str__(self): return "PT: " + _list_to_string(self.plaintext_list) \ + "\nCT: " + _list_to_string(self.ciphertext_list) def encrypt(self, message_string): """ :param message_string: The message in plaintext to encrypt. :return: The encrypted message. """ return _apply_mapping(message_string, self.plaintext_list, self.ciphertext_list) def decrypt(self, message_string): """ :param message_string: The encrypted ciphertext. :return: The decrypted message. """ return _apply_mapping(message_string, self.plaintext_list, self.inverse_list) class KeyedCipher(Cipher): """ A subclass of Cipher to make it easier to use, based on keys composed from the set of characters in the plaintext alphabet. """ def __init__(self, key, plaintext_alphabet=None): """ :param key: The key whose characters are to be pushed to the beginning. :param plaintext_alphabet: The alphabet of characters to source from. """ if plaintext_alphabet is None: plaintext_alphabet = PRINTABLE_ASCII_ALPHABET if key is None or len(key) == 0: raise ValueError("The keyword has to be a non-null string.") ciphertext_alphabet = _generate_case_handled_ciphertext_alphabet(plaintext_alphabet, key) super().__init__(ciphertext_alphabet, plaintext_alphabet) class ShiftedCipher(Cipher): """ Helps create a cipher based on shifted alphabets. """ def __init__(self, shift_amount, plaintext_alphabet=None): """ :param shift_amount: The amount to shift the alphabet by. Can be negative. :param plaintext_alphabet: The alphabet of characters to source from. """ if plaintext_alphabet is None: plaintext_alphabet = PRINTABLE_ASCII_ALPHABET ciphertext_alphabet = _generate_shifted_alphabet(plaintext_alphabet, shift_amount) super().__init__(ciphertext_alphabet, plaintext_alphabet) def get_combined_cipher(key, shift_amount, plaintext_alphabet=None, shift_first=False): """ Obtain a Cipher from both, a key and a shift amount. The order in which the operations are applied can also be specified. By default, the key is applied first, followed by the shift. :param key: The key to generate the ciphertext with. :param shift_amount: The amount by which the ciphertext will be shifted. :param plaintext_alphabet: The alphabet to source from. :param shift_first: False by default. Set to true if the shifting is desired first. :return: A shifted, keyed cipher. """ if plaintext_alphabet is None: plaintext_alphabet = PRINTABLE_ASCII_ALPHABET if shift_first: plaintext_alphabet = _generate_shifted_alphabet(plaintext_alphabet, shift_amount) return KeyedCipher(key, plaintext_alphabet) else: plaintext_alphabet = _generate_case_handled_ciphertext_alphabet(plaintext_alphabet, key) return ShiftedCipher(shift_amount, plaintext_alphabet) </code></pre> <h1>main.py</h1> <p>This is to test the code:</p> <pre><code>from simplesubstitution.Cipher import PRINTABLE_ASCII_ALPHABET, get_combined_cipher def open_as_utf8(file_string, mode): return open(file_string, mode, encoding="utf-8") def generate_files(custom_cipher): input_file = open_as_utf8("data/input.txt", "r") output_file = open_as_utf8("data/output.txt", "w") decrypted_file = open_as_utf8("data/output_decrypt.txt", "w") print("Files have been opened.") message = input_file.read() print("File has been read.") encrypted = custom_cipher.encrypt(message) decrypted = custom_cipher.decrypt(encrypted) assert message == decrypted output_file.write(encrypted) print("File has been encrypted.") decrypted_file.write(decrypted) print("File has been decrypted.") input_file.close() output_file.close() decrypted_file.close() def verify_files_are_equal(): input_file = open_as_utf8("data/input.txt", "r") decrypted_file = open_as_utf8("data/output_decrypt.txt", "r") assert input_file.read() == decrypted_file.read() input_file.close() decrypted_file.close() print("Contents verified to be equal.") if __name__ == '__main__': alphabet = PRINTABLE_ASCII_ALPHABET cipher = get_combined_cipher("The Enigma Machine had a fatal flaw. A character never mapped to itself.", -42000, alphabet, True) generate_files(cipher) verify_files_are_equal() </code></pre> <h1>input.txt</h1> <p>I simply used the first book's TXT file I clicked on at the <a href="https://www.gutenberg.org/" rel="nofollow noreferrer">Project Gutenberg</a> site. The one I have is <a href="https://www.gutenberg.org/files/58962/58962-0.txt" rel="nofollow noreferrer">Making Home Profitable</a>. Here is the <a href="https://www.gutenberg.org/ebooks/58962" rel="nofollow noreferrer">link</a> for all the available formats of the ebook.</p> <p>I downloaded the text file, put it in the <code>data</code> folder and renamed it to <code>input.txt</code>.</p> <h1>My few cents</h1> <p>I'd like to know if using the <code>try-except</code> construct for the <code>list.index()</code> usage is justified, or if it can be improved. Maybe there's a way to make the iterations go faster? The performance is fine as is, but I feel there's certainly scope to improve.</p> <p>Leaving performance aside, maybe the organization needs work? Is the code intuitive enough to be picked up by anyone and start using immediately?</p> <p>These are some of the questions I have. Feel free to address all areas of the code and nitpick on issues.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T16:31:20.230", "Id": "215101", "Score": "2", "Tags": [ "python", "python-3.x", "strings", "caesar-cipher" ], "Title": "Not a very interesting implementation of a simple substitution cipher in Python" }
215101
<p><strong>HTML</strong> </p> <pre><code> &lt;div id="form-0"&gt; form 0 &lt;/div&gt; &lt;div id="form-1" class="add-form"&gt; &lt;a class="remove-form-1"&gt;X&lt;/a&gt; form 1 &lt;/div&gt; &lt;div id="form-2" class="add-form"&gt; &lt;a class="remove-form-2"&gt;X&lt;/a&gt; form 2 &lt;/div&gt; &lt;div id="form-3" class="add-form"&gt; &lt;a class="remove-form-3"&gt;X&lt;/a&gt; form 3 &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-sm-4"&gt;&lt;/div&gt; &lt;div class="col-sm-3"&gt;&lt;p class="request-text"&gt;Maximum of 4 per request&lt;/p&gt;&lt;/div&gt; &lt;div class="col-sm-5"&gt;&lt;a href="#" class="add-another-form"&gt;+ Add another form &lt;/a&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Javascript</strong></p> <pre><code> counter = 0; function checkCounter() { if (counter &gt; 4) { $('.request-text').text('You have reached maximum 4 requests '); $(".request-text").css("color", "green"); $(".add-another-form").css("box-shadow", "none"); $('.add-another-form').unbind('click'); return false; } counter++; return true; } $(".add-another-form").click(function(){ if (checkCounter()) { $(".add-another-form").bind("click", function(e) { $(e.target).closest(".upgrade-quote-form").css("display", "block"); }); counter++; } }); </code></pre> <p>I would like to show the remaining 3 forms on the user actions. When they click on the add another form link, it will show form1, form2,and form3. When it reached 4 times totally, it will display, you have reached the maximum requests. </p> <pre><code>.add-form { display:none; } </code></pre> <p>I will really appreciate for a better solutions. </p>
[]
[ { "body": "<p>You don't need to rebind the click event every time the counter counts has not exceeded its limit. Doing so will only add multiple click event into the <code>.add-another-form</code> element but is not triggered on first click. Just add a condition to prevent your incrementer, etc from being read:</p>\n\n<pre><code>$(\".add-another-form\").click(function(e){\n if ( ! checkCounter() ) {\n return;\n }\n\n $(e.target).closest(\".upgrade-quote-form\").css(\"display\", \"block\");\n counter++;\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T05:24:08.117", "Id": "215166", "ParentId": "215102", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T16:31:33.550", "Id": "215102", "Score": "-2", "Tags": [ "javascript", "jquery", "dom" ], "Title": "Show maximum 4 forms on user actions" }
215102
<p>I'm printing a diamond shape in Java. It's working fine, but is there a way to re-write this code to make it faster?</p> <pre><code>Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); String ns = String.valueOf(n); int z = n/2; int k = n%2; for (int j = 0 ; j&lt;n;j++) { for (int i = 0; i &lt; z; i++) System.out.print(" "); for (int i = 0; i &lt; k ; i++){ System.out.print("*"); if (i==k-1) System.out.print("\n"); } if ((k-n)==0) break; z--; k=k+2; } z = (n)/2; k = (n)%2; int w = k; int y = n-2; for (int j = 0 ; j&lt;z ;j++) { for (int i = 0 ; i&lt;w;i++) System.out.print(" "); for (int i = 0 ; i&lt; y ;i++) System.out.print("*"); w=w+1; y=y-2; System.out.print("\n"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T18:46:34.400", "Id": "415923", "Score": "3", "body": "Welcome to CR! Can you define what you expect by \"faster\"? This is a pretty vague term. Fewer operations (likely)? Improved Big O (unlikely)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T21:49:34.557", "Id": "415940", "Score": "0", "body": "I meant by fewer operations" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T07:33:00.493", "Id": "415975", "Score": "0", "body": "Do you use an IDE? Asking because the code is not *indented* as usual - one point of *perceivability*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T12:37:15.450", "Id": "416004", "Score": "0", "body": "Yes I use IntelliJ , sorry for inconvenience but this is my first question to ask here and I don’t know how to indent right. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T20:43:23.567", "Id": "416061", "Score": "0", "body": "As already said, you need to be more specific about what is it that you expect. If you just want to tinker with the code and see how much shorter you can make it, then move your question to https://codegolf.stackexchange.com" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T20:54:28.497", "Id": "416062", "Score": "0", "body": "I just want the code not to use nested loops @givanse" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T21:04:34.677", "Id": "416063", "Score": "0", "body": "Okay, so that is what you need to specify in your question: That you want to reduce the complexity of your solution (big O notation), ideally to a linear solution i.e. O(n). This is an algorithm design question and you may get more attention in the computer science site https://cs.stackexchange.com" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T21:08:08.203", "Id": "416064", "Score": "0", "body": "Ok thank you so much :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T21:05:38.707", "Id": "416194", "Score": "0", "body": "@Victoria To let IntelliJ indent your code, press Ctrl+Alt+L. Take some time to try out all the other items from the main menu as well, they are worth spending some time." } ]
[ { "body": "<p>After reviewing your code, I'll point out that:</p>\n\n<p>It would be better if you used more descriptive variable names. It improves readability and might even help you better understand your own code, ex:</p>\n\n<pre><code>int width = sc.nextInt(); // or whatever it represents\n</code></pre>\n\n<p>Always use curly braces for <code>if</code> and <code>for</code> statements, even if they wrap around a single statement. Shorter code isn't faster, but makes it easier to introduce bugs. You never pay a penalty for extra curly braces or parentheses, so use them as much as you want to clarify intention. For example this snippet can be ambiguous:</p>\n\n<pre><code>for (int i = 0 ; i&lt; y ;i++)\n System.out.print(\"*\");\nw=w+1;\ny=y-2;\n</code></pre>\n\n<p>Did you mean</p>\n\n<pre><code>for (int i = 0 ; i&lt; y ;i++) {\n System.out.print(\"*\");\n w=w+1;\n y=y-2;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (int i = 0 ; i&lt; y ;i++) {\n System.out.print(\"*\");\n}\nw=w+1;\ny=y-2;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:17:17.003", "Id": "416072", "Score": "0", "body": "I meant this one : \n for (int i = 0 ; i< y ;i++) {\n System.out.print(\"*\");\n }\n w=w+1;\n y=y-2;\n\n//////////" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T21:31:29.687", "Id": "215153", "ParentId": "215104", "Score": "1" } }, { "body": "<p>Your code works well for odd inputs:</p>\n\n<pre><code>9\n *\n ***\n *****\n *******\n*********\n *******\n *****\n ***\n *\n</code></pre>\n\n<p>However, the output is weirdly wrong for even inputs:</p>\n\n<pre><code>8\n **\n ****\n ******\n********\n******\n ****\n **\n \n</code></pre>\n\n<p>If you want to improve performance (in a way that would be noticeable to benchmarks, but not to the human eye), the most important change you should make is to reduce the number of <code>System.out.print()</code> calls. Each <code>.print()</code> results in a system call, which would require synchronization (acquiring a lock, in case your program is multithreaded, so that the output of multiple simultaneous <code>.print()</code> calls won't get interleaved with each other), as well as context switching (putting your Java code on hold to run code in the operating system kernel). All of that overhead is <em>huge</em>, compared to any other change you can make to your algorithm.</p>\n\n<p>Therefore, for better performance, you should create a <code>StringBuilder</code> and repeatedly append the entire diamond to it, then call <code>System.out.println()</code> just once per line, or, better yet, just once at the end. <a href=\"/a/111470/9357\">Here is an example that prints an hourglass shape</a>, which is closely related to your diamond shape.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T20:56:22.853", "Id": "416191", "Score": "0", "body": "And yes I wanted an odd integer not even. I should've said that, apologies." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T06:43:51.173", "Id": "215169", "ParentId": "215104", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T17:02:05.710", "Id": "215104", "Score": "0", "Tags": [ "java", "performance", "ascii-art" ], "Title": "Print diamond shape in Java" }
215104
<p>Kata: <a href="https://www.codewars.com/kata/linked-lists-insert-sort/train/python" rel="nofollow noreferrer">https://www.codewars.com/kata/linked-lists-insert-sort/train/python</a> </p> <h2>Description</h2> <blockquote> <p>Write an InsertSort() function which rearranges nodes in a linked list so they are sorted in increasing order. You can use the SortedInsert() function that you created in the "Linked Lists - Sorted Insert" kata below. The InsertSort() function takes the head of a linked list as an argument and must return the head of the linked list.</p> <pre><code>var list = 4 -&gt; 3 -&gt; 1 -&gt; 2 -&gt; null insertSort(list) === 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; null </code></pre> <p>If the passed in head node is null or a single node, return null or the single node, respectively. You can assume that the head node will always be either null, a single node, or a linked list consisting of multiple nodes.</p> </blockquote> <hr> <h2>My Solution</h2> <pre class="lang-py prettyprint-override"><code>def insert_sort(head): node = head while node: if node.next and (node.next.data &lt; node.data): to_insert = node.next node.next = to_insert.next head = sorted_insert(head, to_insert.data) #Inserts a node containing it's second argument at the correct position in the linked list that begins with its first argument. continue node = node.next return head </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T17:29:49.313", "Id": "215105", "Score": "1", "Tags": [ "python", "performance", "beginner", "programming-challenge", "linked-list" ], "Title": "(Codewars) Linked Lists - Insert Sort" }
215105
<p>I'm creating an online calculator to get the average grade of different tests my students take and also the final grade. I wonder if you see any problems in this update or any way to improve it:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var inputs = document.getElementsByTagName('input'); var i; function calculateAverage(tests) { var total = 0; var count = 0; for (i = 0; i &lt; tests.length; i++) { if (tests[i].value) { total += Number(tests[i].value); count++; } } if (!count) { return 'Please enter a grade.'; } return 'Average: ' + (total / count).toFixed(1); } document.getElementById('calculator').addEventListener('click', function() { var physicsTests = document.getElementById('physics').getElementsByTagName('input'); var physicsAverage = document.getElementById('physicsAverage'); physicsAverage.value = calculateAverage(physicsTests); var historyTests = document.getElementById('history').getElementsByTagName('input'); var historyAverage = document.getElementById('historyAverage'); historyAverage.value = calculateAverage(historyTests); var finalGrade = document.getElementById('finalGrade'); var averagesTotal = physicsAverage.value.slice(9) * 3 + historyAverage.value.slice(9) * 2; if (averagesTotal || averagesTotal == 0) { finalGrade.value = 'Final grade:' + (averagesTotal / 5).toFixed(1); } else { finalGrade.value = ''; } }); document.getElementById('resetter').addEventListener('click', function() { var form = document.getElementById('form'); var edited = calculateAverage(inputs); if (edited != 'Please enter a grade.' &amp;&amp; confirm('Your changes will be lost.\nAre you sure you want to reset?')) { form.reset(); } }); window.addEventListener('beforeunload', function(event) { var edited = calculateAverage(inputs); if (edited != 'Please enter a grade.') { event.returnValue = 'Your changes may be lost.'; } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="form"&gt; &lt;p id="physics"&gt; Physics: &lt;input type="number"&gt; &lt;input type="number"&gt; &lt;input type="number"&gt; &lt;output id="physicsAverage"&gt;&lt;/output&gt; &lt;/p&gt; &lt;p id="history"&gt; History: &lt;input type="number"&gt; &lt;input type="number"&gt; &lt;input type="number"&gt; &lt;output id="historyAverage"&gt;&lt;/output&gt; &lt;/p&gt; &lt;button type="button" id="calculator"&gt;Calculate&lt;/button&gt; &lt;button type="button" id="resetter"&gt;Reset&lt;/button&gt; &lt;output id="finalGrade"&gt;&lt;/output&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>P.S. I've made changes to the <a href="https://codereview.stackexchange.com/q/214853/33793">previous code</a> to shorten the script and added some new features such as a reset button.</p> <h1>Note</h1> <p>Please review the <a href="https://codereview.stackexchange.com/q/220084/33793">final product</a> made thanks to the hints I've received in this thread.</p>
[]
[ { "body": "<h3>Separate logical elements</h3>\n\n<p>The <code>calculateAverage</code> does multiple things:</p>\n\n<ul>\n<li>Calculate average</li>\n<li>Return the computed value as a formatted string</li>\n<li>Return a special string in case of missing user input</li>\n</ul>\n\n<p>It would be better to separate these elements.</p>\n\n<p>Because these are not separated well,\nthe rest of the program has to work extra hard, for example:</p>\n\n<blockquote>\n<pre><code>var averagesTotal = physicsAverage.value.slice(9) * 3 + historyAverage.value.slice(9) * 2;\n</code></pre>\n</blockquote>\n\n<p>Readers may be puzzled, and ask questions like:</p>\n\n<ul>\n<li><em>Why do we need that <code>.slice(9)</code> there?</em></li>\n<li><em>And where does that magic number 9 come from anyway?</em></li>\n</ul>\n\n<p>Of course it's to chop off the <code>'Average: '</code> prefix from the value.\nIt would be much better if the rest of the program could work with numeric values directly, without having to do string manipulations.</p>\n\n<p>And the way to do that is by using more functions,\ncleanly separating computation and printing.</p>\n\n<h3>Avoid magic numbers</h3>\n\n<p>On the same line in the earlier example,\nthe physics average is multiplied by 3,\nthe history average is multiplied by 2.\n<em>Why? Where do these values come from?\nAre they correct like this?</em>\nThe purpose of these values,\nand the intention of the program could become clear by giving them good, descriptive names.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:30:05.967", "Id": "416295", "Score": "0", "body": "Thanks for the review! I just added [an update](https://codereview.stackexchange.com/a/215127/33793) according to your hints. Is it better now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:57:32.317", "Id": "416300", "Score": "0", "body": "@Mori if you would like a review of your updated implementation, it's good to ask it as a new question. See the conversations [here](https://codereview.meta.stackexchange.com/questions/9109/how-many-questions-with-same-script-can-i-ask-if-code-not-only-merged-reviews-b) for example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:06:20.930", "Id": "416304", "Score": "0", "body": "Good point, but I've already offered a bounty for this question and don't want to take the reviewers to a new one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T06:27:32.253", "Id": "417401", "Score": "0", "body": "@Mori Why did you award the bounty to this answer? I was certain you would award it to other answers with more concrete detail. If this happened by mistake, the moderators might be able to fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T06:29:57.477", "Id": "417402", "Score": "0", "body": "@Mori I reviewed your revised code now (sorry I was busy / forgetful). It looks much better. The only missing is the weights per grade are still magic numbers 3 and 2. They are called \"magic\" because they have no name, and so no clue to the reader what they represent, and why they are those particular values. To make them less magical, give them descriptive names. For example `physicsWeight` and `historyWeight`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T07:08:38.483", "Id": "417408", "Score": "0", "body": "_\" no clue to the reader what they represent, and why they are those particular values\"_ Doesn't the JavaScript comment help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:27:33.650", "Id": "417417", "Score": "0", "body": "@Mori The comment helps, but it's better to describe things with code when easily possible. Comments can become out of date with the code they refer to. Code on the other hand never lies." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T18:30:33.923", "Id": "215110", "ParentId": "215107", "Score": "4" } }, { "body": "<h2>Main updates</h2>\n<ul>\n<li>Added a new function to detect changes to the input fields. It's used when resetting the form or reloading the page.</li>\n<li>Used two separate functions to calculate and display averages.</li>\n<li>Removed the <code>slice</code> method.</li>\n</ul>\n<p><strong>Credit</strong>: Special thanks to <a href=\"https://codereview.stackexchange.com/a/215110/33793\">janos</a> for the above pointers!</p>\n<br>\n<h2>Final code</h2>\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>var i;\n\nfunction detectChanges() {\n var inputs = document.querySelectorAll('input');\n for (i = 0; i &lt; inputs.length; i++) {\n if (inputs[i].value) {\n return true;\n }\n }\n}\n\nfunction calculateAverage(tests) {\n var total = 0;\n var count = 0;\n for (i = 0; i &lt; tests.length; i++) {\n if (tests[i].value) {\n total += Number(tests[i].value);\n count++;\n }\n }\n return total / count;\n}\n\nfunction displayAverage(tests) {\n var avg = calculateAverage(tests);\n if (isNaN(avg)) {\n return 'Please enter a grade.';\n } else {\n return 'Average: ' + avg.toFixed(1);\n }\n}\n\ndocument.getElementById('calculator').addEventListener('click', function() {\n var physicsTests = document.querySelectorAll('#physics &gt; input');\n var physicsAverage = document.getElementById('physicsAverage');\n physicsAverage.value = displayAverage(physicsTests);\n\n var historyTests = document.querySelectorAll('#history &gt; input');\n var historyAverage = document.getElementById('historyAverage');\n historyAverage.value = displayAverage(historyTests);\n\n var finalGrade = document.getElementById('finalGrade');\n var averagesTotal = (calculateAverage(physicsTests) * 3 + calculateAverage(historyTests) * 2) / 5;\n // course average * its weight; weights total = 5\n if (isNaN(averagesTotal)) {\n finalGrade.value = '';\n } else {\n finalGrade.value = 'Final grade: ' + averagesTotal.toFixed(1);\n }\n});\n\ndocument.getElementById('resetter').addEventListener('click', function() {\n var form = document.getElementById('form');\n if (detectChanges() &amp;&amp; confirm('Your changes will be lost.\\nAre you sure you want to reset?')) {\n form.reset();\n }\n});\n\nwindow.addEventListener('beforeunload', function(event) {\n if (detectChanges()) {\n event.returnValue = 'Your changes may be lost.';\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input {\n width: 5em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form id=\"form\"&gt;\n &lt;p id=\"physics\"&gt;\n Physics:\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;output id=\"physicsAverage\"&gt;&lt;/output&gt;\n &lt;/p&gt;\n &lt;p id=\"history\"&gt;\n History:\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;output id=\"historyAverage\"&gt;&lt;/output&gt;\n &lt;/p&gt;\n &lt;button type=\"button\" id=\"calculator\"&gt;Calculate&lt;/button&gt;\n &lt;button type=\"button\" id=\"resetter\"&gt;Reset&lt;/button&gt;\n &lt;output id=\"finalGrade\"&gt;&lt;/output&gt;\n&lt;/form&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-03-10T09:25:49.047", "Id": "215127", "ParentId": "215107", "Score": "1" } }, { "body": "<p><em>I went ahead and refactored your code a lot. However, before I get into that, lets talk about what you did and what you could have done differently.</em></p>\n\n<p><em>Feel free to let me know if you want me to expand on something specific.</em></p>\n\n<h2>Logic regarding: function calculateAverage(tests) {}</h2>\n\n<p>Calculate average function should <strong>not</strong> take in parameters a list of <code>HTMLInputElements</code> and should <strong>not</strong> return a <code>string</code>.</p>\n\n<p>Why? Well it doesn't make sense. <code>calculateAverage</code> should take a list of values and calculate an average.</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 calculateAverage(values){\n return values.reduce((a,c)=&gt;a+c,0)/values.length;\n}\nconst avg = calculateAverage([1,2,3]);\n\nconsole.log(avg);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Because you return a string... later on you have to do this:</p>\n\n<pre><code>physicsAverage.value.slice(9)\n</code></pre>\n\n<p>Not good ! And can become extremely buggy !</p>\n\n<h2>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll\" rel=\"noreferrer\">querySelectorAll</a></h2>\n\n<p><code>querySelectorAll</code> is your friend. It allows you to transform this:</p>\n\n<pre><code>document.getElementById('physics').getElementsByTagName('input');\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code>document.querySelectorAll('#physics &gt; input');\n</code></pre>\n\n<h2>Declare static variables globally:</h2>\n\n<p>In your calculator listener callback, you declare a list of variables.</p>\n\n<pre><code>var physicsTests = document.getElementById('physics').getElementsByTagName('input');\nvar physicsAverage = document.getElementById('physicsAverage');\n//etc\n</code></pre>\n\n<p>But these variables never change. So don't declare them in your callback, move them outside and at the top of your file.</p>\n\n<h2>Create generic code !</h2>\n\n<p>With the current code you have, a lot of manual labor is needed if you wish to add another subject. In my final solution, everything is built in a way where adding a new subject requires <strong>NO</strong> changes in the javascript.</p>\n\n<p>To able to do this, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*\" rel=\"noreferrer\">data-*</a> HTML properties. It's super powerful when you need to add some extra info like the coefficients of each subject.</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 subjects = document.querySelectorAll(\"div[data-coef]\");\n\nsubjects.forEach(subject=&gt;{\n console.log(subject.id, subject.dataset.coef);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"physics\" data-coef=\"3\"&gt;&lt;/div&gt;\n&lt;div id=\"history\" data-coef=\"2\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Another powerful tool is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"noreferrer\">Map</a>. It allows you to easily keep track of specific subjects and other variables. </p>\n\n<h2>Solution:</h2>\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>const inputContainers = document.querySelectorAll('form#form &gt; .subject');\n\nconst finalGradeElement = document.getElementById('finalGrade'); \nconst form = document.getElementById('form');\n\nconst m = new Map();\n\ninputContainers.forEach((container,i)=&gt;{\n const output = container.querySelector(\".output\");\n const inputs = Array.from(container.getElementsByTagName(\"input\"));\n const coef = Number(container.dataset.coef);\n \n const data = Array(inputs.length);\n m.set(i, {\n output, data, coef\n }); \n \n inputs.forEach((item,j)=&gt;item.addEventListener(\"input\", function(){\n if(!this.value.length &gt; 0){\n data[j] = undefined;\n } else {\n data[j] = Number(this.value);\n }\n }));\n});\n\ndocument.getElementById('calculator')\n.addEventListener('click', function() {\n\n const res = Array.from(m.values()).reduce( (a,{output, data, coef})=&gt;{\n \n const values = data.filter(item=&gt;item!==undefined);\n \n if(values.length &gt; 0){\n const avg = values.reduce((a,c)=&gt;a+c, 0)/values.length;\n a.avgTotal += avg * coef;\n a.coefTotal += coef;\n \n output.value = `Average: ${avg.toFixed(1)}`;\n } else {\n output.value = \"Please enter a number\";\n }\n \n return a;\n }, {avgTotal: 0, coefTotal: 0})\n\n const averagesTotal = res.avgTotal/res.coefTotal;\n \n finalGradeElement.value = `Final Grade: ${averagesTotal.toFixed(1)}`\n \n});\n\nfunction isEdited(){\n return !Array.from(m.values()).every(({data})=&gt;{\n return data.every(i=&gt;i===undefined);\n });\n}\n\ndocument.getElementById('resetter')\n.addEventListener('click', function() {\n if (isEdited() &amp;&amp; confirm('Your changes will be lost.\\nAre you sure you want to reset?')) {\n form.reset();\n m.clear();\n }\n});\n\nwindow.addEventListener('beforeunload', function(event) {\n if (isEdited()) {\n event.returnValue = 'Your changes may be lost.';\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>form &gt; div {\n display: flex;\n flex-direction: column;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form id=\"form\"&gt;\n &lt;div class=\"subject\" data-coef=\"3\"&gt;\n Physics:\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;output class=\"output\"&gt;&lt;/output&gt;\n &lt;/div&gt;\n &lt;div class=\"subject\" data-coef=\"2\"&gt;\n History:\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;output class=\"output\"&gt;&lt;/output&gt;\n &lt;/div&gt;\n &lt;button type=\"button\" id=\"calculator\"&gt;Calculate&lt;/button&gt;\n &lt;button type=\"button\" id=\"resetter\"&gt;Reset&lt;/button&gt;\n &lt;output id=\"finalGrade\"&gt;&lt;/output&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T09:04:57.280", "Id": "416237", "Score": "0", "body": "_\"querySelectorAll is your friend.\"_ Good point!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T23:00:11.360", "Id": "417381", "Score": "1", "body": "When recommending [tag:ecmascript-6] features like arrow functions, it would be wise to mention this to the OP, since, while it wasn’t listed in the description there may be browser restrictions for the OPs code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T06:39:43.777", "Id": "417405", "Score": "0", "body": "All major browsers (except e11 and under) cover 99% of es6 features. es6 is JavaScript at this point. Arrow functions are covered by all major browsers except e11 and under. There won't be browser restrictions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-08T04:14:59.250", "Id": "419814", "Score": "0", "body": "Using custom data attributes is a brilliant idea! " } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:05:31.470", "Id": "215201", "ParentId": "215107", "Score": "5" } }, { "body": "<p>A couple of suggestions for a little more generality; the <code>input</code> event could be used on the form itself, as it propagates the events down to the inputs. From there one can use the <code>HTMLFormElement</code> API to grab the sibling inputs and output.</p>\n\n<p>Also when using the <code>input</code> event, it allows for the <code>&lt;output&gt;</code> elements to update on every change, and to show for example input errors in real-time.</p>\n\n<p>For semantic markup, I would suggest using <code>&lt;fieldset&gt;</code> and <code>&lt;legend&gt;</code>, although they still suffer from getting special treatment from some browser vendors which can make styling difficult. I would also recommend using <code>&lt;input type=\"number\"&gt;</code>'s <code>min</code>, <code>max</code> and <code>step</code> attributes.</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>document.addEventListener('DOMContentLoaded', () =&gt; {\n const outputs = document.querySelectorAll('output')\n const using = (thing, fun) =&gt; fun(thing)\n\n const average = ary =&gt;\n using(ary.map(x =&gt; Number(x.value)).filter(Boolean),\n xs =&gt; (xs.reduce((x, y) =&gt; x + y, 0) / xs.length).toFixed(1))\n const lastAsAverage = coll =&gt;\n using([...coll], xs =&gt; xs.pop().value = average(xs))\n\n document.forms[0].addEventListener('input',\n ({target: {parentElement: {elements: inputs}}}) =&gt;\n [inputs, outputs].forEach(lastAsAverage))\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input:invalid { background-color: #faa }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;Physics:&lt;/legend&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;output&gt;&lt;/output&gt;\n &lt;/fieldset&gt;\n\n &lt;fieldset&gt;\n &lt;legend&gt;History:&lt;/legend&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;input type=\"number\"&gt;\n &lt;output&gt;&lt;/output&gt;\n &lt;/fieldset&gt;\n\n &lt;output&gt;&lt;/output&gt;\n\n &lt;input type=\"reset\"&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T08:14:44.753", "Id": "416419", "Score": "0", "body": "_\"I would suggest using `<fieldset>` and `<legend>`\"_ " } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T07:26:44.213", "Id": "215322", "ParentId": "215107", "Score": "2" } } ]
{ "AcceptedAnswerId": "215201", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T18:05:45.680", "Id": "215107", "Score": "5", "Tags": [ "javascript", "html", "form" ], "Title": "Calculate Final Grade: follow-up" }
215107
<p>I'm trying to implement a fixed sized array that uses versioned keys for dangling safety. This structure is similar to a <a href="https://www.youtube.com/watch?v=SHaAR7XPtNU" rel="nofollow noreferrer">slot map</a> data structure, with the exception that this does not automatically compact and rearrange the data array. I have no need to iterate over this structure, and so compaction isn't necessary.</p> <p><strong>versioned_key.h</strong></p> <pre><code>#pragma once #include &lt;cstdint&gt; #include &lt;memory&gt; using bool_t = bool; // For consistency with another library namespace nonstd { struct versioned_key { template&lt;class, size_t, typename&gt; friend class slot_array; template&lt;class, size_t, typename&gt; friend class keyed_array; public: versioned_key() = default; bool_t is_null() const noexcept { return (m_version == 0); } operator bool_t() const noexcept { return (m_version != 0); } private: versioned_key( uint32_t version, uint16_t index, uint16_t meta_data) : m_version(version) , m_index(index) , m_meta_data(meta_data) { // Pass } uint32_t m_version; uint16_t m_index; protected: uint16_t m_meta_data; // User data field, hidden unless overridden }; } </code></pre> <p><strong>keyed_array.h</strong></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;cstdint&gt; #include &lt;limits&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;tuple&gt; #include "versioned_key.h" namespace nonstd { template&lt;class T, size_t Capacity, typename Key = versioned_key&gt; class keyed_array { static const size_t max_index = std::numeric_limits&lt;uint16_t&gt;::max(); static_assert(Capacity &lt;= max_index, "keyed_array capacity too large"); static const uint16_t invalid_index = max_index; public: keyed_array() : m_data() , m_versions() , m_free() , m_size() , m_free_head() { // Initialize the in-place free list for (uint16_t pos = 0; pos &lt; (Capacity - 1); ++pos) m_free[pos] = (pos + 1); m_free[Capacity - 1] = invalid_index; } // This is a big, fixed data structure for holding resources keyed_array(const keyed_array&amp; rhs) = delete; keyed_array&amp; operator=(const keyed_array&amp; rhs) = delete; keyed_array(keyed_array&amp;&amp; rhs) = delete; keyed_array&amp; operator=(keyed_array&amp;&amp; rhs) = delete; constexpr bool empty() const { return m_size == 0; } constexpr uint16_t size() const { return m_size; } constexpr uint16_t max_size() const { return Capacity; } /// &lt;summary&gt; /// Inserts a value into the keyed array. /// Optionally provide a meta_data value to inscribe into the key. /// &lt;/summary&gt; template&lt;typename ... Args&gt; std::tuple&lt;Key, T&amp;&gt; emplace(Args&amp;&amp; ... args, uint16_t meta_data = 0) { if ((m_size &gt;= Capacity) || (m_free_head == invalid_index)) throw std::out_of_range("keyed_array has no free slots"); const uint16_t index = m_free_head; // We could probably recover by just orphaning this slot, but // that would make insertion O(n) as we'd have to find the next. // Otherwise this is fatal as it makes all key handles unsafe. if (increment_version(m_versions[index]) == false) throw std::overflow_error("keyed_array version overflow"); // Store data and update structure status information T&amp; entry = *::new(std::addressof(m_data[m_size])) T(std::forward&lt;Args&gt;(args) ...); m_free_head = m_free[index]; m_free[index] = invalid_index; ++m_size; Key key = { m_versions[index], index, meta_data }; return std::forward_as_tuple(key, entry); } /// &lt;summary&gt; /// Tries to get a value at the given key. /// Will return a nullptr if the key did not match any values. /// &lt;/summary&gt; T* try_get(Key key) { if (evaluate_key(key) == false) return nullptr; return std::addressof(m_data[key.m_index]); } /// &lt;summary&gt; /// Tries to get a value at the given key. /// Will return a nullptr if the key did not match any values. /// &lt;/summary&gt; const T* try_get(Key key) const { if (evaluate_key(key) == false) return nullptr; return std::addressof(m_data[key.m_index]); } /// &lt;summary&gt; /// Tries to remove a given key. /// Returns false if no value was found. /// &lt;/summary&gt; bool_t try_remove(Key key) { if (evaluate_key(key) == false) return false; const uint16_t index = key.m_index; // Destroy the stored data in-place and update the free list std::destroy_at(std::addressof(m_data[key.m_index])); m_free[index] = m_free_head; m_free_head = index; --m_size; return true; } private: static bool_t increment_version(uint32_t&amp; version) { return (++version &gt; 0); } bool_t evaluate_key(Key key) const { if (key.m_index &gt;= Capacity) return false; if (key.m_version != m_versions[key.m_index]) return false; return true; } std::array&lt;T, Capacity&gt; m_data; std::array&lt;uint32_t, Capacity&gt; m_versions; std::array&lt;uint16_t, Capacity&gt; m_free; uint16_t m_size; uint16_t m_free_head; }; } </code></pre> <h1>Questions:</h1> <ol> <li><p>Are placement new and placement delete safe in this case? Do I have to worry about alignment in this array? </p></li> <li><p>Do I have to use <code>std::launder</code>? I'm really trying to avoid using <code>std::aligned_storage</code>/<code>std::launder</code>, mostly due to complication and loss of both optimization and some compile time safety checking.</p></li> <li><p>Anything else major or glaring that I'm missing?</p></li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T18:06:05.067", "Id": "215108", "Score": "2", "Tags": [ "c++", "array", "memory-management", "c++17" ], "Title": "Fixed Size Resource Array with Versioned Indexes" }
215108
<p><a href="https://codereview.stackexchange.com/questions/215155/linked-list-interview-code-methods-runtime-and-edge-cases-refactored">Refactored code here</a></p> <p>I want to write a very simple Linked List with only 3 methods Append, Remove and Print. This is not for production and is to be treated as code that could be used in an interview or a quick and dirty prototype. I'm really curious about the approach I've taken here to ensure no duplicates appear in my Linked List. I feel the data structure will be much easier to work with if remove any complexity around duplicate data and want to use this Linked List to implement a Stack, or Queue, or Binary Search Tree etc. I had int data before as the member data field for my Linked List and don't want to make this overly complex by introducing a concept of ids.</p> <p>First I'd like to know if my member functions for the Linked List have any edge cases I am not catching and any improvements I can make to run time efficiency . Anyway I can simplify this code further with c++11 features, shorter variable names or any other suggestions would be appreciated too.</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct Node { int id; Node* next; Node(int id) : id(id), next(nullptr) { } void append(int newId) { Node* current = this; while (current-&gt;next != nullptr) { if (current-&gt;id == newId) { return; } else { current = current-&gt;next; } } current-&gt;next = new Node(newId); } void remove(int targetId) { Node* current = this; Node* previous; while (current-&gt;id != targetId) { if (current-&gt;next != nullptr) { previous = current; current = current-&gt;next; } else { cout &lt;&lt; "node not found :(\n"; return; } } if (current-&gt;next == nullptr) { delete current; previous-&gt;next = nullptr; } else { Node* danglingPtr = current-&gt;next; current-&gt;id = current-&gt;next-&gt;id; current-&gt;next = current-&gt;next-&gt;next; delete danglingPtr; } } void print() { if (this-&gt;next == nullptr) { cout &lt;&lt; this-&gt;id &lt;&lt; endl; } else { cout &lt;&lt; this-&gt;id &lt;&lt; " "; this-&gt;next-&gt;print(); } } }; int main() { Node list(1); list.append(2); list.append(3); list.append(4); list.print(); list.remove(3); list.print(); list.remove(4); list.print(); list.remove(1337); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T23:08:52.217", "Id": "416208", "Score": "1", "body": "How do you represent the empty list? `Node` and a `List` are different things. A `Node` is a member of a `List` (maybe a very simple member) but a `List` does not need to have any `Nodes`. There are several linked list implementations that we have reviewed here. Have a look at an existing one." } ]
[ { "body": "<ol>\n<li><p>The namespace <code>std</code> is not designed for wholesale importation, see &quot;<em><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std” considered bad practice?</a></em>&quot; for more detail.</p>\n<p>You could instead do a <code>using std::cout;</code> or better qualify the three use-sites.</p>\n</li>\n<li><p>You don't in any way encapsulate the list and abstract over the list. It's just a bunch of <code>Node</code>s. Consider putting it all into a <code>List</code> owning and managing the whole lot.</p>\n</li>\n<li><p>Trying to <code>remove()</code> the root-<code>Node</code> uncovers a bug. Try to trace it through.</p>\n</li>\n<li><p><code>pointer != nullptr</code> is just a long-winded way to write <code>pointer</code> in a boolean context. Respectively for <code>pointer == nullptr</code> and <code>!pointer</code>. Yes, Java needs that, but this is C++.</p>\n</li>\n<li><p>When you <code>return</code> from the <code>if</code>-branch, putting the alternative in an <code>else</code>-branch is superfluous.</p>\n</li>\n<li><p>A function for printing an object should allow the <em>caller</em> to specify the stream, and be called <code>operator&lt;&lt;</code>.</p>\n</li>\n<li><p>There is no reason to rely on the compiler transforming recursion to iteration, especially as it might not always be able.</p>\n</li>\n<li><p><code>this</code> should rarely be used explicitly.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T21:05:23.797", "Id": "415938", "Score": "0", "body": "Thanks for the feedback Deduplicator. I'll refactor my code with these points, very helpful. In an interview scenario would you consider not encapsulating the Node, polluting the global namespace with `using namespace std` a bad reflection on the candidate? I want to write a solution as fast a possible, maybe in an interview I just mention that I should encapsulate my Node struct and not use std globally in a production code scenario?." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T22:33:02.790", "Id": "415944", "Score": "0", "body": "Just take a look how much the rest would change if you don't use `using namespace std;`. Huh, it's only used for `std::cout`, and that three times? And Considering that the `Node`, as an internal implementation-detail of `List`, would *at most* need a single ctor for ease-of-use, it wouldn't lead to that much more code. Actually, when re-writing the rest you can actually shorten things, and get rid of the recursion too!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T01:44:13.547", "Id": "415956", "Score": "0", "body": "Should I replace my recursion with a while loop instead? In what cases will the compiler not be able to transform recursion to iteration?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:08:12.810", "Id": "416032", "Score": "1", "body": "Well, if there are locals with non-trivial dtors, it might be non-trivial to prove, or need additional info. In this case, an *optimising* compiler should be able to. But writing it as iteration is more concise, clean, and always right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T21:14:03.197", "Id": "416065", "Score": "0", "body": "Any advice for \"Trying to remove() the root-Node uncovers a bug. Try to trace it through\" I'm having trouble finding the root cause of the bug." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T21:27:03.240", "Id": "416066", "Score": "1", "body": "The root cause is that when you are trying to remove the first node, you don't have access to whatever owns that node. Fix point 2, and you can fix that." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T20:44:21.757", "Id": "215116", "ParentId": "215112", "Score": "4" } } ]
{ "AcceptedAnswerId": "215116", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T19:01:27.563", "Id": "215112", "Score": "1", "Tags": [ "c++", "c++11", "linked-list" ], "Title": "Linked List Interview Code methods, runtime, and edge cases" }
215112
<p>Rumor is that the next version of C will disallow <a href="https://en.wikipedia.org/wiki/Signed_number_representations" rel="nofollow noreferrer">sign magnitude</a> and <a href="https://en.wikipedia.org/wiki/Ones%27_complement" rel="nofollow noreferrer">ones' complement</a> signed integer encoding. True or not, it seems efficient to not have to code and test for those rare encodings.</p> <p>Yet if code might not handle such cases as non-<a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">2's complement</a>, it is prudent to <em>detect</em> and fail such compilations today.</p> <p>Rather than just look for that one kind of dinosaur¹, below is C code that looks for various unicorns² and dinosaurs. Certainly some tests are more useful than others.</p> <p>Review goal:</p> <ul> <li><p>Please report any <strong>dinosaur</strong>¹ and <strong>unicorns</strong>² compilers found by this code.</p> </li> <li><p>Review how well this code would successfully flag true <a href="https://en.wiktionary.org/wiki/pass%C3%A9" rel="nofollow noreferrer">passé</a> compilers and not report new innovative ones (e.g. 128-bit <code>intmax_t</code>.)</p> </li> <li><p>Suggest any additional or refined tests.</p> </li> <li><p>Pre-C11 compilers that lack <code>static_assert</code> may readily need a better <code>#define static_assert ...</code> than this code. Better alternatives are appreciated, but not a main goal of this post.</p> </li> </ul> <p>Note: I am not trying to rate strict adherence to <a href="https://en.wikipedia.org/wiki/IEEE_754-1985" rel="nofollow noreferrer">IEEE_754</a> and the like.</p> <blockquote> <p>Future readers concerning spelling and grammar in this post: Although they should get corrected in an <em>answer</em>, edits to the <em>question's code</em> are not site appropriate.</p> </blockquote> <hr /> <pre><code>/* * unicorn.h * Various tests to detect old and strange compilers. * * Created on: Mar 8, 2019 * Author: chux */ #ifndef UNICORN_H_ #define UNICORN_H_ #include &lt;assert.h&gt; #ifndef static_assert #define static_assert( e, m ) typedef char _brevit_static_assert[!!(e)] #endif #include &lt;float.h&gt; #include &lt;limits.h&gt; #include &lt;stdint.h&gt; /* * Insure 2's complement * Could also check various int_leastN_t, int_fastN_t */ static_assert(SCHAR_MIN &lt; -SCHAR_MAX &amp;&amp; SHRT_MIN &lt; -SHRT_MAX &amp;&amp; INT_MIN &lt; -INT_MAX &amp;&amp; LONG_MIN &lt; -LONG_MAX &amp;&amp; LLONG_MIN &lt; -LLONG_MAX &amp;&amp; INTMAX_MIN &lt; -INTMAX_MAX &amp;&amp; INTPTR_MIN &lt; -INTPTR_MAX &amp;&amp; PTRDIFF_MIN &lt; -PTRDIFF_MAX , &quot;Dinosuar: Non-2's complement.&quot;); /* * Insure the range of unsigned is 2x that of positive signed * Only ever seen one once with the widest unsigned and signed type with same max */ static_assert(SCHAR_MAX == UCHAR_MAX/2 &amp;&amp; SHRT_MAX == USHRT_MAX/2 &amp;&amp; INT_MAX == UINT_MAX/2 &amp;&amp; LONG_MAX == ULONG_MAX/2 &amp;&amp; LLONG_MAX == ULLONG_MAX/2 &amp;&amp; INTMAX_MAX == UINTMAX_MAX/2, &quot;Dinosuar: narrowed unsigned.&quot;); /* * Insure char is sub-range of int * When char values exceed int, makes for tough code using fgetc() */ static_assert(CHAR_MAX &lt;= INT_MAX, &quot;Dinosuar: wide char&quot;); /* * Insure char is a power-2-octet * I suspect many folks would prefer just CHAR_BIT == 8 */ static_assert((CHAR_BIT &amp; (CHAR_BIT - 1)) == 0, &quot;Dinosaur: Uncommon byte width.&quot;); /* * Only binary FP */ static_assert(FLT_RADIX == 2, &quot;Dinosuar: Non binary FP&quot;); /* * Some light checking for pass-able FP types * Certainly this is not a full IEEE check * Tolerate float as double */ static_assert(sizeof(float)*CHAR_BIT == 32 || sizeof(float)*CHAR_BIT == 64, &quot;Dinosuar: Unusual float&quot;); static_assert(sizeof(double)*CHAR_BIT == 64, &quot;Dinosuar: Unusual double&quot;); /* * Heavier IEEE checking */ static_assert(DBL_MAX_10_EXP == 308 &amp;&amp; DBL_MAX_EXP == 1024 &amp;&amp; DBL_MIN_10_EXP == -307 &amp;&amp; DBL_MIN_EXP == -1021 &amp;&amp; DBL_DIG == 15 &amp;&amp; DBL_DECIMAL_DIG == 17 &amp;&amp; DBL_MANT_DIG == 53, &quot;Dinosuar: Unusual double&quot;); /* * Insure uxxx_t range &lt;= int * Strange when unsigned helper types promote to int */ static_assert(INT_MAX &lt; UINTPTR_MAX, &quot;Unicorn: narrow uintptr_t&quot;); static_assert(INT_MAX &lt; SIZE_MAX, &quot;Unicorn: narrow size_tt&quot;); /* * Insure xxx_t range &gt;= int * Also expect signed helper types at least int range */ static_assert(INT_MAX &lt;= PTRDIFF_MAX, &quot;Unicorn: narrow ptrdiff_t&quot;); static_assert(INT_MAX &lt;= INTPTR_MAX, &quot;Unicorn: narrow intptr_&quot;); /* * Insure all integers are within `float` finite range */ // Works OK when uintmax_t lacks padding static_assert(FLT_RADIX == 2 &amp;&amp; sizeof(uintmax_t)*CHAR_BIT &lt; FLT_MAX_EXP, &quot;Unicorn: wide integer range&quot;); // Better method #define UNICODE_BW1(x) ((x) &gt; 0x1u ? 2 : 1) #define UNICODE_BW2(x) ((x) &gt; 0x3u ? UNICODE_BW1((x)/0x4)+2 : UNICODE_BW1(x)) #define UNICODE_BW3(x) ((x) &gt; 0xFu ? UNICODE_BW2((x)/0x10)+4 : UNICODE_BW2(x)) #define UNICODE_BW4(x) ((x) &gt; 0xFFu ? UNICODE_BW3((x)/0x100)+8 : UNICODE_BW3(x)) #define UNICODE_BW5(x) ((x) &gt; 0xFFFFu ? UNICODE_BW4((x)/0x10000)+16 : UNICODE_BW4(x)) #define UNICODE_BW6(x) ((x) &gt; 0xFFFFFFFFu ? \ UNICODE_BW5((x)/0x100000000)+32 : UNICODE_BW5(x)) #define UNICODE_BW(x) ((x) &gt; 0xFFFFFFFFFFFFFFFFu ? \ UNICODE_BW6((x)/0x100000000/0x100000000)+64 : UNICODE_BW6(x)) static_assert(FLT_RADIX == 2 &amp;&amp; UNICODE_BW(UINTMAX_MAX) &lt; FLT_MAX_EXP, &quot;Unicorn: wide integer range&quot;); /* * Insure size_t range &gt; int * Strange code when a `size_t` object promotes to an `int`. */ static_assert(INT_MAX &lt; SIZE_MAX, &quot;Unicorn: narrow size_t&quot;); /* * Recommended practice 7.19 4 */ static_assert(PTRDIFF_MAX &lt;= LONG_MAX, &quot;Unicorn: ptrdiff_t wider than long&quot;); static_assert(SIZE_MAX &lt;= ULONG_MAX, &quot;Unicorn: size_t wider thna unsigned long&quot;); /* * Insure range of integers within float */ static_assert(FLT_RADIX == 2 &amp;&amp; sizeof(uintmax_t)*CHAR_BIT &lt; FLT_MAX_EXP, &quot;Unicorn: wide integer range&quot;); // Addition code could #undef the various UNICODE_BWn #endif /* UNICORN_H_ */ </code></pre> <p>Test driver</p> <pre><code>#include &quot;unicorn.h&quot; #include &lt;stdio.h&gt; int main(void) { printf(&quot;Hello World!\n&quot;); return 0; } </code></pre> <hr /> <p>¹ C is very flexible, yet some features applied to compilers simply no longer in use for over 10 years. For compilers that used out-of-favor features (non-2's complement, non-power-of-2 bit width &quot;bytes&quot;, non-binary floating-point, etc.) I'll call <strong>dinosaurs</strong>.</p> <p>² C is very flexible for new platform/compilers too. Some of these potential and theoretical compliers could employ <em>very</em> unusual features. I'll call these compilers <strong>unicorns</strong>. Should one appear, I rather have code fail to compile than compile with errant functioning code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T19:27:06.343", "Id": "415928", "Score": "0", "body": "Silly me - did not use an ASCII test yet...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T20:49:19.067", "Id": "415934", "Score": "2", "body": "Are you sure you don't want to ensure that `unsigned char` is a sub-range of `int` instead? To wit, `EOF` being distinct is useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T20:55:25.500", "Id": "415936", "Score": "0", "body": "@Deduplicator Yes, for `fgetc()` , `UCHAR_MAX <= INT_MAX` is better and `CHAR_MAX <= INT_MAX` insufficient. Suggest forming an answer with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T23:12:31.950", "Id": "415948", "Score": "2", "body": "Serious question - how frequently do you run into these types of compilers? I think this is a cool idea! But honestly, I would never need it, as even doing cross-platform stuff, we usually know ahead-of-time which compilers we'll use, and none would have features this obscure. I'm always curious to learn a little about the things I don't run into myself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:05:42.220", "Id": "416069", "Score": "3", "body": "@user1118321 \"know ahead-of-time which compilers we'll use, and none would have features this obscure\" --> that is what this file is for: to help make that assessment. Consider it a like a spell checker. I certainly do not come across unicorns even sporadically, yet an automated review could help. Additional tests could help detect near-unicorns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:57:12.243", "Id": "416138", "Score": "0", "body": "I think it would be interesting to write a program that counts dinosaurs and unicorns in run-time. Giving a Dinosaur-Unicorn Score to compilers :) Kind of a test for compiler compliance, like paranoia.c is a test for float number compliance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T14:51:04.013", "Id": "458463", "Score": "1", "body": "Typo: “insure” -> “ensure”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T17:41:15.823", "Id": "458472", "Score": "0", "body": "@CrisLuengo Let me _assure_ you that there are many views such as [When to Use Insure, Ensure, and Assure](https://grammar.yourdictionary.com/style-and-usage/when-to-use-insure-ensure-and-assure.html). [You Say 'Tomato', I say 'Tomato'](https://www.youtube.com/watch?v=q7a4z7zLKts) ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T18:26:57.470", "Id": "458475", "Score": "0", "body": "Tomeito/tomahto is about pronunciation, not spelling. Regarding ensure/insure, [“ There are some newspapers and magazines [...] that still use “insure” in both instances, but it’s fairly archaic to do so. Most publications differentiate the two.”](https://www.writersdigest.com/online-editor/ensure-vs-insure). In any case, most people associate “insure” with buying insurance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T18:34:19.540", "Id": "458478", "Score": "0", "body": "Since it is a most people issue, it is not a typo then. \"Tomeito/tomahto is about pronunciation\" was to lighten the mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T10:42:37.073", "Id": "462179", "Score": "0", "body": "@chqrlie [Code must not be edited after an answer has been posted](https://codereview.meta.stackexchange.com/a/2376/52915)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T14:14:52.897", "Id": "462209", "Score": "0", "body": "@Mast: sorry about that, I should know :)... yet a corrected version of the code should be posted as an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:48:13.580", "Id": "521574", "Score": "0", "body": "Are you also interested in looking for DeathStation 9000 intentionally-hostile compilers with maximally weird setups that nobody would ever want to use? Your question phrasing is mostly about real-world practical compilers. (IDK if there's anything a DS9k might do that isn't already covered.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:27:21.283", "Id": "534323", "Score": "0", "body": "@chux-ReinstateMonica From OED: *There is considerable overlap between the meaning and use of insure and ensure. In both British and US English the primary meaning of insure is the commercial sense of providing financial compensation in the event of damage to property; ensure is not used at all in this sense. For the more general senses, ensure is the more usual word, but insure is also sometimes used, particularly in US English, e.g. bail is posted to insure that the defendant appears for trial; the system is run to ensure that a good quality of service is maintained.* It's ensure not insure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:28:15.883", "Id": "534324", "Score": "0", "body": "@chux-ReinstateMonica Not that it's really important but since you tried going there I might as well go there too. Maybe US English uses it more though. I don't use US English so I don't really know. But it doesn't really matter I guess anyway. Stay safe in our crazy world!" } ]
[ { "body": "<p>I'm appalled! What kind of code are you writing that's so inflexible it needs all these tests? ;-p</p>\n\n<p>Seriously, it ought to be possible to enable only the tests that the including code needs, perhaps by predefining macros that declare its non-portabilities:</p>\n\n<pre><code>#ifdef REQUIRE_BINARY_FP\nstatic_assert(FLT_RADIX == 2, \"Dinosuar: Non binary FP\");\n#endif\n</code></pre>\n\n<p>(to pick a simple example)</p>\n\n<hr>\n\n<p>On an extremely minor note, in the comments you've consistently written \"insure\" where you evidently mean \"ensure\".</p>\n\n<hr>\n\n<p>Additional tests to consider:</p>\n\n<ul>\n<li>I've seen code that breaks if <code>'z' - 'a' != 25</code> and/or <code>'Z' - 'A' != 25</code>.</li>\n<li>Some code requires the existence of exact-width integer types such as <code>uint32_t</code>, which are not available on all platforms (it's possible this is covered by the power-of-two byte-width test, but I can't prove it).</li>\n<li>Perhaps some code requires <code>long double</code> to be bigger (in precision and/or range) than <code>double</code>?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:56:47.143", "Id": "521576", "Score": "1", "body": "A DeathStation9000 could choose not to provide `uint32_t` even if `CHAR_BIT=8`, even if `unsigned` would work as `uint32_t`. That's unlikely for real-world C99 implementations, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:32:48.760", "Id": "534325", "Score": "0", "body": "@PeterCordes And technically *uintN_t* are optional. You can use e.g. *uint_least32_t* instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T11:07:14.923", "Id": "215187", "ParentId": "215113", "Score": "10" } }, { "body": "<ul>\n<li><p>I think that <code>static_assert((CHAR_BIT &amp; (CHAR_BIT - 1)) == 0</code> can be pretty safely replaced by <code>CHAR_BIT==8</code>. There are various old DSP compilers that would fail the test, but they are indeed dinosaur systems.</p>\n</li>\n<li><p>stdint.h and constants like <code>SIZE_MAX</code>, <code>PTRDIFF_MAX</code> were added in C99. So by using such macros/constants, you'll essentially cause all C90 compilers to fail compilation.</p>\n<p>Are C90 compilers dinosaurs per your definition? If not, then maybe\ndo some checks if <code>__STDC_VERSION__</code> is defined and if so what\nversion. Because most of the exotic ones are likely to follow C90.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:53:04.060", "Id": "521575", "Score": "1", "body": "I was under the impression that some *modern* DSPs were word-addressable and had `CHAR_BIT` = 16, 24, or 32. But I don't do embedded development so I might have read something old without realizing it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:41:45.987", "Id": "215204", "ParentId": "215113", "Score": "13" } }, { "body": "<p>In addition to fine answers <a href=\"https://codereview.stackexchange.com/a/215187/29485\">@Toby Speight</a>, <a href=\"https://codereview.stackexchange.com/a/215204/29485\">@Lundin</a> and <a href=\"https://stackoverflow.com/q/55300378/2410359\">a related FP question</a>, came up with additional idea/detail.</p>\n\n<p><strong>Spelling*</strong></p>\n\n<p>\"Dinosuar\" --> \"Dinosaur\".</p>\n\n<p><strong><a href=\"https://en.wikipedia.org/wiki/ASCII\" rel=\"noreferrer\">ASCII</a> or not</strong></p>\n\n<p>Could use a lengthy test of the <em>execution character set</em> <code>C11 §5.2.1 3</code></p>\n\n<pre><code>A to Z\na to z\n0 to 9\n! \" # % &amp; ’ ( ) * + , - . / : ; &lt; = &gt; ? [ \\ ] ^ _ { | } ~\nspace character, \n and control characters representing horizontal tab, vertical tab, and form feed.\nsome way of indicating the end of each line of text\n</code></pre>\n\n<p>Note that <code>$</code>, <code>@</code>, <a href=\"https://en.wikipedia.org/wiki/Grave_accent\" rel=\"noreferrer\">grave accent</a>, ASCII 127 and various control characters are not mentioned above.</p>\n\n<pre><code> static_assert(\n 'A' == 65 &amp;&amp; 'B' == 66 &amp;&amp; 'C' == 67 &amp;&amp; 'D' == 68 &amp;&amp; 'E' == 69 &amp;&amp; 'F' == 70\n &amp;&amp; 'G' == 71 &amp;&amp; 'H' == 72 &amp;&amp; 'I' == 73 &amp;&amp; 'J' == 74 &amp;&amp; 'K' == 75\n &amp;&amp; 'L' == 76 &amp;&amp; 'M' == 77 &amp;&amp; 'N' == 78 &amp;&amp; 'O' == 79 &amp;&amp; 'P' == 80\n &amp;&amp; 'Q' == 81 &amp;&amp; 'R' == 82 &amp;&amp; 'S' == 83 &amp;&amp; 'T' == 84 &amp;&amp; 'U' == 85\n &amp;&amp; 'V' == 86 &amp;&amp; 'W' == 87 &amp;&amp; 'X' == 88 &amp;&amp; 'Y' == 89 &amp;&amp; 'Z' == 90,\n \"Dinosaur: not ASCII A-Z\");\n static_assert(\n 'a' == 97 &amp;&amp; 'b' == 98 &amp;&amp; 'c' == 99 &amp;&amp; 'd' == 100 &amp;&amp; 'e' == 101\n &amp;&amp; 'f' == 102 &amp;&amp; 'g' == 103 &amp;&amp; 'h' == 104 &amp;&amp; 'i' == 105 &amp;&amp; 'j' == 106\n &amp;&amp; 'k' == 107 &amp;&amp; 'l' == 108 &amp;&amp; 'm' == 109 &amp;&amp; 'n' == 110 &amp;&amp; 'o' == 111\n &amp;&amp; 'p' == 112 &amp;&amp; 'q' == 113 &amp;&amp; 'r' == 114 &amp;&amp; 's' == 115 &amp;&amp; 't' == 116\n &amp;&amp; 'u' == 117 &amp;&amp; 'v' == 118 &amp;&amp; 'w' == 119 &amp;&amp; 'x' == 120 &amp;&amp; 'y' == 121\n &amp;&amp; 'z' == 122, \"Dinosaur: not ASCII a-z\");\n static_assert('0' == 48, \"Dinosaur: not ASCII 0-9\"); // 1-9 follow 0 by spec.\n static_assert(\n '!' == 33 &amp;&amp; '\"' == 34 &amp;&amp; '#' == 35 &amp;&amp; '%' == 37 &amp;&amp; '&amp;' == 38\n &amp;&amp; '\\'' == 39 &amp;&amp; '(' == 40 &amp;&amp; ')' == 41 &amp;&amp; '*' == 42 &amp;&amp; '+' == 43\n &amp;&amp; ',' == 44 &amp;&amp; '-' == 45 &amp;&amp; '.' == 46 &amp;&amp; '/' == 47 &amp;&amp; ':' == 58\n &amp;&amp; ';' == 59 &amp;&amp; '&lt;' == 60 &amp;&amp; '=' == 61 &amp;&amp; '&gt;' == 62 &amp;&amp; '?' == 63\n &amp;&amp; '[' == 91 &amp;&amp; '\\\\' == 92 &amp;&amp; ']' == 93 &amp;&amp; '^' == 94 &amp;&amp; '_' == 95\n &amp;&amp; '{' == 123 &amp;&amp; '|' == 124 &amp;&amp; '}' == 125 &amp;&amp; '~',\n \"Dinosaur: not ASCII punct\");\n static_assert(\n ' ' == 32 &amp;&amp; '\\t' == 9 &amp;&amp; '\\v' == 11 &amp;&amp; '\\f' == 12 &amp;&amp; '\\n' == 10,\n \"Dinosaur: not ASCII space, ctrl\");\n static_assert('\\a' == 7 &amp;&amp; '\\b' == 8 &amp;&amp; '\\r' == 13,\n \"Dinosaur: not ASCII spaces\");\n // Not 100% confident safe to do the following test\n static_assert('$' == 36 &amp;&amp; '@' == 64 &amp;&amp; '`' == 96,\n \"Dinosaur: not ASCII special\");\n</code></pre>\n\n<hr>\n\n<p>[Edit 2019 Dec]</p>\n\n<p>On review, incorporating <a href=\"https://codereview.stackexchange.com/questions/215113/detecting-unicorn-and-dinosaur-compilers#comment415934_215113\">@Deduplicator</a> idea: <code>CHAR_MAX &lt;= INT_MAX</code> is not a strong enough test to avoid trouble with <code>fgetc()</code>, but should use <code>UCHAR_MAX &lt;= INT_MAX</code>. This makes certain that the number of possible characters returned from <code>fgetc()</code> is less than the positive <code>int</code> range - preventing a collision with <code>EOF</code>.</p>\n\n<pre><code>/*\n * Insure char is sub-range of int\n * When char values exceed int, makes for tough code using fgetc()\n */\n// static_assert(CHAR_MAX &lt;= INT_MAX, \"Dinosaur: wide char\");\nstatic_assert(UCHAR_MAX &lt;= INT_MAX, \"Dinosaur: wide char\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:59:45.783", "Id": "521577", "Score": "0", "body": "I don't suppose there's any way to rewrite those ASCII range tests as `\"ABCDEFGHI...XYZ\" with a check for `str[i+65] == i`. Probably not in a way compatible with static_assert, without C++ constexpr functions to allow a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T19:04:44.890", "Id": "521578", "Score": "0", "body": "@PeterCordes I do not see a way. Perhaps `static_assert('A' == 65 && 'B' == 'A' + 1 && 'C' == 'B' + 1 && 'D' == 'C' + 1 ...` for a more friendly/sane looking test?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T19:26:19.143", "Id": "216017", "ParentId": "215113", "Score": "8" } }, { "body": "<p>Instead of:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>static_assert(SCHAR_MIN &lt; -SCHAR_MAX &amp;&amp; SHRT_MIN &lt; -SHRT_MAX &amp;&amp;\n INT_MIN &lt; -INT_MAX &amp;&amp; LONG_MIN &lt; -LONG_MAX &amp;&amp;\n LLONG_MIN &lt; -LLONG_MAX &amp;&amp; INTMAX_MIN &lt; -INTMAX_MAX &amp;&amp;\n INTPTR_MIN &lt; -INTPTR_MAX &amp;&amp; PTRDIFF_MIN &lt; -PTRDIFF_MAX\n , \"Dinosuar: Non-2's complement.\");\n</code></pre>\n\n<p>I prefer:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>static_assert( SCHAR_MIN &lt; -SCHAR_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert( SHRT_MIN &lt; -SHRT_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert( INT_MIN &lt; -INT_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert( LONG_MIN &lt; -LONG_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert( LLONG_MIN &lt; -LLONG_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert( INTMAX_MIN &lt; -INTMAX_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert( INTPTR_MIN &lt; -INTPTR_MAX, \"Dinosaur: Non-2's complement.\");\nstatic_assert(PTRDIFF_MIN &lt; -PTRDIFF_MAX, \"Dinosuar: Non-2's complement.\");\n</code></pre>\n\n<p>Granted, this code won't survive any automated code formatting, but it's much easier to grasp than the all-in-one assertion. Also, when one of the assertions fails, you know exactly which of these types is unusual.</p>\n\n<p>On another topic: <code>UNICODE_BW1</code> is a typo, it should be <code>UNICORN_BW1</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T15:21:21.847", "Id": "462219", "Score": "0", "body": "This approach does have an advantage if needing to compile pre-C99 as it is cleaner to `#if define(LLONG_MIN)` around `static_assert( LLONG_MIN < -LLONG_MAX, ...` and any select integer types." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T15:15:19.627", "Id": "236025", "ParentId": "215113", "Score": "4" } } ]
{ "AcceptedAnswerId": "215204", "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T19:13:13.617", "Id": "215113", "Score": "20", "Tags": [ "c" ], "Title": "Detecting unicorn and dinosaur compilers" }
215113
<p>I asked <a href="https://codereview.stackexchange.com/questions/214879/implementation-ceaser-cipher-in-c">another question the other day</a> and decided to rewrite the code with some of the suggestions given and add functionality (instead of reading from a console I'm reading directly from a file) the code works.</p> <p>Looking at it, I think the nested <code>for</code> loop on the encode function doesn't look that good. I tried using <code>std::transform</code> like the comment on the code. It worked when I used the console just to read a line, now with vectors couldn't make it work.</p> <pre><code>// Ceaser Cipher implementation #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;fstream&gt; #include &lt;vector&gt; std::vector&lt;std::string&gt; encode(const std::vector&lt;std::string&gt; &amp;str, int shift) { std::vector&lt;std::string&gt; tempMsg; for (std::string lines : str) { // std::transform(lines.cbegin(), lines.cend(), std::back_inserter(tempMsg), [&amp;](char ch) -&gt; char for (char &amp;ch : lines) { if (ch == 'z' || ch == 'Z') { ch -= 25; } else if (isspace(ch)) { ch = ' '; } else { ch += shift; } } tempMsg.push_back(lines); } return tempMsg; } std::vector&lt;std::string&gt; decode(const std::vector&lt;std::string&gt; &amp;str, int shift) { return encode(str, -1 * shift); } int main(int argc, char *argv[]) { int choice; std::cout &lt;&lt; "What do you want to do? 1.Encrypt, 2.Decrypt: "; std::cin &gt;&gt; choice; int key; std::cout &lt;&lt; "Enter desired shift: "; std::cin &gt;&gt; key; std::ifstream inFile("testfile.txt"); if (!(inFile.is_open())) { std::cout &lt;&lt; "There was a problem with the file!"; std::exit(EXIT_FAILURE); // ExitProcess() if windows especific. } std::vector&lt;std::string&gt; finalResult; std::string line; std::vector&lt;std::string&gt; lines; while (std::getline(inFile, line)) { lines.push_back(line); } inFile.close(); if (choice == 1) { auto result = encode(lines, key); finalResult = result; } else if (choice == 2) { auto result = decode(lines, key); finalResult = result; } else { std::cout &lt;&lt; "Wrong option, exiting!"; std::exit(EXIT_FAILURE); } std::ofstream outFile("testfile.txt"); for (auto i = finalResult.begin(); i != finalResult.end(); ++i) { outFile &lt;&lt; *i &lt;&lt; '\n'; } outFile.close(); std::exit(EXIT_SUCCESS); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T08:00:29.403", "Id": "415982", "Score": "0", "body": "Please [edit] your post to include your test cases. The test cases should contain at least one test that shifts the complete alphabet by 7 places and unshifts it again. Another test should demonstrate what happens when you encode a phone number by shifting it 32 places and then decode it again. (I expect these tests to fix the worst bugs.) As long as there are no answers yet, you may still update the post." } ]
[ { "body": "<p>In the following, I am omitting checking for the correctness of the outputs as you have not provided a specification for what that should be. Nevertheless, consider the following points.</p>\n\n<ul>\n<li><p>I think the signatures of your encoding and decoding functions are a bit unexpected: I would expect an encoding function to take a single string and not a vector of strings. This gives me the feeling that the function is doing too much (i.e., violating the guideline of <em>one function, one responsibility</em>). So I would break the logic into smaller pieces:</p>\n\n<pre><code>std::string encode(const std::string&amp; str, int shift)\n{\n std::string str_enc;\n std::transform(str.cbegin(), str.cend(), std::back_inserter(str_enc), [&amp;](char ch) -&gt; char \n { \n if (ch == 'z' || ch == 'Z')\n {\n return ch - 25;\n }\n else if (isspace(ch)) \n {\n return ' ';\n }\n else\n {\n return ch + shift;\n }\n });\n\n return str_enc;\n}\n\nstd::vector&lt;std::string&gt; encode(const std::vector&lt;std::string&gt;&amp; str, int shift)\n{\n std::vector&lt;std::string&gt; tempMsg;\n std::transform(str.cbegin(), str.cend(), std::back_inserter(tempMsg),\n [&amp;](const std::string&amp; s) { return encode(s, shift); });\n\n return tempMsg;\n}\n</code></pre></li>\n<li><p>In the main loop logic, before getting into any file reading, check whether the <code>choice</code> made by the user is sensible (either 1 or 2). This allows you to make <code>finalResult</code> const and to initialize it in a nicer way. This is a good modern practice as given by e.g., <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-lambda-init\" rel=\"nofollow noreferrer\">ES.28 of the C++ Core Guidelines</a>:</p>\n\n<pre><code>assert(choice == 1 || choice == 2);\nconst std::vector&lt;std::string&gt; finalResult = [&amp;]()\n{\n return choice == 1 ? encode(lines, key) : decode(lines, key);\n}(); \n</code></pre></li>\n<li><p>You don't have to explicitly close file streams. They close upon destruction.</p></li>\n<li><p>To check if the file is good to go, you can do <code>if(inFile) { ... }</code> invoking its <code>operator bool()</code> which tells you if the stream has no errors and is ready for I/O operations (specifically, it returns <code>!fail()</code>).</p></li>\n<li><p>When writing to file, you can use standard algorithms (like <code>std::copy</code>) since your logic is very simple:</p>\n\n<pre><code>std::ofstream outFile(\"outfile.txt\");\nstd::copy(finalResult.cbegin(), finalResult.cend(), \n std::ostream_iterator&lt;std::string&gt;(outFile, \"\\n\"));\n</code></pre></li>\n<li><p>Everywhere in your code, avoid using <code>std::exit</code> (for reasons and more discussion, see <a href=\"https://stackoverflow.com/questions/38724788/what-is-the-difference-between-exit-and-stdexit-in-c\">here</a>). Instead, just do <code>return EXIT_FAILURE</code> or <code>return EXIT_SUCCESS</code> as appropriate.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T11:59:25.913", "Id": "215133", "ParentId": "215115", "Score": "2" } }, { "body": "<p>Take a look at your code, and think about the spec:</p>\n\n<p>It should be, put all letters in order in a circle, if the input is in position n, the output is in position n + shift.</p>\n\n<p>What you have is quite a lot more complicated, and in no way meets the spec.</p>\n\n<hr>\n\n<ol>\n<li>You should add <code>tempMsg.reserve(str.size());</code> to avoid reallocations.</li>\n<li>You should move the line into <code>tempMsg</code> instead of making a spurious copy.</li>\n<li>Consider normalising the shift before using it. And why not pre-calculate a lookup-table for use in the transform? Your choice on whether to do it on the fly, or do all 26 possible ones at compile-time.</li>\n<li>There isn't actually any advantage to using <code>std::transform</code> instead of a for-range-loop, but anyway the third argument should be <code>lines.begin()</code>.</li>\n<li>Your naming is curious: <code>str</code> for all lines, <code>lines</code> for a single line... Also, why not call <code>tempMsg</code> something Shorter but more descriptive like <code>ret</code>?</li>\n<li>You might want to reconsider your decision to read the whole file into memory before starting processing. It isn't even useful to read it as separate lines instead of blocks.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T15:40:33.730", "Id": "416029", "Score": "0", "body": "Hi, about point 5. You are rigth I forgot to change variables when I went from reading just one string to reading files. Point 6 - do you mean read as I do the encoding? Point 3 - What do you mean by lookup-table? Anyway thank you for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:13:24.977", "Id": "416033", "Score": "0", "body": "re 6: Yes, no need for any dynamic allocation. re 3: Simply a `unsigned char[1 + (unsigned char)-1]` where you pre-compute the result for every input, making the transformation itself trivial. And as there are only 26 variations for that lookup-table, it might make sense to calculate them all at compile-time and choose." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T12:03:16.367", "Id": "215134", "ParentId": "215115", "Score": "2" } } ]
{ "AcceptedAnswerId": "215133", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T20:42:11.553", "Id": "215115", "Score": "2", "Tags": [ "c++", "caesar-cipher" ], "Title": "C++ Caesar cipher - follow-up" }
215115
<p>Thanks for all the feedback, I <a href="https://codereview.stackexchange.com/questions/215453/queue-interview-code-basic-methods-made-from-struct-node-optimized">optimized the code here</a>.</p> <p>Here I'm Writing a very simple Queue of struct Nodes with only these methods <code>get_front()</code>, <code>get_back()</code>, <code>pop_front()</code>, <code>push_back()</code>, <code>print</code>. I hope <code>using namespace std;</code> is okay, I will note it should not be used this way in production and I am only using the approach to write my code as quickly as possible so I can have more time to test and refactor while I discuss the code with my interviewer.</p> <p>This is not for production and is to be treated as code that could be used in an interview or a quick and dirty prototype. I'm really curious about the approach I've taken here to keep track of the size, empty status, and back and front pointers, and use of only previous in my Node struct instead of next and previous pointers. I felt having both was not needed and previous makes more sense for a queue.</p> <p>I'd like to know also if my member functions for the Queue have any edge cases I am not catching and any improvements I can make to run time efficiency. Anyway I can simplify this code further with c++11 features, shorter variable names or any other suggestions would be appreciated too.</p> <p>Lastly if you optionally would like to share the memory/space complexity for my code that would be a huge help! I have noted some examples in the member data of my Node struct. </p> <pre><code>#include &lt;iostream&gt; using namespace std; struct Node { int data; // 4 bytes for primatives Node* previous; // 8 bytes for pointers Node(int data) : data(data), previous(nullptr) { } }; struct Queue { Node* queue; int size; bool is_empty; Node* front; Node* back; Queue() : queue(nullptr), size(0), is_empty(true), front(nullptr), back(nullptr) { } string get_front() { if (front == nullptr) { return "empty"; } else { return to_string(front-&gt;data); } } string get_back() { if (back == nullptr) { return "empty"; } else { return to_string(back-&gt;data); } } void push_back(int data, Node* current) { if (current-&gt;previous == nullptr) { Node* n = new Node(data); current-&gt;previous = n; back = n; } else { push_back(data, current-&gt;previous); } } void push_back(int data) { if (is_empty) { queue = new Node(data); back = queue; front = queue; is_empty = false; } else { push_back(data, queue); } size++; } void pop_front() { size--; if (front-&gt;previous == nullptr) { front = nullptr; back = nullptr; delete queue; is_empty = true; } else { Node* dangling = front; front = front-&gt;previous; delete dangling; } } void print(Node* current, string queue_string) { if (current-&gt;previous == nullptr) { queue_string = to_string(current-&gt;data) + " " + queue_string; cout &lt;&lt; queue_string &lt;&lt; endl; } else { queue_string = to_string(current-&gt;data) + " " + queue_string; print(current-&gt;previous, queue_string); } } void print() { if (is_empty) { cout &lt;&lt; "_____________\n\n"; cout &lt;&lt; "_____________\n"; } else { cout &lt;&lt; "_____________\n"; print(front, ""); cout &lt;&lt; "_____________\n"; } } }; int main() { Queue queue; queue.push_back(9); queue.push_back(8); queue.push_back(7); queue.push_back(6); queue.push_back(5); queue.print(); cout &lt;&lt; "front " &lt;&lt; queue.get_front() &lt;&lt; endl; cout &lt;&lt; "back " &lt;&lt; queue.get_back() &lt;&lt; endl; cout &lt;&lt; "size " &lt;&lt; to_string(queue.size) &lt;&lt; endl; cout &lt;&lt; boolalpha &lt;&lt; "queue empty status is " &lt;&lt; queue.is_empty &lt;&lt; endl; queue.pop_front(); queue.pop_front(); queue.pop_front(); queue.print(); cout &lt;&lt; "front " &lt;&lt; queue.get_front() &lt;&lt; endl; cout &lt;&lt; "back " &lt;&lt; queue.get_back() &lt;&lt; endl; cout &lt;&lt; "size " &lt;&lt; to_string(queue.size) &lt;&lt; endl; cout &lt;&lt; "queue empty status is " &lt;&lt; queue.is_empty &lt;&lt; endl; queue.pop_front(); queue.pop_front(); queue.print(); cout &lt;&lt; "front " &lt;&lt; queue.get_front() &lt;&lt; endl; cout &lt;&lt; "back " &lt;&lt; queue.get_back() &lt;&lt; endl; cout &lt;&lt; "size " &lt;&lt; to_string(queue.size) &lt;&lt; endl; cout &lt;&lt; "queue empty status is " &lt;&lt; queue.is_empty &lt;&lt; endl; } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://www.quora.com/How-is-it-true-that-if-I-used-code-using-namespace-std-code-in-an-interview-Ill-be-rejected-immediately\" rel=\"nofollow noreferrer\">Possibly already failed the interview</a></p>\n\n<hr>\n\n<p><strong>Note:</strong> I added an underscore here to avoid another warning that your code generates, namely <a href=\"https://en.wikipedia.org/wiki/Variable_shadowing\" rel=\"nofollow noreferrer\">variable shadowing</a></p>\n\n<blockquote>\n<pre><code>struct Node\n{\n int data; // 4 bytes for primatives\n Node* previous; // 8 bytes for pointers\n\n Node(int data_) : data(data_), previous(nullptr) { }\n};\n</code></pre>\n</blockquote>\n\n<p>Those size assumptions are not necessarily true (also note the typo).<br>\nDepending on the compiler and warning levels you might get padding warnings for the <code>Node</code> struct as well as for this part:</p>\n\n<blockquote>\n<pre><code>struct Queue\n{\n Node* queue;\n int size;\n bool is_empty;\n Node* front;\n Node* back;\n ...\n</code></pre>\n</blockquote>\n\n<p>e.g.:</p>\n\n<pre><code>warning: padding struct 'Node' with 4 bytes to align 'previous' [-Wpadded]\nwarning: padding struct 'Queue' with 3 bytes to align 'front' [-Wpadded]\n</code></pre>\n\n<p>Which is the compiler telling you that it will align things in a way that results in wasted space in the middle of your structs.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>Queue() : queue(nullptr), size(0), is_empty(true), front(nullptr), back(nullptr) { }\n</code></pre>\n</blockquote>\n\n<p>If you don't intend to parameterize your <code>Queue</code> then you don't need to initialize in the ctor.<br>\nInstead you can initalize directly like so:</p>\n\n<pre><code>struct Queue\n{\n Node* queue{nullptr};\n int size{0};\n bool is_empty{true};\n Node* front{nullptr};\n Node* back{nullptr};\n ...\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>if (front == nullptr) {\n</code></pre>\n</blockquote>\n\n<p>You compare to <code>nullptr</code> in various places. Don't. Instead do e.g. <code>!front</code>.</p>\n\n<hr>\n\n<p>At a glance this seems to leak memory as there is no cleanup code and you don't use smart pointers.</p>\n\n<hr>\n\n<p>Apply <code>const</code> where appropriate, at least for the print functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:31:05.617", "Id": "416035", "Score": "0", "body": "Thanks yuri this was really helpful. Only have a few questions, everything else is really clear. Also I'll consider explicitly calling the namespace in an interview to make sure I show up at my very best. I don't fully understand the padding issue and how to fix it, can you explain more? Why should I uses `void print() const { }` or consider using const in other areas?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T17:56:33.573", "Id": "416039", "Score": "1", "body": "@greg (1) For questions about `const` refer to the other excellent reviews. (2) In your case the padding issue could be fixed by manually inserting padding to satisfy the compiler (e.g. `char padding[4]` / `char padding[3]` at places where the compiler complained). [More1](https://software.intel.com/en-us/articles/coding-for-performance-data-alignment-and-structures) [about²](https://hownot2code.com/2016/11/10/the-lost-art-of-c-structure-packing/) [padding³](https://stackoverflow.com/questions/5397447/struct-padding-in-c)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T18:13:51.900", "Id": "416040", "Score": "0", "body": "That's so interesting, firs time I've seen a warning like this. Out side of using the `-W` flag is there any way to notice a padding issue just by looking at the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T18:26:42.497", "Id": "416042", "Score": "0", "body": "Also `Node(int data_)` I noticed the use of underscore in the Node param, is this a style choice or a common practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:05:49.643", "Id": "416046", "Score": "0", "body": "Also of if I refactor this code should I just submit a new question to Code Review and link to this original post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:40:26.273", "Id": "416053", "Score": "1", "body": "(1) Sorry about the underscore. I left it in when I was refactoring your code a bit. It hides another warning, namely that your variable is shadowed. My personal preference is to append a suffix (underscore) to parameters having the same name as a member to evade this. (2) Yes if you rewrite your code please ask another question with the new code and maybe linking to this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:50:03.177", "Id": "416057", "Score": "0", "body": "Sounds good I will, when I refactor I may include the underscore as well to avoid confusion with the variable shadowing too." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T11:07:59.297", "Id": "215130", "ParentId": "215117", "Score": "5" } }, { "body": "<p>To expand on the other review(s), you should pay attention to const correctness.</p>\n\n<ul>\n<li><p>The functions <code>get_front</code>, <code>get_back</code> and both overloads of <code>print</code> should be made const as they don't modify the object. This increases readability and protects from unintended mistakes.</p></li>\n<li><p>There is no need to take the argument by-value in <code>print</code>. You can rewrite this to e.g.,</p>\n\n<pre><code>void print(Node* current, const string&amp; queue_string) const\n{\n const std::string qs = to_string(current-&gt;data) + \" \" + queue_string;\n if (!current-&gt;previous) {\n cout &lt;&lt; qs &lt;&lt; endl;\n }\n else {\n print(current-&gt;previous, qs);\n }\n}\n</code></pre></li>\n<li><p>You need to include <code>&lt;string&gt;</code> because you use <code>std::string</code>.</p></li>\n<li><p>Ultimately, you should properly encapsulate the data and methods in your class (i.e., not use a struct that publicly exposes everything).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:41:54.750", "Id": "215144", "ParentId": "215117", "Score": "3" } }, { "body": "<p>I see a number of things that could help you improve your code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\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. Know when to use it and when not to (as when writing include headers). If I were hiring, I'd prefer that the candidate actually write production quality code, rather than point out that the just-produced sample was not, even if they could articulate and justify the difference. After all, they're probably not hiring someone to produce non-production sample code, right?</p>\n\n<h2>Don't define a default constructor that only initializes data</h2>\n\n<p>Instead of writing this:</p>\n\n<pre><code>struct Queue\n{\n Node* queue;\n int size;\n bool is_empty;\n Node* front;\n Node* back;\n\n Queue() : queue(nullptr), size(0), is_empty(true), front(nullptr), back(nullptr) { }\n // etc.\n};\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>struct Queue\n{\n Node* queue = nullptr;\n int size = 0;\n bool is_empty = true;\n Node* front = nullptr;\n Node* back = nullptr;\n\n // no need to write default constructor\n // other code\n};\n</code></pre>\n\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-default\" rel=\"nofollow noreferrer\">Cpp Core Guidelines C.45</a> for details.</p>\n\n<h2>Use <code>class</code> rather than <code>struct</code> if there are invariants</h2>\n\n<p>The current <code>Queue</code> has pointers and <code>size</code> and <code>is_empty</code> members. Will everything still work if those are arbitrarily changed to random values? No, it will not. There are expectations that <code>size</code> and <code>is_empty</code> will always have the right values and the values of the pointers are critical to the operation of the data structure, therefore this must be a <code>class</code> and not a <code>struct</code>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-struct\" rel=\"nofollow noreferrer\">Cpp Core Guidelines C.2</a>.</p>\n\n<h2>Eliminate redundant data</h2>\n\n<p>Rather than maintaining a separate <code>is_empty</code> data item, I'd suggest only keeping the <code>size</code> and defining a function instead like this:</p>\n\n<pre><code>bool is_empty() const { return size == 0; }\n</code></pre>\n\n<p>As per the previous advice, I'd also keep <code>size</code> private and provide a <code>public</code> access function if needed:</p>\n\n<pre><code>std::size_t size() const { return size_; }\n</code></pre>\n\n<p>Also, you don't really need both <code>queue</code> and <code>front</code>. The code would be both clearer and more compact if only <code>front</code> and <code>back</code> pointers were included.</p>\n\n<h2>Use the appropriate data types</h2>\n\n<p>Would it ever make sense to have a negative <code>size</code> for a queue? I'd suggest not, and so it would make more sense to have <code>size</code> be a <code>std::size_t</code> type.</p>\n\n<h2>Rethink the interface</h2>\n\n<p>If a user of this <code>Queue</code> were to invoke <code>get_front()</code> on an empty queue, I think it would be a much better interface to either throw an exception or to return an empty string rather than the special value <code>\"empty\"</code>. It's also quite peculiar to push <code>int</code>s and then pop strings. That's not what I'd want. Here's how I'd write <code>get_front</code>:</p>\n\n<pre><code>int get_front() const {\n if (is_empty()) {\n throw std::out_of_range{\"cannot get data from empty queue\"};\n }\n return front-&gt;data;\n}\n</code></pre>\n\n<h2>Use const where practical</h2>\n\n<p>The current <code>print()</code> functions do not (and should not) modify the underlying object, and so both should be declared <code>const</code>:</p>\n\n<pre><code>void print(const Node* current, std::string queue_string) const;\nvoid print() const;\n</code></pre>\n\n<p>I would also make the first variant <code>private</code> because the user of the class should not have any pointer to an internal structure.</p>\n\n<h2>Fix the bugs</h2>\n\n<p>There are several problems with <code>pop_front</code>. First, it doesn't check for an empty queue before decrementing the <code>size</code> which is an error. Second, it does not correctly update <code>queue</code> and leads to dereferencing freed memory which is <em>undefined behavior.</em></p>\n\n<h2>Don't use <code>std::endl</code> if <code>'\\n'</code> will do</h2>\n\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>.</p>\n\n<h2>Avoid <code>to_string</code></h2>\n\n<p>The <code>print</code> function currently contains these lines:</p>\n\n<pre><code>queue_string = to_string(current-&gt;data) + \" \" + queue_string;\ncout &lt;&lt; queue_string &lt;&lt; endl;\n</code></pre>\n\n<p>This creates another string and then prints that string which is not needed. Instead, just print directly:</p>\n\n<pre><code>cout &lt;&lt; current-&gt;data &lt;&lt; ' ' &lt;&lt; queue_string &lt;&lt; '\\n';\n</code></pre>\n\n<h2>Use all of the required <code>#include</code>s</h2>\n\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\n<h2>Prefer iteration over recursion</h2>\n\n<p>Recursion tends to use additional stack space over iteration. For that reason (and often for clarity) I'd recomment writing <code>print</code> like this instead:</p>\n\n<pre><code>void print() const {\n std::cout &lt;&lt; \"_____________\\n\";\n for (const auto *item = front; item; item = item-&gt;previous) {\n std::cout &lt;&lt; item-&gt;data &lt;&lt; ' ';\n }\n std::cout &lt;&lt; \"\\n_____________\\n\";\n}\n</code></pre>\n\n<p>Even better would be to pass a <code>std::ostream &amp;</code> argument to this function to allow printing to any stream.</p>\n\n<h2>Simplify your code</h2>\n\n<p>The recursive <code>push_back</code> function is much longer than it needs to be. I'd write it like this:</p>\n\n<pre><code>void push_back(int data) {\n auto temp = new Node{data};\n ++size_;\n if (back == nullptr) { // adding to empty queue\n front = back = temp;\n } else {\n back-&gt;previous = temp;\n back = temp;\n }\n}\n</code></pre>\n\n<p>Note that this version assumes that the data members <code>queue</code> and <code>is_empty</code> have already been removed per the suggestions above.</p>\n\n<h2>Make test success obvious</h2>\n\n<p>The current test code exercizes the queue, but it doesn't indicate what is <em>expected</em> to be printed. I'd instead write both test scenarios and also the expected result so that it would be clear to anyone running the code whether everything was working as expected or not.</p>\n\n<h2>Make private structures private</h2>\n\n<p>Nothing outside of <code>Queue</code> needs to know anything about <code>Node</code>, so I'd strongly recommend making the definition of <code>Node</code> <code>private</code> within <code>Queue</code>.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>This program leaks memory because the <code>Queue</code>'s destructor doesn't free all resources. This is a serious bug.</p>\n\n<h2>Consider using a template</h2>\n\n<p>A queue is a fairly generic structure that could hold any kind of data if the class were templated, and not just an <code>int</code>.</p>\n\n<h2>Consider possible uses</h2>\n\n<p>For any code production, but especially if you're in an interview, think about how the class is being used and whether there are any restrictions or limits inherent in the design. For example, think about <code>copy</code> and <code>move</code> operations. If you write this, does the code do the right thing?</p>\n\n<pre><code>Queue queue;\nqueue.push_back(5);\nqueue.push_back(6);\nqueue.push_back(7);\nauto a_copy{queue};\na_copy.pop_front();\nqueue.print();\na_copy.print();\n</code></pre>\n\n<p>Also consider multithreaded code. Would it be thread-safe to push from one thread and pull from another? If not, what would be needed to make that work?</p>\n\n<h2>Don't make platform assumptions</h2>\n\n<p>Although it doesn't adversely affect the code, the assumptions about data sizes in the comments for <code>Node</code> are simply incorrect on my machine and would be a red flag in an interview.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:56:24.083", "Id": "215145", "ParentId": "215117", "Score": "4" } } ]
{ "AcceptedAnswerId": "215145", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T20:59:36.063", "Id": "215117", "Score": "2", "Tags": [ "c++", "c++11", "queue", "pointers" ], "Title": "Queue Interview Code basic methods made from struct Node" }
215117
<p>I have made a login system where the inserted_id and inserted_password are sent to the <code>login.inc.php</code> via the <code>XMLHttpRequest</code>. I'm not sure if my PHP script is secure. I need some securing advice for my script.</p> <p><strong>login.inc.php:</strong></p> <pre><code>&lt;?php session_start(); $conn = mysqli_connect("localhost", "root", "", "users"); $params = json_decode(file_get_contents('php://input'), true); $inserted_id = $params['inserted_id']; $inserted_password = $params['inserted_password']; $stmt = mysqli_stmt_init($conn); if (mysqli_stmt_prepare($stmt, "SELECT * FROM user WHERE account_name=? OR email=?;")) { mysqli_stmt_bind_param($stmt, "ss", $inserted_id, $inserted_id); mysqli_stmt_execute($stmt); $row = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt)); if ($row == null) { echo ("DOESNT EXISTS"); } else { if (password_verify($inserted_password, $row['password'])) { $_SESSION['user_id'] = $row['id']; echo("SUCCESS"); } else { echo("PASSWORD_FAIL"); } } } ?&gt; </code></pre> <p><strong>signup.inc.php:</strong></p> <pre><code>&lt;?php $conn = mysqli_connect("localhost", "root", "", "users"); $params = json_decode(file_get_contents('php://input'), true); $inserted_first_name = $params['first_name']; $inserted_last_name = $params['last_name']; $inserted_dob = $params['dob']; $inserted_email = $params['email']; $inserted_account_name = $params['account_name']; $inserted_password = $params['password']; $stmt = mysqli_stmt_init($conn); if (mysqli_stmt_prepare($stmt, "SELECT * FROM user WHERE email=?;")) { mysqli_stmt_bind_param($stmt, "s", $inserted_email); mysqli_stmt_execute($stmt); if (mysqli_num_rows(mysqli_stmt_get_result($stmt)) &gt; 0) { echo("EMAIL_TAKEN"); } else { $hashed_password = password_hash($inserted_password, PASSWORD_DEFAULT); $created_id = rand(111111111, 999999999); $stmt = mysqli_stmt_init($conn); if (mysqli_stmt_prepare($stmt, "INSERT INTO user(id, first_name, last_name, dob, email, account_name, password) VALUES (?, ?, ?, ?, ?, ?, ?);")) { mysqli_stmt_bind_param($stmt, "issssss", $created_id, $inserted_first_name, $inserted_last_name, $inserted_dob, $inserted_email, $inserted_account_name, $hashed_password); $result = mysqli_stmt_execute($stmt); echo ($result ? "SUCCESS" : "FAIL"); } } mysqli_stmt_close($stmt); } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:05:54.447", "Id": "416047", "Score": "0", "body": "This code seems insecure, but you should include the browser-side code to be sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:28:10.733", "Id": "416089", "Score": "1", "body": "@200, I think a malicious actor wouldn't the intended browser-side code unmodified..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T23:04:35.137", "Id": "416206", "Score": "0", "body": "Browser code isn't very important. Though I'm using `jQuery ajax POST` request to these `php`" } ]
[ { "body": "<p>The database access information (server address, user name, password, database name) are repeatedly hard coded in each PHP file instead of having them in one common place, where they can be easily changed and configured for each run time environment (development, production, etc.)</p>\n\n<p>Additionally a (production) database should not be accessed using a root user with a blank password.</p>\n\n<p>Personally I never accessed a database in PHP using the built-in low level functions. I found using a database access library lead to less boilerplate code, they had a better readable API, and most importantly built-in security measures, that you can't forget to use. At the very least I would outsource database access into separate repository classes/modules/services.</p>\n\n<p>A common security measure for logins is to have the script return the same result for both unknown account name and wrong password, so that an attacker can't find out if a specific user has an account or not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T14:34:17.353", "Id": "215269", "ParentId": "215126", "Score": "1" } }, { "body": "<blockquote>\n<pre><code> if (mysqli_stmt_prepare($stmt, \"SELECT * FROM user WHERE account_name=? OR email=?;\")) {\n</code></pre>\n</blockquote>\n\n<p>So if I know that someone has an account with e-mail address <code>foo@example.com</code>, I can register with</p>\n\n<pre><code>{\n \"first_name\": \"\",\n \"last_name\": \"\",\n \"dob\": \"1900-01-01\",\n \"email\": \"randomNumber@example.com\",\n \"account_name\": \"foo@example.com\",\n \"password\": \"password\"\n}\n</code></pre>\n\n<p>and have a 50/50 chance of gaining control of their account?</p>\n\n<hr>\n\n<p>Why does the signup ask for an e-mail address? If it's used to send e-mail, the process seems to be missing a verification step. If it isn't used, you shouldn't ask it.</p>\n\n<p>Similarly, is there a good reason to ask for date of birth? If not, collecting it would be a violation of GDPR.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> $created_id = rand(111111111, 999999999);\n</code></pre>\n</blockquote>\n\n<p>If you scale to 30k users (including bots, tests, etc) then you can expect to see a collision. Why not rely on the database's autoincrement?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:48:31.840", "Id": "215272", "ParentId": "215126", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T09:14:15.507", "Id": "215126", "Score": "1", "Tags": [ "php" ], "Title": "Securing login PHP script" }
215126
<p>Any typing, or other improvements that you could make for this simple function?</p> <pre class="lang-py prettyprint-override"><code>def get_json_parsed_from(url: Union[str, bytes]) -&gt; Dict[Any, Any]: """Gets a JSON file and returns it parsed, or returns an empty dict if any error occurred.""" try: headers = random_headers() headers['Accept'] = 'application/json,text/*;q=0.99' return dict(requests.get(url, headers=random_headers()).json()) except BaseException: _LOGGER.exception('Failed getting JSON from %s', repr(url), exc_info=False) return {} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:06:25.623", "Id": "416071", "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": "<pre><code>headers = random_headers()\nheaders['Accept'] = 'application/json,text/*;q=0.99' \nreturn dict(requests.get(url, headers=random_headers()).json())\n</code></pre>\n\n<ul>\n<li><p>You are not using <code>headers</code>. You create it and adding the <code>Accept</code> key to it, but then passing a new call to <code>random_headers()</code> to <code>.get</code> instead of using <code>headers</code>.</p></li>\n<li><p><code>requests.get(...).json()</code> already returns a <code>dict</code>. Passing it to <code>dict(...)</code> is superfluous.</p></li>\n</ul>\n\n<p>This should be your code:</p>\n\n<pre><code>headers = random_headers()\nheaders['Accept'] = 'application/json,text/*;q=0.99' \nreturn requests.get(url, headers=headers).json()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T11:44:51.153", "Id": "416000", "Score": "0", "body": "You know what's strange? When I don't surround it with dict(), mypy complains that `warning: Returning Any from function declared to return \"Dict[Any, Any]\"`. Is this mypy being wrong? Also, if I look up the method definition of .json() in PyCharm, I see `def json(self, **kwargs: Any) -> Any`. It says it returns `Any`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T11:46:53.547", "Id": "416001", "Score": "0", "body": "Wow, good spotting on the `headers` issue! You're a freaking genius! Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T17:42:28.663", "Id": "416038", "Score": "1", "body": "It tells you that because JSON could be an object (dict), array (list) or a primitive (str, float, int, ...)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:05:38.700", "Id": "416068", "Score": "0", "body": "I updated the function from the code review question, still taking into consideration that json() can return other stuff than dict. Is that good now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T07:45:15.630", "Id": "416996", "Score": "0", "body": "@jonrsharpe so then, in the function signature I should have `-> Any:`, right?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T11:25:25.977", "Id": "215132", "ParentId": "215131", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T11:21:52.650", "Id": "215131", "Score": "-2", "Tags": [ "python", "python-3.x" ], "Title": "A function that uses requests in order get JSON content" }
215131
<p>Can I improve its typing? Is there any other improvement or pythonic change that you would do?</p> <pre class="lang-py prettyprint-override"><code>F = TypeVar('F', bound=Callable[..., Any]) # This is mostly so that I practice using a class as a decorator. class CountCalls: """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`.""" def __init__(self, func: F) -&gt; None: functools.update_wrapper(self, func) self.func = func self.num_calls: int = 0 self._logger = logging.getLogger(__name__ + '.' + self.func.__name__) self.last_return_value = None def __call__(self, *args: Any, **kwargs: Any) -&gt; Any: self.num_calls += 1 self._logger.debug(' called %s times', self.num_calls) self.last_return_value = self.func(*args, **kwargs) return self.last_return_value </code></pre> <p>Here's the decorator in action:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; @CountCalls ... def asdf(var: str): ... print(var) ... return len(var) ... &gt;&gt;&gt; asdf('Laur') Laur 4 DEBUG:__main__.asdf: called 1 times &gt;&gt;&gt; asdf('python 3') DEBUG:__main__.asdf: called 2 times python 3 8 &gt;&gt;&gt; asdf(3) DEBUG:__main__.asdf: called 3 times 3 Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "C:/Projects/Python/he/src/he/decorators.py", line 156, in __call__ self.last_return_value = self.func(*args, **kwargs) File "&lt;input&gt;", line 4, in asdf TypeError: object of type 'int' has no len() &gt;&gt;&gt; asdf.num_calls 3 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T15:29:41.867", "Id": "416026", "Score": "0", "body": "FWIW, the [`unittest.mock`](https://docs.python.org/3/library/unittest.mock.html) module may be of use for this sort of thing. Note that [the `Mock` classes are currently not typed due to issues with `mypy`](https://github.com/python/typeshed/commit/feeb4e71ef16932153a06fc26ce7a02ffdbaa2ab). You can see the previous, typed code in the link and I take a full look once I get to a computer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T15:39:22.677", "Id": "416028", "Score": "0", "body": "I updated the \"decorator in action\" part to make it more readable. I don't know what you're saying there about mock typing though." } ]
[ { "body": "<p>One thing you could try to improve the typing would be to type the method itself (although I'm not sure how well tools support it). Also, leading/trailing whitespace should be up to the logger, not the code using it.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>F = TypeVar('F', bound=Callable[..., Any])\n\n\n# This is mostly so that I practice using a class as a decorator.\nclass CountCalls:\n \"\"\"Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`.\"\"\"\n def __init__(self, func: F) -&gt; None:\n functools.update_wrapper(self, func)\n self.func = func\n self.num_calls: int = 0\n self._logger = logging.getLogger(__name__ + '.' + self.func.__name__)\n self.last_return_value = None\n\n __call__: F\n\n def __call__(self, *args: Any, **kwargs: Any) -&gt; Any:\n self.num_calls += 1\n self._logger.debug(f'called %s times', self.num_calls)\n self.last_return_value = self.func(*args, **kwargs)\n return self.last_return_value\n</code></pre>\n\n<p>As for the code itself, you could make a callback-based API.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>F = TypeVar('F', bound=Callable[..., Any])\n\n\n# This is mostly so that I practice using a class as a decorator.\nclass CountCalls:\n \"\"\"Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`.\"\"\"\n def __init__(self, func: F, callback: Optional[Callable[[int, Tuple[Any], Dict[str, Any]], Any]] = None) -&gt; None:\n if callback is None:\n logger = logging.getLogger(__name__ + '.' + self.func.__name__)\n\n def callback(num_calls: int, args: Tuple[Any], kwargs: Dict[str, Any]):\n self._logger.debug(f'called %s times', self.num_calls)\n\n functools.update_wrapper(self, func)\n self.func = func \n self.callback = callback\n self.num_calls: int = 0\n self.last_return_value = None\n\n __call__: F\n\n def __call__(self, *args: Any, **kwargs: Any) -&gt; Any:\n self.num_calls += 1\n self.callback(self.num_calls, args, kwargs)\n self.last_return_value = self.func(*args, **kwargs)\n return self.last_return_value\n</code></pre>\n\n<p>Or with the number of calls tracked in the callback (for increased flexibility):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>F = TypeVar('F', bound=Callable[..., Any])\n\n\n# This is mostly so that I practice using a class as a decorator.\nclass CountCalls:\n \"\"\"Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`.\"\"\"\n def __init__(self, func: F, callback: Optional[Callable[[int, Tuple[Any], Dict[str, Any]], Any]] = None) -&gt; None:\n if callback is None:\n logger = logging.getLogger(__name__ + '.' + self.func.__name__)\n num_calls: int = 0\n\n def callback(args: Tuple[Any], kwargs: Dict[str, Any]):\n nonlocal num_calls # Not sure if this is necessary or not\n num_calls += 1\n self._logger.debug(f'called %s times', self.num_calls)\n\n functools.update_wrapper(self, func)\n self.func = func \n self.callback = callback\n self.last_return_value = None\n\n __call__: F\n\n def __call__(self, *args: Any, **kwargs: Any) -&gt; Any:\n self.callback(self.num_calls, args, kwargs)\n self.last_return_value = self.func(*args, **kwargs)\n return self.last_return_value\n</code></pre>\n\n<p>Earlier, to pass a keyword argument while using it, <code>@functools.partial(CountCalls, callback=callback)</code> was needed. Now, <code>@CountCalls(callback=callback)</code> can be used instead.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>F = TypeVar('F', bound=Callable[..., Any])\n\n\n# This is mostly so that I practice using a class as a decorator.\nclass CountCalls:\n \"\"\"Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`.\"\"\"\n def __init__(self, func: F = None, callback: Optional[Callable[[int, Tuple[Any], Dict[str, Any]], Any]] = None) -&gt; None:\n if callback is None:\n logger = logging.getLogger(__name__ + '.' + self.func.__name__)\n num_calls: int = 0\n\n def callback(args: Tuple[Any], kwargs: Dict[str, Any]):\n nonlocal num_calls # Not sure if this is necessary or not\n num_calls += 1\n self._logger.debug(f'called %s times', self.num_calls)\n\n if func is None:\n return functools.partial(CountCalls, callback=callback)\n\n functools.update_wrapper(self, func)\n self.func = func \n self.callback = callback\n self.last_return_value = None\n\n __call__: F\n\n def __call__(self, *args: Any, **kwargs: Any) -&gt; Any:\n self.callback(self.num_calls, args, kwargs)\n self.last_return_value = self.func(*args, **kwargs)\n return self.last_return_value\n</code></pre>\n\n<p>(Note: none of this code has been tested.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:45:36.443", "Id": "416056", "Score": "1", "body": "[Using `%`-formatting is the default way for the `logging` module](https://docs.python.org/3/howto/logging-cookbook.html#using-particular-formatting-styles-throughout-your-application) (and it is not going to change due to backward compatibility). It is a bit special in that regard. One can change it to use parts of the `str.format` syntax, but not with keyword arguments. Using `f-string`s here is actually a potentially bad idea, because normally the string formatting is only performed if the message is of the right logging level, which means a lot when not having to do it for debug messages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T21:58:08.600", "Id": "416067", "Score": "1", "body": "Typing the `__call__` method itself is genius. Regarding f-strings in logging, I have to agree with @Graipher that string interpolation is better suited for the logging module - that's why I used it in the first place.\n\nI'm starting to understand now what's with the callback part that you proposed, and that's genius as well; if I understand correctly, it allows changing the functionality of the decorator by supplying an optional function... I'll go into test mode for that part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:05:53.053", "Id": "416070", "Score": "0", "body": "@LaurențiuAndronache It would be nice if Python supported additional types of `TypeVar`s for when tricks like this don't work (such as with typing the callback), but oh well... Also, with the callback API, I'll add a version where the number of calls is tracked by the callback for increased flexibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T22:25:58.620", "Id": "416959", "Score": "0", "body": "note that in both examples with callbacks, you can't actually supply a callback to the decorator. `TypeError: b() takes 0 positional arguments but 1 was given`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T22:33:30.273", "Id": "416960", "Score": "0", "body": "@LaurențiuAndronache Interesting.... What is `b`? The decorated function or the callback? What's its signature? Does the error occur when defining the decorated function or when calling it? How are you calling the decorator? I think `functools.partial` with a keyword argument (`callback`) is necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T07:38:00.253", "Id": "416995", "Score": "0", "body": "I wanted to include more code, but it shows up badly as a comment... I was decorating like this:\n```python\ndef b():\n pass\n```\n\nand then: \n\n```\n@CountCalls(b)\ndef c():\n pass\n```\n\nwhich I understand why it doesn't work `__init__` would have to optionally return a decorator when it is called with args, in order to be usable with args..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T11:26:36.403", "Id": "417009", "Score": "0", "body": "What you currently have to do is to use `functools.partial(CountCalls, callback=b)` as a decorator. I'll edit the code to make it so that if only a callback is specified (via a keyword argument), it will return the `partial`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T16:57:35.990", "Id": "215146", "ParentId": "215135", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T12:03:17.923", "Id": "215135", "Score": "2", "Tags": [ "python", "python-3.x", "meta-programming" ], "Title": "A simple decorator written as a class, which counts how many times a function has been called" }
215135
<p>Kata: <a href="https://www.codewars.com/kata/linked-lists-remove-duplicates/train/python" rel="nofollow noreferrer">https://www.codewars.com/kata/linked-lists-remove-duplicates/train/python</a> </p> <h2>Description</h2> <blockquote> <p>Write a RemoveDuplicates() function which takes a list sorted in increasing order and deletes any duplicate nodes from the list. Ideally, the list should only be traversed once. The head of the resulting list should be returned.</p> <pre><code>var list = 1 -&gt; 2 -&gt; 3 -&gt; 3 -&gt; 4 -&gt; 4 -&gt; 5 -&gt; null removeDuplicates(list) === 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; null </code></pre> <p>If the passed in list is null/None/nil, simply return null.</p> <p>Note: Your solution is expected to work on long lists. Recursive solutions may fail due to stack size limitations. </p> </blockquote> <h2>My Solution</h2> <pre class="lang-py prettyprint-override"><code>class Node(object): def __init__(self, data, nxt=None): self.data = data self.next = nxt def remove_duplicates(head): node = Node(None, head) st = set() while node.next: if node.next.data in st: tmp = node.next node.next = node.next.next del tmp else: st.add(node.next.data) node = node.next return head </code></pre> <hr> <p>I am interested in performance and adhering to best practices.</p>
[]
[ { "body": "<p>The space complexity of your solution is <span class=\"math-container\">\\$O(n)\\$</span>. What if I told you that given the constraints in the question, you could solve this problem in <span class=\"math-container\">\\$O(1)\\$</span> space?</p>\n\n<p>Consider that you receive an already sorted list. This implies that all duplicates <strong>must be</strong> adjacent. This in turn means that for deduplicating these, you do not need to keep track of which values you already encountered.</p>\n\n<p>Note that <code>del</code> is not necessary here. You never use <code>tmp</code> aside from assigning <code>node.next</code> to it in any case. <code>del</code> is not clearing the memory allocated to the variable (or the object it refers to), it only destroys the variable itself, the object is unaffected. As such it does <em>not</em> have any effect on the garbage-collection that python performs...</p>\n\n<p>The following should already work just fine:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def remove_duplicates(head):\n node = Node(None, head)\n while node.next:\n if node.next.data == node.data:\n node.next = node.next.next\n else:\n node = node.next\n return head\n</code></pre>\n\n<hr>\n\n<p>Small sidenote: I really like the hack you used to ensure that you handle the <code>head is None</code> case, but you should be aware that it is just a hack. The cleaner solution to this would be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def remove_duplicates(head):\n if not head:\n return head\n node = head\n while node.next:\n # Rest of the code...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:04:23.107", "Id": "416045", "Score": "1", "body": "Surely `if head is None` would be better than `if not head`, no? It may or may not be faster, depending on where the bottlenecks are (it's usually faster) _and_ it more clearly conveys the intent of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:39:56.673", "Id": "416052", "Score": "0", "body": "Thanks for this, yours is really neat. It still looks like it's \\$O(n)\\$ to me as you have to iterate through the list?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:40:49.783", "Id": "416054", "Score": "0", "body": "I find special cases aesthetically unappealing which is why I used the \"hack\"; is that considered bad form?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:54:57.380", "Id": "416058", "Score": "2", "body": "it is in fact O(n) in **time**, but O(1) in **space**. Special cases are something I prefer to handle \"separately\". YMMV, but as soon as special cases become harder to reconciliate with the core algorithm, it makes more and more sense to handle them in dedicated branches" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T14:49:02.457", "Id": "215142", "ParentId": "215140", "Score": "8" } } ]
{ "AcceptedAnswerId": "215142", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T14:26:07.990", "Id": "215140", "Score": "3", "Tags": [ "python", "performance", "beginner", "programming-challenge", "linked-list" ], "Title": "(Codewars) Linked Lists - Remove Duplicates" }
215140
<p>I was given the task to download files for a FTP server. The download should be fairly fast. 15 parallel connections can be used.</p> <p>I have used <code>FluentFTP</code> as the underlying library taking care of the technical details of FTP.</p> <p>Here is the FTP client and tests below.</p> <pre><code>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using FluentFTP; using log4net; namespace FTPSynchronizator { public class ParallelFtpClient : IDisposable { private readonly ILog _logger = LogManager.GetLogger(typeof(MeteologicaFtpSyncer).FullName); private readonly int _maxConcurentConnections; private readonly Func&lt;IFtpClient&gt; _factory; private readonly List&lt;IFtpClient&gt; _ftpClients; public ParallelFtpClient(int maxConcurentConnections, Func&lt;IFtpClient&gt; factory) { _maxConcurentConnections = maxConcurentConnections; _factory = factory; _ftpClients = new List&lt;IFtpClient&gt;(); } public void Connect() { var tasks = new List&lt;Task&gt;(); for (int i = 0; i &lt; _maxConcurentConnections; i++) { var ftpClient = _factory(); _ftpClients.Add(ftpClient); var connectTask = ftpClient.ConnectAsync(); tasks.Add(connectTask); } Task.WaitAll(tasks.ToArray()); } public void Disconnect() { var tasks = _ftpClients .Select(x =&gt; x.DisconnectAsync()) .ToArray(); Task.WaitAll(tasks); } public List&lt;string&gt; ListFilesInDirectories(IEnumerable&lt;string&gt; directories) { var items = new ConcurrentBag&lt;FtpListItem&gt;(); var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients); Parallel.ForEach(directories, new ParallelOptions() {MaxDegreeOfParallelism = _maxConcurentConnections}, (path) =&gt; { IFtpClient client; clients.TryDequeue(out client); var listing = client.GetListing(path); foreach (var item in listing) { items.Add(item); } clients.Enqueue(client); }); var list = items .Where(x =&gt; x.Type == FtpFileSystemObjectType.File) .Select(x =&gt; x.FullName) .ToList(); return list; } public List&lt;string&gt; DownloadFilesParallel(IEnumerable&lt;(string,string)&gt; ftpPathLocalPathPairs, out List&lt;(string, string)&gt; failedDownloads) { var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients); var downloadedFiles = new ConcurrentBag&lt;string&gt;(); var failedDownloadsBag = new ConcurrentBag&lt;(string,string)&gt;(); Parallel.ForEach(ftpPathLocalPathPairs, new ParallelOptions() {MaxDegreeOfParallelism = _maxConcurentConnections}, (ftpPathLocalPathPair) =&gt; { IFtpClient client; clients.TryDequeue(out client); var ftpFilePath = ftpPathLocalPathPair.Item1; var destinationFilePath = ftpPathLocalPathPair.Item2; _logger.Debug($"Downloading {ftpFilePath} to {destinationFilePath}..."); try { var memoryStream = new MemoryStream(); client.Download(memoryStream, ftpFilePath); memoryStream.Position = 0; string destinationDirectory = Path.GetDirectoryName(destinationFilePath); if (!Directory.Exists(destinationDirectory)) { _logger.Info($"Creating new directory {destinationDirectory}"); Directory.CreateDirectory(destinationDirectory); } File.WriteAllBytes(destinationFilePath, memoryStream.ToArray()); downloadedFiles.Add(destinationFilePath); } catch (Exception e) { _logger.Warn($"An unhandled excetpion occured while downloading file {ftpFilePath}", e); failedDownloadsBag.Add(ftpPathLocalPathPair); } clients.Enqueue(client); } ); failedDownloads = failedDownloadsBag.ToList(); return downloadedFiles.ToList(); } public List&lt;string&gt; ListNonArchiveDirectoresWithFiles(string root) { var directoriesWithFiles = new List&lt;string&gt;(); var directoiresToQuery = new Queue&lt;string&gt;(); var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients); directoiresToQuery.Enqueue(root); var tasks = new List&lt;Task&lt;Result&gt;&gt;(); while (directoiresToQuery.Any() || tasks.Any()) { while (clients.Any() &amp;&amp; directoiresToQuery.Any()) { var path = directoiresToQuery.Dequeue(); IFtpClient client; clients.TryDequeue(out client); var task = Task.Run(() =&gt; { var childItems = client.GetListing(path); clients.Enqueue(client); return new Result() { FullName = path, Children = childItems }; }); tasks.Add(task); } var array = tasks.ToArray(); var finishedTaskIndex = Task.WaitAny(array); var finishedTask = array[finishedTaskIndex]; var finishedTaskResult = finishedTask.Result; if (finishedTaskResult.Children.Any(i =&gt; i.Type == FtpFileSystemObjectType.File)) { directoriesWithFiles.Add(finishedTaskResult.FullName); } var subdirectoriesToQuery = finishedTaskResult .Children .Where(x =&gt; x.Type == FtpFileSystemObjectType.Directory) .Where(x =&gt; x.Name != "Archive") .Select(x =&gt; x.FullName); foreach (var subdirectoryToQuery in subdirectoriesToQuery) { directoiresToQuery.Enqueue(subdirectoryToQuery); } tasks = array .Except(new[] {finishedTask}) .ToList(); } return directoriesWithFiles; } public void Dispose() { foreach (var ftpClient in _ftpClients) { ftpClient.Dispose(); } } } public class Result { public string FullName { get; set; } public FtpListItem[] Children { get; set; } } } </code></pre> <p>Tests and stubs:</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Linq; using FluentFTP; using NUnit.Framework; using System.Globalization; using System.Net; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Tests { [TestFixture] public class ParallelFtpClientTests { [Test] public static void Connect_ConstructsCorrectNumberOfClientsAndConnectsThem() { // arrage int factoryInvokedCount = 0; List&lt;IFtpClient&gt; clientsCreatedByFatory = new List&lt;IFtpClient&gt;(); Func&lt;IFtpClient&gt; factory = () =&gt; { factoryInvokedCount++; var client = new StubFtpClient(); clientsCreatedByFatory.Add(client); return client; }; var sut = new ParallelFtpClient(10, factory); // act sut.Connect(); // assert Assert.AreEqual(10, factoryInvokedCount); Assert.IsTrue(clientsCreatedByFatory.All(x =&gt; x.IsConnected)); } [Test] public static void Disconnect_DisconnectsAllClients() { // arrage List&lt;StubFtpClient&gt; clientsCreatedByFatory = new List&lt;StubFtpClient&gt;(); Func&lt;IFtpClient&gt; factory = () =&gt; { var client = new StubFtpClient(); clientsCreatedByFatory.Add(client); return client; }; var sut = new ParallelFtpClient(10, factory); // act sut.Connect(); sut.Disconnect(); // assert Assert.IsTrue(clientsCreatedByFatory.All(x =&gt; x.IsDisconected)); } [Test] public static void Dispose_DisconnectsAllClients() { // arrage List&lt;StubFtpClient&gt; clientsCreatedByFatory = new List&lt;StubFtpClient&gt;(); Func&lt;IFtpClient&gt; factory = () =&gt; { var client = new StubFtpClient(); clientsCreatedByFatory.Add(client); return client; }; var sut = new ParallelFtpClient(10, factory); // act sut.Connect(); sut.Dispose(); // assert Assert.IsTrue(clientsCreatedByFatory.All(x =&gt; x.IsDisposed)); } [Test] public static void ListFilesInDirectories_EmptyInput_ReturnsEmptyList() { // arrange var directories = new string[0]; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListFilesInDirectories(directories); // assert Assert.IsNotNull(result); Assert.IsEmpty(result); } [Test] public static void ListFilesInDirectories_SingleDirectory_ReturnsFilesForDirectory() { // arrange var directories = new string[]{"dir1"}; DateTime lastModifiedTime = DateTime.Now; var map = new Dictionary&lt;string, FtpListItem[]&gt;() { { "dir1", new [] { new FtpListItem("dummy", "file1", 0, false, ref lastModifiedTime){FullName = "/root/file1"}, new FtpListItem("dummy", "file2", 0, false, ref lastModifiedTime){FullName = "/root/file2"}, } } }; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListFilesInDirectories(directories); // assert Assert.AreEqual(2, result.Count); CollectionAssert.Contains(result, "/root/file1"); CollectionAssert.Contains(result, "/root/file2"); } [Test] public static void ListFilesInDirectories_MultipleDirectories_ReturnsFilesForAllDirectories() { // arrange var directories = new string[]{"dir1", "dir2"}; DateTime lastModifiedTime = DateTime.Now; var map = new Dictionary&lt;string, FtpListItem[]&gt;() { { "dir1", new [] { new FtpListItem("dummy", "file1", 0, false, ref lastModifiedTime){FullName = "/root/file1"}, new FtpListItem("dummy", "file2", 0, false, ref lastModifiedTime){FullName = "/root/file2"}, } }, { "dir2", new [] { new FtpListItem("dummy", "file3", 0, false, ref lastModifiedTime){FullName = "/root/file3"}, new FtpListItem("dummy", "file4", 0, false, ref lastModifiedTime){FullName = "/root/file4"}, } }, }; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListFilesInDirectories(directories); // assert Assert.AreEqual(4, result.Count); CollectionAssert.Contains(result, "/root/file1"); CollectionAssert.Contains(result, "/root/file2"); CollectionAssert.Contains(result, "/root/file3"); CollectionAssert.Contains(result, "/root/file4"); } [Test] public static void ListFilesInDirectories_FilesCanNotBeListed_ExceptionIsThrown() { // arrange var directories = new string[]{"this_dir_can_not_be_found_by_ftp_server"}; var map = new Dictionary&lt;string, FtpListItem[]&gt;(); // passing empty map to stub so no directorise can be listed Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act Assert.Throws(typeof(AggregateException), () =&gt; sut.ListFilesInDirectories(directories)); } [Test] public static void DownloadFilesParallel_EmptyInputList_DoesNothing() { // arrange var files = new (string, string)[]{}; List&lt;(string, string)&gt; failedDownloads; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var downloadedFiles = sut.DownloadFilesParallel(files, out failedDownloads); // assert Assert.IsNotNull(downloadedFiles); Assert.IsEmpty(downloadedFiles); } [Test] public static void DownloadFilesParallel_SingleFile_DownloadsFile() { // arrange Directory.CreateDirectory("temp"); var files = new []{("/ftp/file1", "temp/file1")}; List&lt;(string, string)&gt; failedDownloads; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var downloadedFiles = sut.DownloadFilesParallel(files, out failedDownloads); // assert FileAssert.Exists("temp/file1"); Assert.IsTrue(downloadedFiles.Single() == @"temp/file1"); } [Test] public static void DownloadFilesParallel_MultipleFiles_DownloadsAllFiles() { // arrange Directory.CreateDirectory("temp"); var files = new []{("/ftp/file1", "temp/file1"), ("/ftp/file2", "temp/file2")}; List&lt;(string, string)&gt; failedDownloads; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var downloadedFiles = sut.DownloadFilesParallel(files, out failedDownloads); // assert FileAssert.Exists("temp/file1"); FileAssert.Exists("temp/file2"); Assert.AreEqual(2, downloadedFiles.Count); Assert.IsTrue(downloadedFiles.Any(x =&gt; x == @"temp/file1")); Assert.IsTrue(downloadedFiles.Any(x =&gt; x == @"temp/file2")); } [Test] public static void DownloadFilesParallel_ExceptionDuringDownload_LocalFileShouldNotBeCreatedAndFailedDownloadsAreReturned() { // arrange Directory.CreateDirectory("temp"); var files = new []{("/ftp/file1", "temp/file1")}; List&lt;(string, string)&gt; failedDownloads; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClientThrowsAfterCreatingFile(); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var downloadedFiles = sut.DownloadFilesParallel(files, out failedDownloads); // assert Assert.IsFalse(File.Exists("temp/file1")); Assert.AreEqual(0, downloadedFiles.Count); Assert.AreEqual(1, failedDownloads.Count); Assert.AreEqual(("/ftp/file1", "temp/file1"), failedDownloads.First()); } [Test] public static void DownloadFilesParallel_DownloadingToNonExistingDirectory_NewDirectoryIsCreatedAndFileIsDownloaded() { // arrange Directory.CreateDirectory("temp"); var files = new []{("/ftp/newdir/file1", "temp/newdir/file1")}; List&lt;(string, string)&gt; failedDownloads; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var downloadedFiles = sut.DownloadFilesParallel(files, out failedDownloads); // assert FileAssert.Exists("temp/newdir/file1"); Assert.AreEqual(1, downloadedFiles.Count); } [Test] public static void ListNonArchiveDirectoresWithFiles_ThereAreNoDirectoreis_ReturnsEmptyList() { // arange var map = new Dictionary&lt;string, FtpListItem[]&gt;() { {"/root", new FtpListItem[]{}}, }; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListNonArchiveDirectoresWithFiles("/root"); // assert Assert.IsEmpty(result); } [Test] public static void ListNonArchiveDirectoresWithFiles_RootDirectoryContainsFiles_ResultContainsRoot() { // arange DateTime lastModifiedTime = DateTime.Now; var map = new Dictionary&lt;string, FtpListItem[]&gt;() { { "/root", new [] { new FtpListItem("dummy", "file", 0, false, ref lastModifiedTime){FullName = "/root/file"} } }, }; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListNonArchiveDirectoresWithFiles("/root"); // assert Assert.AreEqual(1, result.Count); Assert.IsTrue(result.Any(x =&gt; x == "/root")); } [Test] public static void ListNonArchiveDirectoresWithFiles_RootDirectoryContainsSubdirectoriesWithFiles_ResultContainsAllDirsWithFiles() { // arange DateTime lastModifiedTime = DateTime.Now; var map = new Dictionary&lt;string, FtpListItem[]&gt;() { { "/root", new [] { new FtpListItem("dummy", "file", 0, false, ref lastModifiedTime){FullName = "/root/file"}, new FtpListItem("", "subdir", 0, true, ref lastModifiedTime){FullName = "/root/subdir"}, } }, { "/root/subdir", new [] { new FtpListItem("dummy", "file2", 0, false, ref lastModifiedTime){FullName = "/root/subdir/file2"}, } } }; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListNonArchiveDirectoresWithFiles("/root"); // assert Assert.AreEqual(2, result.Count); Assert.IsTrue(result.Any(x =&gt; x == "/root")); Assert.IsTrue(result.Any(x =&gt; x == "/root/subdir")); } [Test] public static void ListNonArchiveDirectoresWithFiles_ArchiveDirectoryIsPresent_ArchiveDirectoryIsNotQueried() { // arange DateTime lastModifiedTime = DateTime.Now; var map = new Dictionary&lt;string, FtpListItem[]&gt;() { { "/root", new [] { new FtpListItem("dummy", "file", 0, false, ref lastModifiedTime){FullName = "/root/file"}, new FtpListItem("", "Archive", 0, true, ref lastModifiedTime){FullName = "/root/Archive"}, } }, { "/root/Archive", new [] { new FtpListItem("dummy", "file2", 0, false, ref lastModifiedTime){FullName = "/root/subdir/file2"}, null } } }; Func&lt;IFtpClient&gt; factory = () =&gt; new StubFtpClient(map); var sut = new ParallelFtpClient(10, factory); sut.Connect(); // act var result = sut.ListNonArchiveDirectoresWithFiles("/root"); // assert Assert.AreEqual(1, result.Count); Assert.IsTrue(result.Any(x =&gt; x == "/root")); } [TearDown] public static void RemoveTempFolder() { if (Directory.Exists("temp")) { Directory.Delete("temp", true); } } } public class StubFtpClient : IFtpClient { private Dictionary&lt;string, FtpListItem[]&gt; _dirFilesMap; private bool _connected = false; private bool _wasDisconected = false; private bool _isDisposed = false; public StubFtpClient() { _dirFilesMap = new Dictionary&lt;string, FtpListItem[]&gt;(); } public StubFtpClient(Dictionary&lt;string, FtpListItem[]&gt; dirFilesMap) { _dirFilesMap = dirFilesMap; } public void Dispose() { _isDisposed = true; } public FtpReply Execute(string command) { throw new NotImplementedException(); } public FtpReply GetReply() { throw new NotImplementedException(); } public virtual void Connect() { _connected = true; } public void Disconnect() { _wasDisconected = true; } public bool HasFeature(FtpCapability cap) { throw new NotImplementedException(); } public void DisableUTF8() { throw new NotImplementedException(); } public Task&lt;FtpReply&gt; ExecuteAsync(string command) { throw new NotImplementedException(); } public Task&lt;FtpReply&gt; GetReplyAsync() { throw new NotImplementedException(); } public Task ConnectAsync() { Connect(); return Task.CompletedTask; } public Task DisconnectAsync() { _wasDisconected = true; return Task.CompletedTask; } public void DeleteFile(string path) { throw new NotImplementedException(); } public void DeleteDirectory(string path) { throw new NotImplementedException(); } public void DeleteDirectory(string path, FtpListOption options) { throw new NotImplementedException(); } public bool DirectoryExists(string path) { throw new NotImplementedException(); } public bool FileExists(string path) { throw new NotImplementedException(); } public void CreateDirectory(string path) { throw new NotImplementedException(); } public void CreateDirectory(string path, bool force) { throw new NotImplementedException(); } public void Rename(string path, string dest) { throw new NotImplementedException(); } public bool MoveFile(string path, string dest, FtpExists existsMode = FtpExists.Overwrite) { throw new NotImplementedException(); } public bool MoveDirectory(string path, string dest, FtpExists existsMode = FtpExists.Overwrite) { throw new NotImplementedException(); } public void SetFilePermissions(string path, int permissions) { throw new NotImplementedException(); } public void Chmod(string path, int permissions) { throw new NotImplementedException(); } public void SetFilePermissions(string path, FtpPermission owner, FtpPermission @group, FtpPermission other) { throw new NotImplementedException(); } public void Chmod(string path, FtpPermission owner, FtpPermission @group, FtpPermission other) { throw new NotImplementedException(); } public FtpListItem GetFilePermissions(string path) { throw new NotImplementedException(); } public int GetChmod(string path) { throw new NotImplementedException(); } public FtpListItem DereferenceLink(FtpListItem item) { throw new NotImplementedException(); } public FtpListItem DereferenceLink(FtpListItem item, int recMax) { throw new NotImplementedException(); } public void SetWorkingDirectory(string path) { throw new NotImplementedException(); } public string GetWorkingDirectory() { throw new NotImplementedException(); } public long GetFileSize(string path) { throw new NotImplementedException(); } public DateTime GetModifiedTime(string path, FtpDate type = FtpDate.Original) { throw new NotImplementedException(); } public void SetModifiedTime(string path, DateTime date, FtpDate type = FtpDate.Original) { throw new NotImplementedException(); } public Task DeleteFileAsync(string path) { throw new NotImplementedException(); } public Task DeleteDirectoryAsync(string path) { throw new NotImplementedException(); } public Task DeleteDirectoryAsync(string path, FtpListOption options) { throw new NotImplementedException(); } public Task&lt;bool&gt; DirectoryExistsAsync(string path) { throw new NotImplementedException(); } public Task&lt;bool&gt; FileExistsAsync(string path) { throw new NotImplementedException(); } public Task CreateDirectoryAsync(string path, bool force) { throw new NotImplementedException(); } public Task CreateDirectoryAsync(string path) { throw new NotImplementedException(); } public Task RenameAsync(string path, string dest) { throw new NotImplementedException(); } public Task&lt;bool&gt; MoveFileAsync(string path, string dest, FtpExists existsMode = FtpExists.Overwrite) { throw new NotImplementedException(); } public Task&lt;bool&gt; MoveDirectoryAsync(string path, string dest, FtpExists existsMode = FtpExists.Overwrite) { throw new NotImplementedException(); } public Task SetFilePermissionsAsync(string path, int permissions) { throw new NotImplementedException(); } public Task ChmodAsync(string path, int permissions) { throw new NotImplementedException(); } public Task SetFilePermissionsAsync(string path, FtpPermission owner, FtpPermission @group, FtpPermission other) { throw new NotImplementedException(); } public Task ChmodAsync(string path, FtpPermission owner, FtpPermission @group, FtpPermission other) { throw new NotImplementedException(); } public Task&lt;FtpListItem&gt; GetFilePermissionsAsync(string path) { throw new NotImplementedException(); } public Task&lt;int&gt; GetChmodAsync(string path) { throw new NotImplementedException(); } public Task&lt;FtpListItem&gt; DereferenceLinkAsync(FtpListItem item, int recMax) { throw new NotImplementedException(); } public Task&lt;FtpListItem&gt; DereferenceLinkAsync(FtpListItem item) { throw new NotImplementedException(); } public Task SetWorkingDirectoryAsync(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetWorkingDirectoryAsync() { throw new NotImplementedException(); } public Task&lt;long&gt; GetFileSizeAsync(string path) { throw new NotImplementedException(); } public Task&lt;DateTime&gt; GetModifiedTimeAsync(string path, FtpDate type = FtpDate.Original) { throw new NotImplementedException(); } public Task SetModifiedTimeAsync(string path, DateTime date, FtpDate type = FtpDate.Original) { throw new NotImplementedException(); } public FtpListItem GetObjectInfo(string path, bool dateModified = false) { throw new NotImplementedException(); } public FtpListItem[] GetListing() { throw new NotImplementedException(); } public FtpListItem[] GetListing(string path) { if (!_connected) { throw new InvalidOperationException("you didn't connect yet!"); } return _dirFilesMap[path]; } public FtpListItem[] GetListing(string path, FtpListOption options) { throw new NotImplementedException(); } public string[] GetNameListing() { throw new NotImplementedException(); } public string[] GetNameListing(string path) { throw new NotImplementedException(); } public Task&lt;FtpListItem&gt; GetObjectInfoAsync(string path, bool dateModified = false) { throw new NotImplementedException(); } public Task&lt;FtpListItem[]&gt; GetListingAsync(string path, FtpListOption options) { throw new NotImplementedException(); } public Task&lt;FtpListItem[]&gt; GetListingAsync(string path) { throw new NotImplementedException(); } public Task&lt;FtpListItem[]&gt; GetListingAsync() { throw new NotImplementedException(); } public Task&lt;string[]&gt; GetNameListingAsync(string path) { throw new NotImplementedException(); } public Task&lt;string[]&gt; GetNameListingAsync() { throw new NotImplementedException(); } public Stream OpenRead(string path) { throw new NotImplementedException(); } public Stream OpenRead(string path, FtpDataType type) { throw new NotImplementedException(); } public Stream OpenRead(string path, FtpDataType type, bool checkIfFileExists) { throw new NotImplementedException(); } public Stream OpenRead(string path, FtpDataType type, long restart) { throw new NotImplementedException(); } public Stream OpenRead(string path, long restart) { throw new NotImplementedException(); } public Stream OpenRead(string path, long restart, bool checkIfFileExists) { throw new NotImplementedException(); } public Stream OpenRead(string path, FtpDataType type, long restart, bool checkIfFileExists) { throw new NotImplementedException(); } public Stream OpenWrite(string path) { throw new NotImplementedException(); } public Stream OpenWrite(string path, FtpDataType type) { throw new NotImplementedException(); } public Stream OpenWrite(string path, FtpDataType type, bool checkIfFileExists) { throw new NotImplementedException(); } public Stream OpenAppend(string path) { throw new NotImplementedException(); } public Stream OpenAppend(string path, FtpDataType type) { throw new NotImplementedException(); } public Stream OpenAppend(string path, FtpDataType type, bool checkIfFileExists) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenReadAsync(string path, FtpDataType type, long restart, bool checkIfFileExists) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenReadAsync(string path, FtpDataType type, long restart) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenReadAsync(string path, FtpDataType type) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenReadAsync(string path, long restart) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenReadAsync(string path) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenWriteAsync(string path, FtpDataType type, bool checkIfFileExists) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenWriteAsync(string path, FtpDataType type) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenWriteAsync(string path) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenAppendAsync(string path, FtpDataType type, bool checkIfFileExists) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenAppendAsync(string path, FtpDataType type) { throw new NotImplementedException(); } public Task&lt;Stream&gt; OpenAppendAsync(string path) { throw new NotImplementedException(); } public int UploadFiles(IEnumerable&lt;string&gt; localPaths, string remoteDir, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None) { throw new NotImplementedException(); } public int UploadFiles(IEnumerable&lt;FileInfo&gt; localFiles, string remoteDir, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None) { throw new NotImplementedException(); } public int DownloadFiles(string localDir, IEnumerable&lt;string&gt; remotePaths, bool overwrite = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None) { throw new NotImplementedException(); } public bool UploadFile(string localPath, string remotePath, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = false, FtpVerify verifyOptions = FtpVerify.None, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public bool Upload(Stream fileStream, string remotePath, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = false, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public bool Upload(byte[] fileData, string remotePath, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = false, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public bool DownloadFile(string localPath, string remotePath, bool overwrite = true, FtpVerify verifyOptions = FtpVerify.None, IProgress&lt;double&gt; progress = null) { File.WriteAllText(localPath, "dummy"); return true; } public virtual bool Download(Stream outStream, string remotePath, IProgress&lt;double&gt; progress = null) { outStream.Write(new byte[]{1,2,10,100}, 0, 4); return true; } public bool Download(out byte[] outBytes, string remotePath, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public Task&lt;int&gt; UploadFilesAsync(IEnumerable&lt;string&gt; localPaths, string remoteDir, FtpExists existsMode, bool createRemoteDir, FtpVerify verifyOptions, FtpError errorHandling, CancellationToken token) { throw new NotImplementedException(); } public Task&lt;int&gt; UploadFilesAsync(IEnumerable&lt;string&gt; localPaths, string remoteDir, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None) { throw new NotImplementedException(); } public Task&lt;int&gt; DownloadFilesAsync(string localDir, IEnumerable&lt;string&gt; remotePaths, bool overwrite, FtpVerify verifyOptions, FtpError errorHandling, CancellationToken token) { throw new NotImplementedException(); } public Task&lt;int&gt; DownloadFilesAsync(string localDir, IEnumerable&lt;string&gt; remotePaths, bool overwrite = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None) { throw new NotImplementedException(); } public Task&lt;bool&gt; UploadFileAsync(string localPath, string remotePath, FtpExists existsMode, bool createRemoteDir, FtpVerify verifyOptions, CancellationToken token, IProgress&lt;double&gt; progress) { throw new NotImplementedException(); } public Task&lt;bool&gt; UploadFileAsync(string localPath, string remotePath, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = false, FtpVerify verifyOptions = FtpVerify.None) { throw new NotImplementedException(); } public Task&lt;bool&gt; UploadAsync(Stream fileStream, string remotePath, FtpExists existsMode, bool createRemoteDir, CancellationToken token, IProgress&lt;double&gt; progress) { throw new NotImplementedException(); } public Task&lt;bool&gt; UploadAsync(byte[] fileData, string remotePath, FtpExists existsMode, bool createRemoteDir, CancellationToken token, IProgress&lt;double&gt; progress) { throw new NotImplementedException(); } public Task&lt;bool&gt; UploadAsync(Stream fileStream, string remotePath, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = false) { throw new NotImplementedException(); } public Task&lt;bool&gt; UploadAsync(byte[] fileData, string remotePath, FtpExists existsMode = FtpExists.Overwrite, bool createRemoteDir = false) { throw new NotImplementedException(); } public Task&lt;bool&gt; DownloadFileAsync(string localPath, string remotePath, bool overwrite, FtpVerify verifyOptions, CancellationToken token, IProgress&lt;double&gt; progress) { throw new NotImplementedException(); } public Task&lt;bool&gt; DownloadFileAsync(string localPath, string remotePath, bool overwrite = true, FtpVerify verifyOptions = FtpVerify.None, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public Task&lt;bool&gt; DownloadAsync(Stream outStream, string remotePath, CancellationToken token, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public Task&lt;bool&gt; DownloadAsync(Stream outStream, string remotePath) { throw new NotImplementedException(); } public Task&lt;byte[]&gt; DownloadAsync(string remotePath, CancellationToken token, IProgress&lt;double&gt; progress = null) { throw new NotImplementedException(); } public Task&lt;byte[]&gt; DownloadAsync(string remotePath) { throw new NotImplementedException(); } public FtpHashAlgorithm GetHashAlgorithm() { throw new NotImplementedException(); } public void SetHashAlgorithm(FtpHashAlgorithm type) { throw new NotImplementedException(); } public FtpHash GetHash(string path) { throw new NotImplementedException(); } public FtpHash GetChecksum(string path) { throw new NotImplementedException(); } public string GetMD5(string path) { throw new NotImplementedException(); } public string GetXCRC(string path) { throw new NotImplementedException(); } public string GetXMD5(string path) { throw new NotImplementedException(); } public string GetXSHA1(string path) { throw new NotImplementedException(); } public string GetXSHA256(string path) { throw new NotImplementedException(); } public string GetXSHA512(string path) { throw new NotImplementedException(); } public Task&lt;FtpHashAlgorithm&gt; GetHashAlgorithmAsync() { throw new NotImplementedException(); } public Task SetHashAlgorithmAsync(FtpHashAlgorithm type) { throw new NotImplementedException(); } public Task&lt;FtpHash&gt; GetHashAsync(string path) { throw new NotImplementedException(); } public Task&lt;FtpHash&gt; GetChecksumAsync(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetMD5Async(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetXCRCAsync(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetXMD5Async(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetXSHA1Async(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetXSHA256Async(string path) { throw new NotImplementedException(); } public Task&lt;string&gt; GetXSHA512Async(string path) { throw new NotImplementedException(); } public bool IsDisposed { get { return _isDisposed; } } public FtpIpVersion InternetProtocolVersions { get; set; } public int SocketPollInterval { get; set; } public bool StaleDataCheck { get; set; } public bool IsConnected { get { return _connected; } } public bool IsDisconected { get { return _wasDisconected; } } public bool EnableThreadSafeDataConnections { get; set; } public Encoding Encoding { get; set; } public string Host { get; set; } public int Port { get; set; } public NetworkCredential Credentials { get; set; } public int MaximumDereferenceCount { get; set; } public X509CertificateCollection ClientCertificates { get; } public Func&lt;string&gt; AddressResolver { get; set; } public IEnumerable&lt;int&gt; ActivePorts { get; set; } public FtpDataConnectionType DataConnectionType { get; set; } public bool UngracefullDisconnection { get; set; } public int ConnectTimeout { get; set; } public int ReadTimeout { get; set; } public int DataConnectionConnectTimeout { get; set; } public int DataConnectionReadTimeout { get; set; } public bool SocketKeepAlive { get; set; } public FtpCapability Capabilities { get; } public FtpHashAlgorithm HashAlgorithms { get; } public FtpEncryptionMode EncryptionMode { get; set; } public bool DataConnectionEncryption { get; set; } public SslProtocols SslProtocols { get; set; } public string SystemType { get; } public string ConnectionType { get; } public FtpParser ListingParser { get; set; } public CultureInfo ListingCulture { get; set; } public double TimeOffset { get; set; } public bool RecursiveList { get; set; } public bool BulkListing { get; set; } public int BulkListingLength { get; set; } public int TransferChunkSize { get; set; } public int RetryAttempts { get; set; } public uint UploadRateLimit { get; set; } public uint DownloadRateLimit { get; set; } public FtpDataType UploadDataType { get; set; } public FtpDataType DownloadDataType { get; set; } public event FtpSslValidation ValidateCertificate; } public class StubFtpClientFailsToConnect : StubFtpClient { public override void Connect() { throw new Exception("can't connect"); } } public class StubFtpClientThrowsAfterCreatingFile : StubFtpClient { public override bool Download(Stream outStream, string remotePath, IProgress&lt;double&gt; progress = null) { outStream.Write(new byte[]{1,2}, 0, 2); throw new FtpException("Something went wrong while downloading file."); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:30:54.830", "Id": "416178", "Score": "0", "body": "I see the `async-await` tag but no `await/async` code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T23:54:25.420", "Id": "417073", "Score": "0", "body": "you're right @BradM . I intended to use async/await but never got around to (although I thought I did). For example I think this `var finishedTaskIndex = Task.WaitAny(array);` could be using the `async WhenAny()` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T08:40:43.283", "Id": "439072", "Score": "0", "body": "What do you mean with the async WhenAny method? async/await is a pattern used where the method is adorned with _async_ and its body contains one or more _await_ statements on _Task_ instances." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T19:56:55.847", "Id": "441226", "Score": "0", "body": "@dfhwze - I meant that the code could use `await Task.WhenAny()` instead of `Task.WaitAny()` and that would make the method `async`" } ]
[ { "body": "<p>In ListNonArchiveDirectoresWithFiles Method, once you get the <code>finishedTaskIndex</code> you can choose to simply use <code>tasks.RemoveAt(finishedTaskIndex);</code> instead of </p>\n\n<pre><code>tasks = array\n.Except(new[] {finishedTask})\n.ToList();\n</code></pre>\n\n<p>by this you can avoid iterating through whole list with default comparison (<code>EqualityComparer&lt;TElement&gt;.Default</code>) and again transform back to List&lt;>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T23:51:23.670", "Id": "417072", "Score": "0", "body": "Good point! Thanks for taking the time to notice this. I don't consider the extra comparisions a big performance deal since there are always at most 15 tasks, but your idea is the proper and clear way of removing a single item from a list." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T07:43:37.707", "Id": "215560", "ParentId": "215147", "Score": "3" } }, { "body": "<p>While continuing work on this code I have noticed that <code>ListNonArchiveDirectoresWithFiles()</code> already collects all the data retrieved by <code>ListFilesInDirectories()</code> and those methods could be one.</p>\n\n<p>I have also came across [Toub Stephen (2010). Patterns for Parallel Programming, Microsoft]. This book contains a very clear and concise implementation of <code>ParallelWhileNotEmpty()</code> which is exactly what I needed.</p>\n\n<p>Thanks to this the code could become:</p>\n\n<pre><code>using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing DC.Meteologica.Commons.Extensions;\nusing DC.Meteologica.Commons.Helpers;\nusing FluentFTP;\nusing log4net;\n\nnamespace DC.Meteologica.Commons.Ftp\n{\n public class ParallelFtpClient : IDisposable\n {\n private readonly ILog _logger = LogManager.GetLogger(typeof(MeteologicaFtpSyncer).FullName);\n private readonly int _maxConcurrentConnections;\n private readonly Func&lt;IFtpClient&gt; _factory;\n private readonly List&lt;IFtpClient&gt; _ftpClients;\n\n public ParallelFtpClient(int maxConcurrentConnections, Func&lt;IFtpClient&gt; factory)\n {\n _maxConcurrentConnections = maxConcurrentConnections;\n _factory = factory;\n _ftpClients = new List&lt;IFtpClient&gt;();\n }\n\n public void Connect()\n {\n var tasks = new List&lt;Task&gt;();\n for (var i = 0; i &lt; _maxConcurrentConnections; i++)\n {\n var ftpClient = _factory();\n _ftpClients.Add(ftpClient);\n var connectTask = ftpClient.ConnectAsync();\n tasks.Add(connectTask);\n }\n Task.WaitAll(tasks.ToArray());\n }\n\n public void Disconnect()\n {\n var tasks = _ftpClients\n .Select(x =&gt; x.DisconnectAsync())\n .ToArray();\n Task.WaitAll(tasks);\n }\n\n public DownloadResult DownloadFilesParallel(IEnumerable&lt;LocalRemotePathPair&gt; ftpPathLocalPathPairs)\n {\n var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients);\n var downloadedFiles = new ConcurrentBag&lt;LocalRemotePathPair&gt;();\n var failedDownloadsBag = new ConcurrentBag&lt;LocalRemotePathPair&gt;();\n\n Parallel.ForEach(ftpPathLocalPathPairs,\n new ParallelOptions() { MaxDegreeOfParallelism = _maxConcurrentConnections },\n (pair) =&gt;\n {\n clients.TryDequeue(out var client);\n\n _logger.Debug($\"Downloading {pair.FtpFilePath} to {pair.LocalFilePath}...\");\n try\n {\n var memoryStream = new MemoryStream();\n client.Download(memoryStream, pair.FtpFilePath);\n memoryStream.Position = 0;\n var destinationDirectory = Path.GetDirectoryName(pair.LocalFilePath);\n if (!Directory.Exists(destinationDirectory))\n {\n _logger.Info($\"Creating new directory {destinationDirectory}\");\n Directory.CreateDirectory(destinationDirectory);\n }\n\n File.WriteAllBytes(pair.LocalFilePath, memoryStream.ToArray());\n downloadedFiles.Add(pair);\n }\n catch (Exception e)\n {\n _logger.Warn($\"An unhandled exception occured while downloading file {pair.FtpFilePath}\", e);\n failedDownloadsBag.Add(pair);\n }\n\n clients.Enqueue(client);\n }\n );\n\n return new DownloadResult(downloadedFiles.ToList(), failedDownloadsBag.ToList());\n }\n\n public List&lt;string&gt; ListNonArchivedFilesRecursively(string root, CancellationToken token)\n {\n try\n {\n return ListNonArchivedFilesRecursivelyInternal(root, token);\n }\n catch (AggregateException e) when (e.InnerExceptions.Single() is OperationCanceledException)\n {\n throw new OperationCanceledException(token);\n }\n }\n\n private List&lt;string&gt; ListNonArchivedFilesRecursivelyInternal(string root, CancellationToken token)\n {\n var files = new ConcurrentBag&lt;string&gt;();\n var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients);\n\n Parallel2.WhileNotEmpty(\n new []{root},\n new ParallelOptions() { MaxDegreeOfParallelism = _maxConcurrentConnections },\n (path, adder) =&gt;\n {\n token.ThrowIfCancellationRequested();\n _logger.Debug($\"Listing files and folders in {path}...\");\n clients.TryDequeue(out var client);\n try\n {\n var childItems = client.GetListing(path);\n var fileChildItems = childItems\n .Where(x =&gt; x.Type == FtpFileSystemObjectType.File)\n .Select(x =&gt; x.FullName);\n var subDirectoriesToQuery = childItems\n .Where(x =&gt; x.Type == FtpFileSystemObjectType.Directory)\n .Where(x =&gt; x.Name != \"Archive\");\n files.AddRange(fileChildItems);\n foreach (var ftpListItem in subDirectoriesToQuery)\n {\n adder(ftpListItem.FullName);\n }\n }\n catch (TimeoutException e)\n {\n _logger.Info($\"Exception while listing items for: {path}. Listing will be retried.\", e);\n adder(path);\n }\n finally\n {\n clients.Enqueue(client);\n }\n });\n\n return files.ToList();\n }\n\n public void Dispose()\n {\n foreach (var ftpClient in _ftpClients)\n {\n ftpClient.Dispose();\n }\n }\n }\n\n // this is named Parallel2 so it ca coexist with System.Threading.Tasks.Parallel\n internal static class Parallel2\n {\n // from Patterns_of_Parallel_Programming_CSharp.pdf \n public static void WhileNotEmpty&lt;T&gt;(IEnumerable&lt;T&gt; initialValues, ParallelOptions parallelOptions,\n Action&lt;T, Action&lt;T&gt;&gt; body)\n {\n var from = new ConcurrentQueue&lt;T&gt;(initialValues);\n var to = new ConcurrentQueue&lt;T&gt;();\n while (!@from.IsEmpty)\n {\n Action&lt;T&gt; addMethod = v =&gt; to.Enqueue(v);\n Parallel.ForEach(@from, parallelOptions, v =&gt; body(v, addMethod));\n @from = to;\n to = new ConcurrentQueue&lt;T&gt;();\n }\n }\n }\n\n public class DownloadResult\n {\n public DownloadResult(IReadOnlyList&lt;LocalRemotePathPair&gt; downloaded, IReadOnlyList&lt;LocalRemotePathPair&gt; failed)\n {\n Downloaded = downloaded;\n Failed = failed;\n }\n\n public IReadOnlyList&lt;LocalRemotePathPair&gt; Downloaded { get; }\n public IReadOnlyList&lt;LocalRemotePathPair&gt; Failed { get; }\n\n public static DownloadResult AllFine(IReadOnlyList&lt;LocalRemotePathPair&gt; downloadedFiles) =&gt; new DownloadResult(downloadedFiles, new List&lt;LocalRemotePathPair&gt;());\n }\n\n\n public readonly struct LocalRemotePathPair\n {\n public LocalRemotePathPair(string ftpFilePath, string localFilePath) : this()\n {\n FtpFilePath = ftpFilePath;\n LocalFilePath = localFilePath;\n }\n\n public string FtpFilePath { get; }\n public string LocalFilePath { get; }\n\n public override string ToString() =&gt; $\"{FtpFilePath} =&gt; {LocalFilePath}\";\n }\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T20:05:44.170", "Id": "226871", "ParentId": "215147", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T17:32:43.523", "Id": "215147", "Score": "6", "Tags": [ "c#", "asynchronous", "async-await", "task-parallel-library", "ftp" ], "Title": "Parallel FTP client" }
215147
<p><strong>Use case</strong> : <br/>I have a Order web Api which creates an orders and publish the order to messaging queue. Notification service (web api 2) consumes this message by subscribing to the messaging queue and notify the user.</p> <p><em>I'm newbie in messaging queue <br/> I'm using <a href="https://www.cloudamqp.com/" rel="nofollow noreferrer">cloudAMQP</a> as queue service.</em></p> <p><strong>Order Service</strong> where i publish the event</p> <pre><code>public class MessageQueueConfig { public static IModel Channel { get; private set; } public static IConnection Connection { get; private set; } const string ExchangeName = "Notifications"; public const string CreatedRoutingKey = "WorkOrderCreated"; public const string UpdatedRoutingKey = "WorkOrderUpdated"; public static void Register() { var factory = new ConnectionFactory() { Uri = new Uri(@"amqp://myurl"), }; factory.RequestedHeartbeat = 5; Connection = factory.CreateConnection(); Channel = Connection.CreateModel(); Channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Topic, durable: true); } public static void Publish(string routingKey, object body) { var byteBody = MemorySerializer.ObjectToByteArray(body); if (Connection.IsOpen) { Channel.BasicPublish(exchange: ExchangeName, routingKey: routingKey, basicProperties: null, body: byteBody); } } } </code></pre> <p><strong>Order Service Global.asax.cs</strong></p> <pre><code>protected void Application_Start() { FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); //web api config MessageQueueConfig.Register(); //where i start the queue. } </code></pre> <p><strong>Order Service Controller</strong></p> <pre><code>[HttpPost] public async Task&lt;IHttpActionResult&gt; InsertOrder(Order Parms) { try { var jobNumber = await _WorkOrderB.InsertOrder(Parms, passCode); ResponseObj responseobj = new ResponseObj(); var msg= new MyQueueClass{ //some data}; MessageQueueConfig.Publish(MessageQueueConfig.CreatedRoutingKey, msg); responseobj.Result = GeneralDTO.SuccessStatus; responseobj.ResponseData = jobNumber; return Ok(responseobj); } catch (Exception exception) { return InternalServerError(exception); } } </code></pre> <p><strong>Notification Service</strong> where i consume the events</p> <pre><code>public class MessageQueueConfig { public static IModel Channel { get; private set; } public static IConnection Connection { get; private set; } const string ExchangeName = "Notifications"; const string CreatedRoutingKey = "WorkOrderCreated"; const string UpdatedRoutingKey = "WorkOrderUpdated"; static List&lt;string&gt; RoutingKeys = new List&lt;string&gt; { "WorkOrderCreated", "WorkOrderUpdated" }; public static void RegisterAndSubscribe() { var factory = new ConnectionFactory() { Uri = new Uri(@"amqp://myurl"), }; factory.RequestedHeartbeat = 5; Connection = factory.CreateConnection(); Channel = Connection.CreateModel(); Channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Topic, durable: true); var queueName = Channel.QueueDeclare().QueueName; foreach (var routingKey in RoutingKeys) { Channel.QueueBind(queue: queueName, exchange: ExchangeName, routingKey: routingKey); } var consumer = new EventingBasicConsumer(Channel); consumer.Received += Consumer_Received; Channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer); } async static void Consumer_Received(object sender, BasicDeliverEventArgs e) { switch (routingKey) { case CreatedRoutingKey: await ProcessWorkOrderCreated(e.Body); break; case UpdatedRoutingKey: await ProcessWorkOrderUpdated(e.Body); break; default: break; } </code></pre> <p><strong>Notifcation Service Global.ascx.cx</strong></p> <pre><code>protected void Application_Start() { //Web api Conifg BundleConfig.RegisterBundles(BundleTable.Bundles); MessageQueueConfig.RegisterAndSubscribe(); } </code></pre> <p><strong>Questions</strong></p> <ol> <li>I would like to know any potential issue for this architecture ?</li> <li>What should be ideal <code>factory.RequestedHeartbeat = 5;</code> ?</li> <li>What would happen if my notification service (consumer) goes down ? i have put my queue as <code>durable= true</code> assuming it would still available when my consumer is back online.</li> <li>I haven't disposed them, Is Global.asxs.cs <code>public void Dispose()</code> is the right place to Close the rabbitmq connection ?</li> </ol> <p><strong>Global.asxs.cs</strong> <br/></p> <pre><code>public override void Dispose() { MessageQueueConfig.Dispose(); base.Dispose(); } </code></pre> <p><em>Note: This code is running dev environment, i'm planning to release this next week to production</em></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:05:32.423", "Id": "215149", "Score": "0", "Tags": [ "c#", "queue", "asp.net-web-api", "rabbitmq" ], "Title": "Using RabbitMQ in asp.net web api" }
215149
<p>I am quite new to Javascript. For a school project we wrote a website that displays the user's location on a google map alongside with some objects such as vehicles or passengers. I rewrote my code to include async...await syntax after learning about them. But I still do not know if the code is any good, or if it could be improved. I hoped you guys would have an answer. Here is the code:</p> <pre><code>const myID = 'Wkevc4Sj'; const myIcon = 'images/marker.png'; const passIcon = 'images/passenger.png'; const carIcon = 'images/car.png'; const weinerIcon = 'images/weinermobile.png'; const has = Object.prototype.hasOwnProperty; var infowindow = {}; var directionsService = {}; var directionsDisplay = {}; var userLocation = {}; var weinerExists = false; async function run() { try { let map = await initMap(); renderMap(map); let userMarker = addUserMarker(map); let request = getRide(); let response = await request; let ride = await response.json(); console.log(ride); let userType = has.call(ride, "vehicles") ? "passenger" : "vehicle"; populateMap(userType, ride, map, userMarker); } catch (e) { alert (e); } } // getLocation is a promise that resolves with the location that uses navigator const getLocation = new Promise(function(resolve, reject) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(resolve, reject); } else { reject('Browser does not support geolocation'); } }); // initMap() when called initializes the map element on the body using // the user's location async function initMap() { var position = await getLocation; userLocation = { lat: position.coords.latitude, lng: position.coords.longitude }; return new google.maps.Map(document.getElementById('map'), { center: userLocation, zoom: 16, disableDefaultUI: true }); } // renderMap(map) when given a google.maps.map object, // adds direction service and an infoWindow to the map. // also adds a marker on the current position of the user. function renderMap(map) { infowindow = new google.maps.InfoWindow(); directionsService = new google.maps.DirectionsService(); directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); directionsDisplay.setOptions({ suppressMarkers: true }); } // getRide() returns a promise that resolves with a JSON object returned from the // ride API async function getRide() { const url = 'https://hans-moleman.herokuapp.com/rides'; const params = `username=${myID}&amp;lat=${userLocation.lat}&amp;lng=${userLocation.lng}`; return fetch(url, { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: params, }); } // addUserMarker(map) adds a user marker to the provided map function addUserMarker(map) { const content = `&lt;p&gt;&lt;strong&gt;Your Location:&lt;/strong&gt;&lt;br /&gt; Lat = ${precise(userLocation.lat, 4)} Lng = ${precise(userLocation.lng, 4)}`; let userMarker = newMarker(userLocation, myIcon, content, map); google.maps.event.addListener(userMarker, 'click', function() { infowindow.setContent(this.content); infowindow.open(map, this); }); return userMarker; } // newMarker(position, icon, content, map) returns a new marker with the // arguments as marker properties. function newMarker(position, icon, content, map) { return new google.maps.Marker({ position: position, icon: icon, content: content, map: map }); } // newMarkerwListener(position, icon, content, map) returns a new marker with // arguments as marker properties and a popup click listener added. function newMarkerwListener(position, icon, content, map) { let marker = newMarker(position, icon, content, map); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(this.content); infowindow.open(map, this); }); return marker; } // populateMap(userType, ride, map, marker) given the type of the user, // ride API response JSON object, a google map and a user marker, // populates the map with the objects of the ride and modifies the // marker to represent the nearest object function populateMap(userType, ride, map, marker) { const elemArray = ride[userType == "passenger" ? "vehicles" : "passengers"]; let nearest = elemArray[0]; let weinerMobile = {}; for (var i = 0; i &lt; elemArray.length; i++) { let elem = elemArray[i]; let nearestDistance = distanceTo(userLocation, nearest); let distance = distanceTo(userLocation, elem); let content = `&lt;p&gt;&lt;strong&gt;Name: &lt;/strong&gt; ${elem.username}&lt;br /&gt;${distance} miles away from you`; let icon = userType == "vehicle" ? passIcon : carIcon; if (elem.username == "WEINERMOBILE") { icon = weinerIcon; weinerExists = true; weinerMobile = elem; } newMarkerwListener(elem, icon, content, map); nearest = nearestDistance &lt; distance ? nearest : elem; } if (!(nearest === undefined)) { marker.content += `&lt;br /&gt;&lt;strong&gt;Nearest: ${nearest.username}&lt;/strong&gt;&lt;br /&gt;${distanceTo(userLocation, nearest)} miles away from you`; } if (weinerExists) { marker.content += `&lt;br /&gt;&lt;strong&gt;Weinermobile:&lt;/strong&gt;&lt;br /&gt;${distanceTo(userLocation, weinerMobile)} miles away`; } else { marker.content += "&lt;br /&gt;The Weinermobile is nowhere to be seen"; } } /* HELPER FUNCTIONS */ function precise(x, y) { return Number.parseFloat(x).toPrecision(y); } function findDistFromTo(from, to) { var vLatLng = new google.maps.LatLng( parseFloat(from.lat), parseFloat(from.lng) ); var cLatLng = new google.maps.LatLng( parseFloat(to.lat), parseFloat(to.lng) ); return google.maps.geometry.spherical.computeDistanceBetween( cLatLng, vLatLng ); } function toMiles(meters) { return meters * 0.000621371192; } function distanceTo(from, to) { return precise(toMiles(findDistFromTo(from, to)), 4); } </code></pre> <p>Thanks in advance.</p>
[]
[ { "body": "<p>My observations:</p>\n\n<ol>\n<li>Use <code>let</code> instead of <code>var</code>. You are already using <code>let</code> in some places, but a few need to be converted. For those that do not know the difference, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> is one of the new features in ES2015 (ES6) and it respects block scopes in the same way as other programming languages.</li>\n<li>~~</li>\n<li>I would use file scope constants for the strings \"passenger\" and \"vehicle\". Makes it easier in the future to do refactors. For example, at the top of the file <code>const PASSENGER = 'passenger'</code></li>\n<li>Change this <code>if (!(nearest === undefined))</code> to <code>if (!!nearest)</code>, what you care about is if its a truthy value. The specificity of \"not undefined\" would allow other falsy values like <code>0</code>, <code>null</code>, <code>NaN</code>, <code>''</code>, <code>\"\"</code>, ````</li>\n<li>If file scope constant were to be used and all the possible values are known, you could test for those specifically. Instead of <code>if (!!nearest)</code> you could <code>if ([PASSENGER, VEHICLE].includes(nearest))</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T18:28:50.673", "Id": "417526", "Score": "0", "body": "Thank you for the suggestions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:18:46.090", "Id": "215154", "ParentId": "215150", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:13:30.663", "Id": "215150", "Score": "0", "Tags": [ "javascript", "beginner", "ajax", "async-await", "google-maps" ], "Title": "Displaying multiple objects on map and calculating distances using google api" }
215150
<p>I have been developing a graphical calculator, and to allow for natural user input I have written a function which converts their input into a python readable form.</p> <p>This is my first time using regex, and I believe I managed to get each of the expressions to do what I intended by them.</p> <p>However, as can been seen there are quite a few different cases to consider, and so the function is relatively long considering what it does.</p> <p>I was wondering if there was a better solution than this to solve my problem, but if not can I improve my implementation at all?</p> <pre><code>def edit_function_string(func): """Converts the input function into a form executable by Python""" func = re.sub(r'\s+', '', func) # Strip whitespace func = re.sub(r'\^', r'**', func) # replaces '^' with '**' func = re.sub(r'/(([\w()]+(\*\*)?)*)', r'/(\1)', func) # replaces '/nf(x)' with '/(nf(x))' func = re.sub(r'\*\*(([\w()]+(\*\*)?)*)', r'**(\1)', func) # replaces '**nf(x)' with '**(nf(x))' func = re.sub(r'(\d+)x', r'\1*x', func) # replaces 'nx' with 'n*x' func = re.sub(r'(math\.)?ceil(ing)?', 'math.ceil', func) # replaces 'ceil(ing)' with 'math.ceil' func = re.sub(r'(math\.)?floor', 'math.floor', func) # replaces 'floor' with 'math.floor' func = re.sub(r'(math\.f)?abs(olute)?|modulus', 'math.fabs', func) # replaces 'abs(olute)' with 'math.fabs' func = re.sub(r'(math\.)?sqrt|root', 'math.sqrt', func) # replaces 'sqrt' or 'root' with 'math.sqrt' func = re.sub(r'(math\.)?log|ln', 'math.log', func) # replaces 'log' or 'ln' with 'math.log' func = re.sub(r'(math\.)?exp', 'math.exp', func) # replaces 'exp' with 'math.exp' func = re.sub(r'\|(.+?)\|', r'math.fabs(\1)', func) # replaces '|x|' with 'math.fabs(x)' func = re.sub(r'([\w]+)!|\((.+?)\)!', r'math.factorial(\1\2)', func) # replaces 'x!' with 'math.factorial(x)' for f in ('sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh'): # replaces trigonometric or hyperbolic functions with the correct syntax func = re.sub(r'^(\d*){f}\(|([+\-*/()])(\d*){f}\('.format(f=f), r'\1\2\3math.{f}('.format(f=f), func) # replaces inverse trigonometric or hyperbolic functions with the correct syntax func = re.sub(r'^(\d*)a(rc?)?{f}\(|([+\-*/()])(\d*)a(rc?)?{f}\('.format(f=f), r'\3\1\4math.a{f}('.format(f=f), func) for f, reciprocal in (('sec', 'cos'), ('cosec', 'sin'), ('csc', 'sin'), ('cot', 'tan'), ('sech', 'cosh'), ('cosech', 'sinh'), ('csch', 'sinh'), ('coth', 'tanh')): # replaces reciprocal trigonometric or hyperbolic functions with the correct syntax func = re.sub(r'^(\d*){f}\((.+?)\)|([+\-*/()])(\d*){f}\((.+?)\)'.format(f=f), r'\3\1\4(1/math.{reciprocal}(\2\5))'.format(reciprocal=reciprocal), func) # replaces inverse reciprocal trigonometric or hyperbolic functions with the correct syntax func = re.sub(r'^(\d*)a(rc?)?{f}\((.+?)\)|([+\-*/()])(\d*)a(rc?)?{f}\((.+?)\)'.format(f=f), r'\4\1\5(1/math.a{reciprocal}(\3\7))'.format(reciprocal=reciprocal), func) for i in range(2): # Runs twice in order to deal with overlapping matches for constant in ('e', 'pi', 'tau'): # replaces 'e', 'pi', or 'tau' with 'math.e', 'math.pi', or 'math.tau' respectfully # unless in another function such as: 'math.ceil' func = re.sub(r'^(\d*){constant}(x?)$|^(\d*){constant}(x?)([+\-*/(])|' r'([+\-*/()])(\d*){constant}(x?)([+\-*/()])|' r'([+\-*/)])(\d*){constant}(x?)$'.format(constant=constant), r'\6\10\1\3\7\11math.{constant}\2\4\8\12\5\9'.format(constant=constant), func) # replaces 'math.ex', 'math.pix', or 'math.tau' with 'math.e*x', 'math.pi*x', or 'math.tau*x' respectfully # unless part of another function func = re.sub(r'math\.{constant}x([+\-*/()])|math.ex$'.format(constant=constant), r'math.{constant}*x\1'.format(constant=constant), func) func = re.sub(r'([\dx])math\.', r'\1*math.', func) # replaces 'nmath.' with 'n*math.' func = re.sub(r'([\dx])\(', r'\1*(', func) # replaces 'n(' with 'n*(' return func </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T01:16:40.023", "Id": "416076", "Score": "3", "body": "I would suggest you consider writing an expression parser. Eli Bendersky has an excellent [article](https://eli.thegreenplace.net/2010/01/02/top-down-operator-precedence-parsing/) on Top-Down Operator Precedence parsers that uses Python for implementation." } ]
[ { "body": "<p>The main problem I see with this code is that it's write-only:</p>\n\n<ul>\n<li>Single character names. These are deadly to understanding the code.</li>\n<li>Over-reliance on regular expressions. These take a long time to read, and in my experience usually hide at least one bug each.</li>\n<li>Magical values which should be constants, such as <code>2</code>.</li>\n<li>A single variable which is changed several times.</li>\n<li>No unit tests, although they may be elsewhere.</li>\n</ul>\n\n<p>Other than that, provide <em>one</em> way to run each function. Since you already support providing the same name as the Python function, why not just mandate that and make the code significantly simpler? In fact, why invent your own DSL at all for this problem? Just giving the user a Python shell with mathematical functions already imported should get them 90% of the way there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T01:17:26.817", "Id": "215160", "ParentId": "215152", "Score": "2" } } ]
{ "AcceptedAnswerId": "215160", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T19:50:45.460", "Id": "215152", "Score": "0", "Tags": [ "python", "python-3.x", "regex", "math-expression-eval" ], "Title": "Convert natural input into Python executable function" }
215152
<p>In my <a href="https://codereview.stackexchange.com/questions/215112/linked-list-interview-code-basic-methods-made-from-struct-node">previous post</a> I had a number of steps given to me from the accepted answer on how I can write more production ready code. In this post I want this code to be reviewed as near production code I'd write in an interview. I'd like to know how well optimized my code is now from this improvements I've made to it. If there are other optimizations or c++11 features I could be using here please share that as well. </p> <p>I also included comments on worst case run time complexity for my member functions, I'd like some feedback on this and my space complexity too.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; class LinkedList { private: struct Node { int data; Node* next; Node(int data_) : data(data_), next(nullptr) { } }; Node* _head; Node* _tail; public: LinkedList() : _head(nullptr) { } LinkedList(int data) { // O(1) Node* n = new Node(data); _head = n; _tail = n; } ~LinkedList() { // O(n) Node* current = _head; Node* n; while(current) { n = current; current = current-&gt;next; delete n; } _head = nullptr; } void append(int new_data) { // O(1) auto n = new Node(new_data); if(!_head) { _head = n; _tail = n; } else { _tail-&gt;next = new Node(new_data); _tail = _tail-&gt;next; } } void remove(int target_data) { // O(n) if(!_head) { return; } Node* previous = nullptr; auto current = _head; for(; current-&gt;data != target_data; current = current-&gt;next) { if(!current-&gt;next) { return; } previous = current; } if(!current-&gt;next) { if(previous) { delete current; previous-&gt;next = nullptr; } else { delete current; _head = nullptr; } } else { auto dangling_ptr = current-&gt;next; current-&gt;data = current-&gt;next-&gt;data; current-&gt;next = current-&gt;next-&gt;next; delete dangling_ptr; } } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const LinkedList&amp; linked_list) { // O(n) Node* current = linked_list._head; if(!current) { os &lt;&lt; "Linked List is empty" &lt;&lt; std::endl; return os; } else { for(; current; current = current-&gt;next) { os &lt;&lt; '(' &lt;&lt; std::to_string(current-&gt;data) &lt;&lt; ")-&gt;"; } os &lt;&lt; "nullptr"; return os; } } }; int main() { LinkedList linked_List(0); linked_List.append(1); linked_List.append(2); linked_List.append(3); linked_List.append(4); std::cout &lt;&lt; linked_List &lt;&lt; std::endl; linked_List.remove(0); linked_List.remove(4); linked_List.remove(2); std::cout &lt;&lt; linked_List &lt;&lt; std::endl; linked_List.remove(3); linked_List.remove(1); std::cout &lt;&lt; linked_List &lt;&lt; std::endl; LinkedList linked_List_two; linked_List_two.append(1); linked_List_two.append(2); linked_List_two.append(3); linked_List_two.append(4); std::cout &lt;&lt; linked_List_two &lt;&lt; std::endl; linked_List_two.remove(0); linked_List_two.remove(4); linked_List_two.remove(2); std::cout &lt;&lt; linked_List_two &lt;&lt; std::endl; linked_List_two.remove(3); linked_List_two.remove(1); std::cout &lt;&lt; linked_List_two &lt;&lt; std::endl; } </code></pre>
[]
[ { "body": "<p>Overall, your implementation has improved so good job! Here's a few general comments. </p>\n\n<ul>\n<li><p>In <code>operator&lt;&lt;</code>, you can make <code>current</code> of type <code>const Node*</code> (but not of type <code>const Node* const</code>). In other words, you have a pointer to a const Node, but not a const pointer to const Node.</p></li>\n<li><p>In <code>append</code>, if the else-branch is executed, you will have created <code>n</code> for no reason. So move its declaration inside of the if-branch where it is needed.</p></li>\n<li><p>In your destructor, move the declaration of <code>n</code> inside the while-loop and make it const. So its first line should be <code>const Node* const n = current</code>.</p></li>\n<li><p>For the constructor of <code>Node</code>, I find it confusing the argument name has a trailing underscore; this does not happen for the other function arguments anywhere. Perhaps you meant the private member to be <code>data_</code> (or <code>_data</code>) and the argument just <code>data</code>.</p></li>\n<li><p>Why is the default constructor also not making <code>_tail</code> null? To avoid these type of problems, as per <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-in-class-initializer\" rel=\"nofollow noreferrer\">C.48</a>, I would omit the default constructor and just use in-class initialization to set both to <code>{nullptr}</code>.</p></li>\n<li><p>Unless there is a reason not to, it is good practice (as per <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-explicit\" rel=\"nofollow noreferrer\">C.46</a>) to make single-argument constructors explicit to avoid unintentional conversions.</p></li>\n<li><p>For a future version, you might want to look at smart pointers to avoid leaking memory.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:08:00.650", "Id": "416171", "Score": "0", "body": "If I move `n` inside my while loop, will this have any negative impacts on space complicity since I will be declaring and assigning with each iteration? I could be wrong, but I thought in my current implementation it would only allow for a declaration once and then an assignment to `n` for each iteration. I agree with all the points here, I've seen a lot of common feedback with smart pointers and should look into implementing them" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:16:14.843", "Id": "416175", "Score": "0", "body": "@greg But you assign on every iteration anyway. If you really care about the details, there is no substitute at looking at the generated machine code is." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T08:37:06.140", "Id": "215175", "ParentId": "215155", "Score": "2" } }, { "body": "<ul>\n<li><p><code>append</code> leaks memory: the <code>else</code> branch forgets <code>n</code> and creates another <code>Node</code>.</p></li>\n<li><p><code>append</code> should be streamlined. The new node becomes tail no matter what:</p>\n\n<pre><code> Node * n = new Node(new_data);\n\n if (!head) {\n head = n;\n } else {\n tail-&gt;next = n;\n }\n\n tail = n;\n</code></pre></li>\n<li><p><code>remove</code> never updates <code>tail</code>, and only updates <code>head</code> when the list becomes empty. Removal of them makes the list corrupted.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:09:11.380", "Id": "416172", "Score": "0", "body": "Great catch I see this now. I'll include this feedback when I refactor these methods." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:59:04.513", "Id": "215186", "ParentId": "215155", "Score": "3" } }, { "body": "<p>I see a number of things that could help you improve your code.</p>\n\n<h2>Don't define a default constructor that only initializes data</h2>\n\n<p>Instead of writing this:</p>\n\n<pre><code>class LinkedList\n{\n Node* _head;\n Node* _tail;\n public:\n LinkedList() : _head(nullptr) { }\n // etc.\n};\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>class LinkedList\n{\n Node* _head = nullptr;\n Node* _tail = nullptr;\n public:\n // no need to explicitly write default constructor\n LinkedList() = default;\n};\n</code></pre>\n\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-default\" rel=\"nofollow noreferrer\">Cpp Core Guidelines C.45</a> for details. Note also that this initializes <em>both</em> member data items.</p>\n\n<h2>Think about whether the destructor should be virtual</h2>\n\n<p>For an interview, you should be prepared to answer why the class destructor is not virtual and to explain circumstances in which it should be virtual.</p>\n\n<h2>Eliminate redundant variables</h2>\n\n<p>The current code contains this constructor:</p>\n\n<pre><code>LinkedList(int data) { // O(1)\n Node* n = new Node(data);\n _head = n;\n _tail = n;\n}\n</code></pre>\n\n<p>I'd prefer to see <code>n</code> eliminated and to see it written instead like this:</p>\n\n<pre><code>LinkedList(int data) :\n _head{new Node{data}}, _tail{_head} {}\n</code></pre>\n\n<h2>Use <code>for</code> rather than <code>while</code> where appropriate</h2>\n\n<p>The desructor currently looks like this:</p>\n\n<pre><code>~LinkedList() { // O(n)\n Node* current = _head;\n Node* n;\n while(current) {\n n = current;\n current = current-&gt;next;\n delete n;\n }\n _head = nullptr;\n}\n</code></pre>\n\n<p>Rather than introducing two extra variables, I'd write it using a <code>for</code> loop like this:</p>\n\n<pre><code>~LinkedList() { // O(n)\n if (_head == nullptr) {\n return;\n }\n for (auto current{_head-&gt;next}; current; current = current-&gt;next) {\n delete _head;\n _head = current;\n }\n}\n</code></pre>\n\n<h2>Fix the memory leak</h2>\n\n<p>The current code has this member function:</p>\n\n<pre><code>void append(int new_data) { // O(1)\n auto n = new Node(new_data);\n if(!_head) {\n _head = n;\n _tail = n;\n }\n else {\n _tail-&gt;next = new Node(new_data);\n _tail = _tail-&gt;next;\n }\n}\n</code></pre>\n\n<p>The problem is that we create <em>two</em> nodes but only use one unless the list is empty. I'd fix that like this:</p>\n\n<pre><code>void append(int new_data) { // O(1)\n auto n{new Node(new_data)};\n if(_head == nullptr) {\n _head = _tail = n;\n } else {\n _tail-&gt;next = n;\n _tail = _tail-&gt;next;\n }\n}\n</code></pre>\n\n<h2>Simplify your code</h2>\n\n<p>The <code>remove</code> function is much more longer than it needs to be. Right now it looks like this:</p>\n\n<pre><code> void remove(int target_data) { // O(n)\n if(!_head) { return; }\n Node* previous = nullptr;\n auto current = _head;\n for(; current-&gt;data != target_data; current = current-&gt;next) {\n if(!current-&gt;next) {\n return;\n }\n previous = current;\n }\n if(!current-&gt;next) {\n if(previous) {\n delete current;\n previous-&gt;next = nullptr;\n }\n else {\n delete current;\n _head = nullptr;\n }\n }\n else {\n auto dangling_ptr = current-&gt;next;\n current-&gt;data = current-&gt;next-&gt;data;\n current-&gt;next = current-&gt;next-&gt;next;\n delete dangling_ptr;\n }\n }\n</code></pre>\n\n<p>It could be made somewhat simpler by creating a temporary <code>Node</code> that points to <code>_head</code>:</p>\n\n<pre><code>void remove(int target_data) { // O(n)\n Node headptr{0};\n headptr.next = _head;\n for (Node* curr{&amp;headptr}; curr &amp;&amp; curr-&gt;next; curr = curr-&gt;next) {\n if (curr-&gt;next-&gt;data == target_data) {\n auto victim = curr-&gt;next;\n if (victim == _tail) {\n _tail = curr;\n }\n if (victim == _head) {\n _head = victim-&gt;next;\n }\n curr-&gt;next = victim-&gt;next;\n delete victim;\n return;\n }\n }\n}\n</code></pre>\n\n<h2>Rethink the interface</h2>\n\n<p>It's not unreasonable to expect that one might want to actually do something with the things inserted into a list. Right now, there's no way to do anything except print which suggests an incomplete interface.</p>\n\n<h2>Don't use <code>std::endl</code> if <code>'\\n'</code> will do</h2>\n\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>.</p>\n\n<h2>Make test success obvious</h2>\n\n<p>The current test code exersizes the list, but it doesn't indicate what is <em>expected</em> to be printed. I'd instead write both test scenarios and also the expected result so that it would be clear to anyone running the code whether everything was working as expected or not.</p>\n\n<h2>Consider using a template</h2>\n\n<p>A linked list is a fairly generic structure that could hold any kind of data if the class were templated, and not just an <code>int</code>.</p>\n\n<h2>Consider possible uses</h2>\n\n<p>For any code production, but especially if you're in an interview, think about how the class is being used and whether there are any restrictions or limits inherent in the design. For example, think about <code>copy</code> and <code>move</code> operations. If you write this, does the code do the right thing?</p>\n\n<pre><code>LinkedList a;\na.append(1);\na.append(2);\na.append(3);\na.append(4);\nauto b{a};\nstd::cout &lt;&lt; \"a: \" &lt;&lt; a &lt;&lt; '\\n';\nstd::cout &lt;&lt; \"b: \" &lt;&lt; b &lt;&lt; '\\n';\na.remove(1);\nstd::cout &lt;&lt; \"a: \" &lt;&lt; a &lt;&lt; '\\n';\nstd::cout &lt;&lt; \"b: \" &lt;&lt; b &lt;&lt; '\\n';\n</code></pre>\n\n<p>Also consider multithreaded code. Would it be thread-safe to insert nodes from one thread and remove them from another? If not, what would be needed to make that work?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:05:17.020", "Id": "416170", "Score": "0", "body": "Hey thee Edward, this is great feedback and I'll work on implementing it into the code. I noticed the sections Prefer iteration over recursion and Simplify your code for `push_back` may be referencing code that is not in this post. Sorry for the confusion there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:39:34.653", "Id": "416179", "Score": "0", "body": "Thanks, you're right; I had copied some things from another question and forgot to delete those sections. Your code wasn't the problem -- the confusion was all my own creation! Sorry about that; I have fixed my answer now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:51:04.110", "Id": "416180", "Score": "0", "body": "`\\n` will also flush the stream unless the stream can be determined to not go to an interactive device or sync_with_stdio(false) had been called. https://stackoverflow.com/a/25569849/2498188" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:36:31.563", "Id": "416311", "Score": "0", "body": "You would only prefer to see `n` eliminated, and Things rewritten to use the ctor-init-list? It's not a matter of preference but correctness though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:45:01.283", "Id": "416316", "Score": "0", "body": "@Deduplicator: I don't understand your comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T19:14:25.830", "Id": "416346", "Score": "0", "body": "Take a look at the original buggy code, your proposed fixed replacement, and think of exceptions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T21:17:02.413", "Id": "416368", "Score": "0", "body": "If you're talking about the possibility of an out-of-memory exception, there's not a problem because there's exactly one allocation and no other resource allocation. If you're talking about something else, naming it would help educate me and the OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T21:20:18.387", "Id": "416370", "Score": "0", "body": "Take a look at the original code: If there is an exception, the pointers in the class are indeterminate and the dtor is called. Take your replacement: If there is an exception, the dtor is not called at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T21:23:34.117", "Id": "416373", "Score": "0", "body": "Yes, but by definition, if `new` fails in this context, it's not needed to call the destructor because there's nothing to deallocate. What am I missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T22:00:31.093", "Id": "416375", "Score": "0", "body": "@Edward You are missing that in the original code, the call to `new` which potentially throws is in the ctor's *body*, thus the dtor *will* be called!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T22:20:35.287", "Id": "416377", "Score": "0", "body": "@Deduplicator: ah, I thought you were commenting on my rewrite." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:52:46.107", "Id": "215198", "ParentId": "215155", "Score": "4" } } ]
{ "AcceptedAnswerId": "215198", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T22:30:36.420", "Id": "215155", "Score": "3", "Tags": [ "c++", "c++11", "linked-list", "pointers" ], "Title": "Linked List Interview Code methods, runtime, and edge cases refactored" }
215155
<p>I'm doing the <a href="https://materiaalit.github.io/2013-oo-programming/part1/week-6/" rel="nofollow noreferrer">MOOC Java course</a> (<kbd>CTRL</kbd>+<kbd>F</kbd> "distribution"):</p> <blockquote> <p>The input of the program is a set of exam scores of a course. Each score is an integer. When -1 is entered, the program stops asking for further input.</p> <p>After the scores have been read, the program prints the grade distribution and acceptance percentage of the course.</p> <p>Grade distribution is formed as follows:</p> <ul> <li><p>Each exam score is mapped to a grade using the same formula as in exercise 18. If the score is not within the range 0-60 it is not taken into account.</p></li> <li><p>The number of grades are printed as stars, e.g. if there are 2 scores that correspond to grade 5, the line 5: ** is printed. If there are no scores that correspond to a particular grade, the printed line is 4:</p></li> </ul> <p>All the grades besides zeros are accepted, so in the above 7 out of 8 participants were accepted. Acceptance percentage is calculated with the formula 100*accepted/allScores.</p> </blockquote> <p>The formula in exercise 18 is:</p> <pre><code>&lt;table &gt; &lt;tr&gt; &lt;th&gt;Points&lt;/th&gt; &lt;th&gt;Grade&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;0-29&lt;/td&gt; &lt;td&gt;Failed&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;30-34&lt;/td&gt; &lt;td&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;35-39&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;40-44&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;45-49&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;50-60&lt;/td&gt; &lt;td&gt;5&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I wrote code that seems to work fine based on my tests, no compile errors, no run-time errors (except for cases where you enter a string instead of a number or a ridiculously large number).</p> <p>I tested it using input from the table above, i.e I entered the numbers (0, 29, 30, 34, 35, 39, 40, 44, 45, 49, 50, 60), and there were two stars printed in each grade range, as expected. I also tested it with numbers in between the ranges, and numbers outside of [0, 60]. I found no logical errors.</p> <p>I found the names I used too repetitive, <code>GradeDistribution</code> class, 3 arrays called <code>gradeRanges</code>, <code>gradeDistributionList</code>, <code>gradeList</code>.</p> <p>Other problems: The logic of calculating <code>gradeDistribution</code> seems too nested. Should I have used switch-case? Should I have used static methods instead of a class? Should I have combined the methods <code>calculateGradeDistribution</code> and <code>printGradeDistribution</code> into one? Am I worrying too much about little things?</p> <p>This is main:</p> <pre><code>import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); ArrayList&lt;Integer&gt; grades = new ArrayList&lt;Integer&gt;(); int number = 0; System.out.println("Type exam scores, -1 to end"); do{ number = Integer.parseInt(reader.nextLine()); if(number != -1){ grades.add(number); } }while(number != -1); GradeDistribution syrianGradeDistribution = new GradeDistribution(); syrianGradeDistribution.calculateGradeDistribution(grades); syrianGradeDistribution.printGradeDistribution(); System.out.println(syrianGradeDistribution.acceptancePercentage()); } } </code></pre> <p>This is the <code>GradeDistribution</code> class:</p> <pre><code>import java.util.ArrayList; import java.util.Collections; public class GradeDistribution { private ArrayList&lt;Integer&gt; gradeRanges = new ArrayList&lt;&gt;(); private ArrayList&lt;Integer&gt; gradeDistributionList = new ArrayList&lt;&gt;(); public GradeDistribution(){ Collections.addAll(gradeRanges, 0, 30, 35, 40, 45, 50, 61); Collections.addAll(gradeDistributionList, 0, 0, 0, 0, 0, 0); } public void calculateGradeDistribution(ArrayList&lt;Integer&gt; gradeList){ for(int grade: gradeList){ if(grade &lt; 0 || grade &gt; 60){ //invalid grades continue; } for(int i = 0; i &lt; gradeRanges.size() -1 ; i++){ if(grade &gt;= gradeRanges.get(i) &amp;&amp; grade &lt; gradeRanges.get(i + 1)){ gradeDistributionList.set(i, gradeDistributionList.get(i)+ 1); } } } } public void printGradeDistribution(){ for(int i = 0; i &lt; gradeDistributionList.size(); i++){ System.out.print(i + ": "); for(int j = 0; j &lt; gradeDistributionList.get(i); j++){ System.out.print("*"); } System.out.println(); } } public double acceptancePercentage(){ int allScores = 0; for(int number: gradeDistributionList){ allScores += number; } int acceptedScores = allScores - gradeDistributionList.get(0); double acceptancePercentage = 100.0 * acceptedScores / allScores; return acceptancePercentage; } } </code></pre> <p>The code compiles without any errors on Windows 10, Java 11.0.2.</p> <p>This is a very simple program, but yet, I still have many questions about the choices I made. How can I become confident in my choices and know what's acceptable and what's not?</p>
[]
[ { "body": "<p>I do not see any errors in the code. However, I do not like the choice of data structure in <code>GradeDistribution</code>. Not only are insertions slow -- taking time linear in the number of ranges -- but it is also unnecessarily involved. Java has a wealth of data structures in the standard library. Choosing the right one can make your code faster and cleaner. I recommend <code>TreeMap</code>, which has a <code>floorEntry</code> method that makes is easy to find the appropriate range for a given score.</p>\n\n<p>More detailed critique:</p>\n\n<ul>\n<li>Use constants to hold magic numbers like the min/max scores and ranges.</li>\n<li>Add scores to the data structure one at a time instead of as a list.</li>\n<li>Shorten variables and method names.</li>\n<li>Use name <code>getAcceptedPercent</code> to make it clear this method is an accessor.</li>\n<li>Use <code>Scanner.nextInt</code> and <code>Scanner.hasNextInt</code>.</li>\n<li>Use an infinite loop and break to avoid checking <code>number != -1</code> twice.</li>\n<li>Keep track of total and accepted scores as you go.</li>\n</ul>\n\n<p>Here is my implementation, which addresses each issue:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner reader = new Scanner(System.in);\n GradeDistribution grades = new GradeDistribution();\n\n System.out.println(\"Type exam scores, -1 to end\");\n while (reader.hasNextInt()) {\n int number = reader.nextInt();\n if (number == -1) {\n break;\n }\n grades.add(number);\n }\n\n grades.print();\n System.out.println(grades.getAcceptedPercent());\n }\n}\n</code></pre>\n\n<pre><code>import java.util.TreeMap;\nimport java.util.Map;\n\npublic class GradeDistribution {\n private static final int MIN = 0, MAX = 60;\n private static final int[] RANGE_STARTS = {0, 30, 35, 40, 45, 50};\n\n private TreeMap&lt;Integer, Integer&gt; rangeCount = new TreeMap&lt;Integer,Integer&gt;();\n private int totalScores = 0, acceptedScores = 0;\n\n public GradeDistribution(){\n for (int s : RANGE_STARTS) {\n rangeCount.put(s, 0);\n }\n }\n\n public void add(int grade) {\n if (grade &lt; MIN || grade &gt; MAX) {\n return;\n }\n\n Map.Entry&lt;Integer,Integer&gt; e = rangeCount.floorEntry(grade);\n rangeCount.put(e.getKey(), e.getValue() + 1);\n\n totalScores++;\n if (e.getKey() &gt; MIN) {\n acceptedScores++;\n }\n }\n\n public void print(){\n int rangeNum = 1;\n for (int count : rangeCount.tailMap(MIN, false).values()) {\n System.out.printf(\"%d: \", rangeNum++);\n for (; count &gt; 0; count--) {\n System.out.print('*');\n }\n System.out.println();\n }\n }\n\n public double getAcceptedPercent(){\n return (100.0 * acceptedScores) / totalScores;\n }\n}\n</code></pre>\n\n<p>There is another further improvements you could consider, though I did not implement it here for the sake of brevity. You could use a mutable type for the map values. If, say the map was of type <code>TreeMap&lt;Integer,WrappedInteger&gt;</code> for a type <code>WrappedInteger</code> that supports an <code>increment</code> operation, we could write <code>e.getValue().increment()</code> instead of the <code>put</code> in the current implementation. This is potentially faster, as it avoids accessing the tree again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T07:57:12.530", "Id": "215172", "ParentId": "215158", "Score": "1" } } ]
{ "AcceptedAnswerId": "215172", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T01:01:15.953", "Id": "215158", "Score": "3", "Tags": [ "java", "statistics", "ascii-art", "data-visualization" ], "Title": "Program which accepts grades and prints grade distribution" }
215158
<p>The gist of the code is, you give it a date, it will start counting down how many days, hours, minutes and seconds left by emitting an event 'countDown' and once 0 is reached 'expired' event is emitted.</p> <p>How can this code be improved?</p> <pre><code>class DateCountDown { listeners: Map&lt;string, Array&lt;Function&gt;&gt;; constructor(date: Date) { this.startCountDown(date); this.listeners = new Map(); this.listeners.set("countDown", []); this.listeners.set("expired", []); } on(eventName: "countDown", listener: (values: CountDownValues) =&gt; void); on(eventName: "expired", listener: (isExpired: boolean) =&gt; void); on(eventName: string, listener: Function) { this.listeners.get(eventName).push(listener); } startCountDown(date: Date) { const thousand = 1000; const sixty = 60; const twentyfour = 24; const timer = setInterval(() =&gt; { const now = new Date().getTime(); const t = date.valueOf() - now; const days = Math.floor(t / (thousand * sixty * sixty * twentyfour)); const hours = Math.floor((t % (thousand * sixty * sixty * twentyfour)) / (thousand * sixty * sixty)); const minutes = Math.floor((t % (thousand * sixty * sixty)) / (thousand * sixty)); const seconds = Math.floor((t % (thousand * sixty)) / thousand); if (t &lt;= 0) { clearInterval(timer); this.listeners.get("expired").forEach(listener =&gt; listener(true)); return; } this.listeners.get("countDown").forEach(listener =&gt; listener(new CountDownValues(days, hours, minutes, seconds)) ); }, 1000); } } class CountDownValues { days: number; hours: number; minutes: number; seconds: number; constructor(days: number, hours: number, minutes: number, seconds: number) { this.days = days; this.hours = hours; this.minutes = minutes; this.seconds = seconds; } } var date = new Date(); date.setSeconds(date.getSeconds() + 20); let countDown = new DateCountDown(date); countDown.on("countDown", values =&gt; { console.log("from first", values); }); countDown.on("expired", isExpired =&gt; { console.log("expired:", isExpired); }); </code></pre>
[]
[ { "body": "<p>First, taking a look at your code as a consumer of your API:</p>\n\n<ol>\n<li><p>I like that the autocomplete for <code>.on(\"</code> shows what events I can listen to.</p></li>\n<li><p>How do I stop listening to an event? If I don't want <code>countDown</code> events anymore then I have to do <code>countDown.listeners.get(\"countDown\")!.splice(index, 1)</code> which is ugly.</p></li>\n<li><p>How do I cancel a countdown?</p></li>\n<li><p>Why is <code>listeners</code> exposed? This is an internal property of your class that I shouldn't need to know about as a consumer. It should be either <code>private</code> or <code>protected</code>. It's also probably worth marking <code>startCountDown</code> as <code>private</code> or <code>protected</code>.</p></li>\n<li><p>Why does the <code>expired</code> event pass an extra parameter, <code>isExpired</code>? If the <code>expired</code> event is fired, doesn't that imply that the countdown is expired?</p></li>\n<li><p>The <code>countDown</code> event is not fired every second. What happened to second 9 and 6?</p>\n\n<p>This is a common problem with timers, and is present in (almost) every JavaScript clock/timer question on this site. There are several possible solutions, the simplest of which is to check the time more frequently. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified\" rel=\"nofollow noreferrer\">MDN notes</a> on it is worth reading.</p>\n\n<p>[![broken countdown ticks][1]][1]</p></li>\n</ol>\n\n<h3>TypeScript specific notes:</h3>\n\n<ol>\n<li><p>Turn on strict null checks. Yesterday. Without it, TypeScript ignores a whole class of errors.</p></li>\n<li><p>Turn on no implicit any. Once turned on this will point out that the <code>on</code> method has a return type of <code>any</code></p></li>\n<li><p>Don't create a class to just hold properties. An interface is fine.</p>\n\n<pre class=\"lang-ts prettyprint-override\"><code>interface CountDownValues {\n days: number;\n hours: number;\n minutes: number;\n seconds: number;\n}\n</code></pre></li>\n<li><p>Consider initializing properties where they are declared when using classes.</p></li>\n</ol>\n\n<h3>Other:</h3>\n\n<ol>\n<li><p><code>new Date().getTime()</code> can be more concisely written as <code>Date.now()</code></p></li>\n<li><p>The <code>thousand</code>, <code>sixty</code>, and <code>twentyfour</code> variables make it harder to read your code. Get rid of them. You can make the code more readable by instead defining <code>day</code>, <code>hour</code>, etc.</p></li>\n<li><p>Countdown is a word, you don't need to capitalize the D.</p></li>\n<li><p>Using a map for events here is probably overkill. There are only two events and they are both known at compile time. I'd just use an object.</p></li>\n<li><p><code>countDown</code> is kind of an odd name for an event, without looking at your code I had no idea when it would be fired. I prefer <code>tick</code>, but there are other good options.</p></li>\n</ol>\n\n<h3>Rewrite:</h3>\n\n<p>I kept the feature set <em>mostly</em> the same, but wanted to add the ability to stop the timer, remove event listeners, and initialize a countdown before starting it. I let this run for ~15 minutes, and it never skipped a second or repeated one twice, which isn't conclusive, but I'm fairly confident it is stable.</p>\n\n<p>Note that instead of firing the <code>tick</code> function multiple times per second, I do some math to figure out how long to wait and then schedule a tick based on that. This results in some more complicated code, but avoids the need to track what the last reported second was.</p>\n\n<pre class=\"lang-ts prettyprint-override\"><code>interface TickEvent {\n days: number;\n hours: number;\n minutes: number;\n seconds: number;\n}\n\ninterface CountdownEvents {\n tick(values: TickEvent): void;\n expired(): void;\n stop(): void;\n}\n\n// Unfortunately we can't use T[K][] without getting messy.\ntype EventMap&lt;T&gt; = { [K in keyof T]: Function[] };\n\nclass Countdown {\n private listeners: EventMap&lt;CountdownEvents&gt; = { tick: [], expired: [], stop: [] };\n private timer?: number;\n\n on&lt;K extends keyof CountdownEvents&gt;(eventName: K, listener: CountdownEvents[K]): void {\n this.listeners[eventName].push(listener);\n }\n\n off&lt;K extends keyof CountdownEvents&gt;(eventName: K, listener: CountdownEvents[K]): void {\n const listeners = this.listeners[eventName];\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n }\n\n start(date: Date) {\n const end = Math.floor(date.getTime() / 1000);\n\n const tick = () =&gt; {\n const now = Date.now();\n const nowSec = Math.floor(now / 1000);\n const time = end - nowSec;\n\n if (time &lt;= 0) {\n delete this.timer;\n this.listeners.expired.forEach(listener =&gt; listener());\n return;\n }\n\n const minute = 60;\n const hour = minute * 60;\n const day = hour * 24;\n\n const days = Math.floor(time / day);\n const hours = Math.floor(time % day / hour);\n const minutes = Math.floor(time % hour / minute);\n const seconds = time % minute;\n\n this.listeners.tick.forEach(listener =&gt; listener({ days, hours, minutes, seconds }));\n\n const timeToNextSecond = (nowSec + 1) * 1000 - now;\n this.timer = setTimeout(tick, timeToNextSecond);\n }\n\n tick();\n }\n\n stop() {\n if (this.timer) {\n clearTimeout(this.timer);\n delete this.timer;\n this.listeners.stop.forEach(listener =&gt; listener());\n }\n }\n}\n\nconst countdown = new Countdown();\ncountdown.on(\"tick\", event =&gt; console.log(\"tick\", event));\ncountdown.on(\"expired\", () =&gt; console.log(\"expired\"));\ncountdown.on(\"stop\", () =&gt; console.log(\"stopped\"));\n\nconst date = new Date();\ndate.setSeconds(date.getSeconds() + 20);\ncountdown.start(date);\n\nsetTimeout(() =&gt; countdown.stop(), 3 * 1000);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T03:36:11.700", "Id": "416764", "Score": "0", "body": "Perfect, will use ur rewrite and follow all the notes going forward for ts development. Thanks again for taking the time to write such a detailed reply/review" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T05:05:37.050", "Id": "215317", "ParentId": "215161", "Score": "2" } } ]
{ "AcceptedAnswerId": "215317", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T01:33:18.613", "Id": "215161", "Score": "3", "Tags": [ "timer", "typescript" ], "Title": "A countdown clock in TypeScript" }
215161
<p>This is my practice program: a simple dialog box using which a user may specify a frequency of a sinus audio signal, and play it via pressing a button. It contains a GUI:</p> <p><strong>App.java</strong></p> <pre><code>package net.coderodde.fun; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import net.coderodde.os.beep.Beep; import net.coderodde.os.beep.WindowsBeep; /** * This class implements a simple program for generating sinus audio signal. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 10, 2019) */ public final class App extends Application { private final Beep BEEP = new WindowsBeep(); static { try { System.loadLibrary("WinBeepDLLx64"); } catch (UnsatisfiedLinkError error) { error.printStackTrace(); System.exit(1); } } @Override public void start(Stage stage) throws Exception { Text textFrequency = new Text("Frequency (Hz)"); TextField frequencyField = new TextField(); Button playButton = new Button("Play"); VBox vbox = new VBox(textFrequency, frequencyField, playButton); playButton.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent t) { String frequencyInput = frequencyField.getText(); BEEP.setDuration(1000); try { int hz = Integer.parseInt(frequencyInput); BEEP.setFrequency(hz); if (hz &lt;= 0) { Alert alert = new Alert( AlertType.INFORMATION, "Frequency must be at least 1."); alert.showAndWait(); } else { BEEP.beep(); } } catch (NumberFormatException ex) { Alert alert = new Alert( AlertType.ERROR, frequencyInput + " is not an integer."); alert.showAndWait(); } } }); Scene scene = new Scene(vbox); stage.setTitle("Generate sinus audio"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } </code></pre> <p><strong>Beep.java</strong></p> <pre><code>package net.coderodde.os.beep; /** * This interface provides facilities for generating a simple sinus audio * signal. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 10, 2019) */ public interface Beep { /** * Returns the beep duration in milliseconds. * * @return the beep duration in milliseconds. */ public int getDuration(); /** * Returns the beep frequency in milliseconds. * * @return the beep frequency in milliseconds. */ public int getFrequency(); /** * Sets the beep duration. * * @param milliseconds the new beep duration in milliseconds. */ public void setDuration(int milliseconds); /** * Sets the beep frequency. * * @param frequency the new beep frequency in milliseconds. */ public void setFrequency(int frequency); /** * Produce the bee signal. */ public void beep(); } </code></pre> <p><strong>WindowsBeep.java</strong></p> <pre><code>package net.coderodde.os.beep; /** * This class implements the beeping functionality on Windows platform. * * @author Rodion "rodde" Efremov * @version 1.6 */ public final class WindowsBeep implements Beep { /** * The duration of a beep in milliseconds. */ private int beepDuration; /** * The frequency of a beep in hertzes. */ private int beepFrequency; @Override public int getDuration() { return beepDuration; } @Override public int getFrequency() { return beepFrequency; } @Override public void setDuration(int milliseconds) { this.beepDuration = milliseconds; } @Override public void setFrequency(int frequency) { this.beepFrequency = frequency; } @Override public native void beep(); } </code></pre> <p><strong>WinBeep.cpp</strong></p> <pre><code>#include "WinBeep.h" #include &lt;windows.h&gt; #include &lt;jni.h&gt; static const char* CLASS = "net/coderodde/os/beep/WindowsBeep"; static const char* FIELD_DURATION = "beepDuration"; static const char* FIELD_FREQUENCY = "beepFrequency"; static DWORD get_duration(JNIEnv* env, jobject obj) { jclass clazz = env-&gt;FindClass(CLASS); jfieldID fid = env-&gt;GetFieldID(clazz, FIELD_DURATION, "I"); return (DWORD) env-&gt;GetIntField(obj, fid); } static DWORD get_frequency(JNIEnv* env, jobject obj) { jclass clazz = env-&gt;FindClass(CLASS); jfieldID fid = env-&gt;GetFieldID(clazz, FIELD_FREQUENCY, "I"); return (DWORD) env-&gt;GetIntField(obj, fid); } JNIEXPORT void JNICALL Java_net_coderodde_os_beep_WindowsBeep_beep(JNIEnv* env, jobject obj) { DWORD dwFrequency = get_frequency(env, obj); DWORD dwDuration = get_duration(env, obj); Beep(dwFrequency, dwDuration); } </code></pre> <p>(The other DLL code is <a href="https://github.com/coderodde/WinBeepDLL" rel="nofollow noreferrer">here</a>.)</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T07:11:17.123", "Id": "215170", "Score": "1", "Tags": [ "java", "windows", "javafx", "jni", "audio" ], "Title": "A JavaFX for generating beeping sound on Windows via JNI" }
215170
<p>I have a listview of <code>PrivateFile</code> objects which contain the <code>fileId (int)</code>, <code>fileName (String)</code> and the <code>fileContent (byte [])</code>. In order to share the file, I currently save the file first, open it again, and then I share it. In my opinion this is really semi-professional. Is there a way wherein I can only share the file (content)/byte array without saving it before? Or can I improve my code in general?</p> <pre><code>privateDocs.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView&lt;?&gt; arg0, View arg1, int pos, long id) { try { PrivateFile selFile = (PrivateFile) arg0.getItemAtPosition(pos); File folder = new File(Environment.getExternalStorageDirectory() + "/myFolder"); boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } if (success) { //safe file in order to open it later File file = new File(folder.getAbsolutePath() + "/" + selFile.getFileName()); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); fos.write(selFile.getFileContent()); fos.close(); Intent intentShareFile = new Intent(Intent.ACTION_SEND); if(file.exists()) { String newMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString())); intentShareFile.setType(newMimeType); intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath())); intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing File..."); intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File..."); startActivity(Intent.createChooser(intentShareFile, "Share File")); } } else { throw new Exception("could not open folder"); } } catch (Exception ex) { System.out.println("Err:" + ex.getMessage()); } return true; } }); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T08:17:48.810", "Id": "215173", "Score": "2", "Tags": [ "java", "performance", "android", "file" ], "Title": "Sharing File (Content) without saving it before" }
215173
<p>I am trying to find a best match for a name within a list of names.</p> <p>I came up with the below code, which works, but I feel that the creation of the intermediate <code>ratios</code> list is not the best solution performance-wise.</p> <p>Could it be somehow replaced? Would <code>reduce</code> be a good fit here (I have tried it, but could not get the index of best match and its value at the same time).</p> <pre><code>from fuzzywuzzy import fuzz name_to_match = 'john' names = ['mike', 'james', 'jon', 'jhn', 'jimmy', 'john'] ratios = [fuzz.ratio(name_to_match, name) for name in names] best_match = names[ratios.index(max(ratios))] print(best_match) # output is 'john' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T08:43:09.420", "Id": "416084", "Score": "2", "body": "Someone else asked about this on stack overflow once before, and I suggested they try downloading [python-levenshtein](https://github.com/ztane/python-Levenshtein/) since the github page suggests it may speed up execution by 4-10x. They later confirmed that it did in fact speed up their solution, so you may want to try that as well." } ]
[ { "body": "<p>You should take advantage of <a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"noreferrer\">the <code>key</code> argument to <code>max()</code></a>:</p>\n\n<blockquote>\n <p>The <em>key</em> argument specifies a one-argument ordering function like that used for <a href=\"https://docs.python.org/3/library/stdtypes.html#list.sort\" rel=\"noreferrer\"><code>list.sort()</code></a>.</p>\n</blockquote>\n\n<pre><code>best_match = max(names, key=lambda name: fuzz.ratio(name_to_match, name))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T08:46:38.597", "Id": "215176", "ParentId": "215174", "Score": "7" } }, { "body": "<p>fuzzywuzzy <a href=\"https://github.com/seatgeek/fuzzywuzzy#Process\" rel=\"nofollow noreferrer\">already includes functionality</a> to return only the best match. unless you need it sorted like 200_success's solution, this would be the easiest:</p>\n\n<pre><code>from fuzzywuzzy import process\nchoices = [\"Atlanta Falcons\", \"New York Jets\", \"New York Giants\", \"Dallas Cowboys\"]\nprocess.extractOne(\"cowboys\", choices)\n# returns (\"Dallas Cowboys\", 90)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T08:11:37.637", "Id": "215240", "ParentId": "215174", "Score": "2" } } ]
{ "AcceptedAnswerId": "215176", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T08:33:52.020", "Id": "215174", "Score": "6", "Tags": [ "python", "performance", "strings", "search", "edit-distance" ], "Title": "Find a best fuzzy match for a string" }
215174
<p>My code get data from database using AJAX the problem is i want to filter data by month year and quarter and the code that does that is:</p> <pre><code>-&gt;where(\DB::raw('MONTH(created_at)'), Carbon::today()-&gt;month); </code></pre> <p>However can't put it in a variable for example and call it so i did this it works but looks ugly.</p> <p>I have this code in <code>DashboardController</code>:</p> <pre><code>public function readData(){ $TableB1 = \DB::table('users') -&gt;join('group_user', 'users.id', '=', 'group_user.user_id') -&gt;join('groups', 'groups.id', '=', 'group_user.group_id') -&gt;select( 'users.name as name', 'group_user.user_id as id', 'groups.name as groupname' ) -&gt;get(); $filter = $_REQUEST["filter"]; // Get the variable data through AJAX call from the index foreach ($TableB1 as &amp;$entry){ if ($filter == 'month'){ // Filter data by month $meetings = \DB::table('meetings') -&gt;where('company_id', 1)-&gt;where('owned_by_id', $entry-&gt;id) -&gt;where(\DB::raw('MONTH(created_at)'), Carbon::today()-&gt;month); } else if ($filter == 'quarter'){ // Filter data by quarter $meetings = \DB::table('meetings') -&gt;where('company_id', 1)-&gt;where('owned_by_id', $entry-&gt;id) -&gt;where(\DB::raw('QUARTER(created_at)'), Carbon::today()-&gt;quarter); } else if ($filter == 'year'){ // Filter data by year $meetings = \DB::table('meetings') -&gt;where('company_id', 1)-&gt;where('owned_by_id', $entry-&gt;id) -&gt;where(\DB::raw('YEAR(created_at)'), Carbon::today()-&gt;year); } else { // Filter data by day $meetings = \DB::table('meetings') -&gt;where('company_id', 1)-&gt;where('owned_by_id', $entry-&gt;id) -&gt;where(\DB::raw('DAY(created_at)'), Carbon::today()-&gt;day); } $entry-&gt;meetingsCount = $meetings-&gt;count(); } return $TableB1; } </code></pre> <p>In <code>index.blade.php</code> I have this code to retrieve the data using ajax:</p> <pre><code>var filter = 'day'; $(document).ready(function(){ $.get('/dashboard/read?filter=' + filter, function(data){ $.each(data,function(i,value){ var tr =$("&lt;tr/&gt;"); tr.append($("&lt;th/&gt;",{ text : value.groupname })).append($("&lt;th/&gt;",{ text : value.name })).append($("&lt;th/&gt;",{ text : value.meetingsCount })).append($("&lt;th/&gt;",{ text : value.callsCount })).append($("&lt;th/&gt;",{ text : value.leadsCount })) $('#tableData').append(tr); }) }) $("#day").click(function() { // Filter data by day filter = 'day'; $('#tableData').find('tr').empty(); // Clear Table 1st $.get('/dashboard/read?filter=' + filter, function(data){ $.each(data,function(i,value){ var tr =$("&lt;tr/&gt;"); tr.append($("&lt;th/&gt;",{ text : value.groupname })).append($("&lt;th/&gt;",{ text : value.name })).append($("&lt;th/&gt;",{ text : value.meetingsCount })).append($("&lt;th/&gt;",{ text : value.callsCount })).append($("&lt;th/&gt;",{ text : value.leadsCount })) $('#tableData').append(tr); }) }) }); $("#month").click(function() { //Filter data by month $('#tableData').find('tr').empty(); // Clear Table 1st filter = 'month'; $.get('/dashboard/read?filter=' + filter, function(data){ $.each(data,function(i,value){ var tr =$("&lt;tr/&gt;"); tr.append($("&lt;th/&gt;",{ text : value.groupname })).append($("&lt;th/&gt;",{ text : value.name })).append($("&lt;th/&gt;",{ text : value.meetingsCount })).append($("&lt;th/&gt;",{ text : value.callsCount })).append($("&lt;th/&gt;",{ text : value.leadsCount })) $('#tableData').append(tr); }) }) }); $("#quarter").click(function() { //Filter data by quarter filter = 'quarter'; $('#tableData').find('tr').empty(); // Clear Table 1st $.get('/dashboard/read?filter=' + filter, function(data){ $.each(data,function(i,value){ var tr =$("&lt;tr/&gt;"); tr.append($("&lt;th/&gt;",{ text : value.groupname })).append($("&lt;th/&gt;",{ text : value.name })).append($("&lt;th/&gt;",{ text : value.meetingsCount })).append($("&lt;th/&gt;",{ text : value.callsCount })).append($("&lt;th/&gt;",{ text : value.leadsCount })) $('#tableData').append(tr); }) }) }); $("#year").click(function() { //Filter data by year filter = 'year'; $('#tableData').find('tr').empty(); // Clear Table 1st $.get('/dashboard/read?filter=' + filter, function(data){ $.each(data,function(i,value){ var tr =$("&lt;tr/&gt;"); tr.append($("&lt;th/&gt;",{ text : value.groupname })).append($("&lt;th/&gt;",{ text : value.name })).append($("&lt;th/&gt;",{ text : value.meetingsCount })).append($("&lt;th/&gt;",{ text : value.callsCount })).append($("&lt;th/&gt;",{ text : value.leadsCount })) $('#tableData').append(tr); }) }) }); </code></pre> <p>I know its a mess but how to refactor this code to make it look a little bit nicer the code works but looks awful.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:45:19.670", "Id": "416096", "Score": "0", "body": "Do you have Eloquent models set up for your tables i.e. `User` and `Group`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:04:09.270", "Id": "416099", "Score": "0", "body": "No i don't have Eloquent for them" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:59:46.510", "Id": "416104", "Score": "0", "body": "@user194899 Are you opposed to using Eloquent in this scenario?" } ]
[ { "body": "<p>Firstly, don't use php's super globals with Laravel. For the most part you can use the <a href=\"https://laravel.com/docs/5.8/requests\" rel=\"nofollow noreferrer\">Request</a> class for this. With most things in Laravel, the <code>Request</code> can be accessed in multiple different ways including <a href=\"https://laravel.com/docs/5.8/controllers#dependency-injection-and-controllers\" rel=\"nofollow noreferrer\">injection</a> (where it is resolved from the <a href=\"https://laravel.com/docs/5.8/container#resolving\" rel=\"nofollow noreferrer\">service container</a>), <a href=\"https://laravel.com/docs/5.8/facades\" rel=\"nofollow noreferrer\">facades</a> and <a href=\"https://laravel.com/docs/5.8/helpers#method-request\" rel=\"nofollow noreferrer\">helper functions</a>. For this example I'll use the request helper function:</p>\n\n<pre><code>$filter = request()-&gt;input('filter'); \n</code></pre>\n\n<p>*You could also do <code>request('filter')</code> but for some params this could cause an issue.</p>\n\n<hr>\n\n<p>As for you query I would strongly recommend using <a href=\"https://laravel.com/docs/5.8/eloquent\" rel=\"nofollow noreferrer\">Eloquent</a> instead of the query builder in this case. </p>\n\n<p>You should already have a <code>User</code> model in your app directory so you should just need to create the <code>Group</code> and <code>Meeting</code> models. You can run the following command to do this:</p>\n\n<pre><code>php artisan make:model Group &amp;&amp; php artisan make:model Meeting\n</code></pre>\n\n<p>Then add the following to your <code>User</code> model:</p>\n\n<pre><code>public function meetings()\n{\n return $this-&gt;hasMany(Meeting::class, 'owned_by_id');\n}\n\npublic function groups()\n{\n return $this-&gt;belongsToMany(Group::class);\n}\n</code></pre>\n\n<p>and add the following to your <code>Group</code> model:</p>\n\n<pre><code>public function users()\n{\n return $this-&gt;belongsToMany(User::class);\n}\n</code></pre>\n\n<p>finally, you don't need to do this yet but in your <code>Meeting</code> model:</p>\n\n<pre><code>public function user()\n{\n return $this-&gt;belongsTo(User::class, 'owned_by_id');\n}\n</code></pre>\n\n<hr>\n\n<p>The above will allow you to have a controller method looking something like:</p>\n\n<pre><code>public function readData()\n{\n $filter = request()-&gt;input('filter');\n\n return \\App\\User::with('groups')-&gt;withCount(['meetings' =&gt; function ($query) use ($filter) {\n\n $filter = in_array($filter, ['month', 'quarter', 'year']) ? $filter : 'day';\n\n $query-&gt;where('company_id', 1)-&gt;whereRaw(\"$filter(created_at)\", today()-&gt;$filter);\n }]);\n}\n</code></pre>\n\n<p><code>groupname</code> will now be available as <code>group-&gt;name</code> and the count will be available as <code>meetings_count</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T11:15:28.993", "Id": "215188", "ParentId": "215177", "Score": "1" } } ]
{ "AcceptedAnswerId": "215188", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T09:23:00.040", "Id": "215177", "Score": "2", "Tags": [ "javascript", "php", "laravel" ], "Title": "My code get data from database using AJAX and return to view" }
215177
<p>This code will take as output any string (long, empty, with spaces...) and will return its reverse. Can I improve this algorithm so that it can be faster? </p> <p>Right now its complexity is <span class="math-container">\$O(n)\$</span>.</p> <pre><code>def reverse(stri): output = '' length = len(stri) while length &gt; 0: output += stri[-1] stri, length = (stri[0:length - 1], length - 1) return output </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:01:50.357", "Id": "416120", "Score": "12", "body": "I'd say your code is `O(n**2)` because it creates at least n strings with length between `1` and `n`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:26:00.933", "Id": "416126", "Score": "1", "body": "I think you're right, since I didn't take into account the immutability of strings in python, but the graph of @Graipher shows something similar to O(nlgn) complexity for my code, I don't know I'm a bit confused..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:27:39.537", "Id": "416127", "Score": "1", "body": "Depending on how large the string is and what you want to do with it, it might be a good idea to create a lazy `ReverseString` class, which only accesses the data when needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:16:32.213", "Id": "416134", "Score": "3", "body": "@Midos That might be due to the Python implementation used. AFAIK, cPython *does* sometimes manage to reuse one of the two strings (i.e. it tries to reserve enough space after/before one of the two strings and needs to copy only one string, but don't quote me on that). However, that is both implementation dependent and potentially dependent on the available memory, which is why Python's official style-guide recommends not relying on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T20:36:46.953", "Id": "416361", "Score": "0", "body": "@Midos I recommend having a look at my answer now. It shows how you can speed things up with C functions that you call from Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T03:40:53.963", "Id": "416396", "Score": "1", "body": "@Graipher I can't find it now, but I think the docs once said that it running in linear time is a CPython implementation detail. All I can find now is that strings are 100% immutable. [1](https://docs.python.org/3/glossary.html#term-immutable) [2](https://docs.python.org/3.7/reference/datamodel.html) [3](https://docs.python.org/3/library/stdtypes.html#textseq) [4](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations) (note 6 talks about this very usecase)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T06:21:37.677", "Id": "416404", "Score": "0", "body": "@Peilonrayz It's in PEP8 actually, see first link in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T09:46:06.500", "Id": "416437", "Score": "0", "body": "@Graipher That's exactly what I was on about, how funny" } ]
[ { "body": "<p>Yes, this can be faster. Adding strings using <code>+</code> is usually a bad idea in Python, since strings are immutable. This means that whenever you add two strings, a new string needs to be allocated with the size of the resulting strings and then both string contents need to be copied there. Even worse is doing so in a loop, because this has to happen ever time. <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">Instead you usually want to build a list of strings and <code>''.join</code> them at the end</a> (where you pay this cost only once).</p>\n\n<p>But here you can just use the fact that strings can be sliced and you can specify a negative step:</p>\n\n<pre><code>def reverse_g(s):\n return s[::-1]\n</code></pre>\n\n<p>Here is a timing comparison for random strings of length from one up to 1M characters, where <code>reverse</code> is your function and <code>reverse_g</code> is this one using slicing. Note the double-log scale, for the largest string your function is almost a hundred thousand times slower.</p>\n\n<p><a href=\"https://i.stack.imgur.com/6S3ds.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6S3ds.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>The <code>reverse_s</code> function uses the <code>reversed</code> built-in, as suggested in the (now deleted, so 10k+ reputation) <a href=\"https://codereview.stackexchange.com/a/215230/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/26266/sleblanc\">@sleblanc</a> and assumes you actually need the reversed string and not just an iterator over it:</p>\n\n<pre><code>def reverse_s(s):\n return ''.join(reversed(s))\n</code></pre>\n\n<hr>\n\n<p>The <code>reverse_b</code> function uses the C implementation, compiled with <code>-O3</code>, provided in the <a href=\"https://codereview.stackexchange.com/a/215235/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/133688/broman\">@Broman</a>, with a wrapper to create the string buffers and extract the output:</p>\n\n<pre><code>from ctypes import *\n\nrevlib = cdll.LoadLibrary(\"rev.so\")\n_reverse_b = revlib.reverse\n_reverse_b.argtypes = [c_char_p, c_char_p, c_size_t]\n\ndef reverse_b(s):\n stri = create_string_buffer(s.encode('utf-8'))\n stro = create_string_buffer(b'\\000' * (len(s)+1))\n _reverse_b(stro, stri, len(s) - 1)\n return stro.value.decode()\n</code></pre>\n\n<p>In the no interface version, just the call to <code>_reverse_b</code> is timed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:23:23.917", "Id": "416125", "Score": "3", "body": "How did you measure the uncertainty bars, is the drop in processing time with increasing string length near length 10 for `reverse_g` significant and if so why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:55:15.387", "Id": "416129", "Score": "3", "body": "@gerrit: The uncertainty bars come from the fact that each timing measurement is performed three times, so the value is the mean and the uncertainty the uncertainty of the mean (i.e. standard deviation / sqrt(n)). So I would doubt that the drop is significant. Sometimes you get large increases due to some other activity on the machine, so that is what could have happened in the first case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T02:17:56.033", "Id": "416216", "Score": "3", "body": "Data is code and code is data. Ponder why you might want to reverse the string, and consider instead to use an iterator that simply reads the string backwards. This is essentially what this answer is, while the actual implementation the iterator is buried inside CPython's internals. Nice answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T03:42:52.083", "Id": "416220", "Score": "3", "body": "_Adding strings using + is usually a bad idea in Python, since strings are immutable._ Immutability (and the use of Python) isn't what matters here; in nearly every case, string addition requires iterating over at least one of the strings. A pre-allocated, mutable C-string concatenation still requires linear time to copy the contents of the second string into the tail of the first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T09:59:50.300", "Id": "416243", "Score": "0", "body": "Which function is `reverse_g()`? You have `reverse()` and `reverse_s()` on your code, and the question just has `reverse()` as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T10:14:58.960", "Id": "416246", "Score": "1", "body": "@IsmaelMiguel: As mentioned in the text `reverse_g` is the function with the slicing, i.e. the one in the answer. Renamed it so it is the correct name now, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:15:59.660", "Id": "416306", "Score": "0", "body": "Having time/input on the left axis (and adjusting its scaling if needed) might be even better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:26:08.310", "Id": "416310", "Score": "1", "body": "@Deduplicator: That might show off the differences better, but I am usually also interested in the overall running time of an algorithm. It is also less generally useful (because I do need these timing plots quite often and the inputs are quite diverse). In this case it looks interesting, though: https://i.stack.imgur.com/RlEym.png (ignore the ylabel, it should be \"Time / len(s)\", I did not change it)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T18:48:52.143", "Id": "416344", "Score": "1", "body": "Keep in mind that graph is LOGARITHMIC when trying to see exactly how much faster the orange line is than the blue (or even green, which is already substantially improved.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T19:35:06.570", "Id": "416350", "Score": "0", "body": "@corsiKa Thanks for reminding me to check the wording again. In an earlier version the plot only went to 10^5, where the ratio was about a thousand, but at 10^6 this grows to about a hundred thousand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T20:28:12.447", "Id": "416359", "Score": "0", "body": "@Graipher I posted an answer below. If you have the time and energy, you could update the benchmark graph with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T20:29:01.817", "Id": "416360", "Score": "0", "body": "@Broman I'll see if I manage to include it tomorrow." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:11:41.103", "Id": "215181", "ParentId": "215179", "Score": "52" } }, { "body": "<p>In terms of pure complexity, the answer is simple: No, it is not possible to reverse a string faster than O(n). That is the theoretical limit when you look at the pure algorithm.</p>\n\n<p>However, your code does not achieve that because the operations in the loop are not O(1). For instance, <code>output += stri[-1]</code> does not do what you think it does. Python is a very high level language that does a lot of strange things under the hood compared to languages such as C. Strings are immutable in Python, which means that each time this line is executed, a completely <em>new</em> string is created.</p>\n\n<p>If you really need the speed, you could consider writing a C function and call it from Python. Here is an example:</p>\n\n<p>rev.c:</p>\n\n<pre><code>#include &lt;stddef.h&gt;\nvoid reverse(char * stro, char * stri, size_t length) {\n for(size_t i=0; i&lt;length; i++) stro[i]=stri[length-1-i];\n stro[length]='\\0';\n}\n</code></pre>\n\n<p>Compile the above function with this command:</p>\n\n<pre><code>gcc -o rev.so -shared -fPIC rev.c\n</code></pre>\n\n<p>And here is a python script using that function.</p>\n\n<p>rev.py:</p>\n\n<pre><code>from ctypes import *\n\nrevlib = cdll.LoadLibrary(\"rev.so\");\nreverse = revlib.reverse\nreverse.argtypes = [c_char_p, c_char_p, c_size_t]\n\nhello = \"HelloWorld\"\nstri = create_string_buffer(hello)\nstro = create_string_buffer(b'\\000' * (len(hello)+1))\n\nreverse(stro, stri, len(stri)-1)\n\nprint(repr(stri.value))\nprint(repr(stro.value))\n</code></pre>\n\n<p>Please note that I'm by no means an expert on this. I tested this with string of length 10⁸, and I tried the method from Graipher, calling the C function from Python and calling the C function from C. I used <code>-O3</code> optimization. When I did not use any optimization it was slower to call the C function from Python. Also note that I did NOT include the time it took to create the buffers.</p>\n\n<pre><code>stri[::-1] : 0.98s\ncalling reverse from python : 0.59s\ncalling reverse from c: 0.06s\n</code></pre>\n\n<p>It's not a huge improvement, but it is an improvement. But the pure C program was WAY faster. The main function I used was this one:</p>\n\n<pre><code>int __attribute__((optimize(\"0\"))) // Disable optimization for main\nmain(int argc, char ** argv) { // so that reverse is not inlined\n\n const size_t size = 1e9;\n char * str = malloc(size+1);\n\n static const char alphanum[] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n // Take data from outside the program to fool the optimizer \n alphanum[atoi(argv[1])]='7';\n\n // Load string with random data to fool the optimizer \n srand(time(NULL));\n for (size_t i = 0; i &lt; size; ++i) {\n str[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n }\n\n char *o = malloc(size+1);\n reverse(o, str, strlen(str));\n\n // Do something with the data to fool the optimizer \n for(size_t i=0; i&lt;size; i++) \n if(str[i] != o[size-i-1]) {\n printf(\"Error\\n\");\n exit(1);\n }\n}\n</code></pre>\n\n<p>Then, to get the runtime I ran:</p>\n\n<pre><code>gcc -O3 -pg rev.c; ./a.out; gprof a.out gmon.out | head -n8\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T08:47:04.393", "Id": "416424", "Score": "0", "body": "Added the timings to the plot. To be a fair competition I included the time of the wrapper function (since if you want to use the function in Python you want it to accept normal strings and return a normal string). I also had to modify the creation of the input buffer to include an encoding, otherwise it was giving me `TypeError`s. I compiled the runtime with `-O3`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T09:05:04.877", "Id": "416429", "Score": "0", "body": "@Graipher I was unsure if I should include the buffer creation or not. One can think of many circumstances where you continue to work on the same buffer and perform more operations. Maybe the most fair thing to do would be to do one with and one without." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T09:07:24.573", "Id": "416430", "Score": "0", "body": "@Broman: To be honest, part of including it was so that getting and plotting the timings is easier, since all functions have the same interface, which let's me use a function for that. But I'll see what I can do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T09:11:13.707", "Id": "416431", "Score": "0", "body": "@Graipher Well, of course it's completely up to you. I'm just discussing it. Don't feel that you have to do it. But if you do it, it would be interesting to see what happens if you stretch to 10⁸ elements. Don't go to 10⁹ unless you have endless amount of memory. I could not go above 10⁸ before it started to swap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T09:19:18.733", "Id": "416432", "Score": "0", "body": "And btw, I really understand if you don't want to try OP:s code on 10⁸ :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T09:30:53.947", "Id": "416433", "Score": "0", "body": "@Broman: :D Yeah. Anyway, already at about 10^4, the pure C code, with just the calling of the C function included in the timing, is faster than letting Python call it's C function implementation of `s[::-1]` (plot updated). Python seems to be doing some interesting stuff for shortish strings, though, since there it beats your implementation by a factor of five or so." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T06:43:07.603", "Id": "215235", "ParentId": "215179", "Score": "14" } } ]
{ "AcceptedAnswerId": "215181", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:01:06.420", "Id": "215179", "Score": "20", "Tags": [ "python", "performance", "strings" ], "Title": "String reversal in Python" }
215179
<p>I am doing a code challenge of codesignal.com which ask for following things: Given an array of integers, sort its elements by the difference of their largest and smallest digits. In the case of a tie, that with the larger index in the array should come first.</p> <p>Example</p> <pre><code>For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152]. </code></pre> <p>Here are the differences of all the numbers:</p> <pre><code>152: difference = 5 - 1 = 4; 23: difference = 3 - 2 = 1; 7: difference = 7 - 7 = 0; 887: difference = 8 - 7 = 1; 243: difference = 4 - 2 = 2. </code></pre> <p>23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first. I wrote following code using <strong>python3</strong> and <em>it passes all normal tests but it cannot pass execution time tests.</em> <strong>How can I improve my code to decrease it's execution time for list with considerable amount of elements?</strong></p> <pre><code>def digitDifferenceSort(a): diff = [] for i in a: i = list(str(i)) diff.append(i) for i in range(len(diff)): for j in range(i+1, len(diff)): if int(max(diff[i])) - int(min(diff[i])) &gt; int(max(diff[j])) - int(min(diff[j])): diff[j], diff[i] = diff[i], diff[j] elif int(max(diff[i])) - int(min(diff[i])) == int(max(diff[j])) - int(min(diff[j])): diff[i], diff[j] = diff[j], diff[i] new_list = [] for i in diff: b = '' for j in i: b = b + j new_list.append(int(b)) return new_list </code></pre>
[]
[ { "body": "<p>Python has a built-in <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"noreferrer\"><code>sorted</code></a> function, you should use it. What it needs to sort according to some special criteria is a <code>key</code> function:</p>\n\n<pre><code>def max_digit_diff(n):\n n_str = str(n)\n return int(max(n_str)) - int(min(n_str))\n</code></pre>\n\n<p>This uses the fact that <code>\"0\" &lt; \"1\" &lt; ... &lt; \"9\"</code>.</p>\n\n<p>However, the <code>sorted</code> function uses a stable sorting algorithm, so if two elements compare equal, the original order is preserved. But here we want the opposite order (later elements come first), so we just reverse the list first:</p>\n\n<pre><code>def digit_difference_sort(a):\n return sorted(reversed(a), key=max_digit_diff)\n</code></pre>\n\n<p>This should be vastly easier to read than your convoluted function. Note that the function names also follow Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>.</p>\n\n<p>Like all (good) sorting functions, this is <span class=\"math-container\">\\$\\mathcal{O}(n \\log n)\\$</span>. Here is a timing comparison to your function with arrays up to length 10k (at which point your function takes more than a minute...).</p>\n\n<p><a href=\"https://i.stack.imgur.com/L2ydw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/L2ydw.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Here is an implementation of the radix sort suggested by <a href=\"https://codereview.stackexchange.com/users/121394/jollyjoker\">@JollyJoker</a> in <a href=\"https://codereview.stackexchange.com/a/215197/98493\">their answer</a>:</p>\n\n<pre><code>from itertools import chain\n\ndef radix_sort(a):\n sub_a = [[] for _ in range(10)]\n for x in a:\n sub_a[max_digit_diff(x)].append(x)\n return list(chain.from_iterable(reversed(x) for x in sub_a))\n</code></pre>\n\n<p>This seems to have the same complexity as my approach, probably the implementation of <code>max_digit_diff</code> actually dominates this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ipPV2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ipPV2.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:57:58.903", "Id": "416103", "Score": "0", "body": "Thanks a lot. Would you please give more clarification about passing max_digit_diff method as a parameter to sorted function and how this part works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T11:00:30.140", "Id": "416105", "Score": "1", "body": "@IbrahimRahimi: `sorted` calls the function you specify as a `key` exactly once for each input and sorts according to that. Have a look at the official [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html#key-functions) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T12:30:53.707", "Id": "416117", "Score": "1", "body": "Nice answer. Just curious, How did you generate the comparison graph? is there a package for doing it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:56:46.293", "Id": "416130", "Score": "1", "body": "@gustavovelascoh: It is basically done with the code in my question [here](https://codereview.stackexchange.com/questions/165245/plot-timings-for-a-range-of-inputs), with some input from the answers. One of these days I will finally make it look pretty and upload it to github..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:30:07.690", "Id": "215183", "ParentId": "215180", "Score": "14" } }, { "body": "<p>You can do better than <span class=\"math-container\">\\$\\mathcal{O}(n \\log n)\\$</span> using a <a href=\"https://en.wikipedia.org/wiki/Radix_sort\" rel=\"nofollow noreferrer\">Radix sort</a>.</p>\n\n<p>The differences can only have values 0-9, so you can sort the original array into a list of 10 lists while just going through the array once. Then, for each list 0-9, <code>pop()</code> the values into an output list until the list is empty.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:30:48.353", "Id": "416135", "Score": "0", "body": "Added an implementation of this to my answer and included it in the timings. Interestingly it is exactly the same as using the built-in `sorted`. Probably due to the fact that both use `max_digit_diff`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:02:46.550", "Id": "416139", "Score": "0", "body": "@Graipher The scaling seems odd. Could you add some timing check before the return row just to check there's nothing slow in the last line? Then again, maybe `sorted` just is that good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:18:38.233", "Id": "416142", "Score": "0", "body": "Weirdly, it looks exactly the same when directly returning `sub_a`. Also, `max_digit_diff` is basically constant time, obviously, since even the longest numbers have only a few digits (less than a hundred)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:27:11.037", "Id": "416144", "Score": "0", "body": "I also tried arrays with up to 10k elements, still the same (without the OPs algorithm, obviously)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:28:28.910", "Id": "416146", "Score": "0", "body": "Since there are only ten distinct possible values for the digit difference, organizing the array into runs is very efficient (https://en.wikipedia.org/wiki/Timsort#Operation), so I think Python's timsort basically performs partial radix sort as a first step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:48:51.693", "Id": "416150", "Score": "1", "body": "@Graipher You're probably right on Timsort. BTW, good job on turning my answer into actual code :) I wasn't at all certain my text was clear enough." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:11:43.523", "Id": "215197", "ParentId": "215180", "Score": "3" } } ]
{ "AcceptedAnswerId": "215183", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T10:01:43.017", "Id": "215180", "Score": "9", "Tags": [ "python", "python-3.x", "time-limit-exceeded" ], "Title": "List elements digit difference sort" }
215180
<p>I'm trying to get familiar with unit testing. I never implement TDD previously, but I believe it's the best way to write software.</p> <p>So, here I'm trying to test my <code>isLastTwoDates(position)</code> method of my model class:</p> <pre><code>package se.abccompany.models; import org.joda.time.DateTimeZone; import org.joda.time.tz.UTCProvider; import org.junit.Before; import org.junit.Test; import models.Traktamente; import static com.google.common.truth.Truth.assertThat; public class TraktamenteTest { private static final String ORIGIN = "Stockholm"; private static final String DESTINATION = "Goteborg"; private static final String COMMENTS = "Lorem ipsum dolor sit amet."; private final int CASE_1_REPORT_COUNT = 6; private final int CASE_2_REPORT_COUNT = 7; private final int CASE_3_REPORT_COUNT = 14; private final int CASE_4_REPORT_COUNT = 12; private final int CASE_5_REPORT_COUNT = 12; private final int CASE_6_REPORT_COUNT = 16; private Traktamente case1; private Traktamente case2; private Traktamente case3; private Traktamente case4; private Traktamente case5; private Traktamente case6; @Before public void setupOnce() { case1 = new Traktamente(); case1.startTime = "13:00"; case1.startDate = "2019-01-07"; // Måndag case1.endTime = "21:00"; case1.endDate = "2019-01-10"; // Torsdag case1.origin = ORIGIN; case1.destination = DESTINATION; case1.switchEgetBoendeState = true; case1.switchNinetyDaysState = true; case1.comments = COMMENTS; case2 = new Traktamente(); case2.startTime = "20:00"; case2.startDate = "2019-01-06"; // Söndag case2.endTime = "21:00"; case2.endDate = "2019-01-10"; // Torsdag case2.origin = ORIGIN; case2.destination = DESTINATION; case2.switchEgetBoendeState = true; case2.switchNinetyDaysState = true; case2.comments = COMMENTS; case3 = new Traktamente(); case3.startTime = "08:00"; case3.startDate = "2019-01-07"; // Måndag case3.endTime = "17:00"; case3.endDate = "2019-01-18"; // Fredag case3.origin = ORIGIN; case3.destination = DESTINATION; case3.switchEgetBoendeState = true; case3.switchNinetyDaysState = true; case3.comments = COMMENTS; case4 = new Traktamente(); case4.startTime = "08:00"; case4.startDate = "2019-01-07"; // Måndag case4.endTime = "17:00"; case4.endDate = "2019-01-16"; // Onsdag case4.origin = ORIGIN; case4.destination = DESTINATION; case4.switchEgetBoendeState = true; case4.switchNinetyDaysState = true; case4.comments = COMMENTS; case5 = new Traktamente(); case5.startTime = "08:00"; case5.startDate = "2019-01-07"; // Måndag case5.endTime = "17:00"; case5.endDate = "2019-01-16"; // Onsdag case5.origin = ORIGIN; case5.destination = DESTINATION; case5.switchEgetBoendeState = true; case5.switchNinetyDaysState = true; case5.comments = COMMENTS; case6 = new Traktamente(); case6.startTime = "12:00"; case6.startDate = "2019-01-04"; // Fredag case6.endTime = "17:00"; case6.endDate = "2019-01-17"; // Torsdag case6.origin = ORIGIN; case6.destination = DESTINATION; case6.switchEgetBoendeState = true; case6.switchNinetyDaysState = true; case6.comments = COMMENTS; DateTimeZone.setProvider(new UTCProvider()); } @Test public void generateReport_shouldAddTwoDatesAfterTheEndDate() { case1.generateReport(); case2.generateReport(); case3.generateReport(); case4.generateReport(); case5.generateReport(); case6.generateReport(); assertThat(case1.getDateArray().size()).isEqualTo(CASE_1_REPORT_COUNT); assertThat(case2.getDateArray().size()).isEqualTo(CASE_2_REPORT_COUNT); assertThat(case3.getDateArray().size()).isEqualTo(CASE_3_REPORT_COUNT); assertThat(case4.getDateArray().size()).isEqualTo(CASE_4_REPORT_COUNT); assertThat(case5.getDateArray().size()).isEqualTo(CASE_5_REPORT_COUNT); assertThat(case6.getDateArray().size()).isEqualTo(CASE_6_REPORT_COUNT); assertThat(case1.startDate.equals(case1.getDateArray().get(0).toString())).isTrue(); assertThat(case2.startDate.equals(case2.getDateArray().get(0).toString())).isTrue(); assertThat(case3.startDate.equals(case3.getDateArray().get(0).toString())).isTrue(); assertThat(case4.startDate.equals(case4.getDateArray().get(0).toString())).isTrue(); assertThat(case5.startDate.equals(case5.getDateArray().get(0).toString())).isTrue(); assertThat(case6.startDate.equals(case6.getDateArray().get(0).toString())).isTrue(); assertThat(case1.endDate.equals(case1.getDateArray().get(CASE_1_REPORT_COUNT - 3).toString())).isTrue(); assertThat(case2.endDate.equals(case2.getDateArray().get(CASE_2_REPORT_COUNT - 3).toString())).isTrue(); assertThat(case3.endDate.equals(case3.getDateArray().get(CASE_3_REPORT_COUNT - 3).toString())).isTrue(); assertThat(case4.endDate.equals(case4.getDateArray().get(CASE_4_REPORT_COUNT - 3).toString())).isTrue(); assertThat(case5.endDate.equals(case5.getDateArray().get(CASE_5_REPORT_COUNT - 3).toString())).isTrue(); assertThat(case6.endDate.equals(case6.getDateArray().get(CASE_6_REPORT_COUNT - 3).toString())).isTrue(); } @Test public void isEndDateOfTheTrip_shouldReturnsTrue() { case1.generateReport(); assertThat(case1.isEndDateOfTheTrip(CASE_1_REPORT_COUNT-3)).isTrue(); case2.generateReport(); assertThat(case2.isEndDateOfTheTrip(CASE_2_REPORT_COUNT-3)).isTrue(); case3.generateReport(); assertThat(case3.isEndDateOfTheTrip(CASE_3_REPORT_COUNT-3)).isTrue(); case4.generateReport(); assertThat(case4.isEndDateOfTheTrip(CASE_4_REPORT_COUNT-3)).isTrue(); case5.generateReport(); assertThat(case5.isEndDateOfTheTrip(CASE_5_REPORT_COUNT-3)).isTrue(); case6.generateReport(); assertThat(case6.isEndDateOfTheTrip(CASE_6_REPORT_COUNT-3)).isTrue(); } @Test public void isLastTwoDates_shouldReturnsCorrectValue() { case1.generateReport(); assertThat(case1.getDateArray()).isNotNull(); // Test array lower bound for (int position = 0; position &lt; CASE_1_REPORT_COUNT - 2; position++) { assertThat(case1.isLastTwoDates(position)).isFalse(); } for (int position = CASE_1_REPORT_COUNT - 2; position &lt; CASE_1_REPORT_COUNT; position++) { assertThat(case1.isLastTwoDates(position)).isTrue(); } // Test array upper bound assertThat(case1.isLastTwoDates(CASE_1_REPORT_COUNT)).isFalse(); case3.generateReport(); assertThat(case3.getDateArray()).isNotNull(); for (int position = 0; position &lt; CASE_3_REPORT_COUNT - 2; position++) { assertThat(case3.isLastTwoDates(position)).isFalse(); } for (int position = CASE_3_REPORT_COUNT - 2; position &lt; CASE_3_REPORT_COUNT; position++) { assertThat(case3.isLastTwoDates(position)).isTrue(); } assertThat(case3.isLastTwoDates(CASE_3_REPORT_COUNT)).isFalse(); case5.generateReport(); assertThat(case5.getDateArray()).isNotNull(); for (int position = 0; position &lt; CASE_5_REPORT_COUNT - 2; position++) { assertThat(case5.isLastTwoDates(position)).isFalse(); } for (int position = CASE_5_REPORT_COUNT - 2; position &lt; CASE_5_REPORT_COUNT; position++) { assertThat(case5.isLastTwoDates(position)).isTrue(); } assertThat(case5.isLastTwoDates(CASE_5_REPORT_COUNT)).isFalse(); } @Test public void isLastThreeDates_shouldReturnsCorrectValue() { case2.generateReport(); assertThat(case2.getDateArray()).isNotNull(); for (int position = 0; position &lt; CASE_2_REPORT_COUNT - 3; position++) { assertThat(case2.isLastThreeDates(position)).isFalse(); } for (int position = CASE_2_REPORT_COUNT - 3; position &lt; CASE_2_REPORT_COUNT; position++) { assertThat(case2.isLastThreeDates(position)).isTrue(); } assertThat(case2.isLastThreeDates(CASE_2_REPORT_COUNT)).isFalse(); } } </code></pre> <p>The class I'm trying to test is a simple data model I get from Firebase. I store a range of report dates in an array and want to verify that the given position is the last (and only the last) two dates of the report dates:</p> <pre><code>public class Traktamente { // More fields public String startDate; public String startTime; public String endDate; public String endTime; public String origin; public String destination; // More fields @Exclude private List&lt;LocalDate&gt; dateArray; @Exclude public void generateReport() { LocalDate startDate = LocalDate.parse(this.startDate); LocalDate endDate = LocalDate.parse(this.endDate).plusDays(2); int daysNumber = Days.daysBetween(startDate, endDate).getDays() + 1; // endDate inclusive dateArray = new ArrayList&lt;&gt;(daysNumber); for (int i = 0; i &lt; daysNumber; i++) { LocalDate date = startDate.withFieldAdded(DurationFieldType.days(), i); dateArray.add(date); } } @Exclude private boolean isBefore12Pm(String date) { String format = "yyyy-MM-dd HH:mm"; Date date1 = Utils.getDateFromString(format, date + " 12:00"); Date date2 = Utils.getDateFromString(format, date + " " + startTime); assert date2 != null; return date2.compareTo(date1) &lt; 0; } @Exclude private boolean isAfter17Pm(String date) { String format = "yyyy-MM-dd HH:mm"; Date date1 = Utils.getDateFromString(format, date + " 17:00"); Date date2 = Utils.getDateFromString(format, date + " " + endTime); assert date2 != null; return date2.compareTo(date1) &gt; 0; } @Exclude private boolean isFirstDateOfTheTrip(int position) { return position == 0; } @Exclude public boolean isEndDateOfTheTrip(int position) { return position == dateArray.size() - 3; } @Exclude public boolean isLastThreeDates(int position) { return position &gt;= dateArray.size() - 3 &amp;&amp; position &lt; dateArray.size(); } @Exclude public boolean isLastTwoDates(int position) { return position &gt;= dateArray.size() - 2 &amp;&amp; position &lt; dateArray.size(); } } </code></pre> <p>I also have <code>isLastThreeDates(position)</code> with identical purpose. </p> <p>Am I on the right track to test my code? Or is it something I can improve? Or should I even need to write the test for this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:32:47.657", "Id": "416147", "Score": "0", "body": "is it possible to add the hole unit-test class and data model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T16:27:17.013", "Id": "416163", "Score": "0", "body": "@Roman I added the test code," } ]
[ { "body": "<p>Welcome to CodeReview @Seto! :]</p>\n\n<hr>\n\n<p>In a <a href=\"https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29#tests\" rel=\"nofollow noreferrer\">summery for tests</a> of the book Clean Code by Robert C. Martin the following points are important</p>\n\n<blockquote>\n <ul>\n <li>One assert per test.</li>\n <li>Readable.</li>\n <li>Fast.</li>\n <li>Independent.</li>\n <li>Repeatable.</li>\n </ul>\n</blockquote>\n\n<p>At first glance, we can see that the tests break the rule of one assert per test and are not as readable as they could be. </p>\n\n<hr>\n\n<h1><a href=\"https://www.javacodegeeks.com/2013/06/builder-pattern-good-for-code-great-for-tests.html\" rel=\"nofollow noreferrer\">The Builder Pattern for Tests</a></h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>@Before\npublic void setupOnce() {\n\n case1 = new Traktamente();\n case1.startTime = \"13:00\";\n case1.startDate = \"2019-01-07\";\n // ...\n\n case2 = new Traktamente();\n case2.startTime = \"20:00\";\n case2.startDate = \"2019-01-06\";\n // ..\n\n case2 = new Traktamente();\n // ..\n}\n</code></pre>\n</blockquote>\n\n<p>Many fields share the same values. With the builder pattern we can add common values to clean up the <code>setupOnce</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class TraktamenteBuilder {\n\n public String startDate = \"2019-01-07\";\n public String startTime = \"13:00\";\n public String endDate = // add your default here;\n public String endTime = // add your default here;\n public String origin = // add your default here;\n public String destination = // add your default here;\n public boolean switchEgetBoendeState = true;\n public boolean switchNinetyDaysState = true;\n public String comments = \"Lorem ipsum dolor sit amet.\";\n\n public TraktamenteBuilder withStartDate(String startDate) {\n this.startDate = startDate;\n return this;\n }\n\n public TraktamenteBuilder withStartTime(String tartTime) {\n this.startTime = startTime;\n return this;\n }\n\n public TraktamenteBuilder withEgetBoendeState() {\n this.switchEgetBoendeState = true;\n return this;\n }\n\n // make them expressive - much better then setEgetBoendeState(boolean)\n public TraktamenteBuilder withoutEgetBoendeState() {\n this.switchEgetBoendeState = false;\n return this;\n }\n\n // add more..\n\n\n public Traktamente build() {\n Traktamente traktamente = new Traktamente();\n traktamente.startTime = startTime;\n traktamente.startDate = startDate; \n traktamente.endTime = endTime;\n traktamente.endDate = endDate;\n traktamente.origin = origin;\n traktamente.destination = destination;\n traktamente.switchEgetBoendeState = switchEgetBoendeState;\n traktamente.switchNinetyDaysState = switchNinetyDaysState;\n traktamente.comments = comments;\n return traktamente;\n }\n\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class TraktamenteTest {\n\n private final int CASE_1_REPORT_COUNT = 6;\n private final int CASE_2_REPORT_COUNT = 7;\n private final int CASE_3_REPORT_COUNT = 14;\n private final int CASE_4_REPORT_COUNT = 12;\n private final int CASE_5_REPORT_COUNT = 12;\n private final int CASE_6_REPORT_COUNT = 16;\n\n private final Traktamente case1 = new TraktamenteBuilder().withStartDate(\"2019-01-07\")\n .withStartTime(\"13:00\")\n .withEndDate(\"2019-01-10\")\n .withEndTime(\"21:00\")\n .build();\n\n private final Traktamente case2 = new TraktamenteBuilder().withStartDate(\"2019-01-06\")\n .withStartTime(\"20:00\")\n .withEndDate(\"2019-01-10\")\n .withEndTime(\"21:00\")\n .build();\n\n\n // more cases\n\n @Before\n public void setupOnce() {\n DateTimeZone.setProvider(new UTCProvider());\n }\n\n // test cases ...\n}\n</code></pre>\n\n<hr>\n\n<h1>Parameterized Tests</h1>\n\n<p>You have 4 test and 3 of them contains repetitive code, because you want to check the logic for different cases. The disadvantage is that your test cases are big, contains duplicate code and you need to change at so many places if the API of your application will change at one day.</p>\n\n<p>Actually you can think of your different cases as parameters of one test. For jUnit4 you can take a look at <a href=\"https://github.com/junit-team/junit4/wiki/parameterized-tests\" rel=\"nofollow noreferrer\">a github guide for parameterized tests</a> or if you want to take a look at jUnit5 you can take a look into the <a href=\"https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests\" rel=\"nofollow noreferrer\">user guide for parameterized tests</a>. There also exists a tool with the name <a href=\"https://github.com/Pragmatists/JUnitParams\" rel=\"nofollow noreferrer\">JUnitParams</a></p>\n\n<hr>\n\n<h1>Focus on one Assertion</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>@Test\npublic void generateReport_shouldAddTwoDatesAfterTheEndDate() {\n case1.generateReport();\n // ..\n\n assertThat(case1.getDateArray().size()).isEqualTo(CASE_1_REPORT_COUNT);\n // ..\n\n assertThat(case1.startDate.equals(case1.getDateArray().get(0).toString())).isTrue();\n // ..\n\n assertThat(case1.endDate.equals(case1.getDateArray().get(CASE_1_REPORT_COUNT - 3).toString())).isTrue();\n // ..\n}\n</code></pre>\n</blockquote>\n\n<p>The test <code>generateReport_shouldAddTwoDatesAfterTheEndDate</code> tests more than just adding to dates to the end. It also check the array size and the first startDate. This tests should be in their own tests.</p>\n\n<hr>\n\n<h1><a href=\"http://wiki.c2.com/?ArrangeActAssert\" rel=\"nofollow noreferrer\">Arrange Act Assert</a></h1>\n\n<blockquote>\n <p>Each method should group these functional sections, separated by blank lines:</p>\n \n <p><strong>Arrange</strong> all necessary preconditions and inputs.<br>\n <strong>Act</strong> on the object or method under test.<br>\n <strong>Assert</strong> that the expected results have occurred. </p>\n</blockquote>\n\n<p>The AAA-Pattern makes it easier to understand and maintain the code - not only for your self but for other programmers that need to read or change your code too.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\npublic void isEndDateOfTheTrip_shouldReturnsTrue() {\n // arrange\n case1.generateReport();\n\n // act\n boolean isEndDateOfTheTrip = case1.isEndDateOfTheTrip(CASE_1_REPORT_COUNT-3);\n\n // assert\n assertThat(isEndDateOfTheTrip).isTrue();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T10:38:54.623", "Id": "416452", "Score": "0", "body": "A really comprehensive answer. Accepted. I'll read it line by line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T12:10:18.683", "Id": "416473", "Score": "0", "body": "\"The test generateReport_shouldAddTwoDatesAfterTheEndDate tests more than just adding to dates to the end. It also check the array size and the first startDate. This tests should be in their own tests.\" A question, I also need to verify that it's adding the correct date array, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T12:13:42.043", "Id": "416474", "Score": "1", "body": "Yes, this is desirable and I thing this would be the most important test to check the correctness :]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T12:15:36.173", "Id": "416475", "Score": "0", "body": "Ah, so I need to make another test only for this, right?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T08:09:13.437", "Id": "215239", "ParentId": "215189", "Score": "3" } } ]
{ "AcceptedAnswerId": "215239", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T11:20:04.130", "Id": "215189", "Score": "2", "Tags": [ "java", "unit-testing", "android" ], "Title": "Android Java Unit Testing model class" }
215189
<p>I made a simple data entry application in WPF MVVM and was just hoping for some input as I am pretty new to WPF . I have done the same application using winforms. Now I have recreated the same application using WPF.</p> <p>I have understood how to write wpf based application, how to use command and other aspects of c# development in wpf. But the thing I don't understand is XAML UI devleopment.</p> <p>I would appreciate any type of input for XAML. I do feel that I may have problems specifically in how I'm using the panels and allocating space with application using margins. <a href="https://i.stack.imgur.com/M43u4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M43u4.png" alt="enter image description here"></a></p> <p>I have divided the tool into three stack using dockpanel and pasted the componets inside those panels.</p> <p>StackPanel 1:</p> <pre><code> &lt;TabControl SelectedIndex="{Binding selectedIndex}" Grid.Row="0" Height="478" Margin="0,43,-8,-15" x:Name="tabControl1" Width="auto"&gt; &lt;TabItem Header="Claim Information" x:Name="tabItem1"&gt; &lt;UniformGrid Columns="1" Margin="-6,0,55.291,8.027" Width="1144"&gt; &lt;DockPanel Margin="-0,0,-20,0" VerticalAlignment="Top" Width="1161.998" Height="55"&gt; &lt;StackPanel Margin="10,5,35,5" Orientation="Horizontal" DockPanel.Dock="Top" Height="51" Width="1138"&gt; &lt;Label Margin="1,14,708.962,0" x:Name="label11" HorizontalAlignment="Left" VerticalAlignment="Top" Width="44" Height="28" Content="Date"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" Margin="-700,1,708.962,0" HorizontalAlignment="Right" VerticalAlignment="Center" x:Name="txtBoxDate" Width="69" Height="19" Text="{Binding DateTimeArgument, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Margin="-700,1,708.962,0" x:Name="username" HorizontalAlignment="Left" Width="68" Height="28" Content="User Name"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" x:Name="usernameTextbox" Margin="-700,1,708.962,0" Width="99" Height="19" Text="{Binding UserNameArgument, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Button IsEnabled="{Binding IsStartButtonEnabled}" Width="79" Height="19.277" Margin="-700,1,708.962,0" x:Name="startbutton" Command="{Binding AddNew}" Content="Start Time"/&gt; &lt;Label Width="61" Height="24" Margin="-700,1,708.962,0" x:Name="StartTimeLabel" HorizontalAlignment="Left" Content="Start Time"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" x:Name="StarttimeTextbox" Width="71" Height="19.277" Margin="-700,1,708.962,0" Text="{Binding StartTimerArgument, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Width="44" Height="24" Margin="-700,14,708.962,13" x:Name="Timer1" HorizontalAlignment="Left" Content="Timer"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" x:Name="Timer" Width="60" Height="19.277" Margin="-700,1,708.962,0" Text="{Binding TimerArgument, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Width="60" Height="24" Margin="-700,1,708.962,0" x:Name="endtimer" HorizontalAlignment="Left" Content="End Time"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" x:Name="EndTimer" Width="60" Height="19.277" Margin="-700,1,710.962,0" Text="{Binding EndTimerArgument, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Width="65" Height="24" Margin="-710,1,-238.962,0" x:Name="TotalTimer" HorizontalAlignment="Left" Content="Total Time"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" x:Name="TotalTimeTaken" Width="86" Height="19.277" Margin="-635,1,708.962,0" Text="{Binding TotalTimerArgument, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Width="52" Height="24" Margin="-700,1,-238.962,0" x:Name="labelFrportal" HorizontalAlignment="Left" Content="Fr Portal"/&gt; &lt;TextBox IsEnabled="{Binding Isdisabled}" x:Name="txtboxFrportal" Width="62" Height="19.277" Margin="-890,15,338,12" Text="{Binding FRPortalTime, Mode=TwoWay}" /&gt; &lt;/StackPanel&gt; &lt;/DockPanel&gt; </code></pre> <p>stackpanel 2 :</p> <pre><code> &lt;DockPanel VerticalAlignment="Top" Margin="1,-80,0,0" HorizontalAlignment="Left" Width="1075" Height="53"&gt; &lt;StackPanel Margin="1,0,-30,0" Orientation="Horizontal" DockPanel.Dock="Top" Width="1077" Height="53"&gt; &lt;Label Width="49" Height="23.277" HorizontalAlignment="Left" Margin="1,14,30,0" VerticalAlignment="Top" Content="AuditID"/&gt; &lt;TextBox x:Name="txtboxAuditId" IsEnabled="{Binding IsEnabled}" Width="108" Height="19.277" HorizontalAlignment="Left" Margin="-20,14,708.962,0" VerticalAlignment="Top" Text="{Binding GetRowData.AuditId}" /&gt; &lt;Label Margin="-700,1,-228.962,0" x:Name="label111" HorizontalAlignment="Left" Width="77" Height="28" Content="ClaimNumber"/&gt; &lt;TextBox IsEnabled="{Binding IsEnabled}" HorizontalAlignment="Left" Width="113" Height="19.277" Margin="-620,1,-228.962,0" x:Name="txtBoxDate1" Text="{Binding GetRowData.Claimnumber}"/&gt; &lt;Label Margin="-500,1,-228.962,0" x:Name="Linesforcpt" HorizontalAlignment="Left" Width="77" Height="28" Content="CPT Lines"/&gt; &lt;TextBox IsEnabled="{Binding IsEnabled}" HorizontalAlignment="Left" Width="113" Height="19.277" Margin="-420,1,-228.962,0" x:Name="TxtboxLinesforcpt" Text="{Binding CPTLines, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Margin="-290,13,5.962,12" x:Name="lblcommnets" HorizontalAlignment="Left" Width="67" Height="28" Content="Comments"/&gt; &lt;TextBox IsEnabled="{Binding IsEnabled}" HorizontalAlignment="Left" Width="113" Height="19.277" Margin="-200,-1,-218.962,0" x:Name="txtboxComments" Text="{Binding Comments, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/&gt; &lt;Label Margin="-70,13,-228.962,12" x:Name="lblFInalstatus" HorizontalAlignment="Left" Width="72" Height="28" Content="Final Status"/&gt; &lt;ComboBox ItemsSource="{Binding Source={StaticResource MyEnums}}" SelectedItem="{Binding CurrentItem, Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Center" IsEnabled="{Binding IsEnabled}" Width="113" Height="19.277" Margin="10,1,-228.962,0" x:Name="cmbboxFinalstatus"/&gt; &lt;Button Content="End Timer" Command="{Binding stop}" Margin="90,1,-269.962,0" Width="66" Height="19.277"&gt; &lt;Button.Style&gt; &lt;Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}"&gt; &lt;Setter Property="IsEnabled" Value="True" /&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding CurrentItem}" Value="{x:Null}"&gt; &lt;Setter Property="IsEnabled" Value="False" /&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/Button.Style&gt; &lt;/Button&gt; &lt;/StackPanel&gt; &lt;/DockPanel&gt; </code></pre> <p>stack 3:</p> <pre><code> &lt;DockPanel Margin="1,-225,0,0" Width="1075" Height="193"&gt; &lt;StackPanel Margin="1,0,0,0" Orientation="Horizontal" DockPanel.Dock="Top" Width="1077" Height="293"&gt; &lt;Button Command="{Binding Submitbutton}" Margin="500,-19,0,171" Width="70" Height="20" VerticalAlignment="Center" IsEnabled="{Binding IsEnabledSubmit}" Content="Submit"/&gt; &lt;/StackPanel&gt; &lt;/DockPanel&gt; &lt;/UniformGrid&gt; &lt;/TabItem&gt; </code></pre> <p>Namespace : </p> <pre><code> xmlns:vm="clr-namespace:Activity_Tracker_Coding_WPF.ViewModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Converter="clr-namespace:Activity_Tracker_Coding_WPF.ViewModel" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="Activity_Tracker_Coding_WPF.Window1" Title="Activty Tracker Application" Height="506" Width="1177" Background="LightGray"&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T20:54:50.137", "Id": "416190", "Score": "1", "body": "Welcome to CR! It could be a good idea to include the ViewModel class, and keep the xaml markup together in the same block if it's all in the same file." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T12:37:21.317", "Id": "215192", "Score": "2", "Tags": [ "wpf", "xaml" ], "Title": "Simple Data Entry Application in WPF xaml UI" }
215192
<p>I was trying to write a function that would get a random card from a dictionary of cards in a players deck weighted by the number of cards of each type you have. I don't know if the solution I came up with is the fates way of doing something like this and this is something I'm going to be doing a lot per turn because of certain mechanics in the games design. Please let me know if there is something i missed that could help the performance of this code.</p> <p>For some contexts <code>_deck._card</code> is a dictionary with the key being a string and the value being a int. <code>Dictionary&lt;string, int&gt; _cards</code></p> <p>Also <code>Nez.Random</code> is a singleton of my random class for the project. <code>Random.nextInt(int max)</code> takes in a int for the max value of the random number.</p> <pre><code>static public int nextInt( int max ) { return random.Next( max ); } </code></pre> <p>Code:</p> <pre><code>public string GetRandomCard() { string result = ""; var totalWeight = 0; foreach (var cardNumber in _deck._cards) totalWeight += cardNumber.Value; var randNumber = Nez.Random.nextInt(totalWeight); foreach (var cardNumber in _deck._cards) { var value = cardNumber.Value; if (randNumber &gt;= value) { randNumber -= value; } else { result = cardNumber.Key; break; } } return result; } </code></pre> <p>Time complexity O(N^2) I dont think there is a way to decrease the time complexity but there might be other ways to optimize this code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:17:38.570", "Id": "416141", "Score": "0", "body": "The time complexity of this code in currently O(N^2) My question is if there is a way to get this down to O(N). Or if there is just some small improvements in speed I can do. Like I don't know if creating a int is faster using the var keyword or the int keyword, or if there is even a difference in speed (I think the compiler takes care of this so there wont be a difference but I don't know for sure)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T16:01:37.323", "Id": "416154", "Score": "0", "body": "What do you need `numCardTypes` for when you're not using it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:02:38.000", "Id": "416169", "Score": "0", "body": "@t3chb0t Oh wow I completely missed that I left that in from my first attempt at this function.\n\n I also noticed that I misspelled result. These changes have been corrected in the code now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:12:19.993", "Id": "416173", "Score": "0", "body": "I dont know if I should edit my post with these changes or keep it. Anyone know what is common practice here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:14:46.320", "Id": "416174", "Score": "0", "body": "You can edit the code as long as there are no answers. After that, you should no longer do it. It would be great if you corrected it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:11:58.540", "Id": "416177", "Score": "0", "body": "Are you OK with generating the entire card sequence all at once? What this becomes (minus the compression provided by using weights) is the generation of a permutation of the card deck (shuffling the deck) then dealing out the cards in their shuffled order.\n\nThis has examples (unfortunately, in java), but the algorithm is present and should be easy to adapt: https://stackoverflow.com/questions/5505927/how-to-generate-a-random-permutation-in-java.\n\n(Minor nit: Instead of 'weight', 'frequency' would be a better term to use.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:54:52.093", "Id": "416181", "Score": "0", "body": "I'd like to clarify the intention. Hypothetically, say a player has a deck of 10 cards. 5 cards are labeled \"Attack\", 3 cards are labeled \"Defend\", and 2 cards are labeled \"Heal\". You would represent this with the dictionary `{Attack => 5, Defend => 3, Heal => 2}`? And when the player draws a card, you would call this function, which gives the player a 50% chance of Attacking, a 30% chance of Defending, and a 20% chance of Healing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T23:56:55.837", "Id": "416210", "Score": "0", "body": "Can you elaborate on how you will use this class? If you are sampling from a different set of weights every time, then you can't do better than the `O(n)` you already have (per sample); if the sample is the same or a slight variation, then you may be able to do successive samplings in `O(log(n))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T05:30:56.777", "Id": "416225", "Score": "0", "body": "@benj2240 You are right in the result but the system is there is a class named deck that is used for anything that needs cards and to be able to communicate with other decks. Inside the deck is a dictionary of all the cards this deck has. This dictionary is used as a lightweight and fast way of storing and accessing this data. An example of this dictionary would be {WarLord => 8, Mage => 3, Dragon => 4} I want this function to randomly pick a card but have Warlord have a 8/15 change of getting picked and mage having 3/15 and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T05:55:26.447", "Id": "416226", "Score": "0", "body": "@VisualMelon Yes this function will be sampling from a different set of weights almost every time it is used. The function works for all decks in the game and every deck has a different number and types of cards. Also these decks are having cards added and remove constantly due to how some mechanics of the game work. This is why Im using a dictionary to represent what cards this deck currently has because of the speed to fetch info from it. Then if the game every needs to know more info about what a card is or does, it does a lookup using the name(string) of the cards type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:55:48.547", "Id": "416277", "Score": "0", "body": "Could you provide a little more info concerning how the probabilities change and cards are added/removed? You can do all of these operations in `O(log(n))` time with a suitable data-structure, so it the number of changes is small compared to the deck size, then that might be worth investigating. If the decks are size 3 as in your answer, then the complexity doesn't really matter, and it won't be worth anything more complicated than a linear scan." } ]
[ { "body": "<p>After all this good discussion It looks like this function is as optimize as its going to get for its intended purpose. \nI want to note that I was incorrect in its time complexity. The time complexity is actually O(N) not O(N^2) luckily.</p>\n\n<p>Considering this algorithm can perform 1,000 random selections in 0.00194s on a mid range workstation It shouldn't have any performance impact if used many times.</p>\n\n<p>Here are the results of the unit test:</p>\n\n<pre><code>Running random 100 times: 0.0013367s\nKey: 30%, Value: 35\nKey: 60%, Value: 60\nKey: 10%, Value: 5\n\nRunning random 1000 times: 0.0019477s\nKey: 30%, Value: 378\nKey: 60%, Value: 618\nKey: 10%, Value: 104\n\nRunning random 10000 times: 0.0202942s\nKey: 30%, Value: 3391\nKey: 60%, Value: 6635\nKey: 10%, Value: 1074\n\nRunning random 100000 times: 0.191678s\nKey: 30%, Value: 33669\nKey: 60%, Value: 66427\nKey: 10%, Value: 11004\n\nRunning random 1000000 times: 1.77491s\nKey: 30%, Value: 334075\nKey: 60%, Value: 666087\nKey: 10%, Value: 110938\n\nRunning random 10000000 times: 18.43691s\nKey: 30%, Value: 3332173\nKey: 60%, Value: 6667785\nKey: 10%, Value: 1111142\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:48:38.203", "Id": "416298", "Score": "0", "body": "I love it. So often the answer to \"How do I optimize this\" is \"You probably don't need to.\" Since you took the extra step to actually measure, this time the answer is definite. Plus, you confirmed that the probability distribution is working as you intended. Nicely done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:41:21.803", "Id": "416315", "Score": "0", "body": "I'm confused by your results... The sum of your Values doesn't add up to the number of times except for the first case (100). E.g. 1,000 -> 1,100, 10,000 -> 11,000, 100,000 -> 111,100 etc. Do you have a bug in your test or have I misunderstood?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:50:01.277", "Id": "416318", "Score": "0", "body": "@RobH Wow I didn't even notice that. Thank you for pointing that out! Im unable to check the code and test again because it is on my work computer but I will look into once im back at work in 4 days." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:51:54.560", "Id": "416319", "Score": "0", "body": "These are exactly the results we would expect if the counters were cumulative across the test runs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:55:49.260", "Id": "416321", "Score": "0", "body": "@benj2240 Thats most likely it. I don't remember if I reset the results dic ever time I did the test (I doubt I did). If it is then it would not effect the test in any way," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T08:45:23.903", "Id": "416422", "Score": "0", "body": "@benj2240 - yes, that's what I assumed was happening too but I didn't want to lead the witness ;)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T09:28:19.937", "Id": "215246", "ParentId": "215194", "Score": "1" } }, { "body": "<p>You've covered the performance and correctness of your code, so all I can comment on is style.</p>\n\n<p><strong>Linq:</strong> When possible, I prefer a declarative style of programming over an imperative style. That is, saying <em>what</em> you want instead of <em>how</em> to calculate it. Linq makes this easy in the case of totalWeight, which could be declared like this:</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>var totalWeight = _deck._cards.Sum(cardNumber =&gt; cardNumber.Value);\n</code></pre>\n\n<p>Technically the second <code>foreach</code> could also be transformed into a Linq statement, using <code>.Aggregate()</code> and <code>.First()</code>... But I don't recommend it, as in that case I believe it would actually be <em>less</em> readable.</p>\n\n<hr/>\n\n<p><strong>Immediate returns:</strong> Between the following two functions, I prefer the latter:</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>int Foo1(Bar bar)\n{\n var answer = 0;\n\n if (bar != null)\n {\n answer = bar.Baz;\n }\n\n return answer;\n}\n</code></pre>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>int Foo2(Bar bar)\n{\n if (bar == null)\n {\n return 0;\n }\n\n return bar.Baz;\n}\n</code></pre>\n\n<p>In <code>Foo2</code>, I don't have to mentally track the state of the <code>answer</code> variable as I read. Another benefit is that <code>Foo2</code> scratches that itch I get when I see a bad variable name... \"answer\" is only a tiny bit more informative than \"x\", as variable names go.</p>\n\n<p>So I would refactor your code to remove the <code>result</code> variable completely. On the line where you set it, just <code>return cardNumber.Key</code>.</p>\n\n<hr/>\n\n<p><strong>Defaults vs Exceptions:</strong> I would also change the line where you <code>return result</code>. Instead, just throw an Exception. You seem to have tested your code pretty well, so you can be confident that the exception will never be thrown... Until the code is refactored, or the card weights are changed to Floats, or who-knows-what.</p>\n\n<p>If that ever happens, an exception saying \"The weighted card drawing function failed to select a card\" will be easier to debug than an exception saying \"Player cannot summon '': invalid unit type.\"</p>\n\n<p>As a side note, yes I <em>would</em> prefer a third version of my function above. If you're going to fail, fail fast!</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>int Foo3(Bar bar)\n{\n if (bar == null) throw new ArgumentNullException(nameof(bar));\n\n return bar.Baz;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:08:09.437", "Id": "416323", "Score": "0", "body": "I completely forgot `Sum()` was a function in dictionary's! As for the Immediate returns I personally prefer the former because returning 0 is a expected response to this call. There are decks that at time will have no cards in them at all (_cards will still be a dictionary just with 0 keys). This point also falls into why this function doesn't need a exception because there is no unexpected result that is still a number." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:40:09.867", "Id": "215278", "ParentId": "215194", "Score": "1" } }, { "body": "<p>Since the original question was about efficiency, here's how you achieve the same thing enumerating the dictionary once...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace CodeReviewFun\n{\n static class Program\n {\n private static Random _random = new Random();\n private static Dictionary&lt;string, int&gt; _dict;\n private static Dictionary&lt;string, int&gt; _hits;\n private static int _nCardTypes;\n private static int _nCatds;\n\n static Program()\n {\n _dict = new Dictionary&lt;string, int&gt;();\n _hits = new Dictionary&lt;string, int&gt;();\n _dict.Add(\"WarLord\", 8);\n _dict.Add(\"Mage\", 3);\n _dict.Add(\"Dragon\", 4);\n _nCardTypes = _dict.Count;\n _nCatds = 0;\n foreach (var cardTypeKey in _dict.Keys)\n {\n _hits.Add(cardTypeKey, 0);\n _nCatds += _dict[cardTypeKey];\n }\n }\n\n // The idea is that Value * randomNumber is already weighted\n // so just remember the key for the most heavily weighted value and the corresponding key\n // and return that\n public static string GetRandomCard()\n {\n string pick_Key = \"\";\n int pick_Value = -1;\n foreach (var entry in _dict)\n {\n int pick = _random.Next(_nCardTypes);\n int thisValue = pick * entry.Value;\n if (thisValue &gt; pick_Value)\n {\n pick_Key = entry.Key;\n pick_Value = thisValue;\n }\n }\n return pick_Key;\n }\n\n static void Main(string[] args)\n {\n const int nSamples = 10000000;\n for (int i = 0; i &lt; nSamples; i++)\n {\n var hitKey = GetRandomCard();\n _hits[hitKey]++;\n }\n foreach (var entry in _hits)\n {\n Console.WriteLine($\"{entry.Key, -10}: {entry.Value} ({(double)entry.Value * _nCatds / _nCardTypes})\");\n }\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n\n<p>Sample run:</p>\n\n<pre><code>WarLord : 7037889 (35189445)\nMage : 1112616 (5563080)\nDragon : 1849495 (9247475) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:39:26.853", "Id": "416333", "Score": "0", "body": "I original had this idea put unfortunately decks are gaining and losing card all the time (It can be up to 100 times per micro turn in some very extreme but possible cases (a micro turn is just a subsection of a turn)) so the weight needs to be calculate every time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T18:00:35.863", "Id": "416336", "Score": "0", "body": "@TylerGregorcyk how large are the decks? how many different types of card are there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T18:12:48.643", "Id": "416339", "Score": "0", "body": "Then you're heading for trouble. If the totalWeight calculated in the 1st enumeration exceeds the total of the values encountered in the 2nd enumeration pass, then you can generate a random number that exceeds the new total and return a result of \"\". If this possibility breaks your logic, you should (a) minimise the number of enumeration passes and (b) consider making judicious use of lock(s) to protect the bits of code that update the values. Otherwise you're just setting up a target that you know won't stand still while you're shooting at it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T18:13:33.040", "Id": "416340", "Score": "0", "body": "@VisualMelon These decks very in size from 0-500. This is because the object `deck` is used for anything that needs cards and needs to be able to move cards around from its self to other decks and vice versa. So for example the players hand is just a `deck` object and the players playing deck is also a `deck` object. As to how many cards, as of right now there are planned to be 150 different types of cards but this can be expanded as needed (And most likely will be)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T18:20:49.897", "Id": "416341", "Score": "0", "body": "@AlanK This should not be a issue because all request to move or edit a deck is through a [command system](https://en.wikipedia.org/wiki/Command_pattern) and all commands make sure they are on the same thread as the data they are manipulating." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:33:09.450", "Id": "215282", "ParentId": "215194", "Score": "0" } } ]
{ "AcceptedAnswerId": "215246", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T13:01:46.590", "Id": "215194", "Score": "0", "Tags": [ "c#", "game", "random", "hash-map" ], "Title": "Randomly pick key from dictionary weighted by the keys value" }
215194
<p>I'm currently working on a linux daemon and would like some feedback. The program is a simple unix socket server that sends around <a href="https://blog.golang.org/gobs-of-data" rel="nofollow noreferrer">gob</a> encoded messages. I'm still getting the hang of concurrency in go and I'm not terribly confidant the socket server is passing around messages properly especially on shutdown. Hopefully, I'm not doing anything too egregious.</p> <p>EDIT: I rewrote most of the server code after getting a burst of inspiration from this <a href="https://stackoverflow.com/questions/48224908/better-error-handling">post</a>. I fell back to a previous iteration that didn't use channels to communicate errors and connections. Instead it just uses a callback for errors in much the same way it does for regular messages. Finally, I then wrote units tests for the whole thing.</p> <p>I'll remove the old code. Any feedback would still be appreciated.</p> <p><strong>server.go</strong></p> <pre><code>package network import ( "encoding/gob" "errors" "net" "sync" ) var ( ErrNoMessageHandler = errors.New("server: message handler not specified") ) type Options struct { Network string Address string } type Server struct { opts *Options lis net.Listener mh func(interface{}) interface{} eh func(error) quit bool conns sync.WaitGroup } func NewServer(opts *Options) *Server { return &amp;Server{opts: opts} } func (s *Server) OnMessage(handler func(interface{}) interface{}) { s.mh = handler } func (s *Server) OnError(handler func(error)) { s.eh = handler } func (s *Server) Listen() error { lis, err := net.Listen(s.opts.Network, s.opts.Address) if err != nil { return err } s.lis = lis return nil } func (s *Server) Network() string { return s.lis.Addr().Network() } func (s *Server) Address() string { return s.lis.Addr().String() } func (s *Server) Serve() error { if s.mh == nil { return ErrNoMessageHandler } for { conn, err := s.lis.Accept() if err != nil { if s.quit { return nil } return err } s.conns.Add(1) go s.handle(conn) } } func (s *Server) Close() error { s.quit = true err := s.lis.Close() s.conns.Wait() return err } func (s *Server) handle(conn net.Conn) { defer s.cleanup(conn) dec := gob.NewDecoder(conn) var req interface{} if err := dec.Decode(&amp;req); err != nil { if s.eh != nil { s.eh(err) } return } res := s.mh(req) enc := gob.NewEncoder(conn) if err := enc.Encode(&amp;res); err != nil { if s.eh != nil { s.eh(err) } return } } func (s *Server) cleanup(conn net.Conn) { conn.Close() s.conns.Done() } </code></pre> <p><strong>client.go</strong></p> <pre><code>package network import ( "encoding/gob" "net" ) type Client struct { opts *Options } func NewClient(opts *Options) *Client { return &amp;Client{opts: opts} } func (c *Client) Send(req interface{}) (res interface{}, err error) { conn, err := net.Dial(c.opts.Network, c.opts.Address) if err != nil { return nil, err } defer conn.Close() enc := gob.NewEncoder(conn) err = enc.Encode(&amp;req) if err != nil { return nil, err } dec := gob.NewDecoder(conn) err = dec.Decode(&amp;res) if err != nil { return nil, err } return res, nil } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T14:59:50.830", "Id": "215199", "Score": "2", "Tags": [ "go", "linux", "socket", "server" ], "Title": "Simple Go Linux daemon to send/receive gob-encoded data on a socket" }
215199
<p>The following Go program parses a gzipped XML file (available <a href="https://dblp.uni-trier.de/xml/" rel="nofollow noreferrer">here</a>) which contains bibliographic information on computer science publications and has the following indicative structure:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;!DOCTYPE dblp SYSTEM "dblp.dtd"&gt; &lt;dblp&gt; &lt;article mdate="2017-05-28" key="journals/acta/Saxena96"&gt; &lt;author&gt;Sanjeev Saxena&lt;/author&gt; &lt;title&gt;Parallel Integer Sorting and Simulation Amongst CRCW Models.&lt;/title&gt; &lt;pages&gt;607-619&lt;/pages&gt; &lt;year&gt;1996&lt;/year&gt; &lt;volume&gt;33&lt;/volume&gt; &lt;journal&gt;Acta Inf.&lt;/journal&gt; &lt;number&gt;7&lt;/number&gt; &lt;url&gt;db/journals/acta/acta33.html#Saxena96&lt;/url&gt; &lt;ee&gt;https://doi.org/10.1007/BF03036466&lt;/ee&gt; &lt;/article&gt; &lt;article mdate="2017-05-28" key="journals/acta/Simon83"&gt; &lt;author&gt;Hans Ulrich Simon&lt;/author&gt; &lt;title&gt;Pattern Matching in Trees and Nets.&lt;/title&gt; &lt;pages&gt;227-248&lt;/pages&gt; &lt;year&gt;1983&lt;/year&gt; &lt;volume&gt;20&lt;/volume&gt; &lt;journal&gt;Acta Inf.&lt;/journal&gt; &lt;url&gt;db/journals/acta/acta20.html#Simon83&lt;/url&gt; &lt;ee&gt;https://doi.org/10.1007/BF01257084&lt;/ee&gt; &lt;/article&gt; &lt;article mdate="2017-05-28" key="journals/acta/GoodmanS83"&gt; &lt;author&gt;Nathan Goodman&lt;/author&gt; &lt;author&gt;Oded Shmueli&lt;/author&gt; &lt;title&gt;NP-complete Problems Simplified on Tree Schemas.&lt;/title&gt; &lt;pages&gt;171-178&lt;/pages&gt; &lt;year&gt;1983&lt;/year&gt; &lt;volume&gt;20&lt;/volume&gt; &lt;journal&gt;Acta Inf.&lt;/journal&gt; &lt;url&gt;db/journals/acta/acta20.html#GoodmanS83&lt;/url&gt; &lt;ee&gt;https://doi.org/10.1007/BF00289414&lt;/ee&gt; &lt;/article&gt; &lt;/dblp&gt; </code></pre> <p>The XML has multiple publication types denoted by the title of the element (i.e. proceedings, book, phdthesis) and for each of which I have defined a separate struct in my program:</p> <pre><code>package main import ( "compress/gzip" "encoding/csv" "encoding/xml" "fmt" "io" "log" "os" "sort" "strconv" "time" "golang.org/x/text/encoding/charmap" ) // Dblp contains the array of articles in the dblp xml file type Dblp struct { XMLName xml.Name `xml:"dblp"` Dblp []Article } // Metadata contains the fields shared by all structs type Metadata struct { Key string `xml:"key,attr"` // not currently in use Year string `xml:"year"` Author string `xml:"author"` // not currently in use Title string `xml:"title"` // not currently in use } // Article struct and the following structs contain the elements we want to parse and they "inherit" the metadata struct defined above type Article struct { XMLName xml.Name `xml:"article"` Metadata } type InProceedings struct { XMLName xml.Name `xml:"inproceedings"` Metadata } type Proceedings struct { XMLName xml.Name `xml:"proceedings"` Metadata } type Book struct { XMLName xml.Name `xml:"book"` Metadata } type InCollection struct { XMLName xml.Name `xml:"incollection"` Metadata } type PhdThesis struct { XMLName xml.Name `xml:"phdthesis"` Metadata } type MastersThesis struct { XMLName xml.Name `xml:"mastersthesis"` Metadata } type WWW struct { XMLName xml.Name `xml:"www"` Metadata } // Record is used to store each Article's type and year which will be passed as a value to map m type Record struct { UID int ID int Type string Year string } // SumRecord is used to store the aggregated articles by year in srMap map //(count is stored in the map's int which is used as key) type SumRecord struct { Type string Year string } </code></pre> <p>The program stores each publication in a map structure and finally exports two csv files:</p> <ul> <li>results.csv which contains an id, publication type and year for each publication</li> <li>sumresults.csv which contains the sum of each publication type per year</li> </ul> <p>It is the first "complete" program I've written in Go - I'm currently trying to get a grasp on the language and I've needed to ask two questions on Stack Overflow while writing it <a href="https://stackoverflow.com/questions/54964781/exporting-a-map-containing-a-struct-as-value-to-csv-with-golang">here</a> and <a href="https://stackoverflow.com/questions/54993543/how-to-count-number-of-occurrences-of-a-value-in-a-map-with-golang">here</a>.</p> <p>The rest of the code:</p> <pre><code>func main() { // Start counting time start := time.Now() // Initialize counter variables for each publication type var articleCounter, InProceedingsCounter, ProceedingsCounter, BookCounter, InCollectionCounter, PhdThesisCounter, mastersThesisCounter, wwwCounter int var i = 1 // Initialize hash map m := make(map[int]Record) //Open gzipped dblp xml xmlFile, err := os.Open("dblp.xml.gz") gz, err := gzip.NewReader(xmlFile) if err != nil { log.Fatal(err) } defer gz.Close() //Directly open xml file for testing purposes if needed - be sure to comment out gzip file opening above //xmlFile, err := os.Open("dblp.xml") //xmlFile, err := os.Open("TestDblp.xml") if err != nil { fmt.Println(err) } else { log.Println("Successfully Opened Dblp XML file") } // defer the closing of XML file so that we can parse it later on defer xmlFile.Close() // Initialize main object from Dblp struct var articles Dblp // Create decoder element decoder := xml.NewDecoder(gz) // Suppress xml errors decoder.Strict = false decoder.CharsetReader = makeCharsetReader err = decoder.Decode(&amp;articles.Dblp) if err != nil { fmt.Println(err) } for { // Read tokens from the XML document in a stream. t, err := decoder.Token() // If we reach the end of the file, we are done if err == io.EOF { log.Println("XML successfully parsed:", err) break } else if err != nil { log.Fatalf("Error decoding token: %t", err) } else if t == nil { break } // Here, we inspect the token switch se := t.(type) { // We have the start of an element and the token we created above in t: case xml.StartElement: switch se.Name.Local { case "dblp": case "article": var p Article decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;articleCounter) m[i] = Record{i, articleCounter, "article", p.Year} increment(&amp;i) case "inproceedings": var p InProceedings decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;InProceedingsCounter) m[i] = Record{i, InProceedingsCounter, "inproceedings", p.Year} increment(&amp;i) case "proceedings": var p Proceedings decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;ProceedingsCounter) m[i] = Record{i, ProceedingsCounter, "proceedings", p.Year} increment(&amp;i) case "book": var p Book decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;BookCounter) m[i] = Record{i, BookCounter, "proceedings", p.Year} increment(&amp;i) case "incollection": var p InCollection decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;InCollectionCounter) m[i] = Record{i, InCollectionCounter, "incollection", p.Year} increment(&amp;i) case "phdthesis": var p PhdThesis decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;PhdThesisCounter) m[i] = Record{i, PhdThesisCounter, "phdthesis", p.Year} increment(&amp;i) case "mastersthesis": var p MastersThesis decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;mastersThesisCounter) m[i] = Record{i, mastersThesisCounter, "mastersthesis", p.Year} increment(&amp;i) case "www": var p WWW decoder.DecodeElement(&amp;p, &amp;se) increment(&amp;wwwCounter) m[i] = Record{i, wwwCounter, "www", p.Year} increment(&amp;i) } } } log.Println("Element parsing completed in:", time.Since(start)) // All parsed elements have been added to m := make(map[int]Record) // We can start processing the map. // First we create a map and count the number of occurences of each publication type for a given year. srMap := make(map[SumRecord]int) log.Println("Creating sums by article type per year") for key := range m { sr := SumRecord{ Type: m[key].Type, Year: m[key].Year, } srMap[sr]++ } //// Create sum csv log.Println("Creating sum results csv file") sumfile, err := os.Create("sumresult.csv") checkError("Cannot create file", err) defer sumfile.Close() sumwriter := csv.NewWriter(sumfile) defer sumwriter.Flush() // define column headers sumheaders := []string{ "type", "year", "sum", } sumwriter.Write(sumheaders) var SumString string // Create sorted map by VALUE (integer) SortedSrMap := map[int]SumRecord{} SortedSrMapKeys := []int{} for key, val := range SortedSrMap { // SortedSrMap[val] = key // SortedSrMapKeys = append(SortedSrMapKeys, val) SumString = strconv.Itoa(key) fmt.Println("sumstring:", SumString, "value: ", val) } sort.Ints(SortedSrMapKeys) // END Create sorted map by VALUE (integer) // Export sum csv for key, val := range srMap { r := make([]string, 0, 1+len(sumheaders)) SumString = strconv.Itoa(val) r = append( r, key.Type, key.Year, SumString, ) sumwriter.Write(r) } sumwriter.Flush() // CREATE RESULTS CSV log.Println("Creating results csv file") file, err := os.Create("result.csv") checkError("Cannot create file", err) defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() // define column headers headers := []string{ "uid", "id", "type", "year", } // write column headers writer.Write(headers) var idString string var uidString string // Create sorted map var keys []int for k := range m { keys = append(keys, k) } sort.Ints(keys) for _, k := range keys { r := make([]string, 0, 1+len(headers)) // capacity of 4, 1 + the number of properties our struct has &amp; the number of column headers we are passing // convert the Record.ID and UID ints to string in order to pass into append() idString = strconv.Itoa(m[k].ID) uidString = strconv.Itoa(m[k].UID) r = append( r, uidString, idString, m[k].Type, m[k].Year, ) writer.Write(r) } writer.Flush() // END CREATE RESULTS CSV // Finally report results - update below line with more counters as desired log.Println("Articles:", articleCounter, "inproceedings", InProceedingsCounter, "proceedings:", ProceedingsCounter, "book:", BookCounter, "incollection:", InCollectionCounter, "phdthesis:", PhdThesisCounter, "mastersthesis:", mastersThesisCounter, "www:", wwwCounter) //log.Println("map:", m) //log.Println("map length:", len(m)) //log.Println("sum map length:", len(srMap)) //fmt.Println("sum map contents:", srMap) log.Println("XML parsing and csv export executed in:", time.Since(start)) } func increment(i *int) { *i = *i + 1 } func checkError(message string, err error) { if err != nil { log.Fatal(message, err) } } func makeCharsetReader(charset string, input io.Reader) (io.Reader, error) { if charset == "ISO-8859-1" { // Windows-1252 is a superset of ISO-8859-1, so it should be ok for this case return charmap.Windows1252.NewDecoder().Reader(input), nil } return nil, fmt.Errorf("Unknown charset: %s", charset) } </code></pre> <p>Main problems and issues I've identified:</p> <ul> <li>The parsing is quite slow (it takes about 3:45 minutes) given the size of the file (474 Mb gzip). Can I improve something to make it faster?</li> <li>Can the code be made less verbose but not at the expense of making it less readable / understandable to a person just starting out with Go? For example, by generalizing the structs which are used to define the different publication types as well as the <code>case</code> / <code>switch</code> statements?</li> </ul>
[]
[ { "body": "<p>The <code>decoder.Decode</code> call is unnecessary and in fact throws an error at\nthe moment.</p>\n\n<p>To your second point, yes, especially the <code>case</code> statements can all be\ncompressed down to a single function most likely, since they all only\nhave a few variables exchanged.</p>\n\n<p>The indexing into a hash map <code>map[int]Record</code> is not ideal, in fact\nthat's probably causing a slowdown too with the two million elements in\nthat table, instead you can simply <code>append</code> the elements to a slice and\nthen it's all sorted and fine for iteration later on, no sorting\nnecessary at all.</p>\n\n<p>And for <code>increment(&amp;i)</code> ... just go ahead and increment the counters.\nIf you make functions, okay, but like this it's not helping with\nreadability (<code>i += 1</code> is much clearer).</p>\n\n<p><code>make([]string, 0, 1+len(headers)</code> - well that's valid, but you can\nsimply create the array with all elements instead, like\n<code>[]string{uidString, ..., m[k].Year</code> etc. Might be even better if you\ncan reuse that array for all loop iterations.</p>\n\n<p>Well I can't see any other obvious things to change. There's the\npossibility that getting rid of <code>DecodeElement</code> and doing the whole\ndecoding yourself might improve things, but I'm skeptical. If I, for\nexample, remove the whole <code>switch</code> block, doing <em>nothing</em> but XML\ndecoding essentially, this still takes three minutes for me, essentially\njust one minute less than with that block included! Meaning that with\nthis library it's just not going to get much quicker overall.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:01:53.687", "Id": "417151", "Score": "1", "body": "Thanks for taking the time to review the code! I've reworked it based on your feedback:\n- Removed `decoder.Decode`.\n- Created single function to process the elements I'm interested in which will do the increments / map / slice appends.\n- For the increment functions, indeed they would make the code a bit more readable, however I want to keep them for now for learning's sake.\n- Working on removing the maps and using a slice instead.\nI was wondering whether it would be possible to \"concatenate\" the different structs, as the only difference about them is the `xml.Name` element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T22:25:19.750", "Id": "417176", "Score": "1", "body": "From what I know about the `encoding/xml` package I don't think there's anything to make more succinct about the structs unfortunately. You could go to a generic nested struct and to the decoding though without the struct definitions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T23:37:23.510", "Id": "215222", "ParentId": "215203", "Score": "2" } }, { "body": "<p>I've revisited the code to clean it up a bit and to follow some of the recommendations as I progress with my understanding of the language.</p>\n\n<p>Main points:</p>\n\n<p>Only two structs are now used:</p>\n\n<pre><code>type Metadata struct {\n Key string `xml:\"key,attr\"`\n Year string `xml:\"year\"`\n Author string `xml:\"author\"`\n Title string `xml:\"title\"`\n}\n\ntype Record struct {\n UID int\n ID int\n Type string\n Year string\n}\n</code></pre>\n\n<p>The publications are all processed with the following function: </p>\n\n<pre><code>func ProcessPublication(i Counter, publicationCounter Counter, publicationType string, publicationYear string, m map[int]Record) {\n m[i.Incr()] = Record{i.ReturnInt(), int(publicationCounter.Incr()), publicationType, publicationYear}\n}\n</code></pre>\n\n<p>The entire code looks now like this:</p>\n\n<pre><code>package main\n\nimport (\n \"compress/gzip\"\n \"encoding/csv\"\n \"encoding/xml\"\n \"fmt\"\n \"io\"\n \"log\"\n \"os\"\n \"sort\"\n \"strconv\"\n \"time\"\n\n \"golang.org/x/text/encoding/charmap\"\n)\n\n// Metadata contains the fields shared by all structs\ntype Metadata struct {\n Key string `xml:\"key,attr\"` // currently not in use\n Year string `xml:\"year\"`\n Author string `xml:\"author\"` // currently not in use\n Title string `xml:\"title\"` // currently not in use\n}\n\n// Record is used to store each Article's type and year which will be passed as a value to map m\ntype Record struct {\n UID int\n ID int\n Type string\n Year string\n}\n\ntype Count int\n\ntype Counter interface {\n Incr() int\n ReturnInt() int\n}\n\nvar articleCounter, InProceedingsCounter, ProceedingsCounter, BookCounter,\n InCollectionCounter, PhdThesisCounter, mastersThesisCounter, wwwCounter, i Count\n\nfunc main() {\n start := time.Now()\n\n //Open gzipped dblp xml\n //xmlFile, err := os.Open(\"TestDblp.xml.gz\")\n // Uncomment below for actual xml\n xmlFile, err := os.Open(\"dblp.xml.gz\")\n gz, err := gzip.NewReader(xmlFile)\n if err != nil {\n log.Fatal(err)\n\n } else {\n log.Println(\"Successfully Opened Dblp XML file\")\n }\n\n defer gz.Close()\n\n // Create decoder element\n decoder := xml.NewDecoder(gz)\n\n // Suppress xml errors\n decoder.Strict = false\n decoder.CharsetReader = makeCharsetReader\n if err != nil {\n log.Fatal(err)\n }\n\n m := make(map[int]Record)\n var p Metadata\n\n for {\n // Read tokens from the XML document in a stream.\n t, err := decoder.Token()\n\n // If we reach the end of the file, we are done with parsing.\n if err == io.EOF {\n log.Println(\"XML successfully parsed:\", err)\n break\n } else if err != nil {\n log.Fatalf(\"Error decoding token: %t\", err)\n } else if t == nil {\n break\n }\n\n // Let's inspect the token\n switch se := t.(type) {\n\n // We have the start of an element and the token we created above in t:\n case xml.StartElement:\n switch se.Name.Local {\n\n case \"article\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;articleCounter, se.Name.Local, p.Year, m)\n\n case \"inproceedings\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;InProceedingsCounter, se.Name.Local, p.Year, m)\n\n case \"proceedings\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;ProceedingsCounter, se.Name.Local, p.Year, m)\n\n case \"book\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;BookCounter, se.Name.Local, p.Year, m)\n\n case \"incollection\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;InCollectionCounter, se.Name.Local, p.Year, m)\n\n case \"phdthesis\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;PhdThesisCounter, se.Name.Local, p.Year, m)\n\n case \"mastersthesis\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;mastersThesisCounter, se.Name.Local, p.Year, m)\n\n case \"www\":\n decoder.DecodeElement(&amp;p, &amp;se)\n ProcessPublication(&amp;i, &amp;wwwCounter, se.Name.Local, p.Year, m)\n }\n }\n }\n log.Println(\"XML parsing done in:\", time.Since(start))\n\n // All parsed elements have been added to m := make(map[int]Record)\n // We create srMap map object and count the number of occurences of each publication type for a given year.\n\n srMap := make(map[Record]int)\n log.Println(\"Creating sums by article type per year\")\n for key := range m {\n sr := Record{\n Type: m[key].Type,\n Year: m[key].Year,\n }\n srMap[sr]++\n }\n\n // Create sumresult.csv\n log.Println(\"Creating sum results csv file\")\n sumfile, err := os.Create(\"sumresult.csv\")\n checkError(\"Cannot create file\", err)\n defer sumfile.Close()\n\n sumwriter := csv.NewWriter(sumfile)\n defer sumwriter.Flush()\n\n sumheaders := []string{\n \"publicationType\",\n \"year\",\n \"sum\",\n }\n\n sumwriter.Write(sumheaders)\n\n // Export sumresult.csv\n for key, val := range srMap {\n r := make([]string, 0, 1+len(sumheaders))\n r = append(\n r,\n key.Type,\n key.Year,\n strconv.Itoa(val),\n )\n sumwriter.Write(r)\n }\n sumwriter.Flush()\n\n // Create result.csv\n log.Println(\"Creating result.csv\")\n\n file, err := os.Create(\"result.csv\")\n checkError(\"Cannot create file\", err)\n defer file.Close()\n\n writer := csv.NewWriter(file)\n defer writer.Flush()\n\n headers := []string{\n \"uid\",\n \"id\",\n \"type\",\n \"year\",\n }\n\n writer.Write(headers)\n\n // Create sorted map\n var keys []int\n for k := range m {\n keys = append(keys, k)\n }\n sort.Ints(keys)\n\n for _, k := range keys {\n\n r := make([]string, 0, 1+len(headers))\n r = append(\n r,\n strconv.Itoa(m[k].UID),\n strconv.Itoa(m[k].ID),\n m[k].Type,\n m[k].Year,\n )\n writer.Write(r)\n }\n writer.Flush()\n\n // Finally report results\n log.Println(\"Articles:\", articleCounter, \"inproceedings\", InProceedingsCounter, \"proceedings:\",\n ProceedingsCounter, \"book:\", BookCounter, \"incollection:\", InCollectionCounter, \"phdthesis:\",\n PhdThesisCounter, \"mastersthesis:\", mastersThesisCounter, \"www:\", wwwCounter)\n log.Println(\"Distinct publication map length:\", len(m))\n log.Println(\"Sum map length:\", len(srMap))\n log.Println(\"XML parsing and csv export executed in:\", time.Since(start))\n}\n\nfunc checkError(message string, err error) {\n if err != nil {\n log.Fatal(message, err)\n }\n}\n\nfunc makeCharsetReader(charset string, input io.Reader) (io.Reader, error) {\n if charset == \"ISO-8859-1\" {\n // Windows-1252 is a superset of ISO-8859-1, so it should be ok for correctly decoding the dblp.xml\n return charmap.Windows1252.NewDecoder().Reader(input), nil\n }\n return nil, fmt.Errorf(\"Unknown charset: %s\", charset)\n}\n\nfunc (c *Count) Incr() int {\n *c = *c + 1\n return int(*c)\n}\n\nfunc (c *Count) ReturnInt() int {\n return int(*c)\n}\n\nfunc ProcessPublication(i Counter, publicationCounter Counter, publicationType string, publicationYear string, m map[int]Record) {\n m[i.Incr()] = Record{i.ReturnInt(), int(publicationCounter.Incr()), publicationType, publicationYear}\n}\n</code></pre>\n\n<p>I feel that the csv generation parts can be further streamlined as they are still a bit messy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-24T01:35:20.377", "Id": "216089", "ParentId": "215203", "Score": "0" } } ]
{ "AcceptedAnswerId": "215222", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T15:20:41.137", "Id": "215203", "Score": "6", "Tags": [ "parsing", "xml", "go" ], "Title": "Parse dblp XML and output sums of publications grouped by year and type" }
215203
<p>I'm new to Pandas, and slightly new to Python as well (but not development in general). I've got a chunk of code that works, but it feels like I'm missing out on the Pandas/Python way of doing something, and would love some feedback.</p> <p>In short, I'm doing calculations over a fixed period of time (say 60 months) where I apply a bunch of different financial calculations to generate various debits and credits. In this example I'm calculating gross incomes. I have models that represent the <code>Income</code>s, and want to create Dataframes with the corresponding data that I can eventually sum together for final answers.</p> <p>Full code for experimentation is available at <a href="https://repl.it/repls/BlissfulShabbyColdfusion" rel="nofollow noreferrer">https://repl.it/repls/BlissfulShabbyColdfusion</a> and repeated here:</p> <pre><code>### Income Models: ### start_date end_date amount yearly_raise 2019-01-01 2025-01-01 100.0 0.03 2020-01-01 2022-01-01 200.0 0. ### Base DataFrame: ### YearOffset 2019-01-01 0 2020-01-01 1 2021-01-01 2 2022-01-01 3 2023-01-01 4 </code></pre> <p>Then the code is as follows:</p> <pre><code>import datetime import numpy as np import pandas as pd class Income: def __init__(self, start, end, amount, yearly_raise): self.start = start self.end = end self.amount = amount self.yearly_raise = yearly_raise # Two sample income models incomes = [ Income(datetime.date(2019, 1, 1), datetime.date(2025, 1, 1), 100, 0.03), Income(datetime.date(2020, 1, 1), datetime.date(2022, 1, 1), 200, 0.) ] # Create dataframe with index of the next five years dates = pd.date_range('2019-01-01', periods=5, freq='YS') df = pd.DataFrame(np.arange(len(dates)), index=dates, columns=['YearOffset']) def calculate_monthly_income(row): """Given a dataframe row, add up all incomes applicable to that row/month""" value = 0. for income in incomes: # Filter on overlapping date ranges first if pd.Timestamp(income.start) &gt; row.name or pd.Timestamp(income.end) &lt; row.name: continue value += row['GrossIncome'] + income.amount * (1 + income.yearly_raise) ** row['YearOffset'] return value # Initialize a GrossIncome column and do the math df['GrossIncome'] = 0. df['GrossIncome'] = df.apply(calculate_monthly_income, axis=1) </code></pre> <p>And the after, which yields the correct results:</p> <pre><code>### After Calculations: ### YearOffset GrossIncome 2019-01-01 0 100.000000 2020-01-01 1 303.000000 2021-01-01 2 306.090000 2022-01-01 3 309.272700 2023-01-01 4 112.550881 </code></pre> <p><strong>Thoughts:</strong> </p> <ul> <li>I'm using <code>apply()</code> to iterate through the rows and assigning the result back into the dataframe. This works and beats using a for loop, but seems like there's probably a better way to do this.</li> <li>I'm still using a <code>for ... in</code> to iterate through multiple <code>Incomes</code></li> <li>The filtering by applicable date range also seems like I should probably be using some built-in Pandas thing like <code>mask</code>, but I'm unsure of where to start looking.</li> </ul> <p>There's a lot here, I know, but if there's some good feedback on the current approach or recommendations for better approaches, I'd love to hear them!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T22:59:16.287", "Id": "416205", "Score": "3", "body": "Welcome to Code Review. There is a lot of context missing in that code, for example `incomes`, `pd` and other values. As your repl.it snippet is quite short, I recommend you to include the complete snippet, including the `import`s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T02:11:24.320", "Id": "416215", "Score": "0", "body": "Thanks for the feedback @Zeta. I went ahead and pulled all the code in from the repl to provide context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T23:17:49.250", "Id": "417070", "Score": "0", "body": "Did you resolve this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T16:49:09.117", "Id": "215206", "Score": "2", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Efficiently/pythonically calculating new Dataframe rows" }
215206
<p>I read time complexity of radix sort is O(wn) or O(n log n), if all n numbers are distinct. After implementation it look to me as if I have implemented radix sort which has time complexity of O(n ^2). Please take a look at my implementation and suggest, if there is some implementation problem or my observation about time complexity is wrong. </p> <p><strong>Please note: I have hard coded few values for simplicity to sort 3 digit numbers only.</strong></p> <pre><code>private void LSBSort(int[] arr) { _LSBSort(arr, 1); } private void _LSBSort(int[] arr, int divisor) { Deque[] deques = new Deque[10]; for(int i = 0 ; i &lt; arr.length ; i++) { int mod = (arr[i] /divisor ) % 10; if (deques[mod] == null) { deques[mod] = new ArrayDeque&lt;&gt;(); } deques[mod].add(arr[i]); } divisor *= 10; if (divisor &gt; 1000) { return; } int cursor = 0; for (int i = 0 ; i &lt; 10 ; i++) { if (deques[i] != null) { for (int j = 0 ; j &lt;= deques[i].size() ; j++) { cursor = cursor + j; arr[cursor] = (int)deques[i].pollFirst(); } cursor++; } } _LSBSort(arr, divisor); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T22:07:13.670", "Id": "416198", "Score": "0", "body": "Why do you think the time complexity is O(n^2)? To me, it looks like each run of `_LSBSort` takes time O(n), and it is repeated w times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T00:41:48.527", "Id": "416211", "Score": "0", "body": "Due to nested for loop in _LSBSort and if every deque is not null it will take O(n^2) time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T00:47:29.837", "Id": "416212", "Score": "0", "body": "Remember that each item in the list is in exactly one of the deques -- thus iterating through all 10 deques is only iterating through n objects in total." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T02:38:48.567", "Id": "416219", "Score": "0", "body": "but one qeque can have more than one element and iterating each deque is proportional to its size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T04:09:47.697", "Id": "416221", "Score": "2", "body": "Precisely. Say `deques[i]` contains si items, so iterating over it takes time O(si). Then the outer `for` loop takes time O(s1) + O(s2) ... + O(s10) = O(s1 + s2 + ... + s10). But since each item occurs in exactly one deque, we know s1 + s2 + ... + s10 = n. Conclude the loop takes time O(n)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T07:06:28.777", "Id": "416409", "Score": "0", "body": "Got it, thanks. Can you put this as an answer, so other can easily follow it." } ]
[ { "body": "<p><strong>First</strong>: the runtime is O(wn), as it should be for this algorithm.</p>\n\n<p>Consider a single run of <code>_LSBSort</code>. Let n be the length of <code>arr</code>. Clearly the first loop is time O(n). Let si be the length of <code>deques[i]</code>. Then the second loop is time\n<span class=\"math-container\">$$ O(s_1) + O(s_2) + \\dots + O(s_{10}) = O(s_1 + s_2 + \\dots + s_{10}).$$</span>\nNoting that each element is present in exactly one of the deques, we conclude\n<span class=\"math-container\">$$s_1 + s_2 + \\dots + s_{10} = n.$$</span>\nThus the entire method runs in time O(n). As it is called w times, we conclude the entire algorithm is O(wn) time.</p>\n\n<p><strong>Second</strong>: some comments on the code.</p>\n\n<ol>\n<li>These methods should be static.</li>\n<li>Use an <code>ArrayList</code> for <code>deque</code>. Arrays of generics are just too ugly.</li>\n<li>Call the list <code>deques</code> because it is plural. </li>\n<li>Initialize all the deques up front. Clear and reuse between iterations.</li>\n<li>Use extended for loops throughout.</li>\n<li>Use loop instead of recursion.</li>\n</ol>\n\n<pre><code>private static void LSBSort(int[] arr) {\n List&lt;ArrayDeque&lt;Integer&gt;&gt; deques = new ArrayList&lt;&gt;(10);\n for (int i = 0; i &lt; 10; i++) {\n deques.add(new ArrayDeque&lt;Integer&gt;());\n }\n\n for (int d = 1; d &lt;= 1000; d *= 10) {\n for(int i : arr) {\n deques.get((i / d) % 10).add(i);\n }\n\n int cursor = 0;\n for (Deque&lt;Integer&gt; D : deques) {\n for (Integer j : D) {\n arr[cursor++] = j;\n }\n\n D.clear();\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T07:12:42.863", "Id": "215320", "ParentId": "215207", "Score": "1" } } ]
{ "AcceptedAnswerId": "215320", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:35:50.673", "Id": "215207", "Score": "0", "Tags": [ "java", "sorting", "radix-sort" ], "Title": "Time complexity of radix sort" }
215207
<p>This was my first time attempting a project like this, so I figured it would improve readability, and would also just be nice If I allowed each stage to be visualized.</p> <p>Also, this only generates them, I haven't done any solving code, so it can't know if a puzzle has multiple solutions. I didn't forget, I just want to perfect this part first.</p> <p>First up is the <code>Main.java</code> class. it contains the vast majority of my code, and is divided up into several methods whose purposes should be pretty obvious. also, I'd like to mention that while I don't have it implemented here, my code could scale up puzzles other sizes as well.</p> <pre><code>package com.kestrel.sudoku.generate; import java.util.Random; public class Main4 { public static int[] seed = new int[81]; public static int[] cells = new int[81]; public static int[] finalPuzzle = new int[81]; public static void main(String[] args) { genSeed(); genSudoku(); genResult(); printSeed(); System.out.println(); printSudoku(); System.out.println(); printResult(); } public static boolean genSudoku() { Random r = new Random(); for(int y = 0; y &lt; 9; y++) { for(int x = 0; x &lt; 9; x++) { if(cells[9 * y + x] == 0) { for(int i = 0; i &lt; 9; i++) { int n = r.nextInt(9) + 1; if(isSafe(x, y, n)) { cells[9 * y + x] = n; if(genSudoku()) { return true; } else { cells[9 * y + x] = 0; } } } return false; } } } return true; } public static boolean isSafe(int x, int y, int n) { for (int i = 0; i &lt; 9; i++) { if(cells[9 * y + i] == n) { return false; } } for (int i = 0; i &lt; 9; i++) { if(cells[9 * i + x] == n) { return false; } } for (int a = 0 ; a &lt; 3; a++) { for (int b = 0 ; b &lt; 3; b++) { if (cells[9 * (y - y % 3) + (x - x % 3) + (9 * a + b)] == n) { return false; } } } return true; } public static void fill(int[] a, int num) { for (int i = 0; i &lt; a.length; i++) { cells[i] = num; } } public static void genSeed() { Random r = new Random(); for(int i = 0; i &lt; 9; i++) { int n = r.nextInt(81); if(seed[n] == 1 || seed[80 - n] == 1 ) { i--; } else { seed[n] = 1; seed[80 - n] = 1; } } } public static void genResult() { for(int y = 0; y &lt; 9; y++) { for (int x = 0; x &lt; 9; x++) { if(seed[9 * y + x] == 1) { finalPuzzle[9 * y + x] = cells[9 * y + x]; } else { finalPuzzle[9 * y + x] = 0; } } } } public static void printSeed() { for(int y = 0; y &lt; 9; y++) { for (int x = 0; x &lt; 9; x++) { System.out.print(seed[9 * y + x] + " "); if(x % 3 == 2 &amp;&amp; x &lt; 8) { System.out.print("| "); } } System.out.println(); if(y % 3 == 2 &amp;&amp; y &lt; 8) { System.out.println("---------------------"); } } } public static void printSudoku() { for(int y = 0; y &lt; 9; y++) { for (int x = 0; x &lt; 9; x++) { System.out.print(cells[9 * y + x] + " "); if(x % 3 == 2 &amp;&amp; x &lt; 8) { System.out.print("| "); } } System.out.println(); if(y % 3 == 2 &amp;&amp; y &lt; 8) { System.out.println("---------------------"); } } } public static void printResult() { for(int y = 0; y &lt; 9; y++) { for (int x = 0; x &lt; 9; x++) { if(seed[9 * y + x] == 1) { System.out.print(finalPuzzle[9 * y + x] + " "); } else { System.out.print(" "); } if(x % 3 == 2 &amp;&amp; x &lt; 8) { System.out.print("| "); } } System.out.println(); if(y % 3 == 2 &amp;&amp; y &lt; 8) { System.out.println("---------------------"); } } } } </code></pre> <p>One part that I'm really not happy with is that I couldn't figure out any solution other than a recursive function for generating the full Sudoku. I'm guess It might just be because I'm still semi-new to programming, but It just looks really ugly. at one point, I thought I had a solution, a double <code>for</code> loop where one would increment, and the other would decrement, and they shared a variable, but I just couldn't get it to work. I guess the other thing I should mention is the lack of 2d arrays in my code. I don't like them either. I'd rather just do the math. I don't know if it's faster, (its probably not) but I think that's just kinda my coding style at this point. plus, I didn't have to iterate over every single cell this way. only the ones I wanted to. I think that should be it. Looking at it now... I think I could probably get rid of some duplicate code in the <code>isSafe()</code> and <code>printX()</code> functions. so... how did I do?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T22:02:32.793", "Id": "416197", "Score": "0", "body": "What is the purpose of the class `Cell`? It is never used in the main program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T22:54:46.833", "Id": "416202", "Score": "0", "body": "... you are correct. One of the previous versions used it, and I guess I got confused. My project basically looks like a whole bunch of main#.java files, and then whatever else they use, with pretty much zero indication of what uses what. I'll fix that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T07:43:18.253", "Id": "416414", "Score": "0", "body": "`genSudoku()` is actually also a puzzle solving function, in addition to being a puzzle generating function. So you can use that to verify that the final puzzle has a solution (although there may be more than 1 solution). However it is quite inefficient and I suggest looking at other sudoku solvers for inspiration (some are on this site even)." } ]
[ { "body": "<ol>\n<li><p>The <code>fill</code> method is never used.</p></li>\n<li><p>State should not be <code>public static</code>. By passing the relevant data to the relevant methods, you can make a lot more sense of your code, and allow more reusability of methods.</p></li>\n<li><p>None of your methods save <code>main</code> need be <code>public</code>.</p></li>\n<li><p>Choosing a data structure is not a matter of coding style! If you are going to use a 1D array to represent a grid, a rather unintuitive choice, it better help you write elegant code. There are a few places were we can use this 1D structure to our advantage: looping over <code>n</code> instead of <code>x, y</code> in <code>genSodoku</code> and <code>genResult</code> for instance.</p></li>\n<li><p><code>genSoduku</code> is implemented very inefficiently. Instead of looping to find the next empty value, just pass it to the recursive call.</p></li>\n<li><p>In the same method, you need to use a random permutation instead of a random generator. <code>Random.nextInt</code> samples \"with replacement\"; thus some numbers might not be considered. I used <code>Collections.shuffle</code> to do same \"without replacement\" instead.</p></li>\n<li><p><code>genSeed</code> is ill-documented. Explain why you are selecting numbers likes this.</p></li>\n<li><p>In <code>genResult</code> multiply <code>cells[n]</code> and <code>seed[n]</code> to get the same result.</p></li>\n<li><p>Consolidate printing into a single <code>printBoard</code> method that take a 9-by-9 table.</p></li>\n</ol>\n\n<pre><code>import java.util.Random;\nimport java.util.stream.IntStream;\nimport java.util.stream.Collectors;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Main4 {\n\n public static void main(String[] args) {\n int[] seed = genSeed();\n int[] cells = genSudoku();\n int[] finalPuzzle = genResult(seed, cells);\n\n printBoard(seed);\n printBoard(cells);\n printBoard(finalPuzzle);\n }\n\n private static int[] genSudoku() {\n int[] cells = new int[81];\n genHelper(cells, 0);\n return cells;\n }\n\n private static List&lt;Integer&gt; getPermutation() {\n List&lt;Integer&gt; choices = IntStream.rangeClosed(1,9)\n .boxed().collect(Collectors.toList());\n Collections.shuffle(choices);\n return choices;\n }\n\n private static boolean genHelper(int[] cells, int n) {\n if (n == 81) {\n return true;\n }\n\n List&lt;Integer&gt; choices = getPermutation();\n for (int k : choices) {\n if(isSafe(cells, n, k)) {\n cells[n] = k;\n if(genHelper(cells, n + 1)){\n return true;\n }\n }\n }\n\n cells[n] = 0;\n return false;\n }\n\n private static boolean isSafe(int[] cells, int n, int k) {\n int y = n / 9, x = n % 9;\n\n for (int i = 0; i &lt; 9; i++) {\n if(cells[9 * y + i] == k || cells[9 * i + x] == k) {\n return false;\n }\n }\n\n for (int a = 0 ; a &lt; 3; a++) {\n for (int b = 0 ; b &lt; 3; b++) {\n if (cells[9 * (y - y % 3) + (x - x % 3) + (9 * a + b)] == k) {\n return false;\n }\n }\n }\n return true;\n }\n\n private static int[] genSeed() {\n int[] seed = new int[81];\n Random r = new Random();\n\n for(int i = 0; i &lt; 9; i++) {\n int n = r.nextInt(81);\n if(seed[n] == 1 || seed[80 - n] == 1 ) {\n i--;\n } else {\n seed[n] = 1;\n seed[80 - n] = 1;\n }\n }\n return seed;\n }\n\n private static int[] genResult(int[] seed, int[] cells) {\n int[] finalPuzzle = new int[81];\n for(int n = 0; n &lt; 81; n++) {\n finalPuzzle[n] = seed[n] * cells[n];\n }\n return finalPuzzle;\n }\n\n private static void printBoard(int[] board) {\n for(int y = 0; y &lt; 9; y++) { \n for (int x = 0; x &lt; 9; x++) {\n System.out.print(board[9 * y + x] + \" \");\n if(x % 3 == 2 &amp;&amp; x &lt; 8) {\n System.out.print(\"| \");\n }\n }\n System.out.println();\n if(y % 3 == 2 &amp;&amp; y &lt; 8) {\n System.out.println(\"---------------------\");\n }\n }\n System.out.println();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T00:55:57.677", "Id": "215224", "ParentId": "215208", "Score": "2" } }, { "body": "<p>For generating one Sudoku, you should only create a single random number generator. It should be configurable so that you can pass a predictable random number generator during tests. Like this:</p>\n\n<pre><code>public class SudokuGenerator {\n\n private final Random rnd;\n\n public SudokuGenerator(Random rnd) {\n this.rnd = rnd;\n }\n\n public Sudoku generate() {\n …\n }\n}\n</code></pre>\n\n<p>The current <code>genSolve</code> code looks frightening and inefficient. Having a 3-times nested <code>for</code> loops combined with 3 intermingled <code>if</code> statements and calling this method recursively sounds like a bad design. There must be something simpler. I don't know what, but it must exist.</p>\n\n<p>A fairly advanced Sudoku generator is available <a href=\"https://git.tartarus.org/?p=simon/puzzles.git;a=blob;f=solo.c\" rel=\"nofollow noreferrer\">as part of Simon Tatham's Puzzle Collection</a>. The code is written in C but has lots of explaining comments, so you should be able to get some ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T01:35:02.887", "Id": "416213", "Score": "0", "body": "Yeah, it was pretty much a nightmare to get working. Trust me, if I could have gotten that damn for-loop-thing to work, I 100% would have used it instead. The issue was that it just didn't \"remember\" stuff like the resursive one did. I tried to implement it with a stack, but no dice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T01:15:54.493", "Id": "215228", "ParentId": "215208", "Score": "2" } } ]
{ "AcceptedAnswerId": "215228", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T17:52:04.860", "Id": "215208", "Score": "4", "Tags": [ "java", "algorithm", "recursion", "sudoku" ], "Title": "Three stage Sudoku puzzle generator" }
215208
<p>Building upon my <a href="https://codereview.stackexchange.com/questions/214673/reading-all-file-contents-via-x64-assembly">previous question</a>, I have come up with a method that'll search through a buffer and return a pointer to the end of the line. The primary purpose of the function to extract rows from a csv file using the logic specified in <a href="https://www.rfc-editor.org/rfc/rfc4180" rel="nofollow noreferrer">RFC4180</a>; the third parameter <code>isQuotedSequence</code> can be used in cases where parsing is parallelized or started in the middle of a string that is known to be quoted.</p> <p><strong>Notes</strong>:</p> <ul> <li>the excessive amount of comments are for people who may not know the language but still want to try and understand what the code is doing</li> <li>registers are renamed primarily to aid in refactoring but also enable some rudimentary static analysis to be performed</li> <li>the <code>isQuotedSequence</code> variable is placed in the <code>rdx</code> register in order to mimic operations like <code>mul</code> that return a 128-bit result; I'm not sure if this is actually usable by anything other than ASM or supported by the <code>Windows x64</code> or <code>System V</code> ABIs though...</li> </ul> <br/> Anything info that could be used to make the function safer or more performant would be most useful; thanks for your review! <br/> **Code:** <pre><code>COMMENT @ C Interface: extern char* ReadLine(const char* bufferOffset, const char* bufferTail, long long isQuotedSequence); Reference: https://www.rfc-editor.org/rfc/rfc4180 @ ;-----------------------------; (CONSTANTS) CARRIAGE_RETURN = 00000000Dh DOUBLE_QUOTE = 000000022h LINE_FEED = 00000000Ah TRUE = 000000001h ;-----------------------------; (ARGUMENTS) arg0 textequ &lt;rcx&gt; arg1 textequ &lt;rdx&gt; arg2 textequ &lt;r8&gt; ;-----------------------------; (LOCALS) bufferOffset textequ &lt;rax&gt; bufferTail textequ &lt;r9&gt; currentCharacter textequ &lt;ecx&gt; isQuotedSequence textequ &lt;rdx&gt; nextCharacter textequ &lt;r8d&gt; .code ReadLine proc mov bufferOffset, arg0 ; initialize [bufferOffset] mov bufferTail, arg1 ; initialize [bufferTail] mov isQuotedSequence, arg2 ; initialize [isQuotedSequence] cmp bufferOffset, bufferTail ; validate that there are more characters to read jge ReadLine@Return ; if end of file reached, jump to Return movzx nextCharacter, byte ptr[bufferOffset] ; extract [nextCharacter] from [bufferOffset] ReadLine@NextChar: mov currentCharacter, nextCharacter ; shift [nextCharacter] into [currentCharacter] add bufferOffset, 1h ; increment [bufferOffset] cmp bufferOffset, bufferTail ; validate that there are more characters to read jge ReadLine@Return ; if end of file reached, jump to Return movzx nextCharacter, byte ptr[bufferOffset] ; extract [nextCharacter] from [bufferOffset] cmp currentCharacter, DOUBLE_QUOTE ; compare [currentCharacter] to QUOTE_DOUBLE jz ReadLine@HitDoubleQuote ; if equal, jump to HitDoubleQuote cmp currentCharacter, CARRIAGE_RETURN ; compare [currentCharacter] to CARRIAGE_RETURN jz ReadLine@HitCarriageReturn ; if equal, jump to HitCarriageReturn cmp currentCharacter, LINE_FEED ; compare [currentCharacter] to LINE_FEED jz ReadLine@HitLineFeed ; if equal, jump to HitLineFeed jmp ReadLine@NextChar ; jump to NextChar ReadLine@HitDoubleQuote: xor isQuotedSequence, TRUE ; invert [isQuotedSequence] indicator jmp ReadLine@NextChar ; jump to NextChar ReadLine@HitCarriageReturn: cmp nextCharacter, LINE_FEED ; compare [nextCharacter] to LINE_FEED jz ReadLine@NextChar ; if equal, jump to NextChar ReadLine@HitLineFeed: cmp isQuotedSequence, TRUE ; compare [isQuotedSequence] to TRUE jz ReadLine@NextChar ; if equal, jump to NextChar ReadLine@Return: ret ; return to caller ReadLine endp end </code></pre>
[]
[ { "body": "<p>You're treating comparison of addresses as <em>signed</em> values, instead of <em>unsigned</em>. For example, after you execute <code>cmp bufferOffset, bufferTail</code>, you use the <code>jge</code> condition, which is <em>jump greater or equal</em>. This is intended for signed values. You should use <code>jae</code> <em>jump above or equal</em> instruction instead. This condition needs to be changed in several places.</p>\n\n<p>Rather than <code>add bufferOffset, 1h</code>, just use <code>inc bufferOffset</code>.</p>\n\n<p>From a readability perspective, having all those leading zeros on you constants makes the actual value a little harder to read, and implies that they could potentially have some value that would be that large. Since most of those values are character codes, two digits should suffice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T19:05:37.837", "Id": "416183", "Score": "0", "body": "Regarding consistency with carriage return, this is to handle all possible cases of valid line endings: \\r\\n, \\r, \\n. In other words, the line feed after a carriage return is optional (thanks to varying OS behavior)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T19:24:38.630", "Id": "416187", "Score": "0", "body": "@Kittoes0124 I got confused by the `nextCharacter` check. I've removed that paragraph from the review." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:59:53.483", "Id": "215210", "ParentId": "215209", "Score": "4" } }, { "body": "<p>Ok, old question. But no accepted answer and I've got some thoughts, so...</p>\n\n<p>My first thought on reading this code was to suggest you re-arrange your compares, so that you can \"drop through\" rather than doing an additional jump. If you move this to the end of your compare block:</p>\n\n<pre><code>cmp currentCharacter, DOUBLE_QUOTE ; compare [currentCharacter] to QUOTE_DOUBLE\njnz ReadLine@NextChar ; &lt;-- Note: jnz\n</code></pre>\n\n<p>You can get rid of that extra <code>jmp</code>, dropping straight into HitDoubleQuote.</p>\n\n<p>But upon reflection, it might be better to leave it where it is, and add an additional jmp.</p>\n\n<p>Consider the string <code>Goodbye cruel world.\\n</code> How many compares and how many jumps instructions does this take with your current code? Excluding the bufferTail, there's 3 cmp, 3 jz, and 1 jmp for every character. That's 63 cmp, 63 jz, and 62 jmp (including the end of line, which doesn't jmp).</p>\n\n<p>Now, what if right after <code>cmp currentCharacter, DOUBLE_QUOTE</code> you add <code>jg ReadLine@NextChar</code>? Since jg doesn't affect the flags, there would be no need to do an extra cmp, so you're just adding one instruction. And since the \"largest\" value you're interested in parsing is the DOUBLE_QUOTE (0x22), any value greater than that and you already know what to do.</p>\n\n<p>And look what happens to the number of cmp/jz/jmp.</p>\n\n<p>cmp:21+3*2 = 27, jz: 21+3*3 = 30, jmp: 2</p>\n\n<p>To clarify: We'd only go past the jg 3 times: twice for the spaces (0x20), and once for eol (0xa). So, while tabs, spaces, lf, cr, double quotes and exclamation marks (0x21) would all become 1 instruction more expensive due to the extra jg, all the letters and numbers become 5 instructions cheaper.</p>\n\n<p>Worth doing? Probably not now that you likely haven't looked at the code in the last 5 months. But something to think about for next time.</p>\n\n<p>Note: You could still take advantage of the drop thru. Something like this:</p>\n\n<pre><code> cmp currentCharacter, DOUBLE_QUOTE ; compare [currentCharacter] to QUOTE_DOUBLE\n jg ReadLine@NextChar ; not DOUBLE_QUOTE or control code\n jz ReadLine@HitDoubleQuote ; if equal, jump to HitDoubleQuote\n\n cmp currentCharacter, LINE_FEED ; compare [currentCharacter] to LINE_FEED\n jz ReadLine@HitLineFeed ; if equal, jump to HitLineFeed\n\n cmp currentCharacter, CARRIAGE_RETURN ; compare [currentCharacter] to CARRIAGE_RETURN\n jnz ReadLine@NextChar ; if not CR, get next character\n\nReadLine@HitCarriageReturn:\n cmp nextCharacter, LINE_FEED ; compare [nextCharacter] to LINE_FEED\n jz ReadLine@NextChar ; if equal, jump to NextChar\n\nReadLine@HitLineFeed:\n cmp isQuotedSequence, TRUE ; compare [isQuotedSequence] to TRUE\n jz ReadLine@NextChar ; if equal, jump to NextChar\n\nReadLine@Return:\n ret ; return to caller\n\nReadLine@HitDoubleQuote:\n xor isQuotedSequence, TRUE ; invert [isQuotedSequence] indicator\n jmp ReadLine@NextChar ; jump to NextChar\n\nReadLine endp\n</code></pre>\n\n<p>Notice how the <code>jmp</code> is gone after the compares?</p>\n\n<p>What else? 1201ProgramAlarm already mentioned using <code>inc</code> vs <code>add</code>. That's one byte shorter. However you could also use <code>lea rax, [rax + 1]</code>. While it's not shorter than add, it doesn't use the flags register (which both add and inc do). This might ease the CPU's pipelining.</p>\n\n<p>Similarly, <code>xor edx</code> is only 3 bytes, compared to <code>xor rdx</code> which is 4. Since you're only using 1 bit, I don't see any need to use rdx. Similarly, why use r8d/movzx instead of just 'mov r8b, [rax]`? Again, it's a byte shorter.</p>\n\n<p>I note that there is no facility provided for error returns. What if you are inside a quoted string when you hit bufferTail? You want to be able to start \"mid string,\" but you don't return a value indicating that you need to do so? Maybe return NULL in this case? And I guess the caller can check if the return value is bufferTail to detect a missing cr/lf.</p>\n\n<p>I get what you are saying about 128 bit returns. But I don't see a practical way to do that here. Such being the case, you're incurring a penalty (of swapping registers around) for a benefit you cannot (or at least do not) achieve.</p>\n\n<p>From an ease of use point of view, I might be tempted to change the call to:</p>\n\n<pre><code>extern char* ReadLine(const char* bufferOffset, size_t length, bool sQuotedSequence);\n</code></pre>\n\n<p>Obviously I haven't seen the code for the caller, but keeping track of lengths might be a bit easier for people to grasp than \"a pointer to 1 byte after your string.\" Even better might be to indicate that NUL (0x0) is a buffer terminator and may not be embedded in the string. Then you don't need either bufferTail or length, you can just check for currentCharacter being 0.</p>\n\n<p>You apologize for:</p>\n\n<blockquote>\n <p>the excessive amount of comments</p>\n</blockquote>\n\n<p>I'm not sure there is such a thing in asm. They add nothing at all to the execution time of the code, and greatly reduce the maintenance time. In fact, adding comments about how you check for missing cr/lf or how mismatched quoted strings are handled might be a good idea. On the other hand, if the function ever gets <em>changed</em>, the maintainer has to go thru them all and make sure they reflect the new logic or you end up with comments that are WRONG, which can be worse than no comments.</p>\n\n<p>A few stylistic nits: I might add more blank lines to make things easier to read. And I'm pretty sure using \"proc\" means that labels are local to the function. So the \"ReadLine@\" (to avoid conflict with names in other functions?) may be redundant. And as the guy said last time, I'd probably go with <code>je</code> rather than <code>jz</code>. Functionally they're identical, but conceptually you're (J)umping depending on whether currentCharacter is (E)qual to DOUBLE_QUOTE. And you have several comments that read \"compare [nextCharacter]\". Putting the brackets means you're going to read the value at the <em>address</em> pointed to by nextCharacter. But nextCharacter isn't a pointer, it's the actual value. They're comments, but still.</p>\n\n<p>And one last thought: Unless this was a homework project for an asm class, why write this in asm? Unless you know what \"instruction fusing\" and \"pipelining\" mean and what causes \"stalling\" and a dozen other esoteric concepts, squeezing the max perf out of assembler is <em>really hard</em>. The people who write c/c++ compilers are all completely bonkers, but they <strong>do</strong> understand this stuff and have decades worth of \"tricks\" they can apply. As a result, well-structured c code can actually result in smaller code and faster execution times than asm written by us mere mortals.</p>\n\n<hr>\n\n<p>Edit: Rolling my (non-stylistic) comments in:</p>\n\n<pre><code>;-----------------------------; (CONSTANTS)\nCARRIAGE_RETURN = 00Dh\nDOUBLE_QUOTE = 022h\nLINE_FEED = 00Ah\n\narg0 textequ &lt;rcx&gt;\nbufferOffset textequ &lt;rax&gt;\nbufferTail textequ &lt;rdx&gt;\ncurrentCharacter textequ &lt;cl&gt;\nisQuotedSequence textequ &lt;r8d&gt;\nnextCharacter textequ &lt;r9b&gt;\n\n.code\n\nRfc4180_ReadRow proc\n mov bufferOffset, arg0 ; initialize bufferOffset\n\n cmp bufferOffset, bufferTail ; validate that there are more characters to read\n jae Rfc4180_ReadRow@Return ; if end of file reached, jump to Return\n\n mov nextchar, byte ptr[bufferOffset] ; extract nextCharacter from [bufferOffset]\n\n; todo try adding: .align xx\nRfc4180_ReadRow@NextChar:\n mov currentCharacter, nextchar ; shift nextCharacter into currentCharacter\n inc bufferOffset ; increment bufferOffset\n ; todo maybe replace inc: lea bufferOffset, [bufferOffset + 1]\n\n cmp bufferOffset, bufferTail ; validate that there are more characters to read\n jae Rfc4180_ReadRow@Return ; if end of file reached, jump to Return\n\n mov nextchar, byte ptr[bufferOffset] ; extract nextCharacter from [bufferOffset]\n\n cmp currentCharacter, DOUBLE_QUOTE ; compare currentCharacter to QUOTE_DOUBLE\n ; todo maybe add: jg Rfc4180_ReadRow@NextChar\n jz Rfc4180_ReadRow@HitDoubleQuote ; if equal, jump to HitDoubleQuote\n\n cmp currentCharacter, LINE_FEED ; compare currentCharacter to LINE_FEED\n jz Rfc4180_ReadRow@HitLineFeed ; if equal, jump to HitLineFeed\n\n cmp currentCharacter, CARRIAGE_RETURN ; compare currentCharacter to CARRIAGE_RETURN\n jnz Rfc4180_ReadRow@NextChar ; if not CARRIAGE_RETURN, NextChar\n\nRfc4180_ReadRow@HitCarriageReturn:\n cmp nextchar, LINE_FEED ; compare nextCharacter to LINE_FEED\n jz Rfc4180_ReadRow@NextChar ; if equal, jump to NextChar\n\nRfc4180_ReadRow@HitLineFeed:\n test isQuotedSequence, isQuotedSequence ; see if isQuotedSequence is set\n jnz Rfc4180_ReadRow@NextChar ; if set, jump to NextChar\n\nRfc4180_ReadRow@Return:\n ret ; return to caller\n\nRfc4180_ReadRow@HitDoubleQuote:\n xor isQuotedSequence, 1 ; invert isQuotedSequence indicator\n jmp Rfc4180_ReadRow@NextChar ; jump to NextChar\n\nRfc4180_ReadRow endp\n\nend\n</code></pre>\n\n<p>Note: I haven't even <em>assembled</em> this let alone validated or perf tested it. Still, shows you what I'm thinking. While I <em>think</em> it's likely to be better, that can't be known until someone times it against real data. See the 3 <code>todo</code>s for more things to try.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:02:53.543", "Id": "440290", "Score": "0", "body": "`Worth doing? Probably not now that you likely haven't looked at the code in the last 5 months. But something to think about for next time.` One would then probably be surprised at how important it is to me to get this 'right'; pipelining, micro-op fusion, port pressure, instruction latency, etc are all metrics that I care deeply about and have been heavily researching throughout the development of this code. Why? Another project of mine emits and later directly executes x64 bytecode. The belated advice is much appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:19:27.833", "Id": "440293", "Score": "0", "body": "If you're at all interested: the latest revision can be found [here](https://gist.github.com/Kittoes0124/c2288ec4daee90f549dfe73430494847). I'm fairly busy for the next couple of weeks but will definitely find time to test and incorporate many of the changes you've suggested (including stuff related to comments, I found them very sensible). Other stuff like `jz` vs `je` is unlikely to change because this code is primarily just for myself and I find it way easier to collapse the two concepts into a single instruction than mentally tracking the meaning of two instructions; bonkers, I know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:21:06.470", "Id": "440294", "Score": "1", "body": "Ahh. Then you've probably already bumped in to everything I mentioned that was useful. If you are into pipeline analysis, the two best things I know to point you at are [IACA](https://stackoverflow.com/a/26021338/2189500) and [agner fog](https://www.agner.org/optimize/). If you want to compare the latency of `movzx` vs `mov`, agner's guide has all the numbers, and Intel's tool can (statically) analyze your code and show the computed latency numbers and fusions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:29:32.853", "Id": "440296", "Score": "0", "body": "I literally have Agner bookmarked as \"The Old Testament\"; though one doesn't pretend to have mastered the teachings contained within... IACA also guided me to the current layout of the code. I don't at all remember if the instruction/structure changes you suggested were already tested but am more than happy to try again when I get the chance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:36:33.933", "Id": "440297", "Score": "0", "body": "Looking at your current code, some of my (non-stylistic) suggestions still apply. If this really is performance critical, you should give it another look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:51:06.537", "Id": "440300", "Score": "0", "body": "Oh I totally intend to, especially that `lea rax, [rax + 1]` trick; one had failed to consider the concept of 'pressure' on the flags register." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T00:29:48.537", "Id": "226534", "ParentId": "215209", "Score": "2" } } ]
{ "AcceptedAnswerId": "226534", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T18:24:51.787", "Id": "215209", "Score": "3", "Tags": [ "performance", "csv", "assembly" ], "Title": "Multi-line text reader (x64 ASM)" }
215209
<p>A whiteboarding challenge: Given a 2D array (matrix) <code>inputMatrix</code> of integers, create a function <code>spiralCopy</code> that copies <code>inputMatrix</code>'s values into a 1D array in a clockwise spiral order. Your function then should return that array.</p> <pre><code>inputMatrix = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36] ] const spiralCopy = (matrix) =&gt; { const spiralLength = matrix.length * matrix[0].length; const spiral = []; let iLeftRightStart = 0; // +1 let iLeftRightEnd = matrix[0].length; // -1 let leftRightPosition = 0; // +1 let iTopBottomStart = 1; // +1 let iTopBottomEnd = matrix.length; // -1 let topBottomPosition = matrix[0].length - 1; // -1 let iRightLeftStart = matrix[0].length - 2; // -1 let iRightLeftEnd = 0; // +1 let rightLeftPosition = matrix.length - 1; // -1 let iBottomTopStart = matrix.length - 2; // -1 let iBottomTopEnd = 1; // +1 let bottomTopPosition = 0; // +1 const leftToRight = (iStart, iEnd, position) =&gt; { for (let i = iStart; i &lt; iEnd; i++) { spiral.push(matrix[position][i]); } } const topToBottom = (iStart, iEnd, position) =&gt; { for (let i = iStart; i &lt; iEnd; i++) { spiral.push(matrix[i][position]); } } const rightToLeft = (iStart, iEnd, position) =&gt; { for (let i = iStart; i &gt;= iEnd; i--) { spiral.push(matrix[position][i]); } } const bottomToTop = (iStart, iEnd, position) =&gt; { for (let i = iStart; i &gt;= iEnd; i--) { spiral.push(matrix[i][position]); } } while (spiral.length &lt; spiralLength) { leftToRight(iLeftRightStart, iLeftRightEnd, leftRightPosition); topToBottom(iTopBottomStart, iTopBottomEnd, topBottomPosition); rightToLeft(iRightLeftStart, iRightLeftEnd, rightLeftPosition); bottomToTop(iBottomTopStart, iBottomTopEnd, bottomTopPosition); iLeftRightStart++; iLeftRightEnd--; leftRightPosition++; iTopBottomStart++; iTopBottomEnd--; topBottomPosition--; iRightLeftStart--; iRightLeftEnd++; rightLeftPosition--; iBottomTopStart--; iBottomTopEnd++; bottomTopPosition++; } return spiral; } console.log(spiralCopy(inputMatrix)); // prints [1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21] </code></pre> <p>So the function works and runs with time complexity of O(N). However, I don't like that I'm using 12 different variables which I then increment/decrement. How can this be consolidated, and is it possible to make the algorithm even faster due to the instant access of JavaScript arrays?</p>
[]
[ { "body": "<p>First, I normally like using local functions to clean up code like you're doing with <code>topToBottom</code>, <code>rightToLeft</code> and similar functions. I don't think it's helping here though. You've extracted four nearly identical pieces of code into four nearly identical functions. It may be possible to extract the common aspects out into a single function, then you'd have the one function being called four times. Until then though, I'd recommend just inlining the functions:</p>\n\n<pre><code>const spiralCopy = (matrix) =&gt; {\n const spiralLength = matrix.length * matrix[0].length;\n const spiral = [];\n\n let iLeftRightStart = 0; // +1\n let iLeftRightEnd = matrix[0].length; // -1\n let leftRightPosition = 0; // +1\n let iTopBottomStart = 1; // +1\n let iTopBottomEnd = matrix.length; // -1\n let topBottomPosition = matrix[0].length - 1; // -1\n let iRightLeftStart = matrix[0].length - 2; // -1\n let iRightLeftEnd = 0; // +1\n let rightLeftPosition = matrix.length - 1; // -1\n let iBottomTopStart = matrix.length - 2; // -1\n let iBottomTopEnd = 1; // +1 \n let bottomTopPosition = 0; // +1\n\n while (spiral.length &lt; spiralLength) {\n for (let i = iLeftRightStart; i &lt; iLeftRightEnd; i++) {\n spiral.push(matrix[leftRightPosition][i]);\n }\n\n for (let i = iTopBottomStart; i &lt; iTopBottomEnd; i++) {\n spiral.push(matrix[i][topBottomPosition]);\n }\n\n for (let i = iRightLeftStart; i &gt;= iRightLeftEnd; i--) {\n spiral.push(matrix[rightLeftPosition][i]);\n }\n\n for (let i = iBottomTopStart; i &gt;= iBottomTopEnd; i--) {\n spiral.push(matrix[i][bottomTopPosition]);\n }\n\n iLeftRightStart++;\n iLeftRightEnd--;\n leftRightPosition++;\n iTopBottomStart++;\n iTopBottomEnd--;\n topBottomPosition--;\n iRightLeftStart--;\n iRightLeftEnd++;\n rightLeftPosition--;\n iBottomTopStart--;\n iBottomTopEnd++;\n bottomTopPosition++;\n }\n return spiral;\n}\n</code></pre>\n\n<p>The common variable names alone make it clear what direction each loop is responsible for, and if you still wanted an explicit \"name\" associated with each loop, you could add a comment.</p>\n\n<p>As for the bulk of separate variables, it seems like they could fall into a class (or similar grouping mechanism). You have a start bound, an end bound, and a current position. Each bound group also has a specific \"accessor\" (like <code>matrix[i][position]</code>), and a specific way its position is updated. If all five pieces are grouped, you can apply a common function (<code>advance</code>) to the group to isolate the common behavior:</p>\n\n<pre><code>inputMatrix = [\n [1, 2, 3, 4, 5, 6],\n [7, 8, 9, 10, 11, 12],\n [13, 14, 15, 16, 17, 18],\n [19, 20, 21, 22, 23, 24],\n [25, 26, 27, 28, 29, 30],\n [31, 32, 33, 34, 35, 36]\n]\n\n// This arguably isn't necessary, but it reduces some bulk in spiralCopy\n// Accessor is a function that accepts i and the bound's position, and \n// returns the number there.\n// PositionAdvancer is a function that takes the current position, and returns\n// the next position\nconst newBounds = (start, end, position, positionAdvancer, accessor) =&gt;\n ({start: start, end: end,\n position: position, \n positionAdvancer: positionAdvancer,\n accessor: accessor});\n\n// For brevity later\nconst inc = (i) =&gt; i + 1;\nconst dec = (i) =&gt; i - 1;\n\nconst spiralCopy = (matrix) =&gt; {\n const spiralLength = matrix.length * matrix[0].length;\n const spiral = [];\n\n function advance(bounds) {\n const {start, end, position, accessor, positionAdvancer} = bounds;\n\n // Decide what comparing and i advancing functions to use\n const [comp, adv] = start &lt; end ?\n [(a, b) =&gt; a &lt; b, inc]\n : [(a, b) =&gt; a &gt;= b, dec];\n\n // Handle all the common behavior\n for (let i = start; comp(i, end); i = adv(i)) {\n spiral.push(accessor(i, position));\n }\n\n oppAdv = adv === inc ? dec : inc\n\n bounds.start = adv(bounds.start);\n bounds.end = oppAdv(bounds.end);\n bounds.position = positionAdvancer(bounds.position);\n }\n\n const leftRight = newBounds(0, matrix[0].length, 0, inc,\n (i, p) =&gt; matrix[p][i]);\n\n const topBottom = newBounds(1, matrix.length, matrix[0].length - 1, dec,\n (i, p) =&gt; matrix[i][p]);\n\n const rightLeft = newBounds(matrix[0].length - 2, 0, matrix.length - 1, dec,\n (i, p) =&gt; matrix[p][i]);\n\n const bottomTop = newBounds(matrix.length - 2, 1, 0, inc,\n (i, p) =&gt; matrix[i][p]);\n\n while (spiral.length &lt; spiralLength) {\n advance(leftRight);\n advance(topBottom);\n advance(rightLeft);\n advance(bottomTop);\n }\n\n return spiral;\n}\n</code></pre>\n\n<p>Now, I can't say that I <em>necessarily</em> recommend this in its entirety. <code>advance</code> got bulkier the longer I looked at it, and:</p>\n\n<pre><code>const got = spiralCopy(inputMatrix);\nconst expected = [1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21];\n\nif (got === expected) {\n console.log(\"Passed\");\n\n} else {\n console.log(\"Failed\");\n console.log(got);\n console.log(expected);\n}\n\nFailed\n[1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21, 15]\n[1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21]\n</code></pre>\n\n<p>Ouch. For some reason, it insists on circling back up to <code>15</code> at the end. I can't for the life of me figure out why. I've already spent a good like hour and a bit on this though, and didn't want the alternative solution to go to waste. </p>\n\n<p>This solution was mostly how I'd approach it in Clojure, and it doesn't translate 100% to Javascript given the bulk in some places. You still may be able to draw inspiration from it though. My primary goal here was to reduce the redundancy however I could, not adhere to idiomatic Javascript (as I don't write JS very often honestly).</p>\n\n<hr>\n\n<p>Oh, and I increased indentation to use four-spaces, as I find that it's more readable. There doesn't seem to be a good consensus on what should be used though, so take that with a grain of salt.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T22:47:20.970", "Id": "215219", "ParentId": "215214", "Score": "1" } }, { "body": "<h2>Travel directions</h2>\n<p>You can imagine this problem being extended to a 3D array. That would mean you have 6 directions, which using your approach would mean half as much code again, and 4D array would have 8 directions. That would double the amount of code. This becomes impractical as you get to higher dimensions.</p>\n<p>If you break the problem into a simpler model. Move in a direction for distance collecting items as you go then turn, every second turn decrease the distance, until zero.</p>\n<p>A direction can be represented as a vector <code>{x,y}</code> that is right <code>{1,0}</code>, down <code>{0,1}</code> and so on. You store them in an array of vectors in the order you need to use.</p>\n<p>I have solved assuming that the array given is a rhombus . You have not indicated if this is true or not. However it only requires a small modification to handle non rhombus arrays.</p>\n<p>The result is something like</p>\n<pre><code>function spiral(arr) {\n var count, curDir, dist, size, x = 0, y = 0, dir = 0;\n const res = [], directions = [{x: 1, y: 0}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 0, y: -1}];\n curDir = directions[0];\n dist = size = arr.length;\n count = size ** 2;\n while (count--) { \n res.push(arr[y][x]);\n if (!--dist) {\n curDir = directions[++dir % 4];\n if (dir % 2) { size -- }\n dist = size;\n }\n x += curDir.x;\n y += curDir.y;\n }\n return res;\n}\n</code></pre>\n<p>To test the function create some readable test arrays. The snippet has arrays that when processed will have values in order, so that it is easy to see if the result is correct.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>[[\n [1, 2, 3, 4, 5, 6],\n [20, 21, 22, 23, 24, 7],\n [19, 32, 33, 34, 25, 8],\n [18, 31, 36, 35, 26, 9],\n [17, 30, 29, 28, 27, 10],\n [16, 15, 14, 13, 12, 101]\n ], [\n [1, 2, 3, 4, 5],\n [16, 17, 18, 19, 6],\n [15, 24, 25, 20, 7],\n [14, 23, 22, 21, 8],\n [13, 12, 11, 10, 9],\n ], [\n [1, 2, 3, 4],\n [12, 13, 14, 5],\n [11, 16, 15, 6],\n [10, 9, 8, 7],\n ], [\n [1, 2, 3],\n [8, 9, 4],\n [7, 6, 5],\n ], [\n [1, 2],\n [4, 3],\n ], [[1]]\n].reverse().forEach(arr =&gt; console.log(spiral(arr).join(\",\")));\n\n\nfunction spiral(arr) {\n var count, curDir, dist, size, x = 0, y = 0, dir = 0;\n const res = [], directions = [{x: 1, y: 0}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 0, y: -1}];\n curDir = directions[0];\n dist = size = arr.length;\n count = size ** 2;\n while (count--) { \n res.push(arr[y][x]);\n if (!--dist) {\n curDir = directions[++dir % 4];\n if (dir % 2) { size -- }\n dist = size;\n }\n x += curDir.x;\n y += curDir.y;\n }\n return res;\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-03-12T07:13:30.913", "Id": "215238", "ParentId": "215214", "Score": "2" } } ]
{ "AcceptedAnswerId": "215219", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T19:34:05.800", "Id": "215214", "Score": "1", "Tags": [ "javascript", "programming-challenge", "array", "matrix" ], "Title": "JavaScript Spiral Matrix Coding Challenge" }
215214
<p>The purpose of this program is to keep track of some stocks that we bought in a game and every week we must list the closing prices of each stock in a Google Sheet. I thought since I had a lot of different investments to keep track of I would write a quick script to do it for me. And I could have my friends in class send me their stocks as well to save them time. </p> <p>I am just looking for any bad practices I might have in my code as well as any more efficient ways of carrying out some of the functions.</p> <pre><code>from yahoofinancials import YahooFinancials import re import pygsheets import pandas as pd import datetime now = datetime.datetime.now() time_now = (now.year, now.month, now.day) time_now = str(time_now) data = [] formatedData = [] shortData = [] everything = [] tickers = ['XOM', 'JNJ', 'TR', 'CRON', 'HSY', 'FL', 'PLNT', 'MCD', 'ARLP', 'LULU', 'RCII', 'DELL', 'DNKN', 'DIS'] def main(sheet, everything,place): gc = pygsheets.authorize(service_file='creds.json') # Create empty dataframe df = pd.DataFrame() # Create a column df['Closings: ' + time_now] = everything # open the google spreadsheet (where 'PY to Gsheet Test' is the name of my sheet) sh = gc.open('PY to Gsheet Test') # select the first sheet wks = sh[sheet] # update the first sheet with df, starting at cell A2. wks.set_dataframe(df, (1, place)) # up/down,left right for i in tickers: tick = YahooFinancials(i) history = tick.get_historical_price_data('2019-03-07', '2019-03-08', 'daily') y = str(history) data.append(y) for i in data: i = i[i.index('adjclose'):] i = re.findall("\d+\.-?\d*", i) i = str(i) if len(i) &gt; 7: formatedData.append(i[2:9]) #the decimals were really long so this shortens them down a bit else: formatedData.append(i) y = 0 for i in tickers: x = i x = x + " : " + formatedData[y] y = y + 1 everything.append(x) def get_name(person): if person == 'tommy': sheet = 0 elif person == 'chad': sheet = 1 elif person == 'kaya': sheet = 2 elif person == 'twohey': sheet = 3 elif person == 'majers': sheet = 4 elif person == 'tori': sheet = 5 elif person == 'kayla': sheet = 6 place = input("What Week Is This? 1,2,3,4,5?: ") # This will move the entry one place over for each week place = int(place) main(sheet, everything,place) print('DONT FORGET TO CHANGE TICKER') person = input("Whos Data Is Going In: ") get_name(person) </code></pre>
[]
[ { "body": "<p>This looks very interesting. Well done!</p>\n\n<hr>\n\n<p>Here is some nitpicking:</p>\n\n<blockquote>\n<pre><code>from yahoofinancials import YahooFinancials\nimport re\nimport pygsheets\nimport pandas as pd\nimport datetime\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Organise these imports in following way: builtins, third-party then first-party.</li>\n</ul>\n\n<blockquote>\n<pre><code> def main(sheet, everything,place):\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Name of this function is sloppy. Use <code>main</code> function as an entry-point.</li>\n<li>Name the function as a verb phrase or that explains what it is doing.</li>\n<li>What is <code>everything</code> here? I can see that it is defined outside as well.</li>\n<li>Avoid using <code>everything</code> as a name. It is very vague. </li>\n</ul>\n\n<blockquote>\n<pre><code>for i in tickers:\n tick = YahooFinancials(i)\n</code></pre>\n</blockquote>\n\n<ul>\n<li>What is <code>i</code> here? Reserve <code>i</code> for integer indexes. These are ticker_names.</li>\n<li><code>for ticker_name in tickers</code> is more readable. </li>\n</ul>\n\n<blockquote>\n<pre><code>tickers = ['XOM', 'JNJ', 'TR', 'CRON', 'HSY', 'FL', 'PLNT', 'MCD', 'ARLP', 'LULU', 'RCII', 'DELL', 'DNKN', 'DIS']\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Load this from a JSON file.</li>\n</ul>\n\n<blockquote>\n<pre><code>def get_name(person):\n</code></pre>\n</blockquote>\n\n<ul>\n<li>This function doesn't <strong>get</strong> you anything. There is no return.</li>\n<li>Why does this call <code>main</code>?</li>\n<li>Name to sheet mapping can probably be loaded from a JSON as well.</li>\n</ul>\n\n<blockquote>\n<pre><code>adjclose, PY to Gsheet Test\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Perform extract constant refactoring on strings like these and remove magic values. </li>\n</ul>\n\n<blockquote>\n <p>A magic number is a direct usage of a number in the code.</p>\n \n <p>For example, if you have (in Java):</p>\n \n <pre class=\"lang-java prettyprint-override\"><code>public class Foo {\n public void setPassword(String password) {\n // don't do this\n if (password.length() &gt; 7) {\n throw new InvalidArgumentException(\"password\");\n }\n }\n}\n</code></pre>\n \n <p>This should be refactored to:</p>\n \n <pre class=\"lang-java prettyprint-override\"><code>public class Foo {\n public static final int MAX_PASSWORD_SIZE = 7;\n\n public void setPassword(String password) {\n if (password.length() &gt; MAX_PASSWORD_SIZE) {\n throw new InvalidArgumentException(\"password\");\n }\n }\n}\n</code></pre>\n \n <p>From: <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad</a></p>\n</blockquote>\n\n<hr>\n\n<ul>\n<li><strong>Summary</strong> - This code is very hard to understand. Functions do things that are completely different from function-name. Variable names are vague. Contains lot of hard-coded values that can be extracted to a JSON or some other kind of config. Contains magic values that should be converted to meaningful constants. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:31:25.043", "Id": "215261", "ParentId": "215216", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T20:58:37.330", "Id": "215216", "Score": "3", "Tags": [ "python", "python-3.x", "pandas", "finance", "google-sheets" ], "Title": "Tracking stock prices using Python and Google Sheets" }
215216
<p>What I'm trying to create is a generic tooltip component that I can use anywhere. I decided on a stateless component and the use of hooks and ref.</p> <p><strong>Explanation</strong> </p> <p>Hook, because I wanted to have a flag for hover and ref to get element width and/or height to center it correctly.</p> <p><strong>Problem</strong> ❓</p> <p>Is this solution correct and will perform fast enough with the bigger amount of tooltip components on the same page (over 100)? The solutions I've come across so far have not been satisfactory. I wonder if this idea makes a sense if so, I will develop it and publish it as an open source project (I would like to finally make a contribution! )</p> <p><strong>Demo:</strong> <a href="https://danzawadzki.github.io/react-tooltip/" rel="nofollow noreferrer">https://danzawadzki.github.io/react-tooltip/</a></p> <p><strong>Repository:</strong> <a href="https://github.com/danzawadzki/react-tooltip/tree/98d9c61a23437e778bb1ce6f80ee39a95fe86509" rel="nofollow noreferrer">https://github.com/danzawadzki/react-tooltip</a></p> <p><strong>Tooltip.tsx</strong></p> <pre><code>import * as React from 'react'; import './Tooltip.scss'; import {CSSTransition} from 'react-transition-group'; import {useState} from 'react'; import {useRef} from 'react'; export interface ITooltip { /** Tooltip position. */ position?: 'top' | 'left' | 'right' | 'bottom'; /** Tooltip message content. */ message: String; /** Array with details about columns to render. */ children: JSX.Element | Array&lt;JSX.Element&gt; | string; } export interface ITooltipStyle { /** Distance to the left edge. */ left?: string; /** Distance to the top edge. */ top?: string; /** Distance to the bottom edge. */ bottom?: string; /** Distance to the right edge. */ right?: string; } /** * Tooltip component. * * @author Daniel Zawadzki &lt;hello@danielzawadzki.com&gt; * @version 1.0.0 */ const Tooltip: React.FunctionComponent&lt;ITooltip&gt; = ({position = 'top', message, children}) =&gt; { /** * Hook toggling tooltip isVisible flag. */ const [isVisible, setIsVisible] = useState&lt;boolean&gt;(false); const toggle = () =&gt; setIsVisible(!isVisible); /** * Reference to the component to track width and height */ const node = useRef&lt;any&gt;(null); /** * Positioning the component using the reference */ let style: ITooltipStyle = {}; if (node.current &amp;&amp; node.current.offsetWidth) { if (position === 'top' || position === 'bottom') { style.left = `${String(node.current.offsetWidth / 2)}px`; } else { style.top = `-${String(node.current.offsetHeight / 1.5)}px`; } } return ( &lt;div className="Tooltip"&gt; &lt;div className="Tooltip__toggler" onMouseOverCapture={toggle} onMouseOut={toggle} ref={node}&gt; {children} &lt;/div&gt; &lt;CSSTransition in={isVisible} timeout={200} classNames="Tooltip" unmountOnExit&gt; &lt;div className={`Tooltip__message Tooltip__message--${position}`} style={style}&gt; {message} &lt;/div&gt; &lt;/CSSTransition&gt; &lt;/div&gt; ); }; export default Tooltip; </code></pre> <p>I know that there are probably a lot of bugs and areas for development there, but is it any good idea?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T21:55:55.800", "Id": "215217", "Score": "1", "Tags": [ "react.js", "typescript", "jsx" ], "Title": "Stateless tooltip component using React hooks and ref" }
215217
<p>This is an implementation to simulate the basic functionality of c++ shared_ptr. This doesn't provide features like custom deleter and make_shared().</p> <p>I would really appreciate any feedback to improve the below code, any other api's that I should be providing etc.</p> <pre><code>#ifndef SHARED_PTR_H_ #define SHARED_PTR_H_ #include &lt;utility&gt; namespace kapil { template &lt;typename T&gt; class shared_ptr { private: T* ptr_; // data pointer int* ref_count_; // reference count pointer void decrement_ref_count_and_delete_if_needed() { if (ref_count_) { --(*ref_count_); if (*ref_count_ == 0) { delete ptr_; delete ref_count_; ptr_ = nullptr; ref_count_ = nullptr; } } } public: constexpr shared_ptr() noexcept : ptr_{nullptr}, ref_count_{nullptr} {} constexpr explicit shared_ptr(T* ptr) { // constructor ptr_ = ptr; ref_count_ = new int{1}; } shared_ptr(const shared_ptr&amp; other) noexcept { // copy constructor ptr_ = other.ptr_; ref_count_ = other.ref_count_; if (ref_count_ != nullptr) { ++(*ref_count_); } } shared_ptr(shared_ptr&amp;&amp; other) noexcept { // move constructor ptr_ = other.ptr_; ref_count_ = other.ref_count_; other.ptr_ = nullptr; other.ref_count_ = nullptr; } ~shared_ptr() noexcept { // destructor decrement_ref_count_and_delete_if_needed(); } shared_ptr&amp; operator = (const shared_ptr&amp; other) noexcept { // assignent operator if (this != &amp;other) { decrement_ref_count_and_delete_if_needed(); ptr_ = other.ptr_; ref_count_ = other.ref_count_; if (ref_count_) { ++(*ref_count_); } } return *this; } shared_ptr&amp; operator = (shared_ptr&amp;&amp; other) noexcept { // move assignment operator *this = other; } T* get() const noexcept { return ptr_; } void reset() noexcept { decrement_ref_count_and_delete_if_needed(); } void reset(T* ptr) { decrement_ref_count_and_delete_if_needed(); ptr_ = ptr; if (!ref_count_) { ref_count_ = new int{1}; } *ref_count_ = 1; } int use_count() const noexcept { return *ref_count_; } void swap (shared_ptr&amp; other) { std::swap(ptr_, other.ptr_); std::swap(ref_count_, other.ref_count_); } T&amp; operator * () const { return *ptr_; } T* operator -&gt; () const noexcept { return ptr_; } explicit operator bool() const noexcept { return (ptr_ != nullptr); } friend bool operator == (const shared_ptr&amp; lhs, const shared_ptr&amp; rhs) noexcept { return (lhs.ptr_ == rhs.ptr_); } friend bool operator != (const shared_ptr&amp; lhs, const shared_ptr&amp; rhs) noexcept { return !(lhs == rhs); } }; // class shared_ptr template &lt;typename T&gt; void swap(shared_ptr&lt;T&gt;&amp; lhs, shared_ptr&lt;T&gt;&amp; rhs) { // swap function in namespace to facilitate ADL lhs.swap(rhs); } } // namespace kapil #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T04:46:40.530", "Id": "416222", "Score": "0", "body": "So this is not thread safe? I believe it is important detail to include in the post, although it can be easily seen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T18:55:48.127", "Id": "416916", "Score": "0", "body": "I wrote a series of articles on writing smart pointers here: https://lokiastari.com/series/" } ]
[ { "body": "<p>It might be difficult to get great feedback on this <code>shared_ptr</code> just because it omits <em>so many</em> of the features of <code>std::shared_ptr</code>. I mean I'd be tempted to just list all the features it doesn't have and then fail to review the code at all:</p>\n\n<ul>\n<li>Atomic/thread-safe accesses to the reference count.</li>\n<li>Implicit conversion from <code>shared_ptr&lt;T&gt;</code> to <code>shared_ptr&lt;U&gt;</code> whenever <code>T*</code> is convertible to <code>U*</code>.</li>\n<li><code>shared_ptr&lt;void&gt;</code>.</li>\n<li>Custom and type-erased deleters.</li>\n<li>The \"aliasing constructor.\"</li>\n<li><code>weak_ptr</code>.</li>\n<li>Implicit conversion from <code>unique_ptr</code>.</li>\n<li><code>make_shared</code>.</li>\n</ul>\n\n<hr>\n\n<pre><code>~shared_ptr() noexcept { // destructor\n</code></pre>\n\n<p>The comment is redundant. And so is the <code>noexcept</code>: in C++11-and-later, destructors are implicitly <code>noexcept</code>, and it's idiomatic not to write it explicitly.</p>\n\n<p>Contrariwise, it is <em>extremely important</em> to provide a noexcept <code>swap</code> function! You're missing the <code>noexcept</code> keyword here:</p>\n\n<pre><code>void swap (shared_ptr&amp; other) {\n</code></pre>\n\n<p>By the way, it's weird to put a space between the name of the function and its opening parenthesis. Prefer <code>swap(shared_ptr&amp; other)</code>.</p>\n\n<hr>\n\n<p>You've got a typo in a comment: <code>assignent</code>. Look for typos elsewhere. Where there's one mistake, there's often more than one. (Also, eliminate that redundant comment.)</p>\n\n<hr>\n\n<pre><code> --(*ref_count_);\n if (*ref_count_ == 0) {\n</code></pre>\n\n<p>Your accesses to <code>*ref_count</code> already aren't thread-safe; but FYI, here's where the race condition would sneak in if you just went and made <code>ref_count</code> a pointer to a <code>std::atomic&lt;int&gt;</code>. In a multithreaded environment, it might well be that <code>*ref_count_ == 0</code>, but that doesn't mean that <em>you're</em> the one whose decrement took it to <code>0</code>.</p>\n\n<hr>\n\n<pre><code>constexpr shared_ptr() noexcept : ptr_{nullptr}, ref_count_{nullptr} {}\n</code></pre>\n\n<p>If you used C++11 non-static data member initializers (NSDMIs) for <code>ptr_</code> and <code>ref_count_</code>, you could <code>=default</code> this constructor.</p>\n\n<pre><code>T *ptr_ = nullptr;\nint *ref_count_ = nullptr;\n\nconstexpr shared_ptr() noexcept = default;\n</code></pre>\n\n<hr>\n\n<pre><code>shared_ptr&amp; operator = (shared_ptr&amp;&amp; other) noexcept { // move assignment operator\n *this = other;\n}\n</code></pre>\n\n<p>Why did you bother implementing this overload at all, if you're not going to make it more efficient? Either omit it entirely (so that there's only one assignment operator), or implement it as e.g.</p>\n\n<pre><code>shared_ptr&amp; operator=(shared_ptr&amp;&amp; other) noexcept {\n if (this != &amp;other) {\n decrement_ref_count_and_delete_if_needed();\n ptr_ = std::exchange(other.ptr_, nullptr);\n ref_count_ = std::exchange(other.ref_count_, nullptr);\n }\n return *this;\n}\n</code></pre>\n\n<p>By the way, once you make your <code>swap</code> function noexcept, you might consider saving some brain cells by using the <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">copy-and-swap idiom</a>:</p>\n\n<pre><code>shared_ptr&amp; operator=(shared_ptr&amp;&amp; other) noexcept {\n shared_ptr(std::move(other)).swap(*this);\n return *this;\n}\n</code></pre>\n\n<hr>\n\n<pre><code> void reset() noexcept {\n decrement_ref_count_and_delete_if_needed();\n }\n</code></pre>\n\n<p>This is wrong. Consider:</p>\n\n<pre><code>shared_ptr&lt;int&gt; p(new int);\nshared_ptr&lt;int&gt; q = p;\np.reset();\nassert(p.get() != nullptr); // oops\n</code></pre>\n\n<hr>\n\n<pre><code> void reset(T* ptr) {\n decrement_ref_count_and_delete_if_needed();\n ptr_ = ptr;\n if (!ref_count_) {\n ref_count_ = new int{1};\n }\n *ref_count_ = 1;\n }\n</code></pre>\n\n<p>This is also wrong. Consider:</p>\n\n<pre><code>shared_ptr&lt;int&gt; p(new int); // A\nshared_ptr&lt;int&gt; q = p; // B\np.reset(new int); // C\np = shared_ptr&lt;int&gt;(); // D\nassert(q.use_count() == 0); // oops!\n</code></pre>\n\n<p>Line A sets the refcount to 1. Line B increments the refcount to 2. Line C repoints <code>p.ptr_</code> (but does not change <code>p.ref_count_</code> — oops!), and then resets the refcount to 1. Line D decrements the refcount to 0 and frees the int that was allocated on line C. Now <code>q.ptr_</code> still points to the int that was allocated on line A, but <code>*q.ref_count_ == 0</code>.</p>\n\n<p>The correct implementation of <code>reset(T*)</code> is simply</p>\n\n<pre><code> void reset(T *ptr) {\n *this = shared_ptr(ptr);\n }\n</code></pre>\n\n<p>(I strongly advise <em>against</em> ever making calls to <code>reset</code> from user code, by the way, because every call to <code>reset</code> can be more readably expressed as a simple and type-safe assignment.)</p>\n\n<hr>\n\n<pre><code>int use_count() const noexcept {\n return *ref_count_;\n}\n</code></pre>\n\n<p>There's an unspoken precondition here: that <code>use_count()</code> shall never be called on a <code>shared_ptr</code> in the default-constructed (\"disengaged\", \"moved-from\", \"partially formed\") state. If you keep this precondition, then the <a href=\"https://quuxplusone.github.io/blog/2018/04/25/the-lakos-rule/\" rel=\"nofollow noreferrer\">Lakos Rule</a> would suggest that this function shouldn't be <code>noexcept</code>. However, I think it would be more natural to write</p>\n\n<pre><code>int use_count() const noexcept {\n return ref_count_ ? *ref_count_ : 0;\n}\n</code></pre>\n\n<p>so that the function always has well-defined behavior.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T04:56:34.203", "Id": "215233", "ParentId": "215223", "Score": "4" } }, { "body": "<h2>Overview</h2>\n\n<ul>\n<li>You can still leak the pointer from the constructor. </li>\n<li>You can crash the program when a <code>T</code> destructor safely throws.</li>\n<li>You ahve some bugs around reset.</li>\n</ul>\n\n<h2>Code Review</h2>\n\n<p>My biggist issue is here:</p>\n\n<pre><code> constexpr explicit shared_ptr(T* ptr) { // constructor\n ptr_ = ptr;\n ref_count_ = new int{1};\n }\n</code></pre>\n\n<p>The problem is that <code>new</code> can throw. If it throws during a constructor then the destructor is never run. and thus you will leak <code>ptr</code>. The whole point of the class is to prevent leaking so you need to think about this situation.</p>\n\n<p>The function <code>decrement_ref_count_and_delete_if_needed()</code> is called from several function that are marked as <code>noexcept</code>. So this function should also be <code>noexcept</code> or some of your <code>noexcept</code> functions should not be marked <code>noexcept</code>. </p>\n\n<p>In this function you have to either make a concerted effort to make sure no exceptions propagate or that you don't affect the state of your object if it does throw.</p>\n\n<p>The problem is this line:</p>\n\n<pre><code> delete ptr_;\n</code></pre>\n\n<p>Here <code>ptr_</code> is of type <code>T</code>. You don't know what type <code>T</code> and thus you can not guarantee that it does not throw.</p>\n\n<p>The <code>reset()</code> is broken.</p>\n\n<pre><code> void reset() noexcept {\n decrement_ref_count_and_delete_if_needed();\n }\n</code></pre>\n\n<p>If I reset a shared pointer then it should be <code>nullptr</code> inside. This function does not set this object to <code>nullptr</code> (unless it is the only pointer to the object).</p>\n\n<p>The <code>reset(T* ptr)</code> is also broken.</p>\n\n<pre><code> void reset(T* ptr) {\n decrement_ref_count_and_delete_if_needed(); // decrement ref count\n // but if this was not the\n // only pointer to the object\n // then these value are still\n // pointing at the old values.\n\n\n ptr_ = ptr; // Overwrite the pointer OK\n\n\n if (!ref_count_) { // THIS IS WRONG.\n // If you have a pointer to a count\n // This count belongs to the other\n // pointer you were previously\n // countint for.\n\n\n ref_count_ = new int{1}; // BASICALLY THIS LINE SHOULD\n // ALWAYS BE USED.\n }\n *ref_count_ = 1; \n }\n</code></pre>\n\n<h2>Further Reading</h2>\n\n<p>I wrote some articles around writting smart pointer you may find useful:</p>\n\n<p><a href=\"https://lokiastari.com/blog/2014/12/30/c-plus-plus-by-example-smart-pointer/index.html\" rel=\"nofollow noreferrer\">Smart-Pointer - Unique Pointer</a><br>\n<a href=\"https://lokiastari.com/blog/2015/01/15/c-plus-plus-by-example-smart-pointer-part-ii/index.html\" rel=\"nofollow noreferrer\">Smart-Pointer - Shared Pointer</a><br>\n<a href=\"https://lokiastari.com/blog/2015/01/23/c-plus-plus-by-example-smart-pointer-part-iii/index.html\" rel=\"nofollow noreferrer\">Smart-Pointer - Constructors</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T20:16:43.627", "Id": "416937", "Score": "0", "body": "I'll surely have a look at these resources. Looks like I am missing pretty lot of things in the implementation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T19:13:51.780", "Id": "215522", "ParentId": "215223", "Score": "1" } } ]
{ "AcceptedAnswerId": "215233", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T00:02:12.077", "Id": "215223", "Score": "1", "Tags": [ "c++", "c++11", "pointers" ], "Title": "shared_ptr basic implementation for non array types" }
215223
<p>As a first project in Rust, I'm translating an existing, working piece of Python code. This code's purpose is to convert a 15-character Salesforce Id (which is guaranteed to be ASCII, exactly 15 bytes of base-62 data) to its 18-character equivalent, which includes a 3-character suffix to discriminate between values differing from one another only in case.</p> <p>The Rust code works. I am looking for guidance on how to improve its idiomaticity in Rust, particularly around processing this type of data. It's a String conceptually, but doesn't need the overhead of UTF-8 handling, and is likely to be read from (e.g.) CSV files or Web services that do return UTF-8 encoded data.</p> <p>I also suspect that the way I handle the "accumulator" values <code>suffix</code> and <code>base_two</code> is not proper Rust and welcome education there.</p> <h2>Python</h2> <pre><code>class SalesforceId(object): def __init__(self, idstr): if isinstance(idstr, SalesforceId): self.id = idstr.id else: idstr = idstr.strip() if len(idstr) == 15: suffix = '' for i in range(0, 3): baseTwo = 0 for j in range (0, 5): character = idstr[i*5+j] if character &gt;= 'A' and character &lt;= 'Z': baseTwo += 1 &lt;&lt; j suffix += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'[baseTwo] self.id = idstr + suffix elif len(idstr) == 18: self.id = idstr else: raise ValueError('Salesforce Ids must be 15 or 18 characters.') </code></pre> <h2>Rust</h2> <pre><code>#[derive(Debug)] struct SalesforceId(String); impl SalesforceId { fn from_string(s: &amp;str) -&gt; SalesforceId { let b = s.as_bytes(); match b.len() { 18 =&gt; { SalesforceId(s.to_string()) } 15 =&gt; { let mut suffix: [u8; 3] = [b'A', b'A', b'A']; for i in 0..3 { let mut base_two = 0; for j in 0..5 { let character = b[i*5+j]; if character &gt;= b'A' &amp;&amp; character &lt;= b'Z' { base_two += 1 &lt;&lt; j; } } suffix[i] = b'A' + base_two } SalesforceId(format!("{}{}", s, std::str::from_utf8(&amp;suffix).unwrap())) } _ =&gt; panic!("invalid Salesforce Id") } } } fn main() { println!("{:?}", SalesforceId::from_string("0063600000aqQ1h")); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T02:25:29.497", "Id": "416217", "Score": "0", "body": "https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=aa77b2da14dbeb12d5d2cbea3c576c9d" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T02:30:50.473", "Id": "416218", "Score": "0", "body": "`ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'[baseTwo]` != `suffix[i] = b'A' + base_two` are you sure your code is correct ?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T01:13:42.960", "Id": "215227", "Score": "4", "Tags": [ "beginner", "strings", "rust", "converting", "base64" ], "Title": "Translating Python to Rust: reading a Salesforce ID from a string" }
215227
<p>I just made my first registration form with password confirmation, hashing with BCRYPT and PDO. As a beginner, looking around on StackExchange, I seem to miss a lot. </p> <p>To keep it simple for myself, I coded PHP and HTML on the same page. Hence I'm just into PHP for 3 days now.</p> <pre><code>if (isset($_POST['register'])) { $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; $cPassword = $_POST['cPassword']; $options = [ PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES =&gt; false, ]; $host = 'localhost'; $db = 'loginform'; $user = 'root'; $pass = ''; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e-&gt;getMessage(), (int)$e-&gt;getCode()); } if ($password != $cPassword) $msg = "Wachtwoord komt niet overeen!"; else { $hash = password_hash($password, PASSWORD_BCRYPT); $sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)"; $stmt = $pdo-&gt;prepare($sql); $stmt-&gt;execute([$name, $email, $hash]); $msg = "U bent geregistreerd!"; header( "Refresh:3; url=/Login2/inloggen.php", true, 303); } } </code></pre>
[]
[ { "body": "<p>That's a very good code. Speaking of the things that are written in it, there is very little I would <em>change</em>. Only a few things are coming to my mind, </p>\n\n<ul>\n<li>I would move the database connection code into a separate file and then just include in other scripts that needed a database connection.</li>\n<li>Using the Refresh header is old fashioned, inconvenient and buggy. I would rather redirect a user to the newly created account page. So they would know that an account has been created at once.</li>\n<li>I wouldn't hardcode a particular hashing algorithm, and rather use PASSWORD_DEFAULT instead. </li>\n</ul>\n\n<p>That's all. But of course some things could be <em>added</em> to this code as well. You can add some verifications, like as to see </p>\n\n<ul>\n<li>if the username is not empty or already exists</li>\n<li>whether the password is not strong enough</li>\n<li>whether email follows the proper format or already exists</li>\n<li>all other verifications you can think of</li>\n</ul>\n\n<p>And for this purpose it is useful to make $msg not a string but an array of strings, to collect all possible errors in one variable. You can check this approach in my <a href=\"https://codereview.stackexchange.com/a/214895/101565\">recent answer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T19:51:41.683", "Id": "416351", "Score": "0", "body": "I apologize for the late response. I think you covered some interesting things here and to be honest, It's exactly what I needed. At this moment I can use XSS scripts as username and that's something I really don't want. Thank you for reviewing my code, I've set some new goals to work on tonight. Appreciate it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T06:52:33.633", "Id": "215236", "ParentId": "215231", "Score": "2" } } ]
{ "AcceptedAnswerId": "215236", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T04:03:11.277", "Id": "215231", "Score": "2", "Tags": [ "php", "pdo" ], "Title": "PDO / HASH Registration form" }
215231
<p>I developed a simple and short java game in which a random word is selected and the user needs to guess it's letters one after another.</p> <p>I'm a java beginner so I'll be glad to hear your thoughts.</p> <p><strong>WordsBank:</strong></p> <pre><code>import java.util.Random; public class WordsBank { private final String[] Words; // Ctor public WordsBank(){ Words = new String[]{ "Adventure", "Hungary", "Pizza", "Madrid", "Flower", "Chicken", "Israel", "Romania", "Denmark", "Australia" }; } // Returns a random word from the existing words public String getRandomWord() { Random rand = new Random(); return Words[rand.nextInt(Words.length)]; // Word from a random index } } </code></pre> <p><strong>ChosenWord:</strong></p> <pre><code>public class ChosenWord { private String word; // The chosen word private boolean[] charsGuessed; // Array of the guessed chars in the word. // If charsGuessed[0] is True, // it means the first char was guessed by the user already // Initially, all the values are False // Ctor public ChosenWord(String word){ this.word = word.toLowerCase(); charsGuessed = new boolean[word.length()]; } // Check if the entire word is already guessed public boolean isEntireWordGuessed() { // Iterating through the chars guessed array for (boolean b : charsGuessed) { // If a char was not guessed returning false if (!b) return false; } // All the chars were guessed, return true. return true; } // receives a char and checks if it appears in the word. public void charGuess(char guess) { int index = word.indexOf(guess); // Finding first occurrence // Iterating while there are more occurrences of the guess while (index &gt;= 0) { charsGuessed[index] = true; // Marking the char appearance in the fitting index index = word.indexOf(guess, index + 1); // Finding next occurrence } } // Building a string to represent the chosen word with it's revealed letters @Override public String toString(){ StringBuilder formattedWord = new StringBuilder(); // Iterating through the characters of the word. if the character was guessed, adding it, otherwise add '_' for(int index = 0; index &lt; word.length(); index++){ if (charsGuessed[index]){ formattedWord.append(word.charAt(index)); } else { formattedWord.append('_'); } formattedWord.append(' '); } return formattedWord.toString(); } } </code></pre> <p><strong>Game:</strong></p> <pre><code>import javax.swing.*; public class Game { private int numberOfGuesses; private String unguessedCharacters; private ChosenWord chosenWord; private WordsBank wordsBank = new WordsBank(); private JFrame frame = new JFrame("Input"); public void startNewGame(){ // The abc letters to guess this.unguessedCharacters = "abcdefghijklmnopqrstuvwxyz"; numberOfGuesses = 0; // Getting a new random word to guess this.chosenWord = new ChosenWord(wordsBank.getRandomWord()); inputUserLetterGuess(); } // Handling a guess from the user, guessedChar is the guessed char private void handleUserLetterGuess(char guessedChar){ // Increasing number of guesses numberOfGuesses++; // Removing the guessed letter, so that the user can't guess it again removeOptionalCharGuess(guessedChar); // Running the guessing logic chosenWord.charGuess(guessedChar); } private void removeOptionalCharGuess(char guessedChar){ // Replacing the guessed char with empty char, so it can no longer be guessed unguessedCharacters = unguessedCharacters.replace(Character.toString(guessedChar), ""); } private void inputUserLetterGuess() { Character[] charactersArray = new Character[unguessedCharacters.length()]; // Converting to Characters array to be able to present in the dialog for (int index = 0; index &lt; charactersArray.length; index++) { charactersArray[index] = Character.valueOf(unguessedCharacters.charAt(index)); } // Input dialog Character guessedLetter = (Character) JOptionPane.showInputDialog(frame, "What letter do you want to guess?", "Letter guess", JOptionPane.QUESTION_MESSAGE, null, charactersArray, charactersArray[0]); // Validating return value if (guessedLetter == null){ exit(); return; } // Handling the user guess handleUserLetterGuess(guessedLetter); // Display results of the guess displayUserGuessResults(frame); } // Displays the results of the guess to the user private void displayUserGuessResults(JFrame frame){ // Displaying result JLabel wordStartLabel = new JLabel("After your guess: " + chosenWord.toString()); JButton button = new JButton(); JPanel panel = new JPanel(); panel.add(wordStartLabel); panel.add(button); frame.add(panel); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); // Checking if the word is completely exposed if (!chosenWord.isEntireWordGuessed()){ // If it isn't continue guessing button.addActionListener(e -&gt; { frame.remove(panel); inputUserLetterGuess(); }); button.setText("Continue guessing"); } else { JLabel guessesLabel = new JLabel("Congratulations! number of guesses is: " + numberOfGuesses); panel.add(guessesLabel); // If it is, show result and give option to start a new game button.addActionListener(e -&gt; { frame.remove(panel); startNewGame(); }); button.setText("Start a new game"); } } // Closing the frame on forced exit private void exit() { frame.dispose(); } } </code></pre> <p><strong>Main</strong></p> <pre><code>public class Main { public static void main(String[] args) { // Starts a new game Game game = new Game(); game.startNewGame(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T07:29:01.333", "Id": "416230", "Score": "1", "body": "I just scanned through the whole program and it looks really nice. The many comments in the first two classes are necessary right now. Soon, when you have gained more experience, you will be able to read the code without them. Instead of `with it's`, it should be `with its`. I'll leave the remaining nitpicks to the actual answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T08:25:22.917", "Id": "416232", "Score": "0", "body": "Thanks, I'm always happy to learn English Grammer too and not just coding ;)" } ]
[ { "body": "<h1>Swing Event Dispatching Thread</h1>\n\n<p>Always create and manipulate UI elements on Swing's EDT. It isn't hurting you yet, but it may later. It is better to get into the habit now:</p>\n\n<pre><code>public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n void run() {\n Game game = new Game();\n game.startNewGame();\n }\n });\n}\n</code></pre>\n\n<p>If Java8's lambda syntax doesn't frighten you, you could use:</p>\n\n<pre><code>public static void main(String[] args) {\n SwingUtilities.invokeLater( () -&gt; { Game game = new Game(); game.startNewGame(); } );\n}\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>public static void main(String[] args) {\n SwingUtilities.invokeLater( () -&gt; new Game().startNewGame() );\n}\n</code></pre>\n\n<hr>\n\n<h1>Word Bank</h1>\n\n<h2>Static Strings</h2>\n\n<p>Instead of setting the strings in the constructor, you could initialize them at declaration.</p>\n\n<pre><code>private final String[] words = { \"Adventure\", \"Hungary\", ... \"Australia\" };\n</code></pre>\n\n<p>Since the strings do no change, and every instance of <code>WordsBank</code> will have the same strings, this should even be <code>static</code>:</p>\n\n<pre><code>private final static String[] words = { \"Adventure\", \"Hungary\", ... \"Australia\" };\n</code></pre>\n\n<h2>Random</h2>\n\n<p>You are creating a new <code>Random</code> instance every time you call <code>getRandomWord()</code>. This is a little expensive. You could create the <code>Random</code> instance once, save it as a member:</p>\n\n<pre><code>private Random rand = new Random();\n\npublic String getRandomWord() {\n return Words[rand.nextInt(Words.length)];\n}\n</code></pre>\n\n<p>Or use a common thread-local random number generator: </p>\n\n<pre><code>public String getRandomWord() {\n return Words[ThreadLocalRandom.current().nextInt(Words.length)];\n}\n</code></pre>\n\n<hr>\n\n<h1>Game</h1>\n\n<h2><code>this.</code></h2>\n\n<p>You are not consistent in your usages of <code>this.</code>. For example:</p>\n\n<pre><code>this.unguessedCharacters = \"abcdefghijklmnopqrstuvwxyz\";\n\nnumberOfGuesses = 0;\n\nthis.chosenWord = new ChosenWord(wordsBank.getRandomWord());\n</code></pre>\n\n<p>Either use <code>this.</code> everywhere you are referencing an instance member:</p>\n\n<pre><code>this.numberOfGuesses = 0;\n\nthis.chosenWord = new ChosenWord(this.wordsBank.getRandomWord());\n</code></pre>\n\n<p>Or (my preference) don't use <code>this.</code> at all:</p>\n\n<pre><code>unguessedCharacters = \"abcdefghijklmnopqrstuvwxyz\";\n\nchosenWord = new ChosenWord(wordsBank.getRandomWord());\n</code></pre>\n\n<h2>frame</h2>\n\n<p>The member function <code>inputUserLetterGuess()</code> has access to the instance member <code>frame</code>, and so can make the call <code>displayUserGuessResults(frame);</code></p>\n\n<p>But <code>displayUserGuessResults()</code> is also a member function, and has access to <code>frame</code>. You don't need to pass it in as an argument.</p>\n\n<h2>displayUserGuessResults()</h2>\n\n<p>Ok - here is where your program really is in need of work. You are recreating the GUI each time the user guesses a letter, and then destroying it if the user selects \"Continue Guessing\". This is <strong>not</strong> the way to write a Swing GUI.</p>\n\n<p>Your game should have a <code>JFrame</code>, with one or more <code>JPanel</code> inside. In one <code>JPanel</code>, you should have a <code>JLabel</code> with the letter blanked word displayed. Your <code>Game</code> object should hold onto that <code>JLabel</code> as an instance variable, and after each guess is made, update the text of that <code>JLabel</code> to reveal the user's progress.</p>\n\n<hr>\n\n<p>Example Implementation with static GUI. I have all code entirely within one file, so only the <code>Main</code> class is declared public. Feel free to split into multiple files and declare the other classes public as well, if desired. The utility classes are very close to how you wrote them, with minor tweaks from my code review comments above. The <code>Game</code> class is significantly reworked, because I dislike the <code>JOptionsPane</code> being used for user input. Instead, I've added 26 button to the UI, and disable buttons as they have been pressed to prevent the user guessing those letters again. The layout is ugly, but it was a quick and dirty implementation, as an example of how to create a UI once at the beginning of the application and update it as the game progresses, instead of recreating the UI at each and every point. Hope it helps.</p>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.util.ArrayList;\nimport java.util.Random;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\n\nclass WordsBank {\n private final static String[] words = { \"Adventure\", \"Hungary\", \"Pizza\", \"Madrid\", \"Flower\",\n \"Chicken\", \"Israel\", \"Romania\", \"Denmark\", \"Australia\" };\n\n private final Random rand = new Random();\n\n public String getRandomWord() {\n return words[rand.nextInt(words.length)];\n }\n}\n\nclass ChosenWord {\n\n private String word;\n private boolean[] chars_guessed; \n\n public ChosenWord(String word){\n this.word = word.toLowerCase();\n chars_guessed = new boolean[word.length()];\n }\n\n public boolean isEntireWordGuessed() {\n\n for (boolean b : chars_guessed) {\n if (!b)\n return false;\n }\n\n return true;\n }\n\n public void charGuess(char guess) {\n int index = word.indexOf(guess);\n while (index &gt;= 0) {\n chars_guessed[index] = true; \n index = word.indexOf(guess, index + 1);\n }\n }\n\n @Override\n public String toString(){\n StringBuilder formatted_word = new StringBuilder();\n\n for(int index = 0; index &lt; word.length(); index++) {\n if (chars_guessed[index]) {\n formatted_word.append(word.charAt(index));\n } else {\n formatted_word.append('_');\n }\n\n formatted_word.append(' ');\n }\n\n return formatted_word.toString();\n }\n}\n\nclass Game {\n\n private final static String ALL_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n private final WordsBank words_bank = new WordsBank();\n private final JFrame frame = new JFrame(\"Guess the Word\");\n private final JLabel puzzle_word;\n private final ArrayList&lt;JButton&gt; letter_buttons = new ArrayList&lt;&gt;();\n\n private int number_guesses;\n private ChosenWord chosen_word;\n\n Game() {\n frame.setSize(300, 300);\n frame.setLocationRelativeTo(null);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n JPanel panel = new JPanel(new BorderLayout());\n puzzle_word = new JLabel(\"Puzzle: \");\n panel.add(puzzle_word, BorderLayout.PAGE_START);\n\n JPanel grid = new JPanel(new GridLayout(0, 7));\n for (int i=0; i&lt;ALL_LETTERS.length(); i++) {\n String letter = ALL_LETTERS.substring(i, i+1);\n JButton btn = new JButton(letter);\n btn.setActionCommand(letter);\n btn.addActionListener(this::guessLetter);\n letter_buttons.add(btn);\n grid.add(btn);\n }\n panel.add(grid, BorderLayout.CENTER);\n\n JButton btn = new JButton(\"Start a new Game\");\n panel.add(btn, BorderLayout.PAGE_END);\n btn.addActionListener(ActionEvent -&gt; this.reset());\n\n frame.setContentPane(panel);\n\n reset();\n frame.setVisible(true);\n }\n\n private void reset() {\n chosen_word = new ChosenWord(words_bank.getRandomWord());\n number_guesses = 0;\n\n for(JButton btn : letter_buttons) {\n btn.setEnabled(true);\n }\n\n update_game_state();\n }\n\n private void guessLetter(ActionEvent evt) {\n char guessed_letter = evt.getActionCommand().charAt(0);\n handleUserLetterGuess(guessed_letter);\n\n JButton button = (JButton) evt.getSource();\n button.setEnabled(false);\n\n if (chosen_word.isEntireWordGuessed()) {\n for (JButton btn : letter_buttons) {\n btn.setEnabled(false);\n }\n }\n }\n\n private void handleUserLetterGuess(char guessed_char){\n\n number_guesses++;\n chosen_word.charGuess(guessed_char);\n update_game_state();\n }\n\n private void update_game_state() {\n puzzle_word.setText(\"Puzzle: \" + chosen_word + \", guesses: \"+ number_guesses); \n }\n}\n\npublic class Main {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(Game::new);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T19:10:59.930", "Id": "416540", "Score": "0", "body": "I couldn't have wished for a better answer! Very informative and helpful, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T22:56:45.497", "Id": "215306", "ParentId": "215237", "Score": "3" } } ]
{ "AcceptedAnswerId": "215306", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T07:06:49.343", "Id": "215237", "Score": "3", "Tags": [ "java", "beginner", "object-oriented", "hangman" ], "Title": "Java simple game - guess the word" }
215237
<p>I am making plant growth program, and it works right now. But compared to other programs that interact between classes, mine looks inefficient to work. (for example, in Growth class, add "Environment" into init function and expressed as self.Environment.~) I tried to interpret other codes, but too complicated to understand as a beginner...</p> <p>Is there better way to edit my code to interact between classes? Thanks in advance!</p> <pre><code>import requests import random from matplotlib import pyplot as plt from time import sleep class Environment: """Getting 5 day weather forecast from weather API and choosing soil type that would be the base information for the plant growth""" def __init__(self, weather = None, temperature = None, temp_return = None, soil_type = None): self.weather = weather self.temperature = temperature self.temp_return = temp_return self.soil_type = soil_type self.daily_weather_list = [] def get_weather(self): # Error checking format while True: self.zip_code = input("Enter your zip code to get weather info: ") print('-'*30,"\n") self.url = "http://api.openweathermap.org/data/2.5/forecast?appid=a9fed4c32128f18e6142d3bd49fb5f7d&amp;units=metric&amp;zip=" + self.zip_code self.response = requests.get(self.url) self.result = self.response.json() if self.result["cod"] != "404": self.weather_list = self.result['list'] a = -8 # Extract 5 day weather forecast from json format for i in range(1, int(round((len(self.weather_list))/8+1,0))): a += 8 self.weather = self.result['list'][a]['weather'][0]['description'] self.temperature = self.result['list'][a]['main']['temp'] self.daily_weather_list.append(self.weather) print("Day", i, "Weather: {}".format(self.result['list'][a]['weather'][0]['description'])) print("Day", i, "Temperature: {} °C".format(self.result['list'][a]['main']['temp'])) print('-'*30, "\n") if self.temperature &gt;= 35: self.temp_return = "high" elif 35 &gt; self.temperature &gt;= 10: self.temp_return = "moderate" else: self.temp_return = "low" break else: print("***ZIP CODE NOT FOUND***\n") continue def choose_soil_type(self): # Error checking format while True: self.soil_type = input("Please choose soil type - [1]-alkaline, [2]-neutral, [3]-acidic: ") print('-'*30, "\n") if self.soil_type not in '123': print("***NOT A VALID SOIL TYPE***") continue else: break class Plants: """User choice of plants. After the selection, properties of the selected plant are provided.""" def __init__(self, preferred_sunshine = None, preferred_water = None, preferred_fertilizer = None, preferred_temp = None, preferred_soil = None): self.preferred_sunshine = preferred_sunshine self.preferred_water = preferred_water self.preferred_fertilizer = preferred_fertilizer self.preferred_temp = preferred_temp self.preferred_soil = preferred_soil def choose_plant(self): while True: print("**Plant information") print("*lemon - prefer moderate water, less fertilizer, neutral soil") print("*blueberry - prefer more water, moderate fertilizer, acidic soil") print("*pear - prefer less water, more fertilizer, alkaline soil\n") sleep(1) self.choose = input("Please choose your plant to breed [1]-lemon, [2]-blueberry, [3]-pear): ") print('-'*30, "\n") # Error checking if wrong plant name is entered if self.choose not in '123': print("***NOT A VALID PLANT***\n") continue # Locate properties of each plant if self.choose == "1": self.preferred_sunshine = 9 self.preferred_water = 5 self.preferred_fertilizer = 3 self.preferred_temp = "high" self.preferred_soil = "neutral" break elif self.choose == "2": self.preferred_sunshine = 6 self.preferred_water = 8 self.preferred_fertilizer = 5 self.preferred_temp = "moderate" self.preferred_soil = "acidic" break elif self.choose == "3": self.preferred_sunshine = 3 self.preferred_water = 3 self.preferred_fertilizer = 7 self.preferred_temp = "low" self.preferred_soil = "alkaline" break print("Next, you have to determine the amount of water and fertilizer in consideration of the weather.\n") sleep(2) print("Removing weed would be automatically performed, and you will get the full score if it is done in 3 times.\n") sleep(2) print("The goal is to reach 500% fruit growth for 5 days.") print('-'*30, "\n") class Growth: """Based on the plant choice and environment settings, user can select treatment amounts for each day, and calculate accumulated fruit size to determine success or failure.""" def __init__(self, Environment, Plants, water = 0, fertilizer = 0, weed = True): self.Environment = Environment self.Plants = Plants self.water = water self.fertilizer = fertilizer self.weed = weed def treatment(self): self.plot_list = [] self.tracker = 1 self.fruit_size = 0.1 # 5 day iteration from each day's weather forecast for items in self.Environment.daily_weather_list: # Adjust preferred amount of water based on the weather forecast if "rain" in items.lower() and "drizzle" not in items.lower(): self.Plants.preferred_water -= 3 print("Since it's raining, try to decrease the amount of water.\n") sleep(1) elif "drizzle" in items.lower(): self.Plants.preferred_water -= 1 print("Since it's drizzling, try to decrease the amount of water a little bit.\n") sleep(1) elif "clear sky" in items.lower(): self.Plants.preferred_water += 2 print("Since it's sunny outside, try to increase the amount of water.\n") sleep(1) # Error checking format # Determine effectiveness of water and fertilizer amount while True: print("Day", self.tracker) self.water = int(input("Please enter the amount of water (scale 0-10): ")) if self.water not in range(11): print("***NOT A VALID AMOUNT***") continue if self.water == self.Plants.preferred_water: self.water_score = 10 break elif self.Plants.preferred_water - 2 &lt;= self.water &lt;= self.Plants.preferred_water + 2: self.water_score = 7 break else: self.water_score = 4 break while True: self.fertilizer = int(input("Please enter the amount of fertilizer (scale 0-10): ")) if self.fertilizer not in range(11): print("***NOT A VALID AMOUNT***") continue if self.fertilizer == self.Plants.preferred_fertilizer: self.fertilizer_score = 10 break elif self.Plants.preferred_fertilizer - 2 &lt;= self.fertilizer &lt;= self.Plants.preferred_fertilizer + 2: self.fertilizer_score = 7 break else: self.fertilizer_score = 4 break # Automated weed removal: random score count = 0 while self.weed == True: x = 1* random.random() count += 1 if x &lt; 0.3: self.weed == False print("You have removed the weeds", count, "times to help the plant grow. Good job!\n") break if count &lt;= 3: self.weed_score = 10 else: self.weed_score = 5 # Calculate probability of fruit growth. Weight of parameters: water 30%, fertilizer 30%, soil type 10%, - user selection # weed 20%, temperature 10% - random self.probability = 0 if self.Environment.soil_type == self.Plants.preferred_soil: self.probability += random.uniform(0.7, 0.9) * 0.1 else: self.probability += random.uniform(0.3, 0.5) * 0.1 if self.Environment.temp_return == self.Plants.preferred_temp: self.probability += random.uniform(0.7, 0.9) * 0.1 else: self.probability += random.uniform(0.3, 0.5) * 0.1 if self.water_score == 10: self.probability += random.uniform(0.7, 0.9) * 0.3 elif self.water_score == 7: self.probability += random.uniform(0.4, 0.6) * 0.3 elif self.water_score == 4: self.probability += random.uniform(0.1, 0.3) * 0.3 if self.fertilizer_score == 10: self.probability += random.uniform(0.7, 0.9) * 0.3 elif self.fertilizer_score == 7: self.probability += random.uniform(0.4, 0.6) * 0.3 elif self.fertilizer_score == 4: self.probability += random.uniform(0.1, 0.3) * 0.3 if self.weed_score == 10: self.probability += random.uniform(0.7, 0.9) * 0.2 else: self.probability += random.uniform(0.3, 0.5) * 0.2 self.fruit_size = self.fruit_size + self.fruit_size * self.probability self.tracker += 1 # For plotting fruit growth self.plot_list.append((self.tracker-1, round(((self.fruit_size - 0.1)/0.1)*100, 0))) print("Accumulated growth check: ", round(((self.fruit_size - 0.1)/0.1)*100, 0),"% growth") print('-'*30, "\n") print("Fruit size was increased by {}%".format(round(((self.fruit_size - 0.1)/0.1)*100, 0))) print('-'*30, "\n") # Determine the success or failure of fruit growth to a desired point if self.fruit_size &gt; 0.6: print("Great job! You successfully raised the fruit of", self.Plants.choose, "to a desired point.") else: print("I'm sorry to inform you that you failed to raise the fruit of", self.Plants.choose, "to a desired point.") class Growth_plot: """Plot of fruit growth progress""" def __init__(self, Growth): self.Growth = Growth def generate_plot(self): plt.scatter(*zip(*self.Growth.plot_list)) plt.title('Fruit Growth Chart') plt.xlabel('Day') plt.ylabel('Growth %') plt.show() def start_engine(): """Core of the plant growth program.""" print("Welcome to the plant growth game! Please select your location to grow your own plant of your choice.\n") sleep(1) a = Environment() a.get_weather() a.choose_soil_type() b = Plants() b.choose_plant() c = Growth(a, b) c.treatment() d = Growth_plot(c) d.generate_plot() start_engine() </code></pre>
[]
[ { "body": "<p>Hello and welcome to CodeReview! It looks like you're just getting started with OO programming in Python. On the plus side, you've organized your classes by separate areas of responsibility and areas of focus: separating the environment from the plants from the growth from the plotting. That's all good, solid OO design work.</p>\n\n<p>Here are some things I think you could improve:</p>\n\n<h3>Look beyond the surface</h3>\n\n<p>You broke your classes down into obvious parts based on the problem statement. You didn't break them down (yet) based on the actual code you were writing. What's one thing you missed? Interacting with the user!</p>\n\n<p>Every one of your classes tries to \"talk\" with the user: they contain <code>print</code> calls that send output, and <code>input</code> calls that collect input. You should consider writing some user interface code that handles all that talking for you, and then passing that object to the other parts of your program:</p>\n\n<pre><code>user = UserInterface()\nenv = Environment(user)\ngrowth = Growth(user)\n...\n</code></pre>\n\n<p>This would let you identify common themes in your interaction with the user -- like repeating a question until you get an acceptable answer -- and coding them in a central place. It would also make it easier to write unit tests. If you can just swap out a \"keyboard\" object for a \"scripted responses\" object, its easier to control the program and set up test scenarios.</p>\n\n<h3>Separate configuration data from creation</h3>\n\n<p>Most of your classes ask the user questions to set up their data. I suggest that you pull the questioning out (see above) and start passing the setup data to the classes as part of object creation:</p>\n\n<pre><code>zip_code = get_zip_code(user)\nenv = Environment(zip_code)\n</code></pre>\n\n<p>An alternative might be to create a <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\"><em>factory method</em></a> to put the question, the validation, and possibly data conversion into the class with the object creation. Something like:</p>\n\n<pre><code>plant = Plant.get_crop_from_user(user)\n\n# in class Plant:\n@classmethod\nget_crop_from_user(cls, user):\n crops = (\"lemon\", \"blueberry\", \"pear\")\n choice = user.show_menu(crops, prompt=\"What kind of crops to grow?\")\n return cls(crops[choice])\n</code></pre>\n\n<h3>Don't assume the internet is fast</h3>\n\n<p>When I ran your program, connecting to the openweathermap site to get the weather data took several seconds. You should make it clear when you're doing something over the net, to prevent the user from thinking the program is hung up. Since you can't show a \"spinning wheel\" effect, settle for just printing a message about what you're doing:</p>\n\n<pre><code>print(\"Stand by. Getting weather data from openweathermap.org\")\n</code></pre>\n\n<h3>Know what to forget</h3>\n\n<p>You use a lot of object attributes. A <em>lot</em> of attributes. A <strong>lot.</strong></p>\n\n<p>Many of those attributes are never used again. They appear in a method in one or two lines, and then nowhere else in the file. </p>\n\n<p>Those items should be replaced by local variables in the particular methods. For example, in <code>Environment.get_weather</code> you use <code>self.zip_code</code> which never gets used anyplace else. Your only use for it is to construct the query URL for your openweathermap call.</p>\n\n<p>Also, you use <code>self.result</code>. You refer to it several times in in <code>get_weather</code> but it never gets used anyplace else in the code. Both of those could be local variables. Instead of <code>self.zip_code</code> just use <code>zip_code</code>. Instead of <code>self.result</code> use <code>result</code>. They will be valid until the end of the <code>get_weather</code> method, and then they'll be forgotten, which is fine since you only use them in the one place.</p>\n\n<h3>Choose your names wisely</h3>\n\n<p>In general, you did a pretty good job with names until you got to your <code>start_engine</code> function. Why did you go with <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code>? Why not <code>env</code>, <code>plants</code>, <code>growth</code>, and <code>plot</code>? </p>\n\n<h3>Follow community standards</h3>\n\n<p>As they write in <a href=\"https://en.wikipedia.org/wiki/They_Live\" rel=\"nofollow noreferrer\">the movie</a>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/clHY8.png\" width=\"150\" height=\"150\"/></p>\n\n<p>You did a good job putting your code into the <code>start_engine</code> function, and then calling it:</p>\n\n<pre><code>start_engine()\n</code></pre>\n\n<p>But <code>start_engine</code> doesn't mean anything to me, except as the last few words of the <a href=\"http://www.jefffoxworthy.com/jokes/redneck-1420\" rel=\"nofollow noreferrer\">US national anthem.</a></p>\n\n<p>On the other hand, <code>main</code> definitely means something to a lot of people. And the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">officially suggested way</a> to call it is:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>This construction lets other modules import your code without automatically running the game. The only time the <code>if</code> statement will succeed is when you run the program like <code>python myfile.py</code>. If some other module (like a unit test driver) imports your code, the condition will fail and <code>main</code> won't be called. Always do this!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T00:39:10.277", "Id": "215466", "ParentId": "215243", "Score": "3" } } ]
{ "AcceptedAnswerId": "215466", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T08:53:12.433", "Id": "215243", "Score": "9", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Plant growth program" }
215243
<p>This is a controller, which receives the validated input from a http request, then finds the assorted model and for each translation key in the received data, it will add it to the model.</p> <pre><code>public function update(UpdateMenuItemRequest $request) { $validated = $request-&gt;validated(); $item = MenuItem::findOrFail($validated['id']); foreach($validated['translations'] as $validatedTranslation) { $item-&gt;translations()-&gt;updateOrCreate(['locale' =&gt; $validatedTranslation['locale']], $validatedTranslation); } return $item; } </code></pre> <p>Is this Object Oriented enough? It doesn't seem like this method is violating SRP in the first place, or could it be improved? Thank you.</p>
[]
[ { "body": "<p>You could use route model binding to remove some lines from your code, but that would require changing the route so it passes the MenuItem's id.</p>\n\n<pre>\n<code><strike>public function update(UpdateMenuItemRequest $request)</strike>\npublic function update(MenuItem $item, UpdateMenuItemRequest $request)\n{\n $validated = $request->validated();\n\n <strike>$item = MenuItem::findOrFail($validated['id']);</strike>\n\n foreach($validated['translations'] as $validatedTranslation) {\n $item->translations()->updateOrCreate(['locale' => $validatedTranslation['locale']], $validatedTranslation);\n }\n\n return $item;\n}\n</code></pre>\n\n<p>Also, if you want legibility and go all out with functional programming, you could replace your loop with a collection method.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code># Assuming the request object only has a translation array since you don't need the id anymore\npublic function update(MenuItem $item, UpdateMenuItemRequest $request)\n{\n collect($request-&gt;validated()['translations'])-&gt;each(function ($translation) use ($item) {\n $item-&gt;translations()-&gt;updateOrCreate($translation);\n });\n}\n</code></pre>\n\n<p>Depending on what kind of relationship we're dealing with there could be other ways as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T16:43:50.553", "Id": "230857", "ParentId": "215244", "Score": "4" } } ]
{ "AcceptedAnswerId": "230857", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T09:04:02.310", "Id": "215244", "Score": "1", "Tags": [ "php", "laravel", "eloquent" ], "Title": "A PHP Controller, which feels to 'array-like', in Laravel" }
215244
<p>I'm starting to code in the OOP way, but I have doubts with the following example. I have a <code>Product</code> entity and I want to import &amp; create instances of this entity from a CSV file. I load the CSV file into an array in another part of the code, then I pass the array with the data to <code>CSVImport</code> class. </p> <pre><code>class Product { private $id; private $name; private $price; private $stock; private $imageUrl; public function __construct() {} /** Getters &amp; setters */ } class CSVImport extends ProductImport { private $websiteUrl; public function __construct($websiteUrl) { $this-&gt;websiteUrl = $websiteUrl; } public function import($csvData) { $productCollection = new ProductCollection(); foreach ($csvData as $rowData) { $product = $this-&gt;parseProductData($rowData); $productCollection-&gt;addProduct($product); } return $productCollection; } private function parseProductData($productData) { $product = new Product(); list( $id, $name, $price, $stock, $imagePath ) = $productData; $product -&gt;setId($id) -&gt;setName($name) -&gt;setPrice($price) -&gt;setStock($stock) -&gt;setImageUrl($this-&gt;websiteUrl.$imagePath); return $product; } } </code></pre> <p>My questions are:</p> <ol> <li>Is it correct to pass an array of data to <code>CSVImport</code> class? Or should it take the responsability to read &amp; load the CSV file?</li> <li>Who should take care of data validation, <code>Product</code> setters, <code>CSVImport</code> class or a new class? And how can I manage validation errors? </li> <li>In case I need to transform the source data, as I've done with <code>imageUrl</code>, is the correct place to do it?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T14:57:13.960", "Id": "416285", "Score": "0", "body": "Welcome to Code Review. Your comment `/** Getters & setters */` and the `ProductCollection` indicates that there is some code missing. We expect your code to include *all* parts necessary for a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T12:24:58.293", "Id": "416477", "Score": "0", "body": "Hello @Zeta, thank you for your comment, but I was trying not to post a large amount of code. I think that the code can be understood without those parts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T10:32:52.613", "Id": "416798", "Score": "0", "body": "This is my Opinion, **1.** CSVImport , unless you also need to do arrays, in which case make another method for reading the data from the file, but it should be part of the class. The class won't work well without the CSV data. You'd have to make changes to both if fields are added etc.. You can also remove a loop by importing where the `foreach` is and using the file reading loop instead. **2** Product setters, if you ever need to manually create a product, you want them to do the validation too. **3** Should be part of validation, bad data goes in `set`, good data comes from `get`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T10:38:20.150", "Id": "416799", "Score": "0", "body": "For errors, that's harder to say. Use exceptions for validation errors, catch them in the CSV reading loop, so you can continue reading. You'll have to decide what state to leave the Product class in if you do a partial read. If you don't mind passing the constructor an array of this data, even an optional array, you could do all the setting there `$this->{\"set$key\"}($value)` etc. But the big advantage is throwing an exception before the constructor completes destroys the object. Because the constructor can't return the instance in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T10:44:36.523", "Id": "416800", "Score": "0", "body": "Sorry, this `$this->websiteUrl.$imagePath` is part of the input. You can't/shouldn't pass it separatly to the Product" } ]
[ { "body": "<p>As I said in the comments:</p>\n\n<blockquote>\n <p>For errors, that's harder to say. Use exceptions for validation errors, catch them in the CSV reading loop, so you can continue reading. You'll have to decide what state to leave the Product class in if you do a partial read. If you don't mind passing the constructor an array of this data, even an optional array, you could do all the setting there $this->{\"set$key\"}($value) etc. But the big advantage is throwing an exception before the constructor completes destroys the object. Because the constructor can't return the instance in that case</p>\n</blockquote>\n\n<p>Something like this </p>\n\n<pre><code>class Product\n{\n\n private $imageUrl = false;\n\n public function __construct(array $data = []){\n if(!empty($data)){\n foreach($data as $line=&gt;$value){\n if(isset($this-&gt;{$key})){\n $this-&gt;{\"set$key()\"}($value);\n }\n }\n }\n }\n\n public setImageUrl($image){\n if(empty($image)) throw new InvalidArgumentException(\"Image is empty\");\n $this-&gt;imageUrl= $image;\n\n }\n}\n</code></pre>\n\n<p>There are a few tricks here, but you have to set the default to false for <code>if(isset($this-&gt;{$key}))</code> to work, but it's faster then <code>property_exists</code>. This part will dynamically call <code>setimageUrl</code> in this case. The lowercase <code>i</code> doesn't matter much in <code>setImageUrl</code> as user defined methods/function are case insensitive.</p>\n\n<p>The other part I said is this:</p>\n\n<blockquote>\n <p>This is my Opinion, <strong>1.</strong> CSVImport , unless you also need to do arrays, in which case make another method for reading the data from the file, but it should be part of the class. The class won't work well without the CSV data. You'd have to make changes to both if fields are added etc.. You can also remove a loop by importing where the foreach is and using the file reading loop instead. <strong>2.</strong> Product setters, if you ever need to manually create a product, you want them to do the validation too. <strong>3.</strong> Should be part of validation, bad data goes in set, good data comes from get</p>\n</blockquote>\n\n<p>Most of that is pretty self explanatory. For <code>#3</code> the <code>-&gt;setImageUrl($this-&gt;websiteUrl.$imagePath);</code> is part of the input data. So that is fine. You don't want to have to pass them separately. In fact with data loading in the constructor of the Product you can skip that method completely as it becomes:</p>\n\n<pre><code> private function parseProductData($productData)\n {\n return new Product($productData);\n }\n</code></pre>\n\n<p>So that alone saves you a call to <code>list</code> and a call to <code>parseProductData</code> for each product.</p>\n\n<p>I can give you more examples if you need them</p>\n\n<p>I would do the CVSImport something like this (untested)</p>\n\n<pre><code>class CSVImport extends ProductImport\n{\n private $websiteUrl;\n\n private $errors = [];\n\n public function __construct($websiteUrl)\n {\n $this-&gt;websiteUrl = $websiteUrl;\n }\n\n public function import($csvData)\n {\n $productCollection = new ProductCollection();\n //you could do file reading here with a while loop\n foreach ($csvData as $line=&gt;$rowData) {\n try{\n $productCollection-&gt;addProduct(new Product($rowData));\n }catch(Exception $e){\n $this-&gt;errors[$line] = get_class($e).\"::{$e-&gt;getCode()} {$e-&gt;getMessage()} in {$e-&gt;getFile()} on {$e-&gt;getLine()}\";\n } \n\n }\n\n return $productCollection;\n }\n\n //or for max flexabillity you can do it here\n public function readCsv($filename){\n if(!file_exists($filename)) throw new Exception(\"Could not find file $filename\".);//etc.\n\n $f = fopen($filename, 'r');\n\n $header = fgetcsv($f); //get header row\n $len = count($header);\n\n $line = 0;\n $rowData= [];\n while(!feof($f)){\n ++$line;\n\n try{\n $current = fgetcsv($f);\n\n if(count($current) != $len) throw new Exception(\"Delimter count missmatch on line $line of $filname\");\n\n $rowData[$line] = array_combine($header, $current); //combine [$haders =&gt; $current]\n }catch(Exception $e){\n $this-&gt;errors[$line] = get_class($e).\"::{$e-&gt;getCode()} {$e-&gt;getMessage()} in {$e-&gt;getFile()} on {$e-&gt;getLine()}\";\n } \n } \n\n return $rowData;\n }\n\n public function getErrors(){\n return $this-&gt;errors;\n }\n\n public function hasErrors(){\n return count($this-&gt;errors)\n }\n\n}\n</code></pre>\n\n<p>So you see the <code>try/catch</code> is almost the same, you could combine these two methods <code>readCsv</code> and <code>import</code>. But then you cannot accept array as data only the file. That's up to you.</p>\n\n<p>The basics are that you can do <code>new Product($data)</code> and it does all the setting of the data using it's set methods. Then if you throw exceptions in those set methods it not only helps you when using them manually, but when constructing a product from the CSV, the product dies as the exception is thrown. Then we catch that, keep track of it, and move on to the next row. Each part handling it's own concerns.</p>\n\n<p>In any case now it's all nice and clean, the other option would be to make a class just for reading CSV data, that takes headers as an argument, and does some mapping on them etc. But its a lot easier to find then putting the CSV stuff in some random place.</p>\n\n<p>Cheers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T10:52:54.003", "Id": "215497", "ParentId": "215247", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T09:56:42.813", "Id": "215247", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "Import class using OOP" }
215247
<p><code>GlueArrays</code> is used for iterating over an array of arrays, and it looks like this:</p> <p><strong>Main.java</strong></p> <pre><code>import java.util.Iterator; import java.util.NoSuchElementException; public class Main { public static class GlueArrays&lt;T&gt; implements Iterable&lt;T&gt; { private final T[][] arrays; public GlueArrays(T[]... arrays) { this.arrays = arrays; } @Override public Iterator&lt;T&gt; iterator() { return new GlueArrayIterator(arrays); } private static class GlueArrayIterator&lt;T&gt; implements Iterator&lt;T&gt; { private final T[][] arrays; private int arrayIndex = 0; private int localIndex = 0; GlueArrayIterator(T[][] arrays) { this.arrays = arrays; } @Override public boolean hasNext() { if (arrayIndex == arrays.length) { return false; } return arrayIndex &lt; arrays.length || localIndex &lt; arrays[arrayIndex].length; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException("Nothing to iterate."); } T returnValue = arrays[arrayIndex][localIndex]; if (localIndex &lt; arrays[arrayIndex].length) { localIndex++; if (localIndex == arrays[arrayIndex].length) { localIndex = 0; arrayIndex++; } } return returnValue; } } } public static void main(String[] args) { Number[] arr1 = {1, 2, 3}; Number[] arr2 = {4f, 5f, 6f}; Number[] arr3 = {7.0, 8.0, 9.0}; for (Number number : new GlueArrays&lt;&gt;(arr1, arr2, arr3)) { System.out.println(number); } } } </code></pre> <p>As always, any critique is welcome.</p>
[]
[ { "body": "<p>First off, this is buggy. If one of the input arrays is empty, you'll get an <code>ArrayIndexOutOfBoundsException</code> - and even if you correct that error, the iterator will stop if it encounters an empty array.</p>\n\n<p>Consider using proper tests with multiple scenarios, especially with edge cases, in order to catch errors like that.</p>\n\n<hr>\n\n<p>Then I get two warnings from Eclipse (other compilers and their settings may differ, but I believe these are \"common\" warnings, that normally would be raised). You should never have warnings. Code should preferably be adjusted or rewritten to avoid them, or at the very least (if you have a good reason to keep the warning) annotated with <code>@SuppressWarnings</code> and commented on with those reasons.</p>\n\n<p>1) Due to the use of generics together with variable arguments the <code>GlueArrays</code> constructor should have the annotation <code>@SafeVarArgs</code>.</p>\n\n<p>2) The instantiation of the iterator in <code>iterate()</code> is lacking its type parameters. It should be</p>\n\n<pre><code>return new GlueArrayIterator&lt;T&gt;(arrays);\n</code></pre>\n\n<p>or, if you are at least using Java 1.7, just</p>\n\n<pre><code>return new GlueArrayIterator&lt;&gt;(arrays);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:10:04.253", "Id": "215260", "ParentId": "215248", "Score": "6" } }, { "body": "<p>Do you really need an iterator? You could do the same with three lines of Streams and flat mapping:</p>\n\n<pre><code>Arrays.stream(twoDimensionalArray)\n .flatMap(array -&gt; Arrays.stream(array))\n .forEach(element -&gt; System.err.println(element));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T06:47:24.303", "Id": "215477", "ParentId": "215248", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T10:18:57.947", "Id": "215248", "Score": "2", "Tags": [ "java", "array", "iterator", "iteration" ], "Title": "A Java Iterable over multiple arrays" }
215248
<p>I need to find correct index in a array by comparing ranges. Here is my first try:</p> <pre><code>int TunerDriver::TunerLookUpTable(double Freq) { Freq /= 1e6; if (Freq &gt;= 60 and Freq &lt; 140) return 1; else if (Freq &gt;= 180 and Freq &lt; 280) return 2; else if (Freq &gt;= 280 and Freq &lt; 460) return 3; else if (Freq &gt;= 140 and Freq &lt; 180) return 4; else if (Freq &gt;= 2720 and Freq &lt; 4020) return 5; else if (Freq &gt;= 4020 and Freq &lt;= 6000) return 6; else if (Freq &gt;= 2000 and Freq &lt; 2720) return 7; else if (Freq &gt;= 830 and Freq &lt; 1420) return 8; else if (Freq &gt;= 1420 and Freq &lt; 2000) return 9; else if (Freq &gt;= 460 and Freq &lt; 830) return 10; else { //TODO: throw exception } } </code></pre> <p>I believe I can use <code>std::pair</code> and <code>for</code> to increase readability. Can you assist me in this case?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:01:58.030", "Id": "416269", "Score": "0", "body": "You could more simply use `std::map()` and/or `std::lower_bound()`. But you really need to improve the question - *why* do you need to do this lookup? What do the return values actually *mean*?" } ]
[ { "body": "<p>It's a short bit of code, but enough to work with, I think. Here are some suggestions to help you improve your code.</p>\n\n<h2>Minimize the number of comparisons</h2>\n\n<p>There is not really a need to check both upper and lower bounds for each possibility if the comparisons are done in order. That is, we could compare the incoming <code>Freq</code> to 60, then 140, then 180, etc. That might look like this:</p>\n\n<pre><code>int FreqLookup(double Freq) {\n if (Freq &lt; 60e6 || Freq &gt; 6000e6) {\n return 0; // or throw an error\n }\n if (Freq &lt; 140e6) return 1;\n if (Freq &lt; 180e6) return 4;\n if (Freq &lt; 280e6) return 2;\n if (Freq &lt; 460e6) return 3;\n if (Freq &lt; 830e6) return 10;\n if (Freq &lt; 1420e6) return 8;\n if (Freq &lt; 2000e6) return 9;\n if (Freq &lt; 2720e6) return 7;\n if (Freq &lt; 4020e6) return 5;\n return 6;\n}\n</code></pre>\n\n<h2>Put constants in a structure</h2>\n\n<p>Having the constants in a structure allows the code to be more data driven. Here's what I'd suggest:</p>\n\n<pre><code>struct FreqTableEntry {\n double freq;\n int divisor;\n operator double() const { return freq; }\n}; \nstatic constexpr std::array&lt;FreqTableEntry, 11&gt; lookup {{\n { 60e6, 0 }, // error if below 60e6\n { 140e6, 1 },\n { 180e6, 4 },\n { 280e6, 2 },\n { 460e6, 3 },\n { 830e6, 10 },\n { 1420e6, 8 },\n { 2000e6, 9 },\n { 2720e6, 7 },\n { 4020e6, 5 },\n { 6000e6, 6 },\n}};\n</code></pre>\n\n<p>Now we have a nice, neat, compile-time lookup table. Note also that we can avoid division by simply using the full value in the table.</p>\n\n<h2>Use a standard algorithm</h2>\n\n<p>The <a href=\"https://en.cppreference.com/w/cpp/algorithm/upper_bound\" rel=\"nofollow noreferrer\"><code>std::upper_bound</code></a> algorithm returns an iterator to the first entry that is greater than the given value. We can use it:</p>\n\n<pre><code>auto it{std::upper_bound(lookup.cbegin(), lookup.cend(), Freq)};\n</code></pre>\n\n<p>It would be nice to simply return <code>it-&gt;divisor</code> but we have to handle a few special cases. First, if the frequency is exactly 6000e6, we need to return 6. Next, if the frequency is &lt; 60e6 or > 6000e6, we need to indicate an error. I've chosen to return 0 as an indication of error, but one could also <code>throw</code> if that's more appropriate. Putting it all together we have this:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;algorithm&gt;\n\nint alt(double Freq) {\n struct FreqTableEntry {\n double freq;\n int divisor;\n operator double() const { return freq; }\n }; \n static constexpr std::array&lt;FreqTableEntry, 11&gt; lookup {{\n { 60e6, 0 }, // error if below 60e6\n { 140e6, 1 },\n { 180e6, 4 },\n { 280e6, 2 },\n { 460e6, 3 },\n { 830e6, 10 },\n { 1420e6, 8 },\n { 2000e6, 9 },\n { 2720e6, 7 },\n { 4020e6, 5 },\n { 6000e6, 6 },\n }};\n // special case the last entry\n if (Freq == lookup.back().freq) {\n return lookup.back().divisor;\n }\n auto it{std::upper_bound(lookup.cbegin(), lookup.cend(), Freq)};\n if (it == lookup.cend() || it-&gt;divisor == 0) { \n return 0; // could throw here as alternative\n }\n return it-&gt;divisor;\n}\n</code></pre>\n\n<h2>Provide a test program</h2>\n\n<p>It's often helpful to write a test program and to provide it to reviewers to make it clear what the program is expected to do and how it will be called. I modified your routine slightly to return 0 as an error indication and made it a standalone function. The test program in this case, was just to compare the original routine to the alternative (named <code>alt</code>) shown above:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main() {\n for (double f{30e6}; f &lt;= 6020e6; f += 10e6) {\n if (TunerLookUpTable(f) != alt(f)) {\n std::cout &lt;&lt; \"ERROR: TunerLookUpTable(\" &lt;&lt; f/1e6 &lt;&lt; \" MHz) = \" \n &lt;&lt; TunerLookUpTable(f) &lt;&lt; \", but alt(f) = \" &lt;&lt; alt(f) &lt;&lt; '\\n';\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:20:07.080", "Id": "416326", "Score": "0", "body": "The first code block differs from the original if passed a NaN (returns 6 rather than 0 or throw). The subsequent examples look okay." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:31:34.490", "Id": "416330", "Score": "0", "body": "That would be a useful condition to add to a test program." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:07:01.490", "Id": "215258", "ParentId": "215251", "Score": "5" } } ]
{ "AcceptedAnswerId": "215258", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T10:48:59.570", "Id": "215251", "Score": "1", "Tags": [ "c++", "c++11" ], "Title": "Finding index in list in C++" }
215251
<pre><code>i=0 while i&lt;=10: i+=1 if i==5: continue print i*5 </code></pre> <p>It prints the multiplication table of 5 as well as skips the 5th number in the series</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:49:39.460", "Id": "416253", "Score": "0", "body": "A good trick is to use a for loop rather than needing to iterate through i in a while loop, `for i in range(1, 12)` will do this for you rather than needing the `i+=1` and the `i=0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:03:51.440", "Id": "416270", "Score": "1", "body": "@13ros27 - that sounds like a review of the code (\"*Use `for` instead of `while`*), so should be posted as an Answer, so we can give you some votes!" } ]
[ { "body": "<p>I don't program in Python but this is a pretty simple problem to solve.\nHere is the code then I will break it down for you</p>\n\n<pre><code>for i in range(0, 10):\n if i != 5:\n print (i*5)\n</code></pre>\n\n<p>So let's go over this. The first line is a <a href=\"https://www.w3schools.com/python/python_for_loops.asp\" rel=\"nofollow noreferrer\"><code>for</code> loop</a>. This kind of loop is kinda like the <code>while</code> loop but it creates and increments the variable for you and has a harder chance of going infinite. The <code>range()</code> part of that line is just saying to start <code>i</code> at 0 and to increment it by 1 until it reaches 10.</p>\n\n<p>The next line is just checking if <code>i == 5</code> and if so, it will not print that result.</p>\n\n<p>The final line just prints <code>i*5</code> if <code>i</code> is not 5.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:58:17.567", "Id": "416254", "Score": "3", "body": "Why did you change the equality comparison to use `is` instead of `==`? Using `is` to compare numbers is unreliable (and therefore considered wrong). Example: `print(-6 is (-5-1))` can produce `False`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T12:15:30.317", "Id": "416257", "Score": "0", "body": "@200_success I did not know this. As I stated I do not program in Python and just assume it was one of those stile choices that was made to make the language more readable.\nAlso I tried the example you gave me but Python handled it fine\n`>>> print(-6 is (-5-1))\nTrue`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T12:16:58.520", "Id": "416258", "Score": "0", "body": "Try the comparison with very large or very negative numbers then. Or with floating-point numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T12:20:22.903", "Id": "416259", "Score": "0", "body": "@200_success All languages have problem with floating point values because of there inherent disabilities. Do you have any articles I can read talking about the difference of using `is` instead of `==`and the downsides and upsides of each?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:52:54.517", "Id": "416276", "Score": "2", "body": "See [Is there a difference between \"==\" and \"is\"?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is). Short answer: `is` tests for identity, where `==` tests for equivalent values. Compare `1 == 0.5 * 2` and `1 is 0.5 * 2`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:30:36.157", "Id": "215254", "ParentId": "215252", "Score": "0" } }, { "body": "<p>This is the longest possible answer to the shortest problem...</p>\n\n<h2>How to make better loops in python</h2>\n\n<ol>\n<li><code>iterables</code></li>\n<li><code>for</code> loops</li>\n<li><code>range</code></li>\n<li>list comprehensions</li>\n<li>Generator expressions </li>\n</ol>\n\n<h2>How to improve this particular code</h2>\n\n<ol>\n<li>what is the simplest way possible of writing it</li>\n<li>what is the shortest way possible of writing it</li>\n</ol>\n\n<hr>\n\n<h2>How to make better loops in python</h2>\n\n<h3>1. <code>iterables</code></h3>\n\n<p>For loops can iterate over any iterables. What is an iterable? An iterable is a object we can iterate through.</p>\n\n<p>More seriously, an iterable is an object that is itself a sequence of other objects. A list is an iterable, but it is not the only one as you will discover when you learn more about python.</p>\n\n<h3>2. <code>for</code> loops</h3>\n\n<p>A <code>for</code> loop can iterate over an iterable (in this case a list) like so:</p>\n\n<pre><code>for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:\n print(i)\n</code></pre>\n\n<h3>3. <code>range</code></h3>\n\n<p>The previous example is ugly because:\n1. Hard-coded values can't be easily changed and are prone to mistakes.\n2. We stored the first 10 positive integers in memory which take 144 bytes but it isn't scalable as if I want the first 1000000 positive integer, I would need <code>9 mo</code> of memory.</p>\n\n<p>That's where <code>range</code> comes in, it is an iterable that doesn't take much space and is often used in loops:</p>\n\n<pre><code>for i in range(10):\n print(i)\n</code></pre>\n\n<p>note: in earlier versions of python, range created a list and was equivalent to the first example.</p>\n\n<p>What if I only want the numbers between 22 and 42 and skip every odd number:</p>\n\n<pre><code>for i in range(22, 43, 2):\n # range(start, end, step) &lt;- this is a comment\n print(i)\n</code></pre>\n\n<p>note: the <code>range(22, 43)</code> doesn't actually include 43</p>\n\n<h3>4. list comprehensions</h3>\n\n<p>But wait, I don't want a 5 in my range, how can I remove it ?</p>\n\n<pre><code>for i in range(10):\n if i==5:\n continue\n print(i)\n</code></pre>\n\n<p>The technical term for continue is \"ugly\".</p>\n\n<p>What you can use instead is this:</p>\n\n<pre><code>for i in range(10):\n if i!=5:\n print(i)\n</code></pre>\n\n<p>Which is better, but isn't what I want to show you. What I want to show you is list comprehensions:</p>\n\n<pre><code>l = [n for n in range(10) if n!=5]\nfor i in l:\n print(i)\n</code></pre>\n\n<p>A list is an iterable remember. Well, I've created a list containing the first 10 number except 5.</p>\n\n<h3>5. Generator expression</h3>\n\n<p>Remember also that I've said that a list was a very bad choice due to the memory inefficiency. Well fortunately for us, we have a better solution, generator expressions:</p>\n\n<pre><code>l = (n for n in range(10) if n!=5)\nfor i in l:\n print(i)\n</code></pre>\n\n<p>What changed ? Parentheses ! As easy as that. </p>\n\n<p>But wait, I want to do the table of 5. How can I do that ?</p>\n\n<pre><code>l = (n for n in range(10) if n!=5)\nfor i in l:\n print(i*5)\n</code></pre>\n\n<p>Yes, that works, but what if...</p>\n\n<pre><code>l = (n*5 for n in range(10) if n!=5)\nfor i in l:\n print(i)\n</code></pre>\n\n<p>Yep, that also works...</p>\n\n<h2>How to improve your particular code</h2>\n\n<h3>1. what is the simplest way possible of writing it</h3>\n\n<pre><code>for i in range(10):\n if i!=5:\n print(i*5)\n</code></pre>\n\n<h3>2. what is the shortest way possible of writing it</h3>\n\n<pre><code>print('\\n'.join(str(n*5) for n in range(10) if n!=5))\nor \nprint(*(n*5 for n in range(10) if n!=5), sep='\\n')\n</code></pre>\n\n<p>As you learn more about python, you might be tempted to use the second one. But it isn't pythonic because it violates at least 6 of Tim Peter's commandment:</p>\n\n<blockquote>\n <p>Beautiful is better than ugly.&lt;<br>\n Explicit is better than implicit.<br>\n Simple is better than complex.&lt;<br>\n Complex is better than complicated.<br>\n Flat is better than nested.&lt;<br>\n Sparse is better than dense.&lt;<br>\n Readability counts.&lt;<br>\n Special cases aren't special enough to break the rules.<br>\n Although practicality beats purity.<br>\n Errors should never pass silently.<br>\n Unless explicitly silenced.<br>\n In the face of ambiguity, refuse the temptation to guess.<br>\n There should be one-- and preferably only one --obvious way to do it.&lt;<br>\n Although that way may not be obvious at first unless you're Dutch.<br>\n Now is better than never.<br>\n Although never is often better than <em>right</em> now.<br>\n If the implementation is hard to explain, it's a bad idea.<br>\n If the implementation is easy to explain, it may be a good idea.<br>\n Namespaces are one honking great idea -- let's do more of those!</p>\n</blockquote>\n\n<p><code>import this</code> to read it at home</p>\n\n<p>Some techniques of looping might be more appropriate in certain cases, but at least now you know what those techniques are.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:54:44.917", "Id": "416299", "Score": "1", "body": "i would have thanked you but stack exchange recomends me to not" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T17:22:42.307", "Id": "416327", "Score": "2", "body": "Stack Exchange is telling you that because the way you're supposed to thank is by upvoting and/or validating ✅ on the left side of the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T11:20:11.413", "Id": "416461", "Score": "0", "body": "i can't upvote because i just started using the site" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T15:26:56.197", "Id": "215270", "ParentId": "215252", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:07:33.477", "Id": "215252", "Score": "1", "Tags": [ "python" ], "Title": "Prints the multiplication table of 5" }
215252
<p>A Mutual Fund data vendor is updating all Mutual Fund prices partially from 6 PM to early morning at 1 AM. Starting from 6 PM, I started to download prices for every 30 minutes.</p> <ul> <li>1st download - 2 Fund houses updated their prices</li> <li>2nd download - 8 Fund houses updated their prices</li> <li>3rd download - 5 Fund houses updated their prices</li> <li>and so on …</li> </ul> <p>I download all the prices and stored them into CSV files with the filename in the format of <code>[date_time].csv</code>. </p> <p>For example, <code>['03112019_18:00:05.csv','03112019_18:30:02.csv','03112019_19:00:08.csv',....]</code></p> <p>I kept all the files in a directory. I want to check whether are the prices of the Mutual Funds changed from the early time during the subsequent updates. Simply, I want to analyse whether they are updating only new prices of Funds in their every update or If there is a modification of the price that has already been updated. </p> <p>To do this, I write the following code in python and pandas. Please review it and give me your valuable feedback. Also please tell me an alternative or better way If there is. </p> <pre><code># my routine to extract all files of csv. def listofFiles(dirPath, extension=""): if not extension: return os.listdir(dirPath) return [file for file in os.listdir(dirPath) if file.endswith("." + extension)] # setting up directory path dirpath = '/home/user/fund/{}/'.format(arguments[0]) # List out csv file names from the directory to process # my routine to extract all files of csv. list_of_files = listofFiles(dirpath, "csv") # Store date of the filename into a variable if list_of_files: date = list_of_files[0].rsplit('.')[0].rsplit('_')[0] # Extract times from the files and make list of times and sort it time_list = set() for path in list_of_files: if path: if "_" in path: time = path.rsplit('.')[0].rsplit('_')[1] time_list.add(dt.strptime(time, "%H:%M:%S")) time_list = sorted(time_list) # Get earliest file and load into pandas Data Frame time_s = dt.strftime(time_list[0], "%H:%M:%S") file = "{}_{}.csv".format(date, time_s) merged_df = pd.read_csv(dirpath + file) # Filter only needed column merged_df = start_df = merged_df[['Scheme Name', 'pri']] # here merged_df for generating resulting data frame # start_df for comparing data of new one with earliest data frame # Rename the name of the column 'pri' with 'pri_[time_of_the_file]' start_suffix = dt.strftime(time_list[1], "_%H:%M") merged_df = merged_df.rename(columns={'pri': 'pri{}'.format(start_suffix)}) # Start Iterating with next time file for time in time_list[1:]: time_s = dt.strftime(time, "%H:%M:%S") # for making filename # for making columns as per filename end_prefix = dt.strftime(time, "_%H:%M") file = "{}_{}.csv".format(date, time_s) # Set file name frame = pd.read_csv(dirpath + file) # Read csv frame = frame[['Scheme Name', 'pri']] # prepare Intersected list with previous time file inter_df = pd.merge(start_df, frame, on='Scheme Name', how='inner', suffixes=[start_suffix, end_prefix]) # Append the current time price column for resulting data frame merged_df = pd.merge(merged_df, inter_df[[ 'Scheme Name', 'pri'+end_prefix]], on='Scheme Name', how='right') start_df = frame # Make the current data frame as previous start_suffix = end_prefix # Change the previous time suffix to current # print the result print(merged_df.head()) # Check the pair of price columns from earliest to newest If there is a price change for the funds. start = dt.strftime(time_list[0], "%H:%M") for time in time_list[1:]: end = dt.strftime(time, "%H:%M") print("Comparing prices consistency between {} and {}".format(start, end)) print(merged_df.loc[merged_df['pri_'+start] != merged_df['pri_'+end]].dropna()) print("---------------------------------------------------------------------") start = end </code></pre> <p>My Input:</p> <pre class="lang-none prettyprint-override"><code>03112019 directory contains the following CSV files. 03112019_18:00:05.csv 03112019_18:30:02.csv 03112019_19:00:03.csv 03112019_19:30:05.csv 03112019_20:00:08.csv contents of 03112019_18:00:05.csv Scheme Name pri 0 Franklin India Banking &amp; PSU Debt Fund - Direc... 10.7959 1 Franklin India Banking &amp; PSU Debt Fund - Direc... 15.0045 2 Franklin India Banking &amp; PSU Debt Fund - Dividend 10.5216 3 Franklin India Banking &amp; PSU Debt Fund - Growth 14.6659 4 SBI BANKING &amp; PSU FUND - Direct Plan - Weekly... 1016.8984 ..... ..... --------------------------------------------------------------------- contents of 03112019_18:30:02.csv Scheme Name pri 0 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 152.1524 1 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 107.1248 2 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 105.7569 3 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 159.7587 4 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 235.8929 ..... ..... --------------------------------------------------------------------- contents of 03112019_19:00:03.csv Scheme Name pri 0 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 152.1524 1 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 107.1248 2 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 105.7569 3 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 159.7587 4 Aditya Birla Sun Life Banking &amp; PSU Debt Fund ... 235.8929 ..... ..... </code></pre> <p>My executable command is,</p> <pre><code>python3 checkconsistency.py 03112019 </code></pre> <p>and You have to define <code>dirpath</code>. I set this from my configuration file.</p> <p>We could also send the column names to be check the price consistency as an argument. Here I just hardcoded it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-14T13:22:13.240", "Id": "416627", "Score": "0", "body": "Could you add minimal examples of the CSV files so that we could run the program? Also, what is `arguments`? It is never defined in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T04:58:09.050", "Id": "416768", "Score": "0", "body": "I don't know how to add examples here. Could I add those examples as CSV files here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T08:46:15.877", "Id": "416785", "Score": "0", "body": "You can't add files, but you can add text like, for example, [here](https://codereview.stackexchange.com/questions/212559/pandas-updating-cells-with-new-value-plus-old-value). I think a small example of 3 files, each of them not more than 10 lines would be enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T05:29:30.877", "Id": "416980", "Score": "0", "body": "@Georgy: I edited the post as per your request. Is that enough? If not, Please help me to give the better view." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-16T09:45:35.790", "Id": "417001", "Score": "0", "body": "Better, but the contents of the CSV files are still unusable, and the relation between them is still unclear for me. What happens to the lines from the first CSV in the second CSV file? Do they disappear, or shift down? Try to provide such example so that we could just copy and paste the CSV data, and be able to run your program without guessing what missing data could look like. I tried to guess but my examples won't pass the merging part." } ]
[ { "body": "<p>This is an interesting piece of code. You have clearly tried to make it look better. Well done.</p>\n\n<hr>\n\n<ul>\n<li>I recently read in Refactoring book following about comments. Thick comments means code is bad.</li>\n</ul>\n\n<blockquote>\n <p>Comments aren’t a bad smell; indeed they are a sweet smell. The reason\n we mention comments here is that comments are often used as a\n deodorant. It’s surprising how often you look at thickly commented\n code and notice that the comments are there because the code is bad.</p>\n \n <p>-- Refactoring: Improving Design of Existing Code by Martin Fowler</p>\n</blockquote>\n\n<ul>\n<li>Do not specify what your code is doing.\n\n<ul>\n<li>Anyone who want's to read your code will know python or will know how to learn it.</li>\n<li>You are not writing a tutorial.</li>\n<li>Explain your intent.</li>\n<li>Avoid obvious comments.</li>\n</ul></li>\n<li>Specify why you decide to do it that way.</li>\n</ul>\n\n<blockquote>\n<pre><code>def listofFiles(dirPath\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Please follow PEP-8 and make method names and parameters <code>snake_case</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T04:48:56.473", "Id": "416397", "Score": "1", "body": "Thank you for your appreciation and for your valuable time review my code. Thank you for the two points you mention to what to do in my code and your other feedbacks. Your feedback is highly appreciated and will help me to improve my ability to write my code well clear." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T16:08:47.000", "Id": "215274", "ParentId": "215253", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:24:21.877", "Id": "215253", "Score": "3", "Tags": [ "python", "csv", "pandas" ], "Title": "Checking whether fund prices changed over multiple CSV files" }
215253
<p>i'm running a for loop that loops over all the rows of a pandas dataframe, then it calculates the euclidean distance from one point at a time to all the other points in the dataframe, then it pass the following point, and do the same thing, and so on.</p> <p>The thing is that i need to store the value counts of the distances to plot a histogram later, i'm storing this in another pandas dataframe. The problem is that as the second dataframe gets bigger, i will run out of memory at the some time. Not to mention that also as the dataframe size grows, repeating this same loop will get slower, since it will be heavier and harder to handle in memory.</p> <p>Here's some toy data to reproduce the original problem:</p> <pre><code>import pandas as pd xx = [] yy = [] tt = [] for i in progressbar(range(1,655556)): xx.append(i) yy.append(i) tt.append(i) df = pd.DataFrame() df['xx'] = xx df['yy'] = yy df['tt'] = tt df['xx'] = df['xx'].apply(lambda x : float(x)) df['yy'] = df['yy'].apply(lambda x : float(x)) df['tt'] = df['tt'].apply(lambda x : float(x)) df </code></pre> <p>This is the original piece of code i was using:</p> <pre><code>counts = pd.DataFrame() for index, row in df.iterrows(): dist = pd.Series(np.sqrt((row.xx - df.xx)**2 + (row.yy - df.yy)**2 + (row.tt - df.tt)**2)) counter = pd.Series(dist.value_counts( sort = True)).reset_index().rename(columns = {'index': 'values', 0:'counts'}) counts = counts.append(counter) </code></pre> <p>The original df has a shape of <code>(695556, 3)</code> so the expected result should be a dataframe of shape <code>(695556**3, 2)</code> containing all the distance values from all the 3 vectors, and their counts. The problem is that this is impossible to fit into my 16gb ram. </p> <p>So i was trying this instead:</p> <pre><code>for index, row in df.iterrows(): counts = pd.DataFrame() dist = pd.Series(np.sqrt((row.xx - df.xx)**2 + (row.yy - combination.yy)**2 + (row.tt - df.tt)**2)) counter = pd.Series(dist.value_counts( sort = True)).reset_index().rename(columns = {'index': 'values', 0:'counts'}) counts = counts.append(counter) counts.to_csv('counts/count_' + str(index) + '.csv') del counts </code></pre> <p>In this version, instead of just storing the counts dataframe into memory, i'm writting a csv for each loop. The idea is to put it all together later, once it finishes. This code works faster than the first one, since the time for each loop won't increment as the dataframe grows in size. Although, it still being slow, since it has to write a csv each time. Not to say it will be even slower when i will have to read all of those csv's into a single dataframe.</p> <p>Can anyone show me how i could optimize this code to achieve these same results but in faster and more memory efficient way?? I'm also open to other implementations, like, spark, dask, or whatever way to achieve the same result: a dataframe containing the value counts for all the distances but that could be more or less handy in terms of time and memory.</p> <p>Thank you very much in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T14:44:17.693", "Id": "416499", "Score": "1", "body": "Hi, comparatively to StackOverflow we do not accept stub code, also, please give a little more context to your data otherwise it's hard to understand what your code is supposed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T15:21:29.123", "Id": "416504", "Score": "0", "body": "Hi, thank you for the suggestions. What more do you need to know? I think it's clearly explained i9n the question. My code calculates all the distances between a point and all the rest of points in the df, and then goes to the next point and repeat the same operation. My issue is my code being extremely slow and memory consuming, and i would like to know if there's a possible way to optimize it in terms of speed and memory" } ]
[ { "body": "<ol>\n<li>better to use <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html\" rel=\"nofollow noreferrer\">dataframe.apply</a> in vector operation for enhancing\nperformance.</li>\n<li>del dataframe is not working as you think, check\n<a href=\"https://stackoverflow.com/questions/32247643/how-to-delete-multiple-pandas-python-dataframes-from-memory-to-save-ram\">this</a> </li>\n<li>saved reference first and use <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html?highlight=concat#pandas.concat\" rel=\"nofollow noreferrer\">pandas.concat</a> after\nlooping</li>\n<li>size of expected result should be (n ** 2, 2) where df.shape\n= (n, 3)</li>\n<li>Optional: Use different datatype like np.float16 or np.float32 to trade memory size with decimal accuracy</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import gc\n\ndef calc_dist(row):\n return np.sqrt((row ** 2).sum())\n\ntemp = []\nfor _, row in df.iterrows():\n new_df = df - row # recenter\n dist = new_df.apply(calc_dist, 1)\n counts = dist.value_counts(sort = True).reset_index()\n counts.columns = [\"distance\", \"count\"]\n del new_df, dist\n temp.append(counts)\n gc.collect()\nfinal = pd.concat(temp, ignore_index=True).groupby(\"distance\").sum()\nkey = 0.0\nfinal.loc[key] = final.loc[key] - n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T08:45:56.963", "Id": "416423", "Score": "0", "body": "Hi hks014. Thank you for your answer!! After trying your code suggestion i could see that it's way slower than mine. It takes 3 minutes per iteration. It's huge, my code doesn't even take a second per iteration. Are you sure this is the way to go??\n\nI'll edit the question to include some toy data to reproduce the problem" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T03:19:04.470", "Id": "215315", "ParentId": "215255", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T11:38:28.873", "Id": "215255", "Score": "-1", "Tags": [ "python", "python-3.x", "memory-management", "pandas" ], "Title": "Write/read efficiently dataframe objects into memory or disk" }
215255
<p>There's a struct named <code>Player</code> containing <code>name</code> and <code>stat</code>:</p> <pre><code>struct Player { name: String, stat: Stat, } struct Stat { points: u32, fouls: u32, } </code></pre> <p>And I have a <code>Vec&lt;Player&gt;</code>. What is interesting is that there can be multiple players with same name and different stats like the following:</p> <pre><code>let players = vec![ Player { name: String::from("player1"), stat: Stat { points: 10, fouls: 1, }, }, Player { name: String::from("player2"), stat: Stat { points: 30, fouls: 3, }, }, Player { name: String::from("player1"), stat: Stat { points: 5, fouls: 1, }, }, ]; </code></pre> <p>The first and the third elements have same name, but with different stat values. What I want to do is merging those elements into one by adding all stat values. After the merging process, the output vector will have 2 elements like the following:</p> <pre><code>[ Player { name: String::from("player2"), stat: Stat { points: 30, fouls: 3, }, }, Player { name: String::from("player1"), stat: Stat { points: 15, fouls: 2, }, }, ] </code></pre> <p>(The order of output vector is not important in this case.)</p> <p>And the code below is my solution:</p> <pre><code>let dup_merged: Vec&lt;_&gt; = players .into_iter() .fold( HashMap::new(), |mut acc: HashMap&lt;String, Player&gt;, curr: Player| { match acc.get(&amp;curr.name) { Some(prev) =&gt; { // Is it better to modify prev.stat // instead of inserting new Player instance? // HashMap&lt;String, &amp;Player&gt; required to modification? acc.insert( curr.name.clone(), Player { name: curr.name, stat: Stat { points: prev.stat.points + curr.stat.points, fouls: prev.stat.fouls + curr.stat.fouls, }, }, ); } None =&gt; { acc.insert(curr.name.clone(), curr); } } acc }, ) .into_iter() // Hope there's better way to get a vector of a hash map .map(|(_, v)| v) .collect(); </code></pre> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=6ac3cf0789f67ca95a3ae24656d593e6" rel="nofollow noreferrer">Playground link</a></p> <p>I used <code>HashMap</code> (key: <code>player.name: String</code>, value: <code>player: Player</code>) to accumulate stat values for players with same name, then converted the HashMap to <code>Vec&lt;Player&gt;</code> again. I think my solution can be simpler, more idiomatic and refined better.</p>
[]
[ { "body": "<p>Looks pretty good already! Here's some ideas for improvement.</p>\n\n<p>You can make implement Add and AddAssign for Stat so that you can use <code>+</code> and <code>+=</code> on those. Here's an AddAssign implementation:</p>\n\n<pre><code>impl std::ops::AddAssign for Stat {\n fn add_assign(&amp;mut self, other: Self) {\n self.points += other.points;\n self.fouls += other.fouls;\n }\n}\n</code></pre>\n\n<p>I like that you reached for a HashMap and fold, those are definitely how I'd do this. However, you only need to store the name and stat (<code>HashMap&lt;String, Stat&gt;</code>), which will make it so you don't have to clone the name each time and also reduce size. You can simply reconstruct the players at the end, before the collection.</p>\n\n<p>Another thing is that you currently perform two lookups in the hashmap for every insertion. The Entry API is a great tool to learn for interacting with maps. It lets you interact with a possibly missing element of the map and only perform one lookup.</p>\n\n<p>Here's a implementation with what I've mentioned so far.</p>\n\n<pre><code>use std::collections::hash_map::Entry;\n\nlet dup_merged: Vec&lt;_&gt; = players\n .into_iter()\n .fold(\n HashMap::new(),\n |mut acc: HashMap&lt;String, Stat&gt;, curr: Player| {\n match acc.entry(curr.name) {\n Entry::Occupied(mut occ) =&gt; {\n // This player already exists, increase its stats\n *occ.get_mut() += curr.stat;\n }\n Entry::Vacant(vac) =&gt; {\n // No such player exists, insert these stats\n vac.insert(curr.stat);\n }\n }\n acc\n },\n )\n .into_iter()\n .map(|(k, v)| Player { name: k, stat: v })\n .collect();\n</code></pre>\n\n<p>There's another simplification that can be made, due to Stat being a small, cheap struct with sensible default values: You can have Stat implement Default, and then instead of inserting an entry if its missing, you can just have it default to a zero'd Stat and always add:</p>\n\n<pre><code>#[derive(Default, Debug)]\nstruct Stat {\n points: u32,\n fouls: u32,\n}\n// ...\nlet dup_merged: Vec&lt;_&gt; = players\n .into_iter()\n .fold(\n HashMap::new(),\n |mut acc: HashMap&lt;String, Stat&gt;, curr: Player| {\n *acc.entry(curr.name).or_default() += curr.stat;\n acc\n },\n )\n .into_iter()\n .map(|(k, v)| Player { name: k, stat: v })\n .collect();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T20:36:07.067", "Id": "215296", "ParentId": "215259", "Score": "2" } } ]
{ "AcceptedAnswerId": "215296", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-12T13:07:22.667", "Id": "215259", "Score": "1", "Tags": [ "functional-programming", "rust", "iterator" ], "Title": "Merging (not removing) duplicated elements in a vector" }
215259