body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>So I've just finished my first Python module (and published on Github), with this little project I'd like to learn how to distribute my code so that other users can use it as a plug in for their own projects.</p>
<p>Specifically I'm looking for feedback in the following direction:</p>
<ul>
<li>Is the interface to the module designed correctly?</li>
<li>At the beginning of the code I check for completeness of the input, is this the best way to handle errors? (It looks chunky)</li>
<li>Is the repository set up correctly so that it is plug-and-play?</li>
<li>In general, is this the best way to design a module or should I work with classes instead of funtions?</li>
</ul>
<p>Any other feedback is also welcome :)</p>
<p>Thanks in advance!</p>
<hr>
<p>Link to Github repository: <a href="https://github.com/nick-van-h/cutlistcalculator" rel="noreferrer">https://github.com/nick-van-h/cutlistcalculator</a></p>
<p>__main__.py:</p>
<pre class="lang-py prettyprint-override"><code>from cutlist import getCutLists
import sys
import argparse
if __name__ == '__main__':
#Argument parser
text = "This program calculates the most optimal cutlist for beams and planks."
parser = argparse.ArgumentParser(description=text)
parser.add_argument("-i", "--input", help="custom location of input json file (e.g. 'localhost:8080/foo/bar.json'", default="")
parser.add_argument("-o", "--output", help="custom location of output folder (e.g. 'localhost:8080/foo' -> 'localhost:8080/foo/cutlist_result.json'", default="")
args = parser.parse_args()
#Kick-off
result = getCutLists(args.input, args.output)
#Exit function with VS Code workaround
try:
sys.exit(result)
except:
print(result)
</code></pre>
<p>cutlist.py:</p>
<pre><code>import json
from operator import itemgetter
import copy
from pathlib import Path
import os
def getSolution(reqs, combs):
needs = copy.deepcopy(reqs)
res = []
res.append([])
for comb in combs:
#As long as all items from comb[x] fulfill need
combNeed = True
while combNeed:
#Check if comb[x] provides more than need (fail fast)
for need in needs:
if comb[need['Length']] > need['Qty']:
combNeed = False
if not combNeed:
break
for need in needs:
need['Qty'] -= comb[need['Length']]
#Append result
res[0].append(comb.copy())
#Calculate total price
for sol in res:
price = round(sum(x['Price'] for x in sol),2)
res.append([price])
#Return result
return res
def getCutLists(inputstr = "", outputstr = ""):
if inputstr:
jsonlocation = inputstr
else:
jsonlocation = './input/input.json' #default input location
print(jsonlocation)
errstr = ""
#Get input
try:
with open(jsonlocation) as f:
data = json.load(f)
except:
errstr += "JSON file not found. "
return(f"Err: {errstr}")
#Get variables from JSON object
try:
reqs = data['Required Lengths']
except:
errstr += "'Required Lengths' not found. "
try:
avail = data['Available base material']
except:
errstr += "'Available base material' not found. "
try:
cutwidth = data['Cut loss']
except:
errstr += "'Cut loss' not found. "
if errstr:
return(f"Err: {errstr}")
#Test for required keys in array
try:
test = [x['Length'] for x in reqs]
if min(test) <= 0:
errstr += f"Err: Required length ({min(test)}) must be bigger than 0."
except:
errstr += "'Length' not found in required lengths. "
try:
test = [x['Qty'] for x in reqs]
if min(test) <= 0:
errstr += f"Err: Required quantity ({min(test)}) must be bigger than 0."
except:
errstr += "'Qty' not found in required lengths. "
try:
test = [x['Length'] for x in avail]
if min(test) <= 0:
errstr += f"Err: Available length ({min(test)}) must be bigger than 0."
except:
errstr += "'Length' not found in available base material. "
try:
test = [x['Price'] for x in avail]
if min(test) < 0:
errstr += f"Err: Available price ({min(test)}) can't be negative."
except:
errstr += "'Price' not found in available base material. "
if errstr:
return(f"Err: {errstr}")
#Init other vars
listreq = [x['Length'] for x in reqs]
listavail = [x['Length'] for x in avail]
minreq = min(listreq)
res=[]
#Error handling on passed inputs
if max(listreq) > max(listavail):
return(f"Err: Unable to process, required length of {max(listreq)} is bigger than longest available base material with length of {max(listavail)}.")
if cutwidth < 0:
return(f"Err: Cut width can't be negative")
#Make list of all available cut combinations
combs = []
for plank in avail:
myplank = plank.copy()
for cut in reqs:
myplank[cut['Length']] = 0
#Increase first required plank length
myplank[reqs[0]['Length']] += 1
#Set other variables
myplank['Unitprice'] = myplank['Price'] / myplank['Length']
filling = True
while filling:
#Calculate rest length
myplank['Rest'] = myplank['Length']
for i in reqs:
length = i['Length']
myplank['Rest'] -= ((myplank[length] * length) + (myplank[length] * cutwidth))
myplank['Rest'] += cutwidth
#Set rest of variables
myplank['Baseprice'] = (myplank['Price']) / ((myplank['Length'] - myplank['Rest']))
myplank['Optimal'] = (myplank['Rest'] <= minreq)
#Check if rest length is positive
if myplank['Rest'] >= 0:
combs.append(myplank.copy())
myplank[reqs[0]['Length']] += 1
else:
for i in range(len(reqs)):
if myplank[reqs[i]['Length']] > 0:
myplank[reqs[i]['Length']] = 0
if i < len(reqs)-1:
myplank[reqs[i+1]['Length']] += 1
break
else:
filling = False
#Sort combinations descending by remaining length, get solution
combs = sorted(combs, key=lambda k: k['Rest'])
res.append(getSolution(reqs, combs))
#Sort combinations by getting biggest lengths first (largest to smallest), optimal pieces first, get solution
listreq = sorted(listreq, reverse=True)
listreq.insert(0,'Optimal')
for x in reversed(listreq):
combs.sort(key=itemgetter(x), reverse=True)
res.append(getSolution(reqs, combs))
#Sort combination by least effective price per unit, get solution
combs = sorted(combs, key=lambda k: k['Baseprice'])
res.append(getSolution(reqs, combs))
#Get cheapest option & make readable format
cheapest = min([x[1] for x in res])
for x in res:
if x[1] == cheapest:
sol = {}
sol['Required base material'] = {}
sol['Cut list'] = []
i = 1
for plank in x[0]:
if plank['Length'] not in sol['Required base material']:
sol['Required base material'][plank['Length']] = 0
sol['Required base material'][plank['Length']] += 1
str = f"Plank {i}: Length {plank['Length']}, "
for req in reqs:
if plank[req['Length']] > 0: str += f"{plank[req['Length']]}x {req['Length']}, "
str += f"rest: {plank['Rest']}"
sol['Cut list'].append(str)
i += 1
sol['Total price'] = cheapest
break
#Get output location
if outputstr:
outputfile = outputstr
if outputfile[len(outputfile)-1] != "//":
outputfile += "//"
outputfile += "cutlist_result.json"
else:
outputfile = "./output/cutlist_result.json"
#Make directories
Path(os.path.dirname(outputfile)).mkdir(parents=True, exist_ok=True)
#Output to file
f = open(outputfile, "w")
json.dump(sol, f, indent=4)
f.close
return("Success")
</code></pre>
|
[] |
[
{
"body": "<h2>Locations</h2>\n\n<p>The location documentation is confusing. In <code>getCutLists</code>, the input defaults to</p>\n\n<pre><code>'./input/input.json'\n</code></pre>\n\n<p>but in your <code>main</code>, the example in the documentation is</p>\n\n<pre><code>'localhost:8080/foo/bar.json'\n</code></pre>\n\n<p>Is this a file path or a URL? Based on your usage it looks like it must be a file path, and the host and port shown above should not be there. Also, <code>'./input/input.json'</code> should just be made the default value of <code>inputstr</code>, not <code>\"\"</code>.</p>\n\n<h2>Function names</h2>\n\n<p>In Python, the standard for function and variable names is lower_snake_case, i.e. <code>get_cut_lists</code>, <code>get_solution</code>, etc.</p>\n\n<h2>Function complexity</h2>\n\n<p><code>getCutLists</code> should be broken into at least three different functions for maintainability, testability and legibility.</p>\n\n<h2>Exception handling</h2>\n\n<p>Do not degrade exceptions to strings like this:</p>\n\n<pre><code>try:\n ...\nexcept:\n errstr += \"JSON file not found. \"\n return(f\"Err: {errstr}\")\n</code></pre>\n\n<p>There is a handful of problems with this pattern. First, <code>except:</code> interferes with the user's ability to Ctrl+C break out of the program. Also, <code>except:</code> is too broad in general, and you should only catch what you expect the code to throw, in this case <code>FileNotFoundError</code>. Also, if you wanted your error string to be useful, you would include the name of the file. Finally, all of that machinery should go away and you should simply <code>open()</code> and let the exception fall through to the caller without an <code>except</code>. If the caller wants to re-format the way that exceptions are printed on the upper level, it can; but that should not be the responsibility of this function. A pattern to avoid in languages with good exception handling is to degrade that exception handling into scalar return values (string, bool, int error codes, etc.)</p>\n\n<p>As for validation like this:</p>\n\n<pre><code>try:\n test = [x['Length'] for x in reqs]\n if min(test) <= 0:\n errstr += f\"Err: Required length ({min(test)}) must be bigger than 0.\"\nexcept:\n errstr += \"'Length' not found in required lengths. \"\n</code></pre>\n\n<p>Raise your own exception instead:</p>\n\n<pre><code>min_len = min(x['Length'] for x in reqs)\nif min_len <= 0:\n raise ValueError(f'Required length ({min_len}) must be greater than 0.')\n</code></pre>\n\n<p>Also don't make a temporary list; apply <code>min</code> directly to the generator.</p>\n\n<h2>Comments</h2>\n\n<p>Whereas</p>\n\n<pre><code>#Make list of all available cut combinations\n</code></pre>\n\n<p>is a useful comment,</p>\n\n<pre><code>#Set other variables\n</code></pre>\n\n<p>is not. It's worse than having no comment at all. If there's something complex or surprising going on, or something to do with business logic, document it; otherwise avoid </p>\n\n<pre><code># do the thing\ndo_thing()\n</code></pre>\n\n<h2>Expression simplification</h2>\n\n<pre><code>((myplank[length] * length) + (myplank[length] * cutwidth))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>myplank[length]*(length + cut_width)\n</code></pre>\n\n<h2>Weakly-typed structures</h2>\n\n<p>You're loading from JSON; fine: but then you never unpack the dictionary representation of your data to objects; you leave it in dictionaries. This leads to code like</p>\n\n<pre><code> myplank['Baseprice'] = (myplank['Price']) / ((myplank['Length'] - myplank['Rest']))\n</code></pre>\n\n<p>which is a mess. Instead, make actual classes to represent your data, and unpack to those.</p>\n\n<p>In other words, we aren't in Javascript: not everything is a dictionary.</p>\n\n<h2>Mixed os/path</h2>\n\n<pre><code>Path(os.path.dirname(outputfile)).mkdir(parents=True, exist_ok=True)\n</code></pre>\n\n<p>uses mixed <code>Path</code> (good) and <code>os</code> calls (not so good). You do not need <code>dirname</code> here; instead make <code>outputfile</code> a path directly and then manipulate that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:47:50.567",
"Id": "476837",
"Score": "0",
"body": "This is so much more than I've hoped for, thanks a lot! Especially the part about raising my own error codes hasn't occurred to me. Regarding loading from JSON; do you suggest a more rigid method then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:55:58.693",
"Id": "476840",
"Score": "0",
"body": "JSON itself is fine for storage, but when you deserialize it, it's better if you do it to actual classes. There are easy and hard ways to do this - an easy way is to call `cls(**dict)` on a class that is marked `@dataclass`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:53:30.707",
"Id": "242947",
"ParentId": "242933",
"Score": "7"
}
},
{
"body": "<h1>source directory</h1>\n\n<p>Put the module in a separate source directory. This has the advantage that you can install this directory separately with <code>pip install -e</code> for example, or by adding it to a <code>.pth</code> in your virtual environments site-packages. You are using virtual environments for the development?</p>\n\n<h1>tools</h1>\n\n<p>Use a good IDE, and the tools available to improve your code. I use <code>black</code> as code formatter, <code>mypy</code> with a strict configuration to check for typing errors, <code>pydocstyle</code> to check my docstrings, <code>pytest</code> for unit tests, <code>pyflakes</code> for other errors. Get to know them, look for configuration inspiration to larger python projects, and integrate them in your workflow. Most IDEs make this really simple.</p>\n\n<h1>variable names</h1>\n\n<p>In python, the length of the variable names has no influence on the performance of the program. then pick clear variable names like <code>requested_planks</code> instead or <code>reqs</code>. Decyphering your code is really difficult, due to these unclear names.</p>\n\n<h1>split in functions</h1>\n\n<p>You have 2 functions already, but this code needs a lot more.</p>\n\n<ul>\n<li>reads the input</li>\n<li>validates the input</li>\n<li>makes combinations</li>\n<li>picks a combination</li>\n<li>outputs to an output file</li>\n</ul>\n\n<p>Each of these deserves its own function. Doing so allows you to better document this, test the different parts and make changes in the future.</p>\n\n<p>I try to separate my functions so the data transferred is clear.</p>\n\n<h1>read the inputs</h1>\n\n<p>Hoist your IO (talks: <a href=\"https://rhodesmill.org/brandon/talks/#clean-architecture-python\" rel=\"nofollow noreferrer\">1</a> <a href=\"https://rhodesmill.org/brandon/talks/#hoist\" rel=\"nofollow noreferrer\">2</a>)\nDon't pass along the input file. read the input file in your <code>main()</code>, function and pass the contents on to the validator and later calculations. Same goes for the output. The calculation returns the required planks, and then the <code>main()</code> function writes the result to disk if needed.</p>\n\n<h1>validate the input</h1>\n\n<p>Your input validation is spread around the main method. You also communicate with strings. An alternative is to communicate a validation failure with a <code>ValueError</code></p>\n\n<p>If you add in type hints and docstring you could end up with something like this:</p>\n\n<pre><code>import typing\n\n\nclass Plank(typing.NamedTuple):\n \"\"\"Requested plank.\"\"\"\n\n Length: float\n Qty: int\n\n\nclass BasePlank(typing.NamedTuple):\n \"\"\"Available base plank.\"\"\"\n\n Length: float\n Price: float # or Decimal?\n\n\nInputData = typing.TypedDict(\n InputData,\n {\n \"Cut loss\": float,\n \"Required Lengths\": typing.List[Plank],\n \"Available base material\": typing.List[BasePlank],\n },\n)\n\n\ndef validate_planks(planks: typing.Iterable[Plank]) -> None:\n \"\"\"Validate the requested planks.\n\n - Length must be larger than 0\n - Quantity must be larger than 0\n \"\"\"\n for plank in planks:\n if \"Length\" not in plank:\n raise ValueError(f\"`Length` not found in {plank}\")\n if \"Qty\" not in plank:\n raise ValueError(f\"`Qty` not found in {plank}\")\n if plank[\"Length\"] < 0:\n raise ValueError(f\"`Length` < 0 in {plank}\")\n if plank[\"Qty\"] < 0:\n raise ValueError(f\"`Qty` < 0 in {plank}\")\n\n\ndef validate_baseplanks(planks: typing.Iterable[BasePlank],) -> None:\n \"\"\"Validate the available base planks.\n\n - Length must be larger than 0\n - price must not be negative\n \"\"\"\n for plank in planks:\n if \"Length\" not in plank:\n raise ValueError(f\"`Length` not found in {plank}\")\n if \"Qty\" not in plank:\n raise ValueError(f\"`Qty` not found in {plank}\")\n if plank[\"Length\"] < 0:\n raise ValueError(f\"`Length` < 0 in {plank}\")\n if plank[\"Price\"] <= 0:\n raise ValueError(f\"negative `Price` in {plank}\")\n\n\ndef validate_input(input_data: InputData) -> None:\n \"\"\"Validate the input.\"\"\"\n\n if \"Cut loss\" not in input_data:\n raise ValueError(\"`Cut loss` not found.\")\n if \"Available base material\" not in input_data:\n raise ValueError(\"`Available base material` not found.\")\n baseplanks = input_data[\"Available base material\"]\n validate_baseplanks(baseplanks)\n\n if \"Required Lengths\" not in input_data:\n raise ValueError(\"`Required Lengths` not found.\")\n planks = input_data[\"Required Lengths\"]\n validate_planks(planks)\n\n if max(plank[\"Length\"] for plank in planks) > max(\n plank[Length] for plank in baseplanks\n ):\n raise ValueError(\n \"Maximum requested piece is longer than longest base plank\"\n )\n</code></pre>\n\n<h2><code>jsonschema</code></h2>\n\n<p>Or you can use <code>jsonschema</code> to do the validation for you:</p>\n\n<pre><code>schema = jsonschema.Draft7Validator(\n {\n \"type\": \"object\",\n \"properties\": {\n \"Cut loss\": {\"type\": \"number\", \"minimum\": 0},\n \"Required Lengths\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"Length\": {\"type\": \"number\", \"exclusiveMinimum\": 0},\n \"Qty\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0,\n \"multipleOf\": 1,\n },\n },\n \"required\": [\"Length\", \"Qty\"],\n },\n },\n \"Available base material\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"Length\": {\"type\": \"number\", \"exclusiveMinimum\": 0},\n \"Price\": {\"type\": \"number\", \"minimum\": 0},\n },\n \"required\": [\"Length\", \"Price\"],\n },\n \"minProperties\": 1,\n },\n \"required\": [\n \"Cut loss\",\n \"Available base material\",\n \"Required Lengths\",\n ],\n },\n }\n)\n</code></pre>\n\n<p>and then use </p>\n\n<pre><code>errors = list(schema.iter_errors(data))\n</code></pre>\n\n<p>Having validated your input data, you can choose to put them in classes, but for this solution that might be a bit too much.</p>\n\n<h1>testing</h1>\n\n<p>This way you can test your validation separately.</p>\n\n<p>In a separate directory <code>tests</code>, file <code>test_cutlist.py</code> or in a separate file per function you want to test</p>\n\n<pre><code>import pytest\n\ndef test_validatbaseplanks():\n correct_data = [\n {\n \"Length\": 300,\n \"Price\": 5.95\n },\n {\n \"Length\": 180,\n \"Price\": 2.95\n },\n {\n \"Length\": 360,\n \"Price\": 6.95\n }\n ]\n cutlistcalculator.validate_baseplanks(correct_data)\n\n missing_price = [\n {\n \"Length\": 300,\n },\n {\n \"Length\": 180,\n \"Price\": 2.95\n },\n {\n \"Length\": 360,\n \"Price\": 6.95\n }\n ]\n with pytest.raises(ValueError) as excinfo:\n cutlistcalculator.validate_baseplanks(correct_data)\n assert \"`Price` not found\" in str(excinfo.value)\n</code></pre>\n\n<p>etcetera.</p>\n\n<h1>JSON</h1>\n\n<p>Think about what format you want to serialize the input and output. You use <code>JSON</code>, but as you noticed, this has a few downsides. It is very verbose, and you can'y add comments. JSON is meant to be easily read by a computer. Alternatives are <code>BSON</code>, <code>TOML</code>, ...</p>\n\n<p>I'm not saying these are better, but at least take a look at it. Especially when you are so early in the development, it is easy to switch.</p>\n\n<p>On the other hand, if you partition your code correctly, and make the parsing of the input its own function, you can later easily change the input or aoutput format. You could even foresee multiple parsers, and accept different formats.</p>\n\n<h1>calculation</h1>\n\n<p>I don't get the algorithm you use. I don't have too much time to figure it out, but the way you use unclear names and have it all in 1 large blob doesn't help. Try to partition it in logical structures that you refactor to separate functions. Carefully name the functions, and foresee a docstring and type hnts. Once you have that, post them again as a new question.</p>\n\n<p>Make a function that generates possible cut plans, with only the required planks and available baseplanks as input. Make this a generator, that yields a possible combination. You can the pipe this into a function that calculates the cost of this arrangement. This takes one single combination and the prices of the baseplanks as arguments, and returns the cost of the combination. By splitting the work like this, you can document their behaviour , and can test each of these components separately.</p>\n\n<h1>output</h1>\n\n<p>Separate this from the code that calculates the best solution</p>\n\n<p>use a <code>with</code> statement to construct a context.</p>\n\n<pre><code>with output_file.open(\"w\") as filehandle:\n json.dump(filehandle, result, indent=2)\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>I know this is a lot, but try to incorporate these tips, and the ones from Reinderien, and then if you're unsure come back with a new version. Keep up the good work</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T19:38:48.577",
"Id": "242964",
"ParentId": "242933",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242947",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T08:36:59.037",
"Id": "242933",
"Score": "6",
"Tags": [
"python",
"git"
],
"Title": "Plank cut-list calculator"
}
|
242933
|
<p>I am writing a program to <strong>combine the basic form of a word with suffix arrays following the choices from a form group (Angular 9)</strong> to receive the declination.</p>
<p>This is the flow:</p>
<ol>
<li>The user inputs a word.</li>
<li>The user chooses the predefined grammar categories of the word (genus, class, animacy and others).</li>
<li>According to the choices of the user the input is mapped with an array of the corresponding suffixes.</li>
</ol>
<p>Now, my problem is that I can not wrap my head around the problem to find a more dynamic solution than writing an if-statement for every possible combination of choices and the corresponding array of suffixes.</p>
<p>Right now I compare the values array from the user choices with every predefined combination array.
You will see in a second that this solution leads to a lot of repetitive code and I ask you to help me to find a better solution.</p>
<p><strong>Two (of many possible) predefined conditions of choices plus the fitting suffix arrays</strong> </p>
<pre><code>conditionOne = ['inanimate', 'm', '2', 'hard'];
conditionOneSuffixes = ['', 'а', 'у', 'а', 'ом', 'е', 'ы', 'ов', 'ам', 'ов', 'ами', 'ах'];
conditionTwo = ['animate', 'm', '2', 'hard'];
conditionTwoSuffixes = ['', 'а', 'у', 'а', 'ом', 'е', 'ы', 'ов', 'ам', 'ов', 'ами', 'ах'];
</code></pre>
<p><strong>My first function to save the choices as values from angular reactive forms</strong></p>
<pre><code>setValues($event: string) {
this.values = [];
this.values = Object.values(this.substantiveFormGroup.value); // the user choices from the form group saved to an array
this.setDeclination(this.values);
}
</code></pre>
<p><strong>My second function to map the fitting suffix array on the input (only two possible if statements)</strong></p>
<pre><code>setDeclination(values) {
if (
this.conditionOne.every(i => values // the predefinded array of choices
.includes(i))) {
this.declination = this.conditionOneSuffixes.map( // the corresponding suffix array
suffixes => this.substantiveFormGroup.get("input").value + suffixes
);
}
else if (
this.conditionTwo.every(i => values // another predefinded array of choices
.includes(i))) {
this.declination = this.conditionTwoSuffixes.map( // the corresponding suffix array
suffixes => this.substantiveFormGroup.get("input").value + suffixes
);
}
// else if (another condition) { and so on...}
else this.declination = [];
}
</code></pre>
<p><strong>What would be a better, less repetitive solution?</strong></p>
<p>Thank you for your time.</p>
|
[] |
[
{
"body": "<p><code>this.values = []</code> will never be used. It is unnecessary.</p>\n\n<pre><code>setValues($event: string) {\n //this.values = []; //unnecessary\n this.values = Object.values(this.substantiveFormGroup.value); // the user choices from the form group saved to an array \n this.setDeclination(this.values);\n }\n</code></pre>\n\n<p>The code's logic will always set a value for <code>this.declination</code>, so it makes sense to just assign it at the top, so you know that <code>this.declination</code> will always be overwritten and by default should be initialized to an empty array. It also allows the code to be shorter.<br>\nIf there will be more than two conditions, you should probably have them in a list anyways. This way of organizing still benefits, and the use of an array list and destructuring with <code>for of</code> loop expresses the code's use of conditions to check for and suffixes to use in an organized list in one place, as well as shortening the code significantly and making it more concise.<br>\nThe result is that it can be more simply read as an iteration on a list of conditions to process.<br>\nBrevity and DRY naturally occurs when it is distilled this way.</p>\n\n<pre><code>setDeclination(values) {\n this.declination = [];\n for (const [condition, suffixes] of [\n [this.conditionOne, this.conditionOneSuffixes],\n [this.conditionTwo, this.conditionTwoSuffixes]\n ])\n if(condition.every(i => values.includes(i))) {\n const inputValue = this.substantiveFormGroup.get(\"input\").value;\n this.declination = suffixes.map(suffix => inputValue + suffix));\n break;\n }\n }\n</code></pre>\n\n<p>I have made some modifications to the formatting and the declaration of variables to control line length and make the code more concise, and it should be mostly self-explanatory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:00:40.767",
"Id": "476802",
"Score": "0",
"body": "That looks fine. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:21:43.793",
"Id": "476803",
"Score": "0",
"body": "Welcome to Code Review. At the moment you provided an alternate solution with no explanation or justification that may be deleted, to avoid this situation check for further details [how-to -answer](https://codereview.stackexchange.com/help/how-to-answer)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T11:52:05.880",
"Id": "242941",
"ParentId": "242940",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T11:42:33.567",
"Id": "242940",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"angular-2+"
],
"Title": "Javascript: Mapping combinations of input and possible suffix arrays leads to repetitive if statements"
}
|
242940
|
<p>I implemented the following react hook to get live updates of an element's position and dimensions in the DOM: </p>
<pre><code>/**
* @author devskope
*/
import { useCallback, useRef, useState } from 'react';
import { throttle } from '../limiters';
const useElementDimensions = () => {
const [dimensions, setDimensions] = useState({});
const ref = useRef();
const doUpdate = ({ current: node }) => {
if (node) {
const rect = node.getBoundingClientRect();
const offsetY = Math.round(rect.top + window.scrollY); // add absolute position to top of viewport
setDimensions({ offsetY, ...rect });
}
};
const updateDimensions = useCallback((ref, opts = {}) => {
const { delay = 400 } = opts;
return throttle(() => doUpdate(ref), delay); // regulate update rate
}, []);
return { dimensions, ref, updateDimensions };
};
</code></pre>
<p>The hook can be used in a component to obtain the position to the top of an element as follows:</p>
<pre><code>import useElementDimensions from '../../lib/hooks/useElementDimensions';
const TopCategories = (props) => {
const { id,} = props;
const { dimensions, ref, updateDimensions } = useElementDimensions();
const offset = dimensions?.offsetY;
/**
* Update dimensions on page scroll, can be hooked to any event or manually triggered
*
* How to I trigger this when images load to offset elements or when new elements enter the dom??????
*/
useEffect(() => {
window.addEventListener('scroll', updateDimensions(ref, { delay: 700 }));
}, []);
useEffect(() => {
console.log(offset);
}, [offset]);
return (
<div id={id} ref={ref}>
target element is ${offset} px from the top
</div>
);
};
</code></pre>
<p>How can this implementation be made more efficient/performant?</p>
<p>Thanks.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:23:06.197",
"Id": "242943",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "React: Live DOM element position/dimension resolver hook optimization"
}
|
242943
|
<p>I am learning javascript and have developed a car game using:</p>
<ul>
<li>HTML Canvas</li>
<li>javascript</li>
</ul>
<p>The repository link is: <a href="https://github.com/lazycoder-007/car_race_html_javascript_game" rel="nofollow noreferrer">https://github.com/lazycoder-007/car_race_html_javascript_game</a></p>
<p>The code is given below:</p>
<p>This is the GameArea object, with functions related to load, start and stop the game.</p>
<pre><code>var myGameArea = {
canvas : document.getElementById("myCanvas"),
load : function(){
this.canvas.width = canvasW;
this.canvas.height = canvasH;
this.context = this.canvas.getContext("2d");
this.loadInterval = setInterval(loadGameArea, 20);
this.frameNo = 0;
window.addEventListener("keydown", function(e){
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = true;
});
window.addEventListener("keyup", function(e){
myGameArea.keys[e.keyCode] = false;
});
},
start : function(){
clearInterval(this.loadInterval);
this.interval = setInterval(updateGameArea, 20);
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
myMusic.stop();
}
}
</code></pre>
<p>This is the <code>updateGameArea</code> function, which is invoked in a certain interval defined above.</p>
<pre><code>function updateGameArea()
{
for (i = 0; i < myObstacles.length; i += 1) {
if (redGamePiece.crashWith(myObstacles[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
backgroundRoad.update();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || diveiderInterval(numberOfDividersPerFrame)) {
roadDivider.push(new component(20, 80, "white", canvasW/2, 0));
}
for (i = 0; i < roadDivider.length; i += 1) {
roadDivider[i].y += myObstacleSpeed;
roadDivider[i].update();
}
if (myGameArea.frameNo == 1 || obstacleInterval(numberOfObstaclesPerFrame)) {
myObstacleX = Math.floor(Math.random() * canvasW);
myObstacleY = 0;
myObstacles.push(new component(myObstacleW, myObstacleH, "redCarImage.png", myObstacleX, myObstacleY, "image"));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].y += myObstacleSpeed;
myObstacles[i].update();
}
redGamePiece.speedX = 0;
redGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37] && redGamePiece.x > cornerGap)
{
redGamePiece.speedX = -redGamePieceSpeedLeft;
}
if (myGameArea.keys && myGameArea.keys[39] && redGamePiece.x < myGameArea.canvas.width - myObstacleW - cornerGap)
{
redGamePiece.speedX = redGamePieceSpeedRight;
}
if (myGameArea.keys && myGameArea.keys[38] && redGamePiece.y > cornerGap)
{
redGamePiece.speedY = -redGamePieceSpeedUp;
}
if (myGameArea.keys && myGameArea.keys[40] && redGamePiece.y < myGameArea.canvas.height - myObstacleH - cornerGap)
{
redGamePiece.speedY = redGamePieceSpeedDown ;
}
myScore.text = "SCORE: " + myGameArea.frameNo;
myScore.update();
redGamePiece.newPos();
redGamePiece.update();
}
</code></pre>
<p>Finally, the functions to start the game:</p>
<pre><code>function startTheGame()
{
myMusic = new Sound("gameTheme.mp3", "true");
redGamePieceX = canvasW/2;
redGamePieceY = canvasH - redGamePieceX - cornerGap;
//redGamePiece = new component(redGamePieceW, redGamePieceH, redGamePieceColor, redGamePieceX, redGamePieceY);
redGamePiece = new component(redGamePieceW, redGamePieceH, "yellowCarImage.png", redGamePieceX, redGamePieceY, "image");
backgroundRoad = new component(canvasW, canvasH, "roadImage.png", 0, 0, "image");
myScore = new component("20px", "Consolas", "red", 10, 40, "text");
myGameArea.stop();
if(start)
{
myGameArea.start();
}
else
{
myGameArea.load();
}
//myMusic.play();
}
</code></pre>
<p>It is all working fine in this way. Please help improve this.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:52:59.853",
"Id": "476806",
"Score": "0",
"body": "Mandatory reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes It should be well-suited to you being from a Java background. Be also aware that there are people who do not think class syntax is necessary, and claim that it is backwards, only meant for people who don't really know how to use JavaScript"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:02:31.120",
"Id": "476807",
"Score": "1",
"body": "Thanks @user120242 for the reference. _Be also aware that there are people who do not think class syntax is necessary, and claim that it is backwards, only meant for people who don't really know how to use JavaScript_ : isn't Angular and other frameworks of js, Object Oriented in nature. Just curious to know??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:19:49.450",
"Id": "476809",
"Score": "0",
"body": "It's in reference to classes. Additional mandatory reading: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:29:22.750",
"Id": "476821",
"Score": "2",
"body": "Welcome to code review, where we review working code and provide suggestions on how to improve the code. While asking for reviews of working code is on topic, asking how to change the code to object oriented design is off-topic. If you remove that part of the question the question becomes on-topic. In addition to the -3 you see, there is one vote to close the question as off topic (neither the down votes or the vote to close is mine). [Our guidelines](https://codereview.stackexchange.com/help/asking)."
}
] |
[
{
"body": "<h1>Initial thoughts</h1>\n\n<p>The code is not bad - has most consistent indentation using tabs. The game plays fine in Chrome on my macbook pro. I know <a href=\"https://codereview.stackexchange.com/revisions/242944/1\">you initially asked how to convert it to \"object Oriented Design\"</a>. The current code is somewhat object-oriented already using JavaScripts objects. </p>\n\n<h1>Suggestions</h1>\n\n<h2>Game play</h2>\n\n<p>The score does not appear to be reset after subsequent starts. This is typically a feature in many games.</p>\n\n<p>For mobile users an option to detect motion might be considered for controlling the direction of the car - e.g. with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent\" rel=\"nofollow noreferrer\">DeviceMotionEvent API</a>.</p>\n\n<h2>Code</h2>\n\n<h3>Variable scope</h3>\n\n<p>Limit the scope of variables to blocks and functions by using <code>const</code> as a default when declaring variables and functions. If re-assignment is needed then use <code>let</code> (e.g. in a loop). This can help avoid potential bugs where variables get over-written accidentally.</p>\n\n<p>In a larger application you would want to limit the scope of all the variables declared at the top - e.g. <code>redGamePiece</code>, <code>backgroundRoad</code>, etc. An <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">IIFE</a> or <a href=\"https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch09s03.html\" rel=\"nofollow noreferrer\">revealing module</a> can assist with doing this.</p>\n\n<h3>Braces</h3>\n\n<p>Some braces are placed on a new line:</p>\n\n<blockquote>\n<pre><code>function updateGameArea()\n{\n</code></pre>\n</blockquote>\n\n<p>Many style guides disallow this - e.g. <a href=\"https://google.github.io/styleguide/jsguide.html#formatting-braces\" rel=\"nofollow noreferrer\">the Google JS Style guide</a></p>\n\n<blockquote>\n <h3>4.1.2 Nonempty blocks: K&R style</h3>\n \n <p>Braces follow the Kernighan and Ritchie style (\"<a href=\"http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html\" rel=\"nofollow noreferrer\">Egyptian brackets</a>\") for nonempty blocks and block-like constructs:</p>\n \n <ul>\n <li>No line break before the opening brace.</li>\n <li>Line break after the opening brace.</li>\n <li>Line break before the closing brace.</li>\n <li>Line break after the closing brace <em>if</em> that brace terminates a statement or the body of a function or class statement, or a class method. Specifically, there is no line break after the brace if it is followed by <code>else</code>, <code>catch</code>, <code>while</code>, or a comma, semicolon, or right-parenthesis.</li>\n </ul>\n</blockquote>\n\n<h3>Animation frames</h3>\n\n<p><code>SetInterval()</code> is acceptable for many machines but for machines with lower resources (e.g. older machines, mobile devices) it would be wise to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame\" rel=\"nofollow noreferrer\"><code>requestAnimationFrame()</code></a> instead. For more information on this matter, refer to this blog post: <a href=\"https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/\" rel=\"nofollow noreferrer\"><em>Animating with javascript: from setInterval to requestAnimationFrame</em></a>. </p>\n\n<h3>Prototypal inheritance</h3>\n\n<p>The methods are added to each instance of the classes - e.g. <code>myGameArea</code> has methods <code>load</code>, <code>start</code>, <code>clear</code>, and <code>stop</code> while each <code>component</code> instance has its own <code>update</code>, <code>newPos</code>, and <code>crashWith</code> method. For better performance<sup><a href=\"https://stackoverflow.com/a/4508498/1575353\">1</a></sup> these should be added to the prototypes. </p>\n\n<p>For example: </p>\n\n<pre><code>function myGameArea() {\n this.canvas = document.getElementById(\"myCanvas\");\n}\n\nmyGameArea.prototype.load = function() {\n this.canvas.width = canvasW; \n // etc...\n}\nmyGameArea.prototype.start = function() {\n clearInterval(this.loadInterval);\n this.interval = setInterval(updateGameArea, 20);\n}\n</code></pre>\n\n<h3>Class syntax</h3>\n\n<p>You could convert the code to the newer ES6 <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">class syntax</a> - bear in mind that it is \"<em>primarily syntactical sugar over JavaScript's existing prototype-based inheritance</em>\". If there were many subclasses then it would help simplify setting up the prototypal inheritance. </p>\n\n<h3>Looping</h3>\n\n<p>Some loops can be simplified - e.g. instead of the first <code>for</code> loop in <code>updateGameArea()</code>:</p>\n\n<blockquote>\n<pre><code> for (i = 0; i < myObstacles.length; i += 1) {\n if (redGamePiece.crashWith(myObstacles[i])) {\n myGameArea.stop();\n return;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>A <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loop</a> could eliminate the need to dereference the obstacle at the current index:</p>\n\n<pre><code>for (const obstacle of myObstacles) {\n if (redGamePiece.crashWith(obstacle)) {\n myGameArea.stop();\n return;\n }\n}\n</code></pre>\n\n<p>That could be simplified even further using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\"><code>Array.some()</code></a>:</p>\n\n<pre><code>if (myObstacles.some(obstacle => redGamePiece.crashWith(obstacle))) {\n myGameArea.stop();\n return;\n}\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://stackoverflow.com/a/4508498/1575353\">https://stackoverflow.com/a/4508498/1575353</a>)</sub> </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T04:36:34.670",
"Id": "243162",
"ParentId": "242944",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243162",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:46:16.627",
"Id": "242944",
"Score": "3",
"Tags": [
"javascript",
"object-oriented",
"game",
"html5",
"canvas"
],
"Title": "Learning javascript by developing a simple game"
}
|
242944
|
<p>Is the method used below to get data from a database efficient and optimal? The data is in a MySQL database, and in my server I have a PHP file with the following code to return some information:</p>
<pre><code>if($_POST["method"] == "requestBusinessFood") {
requestBusinessFood();
}
function requestBusinessFood() {
$categoryID = $_POST["category"];
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'fooddatabase';
$conn = mysqli_connect($host, $user, $pass, $db);
$sql = "SELECT * FROM `foodtablebusiness` WHERE category = " . $categoryID;
$result = mysqli_query($conn, $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
}
</code></pre>
<p>On the webpage, I have a js file to retrieve the information in the following way:</p>
<pre><code> function createAJAXRequestToPopulateList(category) {
return $.ajax({ url: '../server.php',
data: {method: 'requestBusinessFood',
category: category},
type: 'post'
});
}
function addActivityItem(){
var selector = document.getElementById("categorySelector");
ajaxRequest = createAJAXRequestToPopulateList(selector.options[selector.selectedIndex].value);
ajaxRequest.done(populateList);
}
function populateList(responseData) {
console.log(responseData);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:34:11.957",
"Id": "476985",
"Score": "0",
"body": "Use mysqli_real_escape_string."
}
] |
[
{
"body": "<h2>PHP</h2>\n\n<h3>SQL injection vulnerabilities</h3>\n\n<p>This code is wide-open to <a href=\"https://phpdelusions.net/sql_injection\" rel=\"nofollow noreferrer\">SQL injection attacks</a>. User input should be sanitized as supplied to the query using parameters (e.g. with <a href=\"https://www.php.net/manual/en/mysqli.prepare.php\" rel=\"nofollow noreferrer\"><code>mysqli_prepare()</code></a> and <a href=\"https://www.php.net/manual/en/mysqli-stmt.bind-param.php\" rel=\"nofollow noreferrer\"><code>bind_param()</code></a>).</p>\n\n<h3>Indentation</h3>\n\n<p>The indentation is somewhat consistent but then in some places it increases without a block-level change - e.g. in the PHP code most lines are indented with four spaces, which is very common, and then when <code>$sql</code> is declared it increases to eight spaces.</p>\n\n<blockquote>\n<pre><code>$conn = mysqli_connect($host, $user, $pass, $db); \n $sql = \"SELECT * FROM `foodtablebusiness` WHERE category = \" . $categoryID; \n</code></pre>\n</blockquote>\n\n<h3>Fetching results</h3>\n\n<p>Instead of using a while loop with <code>mysqli_fetch_assoc()</code> just to push into an array, use <a href=\"https://www.php.net/manual/en/mysqli-result.fetch-all.php\" rel=\"nofollow noreferrer\"><code>mysqli_fetch_all()</code></a> to get an array with one call.</p>\n\n<h3>Selecting fields</h3>\n\n<p>Additionally, the SQL query selects all fields - i.e. with <code>SELECT *</code>. Instead of selecting <code>*</code>, specify the field names needed in order to exclude any fields not needed in the front end.</p>\n\n<h2>Javascript</h2>\n\n<h3>Variable scope</h3>\n\n<p>In this line:</p>\n\n<blockquote>\n<pre><code>ajaxRequest = createAJAXRequestToPopulateList(selector.options[selector.selectedIndex].value);\n</code></pre>\n</blockquote>\n\n<p>it makes a global variable <code>ajaxRequest</code> because there is no <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\"><code>var</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> keyword before it. Use <code>const</code> to limit the scope to the function <code>addActivityItem</code>.</p>\n\n<h3>Utilizing jQuery</h3>\n\n<p>It appears that jQuery is used, given the usage of <a href=\"https://api.jquery.com/jQuery.ajax/\" rel=\"nofollow noreferrer\"><code>$.ajax()</code></a> (though if that is wrong then the following won't work). Presuming that is the case, then the other code can be simplified using jQuery utilities.</p>\n\n<p>For example:</p>\n\n<blockquote>\n<pre><code>var selector = document.getElementById(\"categorySelector\");\najaxRequest = createAJAXRequestToPopulateList(selector.options[selector.selectedIndex].value);\n</code></pre>\n</blockquote>\n\n<p>can be simplified to the following using the <a href=\"https://api.jquery.com/val/\" rel=\"nofollow noreferrer\"><code>.val()</code></a> method:</p>\n\n<pre><code>const selector = $('#categorySelector');\nconst ajaxRequest = createAJAXRequestToPopulateList(selector.val());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:06:19.747",
"Id": "243016",
"ParentId": "242945",
"Score": "2"
}
},
{
"body": "<p>Sadly, the PHP part is neither efficient nor optimal.</p>\n<p>Apart from already mentioned issues, your function does too much work, which makes it non-reusable and which bloats your code in general. Remember the rule of thumb: each unit of code should mind its own business. While your function interacts with a client through $_POST and echo, connects to a database, queries a database, formats the results. You have split it into several parts</p>\n<ol>\n<li>Create a <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">separate file to connect with a database</a> and just include it in every script that needs a database connection.</li>\n<li>Create a function that performs a certain SQL query and return the results, so it can be reused for any other kind of request.</li>\n<li>Write a code that handles a particular request from a client</li>\n</ol>\n<p>So the code should be</p>\n<pre><code><?php\nrequire 'mysqli.php';\n\nif($_POST["method"] == "requestBusinessFood")\n{\n $rows = requestBusinessFood($mysqli, $_POST["category"]);\n echo json_encode($rows);\n} \n\nfunction requestBusinessFood($mysqli, $categoryID)\n{\n $sql = "SELECT * FROM foodtablebusiness WHERE category = ?";\n $stmt = $mysqli->prepare($sql);\n $stmt->bind_param("s", $categoryID);\n $stmt->execute();\n $result = $stmt->get_result();\n return $result->fetch_all(MYSQLI_ASSOC);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T12:04:49.687",
"Id": "245222",
"ParentId": "242945",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T12:51:38.160",
"Id": "242945",
"Score": "3",
"Tags": [
"javascript",
"php",
"mysql",
"database",
"ajax"
],
"Title": "Getting data from database through Ajax post request"
}
|
242945
|
<p>This is a Yahoo Finance wrapper to get income/balance statement for a stock ticker. What I have tried to do is make an abstract implementation so more features can be added easily in the future. The base-class <code>YahooFin</code>
contains methods to get and beat the data into shape so it easily can be put into a pandas DataFrame.
The child-classes <code>IncomeStatementQ</code> and <code>BalanceSheetQ</code> only has one method each which is to make a call to the Yahoo API and set query parameters to get the data from the response. I would highly appreciate any input on how abstraction can be increased so that new features can be added with even less code. Any other input is also highly appreciated no matter how small or big. This is my first time trying the use of decorators and properties and feedback on my utilization of them is welcomed. Thank you!</p>
<p>My ideal use of the program is to run it as below:</p>
<pre class="lang-py prettyprint-override"><code> data = IncomeStatementQ('INVE-B.ST')
data.to_df()
#Do whatever with the data
#...
</code></pre>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
import requests
from matplotlib.backends.backend_pdf import PdfPages
from pprint import pprint
class YahooFin():
BASE_URL = 'https://query1.finance.yahoo.com/v10/finance/quoteSummary/'
def __init__(self, ticker):
"""Initiates the ticker
Args:
ticker (str): Stock-ticker Ex. 'AAPL'
"""
self.ticker = ticker
def make_request(self, url):
"""Makes a GET request"""
return requests.get(url)
def get_data(self):
"""Returns a json object from a GET request"""
return self.make_request(self.url).json()
def data(self):
"""Returns query result from json object"""
data_temp = self.get_data()
try:
return data_temp.get('quoteSummary').get("result")
except KeyError as e:
print("Something went wrong")
def convert_timestamp(self, raw):
"""Converts UNIX-timestamp to YYYY-MM-DD"""
return datetime.utcfromtimestamp(raw).strftime('%Y-%m-%d')
def extract_raw(func):
"""Decorator to remove keys from from json data
that is retreived from the yahoo-module
"""
def wrapper_extract_raw(self, *args, **kwargs):
sheet = func(self)
for items in sheet:
for key, value in items.items():
if type(value) == dict and 'fmt' in value:
del value['fmt']
if type(value) == dict and 'longFmt' in value:
del value['longFmt']
return sheet
return wrapper_extract_raw
def create_dict(self):
"""Creates a dict from extracted data"""
balance_sheet = []
temp_data = self._dict
for d in temp_data:
temp_dict = {}
for key, value in d.items():
if type(value) == dict and 'raw' in value:
v = value['raw']
temp_dict[key] = v
balance_sheet.append(temp_dict)
return balance_sheet
def to_df(self):
"""Creates a pandas Dataframe from dict"""
self._df = pd.DataFrame.from_dict(self.create_dict())
for index, row in self._df.iterrows():
self._df.loc[index, 'endDate'] = self.convert_timestamp(self._df.at[index, 'endDate'])
self._df = self._df.iloc[::-1]
return self._df
class BalanceSheetQ(YahooFin):
def __init__(self, ticker):
super().__init__(ticker)
self._module = 'balanceSheetHistoryQuarterly'
self._url = (f'https://query1.finance.yahoo.com/v10/finance/quoteSummary/'
f'{self.ticker}?'
f'modules={self.module}')
self._dict = self._balance_sheet()
self._df = None
@property
def module(self):
return self._module
@property
def url(self):
return self._url
@property
def df(self):
return self._df
@YahooFin.extract_raw
def _balance_sheet(self):
"""Returns a balance sheet statement"""
data = self.data()
query = data[0]
balance_sheet_qty = query['balanceSheetHistoryQuarterly']
balance_sheet_statements = balance_sheet_qty['balanceSheetStatements']
return balance_sheet_statements
class IncomeStatementQ(YahooFin):
def __init__(self, ticker):
super().__init__(ticker)
self._module = 'incomeStatementHistoryQuarterly'
self._url = (f'https://query1.finance.yahoo.com/v10/finance/quoteSummary/'
f'{self.ticker}?'
f'modules={self.module}')
self._dict = self._income_statement()
self._df = None
@property
def module(self):
return self._module
@property
def url(self):
return self._url
@property
def df(self):
return self._df
@YahooFin.extract_raw
def _income_statement(self):
"""Returns a income statement"""
data = self.data()
query = data[0]
income_statement_qty = query['incomeStatementHistoryQuarterly']
income_statement_statements = income_statement_qty['incomeStatementHistory']
return income_statement_statements
if __name__ == '__main__':
data = IncomeStatementQ('INVE-B.ST')
print(data.to_df())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T19:48:51.053",
"Id": "476852",
"Score": "0",
"body": "This is (mercifully) an API client, not a web scraper."
}
] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>You're most of the way to having a well-explained constructor:</p>\n\n<blockquote>\n <p>ticker (str): Stock-ticker Ex. 'AAPL'</p>\n</blockquote>\n\n<p>It's better to move that <code>(str)</code> to an actual type hint, i.e. </p>\n\n<pre><code>def __init__(self, ticker: str):\n</code></pre>\n\n<h2>Superfluous methods</h2>\n\n<p>As it stands, <code>make_request</code> doesn't need to exist. It would make sense to keep it if you add a <code>Session</code> instance to the class, which (for an API client) you should do anyway. But if you don't have a session, delete this method and just use requests directly. The same goes for <code>get_data</code>.</p>\n\n<h2>Exception handling</h2>\n\n<p>This:</p>\n\n<pre><code> except KeyError as e:\n print(\"Something went wrong\")\n</code></pre>\n\n<p>should probably not be catching at all, or at least not catching here. If you are iterating over several web calls and you don't want them to cancel the loop due to an exception, catch in the loop. If you want to reformat an exception for printing to the console, do that somewhere up in the stack; but don't do it here. And if you <em>do</em> want to print an exception, print its <code>str()</code> representation; don't give a vague <code>Something went wrong</code>.</p>\n\n<h2>Statics</h2>\n\n<p><code>convert_timestamp</code> doesn't reference <code>self</code>, so should be a static method at least. More likely a global, standalone function, since it has nothing to do with your client.</p>\n\n<h2>Type comparison</h2>\n\n<p>Don't do this:</p>\n\n<pre><code>type(value) == dict\n</code></pre>\n\n<p>Instead, use <code>isinstance</code>.</p>\n\n<h2>Parameters to web requests</h2>\n\n<pre><code>self._url = (f'https://query1.finance.yahoo.com/v10/finance/quoteSummary/'\n f'{self.ticker}?'\n f'modules={self.module}')\n</code></pre>\n\n<p>should avoid baking in <code>modules=</code>. This is best done by passing <code>params=</code> to <code>requests.get()</code>.</p>\n\n<h2>\"Private\" variables</h2>\n\n<p>This:</p>\n\n<pre><code>@property\ndef module(self):\n return self._module\n</code></pre>\n\n<p>is a Java-ism. In the strict sense, Python has no private variables, and the underscore is basically a \"soft request\" for exterior users to leave a variable alone. It's more common to simply expose <code>self.module</code> as a variable without the property.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T06:05:32.663",
"Id": "476895",
"Score": "0",
"body": "Thank you for the constructive feedback! I will definitely read more about client APIs and optimal implementations! Also, thank you for pointing out that you don’t always want to catch an error, and how to properly display error messages if any are to be shown!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:00:47.337",
"Id": "242966",
"ParentId": "242948",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242966",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:03:10.820",
"Id": "242948",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"design-patterns"
],
"Title": "Download statements from Yahoo Finance"
}
|
242948
|
<h2>Let's Fight:</h2>
<p>one <code>Entity</code> can perform an attack (thus making him an <em>attacker</em>) on another <code>Entity</code> (<em>defender</em>). This follows some <em>Rules</em>, described within the <code>AttackProcedure.performAttack()</code>. The <code>FightRules</code> describe, what <code>Chances</code> one <code>Entity</code> has to succeed (or not) and what Damage will results from an attack.</p>
<p><a href="https://i.stack.imgur.com/wuJJQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wuJJQ.png" alt="enter image description here"></a></p>
<p>(C) <a href="https://www.pinclipart.com/pindetail/omwhRx_knight-knight-fight-icon-clipart/" rel="nofollow noreferrer">https://www.pinclipart.com/pindetail/omwhRx_knight-knight-fight-icon-clipart/</a></p>
<p>Can you please Review this code?</p>
<h2>Code</h2>
<p><strong>Stat:</strong></p>
<pre><code>public class Stat {
private Object identifier;
private double base;
private double current;
public Stat(Object identifier, double base, int current) {
this.identifier = identifier;
this.base = base;
this.current = current;
}
public Object getIdentifier() {
return identifier;
}
public void apply(StatChange change) {
current = current + change.getDelta();
}
public double getCurrent() {
return current;
}
@Override
public String toString() {
return identifier + " " + current + " / " + base;
}
}
</code></pre>
<p><strong>Stats:</strong></p>
<pre><code>public interface Stats {
Stat getStat(Object identifier);
void changeStats(List<StatChange> impact);
}
</code></pre>
<p><strong>StatChange:</strong></p>
<pre><code>public class StatChange {
private final Object identifier;
private final double delta;
public StatChange(Object identifier, double delta) {
this.identifier = Objects.requireNonNull(identifier, "identifier must not be null");
this.delta = delta;
}
public boolean matches(Stat stat) {
return identifier.equals(stat.getIdentifier());
}
public double getDelta() {
return delta;
}
@Override
public String toString() {
return "" + identifier + " delta:" + delta;
}
}
</code></pre>
<p><strong>Chance:</strong></p>
<pre><code>public interface Chance {
boolean wasSuccessful();
String getRollResult();
}
</code></pre>
<p><strong>FightRules:</strong></p>
<pre><code>public interface FightRules<I extends Chance, E extends Entity> {
I getAttackChance(E attacker, E defender);
I getDefendChance(E attacker, E defender);
List<StatChange> getImpact(E attacker, E defender, I attackChance, I defendChance);
}
</code></pre>
<p><strong>Entity:</strong></p>
<pre><code>public interface Entity {
Stats getStats();
}
</code></pre>
<p><strong>AttackProcedure:</strong></p>
<pre><code>public class AttackProcedure {
private final FightRules rules;
public AttackProcedure(FightRules rules) {
this.rules = rules;
}
public Result performAttack(Entity attacker, Entity defender) {
AttackProcedureResult result = new AttackProcedureResult();
result.logIntro(attacker, defender);
Chance attackChance = rules.getAttackChance(attacker, defender);
Chance defendChance = rules.getDefendChance(attacker, defender);
result.logAttackChance(attackChance);
if (attackChance.wasSuccessful()) {
result.logAttackSucceeded(defendChance);
if (defendChance.wasSuccessful()) {
result.logDefendSucceeded();
} else {
result.logDefendFailed();
applyDamage(attacker, defender, attackChance, defendChance, result);
}
} else {
result.logAttackFailed();
}
result.logOutro(attacker, defender);
return result;
}
private void applyDamage(Entity attacker, Entity defender, Chance attackChance, Chance defendChance, AttackProcedureResult result) {
List<StatChange> impact = rules.getImpact(attacker, defender, attackChance, defendChance);
result.logImpact(impact);
defender.getStats().changeStats(impact);
}
}
</code></pre>
<p><strong>Result:</strong></p>
<pre><code>public interface Result {
void append(String line);
List<String> entries();
}
</code></pre>
<p><strong>AttackProcedureResult:</strong></p>
<pre><code>public class AttackProcedureResult implements Result {
private final List<String> log = new ArrayList<>();
@Override
public void append(String line) {
log.add(line);
}
@Override
public List<String> entries() {
return log;
}
void logAttackSucceeded(Chance defendChance) {
append("attack was successful (attacker hit)");
append("chance of successful block the attack is: " + defendChance);
append("defender rolled: " + defendChance.getRollResult() + ", defense was successful=" + defendChance.wasSuccessful());
append("");
}
void logOutro(Entity attacker, Entity defender) {
append("");
append("attack is done, " + attacker + ", " + defender);
append("--------");
append("");
}
void logAttackChance(Chance attackChance) {
append("chance of successful attack is: " + attackChance);
append("attacker rolled: " + attackChance.getRollResult() + ", attack was successful=" + attackChance.wasSuccessful());
append("");
}
void logIntro(Entity attacker, Entity defender) {
append("attack begins");
append(attacker + " attacks " + defender);
append("--------");
append("");
}
void logDefendSucceeded() {
append("defender successfully avoided the attack");
}
void logDefendFailed() {
append("defender could not avoid the attack - time to take some damage....");
}
void logAttackFailed() {
append("attack was not successful (attacker missed)");
}
void logImpact(List<StatChange> impact) {
append("giving impact: " + impact);
}
}
</code></pre>
<h2>Tests</h2>
<p><strong>AttackProcedureTest:</strong></p>
<pre><code>public class AttackProcedureTest {
private final AttackProcedure attackProcedure = new AttackProcedure(new TestFightRules());
private TestEntity attacker = new TestEntity("attacker");
@Test
public void test_successfulAttack_withFailingDefense_procedureExecution() {
//given
TestEntity defender = new TestEntity("defender");
attacker.setSupposedToSucceedInAttack(true);
defender.setSupposedToSucceedInDefense(false);
double defenderLifeBefore = defender.getStats().getStat(TestStatIdentifier.HEALTH).getCurrent();
//when
Result result = attackProcedure.performAttack(attacker, defender);
result.entries().forEach(System.out::println);
double defenderLifeAfter = defender.getStats().getStat(TestStatIdentifier.HEALTH).getCurrent();
//then
assertEquals(1, defenderLifeBefore, 0.01);
assertEquals(0, defenderLifeAfter, 0.01);
assertNotNull(result);
assertFalse(result.entries().isEmpty());
}
@Test
public void test_failingAttack_ProcedureExecution() {
//given
TestEntity defender = new TestEntity("defender");
attacker.setSupposedToSucceedInAttack(false);
defender.setSupposedToSucceedInDefense(false);
double defenderLifeBefore = defender.getStats().getStat(TestStatIdentifier.HEALTH).getCurrent();
//when
Result result = attackProcedure.performAttack(attacker, defender);
result.entries().forEach(System.out::println);
double defenderLifeAfter = defender.getStats().getStat(TestStatIdentifier.HEALTH).getCurrent();
//then
assertEquals(1, defenderLifeBefore, 0.01);
assertEquals(1, defenderLifeAfter, 0.01);
assertNotNull(result);
assertFalse(result.entries().isEmpty());
}
@Test
public void test_successfulAttack_withSuccessfulDefense_procedureExecution() {
//given
TestEntity defender = new TestEntity("defender");
attacker.setSupposedToSucceedInAttack(true);
defender.setSupposedToSucceedInDefense(true);
double defenderLifeBefore = defender.getStats().getStat(TestStatIdentifier.HEALTH).getCurrent();
//when
Result result = attackProcedure.performAttack(attacker, defender);
result.entries().forEach(System.out::println);
double defenderLifeAfter = defender.getStats().getStat(TestStatIdentifier.HEALTH).getCurrent();
//then
assertEquals(1, defenderLifeBefore, 0.01);
assertEquals(1, defenderLifeAfter, 0.01);
assertNotNull(result);
assertFalse(result.entries().isEmpty());
}
}
</code></pre>
<p><strong>TestEntity:</strong></p>
<pre><code>public class TestEntity implements Entity {
private final String name;
private final Stats stats = new TestStats();
private boolean isSupposedToSucceedInAttack;
private boolean isSupposedToSucceedInDefense;
public TestEntity(String name) {
this.name = name;
}
@Override
public Stats getStats() {
return stats;
}
@Override
public String toString() {
return name + " " + getStats().getStat(TestStatIdentifier.HEALTH);
}
public boolean isSupposedToSucceedInAttack() {
return isSupposedToSucceedInAttack;
}
public void setSupposedToSucceedInAttack(boolean supposedToSucceedInAttack) {
isSupposedToSucceedInAttack = supposedToSucceedInAttack;
}
public boolean isSupposedToSucceedInDefense() {
return isSupposedToSucceedInDefense;
}
public void setSupposedToSucceedInDefense(boolean supposedToSucceedInDefense) {
isSupposedToSucceedInDefense = supposedToSucceedInDefense;
}
}
</code></pre>
<p><strong>TestFightRules:</strong></p>
<pre><code>public class TestFightRules implements FightRules<Chance, TestEntity> {
@Override
public Chance getAttackChance(TestEntity attacker, TestEntity defender) {
if (attacker.isSupposedToSucceedInAttack()) {
return new WinningChance();
}
return new FailingChance();
}
@Override
public Chance getDefendChance(TestEntity attacker, TestEntity defender) {
if (defender.isSupposedToSucceedInDefense()) {
return new WinningChance();
}
return new FailingChance();
}
@Override
public List<StatChange> getImpact(TestEntity attacker, TestEntity defender, Chance attackChance, Chance defendChance) {
return Collections.singletonList(new StatChange(TestStatIdentifier.HEALTH, -1));
}
}
</code></pre>
<p><strong>TestWinningChance:</strong></p>
<pre><code>public class WinningChance implements Chance {
private final int die;
public WinningChance() {
die = 1 + new Random().nextInt(20);
}
@Override
public boolean wasSuccessful() {
return die < 23;
}
@Override
public String getRollResult() {
return "1D20=" + die;
}
@Override
public String toString() {
return "succeed if 1D20 < 23";
}
}
</code></pre>
<p><strong>TestFailingChance:</strong></p>
<pre><code>public class FailingChance implements Chance {
private final int die;
public FailingChance() {
die = 1 + new Random().nextInt(20);
}
@Override
public boolean wasSuccessful() {
return die < 0;
}
@Override
public String getRollResult() {
return "1D20=" + die;
}
@Override
public String toString() {
return "succeed if 1D20 < 0";
}
}
</code></pre>
<p><strong>TestStats:</strong></p>
<pre><code>public class TestStats implements Stats {
private final List<Stat> collection;
public TestStats() {
collection = new ArrayList<>();
collection.add(new Stat(TestStatIdentifier.HEALTH, 1, 1));
}
@Override
public Stat getStat(Object identifier) {
return collection.stream().filter(s -> s.getIdentifier().equals(identifier)).findAny().orElse(null);
}
@Override
public void changeStats(List<StatChange> impact) {
for (Stat stat : collection) {
for (StatChange change : impact) {
if (change.matches(stat)) {
stat.apply(change);
}
}
}
}
}
</code></pre>
<p><strong>TestStatIdentifier:</strong></p>
<pre><code>public enum TestStatIdentifier {
HEALTH, INTELLIGENCE, STRENGTH
}
</code></pre>
|
[] |
[
{
"body": "<p>I compared the class <code>Stat</code>:</p>\n\n<blockquote>\n<pre><code>public class Stat {\n private Object identifier;\n private double base;\n private double current;\n .....methods\n}\n</code></pre>\n</blockquote>\n\n<p>and the class <code>TestStats</code> using it:</p>\n\n<blockquote>\n<pre><code>public class TestStats implements Stats {\n private final List<Stat> collection;\n public TestStats() {\n collection = new ArrayList<>();\n collection.add(new Stat(TestStatIdentifier.HEALTH, 1, 1));\n }\n @Override\n public Stat getStat(Object identifier) {\n return collection.stream().filter(s -> s.getIdentifier().equals(identifier)).findAny().orElse(null);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You are implementing with your two classes a <code>Map<String, Stat></code> because you a direct corrispondence between the name of your stat and the couple of doubles <code>base</code> and <code>current</code> present in your class <code>Stat</code>. The <code>Object</code> field <code>identifier</code> is used a key in the map, so you can rewrite your <code>Stat</code> class in this way:</p>\n\n<pre><code>public class Stat {\n private double base;\n private double current;\n\n public Stat(double base, int current) {\n this.base = base;\n this.current = current;\n }\n\n public void apply(StatChange change) {\n current += change.getDelta();\n }\n\n public double getCurrent() {\n return current;\n }\n\n @Override\n public String toString() {\n return String.format(\"%.1f/%.1f\", current, base);\n }\n}\n</code></pre>\n\n<p>Now your class TestStats will contain a <code>Map<String, Stat></code> and this seems logic to me because every fighter (<code>Entity</code>) has its map of characteristics defined when you initialize the fighter:</p>\n\n<pre><code>public class TestStats implements Stats {\n private final Map<String, Stat> map;\n\n public TestStats(Map<String, Stat> map) {\n this.map = new TreeMap<>(map);\n }\n\n @Override\n public Stat getStat(String identifier) {\n return map.getOrDefault(identifier, null);\n }\n\n @Override\n public void changeStats(List<StatChange> impact) {\n for (String key : map.keySet()) {\n for (StatChange change : impact) {\n if (change.matches(key)) {\n map.get(key).apply(change);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Consequently there are some minor changes to <code>Stats</code> interface and <code>StatChange</code>:</p>\n\n<pre><code>public interface Stats {\n Stat getStat(String identifier);\n void changeStats(List<StatChange> impact);\n}\n</code></pre>\n\n<p>and StatChange class:</p>\n\n<pre><code>public class StatChange {\n private final String name;\n private final double delta;\n\n public StatChange(String identifier, double delta) {\n this.name = Objects.requireNonNull(identifier, \"identifier must not be null\");\n this.delta = delta;\n }\n\n public boolean matches(String identifier) {\n return name.equals(identifier);\n }\n\n public double getDelta() {\n return delta;\n }\n\n @Override\n public String toString() {\n return String.format(\"%s delta:%.1f\", name, delta);\n }\n}\n</code></pre>\n\n<p>Some changes can be applied to your <code>AttackProcedureTest</code> class : you can use the annotation <code>@Before</code> to a <code>setUp</code> method that will be invoked before every test to initialize the scenarios, you class could be rewritten in this way:</p>\n\n<pre><code>public class AttackProcedureTest {\n private final AttackProcedure attackProcedure = new AttackProcedure(new TestFightRules());\n private final static String HEALTH = \"HEALTH\";\n private TestEntity attacker;\n private TestEntity defender;\n\n @Before\n public void setUp() {\n Map<String , Stat> map = new HashMap<String, Stat>();\n map.put(HEALTH, new Stat(1, 1));\n attacker = new TestEntity(\"attacker\", new TestStats(map));\n defender = new TestEntity(\"defender\", new TestStats(map));\n }\n\n @Test\n public void test_successfulAttack_withFailingDefense_procedureExecution() {\n double defenderLifeBefore = defender.getStats().getStat(HEALTH).getCurrent();\n\n attacker.setSupposedToSucceedInAttack(true);\n defender.setSupposedToSucceedInDefense(false);\n Result result = attackProcedure.performAttack(attacker, defender);\n result.entries().forEach(System.out::println);\n\n double defenderLifeAfter = defender.getStats().getStat(HEALTH).getCurrent();\n\n assertEquals(1, defenderLifeBefore, 0.01);\n assertEquals(0, defenderLifeAfter, 0.01);\n assertNotNull(result);\n assertFalse(result.entries().isEmpty());\n }\n\n @Test\n public void test_failingAttack_ProcedureExecution() {\n double defenderLifeBefore = defender.getStats().getStat(HEALTH).getCurrent();\n\n attacker.setSupposedToSucceedInAttack(false);\n defender.setSupposedToSucceedInDefense(false);\n Result result = attackProcedure.performAttack(attacker, defender);\n result.entries().forEach(System.out::println);\n\n double defenderLifeAfter = defender.getStats().getStat(HEALTH).getCurrent();\n\n assertEquals(1, defenderLifeBefore, 0.01);\n assertEquals(1, defenderLifeAfter, 0.01);\n assertNotNull(result);\n assertFalse(result.entries().isEmpty());\n }\n\n @Test\n public void test_successfulAttack_withSuccessfulDefense_procedureExecution() {\n double defenderLifeBefore = defender.getStats().getStat(HEALTH).getCurrent();\n\n attacker.setSupposedToSucceedInAttack(true);\n defender.setSupposedToSucceedInDefense(true); \n Result result = attackProcedure.performAttack(attacker, defender);\n result.entries().forEach(System.out::println);\n\n double defenderLifeAfter = defender.getStats().getStat(HEALTH).getCurrent();\n\n assertEquals(1, defenderLifeBefore, 0.01);\n assertEquals(1, defenderLifeAfter, 0.01);\n assertNotNull(result);\n assertFalse(result.entries().isEmpty());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T05:19:33.937",
"Id": "476981",
"Score": "0",
"body": "Thank you dariosicily for having a look at my code - i read your answer on my code already yesterday and honstely you found a very interesting point! i spend all night on overthinking how and where the identifier is supposed to be and i cannot tell you yet. Your answer provides a great idea on how my code coud be organized in another way. Thanks for sharing these thoughts with me!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:56:47.003",
"Id": "476989",
"Score": "0",
"body": "@MartinFrank, You are welcome, my idea is the stats identifier is the `String` name of the stat, so if you extract it from the class and use it as a key in the `Map` stats the initialization of an `Entity` is simpler and because a map cannot contain duplicate keys you avoid the risk to duplicate the stats."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T07:51:07.967",
"Id": "476993",
"Score": "0",
"body": "it would work as well if you would use the `TestStatIdentifier` as key as well - i would consider using a `String` as key would be slightly [Primitive-Obession](https://refactoring.guru/smells/primitive-obsession)... but thats only my thinking"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T15:54:31.700",
"Id": "243010",
"ParentId": "242949",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:11:03.080",
"Id": "242949",
"Score": "1",
"Tags": [
"java"
],
"Title": "DnD-like Fight (Single Round)"
}
|
242949
|
<p>I have written the following Javascript code which increments and decrements 3 separate inputs by 1:</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>//INCREMENTS/DECREMENTS BEDROOMS BY 1
function plusOneBedrooms() {
var addRoom = document.getElementById('rooms_amount_bedroom');
value = parseInt(addRoom.getAttribute('value'), 10) + 1;
addRoom.setAttribute('value', value);
addRoom.innerHTML = value;
}
function minusOneBedrooms() {
var subtractRoom = document.getElementById('rooms_amount_bedroom');
value = parseInt(subtractRoom.getAttribute('value'), 10) - 1;
subtractRoom.setAttribute('value', value);
subtractRoom.innerHTML = value;
}
//INCREMENTS/DECREMENTS BATHROOMS BY 1
function plusOneBathrooms() {
var addRoom = document.getElementById('rooms_amount_bathrooms');
value = parseInt(addRoom.getAttribute('value'), 10) + 1;
addRoom.setAttribute('value', value);
addRoom.innerHTML = value;
}
function minusOneBathrooms() {
var subtractRoom = document.getElementById('rooms_amount_bathrooms');
value = parseInt(subtractRoom.getAttribute('value'), 10) - 1;
subtractRoom.setAttribute('value', value);
subtractRoom.innerHTML = value;
}
//INCREMENTS/DECREMENTS KITCHENS BY 1
function plusOneKitchens() {
var addRoom = document.getElementById('rooms_amount_kitchens');
value = parseInt(addRoom.getAttribute('value'), 10) + 1;
addRoom.setAttribute('value', value);
addRoom.innerHTML = value;
}
function minusOneKitchens() {
var subtractRoom = document.getElementById('rooms_amount_kitchens');
value = parseInt(subtractRoom.getAttribute('value'), 10) - 1;
subtractRoom.setAttribute('value', value);
subtractRoom.innerHTML = value;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="room_type_wrap">
<small class="counter_title counter_opacity1">Bedrooms</small>
<hr class="counter_title_underline">
<div class="counter_wrap">
<div class="subtractRoom" onclick="minusOneBedrooms()">
<img src="./assets/images/arrow_down.png" alt="" class="counter_down_arrow">
</div>
<input type="number" class="room_count" id="rooms_amount_bedroom" autocomplete="off" value="0">
<div class="addRoom" onclick="plusOneBedrooms()">
<img src="./assets/images/arrow_up_white.png" alt="" class="counter_up_arrow">
</div>
</div>
<small class="counter_title counter_opacity2">Bathrooms</small>
<hr class="counter_title_underline">
<div class="counter_wrap">
<div class="subtractRoom" onclick="minusOneBathrooms()">
<img src="./assets/images/arrow_down.png" alt="" class="counter_down_arrow">
</div>
<input type="number" class="room_count" id="rooms_amount_bathrooms" autocomplete="off" value="0">
<div class="addRoom" onclick="plusOneBathrooms()">
<img src="./assets/images/arrow_up_white.png" alt="" class="counter_up_arrow">
</div>
</div>
<small class="counter_title counter_opacity3">Kitchens</small>
<hr class="counter_title_underline">
<div class="counter_wrap">
<div class="subtractRoom" onclick="minusOneKitchens()">
<img src="./assets/images/arrow_down.png" alt="" class="counter_down_arrow">
</div>
<input type="number" class="room_count" id="rooms_amount_kitchens" autocomplete="off" value="0">
<div class="addRoom" onclick="plusOneKitchens()">
<img src="./assets/images/arrow_up_white.png" alt="" class="counter_up_arrow">
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I would like to be able to have the same functionality but feel I could have probably done this in a simpler way. I'm new to Javascript/JQuery so any suggestions will be appreciated. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:47:36.110",
"Id": "476811",
"Score": "0",
"body": "Thanks, i've edited my question accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T18:52:10.273",
"Id": "476847",
"Score": "0",
"body": "@DelroyBrown your code does not appear to function as intended: `addRoom.innerHTML = value` looks like a mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T18:56:26.283",
"Id": "476849",
"Score": "0",
"body": "Also, I think you might just be looking for the HTML [input type number](http://w3schools-fa.ir/tags/att_input_type_number.html)? No javascript/jQuery needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T19:05:21.193",
"Id": "476850",
"Score": "1",
"body": "@Graipher He's already using `type=number`. I think his code is just broken, and it isn't clear what his code was meant to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T19:28:24.630",
"Id": "476851",
"Score": "0",
"body": "@Graipher Hi, the intent of the code is to increment/decrement an ```input``` value by 1 when the ```addRoom``` and ```subtractRoom``` buttons are clicked. The code works I'm just having trouble trying to simplify the method i've used."
}
] |
[
{
"body": "<p>Some things could be said about the HTML (no need for hr, border will do; those imgs should be background images on buttons; this is obviously a list; those smalls should be labels; way to many divs; ...) but let me focus on te JS as you are asking.</p>\n\n<p>First thing that jumps out is the repetition. Each function basically does the same thing, but for a different room and with a different amount. Not very DRY at all. </p>\n\n<p>The easy solution would be to pass the room name and the change amount in the function as parameters, and now you only need one function. Something like this:</p>\n\n<pre><code>function changeValue(roomName, amount) { ...\n</code></pre>\n\n<p>You can them call your function from the onclick attribute like so:</p>\n\n<pre><code><div ... onclick=\"changeValue('bedroom', -1)\">\n</code></pre>\n\n<p>You can now add more rooms without having to change the javascript, and if you decide to change something in your logic you only have to change it once.</p>\n\n<p>Second thing that was already noticed in the comments, you are changing the <code>innerHtml</code> of your inputs, but there is no such thing on inputs (there is no opening and closing tag with 'innerhtml' between them). Changing the value will suffice.</p>\n\n<p>Also, you mention and tag jQuery, but this is vanilla JS, not a line off jQuery in there (which is fine btw!)</p>\n\n<p>Let me close by showing you how <a href=\"https://jsfiddle.net/_pevara/mnds7et6/1/\" rel=\"nofollow noreferrer\">my code</a> would look if I had to write it:</p>\n\n<p>HTML:</p>\n\n<pre><code><ul id=\"rooms\">\n <li>\n <label for=\"bathroom_count\">bathrooms</label>\n <button data-amount=\"-1\">-</button>\n <input type=\"number\" id=\"bathroom_count\" value=\"0\" autocomplete=\"off\"/>\n <button data-amount=\"1\">+</button>\n </li>\n <li>\n <label for=\"bedroom_count\">bedrooms</label>\n <button data-amount=\"-1\">-</button>\n <input type=\"number\" id=\"bedroom_count\" value=\"0\" autocomplete=\"off\"/>\n <button data-amount=\"1\">+</button>\n </li>\n <li>\n <label for=\"kitchen_count\">kitchens</label>\n <button data-amount=\"-1\">-</button>\n <input type=\"number\" id=\"kitchen_count\" value=\"0\" autocomplete=\"off\"/>\n <button data-amount=\"1\">+</button>\n </li>\n</ul>\n</code></pre>\n\n<p>jQuery:</p>\n\n<pre><code> $('#rooms li').on('click', 'button', function(e) {\n e.preventDefault();\n var $button = $(e.currentTarget);\n var $input = $button.siblings('input');\n\n $input.val(parseInt($input.val(), 10) + parseInt($button.data('amount'), 10));\n });\n</code></pre>\n\n<p>I think the code should speak for itself, but feel free to ask if you want me to elaborate. </p>\n\n<p>I hope you learned something from it and happy coding!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:25:40.813",
"Id": "476910",
"Score": "0",
"body": "This answer is excellent! Thanks alot @Pevara, this has helped me a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T23:39:46.500",
"Id": "242979",
"ParentId": "242950",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242979",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:18:29.300",
"Id": "242950",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Incrementing and decrementing 3 seperate input values by 1 using Javascript"
}
|
242950
|
<p>Wrote a python script to web scrape multiple newspapers and arrange them in their respective directories. I have completed the course Using Python to access web data on coursera and I tried to implement what I learned by a mini project.
I am sure there would be multiple improvements to this script and I would like to learn and implement them to better.</p>
<pre><code>import urllib.request, urllib.error, urllib.parse
from bs4 import BeautifulSoup
import ssl
import requests
import regex as re
import os
from datetime import date, timedelta
today = date.today()
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
def is_downloadable(url):
"""
Does the url contain a downloadable resource
"""
h = requests.head(url, allow_redirects=True)
header = h.headers
content_type = header.get('content-type')
if 'text' in content_type.lower():
return False
if 'html' in content_type.lower():
return False
return True
# dictionary for newspaper names and their links
newspaper = dict({'Economic_times':'https://dailyepaper.in/economic-times-epaper-pdf-download-2020/', 'Times_of_India':'https://dailyepaper.in/times-of-india-epaper-pdf-download-2020/',
'Financial_Express':'https://dailyepaper.in/financial-express-epaper-pdf-download-2020/', 'Deccan_Chronicle':'https://dailyepaper.in/deccan-chronicle-epaper-pdf-download-2020/',
'The_Telegraph':'https://dailyepaper.in/the-telegraph-epaper-pdf-download-2020/', 'The_Pioneer':'https://dailyepaper.in/the-pioneer-epaper-pdf-download-2020/',
'Business_Line':'https://dailyepaper.in/business-line-epaper-pdf-download-2020/', 'Indian_Express':'https://dailyepaper.in/indian-express-epaper-pdf-download-2020/',
'Hindustan_Times':'https://dailyepaper.in/hindustan-times-epaper-pdf-free-download-2020/', 'The_Hindu':'https://dailyepaper.in/the-hindu-pdf-newspaper-free-download/',
'Dainik_Jagran':'https://dailyepaper.in/dainik-jagran-newspaper-pdf/', 'Dainik_Bhaskar':'https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/',
'Amar_Ujala':'https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/'})
#dictionary to give serial numbers to each newspaper
#I think something better could be done instead of this dictionary
serial_num = dict({1:'Economic_times', 2:'Times_of_India', 3:'Financial_Express', 4:'Deccan_Chronicle', 5:'The_Telegraph', 6:'The_Pioneer', 7:'Business_Line',
8:'Indian_Express', 9:'Hindustan_Times', 10:'The_Hindu', 11:'Dainik_Jagran', 12:'Dainik_Bhaskar', 13:'Amar_Ujala'})
print("The following Newspapers are available for download. Select any of them by giving number inputs - ")
print("1. Economic Times")
print("2. Times of India")
print("3. Financial Express")
print("4. Deccan Chronicle")
print("5. The Telegraph")
print("6. The Pioneer")
print("7. Business Line")
print("8. Indian Express")
print("9. Hindustan Times")
print("10. The Hindu")
print("11. Dainik Jagran")
print("12. Dainik Bhaskar")
print("13. Amar Ujala")
#taking serial numbers for multiple nespapers and storing them in a list
serial_index = input('Enter the number for newspapers - ')
serial_index = serial_index.split()
indices = [int(x) for x in serial_index]
for ser_ind in indices:
url = newspaper[serial_num[ser_ind]]
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
html = urllib.request.urlopen(req).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('a')
list_paper = list()
directory = serial_num[ser_ind]
parent_dir = os.getcwd()
path = os.path.join(parent_dir, directory)
#make a new directory for given newspaper, if that exists then do nothing
try:
os.mkdir(path)
except OSError as error:
pass
os.chdir(path) #enter the directory for newspaper
#storing links for given newspaper in a list
for i in range(len(tags)):
links = tags[i].get('href',None)
x = re.search("^https://vk.com/", links)
if x:
list_paper.append(links)
print('For how many days you need the '+ serial_num[ser_ind]+' paper?')
print('i.e. if only todays paper press 1, if want whole weeks paper press 7')
print('Size of each paper is 5-12MB')
for_how_many_days = int(input('Enter your number - '))
for i in range(for_how_many_days):
url = list_paper[i]
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
html = urllib.request.urlopen(req).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('iframe')
link = tags[0].get('src',None)
date_that_day = today - timedelta(days=i) #getting the date
if is_downloadable(link):
print('Downloading '+serial_num[ser_ind]+'...')
r = requests.get(link, allow_redirects=True)
with open(serial_num[ser_ind]+"_"+str(date_that_day)+".pdf",'wb') as f:
f.write(r.content)
print('Done :)')
else:
print(serial_num[ser_ind] + ' paper not available for '+ str(date_that_day))
os.chdir('../') #after downloading all the newspapers go back to parent directory
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Usage of requests</h2>\n\n<p>Strongly consider replacing your use of bare <code>urllib</code> with <code>requests</code>. It's much more usable. Among other things, it should prevent you from having to worry about an SSL context.</p>\n\n<h2>Type hints</h2>\n\n<pre><code>def is_downloadable(url):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def is_downloadable(url: str) -> bool:\n</code></pre>\n\n<p>And so on for your other functions.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code>content_type = header.get('content-type')\nif 'text' in content_type.lower():\n return False\nif 'html' in content_type.lower():\n return False\nreturn True\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>content_type = header.get('content-type', '').lower()\nreturn not (\n 'text' in content_type or\n 'html' in content_type\n)\n</code></pre>\n\n<p>Also note that if a content type is not provided, this function will crash unless you change the default of the <code>get</code> to <code>''</code>.</p>\n\n<h2>Dictionary literals</h2>\n\n<p>This:</p>\n\n<pre><code>newspaper = dict({ ...\n</code></pre>\n\n<p>does not need a call to <code>dict</code>; simply use the braces and they will make a dictionary literal.</p>\n\n<h2>URL database</h2>\n\n<p>Note what is common in all of your newspaper links and factor it out. In other words, all URLs match the pattern</p>\n\n<pre><code>https://dailyepaper.in/...\n</code></pre>\n\n<p>so you do not need to repeat the protocol and host in those links; save that to a different constant.</p>\n\n<h2>Newspaper objects</h2>\n\n<blockquote>\n <p>dictionary to give serial numbers to each newspaper</p>\n \n <p>I think something better could be done instead of this dictionary</p>\n</blockquote>\n\n<p>Indeed. Rather than keeping separate dictionaries, consider making a <code>class Newspaper</code> with attributes <code>name: str</code>, <code>link: str</code> and <code>serial: int</code>.</p>\n\n<p>Then after <code>The following Newspapers are available for download</code>, do not hard-code that list; instead loop through your sequence of newspapers and output their serial number and name.</p>\n\n<h2>List literals</h2>\n\n<pre><code>list_paper = list()\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>papers = []\n</code></pre>\n\n<h2>Get default</h2>\n\n<p>Here:</p>\n\n<pre><code>links = tags[i].get('href',None)\n</code></pre>\n\n<p><code>None</code> is the implicit default, so you can omit it. However, it doesn't make sense for you to allow <code>None</code>, because you immediately require a non-null string:</p>\n\n<pre><code>x = re.search(\"^https://vk.com/\", links)\n</code></pre>\n\n<p>so instead you probably want <code>''</code> as a default.</p>\n\n<h2>String interpolation</h2>\n\n<pre><code>'For how many days you need the '+ serial_num[ser_ind]+' paper?'\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'For how many days do you need the {serial_num[ser_ind]} paper?'\n</code></pre>\n\n<h2>Raw transfer</h2>\n\n<pre><code> r = requests.get(link, allow_redirects=True)\n with open(serial_num[ser_ind]+\"_\"+str(date_that_day)+\".pdf\",'wb') as f:\n f.write(r.content)\n</code></pre>\n\n<p>requires that the entire response be loaded into memory before being written out to a file. In the (unlikely) case that the file is bigger than your memory, the program will probably crash. Instead, consider using <code>requests</code>, passing <code>stream=True</code> to your <code>get</code>, and passing <code>response.raw</code> to <code>shutil.copyfileobj</code>. This will stream the response directly to the disk with a much smaller buffer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:28:53.797",
"Id": "242952",
"ParentId": "242951",
"Score": "4"
}
},
{
"body": "<p>Just one contribution from me: you can get rid of <strong>redundant</strong> declarations and make your code lighter. The newspapers should be defined just once and then reused. You are almost there. Build a list of dictionaries (or use a database).</p>\n\n<pre><code># dictionary for newspaper names and their links\nnewspapers = (\n {\"name\": 'Economic_times', 'url': 'https://dailyepaper.in/economic-times-epaper-pdf-download-2020/'},\n {\"name\": 'Times_of_India', 'url': 'https://dailyepaper.in/times-of-india-epaper-pdf-download-2020/'},\n {\"name\": 'Financial_Express', 'url': 'https://dailyepaper.in/financial-express-epaper-pdf-download-2020/'},\n {\"name\": 'Deccan_Chronicle', 'url': 'https://dailyepaper.in/deccan-chronicle-epaper-pdf-download-2020/'},\n {\"name\": 'The_Telegraph', 'url': 'https://dailyepaper.in/the-telegraph-epaper-pdf-download-2020/'},\n {\"name\": 'The_Pioneer', 'url': 'https://dailyepaper.in/the-pioneer-epaper-pdf-download-2020/'},\n {\"name\": 'Business_Line', 'url': 'https://dailyepaper.in/business-line-epaper-pdf-download-2020/'},\n {\"name\": 'Indian_Express', 'url': 'https://dailyepaper.in/indian-express-epaper-pdf-download-2020/'},\n {\"name\": 'Hindustan_Times', 'url': 'https://dailyepaper.in/hindustan-times-epaper-pdf-free-download-2020/'},\n {\"name\": 'The_Hindu', 'url': 'https://dailyepaper.in/the-hindu-pdf-newspaper-free-download/'},\n {\"name\": 'Dainik_Jagran', 'url': 'https://dailyepaper.in/dainik-jagran-newspaper-pdf/'},\n {\"name\": 'Dainik_Bhaskar', 'url': 'https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/'},\n {\"name\": 'Amar_Ujala', 'url': 'https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/'}\n)\nprint(\"The following Newspapers are available for download. Select any of them by giving number inputs - \")\nfor counter, newspaper in enumerate(newspapers, start=1):\n print(f'{counter}. {newspaper[\"name\"]}')\n\nselected_numbers = input('Enter the number for newspapers - ')\n\nprint(\"You selected the following Newspapers:\")\nfor index in selected_numbers.split():\n newspaper_number = int(index)\n newspaper_detail = newspapers[newspaper_number-1]\n print(f\"Number: {newspaper_number}\")\n print(f\"Name: {newspaper_detail['name']}\")\n print(f\"URL: {newspaper_detail['url']}\")\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nThe following Newspapers are available for download. Select any of them by giving number inputs - \n1. Economic_times\n2. Times_of_India\n3. Financial_Express\n4. Deccan_Chronicle\n5. The_Telegraph\n6. The_Pioneer\n7. Business_Line\n8. Indian_Express\n9. Hindustan_Times\n10. The_Hindu\n11. Dainik_Jagran\n12. Dainik_Bhaskar\n13. Amar_Ujala\nEnter the number for newspapers - 1 12 13\nYou selected the following Newspapers:\nNumber: 1\nName: Economic_times\nURL: https://dailyepaper.in/economic-times-epaper-pdf-download-2020/\nNumber: 12\nName: Dainik_Bhaskar\nURL: https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/\nNumber: 13\nName: Amar_Ujala\nURL: https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/\n</pre>\n\n<p>Warning: the code does not check that the input contains valid numbers (use a regex for that), and that all numbers are within the list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T23:37:18.867",
"Id": "242978",
"ParentId": "242951",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242952",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T13:19:50.150",
"Id": "242951",
"Score": "3",
"Tags": [
"python",
"beginner",
"web-scraping"
],
"Title": "Web Scraping Newspapers"
}
|
242951
|
<p>Inspired by MIT OCW (6.006)'s lecture on BSTs, I implemented them with the slight tweak where an element has to satisfy the "k-minute check" before insertion. If its value is within <em>k</em> of any other existing value in the node, the node should <strong>not</strong> be inserted. <em>k</em> is a positive integer parameter provided upon creation of the BST.</p>
<p>Apart from that I implemented the standard BST functionality of <code>insert</code>, <code>find</code>, <code>delete_min</code>, <code>remove</code>.</p>
<p>Things to critique:</p>
<ol>
<li>I think my program is right (the tests say so?). However, testing can certainly be improved! How do I make better unit test cases?</li>
<li>Does the code follow PEP/Pythonic guidelines? What can I do to make my code closer to production code quality?</li>
<li>I made a function to print out the BST and use it as a visual means of debug, if need be. The problem is this then facilitates needing a debug flag (which Python doesn't really have). I ended up not really using it since the unit testing was sufficient in this case. Is a visual means of debugging like this strictly discouraged? Can it be implemented in unit testing?</li>
</ol>
<p>Here's my implementation code <code>schedule.py</code>:</p>
<pre><code>PRINT_ENABLED = False #this may not be the best approach to turn on/off flag for printing to stdout. Not production code material.
class Node():
"""
Representation of a Node in a BST
"""
def __init__(self, val : int):
# Create a leaf node with a given value
self.val = val
self.disconnect() # this is neat
def disconnect(self):
self.left = self.right = self.parent = None
class BST():
def __init__(self, k_value, current_time):
self.root = None
self.k = k_value
self.current_time = current_time
super().__init__()
def k_min_check_passed(self, booked : int, requested : int) -> bool:
"""
Check if the requested time value is a valid time entry (> current time) within k min of booked request's time value
Return false (failure) if it is, and true if not.
"""
if requested <= self.current_time or (requested <= booked + self.k and requested >= booked - self.k):
return False
else:
return True
def insert(self, t : int) -> Node:
"""
Insert a node with value t into the tree, returning a ptr to the leaf
If the k minute check is violated, don't insert & return None
"""
new_node = Node(t)
if self.root is None:
self.root = new_node
else:
curr = self.root
while True:
val = curr.val
# Check it the k-min invariant is held for every node.
# If it fails, there's no point in inserting.
if self.k_min_check_passed(val, t) == False:
return None
if t < val:
if curr.left is None:
curr.left = new_node
new_node.parent = curr
break
curr = curr.left
else:
if curr.right is None:
curr.right = new_node
new_node.parent = curr
break
curr = curr.right
return new_node
def find(self, t : int) -> Node:
"""
Search for a key in the tree and return the node. Return None otherwise
"""
node = self.root
while node is not None:
val = node.val
if t == val:
return node
elif t < val:
node = node.left
else:
node = node.right
return None
def delete_min(self) -> Node:
"""
Delete the minimum key. And return the old node containing it.
"""
old = self.root
while old is not None:
if old.left is None:
if old.parent is not None:
old.parent.left = old.right
else:
#remove root
self.root = old.right
if old.right is not None:
old.right.parent = old.parent
old.disconnect()
break
old = old.left
return old
def remove(self, t : int) -> Node :
"""
Given a node value t, removes the node
from the BST, restructuring the tree
in the case where the node has children.
If the node to be deleted has both non-null children,
then the node's left child becomes the node's parent's
new child, and the node's right child subtree becomes
the left child's rightmost descendant.
Returns the deleted node.
If the node to be deleted does not exist, returns None
"""
node = self.find(t)
if node is None:
return None
# Case 1: node has 2 children
if node.left is not None and node.right is not None:
# find right most node of the current node's left child's subtree
rleaf = node.left
while rleaf.right is not None:
rleaf = rleaf.right
# then swap the leaf and the current node values
temp = rleaf.val
rleaf.val = node.val
node.val = temp
# delete the leaf node we found (that has current node's value)
# and make its left child the right child of its parent
if rleaf.parent is not None:
# determine the leaf's relationship with its parent
rleaf_is_left_child = (rleaf == rleaf.parent.left)
if rleaf_is_left_child:
rleaf.parent.left = rleaf.left
else:
rleaf.parent.right = rleaf.left
if rleaf.left is not None:
rleaf.left.parent = rleaf.parent
rleaf.disconnect()
else:
# check elif syntax implications here
if node.parent is None:
# remove the root and appoint the new root
# Case 2: node has only right child
if node.right is None and node.left is None:
self.root = None
elif node.left is None:
node.right.parent = None
self.root = node.right
elif node.right is None:
node.left.parent = None
self.root = Node.left
node.disconnect()
else:
# determine the nodes's relationship with its parent
node_is_left_child = (node == node.parent.left)
# Case 2: node has only right child
if node.left is None:
if node_is_left_child:
node.parent.left = node.right
else:
node.parent.right = node.right
if node.right is not None:
node.right.parent = node.parent
node.disconnect()
# Case 3: node has only left child
elif node.right is None:
if node_is_left_child:
node.parent.left = node.left
else:
node.parent.right = node.left
if node.left is not None:
node.left.parent = node.parent
node.disconnect()
return node
def print_BST(root : Node):
"""
Given a pointer to a root node of a BST (sub)Tree,
Prints the level order traversal of that subtree as a list of nodes' values.
Nodes that are null are incdicated as N.
If a node was null in the previous level, it's children will not exist
and the nodes are not considered in the list.
"""
print ('[', end=' ')
q = []
q.append(root)
while q:
front = q.pop(0)
# break
if front is None:
print ('N', end=' ')
else:
print(front.val, end=' ')
q.append(front.left)
q.append(front.right)
print(']\n')
def test_printing():
root = Node(3)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.right.left = Node(4)
print_BST(root)
if __name__ == "__main__":
if PRINT_ENABLED:
test_printing()
</code></pre>
<p>And my unit test code <code>test.py</code>:</p>
<pre><code>import unittest
import sys, os
sys.path.append(os.path.abspath('..')) #this was a workaround I found to avoid ModuleNotFoundErrors, but now I need to mandatorily run tests from ../
from runway_scheduling.src.schedule import BST, Node
class TestBST(unittest.TestCase):
def setUp(self):
super().setUp()
TEST_K_VAL = 1
CURRENT_TIME = 0
self.tree = BST(TEST_K_VAL, CURRENT_TIME)
self.nums = [3, 1, 5, 9, 7]
for t in self.nums:
self.tree.insert(t)
self.rt_node = self.tree.root
def test_k_min_check(self):
vals = self.nums
# 2 things: 1) I don't like writing magic numbers, is there a better way to do this?
# 2) I only test the functionality of the k-min check over here
# I test whether insert checks it each time (for all nodes) in insert. Is this a good approach
self.assertFalse(self.tree.k_min_check_passed(vals[0], -1))
self.assertFalse(self.tree.k_min_check_passed(vals[3], 10))
self.assertTrue(self.tree.k_min_check_passed(vals[-1], 5))
def test_insert(self):
self.assertEqual(self.rt_node.val, self.nums[0]) #check root (initially None) has been correctly inserted
self.assertEqual(self.rt_node.left.val, self.nums[1]) #check left node
self.assertEqual(self.rt_node.left.right, None) #is this test necessary?
self.assertEqual(self.rt_node.right.right.left.val, self.nums[-1]) #Again, I don't think this is a "good" test
# check k min property is applied correctly
self.assertIsNone(self.tree.insert(4))
self.assertIsNotNone(self.tree.insert(11))
def test_find(self):
self.assertEqual(self.tree.find(7), self.rt_node.right.right.left)
self.assertEqual(self.tree.find(4), None)
def test_delete_min(self):
min_key = self.rt_node.left.val
self.assertEqual(self.tree.delete_min().val, min_key) #we should have got back the deleted node
self.assertEqual(self.rt_node.left, None) #the pointer to left child should have been modified
old_root_val = self.rt_node.val
old_root_right_val = self.rt_node.right.val
self.assertEqual(self.tree.delete_min().val, old_root_val) #handled corner case of root being minimum
self.assertEqual(self.tree.root.val, old_root_right_val) #check the root has been updated.
def test_remove(self):
"""
Testing the arbitrary deletion of any specified node
The following test cases exist:
1) Node to be deleted does not exist
2) Node has 2 children:
a) Node is parent's left or right child
b) Node is the root
3) Node has Left Child Only:
a) Node is parent's left child
b) Node is parent's right child
c) Node is the root
4) Node has Right Child Only:
a) Node is parent's left child
b) Node is parent's right child
c) Node is the root
5) Node has no Children
6) Only node in the tree
"""
# CASE 1)
NON_EXISTANT_VAL = 100
self.assertIsNone(self.tree.remove(NON_EXISTANT_VAL))
# CASE 2b)
# 1 (nums[1]) should be the new root
self.tree.remove(3)
self.assertEqual(self.tree.root.val, 1)
# CASE 3b)
self.assertEqual(self.tree.remove(self.nums[3]).val, 9)
self.assertEqual(self.tree.root.right.right.val, 7)
# CASE 4c)
self.tree.remove(1)
self.assertEqual(self.tree.root.val, 5)
# CASE 5, 4b)
self.tree.remove(7)
self.assertIsNone(self.tree.root.left)
# CASE 2a)
# insert two children with subtrees
self.tree.insert(50)
self.tree.insert(10)
self.tree.insert(20)
self.tree.insert(30)
self.tree.insert(70)
self.tree.insert(65)
# The tree should now be:
# [{5}, {N, 50}, {10, 70}, {N, 20, 65, N}, {N, 30, N, N} ]
# (when read as level order traversal)
self.tree.remove(50)
self.assertEqual(self.tree.root.right.val, 30)
# CASE 4a)
self.tree.remove(10)
self.assertEqual(self.tree.root.right.left.val, 20)
# CASE 3a,c)
self.tree.remove(5)
self.tree.remove(70)
self.tree.remove(65)
self.tree.remove(20)
self.assertIsNone(self.tree.root.right)
# CASE 6
self.tree.remove(30)
self.assertIsNone(self.tree.root)
def tearDown(self):
self.nums = []
while (self.tree.root is not None):
self.tree.delete_min()
super().tearDown()
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Any feedback is welcome, thank you!</p>
<p>EDIT: My directory structure is something like: </p>
<pre><code>../
| - src : contains schedule.py
| - test: contains test.py
</code></pre>
<p><a href="https://i.stack.imgur.com/71ygS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/71ygS.png" alt="enter image description here"></a></p>
<p>The <code>ModuleNotFoundError</code>s occured when I didn't add that line, and imported <code>BST</code> and <code>Node</code> from <code>runway_scheduling.src.schedule</code>. There's a few similar Qs on SO, so I'm going over them rn to see if they apply but that was a quick fix I had made - something I'd like to remedy. I tried adding <code>__init__.py</code> files, but that didn't really help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:37:51.463",
"Id": "476834",
"Score": "0",
"body": "Please edit your question to show a full directory tree for your project. Something about your module structure is fishy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:49:29.600",
"Id": "476838",
"Score": "0",
"body": "Use [tox](https://pypi.org/project/tox/) or [nox](https://pypi.org/project/nox/) with a [setuptools package](https://packaging.python.org/tutorials/packaging-projects/). Not the silly `sys.path.append(os.path.abspath('..'))` hack."
}
] |
[
{
"body": "<h2>Debug prints</h2>\n\n<blockquote>\n <p>I made a function to print out the BST and use it as a visual means of debug, if need be. The problem is this then facilitates needing a debug flag (which Python doesn't really have). I ended up not really using it since the unit testing was sufficient in this case. Is a visual means of debugging like this strictly discouraged?</p>\n \n <p>[...]</p>\n \n <p>this may not be the best approach to turn on/off flag for printing to stdout. Not production code material.</p>\n</blockquote>\n\n<p>Indeed! This is the perfect use case for the <a href=\"https://docs.python.org/3.8/library/logging.html#module-email\" rel=\"nofollow noreferrer\">logging</a> module. Leave all of your print statements in but convert them to logging calls at the debug level. Then, by changing only the level of the logger you will be able to show or omit that content.</p>\n\n<h2>Non-init attribute set</h2>\n\n<pre><code>self.disconnect() # this is neat\n</code></pre>\n\n<p>The problem with this approach is that there are attributes being set that are not done directly in the <code>__init__</code> function. Some linters, including PyCharm's built-in linter, will call this out. Consider moving initialization of those three attributes to the constructor, with type hints indicating what actually goes in there - possible <code>Optional['Node']</code>.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code> if requested <= self.current_time or (requested <= booked + self.k and requested >= booked - self.k):\n return False\n else:\n return True\n</code></pre>\n\n<p>can be (if I've done my boolean algebra correctly)</p>\n\n<pre><code>return (\n requested > self.current_time and not (\n -self.k <= requested - booked <= self.k\n )\n)\n</code></pre>\n\n<h2>Unit tests</h2>\n\n<p>You ask:</p>\n\n<blockquote>\n <p>Are the unit testcases I came up with satisfactory, or need more work?</p>\n</blockquote>\n\n<p>About this:</p>\n\n<pre><code>sys.path.append(os.path.abspath('..')) #this was a workaround I found to avoid ModuleNotFoundErrors, but now I need to mandatorily run tests from ../ \n</code></pre>\n\n<p>That's spooky and should be unnecessary. Normal unit test discovery should work fine as long as you run from the \"sources-root\" of your project. Incidentally, <code>src</code> as a module name is a sign that your module paths are wonky. <code>BST</code> should be in <code>runway_scheduling.schedule</code>, and <code>TestBST</code> should be in something like <code>runway_scheduling/tests/test_bst.py</code>. I can't comment any further without seeing your directory structure.</p>\n\n<p>You also write:</p>\n\n<blockquote>\n <p>I don't like writing magic numbers, is there a better way to do this?</p>\n</blockquote>\n\n<p>Tests are somewhat of an exception in my mind. Having everything be explicit and in-place is actually a good thing. The only thing I can suggest, although I don't immediately see where it would be applicable, is <a href=\"https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests\" rel=\"nofollow noreferrer\">subTest</a> - you can find code that is repetitive with only numerical changes, factor out those numerical changes to tuples, and write a parametric loop with a subtest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T16:30:48.037",
"Id": "476823",
"Score": "0",
"body": "1) The logging option seems to be exactly what I was looking for! 2) Interesting, and I didn't consider this. I think i will add the None initializations to the __init__ function, and keep the disconnect as a member function which I use anyways for removal of nodes. I was using VSCode, so I guess my linter didn't complain. 3) That definitely looks cleaner, and something I can get in the habit of editing such code. \nAwesome, thanks for the great feedback! Are the unit testcases I came up with satisfactory, or need more work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:14:11.163",
"Id": "476827",
"Score": "1",
"body": "_I was using VSCode, so I guess my linter didn't complain_ - indeed; professionally, I use PyCharm because I find its static analysis to be more thorough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:15:06.017",
"Id": "476828",
"Score": "0",
"body": "_That definitely looks cleaner_ - Thanks; I just edited it to clean it up even further with the use of a double-inequality. Hopefully it's still equivalent. Good thing you have unit tests..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:26:48.610",
"Id": "476830",
"Score": "1",
"body": "_Are the unit testcases I came up with satisfactory, or need more work?_ - edited. Overall they're quite good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:35:00.083",
"Id": "476832",
"Score": "1",
"body": "p.s. a more quantitative answer to this is \"run a coverage tool\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:57:19.310",
"Id": "476956",
"Score": "1",
"body": "I improved my directory structure and unittest discover (which I didn't know existed, lol) works, so thanks!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:49:34.333",
"Id": "242954",
"ParentId": "242953",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242954",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:34:59.267",
"Id": "242953",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"binary-search-tree"
],
"Title": "BST implementation (MIT OCW Runway scheduling problem) + Unit Testing in Python3"
}
|
242953
|
<p>This is a fully functional code that i have just completed today. I just want to know how efficient is this. and how could i improve it or if theres any bugs that i have miss out.</p>
<pre><code>import os
from AskUser import ask_user as As
from random import randint
#initialising the board
class Board():
def __init__(self):
self.boxs = [' '] * 10
def display(self):
print(f' {self.boxs[1]} | {self.boxs[2]} | {self.boxs[3]} \n---------------')
print(f' {self.boxs[4]} | {self.boxs[5]} | {self.boxs[6]} \n---------------')
print(f' {self.boxs[7]} | {self.boxs[8]} | {self.boxs[9]} ')
def update_box(self, box_num, key):
def valid_position(box_num, key):
return 0 < box_num < 10 and self.boxs[box_num] == ' '
while not valid_position(box_num, key):
box_num = As("Please enter a valid position: ", int)
self.boxs[box_num] = key
def win_solution(self,key):
if (self.boxs[1] == key and self.boxs[2] == key and self.boxs[3] == key) or\
(self.boxs[4] == key and self.boxs[5] == key and self.boxs[6] == key) or\
(self.boxs[7] == key and self.boxs[8] == key and self.boxs[9] == key) or\
(self.boxs[1] == key and self.boxs[4] == key and self.boxs[7] == key) or\
(self.boxs[2] == key and self.boxs[5] == key and self.boxs[8] == key) or\
(self.boxs[3] == key and self.boxs[6] == key and self.boxs[9] == key) or\
(self.boxs[1] == key and self.boxs[5] == key and self.boxs[9] == key) or\
(self.boxs[3] == key and self.boxs[5] == key and self.boxs[7] == key):
return True
return False
def tie_game(self):
count = 0
for i in self.boxs:
if i != ' ':
count += 1
return count == 9
def reset_board(self):
self.boxs = [' '] * 10
board = Board()
Turn = randint(0,1)
#Introduction
def clear_screen():
os.system('clear')
print('Welcome to the TicTacToe simulator')
#Displays the board
board.display()
while True:
if Turn == 1:
#Updates the board after input
clear_screen()
#For X Player
x_move = As('X, Choose a position between 1 - 9 : ',int)
#Put x input into the board
board.update_box(x_move, "X")
Turn = 0
#Updates the board after input
clear_screen()
#Check for win for X or tie
if board.win_solution("X"):
print('Congrats, X you have won')
Turn = 3
elif board.tie_game():
print('This is a tie game')
Turn = 3
else:
pass
elif Turn == 0:
clear_screen()
#For O Player
o_move = As('O, Choose a position between 1 - 9 : ',int)
#Put o input into the board
board.update_box(o_move, "O")
Turn = 1
#Updates the board after input
clear_screen()
#Check for win for O or tie
if board.win_solution("O"):
print('Congrats, O you have won')
Turn = 3
elif board.tie_game():
print('This is a tie game')
Turn = 3
else:
pass
else:
p_again = As('Do you want to play again? (Y/N) : ').upper()
if p_again == "Y":
board.reset_board()
Turn = randint(0,1)
continue
else:
exit('Game is over')
</code></pre>
<p>This is the AskUser function</p>
<h1>Function to check for the user input</h1>
<pre><code>def ask_user(message, type_= str, valid=lambda x: True, invalid_message="Invalid"):
while True:
try:
user_input = type_(input(message))
except (ValueError, TypeError):
print("Invalid input")
continue
if valid(user_input):
return user_input
else:
print(invalid_message)
</code></pre>
|
[] |
[
{
"body": "<h2>Matrix indexing</h2>\n\n<p>The <code>display</code> function is a handful. It's often better to use a matrix library like <code>numpy</code> to allow better indexing features. For instance,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\none_thru_nine = list(range(1,10))\nprint(one_thru_nine)\nmatrix = np.array(one_thru_nine).reshape(3,3)\nprint(matrix)\nprint(matrix[0, 1])\nprint(matrix[1, 1])\nprint(matrix[2, 2])\n</code></pre>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>[1, 2, 3, 4, 5, 6, 7, 8, 9]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n2\n5\n9\n</code></pre>\n\n<p>(Disclaimer: <code>np.array(one_thru_nine).reshape(3,3)</code> is not really an ideal way of initializing <code>numpy</code> arrays, it's just for demonstration purposes.)</p>\n\n<p>Of course, do beware of <a href=\"https://en.wikipedia.org/wiki/Zero-based_numbering\" rel=\"nofollow noreferrer\">zero-indexing</a>. </p>\n\n<h2>Magic numbers</h2>\n\n<p>As a rule of thumb, avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>. Try not to put raw integers into code. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return 0 < box_num < 10\n</code></pre>\n\n<p>will be more readable as </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>min_boxes, max_boxes = 0, 10\nreturn min_boxes < box_num < max_boxes\n</code></pre>\n\n<p>Similarly, I can understand what <code>Turn=3</code> does, but it's unintuitive.</p>\n\n<h2>If-Else statements</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>else:\n pass\n</code></pre>\n\n<p>is redundant. If you don't have anything to do when <code>if</code> and <code>elif</code> conditions fail, you don't have to add the <code>else</code> statement altogether -- unlike some other languages.</p>\n\n<p>That is, you can just do: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n if condition_one:\n do_something()\n elif condition_two:\n do_something_else()\n</code></pre>\n\n<h2>Class declaration</h2>\n\n<p>You don't need to put parentheses next to class declarations if you are not inheriting from a super class. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Board():\n def __init__(self):\n</code></pre>\n\n<p>can just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Board:\n def __init__(self):\n</code></pre>\n\n<h2>Casing</h2>\n\n<p>As a general rule of thumb, in classes are in <a href=\"https://techterms.com/definition/pascalcase\" rel=\"nofollow noreferrer\">PascalCase</a> and everything else (modules, variables, functions, methods) are in <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a>. As such, <code>from AskUser import ask_user as As</code> should be reformatted as <code>from ask_user import ask_user as as_as</code> or something similar.</p>\n\n<p>Similarly, things like <code>Turn</code> should be <code>turn</code>. </p>\n\n<h2>Wrap your module with <code>main</code></h2>\n\n<p>In general, if you are not declaring globals, and you declare functions that you will actually call as main (perhaps you're familiar with <code>C</code> or <code>Java</code>?) you should wrap them in a statement of</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n board = Board()\n turn = randint(0,1) ... \n</code></pre>\n\n<p>If you don't get into the habit of this, you'll end up executing code you don't want to when you're just importing code from other modules.</p>\n\n<h2>Others</h2>\n\n<ul>\n<li>I don't see the use of <code>valid</code> and <code>invalid_message</code> anywhere? </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T14:15:55.257",
"Id": "476922",
"Score": "0",
"body": "wow thanks for the headers. the valid and invalid_message is to check if the data that is imputed correspond to what i want which in this case must be a number as i added , int in the statement which required the user to input the array index for the tictactoe board. but ofc i could change the type_ = int instead of str in the Ask_User function but i imported it from the last project which i haven't change it yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T14:19:53.050",
"Id": "476923",
"Score": "0",
"body": "Saying `valid=lambda x:True` will always run `if valid(user_input)`. Try running your code with wrong inputs. You will never print `invalid_message`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T14:30:07.987",
"Id": "476926",
"Score": "0",
"body": "it will print 'invalid input' if i key in a alphabet as i did this at the end of the statement x_move = As('X, Choose a position between 1 - 9 : ',int). the int would change the type_ into int. and so if non number is key in, it will print 'invalid input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T14:35:37.283",
"Id": "476927",
"Score": "0",
"body": "you mind helping me checking my new code in GitHub it has a single player feature. not really an AI but its able to play on its own. https://github.com/ShreddedPumpkin/Tic-Tac-Toe.git"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T14:06:08.523",
"Id": "243008",
"ParentId": "242955",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:54:09.460",
"Id": "242955",
"Score": "1",
"Tags": [
"python",
"tic-tac-toe"
],
"Title": "2 player CLI Tic-Tac-Toe game in python"
}
|
242955
|
<p>I've self-taught myself Python and have recently started learning tkinter. I made a simple stopwatch program and I wanted to know if the code is clean and written in a way that the code works efficiently. I would highly appreciate any suggestions on how to improve my code! Thank you!</p>
<pre><code>from tkinter import *
import time
root = Tk()
numberOfSeconds = 0
def counting():
global numberOfSeconds
global stopCounting
if stopCounting == False:
numberOfSeconds += 1
seconds.config(text=str(numberOfSeconds))
seconds.after(1000, counting)
elif stopCounting == True:
stopCounting = False
numberOfSeconds = 0
seconds.config(text=str(numberOfSeconds))
def start():
global stopCounting
stopCounting = False
stopButton.config(state=NORMAL)
seconds.after(1000, counting)
def stop():
global stopCounting
stopButton.config(state=DISABLED)
stopCounting = True
seconds = Label(text=str(numberOfSeconds))
startButton = Button(text="Start", command=start)
stopButton = Button(text="Stop", command=stop, state=DISABLED)
seconds.grid(row=0, column=0, columnspan=2)
startButton.grid(row=1, column=0)
stopButton.grid(row=1, column=1)
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<h2>Globals</h2>\n\n<p>Generally speaking it's not a good idea to use globals like this. It harms re-entrance. What if you want to support two stopwatches at once, either in one UI or as a web server? Having globals like this will prevent that.</p>\n\n<p>It also harms testability. It is more difficult to test methods that rely on global state than it is to test methods that are self-contained, having state passed to them either in an object context (<code>self</code>) or as method parameters.</p>\n\n<p>One way to get around this is make a class with attributes <code>number_of_seconds</code> and <code>is_counting</code> (which I find would be more intuitive than <code>stop_counting</code>).</p>\n\n<h2>Booleans</h2>\n\n<p>This block:</p>\n\n<pre><code>if stopCounting == False:\n numberOfSeconds += 1\n seconds.config(text=str(numberOfSeconds))\n seconds.after(1000, counting)\nelif stopCounting == True:\n stopCounting = False\n numberOfSeconds = 0\n seconds.config(text=str(numberOfSeconds))\n</code></pre>\n\n<p>is more easily expressed as</p>\n\n<pre><code>if stopCounting:\n stopCounting = False\n numberOfSeconds = 0\n seconds.config(text=str(numberOfSeconds))\nelse:\n numberOfSeconds += 1\n seconds.config(text=str(numberOfSeconds))\n seconds.after(1000, counting)\n</code></pre>\n\n<h2>Variable names</h2>\n\n<p>They should be lower_snake_case, i.e. <code>start_button</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:02:59.817",
"Id": "476853",
"Score": "0",
"body": "Thank you so much! However, I don't really understand why I can't be using globals that way, is there any chance you could explain it to me a little bit more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:05:19.113",
"Id": "476854",
"Score": "0",
"body": "I've added a little more explanatory text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:05:47.883",
"Id": "476855",
"Score": "0",
"body": "It's not that you _can't_ do it (you already are); it's that it makes your life more difficult when you have non-trivial application development to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:11:00.813",
"Id": "476856",
"Score": "0",
"body": "Ah, ok, thank you so much for your help!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:16:50.810",
"Id": "242957",
"ParentId": "242956",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242957",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:54:20.300",
"Id": "242956",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tkinter"
],
"Title": "Simple stopwatch program with tkinter"
}
|
242956
|
<p>Beginner functional programmer... (but not beginner programmer)</p>
<p>Currently, I have the following code:</p>
<pre class="lang-hs prettyprint-override"><code>import Control.Monad (mapM_)
main = gridMaker 3
gridMaker :: Int -> IO ()
{-Creates a nxn matrix filling the lower triangle with "O"'s
and filling the rest with "X"s
Example:
O --- X --- X
O --- O --- X
O --- O --- O
-}
gridMaker gridSize =
-- Creates the indicators
let startingIter = 1
indicators = indicatorListCreator gridSize startingIter
-- Print each indicator out to IO
in mapM_ linePrinter indicators
indicatorListCreator :: Int -> Int -> [[String]]
{- Build the indicators of
[["O", "X", "X"],["O", "O", "X"] ... and so forth.
Recursively determines how many iterations we've been through,
and determines how many "X"s and "O"s we should have
per each line. -}
indicatorListCreator gridLen iterNum
| iterNum > gridLen = []
| otherwise =
let itersRemaining = gridLen - iterNum
indicator = replicate iterNum "O" ++
replicate itersRemaining "X"
in
indicator: indicatorListCreator gridLen (iterNum + 1)
linePrinter :: [String] -> IO ()
{- Takes the indicators and prints each line accordingly. -}
linePrinter [indicator1, indicator2, indicator3] =
let between = " --- "
outString = indicator1 ++ between ++
indicator2 ++ between ++
indicator3
in putStrLn outString
linePrinter _ = error"Stupidly hardcoded to only show 3x3"
</code></pre>
<p>Running and compiling this code results in:</p>
<pre class="lang-bsh prettyprint-override"><code>O --- X --- X
O --- O --- X
O --- O --- O
</code></pre>
<p>Some of my thoughts...</p>
<ul>
<li>Is it possible to build indicatorListCreator out of folds?</li>
<li>How can I circumvent hardcoding linePrinter</li>
<li>Is this optimal?</li>
<li>Where should I improve on coding conventions / style?</li>
<li>Any other glaring shortcomings? </li>
</ul>
<p>Thank you in advance! </p>
|
[] |
[
{
"body": "<p>I like that you are trying to not use explicit recursions everywhere. That being said, there are a few standard functions that we could use to get a code similar to the following.</p>\n\n<pre><code>import Data.List(intercalate)\n\ngrid :: Int -> [String]\ngrid n = [intercalate \" --- \" . take n . drop (n-k) $ osxs | k <- [1..n]]\n where osxs = replicate n \"O\" ++ replicate n \"X\"\n\nprintGrid :: Int -> IO ()\nprintGrid = putStr . unlines . grid\n</code></pre>\n\n<p>Most notably, <code>Data.List.intercalate</code> can be used to generalize your <code>linePrinter</code>, and <code>unlines</code> helps us avoid <code>mapM_</code>.</p>\n\n<hr>\n\n<p>If you are writing a game, then a <code>Data.Map.Strict.Map</code> could be useful for storing the board's current values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T13:32:44.263",
"Id": "476919",
"Score": "0",
"body": "Thank you so much!\nAmazing how using the right functions can shorten code length by a huge chunk.\n`take n . drop (n-k)` is super neat and clever!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T16:54:24.683",
"Id": "242960",
"ParentId": "242959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242960",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:43:33.107",
"Id": "242959",
"Score": "1",
"Tags": [
"beginner",
"haskell",
"functional-programming"
],
"Title": "Basic tic-tac-toe matrix in Haskell"
}
|
242959
|
<p><strong>The Requirements:</strong></p>
<p>List the expensable items sorted by date and location given two variables: 'categories' and 'expenses'. The Categories variable provides the following information in order: Category ID, Category Name, and whether the category is expensable (Y/N). The Expenses variable provides the following information in order: Location, Date, Item Description, Cost, and Category Code. Each line should be displayed in the format "DATE: LOCATION - $TOTAL". </p>
<p>I put it together in a single JavaScript executable. </p>
<p><strong>The code:</strong></p>
<pre><code>// Input Values
var categories = "CFE,Coffee,Y\nFD,Food,Y\nPRS,Personal,N";
var expenses = "Starbucks,3/10/2018,Iced Americano,4.28,CFE\nStarbucks,3/10/2018,Nitro Cold Brew,3.17,CFE\nStarbucks,3/10/2018,Souvineer Mug,8.19,PRS\nStarbucks,3/11/2018,Nitro Cold Brew,3.17,CFE\nHigh Point Market,3/11/2018,Iced Americano,2.75,CFE\nHigh Point Market,3/11/2018,Pastry,2.00,FD\nHigh Point Market,3/11/2018,Gift Card,10.00,PRS";
var AcceptableExpenses = GetAcceptableExpenses(GetAcceptableCategories(categories), expenses)
AcceptableExpenses.forEach (AcceptableExpense =>{
console.log(AcceptableExpense.join(''))
})
function GetAcceptableExpenses(AcceptableCategories, expenses){
var ExpensesList = expenses.split("\n")
var AcceptableExpenseTotals = []
var categoryIndex = 4
var venderIndex = 0
var dateIndex = 1
var priceIndex = 3
var venderDate = []
ExpensesList.forEach(expense => {
var expenseItemized = expense.split(',')
if ((categoryIndex < expenseItemized.length) && IsExpenseItemAcceptable(AcceptableCategories, expenseItemized[categoryIndex])){
venderDate = [expenseItemized[dateIndex], ": ", expenseItemized[venderIndex], " - $"].join('')
if ( IsVenderDateIncluded(AcceptableExpenseTotals, venderDate) ){
UpdatePrice(AcceptableExpenseTotals, venderDate, expenseItemized[priceIndex] )
}
else{
AcceptableExpenseTotals.push([venderDate, expenseItemized[priceIndex] ])
}
}
})
return AcceptableExpenseTotals
}
function IsVenderDateIncluded(AcceptableExpenseTotals, venderDate){
var venderDateIndex = 0
var IsIncluded = false
AcceptableExpenseTotals.forEach( AcceptableExpenseTotal =>{
if (AcceptableExpenseTotal[venderDateIndex] === venderDate){
IsIncluded = true
}
})
return IsIncluded
}
function UpdatePrice(AcceptableExpenseTotals, venderDate, price ){
var venderDateIndex = 0
var priceIndex = 1
AcceptableExpenseTotals.forEach( AcceptableExpenseTotal =>{
if (AcceptableExpenseTotal[venderDateIndex] === venderDate){
AcceptableExpenseTotal[priceIndex] = parseFloat( price) + parseFloat(AcceptableExpenseTotal[priceIndex])
return
}
})
}
function IsExpenseItemAcceptable(AcceptableCategories, category ){
var IsAcceptable = false
AcceptableCategories.forEach(AcceptableCategory => {
if (AcceptableCategory === category){
IsAcceptable = true
}
})
return IsAcceptable
}
function GetAcceptableCategories(categories){
var categoryList = categories.split("\n")
var AcceptableCategory = []
for (i = 0; i < categoryList.length; i++){
var categoryData = categoryList[i].split(',');
var locationOf_IsExpensible = 2;
var locationOf_Category = 0;
if (locationOf_IsExpensible < categoryData.length ){
if (categoryData[locationOf_IsExpensible]==="Y"){
AcceptableCategory.push(categoryData[locationOf_Category])
}
}
}
return AcceptableCategory
}
</code></pre>
|
[] |
[
{
"body": "<p>This code is a decent start, as it uses ES6 features like arrow functions. However it could take advantage of many Javascript features - e.g. <code>IsExpenseItemAcceptable</code> could be reduced to a single line using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>Array.includes()</code></a>. Additionally, the index variables can be eliminated using the ES6 feature <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">Destructuring assignment</a> - specifically <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring\" rel=\"nofollow noreferrer\">array destructuring</a>.</p>\n<p>Instead of lines like</p>\n<blockquote>\n<pre><code>var expenseItemized = expense.split(',')\n\nif ((categoryIndex < expenseItemized.length) && IsExpenseItemAcceptable(AcceptableCategories, expenseItemized[categoryIndex])){\n</code></pre>\n</blockquote>\n<p>Destructuring assignment can greatly simplify this to something like:</p>\n<pre><code>const [vendor, date, item, price, category] = expense.split(','); \nif (category && IsExpenseItemAcceptable(AcceptableCategories, category)){\n</code></pre>\n<p>Not only is that condition shorter, it doesn't require the use of the index and is more readable (and a typo on the word "<em>vendor</em>" was fixed).</p>\n<p>In the example above <code>const</code> was used instead of <code>var</code>. It is recommended that <code>const</code> be the default keyword for initializing variables. If assignment is required, then use <code>let</code>.</p>\n<p>The function <code>GetAcceptableCategories</code> could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>Array.reduce()</code></a>, similar to <code>Array.forEach()</code>.</p>\n<p>The data structure could be changed from an array to a plain object - i.e. <code>{}</code> to provide a mapping of vendor and date combinations to prices. This would allow the elimination of the functions <code>updatePrice</code> and <code>IsVenderDateIncluded</code> because the loop could be simplified to:</p>\n<pre><code>if (category && IsExpenseItemAcceptable(AcceptableCategories, category)){\n const vendorDate = [date, ": ", vendor, " - $"].join('')\n if (vendorDate in AcceptableExpenseTotals) {\n AcceptableExpenseTotals[vendorDate] += parseFloat(price);\n }\n else{\n AcceptableExpenseTotals[vendorDate] = parseFloat(price);\n }\n}\n</code></pre>\n<p>This would require reformatting the output - e.g.</p>\n<pre><code>for (const [vendorDate, price] of Object.entries(AcceptableExpenses)) {\n console.log(vendorDate, price);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T16:27:11.907",
"Id": "477716",
"Score": "0",
"body": "Thanks for your help. I know the checkmark and point should be enough thanks but I wanted to preface this note with thanks before I bring up the smallest of notes: I looked up vender and vendor because while I am a terrible speller it was not actually my spelling... So it turns out there are 2 words, vender and vendor. From what I gather vender is retail and vendor is manufacture supply so in this case vender was probably the correct choice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T16:28:14.057",
"Id": "243112",
"ParentId": "242965",
"Score": "1"
}
},
{
"body": "<p>1) I would like to add that the solution is not using object-oriented.\nWhich would add alot to the readability and extensibility of the code.\nI think practically its a better as a solution then \"free style - incremental programming\".</p>\n\n<p>The main object can be for example:\n- ExpensesSheet or ExpensesCalculator\n- You can pass proper formatted input object into it\n- You can set up filters\n- You can execute the query</p>\n\n<p>2) You should consider translating long statements into functions that can be read as English</p>\n\n<p>3) ExceptableCategories can be a map instead of an array to lookup isCategoryAcceptable in O(1)</p>\n\n<p>4) var is old and considered bad way to define variables - js linters will recommend using const or let</p>\n\n<p>i.e.: Here's a translation of your code to object-oriented style.</p>\n\n<p>Note: To hide the private functions from the class interface I buried them as functions inside functions, that is not a style recommendation, just a solution I picked on the way. </p>\n\n<pre><code>class ExpensesCalculator {\n constructor(categories, expenses) {\n this.expensibleCateogries = new Map();\n this.expensibleExpenses = {};\n\n initExpensibleCategories(this, categories);\n initExpensibleExpenses(this, expenses);\n calculateTotal(this);\n\n function initExpensibleCategories(_this, categories) {\n categories.split('\\n').forEach(category => {\n const [categoryID, categoryName, isExpensable] = category.split(',');\n\n if(isExpensable) {\n _this.expensibleCateogries.set(categoryID, categoryName);\n }\n })\n }\n\n function initExpensibleExpenses(_this, expenses) {\n expenses.split('\\n').forEach(expense => {\n const [vendor, date, item, price, category] = expense.split(',');\n if (_this.expensibleCateogries.has(category)) {\n if(!_this.expensibleExpenses[date]) {\n _this.expensibleExpenses[date] = {};\n }\n if(!_this.expensibleExpenses[date][vendor]) {\n _this.expensibleExpenses[date][vendor] = 0;\n }\n\n _this.expensibleExpenses[date][vendor] += parseFloat(price);\n }\n })\n }\n\n function calculateTotal(_this) {\n _this.result = [];\n Object.keys(_this.expensibleExpenses).forEach(ddate => {\n Object.keys(_this.expensibleExpenses[ddate]).forEach(vendor=>{\n _this.result.push({\n date: new Date(ddate), \n vendor, \n total: _this.expensibleExpenses[ddate][vendor]})\n })\n })\n }\n }\n\n printReport() {\n this.result\n .sort(byDateAndVedor)\n .forEach(item=>{\n console.log(`${getFormattedDate(item.date)}: ${item.vendor} - ${item.total}`);\n })\n\n function byDateAndVedor(a,b) {\n return a.date - b.date === 0 ? // if date is same\n ('' + a.vendor).localeCompare(b.vendor) : // then sort by vendor\n a.date - b.date // otherwise soft by date\n }\n\n function getFormattedDate(date) {\n const dateTimeFormat = \n new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit' });\n\n const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat.formatToParts(date);\n\n return `${month}/${day}/${year}`;\n }\n }\n}\n\n// Input Values\nconst categories = \"CFE,Coffee,Y\\nFD,Food,Y\\nPRS,Personal,N\";\nconst expenses = \"Starbucks,3/10/2018,Iced Americano,4.28,CFE\\nStarbucks,3/10/2018,Nitro Cold Brew,3.17,CFE\\nStarbucks,3/10/2018,Souvineer Mug,8.19,PRS\\nStarbucks,3/11/2018,Nitro Cold Brew,3.17,CFE\\nHigh Point Market,3/11/2018,Iced Americano,2.75,CFE\\nHigh Point Market,3/11/2018,Pastry,2.00,FD\\nHigh Point Market,3/11/2018,Gift Card,10.00,PRS\";\n\nconst expensesCalculator = new ExpensesCalculator(categories, expenses);\nexpensesCalculator.printReport();\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T23:16:50.357",
"Id": "243346",
"ParentId": "242965",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T19:59:09.107",
"Id": "242965",
"Score": "2",
"Tags": [
"javascript",
"parsing",
"node.js",
"ecmascript-6",
"iteration"
],
"Title": "String data manipulated given CSV variables"
}
|
242965
|
<p>I was following a tutorial for a social network. I want to know how secure this code is because I plan on launching it to the public web.</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// declaring vars to prevent errors
$fname = ""; //First name
$lname = ""; //Last name
$em = ""; //Email
$em2 = ""; // Email 2
$password = ""; //password
$password2 = ""; //password 2
$date = ""; // sign up date
$error_array = array(); //holds error messages
if(isset($_POST['register_button'])) {
// registration form values
// first name
$uname = strip_tags($_POST['reg_uname']); // remove html tags
$uname = str_replace(' ', '', $uname); //remove spaces
$_SESSION['reg_uname'] = $uname; // stores first name in session variable
// first name
$fname = strip_tags($_POST['reg_fname']); // remove html tags
$fname = str_replace(' ', '', $fname); //remove spaces
$fname = ucfirst(strtolower($fname)); //uppercase first letter
$_SESSION['reg_fname'] = $fname; // stores first name in session variable
// Last name
$lname = strip_tags($_POST['reg_lname']); // remove html tags
$lname = str_replace(' ', '', $lname); //remove spaces
$lname = ucfirst(strtolower($lname)); //uppercase first letter
$_SESSION['reg_lname'] = $lname; // stores last name in session variable
// E-mail
$em = strip_tags($_POST['reg_email']); // remove html tags
$em = str_replace(' ', '', $em); //remove spaces
$em = ucfirst(strtolower($em)); //uppercase first letter
$_SESSION['reg_email'] = $em; // stores email in session variable
// E-mail 2
$em2 = strip_tags($_POST['reg_email2']); // remove html tags
$em2 = str_replace(' ', '', $em2); //remove spaces
$em2 = ucfirst(strtolower($em2)); //uppercase first letter
$_SESSION['reg_email2'] = $em2; // stores email2 in session variable
// Password
$password = strip_tags($_POST['reg_password']); // remove html tags
$password2 = strip_tags($_POST['reg_password2']); // remove html tags
$date = date("Y-m-d"); //current date
if($em == $em2) {
//check if email is in valid format
if(filter_var($em, FILTER_VALIDATE_EMAIL)){
$em = filter_var($em, FILTER_VALIDATE_EMAIL);
// check if email already exists
$e_check = mysqli_query($con, "SELECT email FROM users WHERE email='$em'");
// Count the number of rows returned
$num_rows = mysqli_num_rows($e_check);
if($num_rows > 0){
array_push($error_array, "E-mail already in use<br>");
}
} else{
array_push($error_array, "Invalid email format<br>");
}
} else {
array_push($error_array, "E-mails don't match<br>");
}
if(strlen($uname) > 25 || strlen($uname) < 1) {
array_push($error_array, "Your username must be between 2 and 25 characters<br>");
}
if(strlen($fname) > 25 || strlen($fname) < 1) {
array_push($error_array, "Your first name must be between 2 and 25 characters<br>");
}
if(strlen($lname) > 25 || strlen($lname) < 1) {
array_push($error_array, "Your last name must be between 2 and 25 characters<br>");
}
if($password != $password2){
array_push($error_array, "Your passwords do not match<br>");
} else {
if(preg_match('/[^A-Za-z0-9]/', $password)) {
array_push($error_array, "Your password can only contain english characters or numbers.<br>");
}
}
if(strlen($password > 30 || strlen($password) < 5)){
array_push($error_array, "Your password must be between 5 and 30 characters<br>");
}
if(empty($error_array)) {
// $password = password_hash($password); // encrypt password
$password = password_hash($_POST['reg_password'], PASSWORD_BCRYPT, array('cost' => 14));
// profile picture assignment
$profile_pic = "assets/images/profile_pics/defaults/default.jpg";
$query = mysqli_query($con, "INSERT INTO users VALUES(NULL, '$fname', '$lname', '$uname', '$em',
'$password', '$date', '$profile_pic', '0', '0', 'no', ',')");
array_push($error_array, "<span style='color: #669999' >You can now login</span><br>");
//clear session variables
$_SESSION['reg_fname'] = "";
$_SESSION['reg_uname'] = "";
$_SESSION['reg_lname'] = "";
$_SESSION['reg_email'] = "";
$_SESSION['reg_email2'] = "";
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:56:57.227",
"Id": "476859",
"Score": "3",
"body": "You are about to launch a php5 project? Don't touch the password input or force it to have a limited set of characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:59:14.980",
"Id": "476860",
"Score": "2",
"body": "Did you write that code on your own, or is that coming from the tutorial?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T22:10:34.740",
"Id": "476869",
"Score": "0",
"body": "Better to use classes, all together is not a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T08:07:07.450",
"Id": "476907",
"Score": "1",
"body": "(I'm at a loss whether or not to hope you did not write code like that to have it reviewed, ignoring the restriction to present code that's yours to change and put under creative commons. My guess: straight from some introductory material. (Your guess re. my assessment of said material?))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T18:31:57.350",
"Id": "476945",
"Score": "1",
"body": "@user13477176 Then I am sorry having to tell you that your question is _off-topic_ here. SE Code Review requires that you are the author of that code."
}
] |
[
{
"body": "<p>The code is horrible.</p>\n\n<p>It probably contains all of the top 10 vulnerabilities listed on the OWASP web site.</p>\n\n<p>It uses a programming language that is well-known for its bad security history and its awful API that makes it difficult to write secure, solid code.</p>\n\n<p>Forget about that tutorial, warn others about it, find a better tutorial with focus on good code and security, and start over again. A good starting point is the OWASP site. If you really want to stay with PHP, at least use the latest version.</p>\n\n<p>You also have an off-by-one error: the condition <code>< 1</code> doesn't match the error message <code>at least 2</code>. This means you didn't even test your code properly. Especially testing the edge cases is important.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T21:53:55.927",
"Id": "242973",
"ParentId": "242970",
"Score": "7"
}
},
{
"body": "<p>I am bit puzzled by <code>strip_tags</code>:</p>\n\n<pre><code>$em = strip_tags($_POST['reg_email']); // remove html tags\n$em = str_replace(' ', '', $em); //remove spaces\n$em = ucfirst(strtolower($em)); //uppercase first letter\n</code></pre>\n\n<p>I have the impression that you stumbled upon incredibly old tutorials. You don't use that function to check user names or E-mails, because you are not expecting that people will actually put HTML tags in those fields, and besides you should have a more comprehensive routine to check the values entered.</p>\n\n<p>The purpose of <code>strip_tags</code> is to remove html from text messages (and thus filter out some spam, like clickable hyperlinks). Javascript too.</p>\n\n<p>Since you are checking the E-mail address with <code>filter_var</code> you can rid of those lines, they are pointless.</p>\n\n<p>Why capitalize the first letter of the E-mail ?\nCall the variable <code>$email</code>, it's more intuitive. <code>em</code> reminds me of the HTML tag.</p>\n\n<p>To remove whitespace around the string you can just use the <code>trim</code> function.</p>\n\n<p>This code introduces a potential <strong>vulnerability</strong> (SQL injection):</p>\n\n<pre><code>$e_check = mysqli_query($con, \"SELECT email FROM users WHERE email='$em'\");\n</code></pre>\n\n<p>I am wondering why you are not using <strong>parameterized queries</strong> (or <a href=\"https://stackoverflow.com/a/60496/6843158\">prepared statements</a>) systematically (at least whenever user input is involved). I am all the more surprised since your previous submission did not have that kind of vulnerability.</p>\n\n<p>In this particular case, you should be spared the vulnerability because you are relying on <code>filter_var</code> above to ensure that the E-mail is valid but this your only line of defense. What if you forget to check the E-mail in another part of your code ? Also, <code>filter_var</code> may have shortcomings that we don't know about.</p>\n\n<p>In general websites will only allow alphanumeric characters in usernames plus a few signs like space, hyphen, underscore etc. The most straightforward way is to use a regular expression.</p>\n\n<p>There is no need to remove spaces everywhere:</p>\n\n<pre><code>$fname = str_replace(' ', '', $fname); //remove spaces\n</code></pre>\n\n<p>First names may very well contain spaces or be compound names, nothing wrong with that. Trim: yes. Remove all whitespace: no.</p>\n\n<p>In this code, you are checking for <strong>minimum password length</strong> but not for <strong>complexity</strong>. 12345 does pass your test but you should not accept that kind of password. But you've done the exact opposite, users are <em>not</em> allowed to choose strong passwords...</p>\n\n<pre><code>if(preg_match('/[^A-Za-z0-9]/', $password)) {\n\narray_push($error_array, \"Your password can only contain english characters or numbers.<br>\");\n\n}\n</code></pre>\n\n<p>Devise a better password policy like: 12 characters minimum with at least one digit, one special character, <strong>or</strong> a long password like a passphrase that is easier to remember for humans. Each site make up their own rules, which are often counter-productive and nonsensical. The point is to find a balance between security and convenience. People tend to reuse the same passwords, and part of the reason is that they are forced to choose passwords that are not intuitive.</p>\n\n<p>I don't know why you have <code>$_SESSION</code> variables, you are not doing anything with them. In fact they are useless, unless you want to initiate a user session (that is log the user in) right after registration. But you usually you will want to validate their E-mail address first (by sending a registration code).</p>\n\n<p>I don't know large is the scope of your project but it may be a good idea to use a <strong>development framework</strong> because:</p>\n\n<ul>\n<li>it will bring you up to speed with the 21th century, and thus increase your value on the job market if you pursue a career as a developer...</li>\n<li>it will relieve you of that tedious form building and validation exercise - do not reinvent the wheel, use the modern tools that other coders use. If you want to reinvent the wheel do it right. But this will take time without guarantee of good results.</li>\n</ul>\n\n<p>This kind of code is 15 years old. At least. And it's not good.</p>\n\n<p>Unfortunately the Web is littered with outdated tutorials, many of which perpetuate bad practices and security vulnerabilities. In fact it seems that the best-ranking tutorials are the old stuff that nobody should read anymore. I am still looking for a decent tutorial as we speak.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T22:51:48.523",
"Id": "242975",
"ParentId": "242970",
"Score": "6"
}
},
{
"body": "<p>Do not use this code and php5, if you want to use mysqli + \"procedural style\", use <code>mysqli_real_escape_string</code>. The best way out - use \"<a href=\"https://www.lynda.com/PHP-tutorials/Using-prepared-statements/169106/181049-4.html\" rel=\"nofollow noreferrer\">prepared statement</a>\" </p>\n\n<p><strong>My example</strong> (This is <strong>INPUT</strong>)</p>\n\n<pre><code> function insert_user($users) {\n global $db;\n\n $hashed_password = password_hash($users['password'], PASSWORD_BCRYPT);\n\n $sql = \"INSERT INTO users \";\n $sql .= \"(first_name, last_name, email, username, hashed_password) \";\n $sql .= \"VALUES (\";\n $sql .= \"'\" . mysqli_real_escape_string($db, $users['first_name']) . \"',\";\n $sql .= \"'\" . mysqli_real_escape_string($db, $users['last_name']) . \"',\";\n $sql .= \"'\" . mysqli_real_escape_string($db, $users['email']) . \"',\";\n $sql .= \"'\" . mysqli_real_escape_string($db, $users['username']) . \"',\";\n $sql .= \"'\" . mysqli_real_escape_string($db, $hashed_password) . \"'\";\n $sql .= \")\";\n $result = mysqli_query($db, $sql);\n\n // For INSERT statements, $result is true/false\n if($result) {\n return true;\n } else {\n // INSERT failed\n echo mysqli_error($db);\n exit;\n }\n }\n</code></pre>\n\n<p>How to use this function?</p>\n\n<pre><code>$result = insert_user($users);\n</code></pre>\n\n<p>Use <code>strip_tags</code> for <strong>OUTPUT</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:29:18.113",
"Id": "476952",
"Score": "0",
"body": "The function name has an `s` too much at the end. It must be `user`, not `users`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:00:08.180",
"Id": "476957",
"Score": "0",
"body": "@Roland Illig Yes user:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:14:22.407",
"Id": "476958",
"Score": "0",
"body": "Same for the parameter name, by the way."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T06:59:39.453",
"Id": "242992",
"ParentId": "242970",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T20:35:09.670",
"Id": "242970",
"Score": "-3",
"Tags": [
"php",
"security",
"php5"
],
"Title": "Registration code"
}
|
242970
|
<p>I am trying to implement topological sort. The idea is that I have a vector of pairs in which the first element is indegree and the second is a linked list. I tried a bunch of tests, they seem to work, but I am not really sure about my implementation. Is this really a topological sort? Can you please review my code and give some advice on how to improve it?</p>
<pre><code>#include <iostream>
#include <list>
#include <vector>
#include <stack>
using namespace std;
class Graph {
public:
Graph(int V) {
this->V = V;
adj.resize(V);
}
void addEdge(int from, int to) {
adj[from].second.push_back(to);
}
void FillIndegrees() {
for (int i = 0; i < adj.size(); ++i) {
for (int v : adj[i].second) {
adj[v].first++;
}
}
}
void PrintIndegrees() {
for (int i = 0; i < adj.size(); ++i) {
cout << adj[i].first << endl;
}
}
void TopologicalSort() {
FillIndegrees();
stack<int> st;
// find zero indegree and add it to a stack
for (int i = 0; i < adj.size(); ++i) {
if (adj[i].first == 0) {
st.push(i);
}
}
while (!st.empty()) {
int idx = st.top();
cout << idx << " ";
st.pop();
for (int v : adj[idx].second) {
adj[v].first--;
if (adj[v].first == 0) {
st.push(v);
}
}
}
}
private:
int V;
// indegree, list of edges
vector<pair<int, list<int>>> adj;
};
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
// Graph g(6);
// g.addEdge(5, 2);
// g.addEdge(5, 0);
// g.addEdge(4, 0);
// g.addEdge(4, 1);
// g.addEdge(2, 3);
// g.addEdge(3, 1);
g.TopologicalSort();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T21:45:40.200",
"Id": "476866",
"Score": "3",
"body": "Undeclared identifier: stack. Please post your actual, complete, compilable code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T21:48:53.317",
"Id": "476867",
"Score": "3",
"body": "Since topological sort is a well-known topic, you should try your code with the standard test cases that other people have already thought out. After that test has succeeded, you can remove the question mark from the title, then your code is ready for review. Right now it is off-topic because \"the author is reasonable sure that the code works\" does not apply."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T21:58:46.997",
"Id": "476868",
"Score": "1",
"body": "Please include any include headers you use in the code as well as any statements like `using namespace std;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T02:25:11.623",
"Id": "476880",
"Score": "0",
"body": "This question was posted on Stack Overflow first https://stackoverflow.com/questions/62029149/is-this-a-topological-sort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T04:45:12.417",
"Id": "476889",
"Score": "0",
"body": "The main does not look like anything would be shown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T06:17:55.077",
"Id": "476899",
"Score": "0",
"body": "Added headers and using namespace. Also about duplicate. Post on stackoverflow was posted by me and it was claimed off topic, because more appropriate place for it here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T07:33:12.850",
"Id": "476901",
"Score": "0",
"body": "\"I tried a bunch of tests, they seem to work\" Do you have more tests than currently shown in `main`? Could you add those?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T07:52:43.653",
"Id": "476906",
"Score": "0",
"body": "I added one more, I tried others but this is only one that I still have. Thank you"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T21:14:54.130",
"Id": "242972",
"Score": "3",
"Tags": [
"c++",
"sorting"
],
"Title": "Is this a topological sort?"
}
|
242972
|
<p>I have a following list which indicates the indexes.</p>
<pre><code> List<Integer> integerList = Arrays.asList(1, 3, 5, 6); // index
</code></pre>
<p>I have the following collection of objects.</p>
<pre><code>Collection<Test> testCollection = new ArrayList<>();
Test test01 = new Test(0, "A"); // 0
Test test02 = new Test(1, "B"); // 1
Test test03 = new Test(2, "C"); // 2
Test test04 = new Test(3, "D"); // 3
Test test05 = new Test(4, "E"); // 4
Test test06 = new Test(5, "F"); // 5
testCollection.add(test01);
testCollection.add(test02);
testCollection.add(test03);
testCollection.add(test04);
testCollection.add(test05);
testCollection.add(test06);
</code></pre>
<p>The <code>integerList</code> has indexes which are present on <code>testCollection</code>. I want to filter out the <code>testCollection</code> which will have object consisting the index <code>1, 3, 5</code>. Index <code>6</code> is not present on object collection.</p>
<p>I wrote the code as below example. Is there any better as like Java 8 way?</p>
<pre><code>List<Test> testList = new ArrayList<>(testCollection);
List<Test> newTestList = new ArrayList<>();
for (Integer integer : integerList) {
for (int j = 0; j < testList.size(); j++) {
if (integer == j) {
newTestList.add(testList.get(j));
}
}
}
System.out.println(newTestList);
</code></pre>
<p>It will have the following output as result:</p>
<pre><code>[Test{id=1, name='B'}, Test{id=3, name='D'}, Test{id=5, name='F'}]
</code></pre>
<p>The class <code>Test</code> has following information.</p>
<pre><code>class Test {
private int id;
private String name;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T01:12:54.100",
"Id": "476879",
"Score": "0",
"body": "Both lists are sorted, is that guaranteed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:02:26.703",
"Id": "476962",
"Score": "0",
"body": "`integerList` will not be sorted but testCollection will at sorted order."
}
] |
[
{
"body": "<p>You can filter and map the <code>integerList</code> but not sure that it will be more efficient.</p>\n\n<pre><code>List<Test> result = integerList.stream()\n .filter(index -> index>-1 && index<testList.size())\n .map(testList::get)\n .collect(Collectors.toList());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:44:44.687",
"Id": "242999",
"ParentId": "242977",
"Score": "0"
}
},
{
"body": "<p>It seems to me that your solution is basically O(n*m),the size of the unfiltered list times the number of filter indexes. I think you can get O(n+mlogm),the size of the unfiltered list plus sorting the filtered indexes, by using a combination of indexes and iterators and iterating through both lists at the same time. It could look something like this:</p>\n\n<pre><code>public static List<Test> getFilteredList(Collection<Test> unfilteredList, List<Integer> filterIndexes) {\n if(filterIndexes == null || filterIndexes.size() == 0){\n return new ArrayList<Test>(unfilteredList);\n }\n Collections.sort(filterIndexes); \n List<Test> newTestList = new ArrayList<>();\n Iterator uIterator = unfilteredList.iterator();\n Iterator fIterator = filterIndexes.iterator();\n Integer fIndex = (Integer)fIterator.next();\n for (Integer uIndex = 0;uIterator.hasNext();++uIndex) {\n Test nextTest = (Test)uIterator.next();\n if (uIndex == fIndex) {\n newTestList.add(nextTest);\n if(!fIterator.hasNext()){\n break;\n }else{\n fIndex = (Integer)fIterator.next();\n if(fIndex >= unfilteredList.size()){\n break;\n }\n }\n }\n }\n return newTestList;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T22:31:25.423",
"Id": "243037",
"ParentId": "242977",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243037",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T23:20:59.557",
"Id": "242977",
"Score": "1",
"Tags": [
"java"
],
"Title": "List with object and index filtering out the object depends upon the index present at list"
}
|
242977
|
<p>I have written the following code for my 1st year project, the Fibonacci series. I programmed it without searching Google. Is my code good enough to get me an A or a B? Can I make the code more professional?</p>
<pre><code>#include <stdio.h>
#include <windows.h>
#include <math.h>
main(){
double x, y, xy;
printf("Presenting to you the Fibonacci Numbers");
Sleep(2500);
x = 0;
y = 1;
printf("\n%.0f", x);
printf("\n%.0f", y);
while (1){
xy = x + y;
y = y + xy;
x = xy;
printf("\n%.0lf", x);
Sleep(250);
printf("\n%.0lf", y);
Sleep(250);
}}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is my code good enough to get me an A or a B?</p>\n</blockquote>\n\n<p><strong>Produces incorrect output</strong></p>\n\n<p>After a while the code produces wrong output. I would not mind so much that code has a limited range, but one that starts producing errors, without warning, is not good. B for effort - I admire your goals, C for implementation.</p>\n\n<p><strong>FP for an integer problem</strong></p>\n\n<p>The Fibonacci series runs though various odd numbers, resulting in incorrect results after the precision of <code>double</code> is used up at about 2<sup>DBL_MANT_DIG</sup> or typically 2<sup>53</sup>. <code>unsigned long long</code> affords at least 2<sup>64</sup>-1.</p>\n\n<p>Although using <code>double</code> allows for a greater <em>range</em>, I'd see using floating point (FP) as a weaker approach to this problem than integers and <a href=\"https://stackoverflow.com/a/34360258/2410359\">strings</a>.</p>\n\n<p><strong>Unneeded code</strong></p>\n\n<p><code>Sleep(2500);</code> no functional purpose to the calculation of the Fibonacci series. Use of magic numbers 2500, 250 lacks explanation.</p>\n\n<p><strong>main() lacks return type</strong></p>\n\n<p>This style of programming went out 20 years ago. Code the return type.</p>\n\n<pre><code>// main(){\nint main() {\n// or clearly\nint main(void) {\n</code></pre>\n\n<p><strong>Consider declaring object when/where needed</strong></p>\n\n<p>Example</p>\n\n<pre><code>//double x, y, xy;\n//...\n//while (1){\n// xy = x + y;\n\ndouble x = 0;\ndouble y = 1;\n...\nwhile (1) {\n double xy = x + y;\n</code></pre>\n\n<p><strong>Strange to use end-of-line to start printing</strong></p>\n\n<p>A more common idiom is <code>'\\n'</code> afterwards and facilitates flushing <code>stdout</code> when line buffered.</p>\n\n<pre><code>//printf(\"\\n%.0lf\", y);\nprintf(\"%.0lf\\n\", y);\n</code></pre>\n\n<p><strong>Minor: odd formatting</strong></p>\n\n<p><code>}}</code> is uncommon. Perhaps:</p>\n\n<pre><code> }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Can I make the code more professional?</p>\n</blockquote>\n\n<p>Stop before the algorithm can no longer provide correct output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:19:49.840",
"Id": "477112",
"Score": "1",
"body": "In addition, `main()` with a missing `return 0;` invokes K&R style undefined behavior. You can only leave out return 0 from C99 and beyond, but then you can't use `main()` any longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:37:05.463",
"Id": "477114",
"Score": "0",
"body": "@Lundin Interesting. For me, I prefer `int main(void) { .... return 0;}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:39:20.277",
"Id": "477115",
"Score": "0",
"body": "Specifically the standard says that if the caller uses the return value from a function, omitting it results in undefined behavior. And since UNIX OS has been using the return value of programs since the dawn of time, programs such as K&R `main()\n{\nprintf(\"hello, world\\n\");\n}` invokes undefined behavior. Perhaps this one is the first C bug ever written, even."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:41:55.587",
"Id": "477117",
"Score": "0",
"body": "And `int main (void)` is correct, because `int main()` is obsolete style from C99 and beyond. Still marked as obsolete in C17 though, so I guess they won't remove it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T08:39:56.057",
"Id": "478665",
"Score": "0",
"body": "@ReinstateMonica Yea, i figured out a way to avoid the problem that is caused by the series, if it runs for a long time. i used `%.3g` instead of `%lf` so its kinda working fine now."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T02:04:45.647",
"Id": "242982",
"ParentId": "242980",
"Score": "6"
}
},
{
"body": "<p>1) The Fibonacci series shall never yield non whole numbers; <code>double</code>s are unnecessary and possibly computationally expensive. Try a <code>uintmax_t</code>. It will probably give you values of up to 2^64 - 1 (18,446,744,073,709,551,615). That should certainly be sufficient. Additionally, I would put in code to terminate the program as it reaches the upper limit of <code>uintmax_t</code>.</p>\n\n<p>2) Your could have a classic I/O problem: output buffering. Try to put a <code>\\n</code> in every print statement to encourage proper flushing. So rather than having the come at the beginning of each print statement, try putting it at the end. If you like it the way it is, you can call <code>fflush(stdout)</code> after every <code>printf()</code>. While we're on the topic, your first two <code>printf()</code> statements can be combined. More info at <a href=\"https://stackoverflow.com/q/1716296/12786236\">this</a> SO question. </p>\n\n<p>3) Obviously the <code>Sleep()</code> functions are unnecessary to your code. I presume that they are there for the aesthetic value of the output, but I would take them out. Doing so would make your code OS-independent as well as neater. But obviously, depending on the assignment, appearance may be above all. </p>\n\n<p>4) Finally, despite the mathematical purpose of the program, <code>math.h</code> is not needed. </p>\n\n<p>Addendum: You asked how to make it more professional. You could make a Fibonacci function encapsulating the algorithmic properties of your code, while leaving the aesthetic properties (sleep, welcome message) in <code>main()</code>. Example: </p>\n\n<pre><code>uintmax_t num = get_next_fibbonaci(/*reference to struct storing state || values necessary for calculation*/);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T05:10:10.537",
"Id": "476893",
"Score": "6",
"body": "Global variables would not be considered professional in this situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T09:41:45.890",
"Id": "476908",
"Score": "3",
"body": "Using static variables inside a generator function would be less bad than globals, but is not a good pattern for reusable code: it's not thread-safe. A more modern design could have a state object that the caller passes by reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T16:22:56.697",
"Id": "476931",
"Score": "0",
"body": "@Peter Cordes Given that this is a single-thread program that's a one-off for this singular goal, I believe persistent variables would be an acceptable solution. However, I can see how it might not be the most \"professional\" way. Edited answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:45:46.130",
"Id": "476955",
"Score": "0",
"body": "Yup, good edit. But note that you can't just pass the two history values *by value* because this function has to update them, or else the caller has to know about Fibonacci logic. So `|| values necessary for calculation` isn't really a clear logical or."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T15:44:05.493",
"Id": "477128",
"Score": "0",
"body": "I was thinking `x3 = fib(x1,x2)`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T02:12:07.633",
"Id": "242983",
"ParentId": "242980",
"Score": "8"
}
},
{
"body": "<blockquote>\n<p>That should certainly be sufficient</p>\n</blockquote>\n<p>2^64 is a lot, but mathematics is stronger. Instead of just choosing a big number, you should stop before it overflows.</p>\n<pre><code>#include <stdio.h>\n\nvoid main(void) {\n\n unsigned long MAX = -1;\n unsigned long a = 0, b = 1, new;\n do {\n new = a + b;\n printf("%lu\\n", new);\n a = b;\n b = new;\n } while (new < MAX/2);\n}\n</code></pre>\n<p>There were quite a few problems before I got it right. The post-test loop helps, as does a correct <code>%ul</code> in <code>printf()</code>.</p>\n<hr />\n<p>Your two-in-one algorithm looks efficient, but I don't fully understand. I guess you save a variable swapping per iteration. I would give you an A for <em>that</em>. The rest has already been discussed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:35:40.837",
"Id": "252563",
"ParentId": "242980",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "242983",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T00:56:07.670",
"Id": "242980",
"Score": "3",
"Tags": [
"c",
"fibonacci-sequence"
],
"Title": "Fibonacci series"
}
|
242980
|
<p>I was just wondering if there is a way to speed up the performances of this for loops in Python.</p>
<p>I'm trying to process an image to get the color-moments <strong>without using libraries</strong>.
It takes about 12sec to do the <em>calculate_mean</em> and <em>calculate_standard_deviation</em> functions for each part of the image.</p>
<pre><code>import math
import cv2
import numpy as np
</code></pre>
<pre><code>parts = 2
new_height = int(img.shape[0]/parts)
new_width = int(img.shape[1]/parts)
for i in range (0,img.shape[0],new_height):
for j in range(0,img.shape[1],new_width):
color_moments = [0,0,0,0,0,0,0,0,0]
cropped_image = img[i:i+new_height,j:j+new_width]
yuv_image = cv2.cvtColor(cropped_image,cv2.COLOR_BGR2YUV)
Y,U,V = cv2.split(yuv_image)
pixel_image_y = np.array(Y).flatten()
pixel_image_u = np.array(U).flatten()
pixel_image_v = np.array(V).flatten()
calculate_mean(pixel_image_y,pixel_image_u,pixel_image_v,color_moments)
calculate_standard_deviation(pixel_image_y, pixel_image_u, pixel_image_v, color_moments)
</code></pre>
<p>And this are the two functions:</p>
<pre><code>def calculate_mean(pixel_image_y,pixel_image_u,pixel_image_v,color_moments):
for p in pixel_image_y:
color_moments[0]+=(1/(new_height*new_width))*int(p)
for p in pixel_image_u:
color_moments[1]+=(1/(new_height*new_width))*int(p)
for p in pixel_image_v:
color_moments[2]+=(1/(new_height*new_width))*int(p)
def calculate_standard_deviation(pixel_image_y,pixel_image_u,pixel_image_v,color_moments):
temp = [0,0,0]
for p in pixel_image_y:
temp[0]+=(p-color_moments[0])**2
color_moments[3] = math.sqrt((1/(new_height*new_width))*temp[0])
for p in pixel_image_u:
temp[1]+=(p-color_moments[1])**2
color_moments[4] = math.sqrt((1/(new_height*new_width))*temp[1])
for p in pixel_image_v:
temp[2]+=(p-color_moments[2])**2
color_moments[5] = math.sqrt((1/(new_height*new_width))*temp[2])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:21:22.670",
"Id": "476909",
"Score": "1",
"body": "is `color_moments` reset for each iteration, because that is not clear from the code here. Why not just use [`np.mean`](https://numpy.org/doc/1.18/reference/generated/numpy.mean.html) and [`np.std`](https://numpy.org/doc/1.18/reference/generated/numpy.std.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:26:16.017",
"Id": "476911",
"Score": "0",
"body": "Yes, color_moments is reset for each iteration. I'm trying to not use the libraries"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:27:16.617",
"Id": "476912",
"Score": "2",
"body": "Bolding \"without using libraries\" seems really odd. Like really really really odd, since you're using numpy and opencv. Please explain why you don't want to use these libraries and which libraries you can use. Because currently your description says one thing and your code says another."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T13:01:37.207",
"Id": "476917",
"Score": "0",
"body": "I need to calculate the mean and standard deviation without the libraries given by numpy. I edited the code to show how I reset the color_moments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T16:39:39.390",
"Id": "476934",
"Score": "0",
"body": "So, if the color moments are reset every iteration and you don't do anything with them, not even displaying, why calculate them in the first place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:54:28.763",
"Id": "476939",
"Score": "1",
"body": "Please add your imports and all other relevant code."
}
] |
[
{
"body": "<ol>\n<li>Python 2 is end of life, many core libraries and tools are dropping Python 2 support.</li>\n<li>Python is dumb. If you tell it to calculate <code>(1/(new_height*new_width)</code> each and every loop, then Python will.</li>\n<li>Your style is not Pythonic, you should have more whitespace.</li>\n<li><p>If we change one of the for loops in <code>calculate_mean</code> to math, we can see we can that ¶2 isn't needed inside the loop.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for p in pixel_image_y:\n color_moments[0]+=(1/(new_height*new_width))*int(p)\n</code></pre>\n\n<p><span class=\"math-container\">$$\n\\Sigma \\frac{\\lfloor p \\rfloor}{hw} = \\frac{\\Sigma \\lfloor p \\rfloor}{hw}\n$$</span></p></li>\n<li><p>We can utilize numpy to perform the loop, in <code>calculate_standard_deviation</code>, in C.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>color_moments[3] = (\n np.sum((pixel_image_y - color_moments[0]) ** 2)\n * math.sqrt((1/(new_height*new_width))\n)\n</code></pre></li>\n<li>You should change <code>calculate_mean</code> and <code>calculate_standard_deviation</code> to either work in one dimension or all dimensions.</li>\n<li>You should remove <code>color_moments</code> from your code. You should <code>return</code> if you need to return.</li>\n<li>You can determine <code>new_height*new_width</code> by the values you enter in your function. No need to pass them.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def mean(values):\n return sum(int(v) for v in values) / len(values)\n\ndef std_deviation(values):\n return np.sum((values - mean(values)) ** 2) / math.sqrt(len(values))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:36:12.367",
"Id": "476935",
"Score": "0",
"body": "I don't understand the fourth point"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:42:53.833",
"Id": "476937",
"Score": "0",
"body": "@EnricoMosca If we have the list `[1, 0, 1, 0, 1]` then this can be seen as \\$\\Sigma \\frac{\\lfloor p \\rfloor}{5} = \\frac{1}{5} + \\frac{0}{5} + \\frac{1}{5} + \\frac{0}{5} + \\frac{1}{5}\\$, we can simplify this to move the fraction away from the sum \\$\\frac{\\Sigma \\lfloor p \\rfloor}{5} = \\frac{1 + 0 + 1 + 0 + 1}{5}\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T08:55:20.550",
"Id": "476999",
"Score": "0",
"body": "Thank you so much for your precious help!!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T16:59:19.333",
"Id": "243012",
"ParentId": "242996",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "243012",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:10:46.660",
"Id": "242996",
"Score": "0",
"Tags": [
"python",
"performance",
"python-2.x",
"numpy",
"opencv"
],
"Title": "Image color-moment extractor"
}
|
242996
|
<p>im trying to get the factor prime number(s) for given number if its different than the primes that i have in a list.</p>
<p>The number have to:</p>
<ul>
<li><p>dividable with any of the primes in the list</p></li>
<li><p>should not have any other factor as primes other than in the list</p></li>
</ul>
<p>example:</p>
<p>my_primes = [2, 3, 5]</p>
<p>n = 14 should return [7]</p>
<p>14 has factors [1, 2, 7, 14], can be divided by prime 2 (which is in list and prime) but also have 7 as factor prime and it is not in my list so i want to return that. If number has even 1 prime like this its enough for me so i dont need to check till i find other primes.</p>
<p>The code i have come up with so far:</p>
<pre><code>from rTime import timer
@timer
def solve(n):
def is_prime(n):
i = 2
while i**2 <= n:
if n % i == 0:
return False
i += 1
return True
primes = [2, 3, 5]
listo = []
if n % 2 != 0 and n % 3 != 0 and n % 5 != 0:
return False
for i in range(2, n):
if n % i == 0 and is_prime(i) and i not in primes:
listo.append(i)
if listo:
break
return listo
result = solve(1926576016)
print(result)
</code></pre>
<p>so my problem is it takes 22.36 seconds to check if 1926576016 has any primes like that at the moment. Is there anything i can improve in my code to make it faster or whole different approach needed to do this task. </p>
<p>Should note that i have been learning python since 4-5 months so i might not be aware of any build-in tools that makes this faster and its my first question here sorry if i did something wrong !</p>
<p>(@timer is a function that i have write to check how long it takes to run a function)</p>
|
[] |
[
{
"body": "<p>A note on terminology,</p>\n<blockquote>\n<p>14 has factors [1, 2, 7, 14]</p>\n</blockquote>\n<p>Usually these are called divisors, while the factors of 14 are taken to be only 2 and 7.</p>\n<h1>The Algorithm</h1>\n<p>While it is not entirely clear to me what you need the result to be, there is an alternative approach to finding the answer to the following question:</p>\n<blockquote>\n<p>Does the number have any factors that are not in the list?</p>\n</blockquote>\n<p>Which I hope is a fair re-wording of</p>\n<blockquote>\n<p>[the number] should not have any other factor as primes other than in the list</p>\n</blockquote>\n<p>To answer that question, a possible algorithm is:</p>\n<p>For each <code>p</code> in <code>primes</code>, as long as <code>n</code> is divisible by <code>p</code>, divide <code>n</code> by <code>p</code>. The "leftover" <code>n</code> at the end is the product of all the factors of the original <code>n</code> that are not in <code>primes</code>.</p>\n<p>For example in Python,</p>\n<pre><code>def solve(n):\n primes = [2, 3, 5]\n for p in primes:\n while n % p == 0:\n n = n // p\n return n\n</code></pre>\n<p>Now the result will be 1 if the number <code>n</code> only had the <code>primes</code> as factors, or otherwise it will be whatever is left. In the original function, the leftover would also be essentially be factored (but slowly, and only the first factor is returned). An integer factorization algorithm (there are faster options for that than trial division) could be applied as an extra step to recreate that result, but that is not required to answer the question of whether the number has any other factors that were not in the list <code>primes</code>.</p>\n<p>This algorithm would not deal very well with a much longer list of <code>primes</code> (say, millions of primes), but it does deal well with cases such as <code>1926576016</code> where the lowest prime factor which isn't in <code>primes</code> is high.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T12:32:42.037",
"Id": "476916",
"Score": "0",
"body": "\" Usually these are called divisors \" oops , my bad there. \n\" Which I hope is a fair re-wording of \" yup my bad again.\nJust run the code and yeah its much more faster thanks for the explanations !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T11:50:34.743",
"Id": "243004",
"ParentId": "242997",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:18:20.230",
"Id": "242997",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"primes"
],
"Title": "Faster way to check if number has factor of different primes than given list of primes"
}
|
242997
|
<p>I have the following code which works. Been trying to write it in Java 8 streams to make it more readable but unable to get my head around it. Looking for any feedback to make it more readable.
Thanks. </p>
<pre><code>// Expected output like: 1~CODE1|2~CODE2|3~CODE3|4~EX|5~CODE5
private String getFormattedValue(List<Content> list) {
final String tilde = "~";
final String pipe = "|";
StringBuilder codes = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
String code = list.get(i).getCode();
if (StringUtils.isNotBlank(code) && !"null".equals(code)) {
code = "example".equals(code) ? "EX" : code.toUpperCase();
codes.append(i + 1).append(tilde).append(code);
codes.append(pipe);
}
}
if (codes.toString().endsWith("|")) {
codes.deleteCharAt(codes.length() - 1);
}
return codes.toString();
}
</code></pre>
|
[] |
[
{
"body": "<p>One issue is that you cannot consume a stream with index. You can more or less have the same result with a <code>IntStream</code> bounded to your list's size.</p>\n\n<p>Then you just have map each int to a code with the same logic. And, finally, collect them (This is the only part where the Stream will shine).</p>\n\n<pre><code>String string = IntStream.range(0, codes.size())\n .mapToObj(i -> {\n String code = codes.get(i);\n code = \"example\".equals(code) ? \"EX\":code.toUpperCase();\n return String.format(\"%1$d~%2$s\", i, code);\n })\n .collect(Collectors.joining(\"|\"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T16:10:46.050",
"Id": "476929",
"Score": "0",
"body": "Why add 1$ and 2$? Is it convention?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T16:18:03.813",
"Id": "476930",
"Score": "0",
"body": "I would need to do an if check around the 3 lines inside that mapToObj. If check works but wonder if there is a way to do filter by any chance. This if check > if (StringUtils.isNotBlank(code) && !\"null\".equals(code))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T05:17:57.977",
"Id": "476980",
"Score": "1",
"body": "@karvai for `1$` and `2$`, see the documentation of String.format that will point you to https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax . Indeed you have to add the `if ( isNotBlank(..) && !\"null\".equals(..) )` I forgot it?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T11:40:16.747",
"Id": "243003",
"ParentId": "242998",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243003",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T10:38:18.957",
"Id": "242998",
"Score": "1",
"Tags": [
"java"
],
"Title": "Writing a for loop to build a String using Streams"
}
|
242998
|
<p>I'm trying to get my basic coding principles right but there's still a long way to go. This is an exercise for CodeGym. They logic itself isn't very hard and I passed the exercise easily but I'd like my code reviewed with the following in mind:</p>
<ul>
<li><p>In terms of the general architecture, I wasn't quite sure if I needed two methods. It felt tidier to me to have a method for the first task (copy) and one for the second (append) but I couldn't figure out a way to avoid calling the second method from the first. </p></li>
<li><p>Should read the inputs from the console in the main method and pass the result to the class? Or it totally depends on the context of the application I'm working for?</p></li>
<li><p>About error handling, I got completely lost. After doing some research I just decided to let the caller handle the error but I'm sure there's some stuff missing. I wasn't sure for example if I should have two try blocks on the first method but it also depended on the answer to the first point (architecture), so I gave up.</p></li>
<li><p>It's my first time using Javadocs, so I'm not sure what I wrote is enough</p></li>
<li><p>I know "Solution" is not the ideal name for the class, but I used the class created by CodeGym.</p></li>
</ul>
<p>Please feel free to tear it apart :)</p>
<p>Thanks in advance!</p>
<pre><code>public class Solution {
public static void main(String[] args) {
FileProcessor fileProcessor = new FileProcessor();
try {
fileProcessor.copyFile();
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
}
</code></pre>
<pre><code>import java.io.*;
/**
* This class reads 3 filenames from console,
* copies content from the second file to the first and subsequently
* appends content from third file to first file.
*/
public class FileProcessor {
// Study comment: Solution using "var" didn't work in this IntelliJ
/**
* Reads inputs, copies second file to first and calls method to append file
* @throws IOException
*/
public void copyFile() throws IOException {
String outputFile;
String sourceToCopy;
String sourceToAppend;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Enter a filename for the output:");
outputFile = reader.readLine();
System.out.println("Enter the path of the file to be copied");
sourceToCopy = reader.readLine();
System.out.println("Enter the path of the file to be appended");
sourceToAppend = reader.readLine();
}
try (FileOutputStream out = new FileOutputStream(outputFile);
FileInputStream copy = new FileInputStream(sourceToCopy)) {
byte[] buffer = new byte[1024];
while (copy.available() > 0) {
int count = copy.read(buffer);
out.write(buffer, 0, count);
}
}
appendFile(sourceToAppend, outputFile);
}
/**
*
* @param source file to append
* @param output final result file
* @throws IOException
*/
public void appendFile(String source, String output) throws IOException {
try (FileOutputStream appended = new FileOutputStream(output, true);
FileInputStream toAppend = new FileInputStream(source)
) {
byte[] buffer = new byte[1024];
while (toAppend.available() > 0) {
int count = toAppend.read(buffer);
appended.write(buffer, 0, count);
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>General architecture</h2>\n\n<p>A useful architecture guideline is:</p>\n\n<ul>\n<li>By introducing classes and methods, I create the high-level language that I want\nto use for expressing my solution.</li>\n</ul>\n\n<p>So, It's a good idea to start from the most abstract top-level, and later implement the methods needed at that top-level code. So I'd like to rephrase your program (top-level) as follows:</p>\n\n<ul>\n<li>Read the output filename: <code>String outputFile = readWithPrompt(reader, \"Enter a filename for the output:\");</code></li>\n<li>Read the first input filename: <code>String sourceToCopy = readWithPrompt(reader, \"Enter the path of the file to be copied\");</code></li>\n<li>Read the second input filename: <code>String sourceToAppend = readWithPrompt(reader, \"Enter the path of the file to be appended\");</code></li>\n<li>Combine the files: <code>combineFiles(sourceToCopy, sourceToAppend, outputFile);</code></li>\n</ul>\n\n<p>This keeps user interface and business logic apart, which I highly recommend!</p>\n\n<p>Reading the three file names is three times the same, so I used a common phrase (= calling the same method, just with different prompting strings).</p>\n\n<p>The main business of your program is to combine two input files into one output file, so I made that explicit at the top-level.</p>\n\n<p>I like your distinct <code>append()</code> method. It's useful on its own, not only in your combine-two-files setting. You could even implement the whole thing by first creating an empty file, and then twice append some source file to it.</p>\n\n<h2>Where to read user input</h2>\n\n<p>Always separate user interface from doing things. Imagine that tomorrow you want to combine all files from one directory with a common footer (e.g. your company's legal stuff). Then you no longer want to ask the user for every single file, but you'll still be combining pairs of input files into an output. You can then easily re-use a clean business method, but not one mixing user I/O and business.</p>\n\n<h2>Error handling</h2>\n\n<p>I like your exception handling in the main method.</p>\n\n<p>The single most important guideline is: <strong>A method should throw an exception if it couldn't do its job.</strong> </p>\n\n<p>So, if during the files copying something went wrong, you ended up with a missing or corrupt result. The caller of <code>combineFiles()</code> can normally assume that after that call, the output file has the correct content. If not, he needs to know about that, and that's done by throwing an exception (or not catching an exception that came from some inner calls).</p>\n\n<p>Exception handling is a big topic with diverging opinions between the professionals, too much to go into more details here. As long as you follow the guideline, you can't be going wrong.</p>\n\n<h2>Javadoc</h2>\n\n<p>Your Jacadocs are mostly fine. I wish most real-world programs were documented like that. Sigh!</p>\n\n<blockquote>\n <p>Reads inputs, copies second file to first and calls method to append file</p>\n</blockquote>\n\n<p>Here's one quirk: you say \"calls method\", and that's breaking encapsulation. Javadocs should describe a method as a black box, how it behaves to the outside world. For the Javadoc, it doesn't matter if the method does its job all by itself or by calling hundreds of other methods. Only describe things that have an effect visible to your caller.</p>\n\n<p>When describing the <code>append()</code> method, you thoughts were probably withing your overall task, so the text shows parts of what the <code>append()</code> method is meant for (\"final result file\") in the whole program instead of just describing what it does (append one file to the existing contents of another file).</p>\n\n<h2>Class names, packages</h2>\n\n<p>Nothing to complain about your class names.</p>\n\n<p>\"Solution\" is not the most inventive, but a valid name for such a compact program.</p>\n\n<p>\"FileProcessor\" is a perfect name for a class like yours.</p>\n\n<p>But when you start to do serious stuff, you should get into the habit of organizing your classes into packages with unique names, with low risk of colliding with packages from external libraries, typically by using something like a reversed domain name or identity e.g. <code>com.facebook.username</code>, something that's unlikely to be used by someone else.</p>\n\n<p>Finally, I'd like to warn about wildcard import statements like your <code>import java.io.*;</code>. This makes all class names from the <code>java.io</code> package visible in your code. At a first glance, that's fine, you can abbreviate <code>java.io.FileOutputStream</code> to just <code>FileOutputStream</code> in your code.</p>\n\n<p>But maybe, in some future Java version, a class named <code>FileProcessor</code> gets included into the <code>java.io</code> package. Then the confusion starts: does <code>FileProcessor</code> mean your class or the one from <code>java.io</code>? </p>\n\n<p>While exactly that is well-defined (it will be your class as long as you're in the same package), wildcard imports can cause real trouble in related, similar situations. Every decent, modern IDE has the ability to manage individual imports for you, so replacing the wildcard import with the necessary individual imports should be \"one click\" and then avoids the risk I described here.</p>\n\n<h2>Indentation</h2>\n\n<p>The indentation of your code looks mostly fine, but a few lines are out of sync. So probably, you did at least some of it manually. In your IDE, look for automated code indentation or formatting. No need to waste time hitting the space key multiple times, and as a result of the automated feature, your code always looks tidy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T22:10:57.387",
"Id": "476966",
"Score": "0",
"body": "Thanks for taking the time to reply! I won't make any comments just yet but I'll be using your reply (and others) to modify my code and as a guideline for future exercises. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T13:56:13.200",
"Id": "243007",
"ParentId": "243005",
"Score": "2"
}
},
{
"body": "<p>I noticed in your method <code>copyFile</code>, you are including input of filenames from stdin:</p>\n\n<blockquote>\n<pre><code>public void copyFile() throws IOException {\n String outputFile;\n String sourceToCopy;\n String sourceToAppend;\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {\n System.out.println(\"Enter a filename for the output:\");\n outputFile = reader.readLine();\n System.out.println(\"Enter the path of the file to be copied\");\n sourceToCopy = reader.readLine();\n System.out.println(\"Enter the path of the file to be appended\");\n sourceToAppend = reader.readLine();\n }\n //other method\n}\n</code></pre>\n</blockquote>\n\n<p>It is correct, but in this way if you are taking filenames from other source different from stdin like another file you cannot more use this method. A possible alternative is passing filenames as parameters and put the reading block from stdin outside the method:</p>\n\n<pre><code>public class NewSolution {\n public static void main(String[] args) throws IOException {\n String outputFile;\n String sourceToCopy;\n String sourceToAppend;\n\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {\n System.out.println(\"Enter a filename for the output:\");\n outputFile = reader.readLine();\n System.out.println(\"Enter the path of the file to be copied\");\n sourceToCopy = reader.readLine();\n System.out.println(\"Enter the path of the file to be appended\");\n sourceToAppend = reader.readLine();\n }\n\n FileProcessor fileProcessor = new FileProcessor();\n fileProcessor.copyFile(sourceToCopy, sourceToAppend, outputFile);\n }\n}\n</code></pre>\n\n<p>Because in your method <code>copyFile</code> you are not doing operations of data contained in the file but a simple copy, you could write your method using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html\" rel=\"nofollow noreferrer\">Files</a> like below:</p>\n\n<pre><code>public static void copyFile(String sourceToCopy, String sourceToAppend, String outputFile) throws IOException {\n\n Files.copy(Paths.get(sourceToCopy), Paths.get(outputFile), StandardCopyOption.REPLACE_EXISTING);\n Files.copy(Paths.get(sourceToAppend), new FileOutputStream(outputFile, true));\n}\n</code></pre>\n\n<p>Using this new version of method your class <code>Solution</code> can be rewritten in this way:</p>\n\n<pre><code>public class NewSolution {\n public static void main(String[] args) throws IOException {\n String outputFile;\n String sourceToCopy;\n String sourceToAppend;\n\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {\n System.out.println(\"Enter a filename for the output:\");\n outputFile = reader.readLine();\n System.out.println(\"Enter the path of the file to be copied\");\n sourceToCopy = reader.readLine();\n System.out.println(\"Enter the path of the file to be appended\");\n sourceToAppend = reader.readLine();\n }\n FileProcessor.copyFile(sourceToCopy, sourceToAppend, outputFile);\n }\n}\n</code></pre>\n\n<p>Below the new version of class <code>FileProcessor</code>:</p>\n\n<pre><code>public class FileProcessor {\n\n public static void copyFile(String sourceToCopy, String sourceToAppend, String outputFile) throws IOException {\n\n Files.copy(Paths.get(sourceToCopy), Paths.get(outputFile), StandardCopyOption.REPLACE_EXISTING);\n Files.copy(Paths.get(sourceToAppend), new FileOutputStream(outputFile, true));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T08:17:32.667",
"Id": "476995",
"Score": "0",
"body": "Wow that looks way tidier, I'll have a look at the usage of Files class. For the exercise, it was demanted I created a file input stream, but it looks like something great to add to my file handling arsenal. Thanks for the reply, grazie mille!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T09:07:11.930",
"Id": "477000",
"Score": "0",
"body": "@PabloAguirredeSouza You are welcome, the `Files`class contains several methods for operations like move, copy, delete like filesystem operations that can help you to write less code about files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T07:18:33.887",
"Id": "243050",
"ParentId": "243005",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "243007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T12:13:26.733",
"Id": "243005",
"Score": "0",
"Tags": [
"java"
],
"Title": "Architecture and error handling in simple java program"
}
|
243005
|
<p>I decided to make my own data structure. I did this because I wanted a data structure that is a queue but has o(1) time on lookup.
</p>
<pre><code> template <class Object>
class ObjectQueue;
template <class Object>
class ObjectQueueNode: private NonCopyable
{
friend class ObjectQueue<Object>;
public:
ObjectQueueNode(const glm::ivec3& position)
: position(position),
previous(nullptr),
next(nullptr)
{}
ObjectQueueNode(ObjectQueueNode&& orig) noexcept
: position(orig.position),
previous(orig.previous),
next(orig.next)
{
orig.previous = nullptr;
orig.next = nullptr;
}
ObjectQueueNode& operator=(ObjectQueueNode&& orig) noexcept
{
position = orig.position;
previous = orig.previous;
next = orig.next;
orig.previous = nullptr;
orig.next = nullptr;
return *this;
}
const glm::ivec3& getPosition() const
{
return position;
}
private:
glm::ivec3 position;
Object* previous;
Object* next;
};
struct PositionNode : public ObjectQueueNode<PositionNode>
{
PositionNode(const glm::ivec3& position)
: ObjectQueueNode(position)
{}
};
template <class Object>
class ObjectQueue : private NonCopyable, private NonMovable
{
public:
ObjectQueue()
: m_initialObjectAdded(nullptr),
m_recentObjectAdded(nullptr),
m_container()
{}
void add(Object&& newObject)
{
glm::ivec3 position = newObject.position;
if (m_container.empty())
{
assert(!m_initialObjectAdded && !m_recentObjectAdded);
Object& addedObject = m_container.emplace(std::piecewise_construct,
std::forward_as_tuple(position),
std::forward_as_tuple(std::move(newObject))).first->second;
addedObject.previous = nullptr;
m_initialObjectAdded = &addedObject;
m_recentObjectAdded = &addedObject;
}
else if (m_container.size() == 1)
{
assert(m_initialObjectAdded && m_recentObjectAdded);
Object& addedObject = m_container.emplace(std::piecewise_construct,
std::forward_as_tuple(position),
std::forward_as_tuple(std::move(newObject))).first->second;
addedObject.previous = m_initialObjectAdded;
m_initialObjectAdded->next = &addedObject;
m_recentObjectAdded = &addedObject;
}
else if (m_container.size() > 1)
{
assert(m_initialObjectAdded && m_recentObjectAdded);
Object& addedObject = m_container.emplace(std::piecewise_construct,
std::forward_as_tuple(position),
std::forward_as_tuple(std::move(newObject))).first->second;
addedObject.previous = m_recentObjectAdded;
m_recentObjectAdded->next = &addedObject;
m_recentObjectAdded = &addedObject;
}
}
bool contains(const glm::ivec3& position) const
{
return m_container.find(position) != m_container.cend();
}
bool isEmpty() const
{
return m_container.empty();
}
Object* next(Object* object)
{
assert(m_initialObjectAdded && m_recentObjectAdded && !m_container.empty());
if (object)
{
return object->next;
}
else
{
return nullptr;
}
}
Object& front()
{
assert(m_initialObjectAdded && m_recentObjectAdded && !m_container.empty());
auto iter = m_container.find(m_initialObjectAdded->position);
assert(iter != m_container.end());
return iter->second;
}
void pop()
{
assert(m_initialObjectAdded && m_recentObjectAdded && !m_container.empty());
auto iter = m_container.find(m_initialObjectAdded->position);
assert(iter != m_container.end());
if (m_container.size() == 1)
{
assert(m_initialObjectAdded == m_recentObjectAdded);
m_initialObjectAdded = nullptr;
m_recentObjectAdded = nullptr;
}
else if (m_container.size() > 1)
{
assert(m_initialObjectAdded->next);
m_initialObjectAdded = m_initialObjectAdded->next;
m_initialObjectAdded->previous = nullptr;
}
m_container.erase(iter);
}
Object* remove(const glm::ivec3& position)
{
auto iter = m_container.find(position);
if (iter != m_container.end())
{
assert(m_initialObjectAdded && m_recentObjectAdded);
Object* previousObject = iter->second.previous;
Object* nextObject = iter->second.next;
//Top
if (!nextObject && previousObject)
{
m_recentObjectAdded = previousObject;
m_recentObjectAdded->next = nullptr;
previousObject->next = nullptr;
}
//Bottom
else if (!previousObject && nextObject)
{
m_initialObjectAdded = nextObject;
m_initialObjectAdded->previous = nullptr;
nextObject->previous = nullptr;
}
//Inbetween
else if (previousObject && nextObject)
{
previousObject->next = nextObject;
nextObject->previous = previousObject;
}
else
{
assert(m_container.size() == 1);
m_initialObjectAdded = nullptr;
m_recentObjectAdded = nullptr;
}
m_container.erase(iter);
return nextObject;
}
return nullptr;
}
private:
Object* m_initialObjectAdded;
Object* m_recentObjectAdded;
std::unordered_map<glm::ivec3, Object> m_container;
};
</code></pre>
|
[] |
[
{
"body": "<h2>Question</h2>\n\n<p>Why not just use existing containers so you don't need to manage anything.</p>\n\n<pre><code>class ObjectQueue\n{\n private:\n std::unordered_map<K, V> container; // container to hold object\n std::list<V*> list; // list to make your queue?\n};\n</code></pre>\n\n<h2>Limiting Observation</h2>\n\n<p>Your <code>Object</code> type can't be any object. It has to have a member <code>position</code> that acts as the key in the container. The type of this key has to be <code>glm::ivec3</code>which is a bit limiting.</p>\n\n<pre><code>glm::ivec3 position = newObject.position;\n</code></pre>\n\n<p>Normally we would allow the container to specialize the key or provide an access function to get the key.</p>\n\n<pre><code>template<typename V, typename K = typename V::Key, typename F = std::function<K(V const&)>>\nclass MyContainer\n{\n // In Here\n // V is the object you are storing\n // K is the key type used.\n // By default this is defined in V as V::Key\n // But can be overridden if the V type does not have a Key type.\n // F Is the type of the function that is used to retrieve the Key\n // from an object of type V.\n //\n\n // Now we provide a constructor\n // That sets up the key getter method.\n // We can default it to return the position member of object.\n MyContainer(F&& keyGetter = [](V const& o){return o.position})\n : kyeGetter(std::move(keyGetter))\n {}\n\n bool insert(V&& object) {\n K key = keyGetter(object);\n auto insert = m_container.emplace(std::piecewise_construct,\n std::forward_as_tuple(std::move(key)),\n std::forward_as_tuple(std::move(newObject)));\n\n if (insert.first) { // otherwise it was not inserted.\n // You may want it in your list twice\n // But you have to remember that a container item\n // may have more than one entry in the list.\n m_list.emplace_back(&insert.second);\n }\n return insert.first;\n }\n\n};\n</code></pre>\n\n<h2>Some Code Review</h2>\n\n<p>Your move operations are acting more like a copy:</p>\n\n<pre><code>ObjectQueueNode(ObjectQueueNode&& orig) noexcept\n : position(orig.position), // This is a copy\n previous(orig.previous), // This is a copy (but a pointer so don't care)\n next(orig.next) // This is a copy (but a pointer)\n{\n orig.previous = nullptr;\n orig.next = nullptr;\n}\nObjectQueueNode& operator=(ObjectQueueNode&& orig) noexcept\n{\n position = orig.position; // This is a copy. Add std::move\n previous = orig.previous;\n next = orig.next;\n\n orig.previous = nullptr;\n orig.next = nullptr;\n\n return *this;\n}\n</code></pre>\n\n<p>The more standard implementation is:</p>\n\n<pre><code>ObjectQueueNode(ObjectQueueNode&& orig) noexcept\n : previous(nullptr)\n , next(nullptr)\n{\n swap(orig);\n}\nObjectQueueNode& operator=(ObjectQueueNode&& orig) noexcept\n{\n swap(orig);\n\n orig.previous = nullptr;\n orig.next = nullptr;\n\n return *this;\n}\n</code></pre>\n\n<hr>\n\n<p>This is a long windid:</p>\n\n<pre><code>struct PositionNode : public ObjectQueueNode<PositionNode>\n{\n PositionNode(const glm::ivec3& position)\n : ObjectQueueNode(position)\n {}\n};\n</code></pre>\n\n<p>Can be simplified to:</p>\n\n<pre><code>using PositionNode = ObjectQueueNode<PositionNode>;\n</code></pre>\n\n<hr>\n\n<p>These two conditions are the same:</p>\n\n<pre><code> else if (m_container.size() == 1)\n {\n assert(m_initialObjectAdded && m_recentObjectAdded);\n Object& addedObject = m_container.emplace(std::piecewise_construct,\n std::forward_as_tuple(position),\n std::forward_as_tuple(std::move(newObject))).first->second;\n\n addedObject.previous = m_initialObjectAdded;\n m_initialObjectAdded->next = &addedObject;\n m_recentObjectAdded = &addedObject;\n }\n else if (m_container.size() > 1)\n {\n assert(m_initialObjectAdded && m_recentObjectAdded);\n Object& addedObject = m_container.emplace(std::piecewise_construct,\n std::forward_as_tuple(position),\n std::forward_as_tuple(std::move(newObject))).first->second;\n\n addedObject.previous = m_recentObjectAdded;\n m_recentObjectAdded->next = &addedObject;\n m_recentObjectAdded = &addedObject;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:40:33.790",
"Id": "476965",
"Score": "0",
"body": "Fantastic! Thank you so much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:02:42.057",
"Id": "243014",
"ParentId": "243006",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243014",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T13:08:05.380",
"Id": "243006",
"Score": "0",
"Tags": [
"c++",
"performance"
],
"Title": "Wrote My own data structure. Mixture of a doubly linked list & unordered map C++"
}
|
243006
|
<p>After following up <a href="https://stackoverflow.com/questions/55129480/styled-text-in-vue-interpolation">this question</a>, I'm thinking if there's a better/shorter way to write this text element that has part with different style, while allowing localizations:</p>
<pre><code><p>
<span class="has-text-grey">{{ $store.releaseList != null ? $store.releaseList.length : 0 }}</span>
<span> versions released</span>
</p>
</code></pre>
<p>With <code>vue-i18n</code>:</p>
<pre><code><p v-html="$t('downloads.releases.table.versions-total')
.replace('{0}', '<span class=has-text-grey>{1}</span>')
.replace('{1}', $store.releaseList != null ? $store.releaseList.length : 0)">
</p>
</code></pre>
<p>The localizable text would be <code>{0} versions released</code>.</p>
<p>I could set the localizable text to <code><span class=has-text-grey>{0}</span> versions released</code>, but that would make the life of the translators (usually people without knowledge about HTML) a bit more difficult.</p>
<p>Is there any better built in way to add support for localizations in a multi-styled text?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T14:19:39.070",
"Id": "243009",
"Score": "2",
"Tags": [
"html",
"i18n",
"vue.js"
],
"Title": "Localization of multi style text element in Vue"
}
|
243009
|
<p>I have created a <a href="https://codereview.stackexchange.com/q/228912/181325">database</a> using Django. I have a small statistics page as shown below. Can I improve this code?</p>
<p>View file</p>
<pre><code>def statistics(request):
""" Return the number of categories (Category is based on first
three-letter character, say Cry in the example) in the database
and its corresponding count.
The holotype is a protein name that ends in 1. Example: Cry1Aa1
A holotype is a single protein name used to name the lower rank based on identity.
Cry1Aa2 is named based on the identity to Cry1Aa1
"""
category_count = {}
category_holotype_count = {}
category_prefixes = []
total_holotype = 0
categories = \
PesticidalProteinDatabase.objects.order_by(
'name').values_list('name', flat=True).distinct()
for category in categories:
cat = category[:3]
if category[-1] == '1' and not category[-2].isdigit():
total_holotype += 1
count = category_holotype_count.get(cat, 0)
count += 1
category_holotype_count[cat] = count
category_count['Holotype'] = [total_holotype] * 2
for category in categories:
prefix = category[0:3]
if prefix not in category_prefixes:
category_prefixes.append(prefix)
for category in category_prefixes:
count = PesticidalProteinDatabase.objects.filter(
name__istartswith=category).count()
category_count[category] = [
count, category_holotype_count.get(category, 0)]
prefix_count_dictionary = {}
for prefix in category_prefixes:
prefix_count_dictionary[prefix] = category_count[prefix][0]
prefix_count_dictionary.pop('Holotype', None)
context = \
{'category_prefixes': category_prefixes,
'category_count': category_count}
return render(request, 'database/statistics.html', context)
</code></pre>
<p>Urls file</p>
<pre><code> path('statistics/', views.statistics,
name='statistics'),
</code></pre>
<p>Sample HTML file</p>
<pre><code><b>General Statistics</b>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>No</th>
<th>Category</th>
<th>Total Count</th>
<th>Holotype Count</th>
</tr>
{% for key,value in category_count.items %}
<tr>
<td> {{ forloop.counter }} </td>
<td> {{ key }} </td>
<td> {{ value.0 }} </td>
<td> {{ value.1 }} </td>
</tr>
{% endfor %}
<thead>
<table>
</code></pre>
<p><a href="https://i.stack.imgur.com/n5nx1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n5nx1.png" alt="Display page"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:37:30.817",
"Id": "476936",
"Score": "2",
"body": "Please show more of your code, including what produces `request`."
}
] |
[
{
"body": "<p>The first <code>for</code> loop can be simplified a lot by using <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>. The generation of the distinct <code>category_prefixes</code> using a <code>set</code> and the final <code>category_count</code> dictionary using a <a href=\"https://www.datacamp.com/community/tutorials/python-dictionary-comprehension\" rel=\"nofollow noreferrer\">dictionary comprehension</a>:</p>\n\n<pre><code>db = PesticidalProteinDatabase\ncategories = db.objects.order_by('name').values_list('name', flat=True).distinct()\nholotype_counts = Counter(category[:3] for category in categories\n if category[-1] == '1' and not category[-2].isdigit())\n\ncategory_prefixes = sorted({category[:3] for category in categories})\ncategory_count = {cat: [db.objects.filter(name__istartswith=cat).count(), \n holotype_counts[cat]]\n for cat in category_prefixes}\ncategory_count['Holotype'] = [sum(holotype_counts.values())] * 2\n</code></pre>\n\n<p>Note that <code>PesticidalProteinDatabase</code> is not a name following Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for variables and functions and <code>PascalCase</code> only for classes (not instances of classes).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T18:26:10.520",
"Id": "243022",
"ParentId": "243011",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T16:51:51.377",
"Id": "243011",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"django"
],
"Title": "Statistics function"
}
|
243011
|
<p>Following This post : <a href="https://stackoverflow.com/questions/630803/associating-enums-with-strings-in-c-sharp/56482413?noredirect=1#comment107635743_56482413">https://stackoverflow.com/questions/630803/associating-enums-with-strings-in-c-sharp/56482413?noredirect=1#comment107635743_56482413</a> </p>
<p>I wanted to go further as it didn't quite fully met my needs for a Enum like Class that would act as string I ended-up with a solution that allows me to do the following: </p>
<pre><code> string test1 = TestEnum.Analyze; //test1 == "ANALYZE"
string test1bis = (string)TestEnum.Analyze; //test1bis == "ANALYZE"
TestEnum test2 = "ANALYZE"; //test2 == {ANALYZE}
TestEnum test3 = "ANYTHING"; //test3 == null
</code></pre>
<p>As seen below in the unitTests all these work fine with this:</p>
<pre><code> public class TestEnum : EnumType<TestEnum>
{
public static TestEnum Analyze { get { return new EnumType<TestEnum>("ANALYZE"); } }
public static TestEnum Test { get { return new EnumType<TestEnum>("TEST"); } }
public static implicit operator TestEnum(string s) => (EnumType<TestEnum>) s;
public static implicit operator string(TestEnum e) => e.Value;
}
</code></pre>
<p>I can't decide if this solution is elegant or incredibly stupid, It seems to me probably unnecessary complex and I might be messing a much easier solution in any case it could help someone so I'm putting this here.</p>
<pre><code> //for newtonsoft serialization
[JsonConverter(typeof(EnumTypeConverter))]
public class EnumType<T> where T : EnumType<T> , new()
{
public EnumType(string value= null)
{
Value = value;
}
//for servicestack serialization
static EnumType()
{
JsConfig<EnumType<T>>.DeSerializeFn = str =>
{
return (T)str ;
};
JsConfig<EnumType<T>>.SerializeFn = type =>
{
return type.Value;
};
JsConfig<T>.DeSerializeFn = str =>
{
return (T)str;
};
JsConfig<T>.SerializeFn = type =>
{
return type.Value;
};
}
protected string Value { get; set; }
public static T Parse(string s)
{
return (T)s;
}
public override string ToString()
{
return Value;
}
public static EnumType<T> ParseJson(string json)
{
return (T)json;
}
public static implicit operator EnumType<T>(string s)
{
if (All.Any(dt => dt.Value == s))
{
return new T { Value = s };
}
else
{
var ai = new Microsoft.ApplicationInsights.TelemetryClient(Connector.tconfiguration);
ai.TrackException(new Exception($"Value {s} is not acceptable value for {MethodBase.GetCurrentMethod().DeclaringType}, Acceptables values are {All.Select(item => item.Value).Aggregate((x, y) => $"{x},{y}")}"));
return null;
}
}
public static implicit operator string(EnumType<T> dt)
{
return dt?.Value;
}
public static implicit operator EnumType<T>(T dt)
{
if (dt == null) return null;
return new EnumType<T>(dt.Value);
}
public static implicit operator T(EnumType<T> dt)
{
if (dt == null) return null;
return new T { Value = dt.Value };
}
public static bool operator ==(EnumType<T> ct1, EnumType<T> ct2)
{
return (string)ct1 == (string)ct2;
}
public static bool operator !=(EnumType<T> ct1, EnumType<T> ct2)
{
return !(ct1 == ct2);
}
public override bool Equals(object obj)
{
try
{
if(obj.GetType() == typeof(string))
{
return Value == (string)obj;
}
return Value == obj as T;
}
catch(Exception ex)
{
return false;
}
}
public override int GetHashCode()
{
return (!string.IsNullOrWhiteSpace(Value) ? Value.GetHashCode() : 0);
}
public static IEnumerable<T> All
=> typeof(T).GetProperties()
.Where(p => p.PropertyType == typeof(T))
.Select(x => (T)x.GetValue(null, null));
//for serialisation
protected EnumType(SerializationInfo info,StreamingContext context)
{
Value = (string)info.GetValue("Value", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Value",Value);
}
}
</code></pre>
<p>Here are the unit tests:</p>
<pre><code> [TestFixture]
public class UnitTestEnum
{
Connector cnx { get;set; }
private class Test
{
public TestEnum PropertyTest { get; set; }
public string PropertyString { get; set; }
}
[SetUp]
public void SetUp()
{
typeof(EnumType<>)
.Assembly
.GetTypes()
.Where(x => x.BaseType?.IsGenericType == true && x.BaseType.GetGenericTypeDefinition() == typeof(EnumType<>))
.Each(x =>
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(x.BaseType.TypeHandle)
);
cnx = new Connector();
}
[TearDown]
public void Clear()
{
cnx.Dispose();
}
[Test]
public void EqualsString()
{
Assert.AreEqual(TestEnum.Analyze, TestEnum.Analyze);
Assert.AreEqual(TestEnum.Analyze,"ANALYZE");
Assert.IsTrue("ANALYZE" == TestEnum.Analyze);
Assert.IsTrue("ANALYZE".Equals(TestEnum.Analyze));
}
[Test]
public void Casts()
{
string test1 = TestEnum.Analyze;
string test1bis = (string)TestEnum.Analyze;
TestEnum test2 = "ANALYZE";
TestEnum test3 = "NAWAK";
Assert.AreEqual("ANALYZE", test1);
Assert.AreEqual("ANALYZE", test1bis);
Assert.IsTrue(test2 == TestEnum.Analyze);
Assert.IsTrue(test2.Equals(TestEnum.Analyze));
Assert.AreEqual(test3, null);
}
[Test]
public void Deserializations()
{
new List<TestEnum>
{
(TestEnum)ServiceStack.Text.JsonSerializer.DeserializeFromString("\"ANALYZE\"", typeof(TestEnum)),
"\"ANALYZE\"".FromJson<TestEnum>(),
(TestEnum)Newtonsoft.Json.JsonConvert.DeserializeObject("\"ANALYZE\"", typeof(TestEnum)),
Newtonsoft.Json.JsonConvert.DeserializeObject<TestEnum>("\"ANALYZE\"")
}.Each(testEnum => Assert.AreEqual(testEnum, TestEnum.Analyze));
new List<Test>
{
"{\"PropertyTest\":\"ANALYZE\",\"PropertyString\":\"ANALYZE\"}".FromJson<Test>(),
(Test)ServiceStack.Text.JsonSerializer.DeserializeFromString("{\"PropertyTest\":\"ANALYZE\",\"PropertyString\":\"ANALYZE\"}", typeof(Test)),
Newtonsoft.Json.JsonConvert.DeserializeObject<Test>("{\"PropertyTest\":\"ANALYZE\",\"PropertyString\":\"ANALYZE\"}"),
(Test)Newtonsoft.Json.JsonConvert.DeserializeObject("{\"PropertyTest\":\"ANALYZE\",\"PropertyString\":\"ANALYZE\"}",typeof(Test))
}.Each(test =>
{
Assert.AreEqual(test.PropertyTest, TestEnum.Analyze);
Assert.AreEqual(test.PropertyString, "ANALYZE");
});
}
[Test]
public void Serialisations()
{
Assert.AreEqual("{\"PropertyTest\":\"ANALYZE\",\"PropertyString\":\"ANALYZE\"}", new Test { PropertyTest = TestEnum.Analyze, PropertyString = TestEnum.Analyze }.ToJson());
Assert.AreEqual("{\"PropertyTest\":\"ANALYZE\",\"PropertyString\":\"ANALYZE\"}", Newtonsoft.Json.JsonConvert.SerializeObject(new Test { PropertyTest = TestEnum.Analyze, PropertyString = TestEnum.Analyze }));
Assert.AreEqual("\"ANALYZE\"", TestEnum.Analyze.ToJson());
Assert.AreEqual("\"ANALYZE\"", Newtonsoft.Json.JsonConvert.SerializeObject(TestEnum.Analyze));
}
[Test]
public void TestEnums()
{
Assert.AreEqual(TestEnum.All.Count(), 2);
Assert.Contains(TestEnum.Analyze,TestEnum.All.ToList());
Assert.Contains(TestEnum.Test,TestEnum.All.ToList());
}
</code></pre>
|
[] |
[
{
"body": "<p>I won't comment on the <code>Json</code> stuff, as it doesn't seem to be the main subject to the question.</p>\n\n<p>I'm not sure, I quite understand where to use this, so if you have a concrete real use case feel free to update the question with it.</p>\n\n<p>You can't for instance use it in a switch like:</p>\n\n<pre><code> TestEnum te = TestEnum.Analyze;\n\n switch (te)\n {\n case TestEnum.Analyze:\n Console.WriteLine(\"Analyze\");\n break;\n case TestEnum.Test:\n Console.WriteLine(\"Test\");\n break;\n default:\n break;\n }\n</code></pre>\n\n<p>because the-enum properties aren't constant.</p>\n\n<p>You can do:</p>\n\n<pre><code> TestEnum te = TestEnum.Analyze;\n\n switch (te)\n {\n case TestEnum t when t == TestEnum.Analyze:\n Console.WriteLine(\"Analyze\");\n break;\n case TestEnum t when t == TestEnum.Test:\n Console.WriteLine(\"Test\");\n break;\n default:\n break;\n }\n</code></pre>\n\n<p>but IMO that may be tedious in the long run.</p>\n\n<hr>\n\n<p>The overall impression is, that your cast system is messy. Trying to debug it to find a way for a string or an enum value is confusing, and you (I) easily lose track of the path. IMO you rely too heavily on casting to and from <code>string</code>.</p>\n\n<hr>\n\n<p>Be aware, that this:</p>\n\n<blockquote>\n <p><code>public static TestEnum Analyze { get { return new EnumType<TestEnum>(\"ANALYZE\"); } }</code></p>\n</blockquote>\n\n<p>is different than this:</p>\n\n<pre><code>public static TestEnum Analyze { get; } = new EnumType<TestEnum>(\"ANALYZE\");\n</code></pre>\n\n<p>Where the first returns a new instance of <code>Analyze</code> for every call, the latter only instantiates one the first time it is called - just like a static (readonly) property or field should behave. Related to that, I think that each \"enum\"-property should be a singleton, and only instantiated once. You instantiate various instances of each property in the cast methods. I don't like that. Further I think, I would make the constructor of <code>TestEnum</code> private to prevent unauthorized instantiation of invalid enum values. If you make the constructor private, you can't specify <code>T</code> with the constraint <code>new()</code>. But that is OK, if you make each <code>enum</code> value a singleton - only instantiated where defined.</p>\n\n<hr>\n\n<p>As for the initialization of the static enum-properties it goes for <code>All</code>:</p>\n\n<blockquote>\n<pre><code>public static IEnumerable<T> All\n => typeof(T).GetProperties()\n .Where(p => p.PropertyType == typeof(T))\n .Select(x => (T)x.GetValue(null, null));\n</code></pre>\n</blockquote>\n\n<p>where</p>\n\n<pre><code>public static IReadOnlyList<T> All { get; } = \n typeof(T).GetProperties()\n .Where(p => p.PropertyType == typeof(T))\n .Select(x => (T)x.GetValue(null, null))\n .ToList();\n</code></pre>\n\n<p>will be much more efficient as reflection is only activated once. Notice that I've changed <code>IEnumerable<T></code> to <code>IReadOnlyList<T></code> in order to cache the query. Repeatedly using reflection may be a bottleneck - especially if you have many enum-properties.</p>\n\n<hr>\n\n<p>You can and should narrow down the properties searched for by using <code>BindingFlags</code> in <code>All</code>: </p>\n\n<pre><code>typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Static)...\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public override bool Equals(object obj)\n {\n try\n {\n if(obj.GetType() == typeof(string))\n {\n return Value == (string)obj;\n }\n\n return Value == obj as T;\n }\n catch(Exception ex)\n {\n return false;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This seems overly complicated and a catch block here is unnecessary:</p>\n\n<pre><code>public override bool Equals(object obj)\n{\n if (obj is T other) return ReferenceEquals(this, other) || Value == other.Value;\n return obj is string value && Value == value;\n}\n</code></pre>\n\n<hr>\n\n<p>Here:</p>\n\n<blockquote>\n<pre><code> public static implicit operator EnumType<T>(string s)\n {\n if (All.Any(dt => dt.Value == s))\n {\n return new T { Value = s };\n }\n</code></pre>\n</blockquote>\n\n<p>I think, I would do:</p>\n\n<pre><code>public static implicit operator EnumType<T>(string s)\n{\n if (All.FirstOrDefault(dt => dt.Value == s) is T e)\n {\n return e;\n }\n else\n</code></pre>\n\n<p>In this way, the already created enum is reused. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-31T13:07:54.243",
"Id": "483943",
"Score": "0",
"body": "Hi, thanks a lot for your input I used it and wanted to do a proper reply but never got the time...\n\nIt does seem alambicated but there are many case where I have a string (for instance coming from an api) and want to compare it with an enum. \n\nI finally found some place where they used the same kind of approach:\n https://github.com/octokit/octokit.net/pull/1595/commits/4cf1ca8b590467134afaf3c0a396f3b15be63c59#diff-62a4dbc88828864f79581a1184638a7c\n\nI might switch to something more like them. (not sure about the serialisation though)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T14:07:15.750",
"Id": "243065",
"ParentId": "243015",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:04:37.370",
"Id": "243015",
"Score": "3",
"Tags": [
"c#",
".net",
".net-core"
],
"Title": "Writing a c# class that has enum like constraint while behaving like string"
}
|
243015
|
<p>I am conversant with <a href="https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm" rel="nofollow noreferrer">Kadane's Algorithm</a>. This is just an exercise in understanding <code>divide and conquer</code> as a technique.</p>
<blockquote>
<p>Find the maximum sum over all subarrays of a given array of positive/negative integers.</p>
</blockquote>
<p>Here is what I have worked on but accumulating sum in <code>solve_partition()</code> looks pretty similar to <code>solve_crossing_partition()</code>, left and right sections. Am I duplicating computation?</p>
<p>I would also appreciate some guidance on the intuition behind moving from <code>mid</code> to <code>low</code> when calculating <code>left_sum</code>: <code>for i in range(m, lo - 1, -1): ...</code></p>
<pre><code>import math
def max_subarray_sum(A):
def solve_crossing_partition(m, lo, hi):
left_sum = -math.inf
_sum = 0
for i in range(m, lo - 1, -1):
_sum += A[i]
left_sum = max(left_sum, _sum)
right_sum = -math.inf
_sum = 0
for j in range(m + 1, hi):
_sum += A[j]
right_sum = max(right_sum, _sum)
return left_sum + right_sum
def solve_partition(lo, hi):
if lo == hi:
return A[lo]
max_sum = -math.inf
_sum = 0
for i in range(lo, hi):
_sum += A[i]
max_sum = max(max_sum, _sum)
return max_sum
if not A:
return 0
m = len(A) // 2
L = solve_partition(0, m + 1)
R = solve_partition(m + 1, len(A))
X = solve_crossing_partition(m, 0, len(A))
return max(max(L, R), X)
if __name__ == "__main__":
for A in (
[],
[-2, 1, -3, 4, -1, 2, 1, -5, 4],
[904, 40, 523, 12, -335, -385, -124, 481, -31],
):
print(max_subarray_sum(A))
</code></pre>
<p>Output:</p>
<pre><code>0
6
1479
</code></pre>
<p>I followed this <a href="https://web.cs.ucdavis.edu/~bai/ECS122A/Notes/Maxsubarray.pdf" rel="nofollow noreferrer">ref</a>.</p>
|
[] |
[
{
"body": "<p>After battling off-by-one errors, I managed to refactor after revisiting the computation model.</p>\n\n<pre><code>import math\n\ndef max_subarray_sum(A):\n def solve_partition(lo, hi):\n if lo == hi - 1:\n return A[lo]\n\n m = lo + (hi - lo) // 2\n L = solve_partition(lo, m)\n R = solve_partition(m, hi)\n\n left_sum = -math.inf\n _sum = 0\n for i in range(m - 1, lo - 1, -1):\n _sum += A[i]\n left_sum = max(left_sum, _sum)\n\n right_sum = -math.inf\n _sum = 0\n for j in range(m, hi):\n _sum += A[j]\n right_sum = max(right_sum, _sum)\n\n return max(max(L, R), left_sum + right_sum)\n\n return solve_partition(0, len(A))\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>>>> print(max_subarray_sum([4, -1, 2, 1])\n6\n</code></pre>\n\n<p>Recursion Tree, (maximum sum in brackets):</p>\n\n<pre><code> [4, -1, 2, 1] (6)\n / \\\n [4, -1](3) [2, 1](3) \n / \\ / \\\n [4](4) [-1](-1) [2](2) [1](1)\n / \\ / \\\n 4 -1 2 1\n</code></pre>\n\n<p>Moving from <code>mid</code> to <code>low</code> appears to be just how the algorithm works, moving in the opposite direction, yields inaccurate results when calculating the cross section.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:55:11.807",
"Id": "243058",
"ParentId": "243019",
"Score": "0"
}
},
{
"body": "<h2>Nested max</h2>\n<pre><code>max(max(L, R), X)\n</code></pre>\n<p>can be</p>\n<pre><code>max((L, R, X))\n</code></pre>\n<h2>Actual tests</h2>\n<p>Assert what you're expecting:</p>\n<pre><code>assert 0 == max_subarray_sum([])\nassert 6 == max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])\nassert 1479 == max_subarray_sum([904, 40, 523, 12, -335, -385, -124, 481, -31])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T15:29:45.053",
"Id": "244617",
"ParentId": "243019",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:36:33.537",
"Id": "243019",
"Score": "3",
"Tags": [
"python",
"recursion",
"divide-and-conquer"
],
"Title": "Max Contiguous Subarray: Divide and Conquer"
}
|
243019
|
<p>I have this little server at home, which is hosting some websites, school stuff and a minecraft server. I made this backup script and I would like some feedback since I'm not very good at scripting.</p>
<pre><code>#!/bin/bash
# declare folders to backup
dirs=(
"/home/ferre/Minecraft"
"/var/lib/automysqlbackup/daily"
);
# backup names
names=(
"Minecraft"
"Mysql"
);
# backup folder
backupdir="/mnt/backup";
# backup algorithm
for (( i=0; i<=$(( ${#dirs[*]} -1 )); i++))
do
# info
echo "starting backup of ${names[i]}";
# create folder
path="${backupdir}/${names[i]}";
$(mkdir -p "$path");
# create backup
file="${path}/$(date +%F).tar";
$(tar -czf "$file" --absolute-names "${dirs[i]}");
# reporting
result=$?;
if [ $result -eq 0 ]; then
echo "SUCCESS";
elif [ $result -eq 1 ]; then
echo "WARNING some files where changed while copying!";
else
echo "FATAL ERROR";
fi
done
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T18:04:06.853",
"Id": "476943",
"Score": "0",
"body": "Welcome to Code Review! Are you running this manually or by automatic (cron) timed job?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:00:37.643",
"Id": "476948",
"Score": "1",
"body": "This is running by a cron job"
}
] |
[
{
"body": "<p>There is not a lot to say, the script is fairly simple.</p>\n\n<p>For the date format:</p>\n\n<pre><code>file=\"${path}/$(date +%F).tar\";\n</code></pre>\n\n<p>I think I would define a <strong>constant</strong> variable at the top of the code. You might want to change the pattern latter (use something different than <code>YYYY-MM-DD</code>).</p>\n\n<p>This:</p>\n\n<pre><code>$(mkdir -p \"$path\");\n</code></pre>\n\n<p>can simply be written as:</p>\n\n<pre><code>mkdir -p \"$path\"\n</code></pre>\n\n<p>unless you want to save the output of the <code>bash</code> command to a variable but this is not the case here.</p>\n\n<hr>\n\n<p>You have some key/pair values to define your backup sources:</p>\n\n<pre><code>dirs=(\n \"/home/ferre/Minecraft\"\n \"/var/lib/automysqlbackup/daily\"\n);\n\n# backup names\nnames=(\n \"Minecraft\"\n \"Mysql\"\n);\n</code></pre>\n\n<p>I would combine both into an <strong>associative array</strong>.</p>\n\n<pre><code>declare -A sources=(\n [\"Minecraft\"]=\"/home/ferre/Minecraft\"\n [\"Mysql\"]=\"/var/lib/automysqlbackup/daily\"\n)\n\nfor item in \"${!sources[@]}\"; do\n echo \"Name: $item => Directory: ${sources[$item]}\"\ndone\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nName: Mysql => Directory: /var/lib/automysqlbackup/daily\nName: Minecraft => Directory: /home/ferre/Minecraft\n</pre>\n\n<p>Thus you can easily loop on the array and extract name and target directory. Warning: please check the syntax. Bash has many pitfalls and I may have made mistakes.</p>\n\n<hr>\n\n<p><strong>Logging</strong>: I think it is important to retain a trace of script execution. Especially when the script is unattended. The console can quickly fill up and you could miss critical messages.</p>\n\n<p>You have a few options like:</p>\n\n<ul>\n<li>define a variable for a log file then use <code>tee -a next</code> next to each command, so that you get output to console and to a file at the same time. But this is tedious and not flexible.</li>\n<li>Call your script like this: <code>/path/to/your/script.sh > backup.log</code> (use <code>>></code> to append) or: <code>/path/to/your/script.sh | tee backup.log</code></li>\n<li>or better yet <code>/path/to/your/script.sh 2>&1 | tee backup.log</code> to capture the output of stderr.</li>\n</ul>\n\n<p>Last but not least, your script could return an <strong>exit code</strong>. This is useful if your script is going to be handled by another script or even set up as a service.</p>\n\n<hr>\n\n<p>Suggestions:</p>\n\n<ul>\n<li>Have the script send you the log file by E-mail after execution. Or archive the log file somewhere for later review if desired.</li>\n<li>Add <strong>error handling</strong> to make your script more reliable and more robust. If something wrong happens, or at least a fatal error, the script should stop and alert you. Here is an intro: <a href=\"https://linuxhint.com/bash_error_handling/\" rel=\"nofollow noreferrer\">Bash Error Handling</a></li>\n</ul>\n\n<p>A backup script is usually critical, it has to perform reliably. One day, you may need to restore some important files, or recover from a system crash. There is nothing more tragic than useless/incomplete backups.</p>\n\n<p>So you should also <strong>test your backups</strong> manually from time to time. Attempt to restore a random file and verify the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:35:18.310",
"Id": "476986",
"Score": "0",
"body": "Can you split the `declare -A` into multiple lines? This would make them easier readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:37:03.007",
"Id": "476987",
"Score": "0",
"body": "I don't think the date format will ever change. Once you have come to the ISO format, there's no reason to change to anything else."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:47:50.097",
"Id": "243035",
"ParentId": "243020",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243035",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T17:38:00.107",
"Id": "243020",
"Score": "2",
"Tags": [
"bash",
"shell"
],
"Title": "Feedback on my bash backup script"
}
|
243020
|
<p>I am looking for feedback on screen reader improvements for the code/example below.</p>
<p>The Select2 pillbox control needs to be more accessible. They have an open issues on this subject <a href="https://github.com/select2/select2/issues/3744" rel="nofollow noreferrer">Select2 Issue Page</a> and after I get more feedback will submit change suggestions to them (or submit a branch with the changes).</p>
<p>My Goals in the following code is:</p>
<ol>
<li>Start to Finish Experience</li>
<li>When user first gets to control it needs to read out load what items are select
a.The Search Box Input is in the last <LI> and causes confusion, will uses ROLE to change this. </li>
<li>Give user 1 simple way to remove item or all selected items
a. screen reader hide individual remove, too much confusion caused having many ways to do it.</li>
<li>When input selected give clear instructions for usage (filter list, open list, how to navigate)</li>
<li>When dynamically generated available item open and user navigates thought them, tell them what is selected and not selected.
a. Double check Aria tag usage.
b. Tell User they can select and un-select items </li>
</ol>
<p>My working example is on fiddlejs <a href="https://jsfiddle.net/nonoandy/z94dgom7/" rel="nofollow noreferrer">here</a></p>
<p>Also here is a working copy</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>//- nonoandy
$(document).ready(function() {
//this probobly can be done wiht adapters or smarter ways that will take me a lot longer to do lol. -nonoandy
//using this class like a flag to stop circuler reference
var updatedHtmlClass = "select2-skipme";
//init the select2 control
var select2Orginal = $(".select2Control");
select2Orginal.select2();
//find the real select2 control
var select2Control = $(".select2Control").next();
//When screen reader user is arrowing through page (not tabbing through) this will explain the UL
var select2UlDesc = select2Control.find("span.select2-selection");
select2UlDesc.prepend("<span class='sr-only'>Selected Items</span>");
//1. Change the role of the <li> that contains the SearchBox, so screen reader count and reading is more accurate.
//2. Warning! I would like to move the SearchBox out of the <UL> and the remove all BUT Select2 doesnt' work right if you move it (change to div would be best too)
var searchBoxLi = select2Control.find("li.select2-search");
var searchBoxInput = select2Control.find("input.select2-search__field");
if (searchBoxLi) {
//making sure screen reader treat the searchbox <li> as a item
searchBoxLi.attr("role", "search");
//adding in flag for future skips
searchBoxLi.addClass(updatedHtmlClass);
var searchBoxInput = select2Control.find("input.select2-search__field");
if (searchBoxInput) {
//adding in screen reader description to help explain purpose of search box
var searchDescId = select2Orginal.id + "_SearchBox_desc";
searchBoxInput.attr("aria-describedby", searchDescId);
searchBoxLi.append("<div id='" + searchDescId + "' class='sr-only'>Optionally you can type to filter and after activating press Up or Down arrows to select or unselect items</div>")
}
}
//Not tested Yet
//This <span> is inside the <ul> which isn't good syntax but doens't seem to mess with JAWS screen readers
var clearAllSpan = select2Control.find("span.select2-selection__clear");
if (clearAllSpan) {
clearAllSpan.text("<i class='fas fa-times' aria-hidden='true'></i><span class='sr-only'>Remove all items</span>");
}
//When a <li> is added after selection, we need to do a few things
//1. Update the remove <span> with icon because I like that better
//2. Aria Hide the remove-span and leave just selected text for screen readers to find.
// WHY!! because they can select and unselect in the dropdown and there is a "remove all" option. Adding too much stuff makes it confusing. (less is more)
//3. add class-flags in because circular referenes
var selectUl = select2Control.find("ul.select2-selection__rendered");
$(selectUl).on('DOMNodeInserted', 'li', function(e) {
//need "Hooks" or events for custom code when a <li> is added
//DOMNodeInserted is old but faster to uses than MutationObserver #ClearnUp
if (e.currentTarget.className.indexOf(updatedHtmlClass) == -1) {
e.currentTarget.className += " " + updatedHtmlClass;
var newRemoveItemHtml = "<span aria-hidden='true' class='select2-selection__choice__remove' role='presentation' title='Remove " + e.currentTarget.title + "'><i class='fas fa-times'></i></span>" + e.currentTarget.title;
if (e.currentTarget.innerHTML.indexOf(updatedHtmlClass) == -1) {
e.currentTarget.innerHTML = newRemoveItemHtml;
}
}
});
//Select2 dynamically shows a dropdown for selecting or unselecting items
//I want to make sure this list of items is clearly marked as 'Selected' or 'Not Selected'
$('select').on('select2:open', function(e) {
var dynamixULId = "#" + select2Control.find(".select2-selection").attr("aria-owns");
$(dynamixULId).on('DOMNodeInserted', 'li', function(e) {
//AGAIN! need "Hooks" or events for custom code when a <li> is added
//DOMNodeInserted is old but faster to uses than MutationObserver #ClearnUp
var currentLi = $(e.currentTarget);
//it seems the aria-selected is changed after the controls are loaded, so I need a even to trigger and update screen reader text too.
//attrchange is a older extention there could be better ways of doing this #ResearchLater
$(currentLi).attrchange({
trackValues: true,
callback: function(event) {
if (event.attributeName == "aria-selected") {
if (!currentLi.attr("data-select2-data")) {
currentLi.attr("data-select2-data", currentLi.text())
}
//the aria-selected will make the screen reader say "not selected"
currentLi.html("<span class='sr-only'>" +
((event.newValue == "true") ? "Selected" : "") +
"</span>" +
currentLi.attr("data-select2-data"));
}
}
});
});
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
/* background: #20262E;*/
padding: 30px;
font-family: Helvetica;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/attrchange/2.0.1/attrchange.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<div id="banner-message">
<h1>Making the Select2 control more accessible!</h1>
</div>
<div class="form-group">
<label for="select2Control">
Pick People
</label>
<select id="select2Control" class="select2Control form-control" name="things[]" multiple="multiple">
<option value="1">Andy</option>
<option value="2">Bob</option>
<option value="3">Russ</option>
<option value="4">Dave</option>
<option value="5">Matt</option>
<option value="6">Adam</option>
</select>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T18:15:12.503",
"Id": "243021",
"Score": "1",
"Tags": [
"jquery"
],
"Title": "Making Select2 pillbox control more accessible compliant and want feedback (bring your screen reader)"
}
|
243021
|
<p>Hey guys I am trying to improve my Python Programming skills, I tried to build a hangman code.
I know it is not perfect but I works. I am looking for some hints or advice to improve this script.</p>
<pre><code> txt_file = open('dictionnary.txt','r') # Open the file with read option
words = txt_file.readlines() # Read all the lines
words =[word.replace('\n','') for word in words] # Remove '\n' and words is now a list
import random
random_number = random.randint(11,len(words)-1) # Choose a random number between 11 (to avoid words like 'aa', 'aaargh',etc) and the lenght of words
word_to_guess = words[random_number]
user_guesses=['#' for i in word_to_guess]
# Function to check if the input letter is in the world to guess if yes replace '#' with the input letter
def check_index_and_replace(letter):
letter_index=[i[0] for i in enumerate(word_to_guess) if i[1]==letter]
for i in letter_index:
user_guesses[i] = user_guesses[i].replace('#',letter)
return(user_guesses)
# Function to tell how many letter to guess left
def letterleft(user_guesses):
return(user_guesses.count('#'))
# My core code (input and prints)
tries = int(input('How many tries you want ? '))
test = 0
while test < tries+1:
letter = input('Try a letter ')
print(check_index_and_replace(letter))
print(letterleft(user_guesses),'letter left to guess !')
test=test+1
print(word_to_guess)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:31:13.487",
"Id": "476953",
"Score": "3",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] |
[
{
"body": "<h1>Getting lines from a file</h1>\n\n<p>You can use simple list comprehension to get all the lines from a file.</p>\n\n<pre><code>words = [word for word in open(\"dictionary.txt\", \"r\")]\n</code></pre>\n\n<p>However, this does not ensure the file will be closed. To be safe, I would do this:</p>\n\n<pre><code>with open(\"dictionary.txt\", \"r\") as file:\n words = [word for word in file]\n</code></pre>\n\n<p>The <code>with</code> ensures the file will be closed once you're done working with the file.</p>\n\n<h1>Globals</h1>\n\n<p>With a small program like this, globals can be quite helpful since you don't have to pass <code>word_to_guess</code> through functions. However, as you begin to develop more complicated programs, you should be mindful and careful about your globals \"leaking\" into other parts of your programs, should you be using multiple files.</p>\n\n<h1>Random choices</h1>\n\n<p>Instead of generating a random number between the min and max of the list, use <code>random.choice(...)</code> to chose a random word from the dictionary. And if you're worried about the beginning of the alphabet, you can create a buffer variable and splice the list so the beginning of the alphabet is removed.</p>\n\n<pre><code># The first 11 words will be removed from the list #\nbuffer = 11\nword_to_guess = random.choice(words[buffer:])\n</code></pre>\n\n<h1><code>check_index_and_replace</code></h1>\n\n<p>Instead of casting replace on each index, you can use an <code>if</code> statement to make sure the letter is equal to the letter in <code>word_to_guess</code>, and in the same position. If it is, then assign that letter to the position in the list.</p>\n\n<pre><code>from typing import List\n\ndef check_and_replace(letter: str) -> List[str]:\n \"\"\"\n For each character in the word, if that character\n is equal to the passed letter, then the position in\n user_guesses is changed to that letter.\n \"\"\"\n for idx, char in enumerate(word_to_guess):\n if char == letter:\n user_guesses[idx] = letter\n return user_guesses\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>These help yourself and other people looking at your code understand what types of variables are being passed and returned to/from functions. As above, the function accepts a <code>str</code> for <code>letter</code>, and returns a list of strings.</p>\n\n<h1><code>lettersleft</code></h1>\n\n<p>If you have a function that only has one line, most of the time you can delete the function and put that line where the function is called. And since this function utilizes a built-in function to count the occurrences of <code>#</code> in the list, this function doesn't need to be written.</p>\n\n<h1>The main body</h1>\n\n<p>Instead of keeping track for each try, use a <code>for</code> loop and only run as many times as the user inputed. If the user enters <code>4</code>, the loop only runs four times.</p>\n\n<p>When I first played this game, it was impossible to win. I could guess the word, but the game wouldn't end. A quick fix is to check if the number of letters left is <code>0</code>. If it is, display a game won message and exit the program. If it isn't, print how many are left and go through the loop again.</p>\n\n<hr>\n\n<p>All in all, your program would look something like this:</p>\n\n<pre><code>import random\nfrom typing import List\n\nwith open(\"dictionary.txt\", \"r\") as file:\n words = [word for word in file]\nbuffer = 11\nword_to_guess = random.choice(words[buffer:])\nuser_guesses = ['#' for _ in word_to_guess]\n\ndef check_and_replace(letter: str) -> List[str]:\n \"\"\"\n For each character in the word, if that character\n is equal to the passed letter, then the position in\n user_guesses is changed to that letter.\n \"\"\"\n for idx, char in enumerate(word_to_guess):\n if char == letter:\n user_guesses[idx] = letter\n return user_guesses\n\ndef main():\n tries = int(input('How many tries you want? '))\n for _ in range(tries):\n letter = input('Try a letter ')\n print(check_and_replace(letter))\n letters_left = user_guesses.count(\"#\")\n if letters_left == 0:\n print(\"You guessed the word!\")\n quit()\n else:\n print(letters_left, \"letters remaining!\")\n print(\"The word was\", word_to_guess)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T18:06:51.457",
"Id": "477725",
"Score": "0",
"body": "Wow Thank you very much for you reply it helps a lot. However I do not understand why you suggest to close my file 'dictionary.txt'. I read that indeed a file open must be close \"manually\" but I don't understand why I need to close it since I store its content in a list right after I open it. Again thank you very much for your suggestion !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-05T00:19:10.440",
"Id": "477755",
"Score": "1",
"body": "@Ismouss Take a look at [this](https://stackoverflow.com/questions/25070854/why-should-i-close-files-in-python). A great answer about why you should close files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T08:28:23.183",
"Id": "243303",
"ParentId": "243026",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:27:10.820",
"Id": "243026",
"Score": "2",
"Tags": [
"python",
"beginner",
"hangman"
],
"Title": "Beginner Hangman Game"
}
|
243026
|
<p>I'm learning rust by creating a simple card game program, with the usual stuff, ranks, suits etc. Currently I only implemented the card generation and a simple render function (not for future use).</p>
<p>Looking at it, I can abstract some things, in terms of modules:</p>
<ul>
<li>I have a deck generator, it can be for a poker deck with or without jokers (52 or 54 cards), can be a deck with more than two colors, and the list goes on, depending on the game. So I need some type of <strong>abstraction</strong>, which receives a deck type name, or a enum. Another approach would be to have them defined in a external file, perhaps a CSV. But I don't know if this is a good approach.</li>
<li>The render logic cannot mess with the deck generation logic. The deck generator only generates decks and the renderer only renders it.</li>
<li>The same thing happens with game logic. It needs to be in a separate module. There are N ways to play a poker game. Game logic doesn't care about render and deck generation.</li>
</ul>
<p>My question is how it would be approached in Rust. Would I need to create different crates?</p>
<p>Thanks in advance and any errors or bad practices in the code below, I would like to know.</p>
<pre><code>fn main() {
let deck = build_poker_deck(true);
for c in build_poker_deck(true) {
render_card(&c);
}
println!("Generated {} cards.", deck.len());
}
static WHITE_SUITS: [Suit; 2] = [Suit::DIAMONDS, Suit::HEARTS];
static BLACK_SUITS: [Suit; 2] = [Suit::CLUBS, Suit::SPADES];
static RANKS: [Rank; 13] = [Rank::ACE, Rank::TWO, Rank::THREE, Rank::FOUR, Rank::FIVE, Rank::SIX, Rank::SEVEN, Rank::EIGHT, Rank::NINE, Rank::TEN, Rank::JACK, Rank::QUEEN, Rank::KING];
fn build_poker_deck(include_jokers: bool) -> Vec<Card> {
let mut deck: Vec<Card> = Vec::with_capacity(54);
for s in WHITE_SUITS.iter() {
for r in RANKS.iter() {
deck.push(Card {
suit: *s,
rank: *r,
color: 0
});
}
}
for s in BLACK_SUITS.iter() {
for r in RANKS.iter() {
deck.push(Card {
suit: *s,
rank: *r,
color: 1
});
}
}
if include_jokers {
deck.push(Card {
suit: Suit::JOKER,
rank: Rank::JOKER,
color: 0,
});
deck.push(Card {
suit: Suit::JOKER,
rank: Rank::JOKER,
color: 1,
});
}
deck
}
#[derive(Debug, Copy, Clone)]
enum Suit {
DIAMONDS = 0,
CLUBS = 1,
HEARTS = 2,
SPADES = 3,
JOKER = 4,
}
#[derive(Debug, Copy, Clone)]
enum Rank {
ACE = 0,
TWO = 1,
THREE = 2,
FOUR = 3,
FIVE = 4,
SIX = 5,
SEVEN = 6,
EIGHT = 7,
NINE = 8,
TEN = 10,
JACK = 11,
QUEEN = 12,
KING = 13,
JOKER = 14,
}
struct Card {
suit: Suit,
rank: Rank,
color: u8,
}
fn render_card(card: &Card) {
let rendered_suit = if card.color == 0 {
match card.suit {
Suit::DIAMONDS => '♢',
Suit::CLUBS => '♧',
Suit::HEARTS => '♡',
Suit::SPADES => '♤',
Suit::JOKER => '☆',
}
} else {
match card.suit {
Suit::DIAMONDS => '♦',
Suit::CLUBS => '♣',
Suit::HEARTS => '♥',
Suit::SPADES => '♠',
Suit::JOKER => '★',
}
};
let rendered_rank = match card.rank {
Rank::ACE => "A",
Rank::TWO => "2",
Rank::THREE => "3",
Rank::FOUR => "4",
Rank::FIVE => "5",
Rank::SIX => "6",
Rank::SEVEN => "7",
Rank::EIGHT => "8",
Rank::NINE => "9",
Rank::TEN => "10",
Rank::JACK => "J",
Rank::QUEEN => "Q",
Rank::KING => "K",
Rank::JOKER => "J",
};
println!("┌────┐");
if rendered_rank.len() > 1 {
println!("│{} {}│", rendered_suit, rendered_rank);
} else {
println!("│{} {}│", rendered_suit, rendered_rank);
}
println!("│ │");
if rendered_rank.len() > 1 {
println!("│{} {}│", rendered_rank, rendered_suit);
} else {
println!("│{} {}│", rendered_rank, rendered_suit);
}
println!("└────┘");
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The principal problem of your code is that you want modularity but don't really have any:</p>\n\n<ul>\n<li>You use static variable, and they are use directly in your deck generator, this need to recompile the program for each type of card, suit, color and you can't have different type of deck at the same time.</li>\n<li>You want unspecified number of colors but only handle two when printing the deck</li>\n</ul>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::fmt;\n\nconst WHITE_SUITS: [Suit; 2] = [\n Suit::new(SuitKind::DIAMONDS, '♦'),\n Suit::new(SuitKind::HEARTS, '♥'),\n];\n\nconst BLACK_SUITS: [Suit; 2] = [\n Suit::new(SuitKind::CLUBS, '♧'),\n Suit::new(SuitKind::SPADES, '♤'),\n];\n\nconst RANKS: [Rank; 13] = [\n Rank::ACE,\n Rank::TWO,\n Rank::THREE,\n Rank::FOUR,\n Rank::FIVE,\n Rank::SIX,\n Rank::SEVEN,\n Rank::EIGHT,\n Rank::NINE,\n Rank::TEN,\n Rank::JACK,\n Rank::QUEEN,\n Rank::KING,\n];\n\nfn main() {\n env_logger::Builder::new()\n .filter_level(log::LevelFilter::Info)\n .init();\n\n let deck = Deck::new(\n [\n (WHITE_SUITS.iter().copied(), Some('★')),\n (BLACK_SUITS.iter().copied(), Some('☆')),\n ]\n .iter()\n .cloned(),\n RANKS.iter().copied(),\n );\n println!(\"{}\", deck);\n}\n\nstruct Card {\n suit: Suit,\n rank: Rank,\n}\n\n#[derive(Debug, Copy, Clone)]\nenum Rank {\n ACE = 0,\n TWO = 1,\n THREE = 2,\n FOUR = 3,\n FIVE = 4,\n SIX = 5,\n SEVEN = 6,\n EIGHT = 7,\n NINE = 8,\n TEN = 10,\n JACK = 11,\n QUEEN = 12,\n KING = 13,\n JOKER = 14,\n}\n\nimpl AsRef<str> for Rank {\n fn as_ref(&self) -> &'static str {\n match self {\n Rank::ACE => \"A\",\n Rank::TWO => \"2\",\n Rank::THREE => \"3\",\n Rank::FOUR => \"4\",\n Rank::FIVE => \"5\",\n Rank::SIX => \"6\",\n Rank::SEVEN => \"7\",\n Rank::EIGHT => \"8\",\n Rank::NINE => \"9\",\n Rank::TEN => \"10\",\n Rank::JACK => \"J\",\n Rank::QUEEN => \"Q\",\n Rank::KING => \"K\",\n Rank::JOKER => \"J\",\n }\n }\n}\n\n#[derive(Debug, Copy, Clone)]\nenum SuitKind {\n DIAMONDS = 0,\n CLUBS = 1,\n HEARTS = 2,\n SPADES = 3,\n JOKER = 4,\n}\n\n#[derive(Debug, Copy, Clone)]\nstruct Suit {\n kind: SuitKind,\n repr: char,\n}\n\nimpl Suit {\n const fn new(kind: SuitKind, repr: char) -> Self {\n Self { kind, repr }\n }\n}\n\nimpl fmt::Display for Rank {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n writeln!(f, \"{}\", self.as_ref())\n }\n}\n\nstruct Deck {\n deck: Vec<Card>,\n}\n\nimpl Deck {\n fn new<C, S, R, I>(colors: C, ranks: R) -> Self\n where\n C: IntoIterator<Item = (S, Option<char>)>,\n S: IntoIterator<Item = Suit>,\n R: IntoIterator<Item = I::Item, IntoIter = I>,\n I: Clone + Iterator<Item = Rank>,\n {\n log::info!(\"Starting genering cards.\");\n\n let ranks = ranks.into_iter();\n let mut deck: Vec<Card> = Vec::with_capacity(54);\n\n for (suit, joker) in colors.into_iter() {\n for s in suit.into_iter() {\n for r in ranks.clone() {\n deck.push(Card { suit: s, rank: r });\n }\n }\n if let Some(repr) = joker {\n deck.push(Card {\n suit: Suit::new(SuitKind::JOKER, repr),\n rank: Rank::JOKER,\n });\n }\n }\n\n log::info!(\"Generated {} cards.\", deck.len());\n\n Self { deck }\n }\n}\n\nimpl fmt::Display for Card {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n let rank = self.rank.as_ref();\n let suit = self.suit.repr;\n\n writeln!(f, \"┌────┐\")?;\n writeln!(f, \"│{:1.1} {:>2.2}│\", suit, rank)?;\n writeln!(f, \"│ │\")?;\n writeln!(f, \"│{:<2.2} {:1.1}│\", rank, suit)?;\n writeln!(f, \"└────┘\")\n }\n}\n\nimpl fmt::Display for Deck {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n for c in &self.deck {\n writeln!(f, \"{}\", c)?;\n }\n\n Ok(())\n }\n}\n</code></pre>\n\n<p>This example is quite long:</p>\n\n<ul>\n<li>When you want print something always implement <a href=\"https://doc.rust-lang.org/std/fmt/trait.Display.html\" rel=\"nofollow noreferrer\"><code>Display</code></a>, this allow to auto implementation of trait like <a href=\"https://doc.rust-lang.org/std/string/trait.ToString.html\" rel=\"nofollow noreferrer\"><code>ToString</code></a></li>\n<li>Add a lot of generic still limited</li>\n<li>Improve style like use format option, use some trait from std</li>\n<li>Now <code>Suit</code> have a <code>repr</code>, this allow to handle any color</li>\n<li>Now the deck is generate without using any <code>const</code> directly</li>\n<li>Replace static by <a href=\"https://stackoverflow.com/questions/52751597/what-is-the-difference-between-a-const-variable-and-a-static-variable-and-which\"><code>const</code></a></li>\n<li>I left it but there is not reason in your current code to specify variant value.</li>\n<li>Now joker are giving along with colors, in a form of <code>Option<char></code>, this allow handle any color of a joker and allow to add joker for only a selection of color.</li>\n<li>Show example of <a href=\"https://docs.rs/log/0.4.8/log/\" rel=\"nofollow noreferrer\">logging</a> instead of just printing log directly on stdout (bad example because I wanted it's work on playground but setting log level in program is not the right way, it's the user that should set it)</li>\n</ul>\n\n<h1>What you could do next ?</h1>\n\n<p>I didn't push further because that would take a lot of time but if you want more modularity, you will need to use <a href=\"https://doc.rust-lang.org/book/ch10-02-traits.html\" rel=\"nofollow noreferrer\"><code>trait</code></a>, for now, unless you add <code>Rank</code> variant and <code>SuitKind</code> variant you are limited to a specific type of deck. It hard to know in advance what type of trait you could need, you will need to see by yourself when you implement variant of card game what you could share and so use a trait to share behaviour.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T01:44:32.177",
"Id": "477169",
"Score": "0",
"body": "Thank you so much! Very helpful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T23:08:35.060",
"Id": "243040",
"ParentId": "243027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T19:31:18.890",
"Id": "243027",
"Score": "2",
"Tags": [
"game",
"rust"
],
"Title": "How could I modularize this poker card game in rust?"
}
|
243027
|
<p>I have tried implementing an <a href="https://www.cs.auckland.ac.nz/software/AlgAnim/AVL.html" rel="nofollow noreferrer">AVL Tree</a> on my own, based on visualising it. But i'm unsure how many testcases it work with, and how efficient it is. Are there any ways to make it efficient, and compact?</p>
<pre class="lang-py prettyprint-override"><code>class Node:
def __init__(self, value, parent=None):
"""
Every Node has a value, and a height based on how far it is from the root node
"""
self.value = value
self.parent = parent
self.left = None
self.right = None
class AVLTree:
def __init__(self, List=None):
"""
initialising the root which is the first node which is None in an empty Tree
If List keyword argument is provided, then it will insert every value in the List.
"""
self.root = None
if List:
for item in List:
self.insert(item)
def inorder(self, current_node):
"""
Recursive Inorder Traversal of the Binary Tree, to display from smallest to largest, the values in the tree
Ex:
1 2 3 5 6 9
"""
if current_node:
self.inorder(current_node.left)
print(current_node.value, end=' ')
self.inorder(current_node.right)
def get_depth(self, node):
"""
Finds the depth of a specific node, which means the levels of nodes beneath it, also recursive.
Ex: height:
O 0
/ \
O O 1
/ \ / \
O O O O 2
/
O 3
The Depth of root node (height 0) = 3, since there are 3 levels of nodes beneath it
The Depth of left node at (height 1) = 1, since there is only 1 level of nodes beneath it
The Depth of right node at (height 1) = 2, since there are `` 2 `` `` `` `` ``
The Depth of left node of (height 2) = 0, since there are no nodes beneath it
The Depth of a Non Existent Node = 0
"""
# Null node has 0 depth.
if node is None:
return 0
# Get the depth of the left and right subtree
# using recursion.
leftDepth = self.get_depth(node.left)
rightDepth = self.get_depth(node.right)
# Choose the larger one and add the root to it.
if leftDepth > rightDepth:
return leftDepth + 1
elif leftDepth < rightDepth:
return rightDepth + 1
else: # A Node with no children has a depth of 0
return 0
def get_balance_factor(self, node):
"""
Balance_factor is the difference between the heights of the two child node of the node
Rebalancing occurs when the balance_factor is greater than a difference of 1 (or) less than a difference of -1
usage: balance_factor = get_balance_factor(node)
which is left_child_height - right_child_height
If balanced, balance_factor = -1/0/1:
O O O O
/ \ / \ / \ / \
O O O O O O O O
/ \ / \
O O O O
If balance_factor > 1:
O <--- Node
/ \
O O Height = 2
/ \
O O Height = 3
/ \
O O Height = 4
Difference of L and R = 2 (4-2)
If balance_factor < 1:
O <--- Node
/ \
O O Height = 2
/ \
O O Height = 3
/ \
O O Height = 4
Difference of L and R = -2 (2-4)
"""
if node is None:
return
return self.get_depth(node.left) - self.get_depth(node.right)
def rotate_right(self, y):
"""
Rotates right
Ex:
y x
/ \ Right Rotation / \
x T3 - - - - - - - > T1 y
/ \ / \
T1 T2 T2 T3
changed:
1) the left child of y became T2
2) the right child of x became y
3) y's parent now points to x
4) T2's parent is now y if it exists
5) x's parent is now y's parent
"""
# Rotation
parent = y.parent
x = y.left
T2 = x.right
x.right = y
y.left = T2
if T2:
T2.parent = y
x.parent = parent
# If there is no parent, then that means y was the root node
if parent is None:
self.root = x
elif parent.left == y:
parent.left = x
elif parent.right == y:
parent.right = x
def rotate_left(self, x):
"""
Rotates left
Ex:
y x
/ \ / \
x T3 T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3
changed:
1) the left child of y became x
2) the right child of x became T2
3) x's parent now points to y
4) T2's parent is now x if it exists
5) y's parent is now x's parent
"""
# Rotation
parent = x.parent
y = x.right
T2 = y.left
y.left = x
x.right = T2
if T2:
T2.parent = x
y.parent = parent
# If there is no parent, then that means y was the root node
if parent is None:
self.root = y
elif parent.left == x:
parent.left = y
elif y.parent.right == x:
parent.right = y
def recursive_balancing_for_insertion(self, current_node, value):
"""
As the name says, rebalances, by using comparisons between the value to be inserted and child node's value
It slowly checks the balance factor of every node from the parent of the recently inserted node,
after a node has been checked, it goes the parent of that node, until it reaches the root node, which doesn't have a parent /= None.
Depending on the balance factor and comparison, it may perform a left rotation, or right rotation, or even both.
Rotations shift the position of the nodes so that o(log N) operations will still be performed, and prevents skewed trees
Cases:
1) Left Left 2) Right Right
O O
/ \
O O
/ \
O O
2) Right Left 4) Left Right
O O
/ \
O O
\ /
O O
"""
if current_node is None:
return
# Getting the balance factor, which shows if the tree is balanced or not after insertion, by the difference of the heights between the left and right children of the node
balance_factor = self.get_balance_factor(current_node)
# Checks if the node is unbalanced, and if it is, perform one of the 4 cases
# Case 1: Left Left
if balance_factor > 1 and current_node.left:
if value < current_node.left.value:
self.rotate_right(current_node)
# Case 2: Right Right
if balance_factor < -1 and current_node.right:
if value > current_node.right.value:
self.rotate_left(current_node)
# Case 3: Left Right
if balance_factor > 1 and current_node.left:
if value > current_node.left.value:
self.rotate_left(current_node.left)
self.rotate_right(current_node)
# Case 4: Right Left
if balance_factor < -1 and current_node.right:
if value < current_node.right.value:
self.rotate_right(current_node.right)
self.rotate_left(current_node)
self.recursive_balancing_for_insertion(current_node.parent, value)
def recursive_balancing_for_deletion(self, current_node):
"""
As the name says, rebalances, by using balance factor of it's child nodes
It slowly checks the balance factor of every node from the parent of the recently inserted node,
after a node has been checked, it goes the parent of that node, until it reaches the root node, which doesn't have a parent /= None.
Depending on the balance factor and comparison, it may perform a left rotation, or right rotation, or even both.
Rotations shift the position of the nodes so that o(log N) operations will still be performed, and prevents skewed trees
Cases:
1) Left Left 2) Right Right
O O
/ \
O O
/ \
O O
2) Right Left 4) Left Right
O O
/ \
O O
\ /
O O
"""
if current_node is None:
return
balance_factor = self.get_balance_factor(current_node)
# Case 1 - Left Left
if balance_factor > 1 and self.get_balance_factor(current_node.left) >= 0:
self.rotate_right(current_node)
# Case 2 - Right Right
if balance_factor < -1 and self.get_balance_factor(current_node.right) <= 0:
self.rotate_left(current_node)
# Case 3 - Left Right
if balance_factor > 1 and self.get_balance_factor(current_node.left) < 0:
self.rotate_left(current_node.left)
self.rotate_right(current_node)
# Case 4 - Right Left
if balance_factor < -1 and self.get_balance_factor(current_node.right) > 0:
self.rotate_right(current_node.right)
self.rotate_left(current_node)
self.recursive_balancing_for_deletion(current_node.parent)
def insert(self, value):
"""
Inserts a value into the tree, by traversing through the tree till it finds a None.
1) No balancing is done when inserting the root node.
2) Balancing is done for any other node.
"""
NewNode = Node(value)
current_node = self.root
# Traversing through the Tree till we find the right place to put the value
if current_node is None:
self.root = NewNode
else:
while True:
if value < current_node.value:
NewNode.parent = current_node
#Left
if not current_node.left:
current_node.left = NewNode
break
NewNode.parent = current_node
current_node = current_node.left
else:
NewNode.parent = current_node
#Right
if not current_node.right:
current_node.right = NewNode
break
NewNode.parent = current_node
current_node = current_node.right
# Recursive balancing
self.recursive_balancing_for_insertion(current_node, value)
def lookup(self, value):
"""
Searches for a value in the tree,
if the value is found, returns True
if the value isn't found, returns False
"""
current_node = self.root
if current_node is None:
return None
while current_node:
current_value = current_node.value
if value < current_value:
current_node = current_node.left
elif value > current_value:
current_node = current_node.right
else:
return True
return False
def getMin(self, current_node):
"""
returns the smallest value of a node in the current_node, by going left, until there is no more left child nodes
Used to find the in order successor for a node, incase it has two children when removing.
"""
while current_node.left is not None:
current_node = current_node.left
return current_node.value
def remove(self, value, current_node=None):
"""
Removes a value from the tree
returns True, if value was deleted
returns False, if value wasn't found/deleted
Different position changes depending on 3 cases:
1) Node has no children
easiest to remove, just remove the parent nodes pointer to it
2) Node has 1 child
just point the next child of parent node to the next child of the node to be deleted instead
3) Node has 2 children
hardest to remove, first the in order successor of the node is found, by getting the smallest value in the right child node.
Then the node value is replaced with the in order successor, and the inorder successor is recursively deleted.
"""
if not current_node:
current_node = self.root
if not current_node: # if the root is None
return None
parent_node = None
while current_node:
# value of current node
current_value = current_node.value
# If value to be searched is less than the current node value, then move left
if value < current_value:
parent_node = current_node
current_node = current_node.left
# If value to be searched is greater than the current node value, then move right
elif value > current_value:
parent_node = current_node
current_node = current_node.right
# if value to be searched is the current node's value
else:
# No Child
if not current_node.left and not current_node.right:
# If there is no parent node, then it is the root node
if parent_node is None:
self.root = None
elif current_node == parent_node.left:
parent_node.left = None
else:
parent_node.right = None
self.recursive_balancing_for_deletion(current_node)
# One Child
elif current_node.right and not current_node.left:
if parent_node is None:
self.root = current_node.right
elif current_node == parent_node.left:
parent_node.left = current_node.right
else:
parent_node.right = current_node.right
current_node.right.parent = parent_node
current_node.right = None
self.recursive_balancing_for_deletion(current_node)
elif current_node.left and not current_node.right:
if parent_node is None:
self.root = current_node.left
elif current_node == parent_node.left:
parent_node.left = current_node.left
else:
parent_node.right = current_node.left
current_node.left.parent = parent_node
current_node.left = None
self.recursive_balancing_for_deletion(current_node)
# Two Child
else:
# gets the successor of the current_node
in_order_successor = self.getMin(current_node.right)
# Removes the successor to replace the node to be removed
self.remove(in_order_successor, current_node)
#if the node to be removed is the root node
if parent_node is None:
self.root.value = in_order_successor
elif current_node == parent_node.left:
parent_node.left.value = in_order_successor
else:
parent_node.right.value = in_order_successor
self.recursive_balancing_for_deletion(parent_node)
current_node.parent = None
return True # if removed
return False # if value doesnt exist
test = AVLTree((1, 2, 3, 4, 5))
#test.remove(3)
#test.remove(1)
#test.remove(2)
#test.remove(4)
#test.remove(5)
#print(test.lookup(5))
test.inorder(test.root)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-04T02:13:46.867",
"Id": "532224",
"Score": "0",
"body": "`get_depth()` has *depth* and *height* backwards."
}
] |
[
{
"body": "<p>I believe it's usual, and more efficient to store the balance of each node ( -1, 0, +1 ) in the node rather than computing it each time.</p>\n<p>Another point : I think you could use some more elif statements, only one kind of rotation will apply.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:30:52.950",
"Id": "245013",
"ParentId": "243028",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:08:37.647",
"Id": "243028",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"tree",
"binary-tree"
],
"Title": "AVL Tree implementation Based on VisualGo"
}
|
243028
|
<pre><code>import requests
import json
import time
f = open('ok.txt', 'r')
c = f.read()
r = []
start = time.perf_counter()
def steamCheck(name):
return requests.get("https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=removed&vanityurl=%s" % (name)).json()
for word in c.split():
p = steamCheck(word)
if p['response']['success'] == 42:
with open('www.txt', 'a') as save:
save.write(word + '\n')
print('%s is available' % (word))
r.append(word)
else:
print('%s is taken' % (word))
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
</code></pre>
<p>Hi this is a script I made to check if each word from a list exists as a vanityurl on steam or not.
I removed the api key so if you wanted to test yourself you would have to get one here :
<a href="https://steamcommunity.com/dev/apikey" rel="nofollow noreferrer">https://steamcommunity.com/dev/apikey</a></p>
<p>I am a beginner in python and would like to know how you would change my script to make it better (faster, cleaner, etc..).
So far it works as intended however it is fairly slow and believe I may be doing something inefficiently.
Thanks for any advice you may have. </p>
<p>Example response from api if url is not taken:</p>
<pre><code>{'response': {'success': 42, 'message': 'No match'}}
</code></pre>
<p>Example if the url IS taken:</p>
<pre><code>{"response": {"steamid": "76561198868XXXXXX", "success": 1}}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:27:56.200",
"Id": "476959",
"Score": "1",
"body": "Hi, would be good if you can provide example response of that api request to give us better idea of the code without having to get api key :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:31:12.503",
"Id": "476961",
"Score": "2",
"body": "sorry about that @K.H. , i've added the 2 possible responses to the thread"
}
] |
[
{
"body": "<p>This is a good start for a script. The next step should be separating in-/output from the functions doing the actual work.</p>\n\n<p>In addition, whenever you make multiple requests to the same server, you should use a <a href=\"https://2.python-requests.org/en/v1.1.0/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>requests.Session</code></a>, which will re-use the connection. You can also pass a dictionary <code>params</code> which will be the URL-encoded parameters for the request. The <code>Session</code> can take a default value for that.</p>\n\n<p>You should always use <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code></a> when opening a file or resource. This way it is ensured that it is closed properly, even if an exception occurs during the intervening code.</p>\n\n<p>You can write multiple rows at once using <a href=\"https://www.tutorialspoint.com/python/file_writelines.htm\" rel=\"nofollow noreferrer\"><code>writelines</code></a>. You can even pass an iterable to this function and it will iterate for you.</p>\n\n<p>I would write your script something like this:</p>\n\n<pre><code>import requests\n\nURL = \"https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/\"\nPARAMS = {\"key\": \"removed\"}\n\ndef url_available(session, url):\n response = session.get(URL, params={\"vanityurl\": url}).json()\n return response['response']['success'] == 42\n\ndef main():\n session = requests.Session()\n session.params = PARAMS\n with open('ok.txt') as in_file, open('www.txt', 'w') as out_file:\n out_file.writelines(url for url in in_file\n if url_available(session, url.strip()))\n\nif __name__ == \"__main__\":\n with Timer(\"main\"):\n main()\n</code></pre>\n\n<p>To this you should add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> to each function describing what it does, but that is left as an exercise :).</p>\n\n<p>Here <code>Timer</code> is a simple class that starts a timer when the context is entered and reports the result when the <code>with</code> block is finished:</p>\n\n<pre><code>from time import perf_counter\n\nclass Timer:\n def __init__(self, name):\n self.name = name\n\n def __enter__(self):\n self.start = perf_counter\n\n def __exit__(self, *args):\n diff = round(perf_counter() - self.start, 2)\n print(f'{self.name} finished in {diff} second(s)')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:18:50.310",
"Id": "476963",
"Score": "0",
"body": "Thank you for your input, I will be sure to follow the advice you have given and this looks nice I will try my best to learn from this and implement it into my own code. @Graipher"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:40:56.880",
"Id": "243030",
"ParentId": "243029",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T20:15:43.807",
"Id": "243029",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "VanityURL checker in Python"
}
|
243029
|
<p>Scraping news articles from various web page is the main goal of this code. For starting all spiders(web crawlers) at the same time, I try to implement the facade design pattern. It works but I feel the constructor of <code>SpiderFacade</code> class can be improved. Is there better way to do it or better design pattern to do it ?</p>
<p><strong>Abstract Spider</strong></p>
<pre><code>public abstract class NewsSpider {
public void crawl() {
}
}
</code></pre>
<p><strong>Custom Spider1</strong></p>
<pre><code>public class NYTimesSpider extends NewsSpider {
private final NewsService newsService;
public NYTimesSpider(NewsService newsService) {
this.newsService = newsService;
}
@Override
public void crawl() {
// crawl logic
}
}
</code></pre>
<p><strong>Custom Spider2</strong></p>
<pre><code>public class BbcSpider extends NewsSpider {
private final NewsService newsService;
public BbcSpider(NewsService newsService) {
this.newsService = newsService;
}
@Override
public void crawl() {
// crawl logic
}
}
</code></pre>
<p><strong>Facade Class</strong></p>
<pre><code>public class SpiderFacade {
private final List<NewsSpider> spiderList;
public SpiderFacade(NewsService newsService) {
spiderList = Arrays.asList(
new NYTimesSpider(newsService), // the wrong part in my opinion
new BbcSpider(newsService)
);
}
public void startCollectingNews() {
spiderList.forEach(NewsSpider::crawl);
}
}
</code></pre>
<p><strong>Starting Spiders</strong></p>
<pre><code> SpiderFacade spiderFacade = new SpiderFacade(newsService);
spiderFacade.startCollectingNews();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:51:51.007",
"Id": "476988",
"Score": "0",
"body": "The only \"wrong\" things I can notice is that you don't pass the services as constructor parameters (Inversion of control). From my knowledge I would say that it is not a _facade_ but a _composite_ and, thus, your `SpiderFacade` must implement/extend `NewsSpider` and accept an unbound number of `NewsSpider`."
}
] |
[
{
"body": "<ol>\n<li>Use interface instead of class with single method</li>\n<li>Each concrete implementation should be a singletone</li>\n<li>Each concrete implementation should contain only logic and accept your current news in crowler() method: do not recreate a strategy instance for each news.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:57:37.053",
"Id": "476990",
"Score": "2",
"body": "Welcome to CodeReview! Please also explain *why* your alterenatives are is better, so the OP can learn form it :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T06:08:42.223",
"Id": "243049",
"ParentId": "243031",
"Score": "1"
}
},
{
"body": "<p>From the high level I don't see anything wrong in your constructor. But I have some improvement to propose:</p>\n\n<p><strong>Use interface</strong></p>\n\n<p>Your <code>NewsSpider</code> is an abstract class with one empty method. If you want to force the implementation of the <code>crawl</code> method make it abstract. And if your class has no implementations, make it an interface. </p>\n\n<pre><code>interface NewsSpider {\n void crawl();\n}\n</code></pre>\n\n<p>But interfaces with single methods are also <em>function interfaces</em>. In this case You can replace your <code>NewsSpider</code> with <code>Runner</code> because it also provide one method that returns nothing. But I guess you would at least returns a set of news. So your news spider can be seen has a <code>Supplier<News></code>.</p>\n\n<p><strong>Inversion of control</strong></p>\n\n<p>Instead of creating the <code>NYTImeSpider</code> and <code>BBCSpider</code> inside the <code>SpiderFacade</code> pass a list or varargs of <code>NewsSpider</code> :</p>\n\n<pre><code>public SpiderFacade(NewsSpider... spiders) {\n this.spiderList = Arrays.asList(spiders);\n}\n</code></pre>\n\n<p>By doing so you improve the evolvability of your code because you can easily provide another spider. You also improve the testability because you can pass mocks to your facade to test his behavior. </p>\n\n<p><strong>Composite</strong></p>\n\n<p>I have the feeling that what you are building is more a <em>composite</em> than a <em>facade</em>. With the composite your program will be much more modular because you can use a single crawler or many with the same interfaces.</p>\n\n<pre><code>CompositeSpider implements Supplier<Set<News>> {\n // ...\n CompositeSpider(Supplier<Set<News>>... components) {\n this.components = Arrays.asList(components);\n }\n\n public Set<News> get() {\n // get and aggregate news from all components\n } \n} \n</code></pre>\n\n<p>By doing that you increase the modularity. You can later create another implementation that remove duplicates and compose all of them.</p>\n\n<pre><code>Set<News> uniqueNews = new DuplicatesPruner(\n new CompositeSpider(\n new NYTimeSpider(),\n new BBCSpider()\n )\n).get();\n</code></pre>\n\n<p>And because all the crawlers share the same interfaces you can easily switch them and pass them to another service:</p>\n\n<pre><code>class NotificationService {\n void sendNews(Function<Set<News>> crawler)\n}\n\nclass AsyncNewsService {\n CompletableFuture<Set<News>>> fetch(Function<Set<News>> crawler)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T07:25:02.323",
"Id": "243051",
"ParentId": "243031",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243051",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:19:00.063",
"Id": "243031",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Scraping news articles from various pages"
}
|
243031
|
<p><a href="https://try.gitea.io/nadal/repository" rel="nofollow noreferrer">https://try.gitea.io/nadal/repository</a></p>
<p>Used this in a coding challenge after a job interview. I didn't get chosen, but I was wondering if it was because of the code quality in the project.</p>
<pre><code>import React, { Component } from 'react';
import * as ExpenseActions from '../actions/ExpenseActions';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import ExpenseTable from '../components/ExpenseTable';
export class ExpenseContainer extends Component {
constructor(props) {
super(props)
}
/**
* Triggers the create action
* @method
*
*/
createExpense = (expense) => {
this.props.actions.CreateExpense(expense)
}
/**
* Triggers the start edit action
* @method
*
*/
startEditing = (id) => {
this.props.actions.StartEditing(id);
}
/**
* Triggers the cancel action
* @method
*
*/
cancelEditing = (id) => {
this.props.actions.CancelEditing(id);
}
/**
* Triggers the edit action
* @method
*
*/
editExpense = (expense) => {
this.props.actions.UpdateExpense(expense);
}
/**
* Triggers the delete action
* @method
*
*/
deleteExpense = (expense) => {
this.props.actions.DeleteExpense(expense);
}
render() {
return (
<div className="expense-container">
<ExpenseTable
subTotal={this.props.expenses.subTotal}
total={this.props.expenses.total}
expenses={this.props.expenses.expenses}
createExpense={this.createExpense}
startEditing={this.startEditing}
cancelEditing={this.cancelEditing}
editExpense={this.editExpense}
deleteExpense = {this.deleteExpense}
/>
</div>
);
}
}
ExpenseContainer.propTypes = {
actions: PropTypes.object.isRequired,
expenses: PropTypes.object.isRequired
}
function mapStateToProps(state, ownProps) {
return {
expenses: state.expenses
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(ExpenseActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ExpenseContainer);
</code></pre>
<p>Aside the fact, I could have used a hook called <code>useSelector</code> and <code>useDispatch</code>. I am not sure how I could have made it better. The backend side, I am not too sure if there's anything wrong with it, because I am not too familiar with Node/Express. Try to be as nitpicky as possible.</p>
|
[] |
[
{
"body": "<p>Sorry you didn't get the position, but perhaps the interviewers/code reviewers were looking for something else or some very specific things.</p>\n<p>You cannot, in fact, use <code>useSelector</code> or <code>useDispatch</code>, nor any other react hook as they are only compatible with functional components. Other than that this appears to be clean and readable code, although it does have some redundancy.</p>\n<h3>Suggestions</h3>\n<ol>\n<li>The constructor doesn't actually do anything, so it can be removed</li>\n<li>All the class functions simply proxy props that are passed, so they, too, can be removed</li>\n<li>This <em>is</em> debatable, but IMO you should explicitly map the actions to props that you will use, it makes it clearer what the component can do</li>\n<li>The connect HOC's second parameter <code>mapDispatchToProps</code> automagically wraps each actionCreator with a call to dispatch as well</li>\n<li>It appears <code>this.props.expenses</code> object shape is identical to the props <code>ExpenseTable</code> takes, so you can spread those in, more DRY</li>\n</ol>\n<h3>Nit-picky Suggestions</h3>\n<ol>\n<li>Try to be as precise/explicit when defining proptypes</li>\n<li>Consistently use semi-colons</li>\n<li>In react only Components are PascalCased, most other variables and objects should be normal camelCased</li>\n<li>Destructure props to be more DRY, i.e. much less <code>this.props.X</code>, <code>this.props.Y</code>, <code>this.props.Z</code>. This one is debatable however as the argument against is that not destructuring them it is easy to see what is a prop versus state versus neither. I say you can just look to the top of the function where variables should normally be defined anyway to glean these details.</li>\n</ol>\n<p>Component</p>\n<pre><code>import React, { Component } from 'react';\nimport { connect } from 'react-redux';\nimport { PropTypes } from 'prop-types';\nimport ExpenseTable from '../components/ExpenseTable';\nimport {\n CancelEditing,\n CreateExpense,\n DeleteExpense,\n StartEditing,\n UpdateExpense,\n} from '../actions/ExpenseActions';\n\nexport class ExpenseContainer extends Component {\n render() {\n const {\n CancelEditing,\n CreateExpense,\n DeleteExpense,\n expenses,\n StartEditing,\n UpdateExpense,\n } = this.props;\n\n return (\n <div className="expense-container">\n <ExpenseTable\n {...expenses}\n createExpense={CreateExpense}\n startEditing={StartEditing}\n cancelEditing={CancelEditing}\n editExpense={UpdateExpense}\n deleteExpense={DeleteExpense}\n />\n </div>\n );\n }\n}\n\nExpenseContainer.propTypes = {\n CancelEditing: PropTypes.func.isRequired,\n CreateExpense: PropTypes.func.isRequired,\n DeleteExpense: PropTypes.func.isRequired,\n StartEditing: PropTypes.func.isRequired,\n UpdateExpense: PropTypes.func.isRequired,\n expenses: PropTypes.shape({\n expenses: PropTypes.string.isRequired, // or number or whatever the specific type is\n subTotal: PropTypes.string.isRequired,\n total: PropTypes.string.isRequired,\n }).isRequired\n};\n\nfunction mapStateToProps(state) {\n return {\n expenses: state.expenses\n }\n};\n\nconst mapDispatchToProps = {\n CancelEditing,\n CreateExpense,\n DeleteExpense,\n StartEditing,\n UpdateExpense,\n};\n\nexport default connect(mapStateToProps, mapDispatchToProps)(ExpenseContainer);\n</code></pre>\n<p>A final suggestion would be to just convert <code>ExpenseContainer</code> to a functional component since it doesn't use <em>any</em> of the class-based lifecycle functions.</p>\n<pre><code>export const ExpenseContainer = ({\n CancelEditing,\n CreateExpense,\n DeleteExpense,\n expenses,\n StartEditing,\n UpdateExpense,\n}) => (\n <div className="expense-container">\n <ExpenseTable\n {...expenses}\n createExpense={CreateExpense}\n startEditing={StartEditing}\n cancelEditing={CancelEditing}\n editExpense={UpdateExpense}\n deleteExpense = {DeleteExpense}\n />\n </div>\n);\n\nExpenseContainer.propTypes = { ... };\n\nfunction mapStateToProps(state) { ... };\n\nconst mapDispatchToProps = { ... };\n\nexport default connect(mapStateToProps, mapDispatchToProps)(ExpenseContainer);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-05T07:16:12.837",
"Id": "243411",
"ParentId": "243032",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:20:17.273",
"Id": "243032",
"Score": "3",
"Tags": [
"react.js",
"jsx"
],
"Title": "React/Redux/Node/Express crud application with a React class component"
}
|
243032
|
<p>I tried to implement union find (disjoint set data structure) algorithm in C++. There I used unordered_map data structure. Is there a better way of doing this using any other data structure.</p>
<p>While finding the root I have used the following way.</p>
<pre><code>int root(int i){
if(i != parent[i]) parent[i] = root(parent[i]);
return parent[i];
}
</code></pre>
<p>Also, I can implement it as</p>
<pre><code>int root(int i){
while (i != parent[i]){
parent[i] = parent[parent[i]]);
i = parent[i];
}
return i;
}
</code></pre>
<p>It seems like both are same other than the (recursive and iterative) approach for me. Which is better here!</p>
<p>The following is my implementation.</p>
<pre><code>#include<iostream>
#include<unordered_map>
#include<vector>
using namespace std;
class Disjoinset{
private:
unordered_map<int, int> parent, rank;
// find the root
int root(int i){
if(i != parent[i]) parent[i] = root(parent[i]);
return parent[i];
}
public:
// initialize the parent map
void makeSet(int i){
parent[i] = i;
}
// check for the connectivity
bool is_connected(int p, int q){
return root(p) == root(q);
}
// make union of two sets
void Union(int p, int q){
int proot = root(p);
int qroot = root(q);
if(proot == qroot) return;
if(rank[proot] > rank[qroot]) {
parent[qroot] = proot;
}
else{
parent[proot] = qroot;
if(rank[proot] == rank[qroot]) rank[qroot]++;
}
}
};
</code></pre>
<p>Driver code</p>
<pre><code>int main(){
vector<int> arr = {1,2,9,8,6,5,7};
Disjoinset dis; // create a disjoint set object
for(int x: arr){
dis.makeSet(x); // make the set
}
dis.Union(1,9); // create connections
dis.Union(6,5);
dis.Union(7,9);
cout << dis.is_connected(1,7) << endl; // check the connectivity.
cout << dis.is_connected(1,6) << endl;
return 0;
}
</code></pre>
<p>Thereafter I tried to use generics and I came up with following. Can someone help me on this as I am new to C++. Is my implementation is correct or are there any better approach.</p>
<pre><code>#include<iostream>
#include<unordered_map>
#include<vector>
#include<string>
using namespace std;
template<class T>
class Disjoinset{
private:
unordered_map< T, T> parent;
unordered_map< T, int>rank;
// find the root
T root(T i){
if(i != parent[i]) parent[i] = root(parent[i]);
return parent[i];
}
public:
// initialize the parent map
void makeSet(T i){
parent[i] = i;
}
// check for the connectivity
bool is_connected(T p, T q){
return root(p) == root(q);
}
// make union of two sets
void Union(T p, T q){
T proot = root(p);
T qroot = root(q);
if(proot == qroot) return;
if(rank[proot] > rank[qroot]) {
parent[qroot] = proot;
}
else{
parent[proot] = qroot;
if(rank[proot] == rank[qroot]) rank[qroot]++;
}
}
};
int main(){
vector<string> arr = {"amal", "nimal", "kamal", "bimal", "saman"};
Disjoinset <string>dis; // create a disjoint set object
for(string x: arr){
dis.makeSet(x); // make the set
}
dis.Union("amal", "kamal"); // create connections
dis.Union("kamal", "nimal");
cout << dis.is_connected("amal", "nimal") << endl; // check the connectivity.
cout << dis.is_connected("bimal", "amal") << endl;
return 0;
}
</code></pre>
<p>Thank you for every answer.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T19:40:45.453",
"Id": "477042",
"Score": "0",
"body": "Did you test it? Does it produce the correct output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:11:02.280",
"Id": "477045",
"Score": "0",
"body": "@Mast Did you find anything wrong here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T04:29:46.087",
"Id": "477077",
"Score": "0",
"body": "Without a specification what, e.g. `int root(int i)` is to accomplish, who is to tell if it works as intended, is coded justifiably? (I see the single line comments in the larger code blocks. I'm, old, trying to be patient. And attentive. Failing time and again…)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T06:23:42.880",
"Id": "477081",
"Score": "0",
"body": "@greybeard sorry for that. Thanks for the advice."
}
] |
[
{
"body": "<p>Overall, that looks good to me. A few nitpicks, however, follow:</p>\n\n<p><strong>Advice 1</strong></p>\n\n<pre><code>#include<iostream>\n#include<unordered_map>\n#include<vector>\n#include<string>\n</code></pre>\n\n<p>I would put a space between <code>e</code> and <code><</code>. Also, I would sort the rows alphabetically, so that we get:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n</code></pre>\n\n<p><strong>Advice 2: One template per file</strong></p>\n\n<p>I would extract away the <code>main</code> and put the entire disjoint set template into its own file; call it <code>DisjointSet.hpp</code> to begin with.</p>\n\n<p><strong>Advice 3: Protect your header files from multiple inclusion</strong></p>\n\n<p>I would most definitely put the header guards in <code>DisjointSet.hpp</code> so that it looks like this:</p>\n\n<pre><code>#ifndef COM_STACKEXCHANGE_RUSIRU_UTIL_HPP\n#define COM_STACKEXCHANGE_RUSIRU_UTIL_HPP\n.\n. Your funky DisjointSet.hpp code here. :-)\n.\n#endif // COM_STACKEXCHANGE_RUSIRU_UTIL_HPP\n</code></pre>\n\n<p><strong>Advice 4: \"Package\" your code into namespaces</strong></p>\n\n<p>I have a habit of putting my data structures into relevant namespaces in order to avoid name collisions with other people's code:</p>\n\n<pre><code>namespace com::stackexchange::rusiru::util {\n template<class T>\n class DisjointSet {\n ...\n };\n}\n</code></pre>\n\n<p><strong>Advice 5: Remove minor noise</strong></p>\n\n<pre><code>unordered_map< T, T> parent; \nunordered_map< T, int>rank;\n</code></pre>\n\n<p>I would write:</p>\n\n<pre><code>unordered_map<T, T> parent;\nunordered_map<T, int> rank;\n</code></pre>\n\n<p>Note the placement of spaces!</p>\n\n<p><strong>Advice 6: Arbitrary method naming scheme</strong></p>\n\n<p>Essentially, you have <code>makeSet</code>, <code>is_connected</code>, <code>Union</code>. That's three different method naming schemes right there; choose one and stick to it. For example, <code>makeSet</code>, <code>isConnected</code>, <code>union</code>.</p>\n\n<p><strong>Advice 7: Printing booleans to <code>stdout</code></strong>:</p>\n\n<p>You can do <code>cout << std::boolalpha << ...;</code> in order to print <code>true</code>/<code>false</code>.</p>\n\n<p><strong>Advice 8: Don't pollute your namespace</strong></p>\n\n<p>Generally speaking, <code>using namespace std;</code> is not what you may see in professional C++ code. Consider using individual <code>use</code>s such as:</p>\n\n<pre><code>using std::cout;\nusing std::endl;\n</code></pre>\n\n<p><strong>Putting all together</strong></p>\n\n<p>Overall, I had this in mind:</p>\n\n<p><strong><code>DisjointSet.hpp</code></strong></p>\n\n<pre><code>#ifndef COM_STACKEXCHANGE_RUSIRU_UTIL_HPP\n#define COM_STACKEXCHANGE_RUSIRU_UTIL_HPP\n\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace com::stackexchange::rusiru::util {\n\n using std::boolalpha;\n using std::cout;\n using std::endl;\n using std::string;\n using std::unordered_map;\n using std::vector;\n\n template<typename T>\n class DisjointSet {\n\n private:\n\n unordered_map<T, T> parent;\n unordered_map<T, int> rank;\n\n // find the root\n T root(T i) {\n if (i != parent[i]) parent[i] = root(parent[i]);\n return parent[i];\n }\n\n public:\n\n // initialize the parent map\n void makeSet(T i) {\n parent[i] = i;\n }\n // check for the connectivity\n bool isConnected(T p, T q) {\n return root(p) == root(q);\n }\n // make union of two sets\n void union(T p, T q) {\n\n T proot = root(p);\n T qroot = root(q);\n\n if (proot == qroot) return;\n\n if (rank[proot] > rank[qroot]) {\n parent[qroot] = proot;\n }\n else {\n parent[proot] = qroot;\n if (rank[proot] == rank[qroot]) rank[qroot]++;\n }\n }\n };\n}\n\n#endif // COM_STACKEXCHANGE_RUSIRU_UTIL_HPP\n</code></pre>\n\n<p><strong><code>main.cpp</code></strong></p>\n\n<pre><code>#include \"DisjointSet.hpp\"\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing std::boolalpha;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing com::stackexchange::rusiru::util::DisjointSet;\n\nint main() {\n vector<string> arr = { \"amal\", \"nimal\", \"kamal\", \"bimal\", \"saman\" };\n DisjointSet<string> dis; // create a disjoint set object\n\n for (const string x : arr) {\n dis.makeSet(x); // make the set\n }\n\n dis.union(\"amal\", \"kamal\"); // create connections\n dis.union(\"kamal\", \"nimal\");\n\n cout << boolalpha << dis.isConnected(\"amal\", \"nimal\") << endl; // check the connectivity.\n cout << dis.isConnected(\"bimal\", \"amal\") << endl;\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T12:39:14.787",
"Id": "477019",
"Score": "0",
"body": "Thank you very much for your detailed advises. Those are really helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T15:49:23.317",
"Id": "477029",
"Score": "0",
"body": "Nothing about `using namespace std;`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T17:16:56.217",
"Id": "477033",
"Score": "0",
"body": "@pacmaninbw Mitigated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T09:06:06.183",
"Id": "477094",
"Score": "1",
"body": "I wouldnt recommend sorting the inclusions alphabetically, since you sometimes need to worry which one goes first. You also sometimes want to separate standard ones from custom ones."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T12:12:04.257",
"Id": "243062",
"ParentId": "243033",
"Score": "2"
}
},
{
"body": "<p>There is no need for unordered maps, especially not for two of them. Also, since you are dealing with indices and counts, you should make them <code>std::size_t</code>, not <code>int</code> or generic. The datatype for storing parent-rank-tuples should look like this:</p>\n\n<pre><code>std::vector<std::tuple<std::size_t, std::size_t>> data;\n</code></pre>\n\n<p>Performance will be a good deal better because <code>vector</code> is faster than <code>unordered map</code> and in addition to that, there's only one lookup required to get both parent and rank, like this:</p>\n\n<pre><code>auto [parent, rank] = data[i];\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>std::tie(parent, rank) = data[i];\n</code></pre>\n\n<p>If you want the union-find datastucture to work on arbitrary objects instead of indices, create a generic wrapper class that translates objects to indices and then invokes the non-generic version. This way, the <code>unordered_map</code> lookup is done only once for each argument, even if the non-generic version subsequently performs several recursions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T10:55:12.117",
"Id": "477099",
"Score": "0",
"body": "P Thanks. What did you mean by \" vector is faster than unordered map\". Better if you can you explain it ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T12:04:48.500",
"Id": "477101",
"Score": "0",
"body": "@rusiruthushara - `std::vector` is an array and `std::unordered_map` is a [hash table](https://en.wikipedia.org/wiki/Hash_table). A hash table is built upon an array but with key hashing and collision handling on top, so it is obviously slower than a plain array. The disadvantage of an array is that the keys must be integers between zero and the size of the array. A hash table can handle arbitrary indices, including strings and objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T15:30:18.937",
"Id": "477125",
"Score": "0",
"body": "Thanks for the information."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T07:24:07.273",
"Id": "243091",
"ParentId": "243033",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243062",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:31:35.933",
"Id": "243033",
"Score": "0",
"Tags": [
"c++",
"algorithm",
"template",
"c++17",
"union-find"
],
"Title": "Union find using unordered map and templates in C++"
}
|
243033
|
<p>I'm making a Minecraft clone and have made an Object Pool. Looking for some advice on how I have implemented it. </p>
<p>Uses m_availableObjects as a O(1) way of searching for the next available object. </p>
<p>Thank you in advance. </p>
<pre><code>constexpr int INVALID_OBJECT_ID = -1;
//Internal Use - Object Pool
template <class Object>
struct ObjectInPool : private NonCopyable
{
ObjectInPool(int ID)
: object(),
inUse(false),
ID(ID)
{}
ObjectInPool(ObjectInPool&& orig) noexcept
: object(std::move(orig.object)),
inUse(orig.inUse),
ID(orig.ID)
{
orig.ID = INVALID_OBJECT_ID;
orig.inUse = false;
}
ObjectInPool& operator=(ObjectInPool&& orig) noexcept
{
object = std::move(orig.object);
inUse = orig.inUse;
ID = orig.ID;
orig.ID = INVALID_OBJECT_ID;
orig.inUse = false;
return *this;
}
~ObjectInPool() {}
Object object;
bool inUse;
int ID;
};
//External Use - Object Pool
template <class Object>
class ObjectPool;
template <class Object>
struct ObjectFromPool : private NonCopyable
{
ObjectFromPool(ObjectInPool<Object>* objectInPool, std::function<void(int)> func)
: objectInPool(objectInPool),
m_func(func)
{
if (objectInPool)
{
objectInPool->inUse = true;
}
}
~ObjectFromPool()
{
if (objectInPool)
{
objectInPool->object.reset();
objectInPool->inUse = false;
m_func(objectInPool->ID);
}
}
ObjectFromPool(ObjectFromPool&& orig) noexcept
: objectInPool(orig.objectInPool),
m_func(orig.m_func)
{
orig.objectInPool = nullptr;
}
ObjectFromPool& operator=(ObjectFromPool&& orig) noexcept
{
objectInPool = orig.objectInPool;
m_func = orig.m_func;
orig.objectInPool = nullptr;
return *this;
}
Object* getObject() const
{
return (objectInPool ? &objectInPool->object : nullptr);
}
private:
ObjectInPool<Object>* objectInPool;
std::function<void(int)> m_func;
};
using std::placeholders::_1;
//Object Pool
template <class Object>
class ObjectPool : private NonCopyable, private NonMovable
{
public:
ObjectPool(int visibilityDistance, int chunkWidth, int chunkDepth)
: m_objectPool()
{
//Added a little bit more than neccessary due to how the inifinite map generates
int x = visibilityDistance / chunkWidth;
x += x += 1;
int z = visibilityDistance / chunkDepth;
z += z += 1;
m_objectPool.reserve(x * z);
for (int i = 0; i < x * z; ++i)
{
m_objectPool.emplace_back(i);
m_availableObjects.push(i);
}
}
ObjectFromPool<Object> getNextAvailableObject()
{
if (!m_availableObjects.empty())
{
int ID = m_availableObjects.top();
m_availableObjects.pop();
assert(ID < m_objectPool.size());
return ObjectFromPool<Object>(&m_objectPool[ID], std::bind(&ObjectPool<Object>::releaseID, this, _1));
}
else
{
return ObjectFromPool<Object>(nullptr, std::bind(&ObjectPool<Object>::releaseID, this, _1));
}
}
private:
std::stack<int> m_availableObjects;
std::vector<ObjectInPool<Object>> m_objectPool;
void releaseID(int ID)
{
assert(ID != INVALID_OBJECT_ID);
m_availableObjects.push(ID);
}
};
</code></pre>
|
[] |
[
{
"body": "<p>This looks way too overengineered. Is there really a need for all the complexity? Use the KISS principle!</p>\n\n<p>I'm assuming you have this pool because you want to avoid the cost of constructing and destructing <code>Object</code>s, and possibly to allocate a lot of instances of <code>Object</code> up front to avoid latency later on. If that's the case, I would instead write the pool like so:</p>\n\n<pre><code>template<typename Object>\nclass ObjectPool: private NonCopyable\n{\n std::deque<std::unique_ptr<Object>> m_objects;\n\npublic:\n ObjectPool(size_t count = 0) {\n for(size_t i = 0; i < count; ++i) {\n auto object = std::make_unique<Object>();\n enqueue(object);\n }\n }\n\n std::unique_ptr<Object> dequeue() {\n if (m_objects.empty()) {\n return std::make_unique<Object>();\n } else {\n auto object = std::move(m_objects.back());\n m_objects.pop_back();\n return object;\n }\n }\n\n void enqueue(std::unique_ptr<Object> &object) {\n m_objects.emplace_back(std::move(object));\n }\n};\n</code></pre>\n\n<p>First, the constructor of this object pool just takes the initial size of the pool as a single value, so it doesn't have to know the specifics of chunk sizes.</p>\n\n<p>Second, the <code>dequeue()</code> function creates a new object for you automatically if the pool is empty. Maybe that is not desired, in which you could return an empty <code>std::unique_pointer</code> instead.</p>\n\n<p>Last but not least, instead of leaving it up to the destructor of an <code>ObjectFromPool</code> to return the object back to the pool it came from, there is now a counterpart to <code>dequeue()</code>: <code>enqueue()</code>. It simply returns an object back to its pool. This avoids having to wrap objects in custom classes.</p>\n\n<p>The only issue with this solution might be that you forget to return an object to its pool, but on the other hand it will still safely destruct itself once its lifetime ends.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T22:51:50.667",
"Id": "476968",
"Score": "0",
"body": "This is great, thank you!\n\nI think I went with my option to try and keep my code cache friendly but I don't think I actually succeeded with that and definitely didn't follow the KISS principle like you say. \n\nIn theory could I use RAII to wrap the dequeue & enqueue functions with my own object types too?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T22:36:18.217",
"Id": "243038",
"ParentId": "243034",
"Score": "3"
}
},
{
"body": "<p>I agree with G. Sliepen that this seems way too over-engineered. I just wanted to add a few more things.</p>\n\n<p>Is there a reason you're inheriting <code>NonCopyable</code> and <code>NonMovable</code>? This doesn't seem like a good use of inheritance.</p>\n\n<pre><code>Object(const Object&) = delete;\nObject(Object&&) = delete;\n</code></pre>\n\n<p>This is much clearer. </p>\n\n<p>Secondly, <code>x += x += 1;</code> just looks terrible. Focus on readability. The compiler will optimize it anyway, and it does. See here (<a href=\"https://godbolt.org/z/iQOwPg\" rel=\"nofollow noreferrer\">https://godbolt.org/z/iQOwPg</a>).</p>\n\n<p>Finally, your pool is default-constructing objects at initialization. This is may be fine for small objects, but can lead to performance loss for large objects, especially if you don't use a lot of the objects. </p>\n\n<p>More typically, pool allocators allocate a single block of memory during the start, and internally represent them as linked list of objects. Then, when a user requests an object, it picks the first node from the linked list, constructs the object, and returns it to the user. This method has the added benefit that the user can pass in arguments for the constructor. </p>\n\n<p>Obviously, there are more features you can add, like dynamically resizing the pool if the memory is low.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T17:53:41.587",
"Id": "477035",
"Score": "1",
"body": "I would rewrite `x = foo; x += x += 1` to: `x = 2 * (foo + 1)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T01:07:19.550",
"Id": "243044",
"ParentId": "243034",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243038",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:33:39.760",
"Id": "243034",
"Score": "1",
"Tags": [
"c++",
"performance",
"game"
],
"Title": "Made an Object pool in C++"
}
|
243034
|
<p>It's a pretty simple script really, i just want to know if there is a way to improve it.</p>
<pre><code>#!/bin/env sh
set -o nounset
set -o errexit
if [[ "$#" -ne 3 ]] && [[ "$#" -ne 2 ]];
then
echo "Usage: ./project.sh [NAME] [GENERATOR] [MAKEFILES]"
exit 1
fi
mkdir $HOME/Dev/$1
mkdir $HOME/Dev/$1/src/
mkdir $HOME/Dev/$1/build/
cp $HOME/ProjectSetup/CMakeLists.txt $HOME/Dev/$1/
sed -i "s/set(CMAKE_PROJECT_NAME placeholder/set(CMAKE_PROJECT_NAME $1/" $HOME/Dev/$1/CMakeLists.txt
git init $HOME/Dev/$1/
cat > $HOME/Dev/$1/.gitignore << EOL
build/
compile_commands.json
.vscode/
EOL
touch $HOME/Dev/$1/src/main.cpp
cat > $HOME/Dev/$1/src/main.cpp << EOL
int main(int argc, const char* argv[])
{
return 0;
}
EOL
if [[ "$#" -eq 3 ]];
then
cmake -G "$2 - $3" -S $HOME/Dev/$1 -B $HOME/Dev/$1/build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=1
else
cmake -G "$2" -S $HOME/Dev/$1 -B $HOME/Dev/$1/build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=1
fi
ln -s $HOME/Dev/$1/build/compile_commands.json $HOME/Dev/$1/
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T12:38:57.213",
"Id": "477018",
"Score": "0",
"body": "Hi Nadpher. Are you aiming for a generic Bourne-compatible shell or specifically bash? Your shebang line says generic shell, but your question tag says bash. So there seems to be some ambiguity over this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:12:56.757",
"Id": "477046",
"Score": "1",
"body": "Yeah that's because i got the tag wrong, sorry. really i meant to write shell cause i use zsh personally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T00:24:53.670",
"Id": "477068",
"Score": "1",
"body": "Thanks. I can see a few things that would get picked up by https://www.shellcheck.net/"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T23:01:56.587",
"Id": "243039",
"Score": "1",
"Tags": [
"shell"
],
"Title": "Project setup script"
}
|
243039
|
<p>I implemented an open-addressed, double-hashed hashmap in C, now looking for some advice on improving it. Thank you.</p>
<p>hashmap.h:</p>
<pre><code>#pragma once
#include <stdbool.h>
typedef struct hm_hashmap_t *hm_hashmap_t;
hm_hashmap_t hm_init(void);
void hm_destroy(hm_hashmap_t hm);
void hm_set(hm_hashmap_t hm, const char *key, void *val);
void *hm_get(hm_hashmap_t hm, const char *key);
void hm_delete(hm_hashmap_t hm, const char *key);
typedef struct hm_iterator_t *hm_iterator_t;
hm_iterator_t hm_iteratorInit(hm_hashmap_t hm);
void hm_iteratorDestroy(hm_iterator_t iter);
bool hm_iteratorNext(hm_iterator_t iter);
char *hm_iteratorKey(hm_iterator_t iter);
void *hm_iteratorVal(hm_iterator_t iter);
</code></pre>
<p>hashmap.c:</p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "hashmap.h"
#include "hashfuncs.h"
#define INITIAL_BASE_SIZE 100
#define PRIME1 151
#define PRIME2 163
#define HIGH_DENSITY 70
typedef struct
{
char *key;
void *value;
} hm_item;
struct hm_hashmap_t
{
long size;
long count;
hm_item **items;
};
struct hm_iterator_t
{
hm_hashmap_t hm;
long cursor;
bool finished;
char *key;
void *val;
};
static hm_item HM_DELETED_ITEM = {NULL, NULL};
enum itemType
{
empty,
deleted,
normal
};
static long sizes[] = {1009, 2027, 8111, 16223, 32467, 64937, 129887, 259781, 519577, 1039169, 2078339, 4156709, 8313433, 16626941, 33253889};
static int currentSizeIndex = 0;
#define sizeLength sizeof(sizes) / sizeof(sizes[0])
typedef struct
{
long index;
enum itemType type;
} itemIndex;
/*
* private methods
*/
static hm_item *hm_newItem(const char *k, void *v)
{
hm_item *item = malloc(sizeof(hm_item));
item->key = strdup(k);
item->value = v;
return item;
}
static hm_hashmap_t hm_initSized(const int newSize)
{
hm_hashmap_t hm = malloc(sizeof(*hm));
hm->size = newSize;
hm->count = 0;
hm->items = calloc((size_t)hm->size, sizeof(hm_item *));
return hm;
}
static void hm_resize(hm_hashmap_t hm, const long newSize)
{
if (newSize >= sizes[sizeLength - 1])
{
return;
}
hm_hashmap_t tmpHm = hm_initSized(newSize);
if (tmpHm == NULL)
{
return; // if there wasn't enough memory, just return
}
for (int i = 0; i < hm->size; i++)
{
hm_item *item = hm->items[i];
if (item != NULL && item != &HM_DELETED_ITEM)
{
hm_set(tmpHm, item->key, item->value);
}
}
hm->count = tmpHm->count;
const long tmpSize = hm->size;
hm->size = tmpHm->size;
tmpHm->size = tmpSize;
hm_item **tmpItems = hm->items;
hm->items = tmpHm->items;
tmpHm->items = tmpItems;
hm_destroy(tmpHm);
}
static itemIndex hm_findItemIndex(hm_hashmap_t hm, const char *key)
{
long index = strHash(key, PRIME1, hm->size);
hm_item *item = hm->items[index];
int i = 1;
while (item != NULL)
{
if (item == &HM_DELETED_ITEM)
{
return (itemIndex){index, deleted};
}
else if (strcmp(item->key, key) == 0)
{
return (itemIndex){index, normal};
}
index = strDoubleHash(key, hm->size, PRIME1, PRIME2, i);
item = hm->items[index];
i++;
if (i > hm->size)
{
// out of memory
exit(1);
}
}
return (itemIndex){index, empty};
}
static void hm_deleteItem(hm_item *item)
{
free(item->key);
free(item);
}
static void hm_iteratorFindNext(hm_iterator_t it)
{
long cur = it->cursor + 1;
while (cur < it->hm->size)
{
if (it->hm->items[cur] != NULL && it->hm->items[cur] != &HM_DELETED_ITEM)
{
it->cursor = cur;
it->key = it->hm->items[cur]->key;
it->val = it->hm->items[cur]->value;
return;
}
++cur;
}
it->finished = true;
}
/*
* public methods
*/
hm_hashmap_t hm_init()
{
return hm_initSized(sizes[0]);
}
void hm_destroy(hm_hashmap_t hm)
{
for (long i = 0; i < hm->size; i++)
{
hm_item *item = hm->items[i];
if (item != NULL && item != &HM_DELETED_ITEM)
{
hm_deleteItem(item);
}
}
free(hm->items);
free(hm);
}
void hm_set(hm_hashmap_t hm, const char *key, void *value)
{
itemIndex i = hm_findItemIndex(hm, key);
if (i.type == normal)
{
free(hm->items[i.index]->value);
hm->items[i.index]->value = value;
return;
}
hm_item *item = hm_newItem(key, value);
hm->items[i.index] = item;
hm->count++;
long long load = hm->count * 100 / hm->size;
if (load > HIGH_DENSITY && currentSizeIndex < (int)(sizeLength - 1))
{
hm_resize(hm, sizes[++currentSizeIndex]);
}
}
void *hm_get(hm_hashmap_t hm, const char *key)
{
itemIndex i = hm_findItemIndex(hm, key);
return i.type == empty || i.type == deleted ? NULL : hm->items[i.index]->value;
}
void hm_delete(hm_hashmap_t hm, const char *key)
{
itemIndex i = hm_findItemIndex(hm, key);
if (i.type == empty || i.type == deleted)
{
return;
}
hm_deleteItem(hm->items[i.index]);
hm->items[i.index] = &HM_DELETED_ITEM;
hm->count--;
}
hm_iterator_t hm_iteratorInit(hm_hashmap_t hm)
{
hm_iterator_t it = malloc(sizeof(*it));
it->hm = hm;
it->cursor = -1;
it->finished = false;
return it;
}
void hm_iteratorDestroy(hm_iterator_t iter)
{
free(iter);
}
bool hm_iteratorNext(hm_iterator_t iter)
{
if (iter->finished)
return false;
hm_iteratorFindNext(iter);
return !iter->finished;
}
char *hm_iteratorKey(hm_iterator_t iter)
{
return iter->hm->items[iter->cursor]->key;
}
void *hm_iteratorVal(hm_iterator_t iter)
{
return iter->hm->items[iter->cursor]->value;
}
</code></pre>
<p>hashfuncs.h:</p>
<pre><code>#pragma once
long strHash(const char *s, const int p, const long m);
long strDoubleHash(const char *s, const long m, const int p1, const int p2, const int numAttempts);
</code></pre>
<p>hashfuncs.c:</p>
<pre><code>long strHash(const char *s, const int p, const long m) {
long long hashValue = 0;
long long pPow = 1;
while(*s != '\0') {
hashValue = (hashValue + *s++ * pPow) % m;
pPow = (pPow * p) % m;
}
return hashValue;
}
long strDoubleHash(const char *s, const long m, const int p1, const int p2, const int numAttempts) {
const long hash1 = strHash(s, p1, m);
if (numAttempts == 0) {
return hash1;
}
else {
const long hash2 = strHash(s, p2, m);
return (hash1 + (numAttempts * (p2 - hash2 % p2))) % m;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Impressive...</p>\n\n<h2>hashing</h2>\n\n<p>I would suggest that the strHash just take the string, the strDoubleHash not exist, and the hash map code handle making the first and second hash values.\nThis would facilitate putting other hashes of different types of keys in.</p>\n\n<p>As a hint: assume strHash is expensive, and minimize it's calls.</p>\n\n<h2>deleted</h2>\n\n<p>I suspect there is a flaw in hm_findItemIndex about deleted items. If you:</p>\n\n<ol>\n<li>place item X at location n</li>\n<li>try placing item Y again at location n, so it gets location m instead</li>\n<li>delete item X</li>\n<li>try to get item Y</li>\n</ol>\n\n<p>At this point, hm_findItemIndex will return (n,deleted) instead of (m,normal), and Y has disappeared.\nhm_findItemIndex must skip deleted, except for a special case for hm_set(). For hm_set(), you can use one pass to find an existing Y, and a second to find a deleted entry you can fill, and the first pass could return that there was a deleted, or even search to the empty and then return the deleted. </p>\n\n<h2>fractions</h2>\n\n<pre><code> long long load = hm->count * 100 / hm->size;\n if (load > HIGH_DENSITY && currentSizeIndex < (int)(sizeLength - 1))\n</code></pre>\n\n<p>well, load will be between 0 and 70. No need for long long, or even long or int.\nHowever, you might overflow before then. Try:</p>\n\n<pre><code> int load = (int)(((long long)hm->count) * 100 / hm->size);\n</code></pre>\n\n<p>On the other hand, you might be better with changing HIGH_DENSITY to 0.70 and writing:</p>\n\n<pre><code> if ((hm->count > (hm_size * HIGH_DENSITY)) && \n currentSizeIndex < (int)(sizeLength - 1))\n</code></pre>\n\n<h2>currentSizeIndex</h2>\n\n<p>currentSizeIndex is a global. Get rid of it. Add a function to pick a size from your list given a minimum needed size. This only is needed when you make an initial hash or when you enlarge the hash.</p>\n\n<p>Speaking of which, if the caller knows he is going to add 5000 items, he should be able to access hm_initSize() telling it 5000, which should then back out the HIGH_DENSITY and find the right size in the list.</p>\n\n<h2>Size List</h2>\n\n<p>Curious choices. Primes less than <span class=\"math-container\">\\$2^n\\$</span>, but not the largest such primes. Why not?</p>\n\n<p>Edit: two additional thoughts</p>\n\n<h2>Memory Management##</h2>\n\n<p>Currently you duplicate and free the keys, and leave the caller responsible for the values. If you wish to continue this, hm_set() and hm_delete() should return the removed values for deletion, if needed.</p>\n\n<p>Alternatively, the could be configuration in the hm_init() saying how to delete the value entries. (This would be a function to call, with stock functions for do nothing and call free().) There could also reasonably be a need to clone the value entries.</p>\n\n<h2>Other Key Types</h2>\n\n<p>Other key types would also be good. hm_init would need to be passed: a clone function, a free function, a compare function, and a hash function. For keys that are stable and lasting, the clone could could return its parameter and the free do nothing.</p>\n\n<p>Having hm_init() variants that provide the default string version would be quite reasonable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T15:27:06.587",
"Id": "243613",
"ParentId": "243042",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T00:09:13.050",
"Id": "243042",
"Score": "3",
"Tags": [
"c",
"hash-map"
],
"Title": "Open-addressed C hashmap"
}
|
243042
|
<p>I have implemented a binary search tree with 2 operations to begin with. I have tried to implement it using the best practices I could think of. Overall, I am happy with the implementation. But, I want someone else's opinion about what they think about the design or any bad practice I have used. </p>
<p>I wanted to get rid of getLeftRef() and getRightRef() functions in Node class but they are being used in insert_ and delete_ function as parameters for the recursive call. Because in the insert_ and delete_ function we are reseating the unique_ptr, I passed it by reference and according to isocpp guidelines, it is ok to pass by unique_ptr reference if it is being used to reseat the unique_ptr. It would be great to have someone's review of this bit. </p>
<p>P.S. I am using C++11 so I cannot use make_unique instead of using new to allocate unique_ptr.</p>
<pre><code>//
// BST.hpp
// PracticeC++
//
#ifndef BST_hpp
#define BST_hpp
#include <memory>
// Binary Search Tree class
class BST
{
private:
// Binary Search Tree node
class Node
{
public:
Node(int val, Node* p) : data(val), parent(p), left(nullptr), right(nullptr) {}
bool isLeftChild() { return parent->left.get() == this; }
bool isRightChild() { return parent->right.get() == this; }
Node* getLeft() { return left.get(); }
Node* getRight() { return right.get(); }
Node* getParent() { return parent; }
std::unique_ptr<Node>& getLeftRef() { return left; }
std::unique_ptr<Node>& getRightRef() { return right; }
int getData() { return data; }
std::unique_ptr<Node> extract()
{ return isLeftChild() ? std::move(parent->left) : std::move(parent->right); }
std::unique_ptr<Node> extractLeft() { return std::move(left); }
std::unique_ptr<Node> extractRight() { return std::move(right); }
void setLeft(std::unique_ptr<Node> n)
{
if (!n)
return;
n->Reparent(this);
left = std::move(n);
}
void setRight(std::unique_ptr<Node> n)
{
if (!n)
return;
n->Reparent(this);
right = std::move(n);
}
void resetParent() { parent = nullptr; }
void setData(int val) { data = val; }
private:
// member variables
int data;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
Node* parent;
void Reparent(Node* newParent) { parent = newParent; }
};
void insert_(std::unique_ptr<Node>& root, int val, Node* parent);
bool remove_(std::unique_ptr<Node>& root, int val, Node* parent);
std::unique_ptr<Node> extractInOrderPredOrSucc(Node* node, bool isPred);
Node* find(Node* n, int val);
Node* findInOrderPredecessor(Node* node);
Node* findInOrderSuccessor(Node* node);
// Member variables
std::unique_ptr<Node> root;
public:
void insert(int val) { insert_(root, val, nullptr); }
bool remove(int val) { return remove_(root, val, nullptr); }
};
#endif /* BST_hpp */
</code></pre>
<pre><code>//
// BST.cpp
// PracticeC++
//
//
#include "BST.hpp"
BST::Node* BST::findInOrderPredecessor(BST::Node* node)
{
if (!node || !node->getLeft())
return nullptr;
node = node->getLeft();
while (node->getRight())
node = node->getRight();
return node;
}
BST::Node* BST::findInOrderSuccessor(BST::Node* node)
{
if (!node)
return nullptr;
else if (!node->getRight())
return node->getParent();
node = node->getLeft();
while (node->getRight())
node = node->getRight();
return node;
}
std::unique_ptr<BST::Node> BST::extractInOrderPredOrSucc(BST::Node* node, bool isPred)
{
if (isPred)
{
Node* n = findInOrderPredecessor(node);
if (!n)
return nullptr;
auto subtree = n->extract();
subtree->getParent()->setRight(subtree->extractLeft());
subtree->resetParent();
return subtree;
}
else
{
Node* n = findInOrderSuccessor(node);
if (!n)
return nullptr;
auto subtree = n->extract();
subtree->getParent()->setLeft(subtree->extractRight());
subtree->resetParent();
return subtree;
}
}
void BST::insert_(std::unique_ptr<Node>& node, int val, Node* parent)
{
if (!node)
{
node = std::unique_ptr<Node>(new Node(val, parent));
return;
}
return (val <= node->getData()
? insert_(node->getLeftRef(), val, node.get())
: insert_(node->getRightRef(), val, node.get()));
}
bool BST::remove_(std::unique_ptr<Node>& node, int val, Node* parent)
{
if (!node)
return false;
if (val == node->getData())
{
if (!node->getLeft())
{
if (!node->getRight())
node.reset();
else
node->setRight(node->extractRight());
}
else
{
if (!node->getRight())
node->setLeft(node->extractLeft());
else
{
// Both children exist, so replace with either in-order pred or succ
auto predNode = extractInOrderPredOrSucc(node.get(), true);
predNode->setLeft(node->extractLeft());
predNode->setRight(node->extractRight());
node->isLeftChild()
? node->getParent()->setLeft(std::move(predNode))
: node->getParent()->setRight(std::move(predNode));
}
}
return true;
}
return (val < node->getData()
? remove_(node->getLeftRef(), val, node.get())
: remove_(node->getRightRef(), val, node.get()));
}
</code></pre>
|
[] |
[
{
"body": "<h2>Observation</h2>\n<p>I normally don't see a <code>parent</code> pointer in a binary tree.<br />\nBecause you have to keep and maintain this extra pointer your code is a lot more complicated then it needs to be.</p>\n<hr />\n<p>The <code>Node</code> object is part of <code>BST</code> so you don't need need an interface to protect you from changes. Any changes in the BST or node are going to result in changes in the other.</p>\n<p>As a result I would simplify the <code>Node</code> to be a simple structure and get rid of that confusing mess of accessor functions.</p>\n<hr />\n<p>Personally I don't use smart pointers to build containers. The container is its own manager of memory abstracting that out is redundant. Though others would argue with me on that point and I do see their point.</p>\n<hr />\n<p>Your code can only store <code>int</code>. Why did you make this limitation. A simple templatization will allow you to store any type that is comparable.</p>\n<h2>Alternative</h2>\n<p>This is to show that you made the code twice as long by simply adding the parent member to the class.</p>\n<pre><code>template<typename T>\nclass BST\n{\n struct Node\n {\n Node* left;\n Node* right;\n T value;\n };\n Node* root = nullptr;\n\n // This function assumes node is not null.\n // So check before you call.\n Node* findLeftMostNode(Node* node) {\n return node->left == nullptr ? node: findLeftMostNode(node->left);\n }\n\n Node* insertNode(Node* node, T consT& val) {\n if (node == nullptr) {\n return new Node{nullptr, nullptr, val};\n }\n\n if (val < node->value) {\n node->left = insertNode(node->left, val);\n }\n else {\n node->right = insertNode(node->right, val);\n }\n return node;\n }\n Node* deleteNode(Node* node, T const& val)\n {\n if (node == nullptr) {\n return nullptr;\n }\n if (val < node->val) {\n node->left = deleteNode(node->left, val);\n }\n else if (val > node->val) {\n node->right = deleteNode(node->right, val);\n }\n else {\n // The interesting part.\n Node* old = node; // the node to delete;\n\n // If both children are null.\n // Simply delete the node and return nullptr\n // as the value to be used for this point.\n if (node->left == nullptr && node->right == nullptr) {\n node = nullptr;\n }\n // If either the left or right node is null\n // then we can use the other one as the replacement for\n // for node in the tree.\n else if (node->left == nullptr) {\n node = node->right; // the node to return as replacement\n }\n else if (node->right == nullptr) {\n node = node->left; // the node to return as replacement\n }\n else {\n // The shit just got real.\n // We can't delete the node (as we can return two pointers)\n old = nullptr;\n\n // This is the complicated part.\n // Remember that both the left and right are not nullptr.\n // So the leftmost sub-node of the right tree is the smallest\n // value in the right subtree. \n // If we move this value to here then the right sub-tree can\n // still be on the right of this node.\n Node* leftMost = findLeftMostNode(node->right);\n // Don't need to re-shape the tree simply move the value.\n node->val = leftMost->val;\n\n // We have moved the value.\n // But now we have to delete the value we just moved from the\n // right sub-tree. Luckily we have a function for that.\n node->right = deleteNode(node->right, leftMost->val);\n }\n delete old;\n }\n return node;\n }\n\n public:\n ~BST()\n {\n Node* bottomLeft = root == nullptr ? nullptr : findLeftMostNode(root);\n\n while (root) {\n Node* old = root;\n root = root->left;\n bottomLeft->left = old->right;\n bottomLeft = findLeftMostNode(bottomLeft);\n delete old;\n }\n }\n // Deletet the copy operator\n BST(BST const&) = delete;\n BST& operator(BST const&) = delete;\n\n // Simple interface.\n void insertNode(T const& val) {root = insertNode(root, val);}\n void deleteNode(T const& val) {root = deleteNode(root, val);}\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T06:16:42.413",
"Id": "243089",
"ParentId": "243046",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T03:46:01.230",
"Id": "243046",
"Score": "0",
"Tags": [
"c++",
"c++11",
"pointers",
"binary-search-tree"
],
"Title": "Implementing a binary search tree using std::unique_ptr"
}
|
243046
|
<p>There is few points In the script I don't like I think it can be improved, but I need a second opinion, here is the interactive plot I'm trying to build.</p>
<p><a href="https://i.stack.imgur.com/NeBQY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NeBQY.png" alt="enter image description here"></a></p>
<p>here is the code with thought in comments.</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/python3
from functools import lru_cache
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
@lru_cache # beacuse it redraws each time
def get_pdf(mu, sigma=1, offset=4):
o = sigma * offset
x = np.linspace(mu - o, mu + o, 100)
rv = ss.norm(mu, sigma)
return x, rv.pdf(x)
fig, ax = plt.subplots()
# added the subplot for bottom margin and the slider, since its also the ax
plt.subplots_adjust(bottom=0.25)
ax.fill_between(*get_pdf(0), label='A', alpha=0.7)
ax.set_xlim(-10, 10)
ax.set_ylim(0, 1)
# my guess is this has to be integrated with the update rather than outside
# and using t variable as global which I don't like, and guess it can be improved
t = ax.fill_between(*get_pdf(2), label='B', color='crimson', alpha=0.7)
slider = widgets.Slider(
# ax position are absolute, should be easy without subplot may be
ax = plt.axes([0.25, 0.1, 0.5, 0.03]),
label = "shift",
valmin = -5,
valmax = 5,
valinit = 2,
valstep = 0.5
)
def update(val):
x, y = get_pdf(val)
global t # really hate to do this
t.remove()
t = ax.fill_between(*get_pdf(val), color='crimson', alpha=0.7)
fig.canvas.draw_idle()
slider.on_changed(update)
ax.legend()
plt.show()
</code></pre>
|
[] |
[
{
"body": "<p>If you want to get rid of the global <code>t</code> you could consider creating a class to manage the data and updating. I quickly whipped something together, although I'm not well versed enough in stats to have a good idea about what names would be more appropriate.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import lru_cache\n\nimport numpy as np\nimport scipy.stats as ss\nimport matplotlib.pyplot as plt\nimport matplotlib.widgets as widgets\n\n#probability density function generator: chached\n@lru_cache # beacuse it redraws each time\ndef get_pdf(mu, sigma=1, offset=4):\n o = sigma * offset\n x = np.linspace(mu - o, mu + o, 100)\n rv = ss.norm(mu, sigma)\n return x, rv.pdf(x)\n\n# This simple class will hold the reference to `t` so that it doesn't need to \n# be a global\nclass Data():\n '''\n A simple class that plots data on an axis and contains a method for updating\n the plot.\n '''\n\n def __init__(self, ax, **properties):\n self.properties = properties\n self.t = ax.fill_between(*get_pdf(2), **properties)\n\n def update(self, val):\n x, y = get_pdf(val)\n self.t.remove()\n self.t = ax.fill_between(x, y, **self.properties)\n fig.canvas.draw_idle()\n\n\n# Generate the figure and axis for our widget\n\nfig, ax = plt.subplots()\n# added the subplot for bottom margin and the slider, since its also the ax\nplt.subplots_adjust(bottom=0.25)\n\n# add a slider widget\nslider = widgets.Slider(\n # ax position are absolute, should be easy without subplot may be\n ax = plt.axes([0.25, 0.1, 0.5, 0.03]), \n label = \"shift\",\n valmin = -5,\n valmax = 5,\n valinit = 2,\n valstep = 0.5\n)\n\n\n# add a reference distribution *A*\nax.fill_between(*get_pdf(0), label='A', alpha=0.7)\nax.set_xlim(-10, 10)\nax.set_ylim(0, 1)\n\n# Create a data instance\nproperties = dict(label='B', color='crimson', alpha=0.7)\ndata = Data(ax=ax, **properties)\n\n# link data update method to slider.on_changed\nslider.on_changed(data.update)\nax.legend()\nplt.show()\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:27:30.357",
"Id": "477003",
"Score": "0",
"body": "You are not using the `x, y` you defined in the `update` method. You can either remove them or re-use them in the `fill_between`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:28:02.150",
"Id": "477004",
"Score": "0",
"body": "Ah, just saw that the same is true in the OP :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:29:36.070",
"Id": "477005",
"Score": "0",
"body": "Thanks, want to edit the post perhaps?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:30:19.773",
"Id": "477006",
"Score": "0",
"body": "No, that would be a valid point to include in a review! Feel free to edit your post to include it, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T11:08:10.350",
"Id": "477010",
"Score": "1",
"body": "actually, on reflection I feel like getting `x,y = get_pdf(val)` and then `ax.fill_between(x,y...)` is more pythonic than `*get_pdf(val)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T11:16:26.183",
"Id": "477011",
"Score": "0",
"body": "Not so sure on Pythonic, both should be fine for that. But it is definitely more readable, which is why I would use it too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T11:20:31.973",
"Id": "477012",
"Score": "0",
"body": "Isn't Pythonic synonymous with readability? Otherwise, what are your thoughts on a class with a single method? I've heard people ranting about them not being a good idea, but in this case I have no idea how to keep a reference to `t` without embedding it in a new class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T11:23:11.987",
"Id": "477013",
"Score": "0",
"body": "It is a part of it for sure, but I would define it as more than readable. [This answer](https://stackoverflow.com/a/25011492/4042267) sums it up quite nicely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T11:25:49.120",
"Id": "477014",
"Score": "0",
"body": "Also, I would not think of this class as a class with one method, but rather as a class that keeps state, which also happens to have only one method (currently). But opinions may differ on that. You could make the PDF also a member of the class, if you want it to do more:-)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T09:01:29.403",
"Id": "243053",
"ParentId": "243048",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T04:36:40.140",
"Id": "243048",
"Score": "3",
"Tags": [
"python",
"matplotlib"
],
"Title": "matplotlib fixing axis scale and alignment"
}
|
243048
|
<p>I'm writing code for some accordions at the moment, using some simple vanilla JS (strictly not jQuery, has to be vanilla) and it feels like my code is really inefficient.</p>
<p>Here it is at the moment:</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>// Variables
let down = document.getElementById("chevron-down-1");
let down2 = document.getElementById("chevron-down-2");
let up = document.getElementById("chevron-up-1");
let up2 = document.getElementById("chevron-up-2");
let drop = document.getElementById("dropdown-1");
let drop2 = document.getElementById("dropdown-2");
// Functions
let open = function() {
down.style.display = "none";
up.style.display = "block";
drop.style.display = "block";
};
let close = function() {
down.style.display = "block";
up.style.display = "none";
drop.style.display = "none";
};
let open2 = function() {
down2.style.display = "none";
up2.style.display = "block";
drop2.style.display = "block";
};
let close2 = function() {
down2.style.display = "block";
up2.style.display = "none";
drop2.style.display = "none";
};
// Event Listeners
down.addEventListener('click', open);
down2.addEventListener('click', open2);
up.addEventListener('click', close);
up2.addEventListener('click', close2);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> .accordion-container {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: space-around;
flex-direction: column;
background-color: #f9f9f9;
}
.accordion {
height: auto;
width: 90%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background-color: #999;
box-shadow: 5px 10px 5px #888888;
}
.accordion-1 {
height: 30%;
width: 90%;
display: flex;
align-items: center;
justify-content: space-around;
}
#chevron-down-1 {
cursor: pointer;
}
#chevron-up-1 {
cursor: pointer;
display: none;
}
#dropdown-1 {
width: 80%;
display: none;
}
.accordion-2 {
height: 30%;
width: 90%;
display: flex;
align-items: center;
justify-content: space-around;
}
#chevron-down-2 {
cursor: pointer;
}
#chevron-up-2 {
cursor: pointer;
display: none;
}
#dropdown-2 {
width: 80%;
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="accordion-container">
<div class="accordion">
<div class="accordion-1">
<h2>Click here</h2>
<i id="chevron-down-1" class="fas fa-chevron-down"></i>
<i id="chevron-up-1" class="fas fa-chevron-up"></i>
</div>
<p id="dropdown-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="accordion">
<div class="accordion-2">
<h2>Click here</h2>
<i id="chevron-down-2" class="fas fa-chevron-down"></i>
<i id="chevron-up-2" class="fas fa-chevron-up"></i>
</div>
<p id="dropdown-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</code></pre>
</div>
</div>
</p>
<p>It feels like there's a way of writing the JavaScript so I don't have to write new functions for each new accordion, or call each element through its ID, or add respective event listeners - but I don't know the best way to approach it.</p>
<p>How would you re-shape this code to reduce the repetition?</p>
|
[] |
[
{
"body": "<p>The code can be re-written so that you don't have to write new functions. The relevant <code>functions</code>, <code>ids</code> and <code>classes</code> are there but actual power of those is not utilized. The following pointers can be noted while re-writing:</p>\n\n<ul>\n<li>The common functionalities for accordions can be clubbed via classes</li>\n<li>The common CSS for the accordion can be clubbed via classes</li>\n<li>There can be n number of accordions with <code>different ids</code> to uniquely identify each one of them and then <code>the inside html structure can be identical</code></li>\n<li>While writing functions; classes, ids etc can also be passed as arguments to make generic functions</li>\n</ul>\n\n<p>Considering these, the code can be re-written as:</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>let open = function(accordion) {\n accordion.getElementsByClassName(\"fa-chevron-down\")[0].style.display = \"none\";\n accordion.getElementsByClassName(\"fa-chevron-up\")[0].style.display = \"block\";\n accordion.getElementsByClassName(\"dropdown\")[0].style.display = \"block\";\n};\n\nlet close = function(accordion) {\n accordion.getElementsByClassName(\"fa-chevron-down\")[0].style.display = \"block\";\n accordion.getElementsByClassName(\"fa-chevron-up\")[0].style.display = \"none\";\n accordion.getElementsByClassName(\"dropdown\")[0].style.display = \"none\";\n};\n\n\ndocument.getElementsByClassName(\"accordion-container\")[0].addEventListener('click', function(e) {\n if (e.target.classList.contains(\"fa-chevron-down\")) {\n open(e.target.parentNode.parentNode)\n }\n if (e.target.classList.contains(\"fa-chevron-up\")) {\n close(e.target.parentNode.parentNode)\n }\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.accordion-container {\n height: 100vh;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-around;\n flex-direction: column;\n background-color: #f9f9f9;\n}\n\n.accordion-wrap {\n height: auto;\n width: 90%;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n background-color: #999;\n box-shadow: 5px 10px 5px #888888;\n}\n\n.accordion {\n height: 30%;\n width: 90%;\n display: flex;\n align-items: center;\n justify-content: space-around;\n}\n\n.fa-chevron-down {\n cursor: pointer;\n}\n\n.fa-chevron-up {\n cursor: pointer;\n display: none;\n}\n\n.dropdown {\n width: 80%;\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"accordion-container\">\n <div class=\"accordion-wrap\">\n <div class=\"accordion\">\n <h2>Click here</h2>\n <i class=\"fas fa-chevron-down\">></i>\n <i class=\"fas fa-chevron-up\">^</i>\n </div>\n <p class=\"dropdown\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure\n dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum..</p>\n </div>\n <div class=\"accordion-wrap\">\n <div class=\"accordion\">\n <h2>Click here</h2>\n <i class=\"fas fa-chevron-down\">></i>\n <i class=\"fas fa-chevron-up\">^</i>\n </div>\n <p class=\"dropdown\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure\n dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Here you can add <code>n</code> number of accordions. Same <code>open</code> and <code>close</code> function will be used.</p>\n\n<p>Hope it helps. Revert for any doubts/clarifications.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:38:19.357",
"Id": "243105",
"ParentId": "243055",
"Score": "1"
}
},
{
"body": "<p>Actually, you just need one handler (snippet: <code>toggleAccordeonElement</code>) to toggle the open/close state of an Accord<strong>e</strong>on. \nIf the clickable element has a <code>data-attribute</code> (snippet: <code>data-isAccordeonToggle</code>) it's easy identifiable as the element to take action on within the handler (using <a href=\"https://javascript.info/event-delegation\" rel=\"nofollow noreferrer\">event delegation</a> here). Find the closest <code>.accordion</code>-element and from that identify the elements to toggle the display value. Create an array of the elements identified and apply the toggle routing (based on the current style) for each of those elements.</p>\n\n<p>I have also reduced the number of css-classes in the snippet, and added a class name <code>dropdown</code> for the '#dropdown-[n]` elements.</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 toggleAccordeonElement = evt => {\n const origin = evt.target;\n if (origin.dataset.isaccordeontoggle) {\n const localRoot = origin.closest(\".accordion\");\n [localRoot.querySelector(`.fa-chevron-down`),\n localRoot.querySelector(`.fa-chevron-up`),\n localRoot.querySelector(`.dropdown`)\n ].forEach(elem => {\n const currentDisplayStyle = getComputedStyle(elem).getPropertyValue(\"display\");\n elem.style.display = currentDisplayStyle === \"none\" ? \"block\" : \"none\";\n origin.dataset.isaccordeontoggle = origin.dataset.isaccordeontoggle === \"Open\" \n ? \"Close\" : \"Open\";\n });\n\n }\n};\n\ndocument.addEventListener('click', toggleAccordeonElement);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.accordion-container {\n height: 100vh;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-around;\n flex-direction: column;\n background-color: #f9f9f9;\n}\n\n.accordion {\n height: auto;\n width: 90%;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n background-color: #999;\n box-shadow: 5px 10px 5px #888888;\n}\n\n.accordionInner {\n height: 30%;\n width: 90%;\n display: flex;\n align-items: center;\n justify-content: space-around;\n}\n\n.fas.fa-chevron-down {\n display: block;\n}\n\n.fas.fa-chevron-up {\n display: none;\n}\n\n.dropdown {\n width: 80%;\n display: none;\n}\n\n.accordion H2 {\n cursor: pointer;\n}\n\n[data-isaccordeontoggle]:before {\n content: attr(data-isaccordeontoggle)\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\" rel=\"stylesheet\">\n<div class=\"accordion-container\">\n <div class=\"accordion\">\n <div class=\"accordionInner\">\n <h2 data-isAccordeonToggle=\"Open\"></h2>\n <i id=\"chevron-down-1\" class=\"fas fa-chevron-down\"></i>\n <i id=\"chevron-up-1\" class=\"fas fa-chevron-up\"></i>\n </div>\n <p id=\"dropdown-1\" class=\"dropdown\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure\n dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n </div>\n <div class=\"accordion\">\n <div class=\"accordionInner\">\n <h2 data-isAccordeonToggle=\"Open\"></h2>\n <i id=\"chevron-down-2\" class=\"fas fa-chevron-down\"></i>\n <i id=\"chevron-up-2\" class=\"fas fa-chevron-up\"></i>\n </div>\n <p id=\"dropdown-2\" class=\"dropdown\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure\n dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T14:13:53.767",
"Id": "243107",
"ParentId": "243055",
"Score": "1"
}
},
{
"body": "<p>I like to always keep all my styling inside my css (unless you need to calculate something dynamically like a height, but that isn't the case here). This way you always know where to look for stuff, and css is clearly meant for styling.</p>\n\n<p>All you really need to do is toggle the state of your accordion when it is clicked, and the state defines the way it is displayed. That could be as simple as toggling a class on the accordion wrapper. Something like this:</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.querySelectorAll('.accordion header').forEach(trigger => {\n trigger.addEventListener('click', e => {\n e.currentTarget.parentNode.classList.toggle('open');\n });\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.accordion header {\n background: gray;\n cursor: pointer;\n}\n\n.fa-chevron-down {\n display: none;\n}\n\n.accordion-content {\n display: none;\n}\n\n.accordion.open .accordion-content {\n display: block;\n}\n\n.accordion.open .fa-chevron-up {\n display: none;\n}\n.accordion.open .fa-chevron-down {\n display: inline;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <div class=\"accordion-container\">\n <article class=\"accordion\">\n <header>\n <h2>Click here</h2>\n <i class=\"fas fa-chevron-down\">+</i>\n <i class=\"fas fa-chevron-up\">-</i>\n </header>\n <p class=\"accordion-content\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n </article>\n <article class=\"accordion\">\n <header>\n <h2>Click here</h2>\n <i class=\"fas fa-chevron-down\">+</i>\n <i class=\"fas fa-chevron-up\">-</i>\n </header>\n <p class=\"accordion-content\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n </article>\n </div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>(note that I reduced the css to the essential parts for clarity)</p>\n\n<p>Now you can add as many <code>.accordion</code> elements as you want without having to update your javascript, as long as you maintain the same structure. And no need for ID's either. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T01:50:41.713",
"Id": "243129",
"ParentId": "243055",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:10:20.740",
"Id": "243055",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Creating accordions without using repetitive functions"
}
|
243055
|
<p>This is my first project using Python OOP. I don't know whether the code I have written is correctly or not. How can I make this code feasible?</p>
<h1>Machine.py</h1>
<p>Class containing some default values</p>
<pre><code>class Machine:
dict_coffee = {
'Cappuccino' : 100,
'Cafe Latte' : 200,
'Espresso' : 300
}
quantity = [2,2,2]
power_status = False
</code></pre>
<h1>Coffee_Operator.py</h1>
<p>Operator class</p>
<p>Here operator can</p>
<ol>
<li>add coffee</li>
<li>modify price</li>
<li>modify quantity (add/remove)</li>
<li>turn the power on, so that the user can buy coffee</li>
<li>power off</li>
</ol>
<p></p>
<pre><code>from Machine import Machine
class CoffeeOperator(Machine):
def __init__(self):
Machine.dict_coffee
Machine.quantity
if Machine.power_status == False:
self.power_on()
while Machine.power_status == True:
print('=====================================')
print('Welcome Operator')
choice = int(input('1. Add new coffee\n2. Modify Price\n3. Modify Quantity\n4. Power On for the user\n5. Power Off\n'))
if choice == 1:
self.add_coffee()
elif choice == 2:
self.modify_price()
elif choice == 3:
self.modify_quantity()
elif choice == 4:
self.power_on()
from Coffee_Buyer import Coffee
Machine.power_status = False
elif choice == 5:
self.power_off()
else:
print('Invalid Input')
def power_on(self):
Machine.power_status = True
def power_off(self):
Machine.power_status = False
return Machine.power_status
def print_values(self):
print('=====================================')
print('List of Coffee: ')
print('Coffee | Cost | Quantity')
key_lst = list(Machine.dict_coffee)
value = Machine.dict_coffee.values()
value_lst = list(value)
for i in range(len(key_lst)):
print('{} | {} | {} '.format(key_lst[i],value_lst[i],Machine.quantity[i]))
def add_coffee(self):
name= input('New coffee name: ')
price = int(input('New coffee price: '))
quantity = int(input('New coffee Quality: '))
Machine.dict_coffee.update({name:price})
Machine.quantity.append(quantity)
self.print_values()
def modify_price(self):
name = input('Enter name of coffee: ')
if name in Machine.dict_coffee:
update_price = int(input('Updated price: '))
Machine.dict_coffee[name] = update_price
print('Cost of {} is Rs{}'.format(name,update_price))
else:
print('Invalid coffee name')
def modify_quantity(self):
print('Available quantity:')
key_lst = list(Machine.dict_coffee)
for i in range(len(key_lst)):
print('Quantity of {} is {}'.format(key_lst[i],Machine.quantity[i]))
name = input('Enter name of coffee: ')
if name in Machine.dict_coffee:
add_remove = int(input('1.Add more\n2.Remove existing\n'))
change_quantity = int(input('Update quantity: '))
name_lst = list(Machine.dict_coffee)
index_name = name_lst.index(name)
if add_remove == 1:
Machine.quantity[index_name] += change_quantity
self.print_values()
elif add_remove == 2:
if Machine.quantity[index_name] >= change_quantity:
Machine.quantity[index_name] -= change_quantity
self.print_values()
else:
print('You have exceed the quantity')
def get_dict(self):
return Machine.dict_coffee
def get_quantity(self):
return Machine.quantity
def get_power(self):
return Machine.power_status
if __name__ == "__main__":
opr = CoffeeOperator()
</code></pre>
<h1>Coffee_Buyer.py</h1>
<p>Buyer class</p>
<p>User can buy the coffee. If the quantity of coffee is zero then that coffee is removed from the list.</p>
<pre><code>import os
import time
from Coffee_Operator import CoffeeOperator
class Coffee(CoffeeOperator):
def __init__(self):
dict_coffee = CoffeeOperator.get_dict(CoffeeOperator)
quantity = CoffeeOperator.get_quantity(CoffeeOperator)
power_status = CoffeeOperator.get_power(CoffeeOperator)
self.power_status = True
print('Welcome User')
while self.power_status == True:
self.display(len(self.quantity))
if self.quantity == [0] or len(self.quantity) == 0:
print("No Coffee. Turning off")
self.power_status = False
break
else:
user_input = int(input('Your choice: ')) - 1
if 0 <= user_input < len(self.quantity):
if self.available(user_input) == True:
print('Coffee is getting ready, Please pay the cost')
self.coffee_cost(user_input)
else:
os.system('cls' if os.name == 'nt' else 'clear')
print('Invalid input. There is no coffee at option {}'.format(user_input+1))
def available(self,user_input):
if self.quantity[user_input] > 0:
self.quantity[user_input] -= 1
return True
def display(self,length):
for i in [0]:
try:
x = self.quantity.index(i)
self.quantity.pop(x)
keys_list = list(self.dict_coffee)
del_x = keys_list[x]
self.dict_coffee.pop(del_x)
except ValueError:
pass
for key,value in self.dict_coffee.items():
print('{} at Rs {}'.format(key,value))
def coffee_cost(self,user_input):
value = self.dict_coffee.values()
cost_lst = list(value)
cost = cost_lst[user_input]
jack=True
while jack:
cost_input = int(input('Coffee cost: '))
if cost_input != cost:
print('Please enter perfect amount of Rs{}'.format(cost))
jack = True
else:
print('Please collect your coffee')
time.sleep(2)
os.system('cls' if os.name == 'nt' else 'clear')
jack = False
os.system('cls' if os.name == 'nt' else 'clear')
c = Coffee()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T10:12:56.097",
"Id": "243056",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Coffee machine project using Python OOP"
}
|
243056
|
<p>I have tree-like data that is constructed of Parent codes that contain Child codes which may act as parents themselves, depending on if they're marked as "SA". This data is present in an Excel sheet and looks like follows: </p>
<pre class="lang-none prettyprint-override"><code>| Tree Level (A) | Code (B) | Spec (C) | Comm. Code (D) | Parent Code (J) |
|----------------|----------|----------|----------------|-----------------|
| 1 | A12 | 1 | SA | Mach |
| 2 | B41 | 2 | SA | A12 |
| 3 | A523 | 1 | BP | B41 |
| 2 | G32 | 4 | BP | A12 |
| 2 | D3F5 | 1 | SA | A12 |
| 3 | A12 | 4 | SA | D3F5 |
| 3 | A12 | 1 | SA | D3F5 |
</code></pre>
<p>There is one issue here: A12, at the top tree level (1), contains a child (D3F5), which itself contains another parent that's the same as D3F5's own parent. As you may be able to imagine, this (although not represented in the data as it is delivered to me) creates an endless loop, where A12 at tree level 3 unfolds the entire structure again and again.</p>
<p>Note that one of the two 'A12' children poses no problem, as this has a different specification as to the A12 parent at tree level 1.</p>
<p>I have a function that checks for this situation, but it is extremely slow as it uses nested loops to go through the rows, and the total row count can be several 1000s:</p>
<pre><code>def nested_parent(sht):
"""
Checks if a parent SA contains itself as a child.
:return: nested_parents: Dictionary of found 'nested parents'. None if none found
"""
nested_parents = {}
found = False
lrow = sht.Cells(sht.Rows.Count, 1).End(3).Row
parent_treelevel = 1
# Get deepest tree level, as this no longer contains children
last_treelevel = int(max([i[0] for i in sht.Range(sht.Cells(2, 1), sht.Cells(lrow, 1)).Value]))
# Loop through parent rows
print('Checking for nested parents...')
for i in range(2, lrow):
if sht.Cells(i, "D").Value == "SA":
parent_code, parent_treelevel = f'{sht.Cells(i, "B").Value}_{sht.Cells(i, "C")}', sht.Cells(i, "A").Value
# Add new key with list containing parent's tree level for parent code
if parent_code not in nested_parents:
nested_parents[parent_code] = [int(parent_treelevel)]
# Loop child rows
for j in range(i + 1, lrow + 1):
child_code, child_treelevel = f'{sht.Cells(j, "B").Value}_{sht.Cells(j, "C")}', sht.Cells(i, "A").Value
if child_code == parent_code and child_treelevel > parent_treelevel:
found = True
nested_parents[parent_code].append(int(child_treelevel))
if parent_treelevel == last_treelevel:
# End function if deepst tree level is reached
print("done")
if found:
# Delete keys that contain no information
delkeys = []
for key in reversed(nested_parents):
if len(nested_parents[key]) == 1:
delkeys.append(key)
for key in delkeys:
del nested_parents[key]
return nested_parents
else:
return
</code></pre>
<p>This function can be called as follows, where <code>wb_name</code> is the name of the workbook that contains the data:</p>
<pre><code>from win32com.client import GetObject
wb_name = "NAME"
sht = GetObject(None, "Excel.Application").Workbooks(wb_name).Worksheets(1)
infloop = nested_parent(sht)
if infloop is not None:
dict_str = ''.join([f'Code: {key}, Tree levels: {infloop[key]}\n' for key in infloop])
err(f"Warning: one or more parent codes contain their own code as a child:\n{dict_str}")
</code></pre>
<p>I am hoping to speed up this code, as the rest of my script is fairly quick and its speed is being seriously hampered by this function.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:32:11.360",
"Id": "477049",
"Score": "0",
"body": "Isn't this just looking for directed cycles in the directed graph? Just have the tuples `Code, Spec` be the nodes and add an edge from each node to its parent. Then use [this](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.cycles.find_cycle.html) to find if the graph contains a directed cycle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:37:27.187",
"Id": "477051",
"Score": "0",
"body": "Since it just uses DFS, it should even be O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T04:12:05.503",
"Id": "477075",
"Score": "0",
"body": "Maybe your other code can keep track of what 'parents' nodes have been seen (add them to a `set()` after processing them). Then before processing a new parent node, check to see if it's in the set already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T04:15:58.497",
"Id": "477076",
"Score": "0",
"body": "Would it suffice to search for two rows with \"Comm. Code (D)\" == \"SA\" and the same \"Code (B)\", but different \"Tree Level (A)\"s"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T10:04:31.060",
"Id": "477096",
"Score": "0",
"body": "@RootTwo both methods would not work as parent nodes can and will be present multiple times without it being an issue, as I show in the example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T10:05:27.140",
"Id": "477097",
"Score": "0",
"body": "@Graipher I am not familiar with directed cycles, nor with directed graphs. If you could construct an answer out of your comment, that would help tremendously"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T14:57:37.667",
"Id": "477120",
"Score": "0",
"body": "@TimStack: What is not quite clear to me is how do you know that the `A12` of the entry `D3F5` corresponds to the `A12` with spec 1 and not 4? Is it always the one with the lowest tree level?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T10:54:01.967",
"Id": "477348",
"Score": "0",
"body": "@Graipher both `A12`'s are children of `D3F5` and indirectly of the top `A12`. However, since one has the same specification as the top `A12`, an endless loop follows. A parent's contents depend on the parent's code + spec."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T11:27:52.613",
"Id": "243060",
"Score": "0",
"Tags": [
"python",
"excel",
"time-limit-exceeded"
],
"Title": "How do I quickly look for parents containing their own code as child?"
}
|
243060
|
<p>I have recently been digging into understanding Golang concurrency, in particular the use of channels and worker pools. I wanted to compare performance between Go and Python (as many have done) because I have mostly read that Go outperforms Python with regard to concurrency. So I wrote two programs to scan an AWS account's S3 buckets and report back the total size. I performed this on an account that had more the 75 buckets totalling more than a few TB of data. </p>
<p>I was surprised to find that my Python implementation was nearly 2x faster than my Go implementation. This confuses me based on all the benchmarks and literature I have read. This leads me to believe that I did not implement my Go code correctly. While watching both programs run I noticed that the Go implementation only used up to 15% of my CPU while Python used >85%. Am I missing an important step with Go or am I missing something in my implementation? Thanks in advance! </p>
<p><strong>Python Code:</strong></p>
<blockquote>
<pre class="lang-py prettyprint-override"><code>'''
Get the size of all objects in all buckets in S3
'''
import os
import sys
import boto3
import concurrent.futures
def get_s3_bucket_sizes(aws_access_key_id, aws_secret_access_key, aws_session_token=None):
s3client = boto3.client('s3')
# Create the dictionary which will be indexed by the bucket's
# name and has an S3Bucket object as its contents
buckets = {}
total_size = 0.0
#
# Start gathering data...
#
# Get all of the buckets in the account
_buckets = s3client.list_buckets()
cnt = 1
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
future_bucket_to_scan = {executor.submit(get_bucket_objects, s3client, bucket): bucket for bucket in _buckets["Buckets"]}
for future in concurrent.futures.as_completed(future_bucket_to_scan):
bucket_object = future_bucket_to_scan[future]
try:
ret = future.result()
except Exception as exc:
print('ERROR: %s' % (str(exc)))
else:
total_size += ret
print(total_size)
def get_bucket_objects(s3client, bucket):
name = bucket["Name"]
# Get all of the objects in the bucket
lsbuckets = s3client.list_objects(Bucket=name)
size = 0
while True:
if "Contents" not in lsbuckets.keys():
break
for content in lsbuckets["Contents"]:
size += content["Size"]
break
return size
#
# Main
#
if __name__=='__main__':
get_s3_bucket_sizes(os.environ.get("AWS_ACCESS_KEY_ID"), os.environ.get("AWS_SECRET_ACCESS_KEY"))
</code></pre>
</blockquote>
<p><strong>Go Code:</strong></p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"fmt"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
type S3_Bucket_Response struct {
bucket string
count int64
size int64
err error
}
type S3_Bucket_Request struct {
bucket string
region string
}
func get_bucket_objects_async(wg *sync.WaitGroup, requests chan S3_Bucket_Request, responses chan S3_Bucket_Response) {
var size int64
var count int64
for request := range requests {
bucket := request.bucket
region := request.region
// Create a new response
response := new(S3_Bucket_Response)
response.bucket = bucket
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
})
s3conn := s3.New(sess)
resp, err := s3conn.ListObjectsV2(&s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case "NoSuchBucket":
response.err = fmt.Errorf("Bucket: (%s) is NoSuchBucket. Must be in process of deleting.", bucket)
case "AccessDenied":
response.err = fmt.Errorf("Bucket: (%s) is AccessDenied. You should really be running this with full Admin Privaleges", bucket)
}
} else {
response.err = fmt.Errorf("Listing Objects Unhandled Error: %s ", err)
}
responses <- *response
continue
}
contents := resp.Contents
size = 0
count = 0
for i:=0; i<len(contents); i++ {
size += *contents[i].Size
count += 1
}
response.size = size
response.count = count
responses <- *response
}
wg.Done()
}
func main() {
var err error
var size int64
var resp *s3.ListBucketsOutput
var wg sync.WaitGroup
sess, _ := session.NewSession()
s3conn := s3.New(sess)
// Get account bucket listing
if resp, err = s3conn.ListBuckets(&s3.ListBucketsInput{});err != nil {
fmt.Println("Error listing buckets: %s", err)
return
}
buckets := resp.Buckets
size = 0
// Create the buffered channels
requests := make(chan S3_Bucket_Request , len(buckets))
responses := make(chan S3_Bucket_Response, len(buckets))
for i := range buckets {
bucket := *buckets[i].Name
resp2, err := s3conn.GetBucketLocation(&s3.GetBucketLocationInput{
Bucket: aws.String(bucket),
})
if err != nil {
fmt.Printf("Could not get bucket location for bucket (%s): %s", bucket, err)
continue
}
wg.Add(1)
go get_bucket_objects_async(&wg, requests, responses)
region := "us-east-1"
if resp2.LocationConstraint != nil {
region = *resp2.LocationConstraint
}
request := new(S3_Bucket_Request)
request.bucket = bucket
request.region = region
requests <- *request
}
// Close requests channel and wait for responses
close(requests)
wg.Wait()
close(responses)
cnt := 1
// Process the results as they come in
for response := range responses {
fmt.Printf("Bucket: (%s) complete! Buckets remaining: %d\n", response.bucket, len(buckets)-cnt)
// Did the bucket request have errors?
if response.err != nil {
fmt.Println(response.err)
continue
}
cnt += 1
size += response.size
}
fmt.Println(size)
return
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T12:58:14.123",
"Id": "477021",
"Score": "1",
"body": "A little of the Python formatting may have been messed up when I pressed the block quote button. Why it doesn't just add `> ` to the beginning of each line is beyond me. -.-"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T06:52:20.983",
"Id": "477546",
"Score": "1",
"body": "maybe you should not open a new session for each bucket. maybe you are being throttled because you perform too many concurrent connections. That golang consumes only 15% is expected as your code is not doing intensive work. This should be async `wg.Wait(); close(responses);`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T12:26:20.667",
"Id": "243063",
"Score": "0",
"Tags": [
"go",
"concurrency"
],
"Title": "Why is my Python thread pool faster than my Go worker pool?"
}
|
243063
|
<p>I need help fixing my gameloop. Sometimes the game feels very laggy and I think the reason is that the tick() method is called slower then the render() method. What I want is that update is called as often as possible and the tick method gets executed with some kind of value that determines how fast thinks are going. For example the value is 0.8 and I just multiply it to determine how fast Things should go.</p>
<p>And I think my current gameloop is just a mess!</p>
<pre><code>public void run() {
init();
double timePerTick = 1000000000 / targetTicksPerSecond;
double timePerFrame = 1000000000 / targetFramesPerSecond;
double delta = 0;
double delta2 = 0;
long now;
long lastTime = System.nanoTime();
long timer = 0;
long renderTimer = 0;
int ticks = 0;
while (running) {
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
delta2 += (now - lastTime) / timePerFrame;
timer += now - lastTime;
lastTime = now;
if (delta >= 1) {
tick();
ticks++;
delta--;
}
if(delta2 >= 1) {
render();
renderTimer++;
delta2--;
}
if (timer >= 1000000000) {
currentTicks = ticks;
currentFPS = (int) renderTimer;
ticks = 0;
timer = 0;
renderTimer = 0;
}
}
stop();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T16:14:32.570",
"Id": "477031",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T16:09:42.647",
"Id": "243067",
"Score": "1",
"Tags": [
"java",
"performance"
],
"Title": "Lags caused by bad Game Loop"
}
|
243067
|
<p>I am new to rust and this is a program that finds out the palindromes between a range. All tests have been passed but this program is really slow in finding the 4 digits Palindromes.</p>
<p>This is an exercism exercise and Palindrome struct and struct methods new, value, and insert must be used in the final solution.</p>
<p>I need your help to review this code. </p>
<pre><code>use std::cmp::Ordering;
#[macro_use]
extern crate itertools;
#[derive(Debug, Eq)]
pub struct Palindrome {
factors: (u64, u64)
}
impl PartialOrd for Palindrome {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Palindrome {
fn cmp(&self, other: &Self) -> Ordering {
// self.height.cmp(&other.height)
(self.value()).cmp(&other.value())
}
}
impl PartialEq for Palindrome {
fn eq(&self, other: &Self) -> bool {
// self.height == other.height
self.value() == other.value()
}
}
impl Palindrome {
pub fn new(a: u64, b: u64) -> Palindrome {
Palindrome{
factors: (b, a)
}
}
pub fn value(&self) -> u64 {
self.factors.0*self.factors.1
}
pub fn insert(&mut self, a: u64, b: u64) {
self.factors.0 = a;
self.factors.1 = b;
}
}
fn reverse_number(mut n: u64) -> u64{
let radix = 10;
let mut reversed = 0;
while n != 0 {
reversed = reversed * radix + n % radix;
n /= radix;
}
reversed
}
fn is_palindrome(palindrome: &Palindrome) -> bool{
if palindrome.value() == reverse_number(palindrome.value()){
return true;
}
false
}
pub fn palindrome_products(min: u64, max: u64)-> Option<(Palindrome, Palindrome)>{
if max <= min {
return None;
}
let products = iproduct!(min..=max, min..=max)
.map(|(i, j)| Palindrome::new(i, j))
.filter(|palindrome| is_palindrome(palindrome));
Some((products.clone().min()?, products.clone().max()?))
}
</code></pre>
<p>Here is the full the test Suit</p>
<pre><code>//! This test suite was generated by the rust exercise tool, which can be found at
//! https://github.com/exercism/rust/tree/master/util/exercise
use palindrome_products::{palindrome_products, Palindrome};
/// Process a single test case for the property `smallest`
///
/// All cases for the `smallest` property are implemented
/// in terms of this function.
fn process_smallest_case(input: (u64, u64), expected: Option<Palindrome>) {
let min = palindrome_products(input.0, input.1).map(|(min, _)| min);
assert_eq!(min, expected);
}
/// Process a single test case for the property `largest`
///
/// All cases for the `largest` property are implemented
/// in terms of this function.
///
fn process_largest_case(input: (u64, u64), expected: Option<Palindrome>) {
let max = palindrome_products(input.0, input.1).map(|(_, max)| max);
assert_eq!(max, expected);
}
#[test]
/// finds the smallest palindrome from single digit factors
fn test_finds_the_smallest_palindrome_from_single_digit_factors() {
process_smallest_case((1, 9), Some(Palindrome::new(1, 1)));
}
#[test]
#[ignore]
/// finds the largest palindrome from single digit factors
fn test_finds_the_largest_palindrome_from_single_digit_factors() {
let mut expect = Palindrome::new(1, 9);
expect.insert(3, 3);
process_largest_case((1, 9), Some(expect));
}
#[test]
#[ignore]
/// find the smallest palindrome from double digit factors
fn test_find_the_smallest_palindrome_from_double_digit_factors() {
process_smallest_case((10, 99), Some(Palindrome::new(11, 11)));
}
#[test]
#[ignore]
/// find the largest palindrome from double digit factors
fn test_find_the_largest_palindrome_from_double_digit_factors() {
process_largest_case((10, 99), Some(Palindrome::new(91, 99)));
}
#[test]
#[ignore]
/// find smallest palindrome from triple digit factors
fn test_find_smallest_palindrome_from_triple_digit_factors() {
process_smallest_case((100, 999), Some(Palindrome::new(101, 101)));
}
#[test]
#[ignore]
/// find the largest palindrome from triple digit factors
fn test_find_the_largest_palindrome_from_triple_digit_factors() {
process_largest_case((100, 999), Some(Palindrome::new(913, 993)));
}
#[test]
#[ignore]
/// find smallest palindrome from four digit factors
fn test_find_smallest_palindrome_from_four_digit_factors() {
process_smallest_case((1000, 9999), Some(Palindrome::new(1001, 1001)));
}
#[test]
#[ignore]
/// find the largest palindrome from four digit factors
fn test_find_the_largest_palindrome_from_four_digit_factors() {
process_largest_case((1000, 9999), Some(Palindrome::new(9901, 9999)));
}
#[test]
#[ignore]
/// empty result for smallest if no palindrome in the range
fn test_empty_result_for_smallest_if_no_palindrome_in_the_range() {
process_smallest_case((1002, 1003), None);
}
#[test]
#[ignore]
/// empty result for largest if no palindrome in the range
fn test_empty_result_for_largest_if_no_palindrome_in_the_range() {
process_largest_case((15, 15), None);
}
#[test]
#[ignore]
/// error result for smallest if min is more than max
fn test_error_result_for_smallest_if_min_is_more_than_max() {
process_smallest_case((10000, 1), None);
}
#[test]
#[ignore]
/// error result for largest if min is more than max
fn test_error_result_for_largest_if_min_is_more_than_max() {
process_largest_case((2, 1), None);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Run <code>rustfmt</code></h1>\n\n<p>You have some inconsistent formatting. Just run <code>cargo fmt</code> and your code will be automatically formatted to best practices.</p>\n\n<h1>Make <code>Palindrome</code> a tuple struct</h1>\n\n<p>Instead of</p>\n\n<pre><code>#[derive(Debug, Eq)]\npub struct Palindrome {\n factors: (u64, u64),\n}\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>#[derive(Debug, Eq)]\npub struct Palindrome(u64, u64);\n</code></pre>\n\n<h1>Derive <code>PartialOrd</code></h1>\n\n<p>Instead of</p>\n\n<pre><code>impl PartialOrd for Palindrome {\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n Some(self.cmp(other))\n }\n}\n</code></pre>\n\n<p>Just use <code>#[derive(Debug, Eq, PartialOrd)]</code> instead, like what you already do for <code>Eq</code>.</p>\n\n<h1>Rename <code>Palindrome</code></h1>\n\n<p>It should be called something like <code>Pair</code> instead, unless required by your course—an instance of a <code>Palindrome</code> can actually not be a palindrome.</p>\n\n<h1>Don't explicitly return</h1>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn is_palindrome(palindrome: &Palindrome) -> bool {\n if palindrome.value() == reverse_number(palindrome.value()) {\n return true;\n }\n false\n}\n</code></pre>\n\n<p>You're comparing a boolean, then returning based on that. Just return the boolean directly:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn is_palindrome(palindrome: &Palindrome) -> bool {\n palindrome.value() == reverse_number(palindrome.value())\n}\n</code></pre>\n\n<p>However, that function should probably be a method of <code>Palindrome</code> unless it's required to be separate by the course.</p>\n\n<h1>Accept a range instead of <code>(min, max)</code></h1>\n\n<p>Instead of</p>\n\n<pre><code>pub fn palindrome_products(min: u64, max: u64) -> Option<(Palindrome, Palindrome)> {\n if max <= min {\n return None;\n }\n\n let products = iproduct!(min..=max, min..=max)\n .map(|(i, j)| Palindrome::new(i, j))\n .filter(|palindrome| palindrome.is_palindrome());\n\n Some((products.clone().min()?, products.clone().max()?))\n}\n\nfn process_smallest_case(input: (u64, u64), expected: Option<Palindrome>) {\n let min = palindrome_products(input.0, input.1).map(|(min, _)| min);\n assert_eq!(min, expected);\n}\n</code></pre>\n\n<p>How about</p>\n\n<pre><code>pub fn palindrome_products(range: RangeInclusive<u64>) -> Option<(Palindrome, Palindrome)> {\n let products = iproduct!(range.clone(), range)\n .map(|(i, j)| Palindrome::new(i, j))\n .filter(|palindrome| palindrome.is_palindrome());\n\n Some((products.clone().min()?, products.clone().max()?))\n}\n\nfn process_smallest_case(input: RangeInclusive<u64>, expected: Option<Palindrome>) {\n let min = palindrome_products(input).map(|(min, _)| min);\n assert_eq!(min, expected);\n}\n</code></pre>\n\n<h1>Performance: use <code>Itertools::minmax</code></h1>\n\n<p>Currently, you check if every number is a palindrome twice:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn palindrome_products(range: RangeInclusive<u64>) -> Option<(Palindrome, Palindrome)> {\n let products = iproduct!(range.clone(), range)\n .map(|(i, j)| Palindrome::new(i, j))\n .filter(|palindrome| palindrome.is_palindrome());\n\n Some((products.clone().min()?, products.clone().max()?))\n}\n</code></pre>\n\n<p>Instead, use:</p>\n\n<pre><code>pub fn palindrome_products(range: RangeInclusive<u64>) -> Option<(Palindrome, Palindrome)> {\n let products = iproduct!(range.clone(), range)\n .map(|(i, j)| Palindrome::new(i, j))\n .filter(|palindrome| palindrome.is_palindrome());\n match products.minmax() {\n MinMaxResult::NoElements => None,\n // You'll need to #[derive(Copy, Clone)] on Palindrome\n MinMaxResult::OneElement(p) => Some((p, p)),\n MinMaxResult::MinMax(min, max) => Some((min, max)),\n }\n}\n</code></pre>\n\n<p>Alternatively, you could return a <code>impl Iterator<Item = Palindrome></code> from <code>palindrome_products</code> and call <code>.min()</code> or <code>.max()</code> from <code>process_smallest_case</code> and <code>process_largest_case</code> respectively.</p>\n\n<h1>Embed tests</h1>\n\n<p>Put your tests in the same file, then gate them behind a</p>\n\n<pre><code>#[cfg(test)]\nmod tests {\n // tests\n}\n</code></pre>\n\n<h1>Add benchmarks</h1>\n\n<p>I don't know how you're testing speed, but Rust doesn't optimize your code by default when running tests. Either use the <a href=\"https://doc.rust-lang.org/unstable-book/library-features/test.html\" rel=\"nofollow noreferrer\">unstable <code>#[bench]</code> attribute</a> or my personal favorite <a href=\"https://bheisler.github.io/criterion.rs/book/getting_started.html\" rel=\"nofollow noreferrer\">Criterion</a>. Both will automatically compile for optimization.</p>\n\n<h1>Final code</h1>\n\n<pre><code>use std::cmp::Ordering;\nuse std::ops::RangeInclusive;\n\nuse itertools::iproduct;\nuse itertools::{Itertools, MinMaxResult};\n\n#[derive(Copy, Clone, Debug, Eq, PartialOrd)]\npub struct Pair(u64, u64);\n\nimpl Ord for Pair {\n fn cmp(&self, other: &Self) -> Ordering {\n self.value().cmp(&other.value())\n }\n}\n\nimpl PartialEq for Pair {\n fn eq(&self, other: &Self) -> bool {\n self.value() == other.value()\n }\n}\n\nimpl Pair {\n pub fn new(a: u64, b: u64) -> Pair {\n Pair(b, a)\n }\n\n pub fn value(&self) -> u64 {\n self.0 * self.1\n }\n\n pub fn insert(&mut self, a: u64, b: u64) {\n self.0 = a;\n self.1 = b;\n }\n\n pub fn is_palindrome(&self) -> bool {\n self.value() == reverse_number(self.value())\n }\n}\n\nfn reverse_number(mut n: u64) -> u64 {\n let radix = 10;\n let mut reversed = 0;\n\n while n != 0 {\n reversed = reversed * radix + n % radix;\n n /= radix;\n }\n\n reversed\n}\n\npub fn palindrome_products(range: RangeInclusive<u64>) -> Option<(Pair, Pair)> {\n let products = iproduct!(range.clone(), range)\n .map(|(i, j)| Pair::new(i, j))\n .filter(Pair::is_palindrome);\n match products.minmax() {\n MinMaxResult::NoElements => None,\n MinMaxResult::OneElement(p) => Some((p, p)),\n MinMaxResult::MinMax(min, max) => Some((min, max)),\n }\n}\n\n#[cfg(test)]\nmod tests {\n use std::ops::RangeInclusive;\n\n use super::{palindrome_products, Pair};\n\n fn process_smallest_case(input: RangeInclusive<u64>, expected: Option<Pair>) {\n let min = palindrome_products(input).map(|(min, _)| min);\n assert_eq!(min, expected);\n }\n\n /// Process a single test case for the property `largest`\n ///\n /// All cases for the `largest` property are implemented in terms of this function.\n ///\n fn process_largest_case(input: RangeInclusive<u64>, expected: Option<Pair>) {\n let max = palindrome_products(input).map(|(_, max)| max);\n assert_eq!(max, expected);\n }\n\n #[test]\n /// finds the smallest palindrome from single digit factors\n fn test_finds_the_smallest_palindrome_from_single_digit_factors() {\n process_smallest_case(1..=9, Some(Pair::new(1, 1)));\n }\n\n #[test]\n #[ignore]\n /// finds the largest palindrome from single digit factors\n fn test_finds_the_largest_palindrome_from_single_digit_factors() {\n let mut expect = Pair::new(1, 9);\n expect.insert(3, 3);\n process_largest_case(1..=9, Some(expect));\n }\n\n #[test]\n #[ignore]\n /// find the smallest palindrome from double digit factors\n fn test_find_the_smallest_palindrome_from_double_digit_factors() {\n process_smallest_case(10..=99, Some(Pair::new(11, 11)));\n }\n\n #[test]\n #[ignore]\n /// find the largest palindrome from double digit factors\n fn test_find_the_largest_palindrome_from_double_digit_factors() {\n process_largest_case(10..=99, Some(Pair::new(91, 99)));\n }\n\n #[test]\n #[ignore]\n /// find smallest palindrome from triple digit factors\n fn test_find_smallest_palindrome_from_triple_digit_factors() {\n process_smallest_case(100..=999, Some(Pair::new(101, 101)));\n }\n\n #[test]\n #[ignore]\n /// find the largest palindrome from triple digit factors\n fn test_find_the_largest_palindrome_from_triple_digit_factors() {\n process_largest_case(100..=999, Some(Pair::new(913, 993)));\n }\n\n #[test]\n #[ignore]\n /// find smallest palindrome from four digit factors\n fn test_find_smallest_palindrome_from_four_digit_factors() {\n process_smallest_case(1000..=9999, Some(Pair::new(1001, 1001)));\n }\n\n #[test]\n #[ignore]\n /// find the largest palindrome from four digit factors\n fn test_find_the_largest_palindrome_from_four_digit_factors() {\n process_largest_case(1000..=9999, Some(Pair::new(9901, 9999)));\n }\n\n #[test]\n #[ignore]\n /// empty result for smallest if no palindrome in the range\n fn test_empty_result_for_smallest_if_no_palindrome_in_the_range() {\n process_smallest_case(1002..=1003, None);\n }\n\n #[test]\n #[ignore]\n /// empty result for largest if no palindrome in the range\n fn test_empty_result_for_largest_if_no_palindrome_in_the_range() {\n process_largest_case(15..=15, None);\n }\n\n #[test]\n #[ignore]\n /// error result for smallest if min is more than max\n fn test_error_result_for_smallest_if_min_is_more_than_max() {\n process_smallest_case(10000..=1, None);\n }\n\n #[test]\n #[ignore]\n /// error result for largest if min is more than max\n fn test_error_result_for_largest_if_min_is_more_than_max() {\n process_largest_case(2..=1, None);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T07:24:11.120",
"Id": "477183",
"Score": "0",
"body": "Couldn't figure out where I am testing for palindrome twice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T07:30:17.400",
"Id": "477184",
"Score": "0",
"body": "''' filter(|palindrome| palindrome.is_palindrome());''' should be '''.filter(palindrome.is_palindrome);'''"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T16:55:01.427",
"Id": "477230",
"Score": "1",
"body": "@GraphicalDot you were testing for palindromes twice because you were cloning the iterator and using it in `min` and `max`. Iterators are lazy, so they're evaluated when used—there's no temporary array created. So `min` would run through the entire iterator and find minimums, and `max` would run through it again (calling `is_palindrome` on every number a second time). As for `filter`, you can either use `filter(|palindrome| palindrome.is_palindrome())` or `filter(Pair::is_palindrome)`. `filter(palindrome.is_palindrome)` is not valid Rust (nor is it valid Java, JS, or C++, but it is in Go)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T17:17:17.237",
"Id": "243115",
"ParentId": "243068",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T16:41:22.693",
"Id": "243068",
"Score": "4",
"Tags": [
"performance",
"rust"
],
"Title": "Smallest and largest palindromes"
}
|
243068
|
<p>The following code represents the store method of a resource controller.
A user can create an training offer on my website and can pass various information like <code>website</code>, <code>trainers</code>, <code>date</code>, <code>title</code>, <code>address</code>, <code>videos</code> and also upload a <code>coverImage</code> and multiple images for a <code>gallery</code>. </p>
<p>The following steps are conducted:</p>
<ul>
<li>Validate the input in <code>StoreTraining</code></li>
<li>Parse the input from user in <code>ParseStoreTraining</code></li>
<li>Create the training model in <code>TrainingRepository</code></li>
<li>Upload cover image in <code>TrainingRepository</code></li>
<li>Upload gallery in <code>MediaRepository</code></li>
<li>Create relationships for training model (this is a hasManyThrough relation for <code>gallery</code> and <code>video</code>) in <code>MediaRepository</code>.</li>
</ul>
<p>Here comes the store method from the <code>TrainingsController</code>.</p>
<pre><code>public function store(StoreTraining $request)
{
\App\Repositories\TrainingRepository::create($request);
return view('home.training.show');
}
</code></pre>
<p>The <code>StoreTraining</code> is a <code>FormRequest</code> that handles the validation:</p>
<pre><code>class StoreTraining extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'addressid' => 'required',
'trainer' => 'required',
'dates' => 'required',
'mode' => 'required',
];
}
}
</code></pre>
<p>The <code>TrainingRepository</code> class handles the creation of the training.</p>
<pre><code>class TrainingRepository
{
public static function create(Request $request)
{
$parsedRequest = new ParseStoreTraining($request);
$profileTraining = ProfileCalender::create($parsedRequest->all());
// Upload Image
if (!empty($request->file('coverImage'))) {
$path = Storage::disk('public')->putFile('trainings/' . $profileTraining->id, $request->file('coverImage'));
$profileTraining->cover_image = $path;
$profileTraining->save();
}
// Update relations
$mediaRepository = new MediaRepository($profileTraining);
if (!empty($request->gallery)) {
$mediaRepository->addGalleryToTraining($request->gallery);
}
if (!empty($request->video_url)) {
$mediaRepository->addVideo($request->video_url);
}
}
}
</code></pre>
<p>The <code>ParseStoreTraining</code> request converts the input to be useable for the <code>ProfileCalender::create</code> method:</p>
<pre><code>class ParseStoreTraining
{
private $request;
private $trainerA;
private $trainerB;
private $institute_id;
private $beginn_date;
public function __construct(FormRequest $request)
{
$this->request = $request;
$this->identifyTrainer();
$this->identifyInstitute();
$this->identifyDate();
}
public function all(): array
{
return [
'idAddress' => $this->request->addressid,
'trainerA' => $this->trainerA,
'trainerB' => $this->trainerB,
'beginnDate' => $this->beginn_date,
'mode_id' => $this->request->mode,
'idInstitute' => $this->institute_id,
'viewable' => false,
'idOrga' => getOrga(),
'title' => $this->request->title,
'coreArea' => $this->request->focus,
'url' => $this->request->website,
'price' => $this->request->price,
'description' => $this->request->description,
];
}
private function identifyTrainer(): void
{
if (is_array($this->request->trainer)) {
$this->trainerA = $this->request->trainer[0];
$this->trainerB = $this->request->trainer[1] ?? null;
return;
}
$this->trainerA = $this->request->trainer;
$this->trainerB = null;
}
private function identifyInstitute(): void
{
$this->institute_id = \Auth::user()->getInstituteId();
if (empty($this->institute_id)) {
throw new \Exception('User has no related institute id', 1);
}
}
private function identifyDate(): void
{
// Convert JS Date to MYSQL Timestamp
$cleanDate = preg_replace('/\(.*\)/', '', $this->request->dates);
$beginn_date = strtotime($cleanDate);
$this->beginn_date = date('Y-m-d', $beginn_date);
}
}
</code></pre>
<p>A training has many <code>galleries</code> and <code>videos</code> through a <code>media</code> class. The <code>MediaRepository</code> is responsible for creating these relations:</p>
<pre><code>class MediaRepository
{
private $training;
public function __construct(ProfileCalender $training)
{
$this->training = $training;
}
public function addGalleryToTraining(array $images): void
{
if (empty($images)) {
return;
}
$media = $this->training->media()->create([
'institute' => false, // prevent duplicate images if user does not understand how to use gallery
]);
$gallery = $media->galleries()->create();
foreach ($images as $image) {
$image_path = Storage::disk('public')->putFile('trainings/gallery/' . $gallery->id . '/pictures', $image);
$avatar = \Image::make($image->getRealPath());
$avatar->fit(221, 146);
$avatar_path = 'trainings/gallery/' . $gallery->id . '/avatars/' . $image->hashName();
Storage::disk('public')->put($avatar_path, $avatar);
$gallery->images()->create([
'path_image' => $image_path,
'path_avatar' => $avatar_path,
]);
}
}
public function addVideo(String $url, String $name = null): void
{
$media = $this->training->media()->create([
'institute' => false, // prevent duplicate images if user does not understand how to use gallery
]);
$media->videos()->create([
'url' => $url,
'name' => $name,
]);
}
}
</code></pre>
<p>Any suggestions how I could improve the code?</p>
|
[] |
[
{
"body": "<p>There are some great things you're doing in this code.</p>\n<ol>\n<li>Not placing logic into your controller</li>\n<li>Using repositories to control your data</li>\n<li>Using requests to validate data in</li>\n</ol>\n<p>Some things that could be improved.</p>\n<ol>\n<li>Repositories are tightly coupled</li>\n<li><code>store</code> method on the controller is tightly coupled to a repository</li>\n<li>Lack of interfaces controlling repositories</li>\n</ol>\n<p>I'll step through all the areas that could be improved to add some context.</p>\n<p>When you explicitly create an instance of a class within in a method of another class, you are binding the instantiation of not just the required class instance but the specific class itself, this is always true when you call static methods on classes, as such I'd recommend that you don't use static methods at all.</p>\n<p>It's much more desirable in most cases to loosly couple class instances and Laravel provides an easy way to do this through its IoC implementation or <code>App</code> instance.</p>\n<p>The IoC doesn't explicitly require an interface <em>but</em> it is preferable to make it easier on you as a developer, it also allows you to achieve a better design overall by ensuring that some object oriented design principles are adhered to. The go to design I use is <a href=\"https://medium.com/successivetech/s-o-l-i-d-the-first-5-principles-of-object-oriented-design-with-php-b6d2742c90d7\" rel=\"nofollow noreferrer\">SOLID</a>. SOLID outlines 5 rules to keep your code consise and maintainable. In this case by using the IoC we are enforcing (<strong>L</strong>) Liskovs substitution principle, (<strong>I</strong>) Interface segragation, and (<strong>D</strong>) Dependency Inversion.</p>\n<p>An example.</p>\n<pre><code>// app\\Repositories\\TrainingRepositoryInterface\n\ninterface TrainingRepositoryInterface {\n // No longer a static function\n public function create(Request $request)\n}\n\n// app\\Repositories\\TrainingRepository\n\nclass TrainingRepository implements TrainingRepositoryInterface {\n public function create(Request $request) {\n //\n }\n}\n</code></pre>\n<p>With an interface we can bind it to an instance in a provider. We now have interface segregation.</p>\n<pre><code>// AppProvider.php (register function only)\n\npublic function register() {\n $this->app->bind(TrainingRepositoryInterface::class, TrainingRepository::class);\n}\n</code></pre>\n<p>We now have Liskovs substitution principle in place, we can use this to swap out <code>TrainingRepository</code> for another repository that has the same interface if we want to.</p>\n<p>In your controller we can complete this implementation by injecting the interface now it is registered.</p>\n<pre><code>// app\\Http\\Controllers\\TrainingsController\n\nclass TrainingsController extends Controller {\n protected $trainingRepository;\n \n public function constructor(TrainingRepositoryInterface $trainingRepo) {\n $this->trainingRepository = $trainingRepo;\n }\n\n public function store(Request $request) {\n $this->trainingRepository->create($request);\n return view('home.training.show')\n }\n}\n</code></pre>\n<p>Repeat the process with your other repositories:</p>\n<ol>\n<li>Create interfaces</li>\n<li>Bind interfaces to concrete classes in a provider</li>\n<li>Inject these repositories in the constructor of your training repository using the interfaces instead of manually instantiating them.</li>\n</ol>\n<p>You now have a de-coupled implementation with interface segregation, an inverted dependency model and all your instances are substitutable by switching out the instances in the IoC.</p>\n<p>I hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T09:02:18.853",
"Id": "243708",
"ParentId": "243069",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T17:30:14.943",
"Id": "243069",
"Score": "2",
"Tags": [
"php",
"laravel",
"controller"
],
"Title": "Controller in Laravel with parsing, creation and relationships"
}
|
243069
|
<p>I develop an in-house Java framework. I provide an interface so that my end users can provide their own custom implementation (i.e. plugin/SPI).</p>
<pre><code>public interface SomePlugin {
SomeResponse doSomething(SomeRequest request);
}
</code></pre>
<p>There are a number of small configurations to be made, some required and some optional. For example: plugin name, response formatter.</p>
<h3>My initial interface looked like this (V1):</h3>
<pre><code>public interface SomePlugin { // V1
String getName();
default SomeFormatter getResponseFormatter() { return new DefaultFormatter(); }
SomeResponse doSomething(SomeRequest request);
}
</code></pre>
<p>Over time I learned this is not easily extensible, without breaking existing user implementations or abusing the <code>default</code> keyword. Reasons:</p>
<ul>
<li>What if I want to receive another config value, e.g. plugin description?</li>
<li>What if I need to provide an alternative way to receive response formatting?</li>
</ul>
<h2>V2</h2>
<p>Now, <a href="https://blog.jooq.org/2015/05/21/do-not-make-this-mistake-when-developing-an-spi/" rel="nofollow noreferrer">this blog post</a> suggests that I may use "argument objects" to better achieve this.</p>
<blockquote>
<p>It is generally a bad idea to have non-void methods in SPIs as you will never be able to change the return type of a method again. Ideally, you should have argument types that accept “outcomes”.</p>
</blockquote>
<pre><code>public interface SomePlugin { // V2
void configure(SomeConfigurator config);
SomeResponse doSomething(SomeRequest request);
}
public interface SomeConfigurator {
void setName(String name);
void setDescription(String description);
void useFormat(SomeFormatter formatter);
void useFormat(SomeParser parser, SomeOutputBuilder builder);
}
</code></pre>
<pre><code>public class MyPlugin { // Usage example
void configure(SomeConfigurator config) {
config.setName("Test plugin");
config.useFormat(new MyFormatter());
}
...
}
</code></pre>
<p>This nicely solves the extension/evolution problem that my initial design (V1) had.</p>
<ul>
<li>Deprecation and addition are easier.</li>
<li>I can now receive multiple objects at once, i.e. parser and builder, without creating a wrapper object.</li>
<li>I can overload some methods because what was a return type is now a parameter.</li>
</ul>
<p>I lose the required-ness of mandatory configs, i.e. users may forget to provide name and it will still compile. But I think this is an acceptable trade-off for maintainability, with help of Javadoc and runtime checks.</p>
<h2>V3</h2>
<p>One concern on the concept of "argument objects" with void return type is that it is a foreign idea. When I showed this prototype to my end users, they didn't grasp how to use it unless an example was provided. This leads me to consider:</p>
<pre><code>public interface SomePlugin { // V3
SomeConfig getConfig();
SomeResponse doSomething(SomeRequest request);
}
public final class SomeConfig {
private String name;
private String description = "";
private SomeFormatter formatter = new DefaultFormatter();
private SomeParser parser;
private SomeOutputBuilder builder;
... getters and setters ...
}
</code></pre>
<pre><code>public class MyPlugin { // Usage example
SomeConfig getConfig() {
SomeConfig config = new SomeConfig();
config.setName("Test plugin");
config.useFormat(new MyFormatter());
return config;
}
...
}
</code></pre>
<p>Now, this feels more like a "traditional" Java and should be more intuitive to my end users. I still get the benefits of V2. It's unlikely that I'd have to worry about deprecating or replacing <code>getConfig()</code> itself.</p>
<p>One small con: <code>SomeConfig</code> is now more <em>verbose</em> with all getters and setters, compared to <code>SomeConfigurator</code> in V2 which looked like a clean "header file". Despite this, I feel like V3 is the way to go.</p>
<p>Does my reasoning make sense? Are there any reasons to favor V2 over V3, or do you have other approaches to suggest? Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T00:21:15.010",
"Id": "477066",
"Score": "1",
"body": "Welcome to code review where we review code that is working as expected and suggest improvements to that code. We only occasionally discuss architecture. This question might be better asked on [Software Engineering](https://softwareengineering.stackexchange.com/) but check their [guidelines](https://softwareengineering.stackexchange.com/help/asking) first."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T17:41:27.827",
"Id": "243070",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"api"
],
"Title": "Designing a public facing Java interface for future extensibility (API evolution)"
}
|
243070
|
<p>I have tried the code for finding the class of the IP address the user inputs, and printing the network and the host bits in the IP address. Could someone please review this approach and provide suggestions. Thanks:). </p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<error.h>
#include<errno.h>
#define size 32
int bin[size];
void print(int class, int nb, int hb);
void convert_to_binary(uint32_t decimal);
void print(int class, int nb, int hb)
{
int i = 0;
printf("The Network bits are:\n");
for(i = class; i < (nb + class); i++) {
printf("%d ", bin[i]);
}
printf("\n");
printf("The host bits are:\n");
for(i = (class + nb); i < size; i++) {
printf("%d ", bin[i]);
}
}
void convert_to_binary(uint32_t decimal)
{
int index = 0;
int temp = 0;
int i = 0;
while (decimal > 0) {
temp = decimal % 2;
bin[index++] = temp;
decimal = decimal / 2;
}
for (i = 0; i < size / 2; i++) {
temp = bin[i];
bin[i] = bin[size - i - 1];
bin[size - i - 1] = temp;
}
}
int main(int argc, char **argv)
{
struct in_addr addr;
uint32_t result;
char *IP;
int ret = 0;
int value = 0;
if (argc != 2)
error(1, errno, "Too many or few arguments\n");
IP = argv[1];
ret = inet_aton(IP, &addr);
if (ret == 0)
error(1, errno, "Invalid IP- address provided\n");
printf("The address in the structure is network byte order:(Big- Endian) %X %d\n", addr, addr);
result = ntohl(addr.s_addr);
convert_to_binary(result);
if (bin[0] == 0) {
printf("Class - A\n");
print(1, 7, 24);
} else if (bin[0] == 1 && bin[1] == 0) {
printf("Class - B\n");
print(2, 14, 24);
} else if(bin[0] == 1 && bin[1] == 1 && bin[2] == 0) {
printf("Class - C\n");
print(3, 21, 8);
} else {
printf("It does not belong to any of the class\n");
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T10:42:30.550",
"Id": "477271",
"Score": "0",
"body": "There is actually a minor bug. for class B, `print(2, 14, 24);` should be `print(2, 14, 16);` Since the third parameter is ignored, this bug doesn't matter."
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The parameter <code>hb</code> in the <code>print()</code> function and <code>value</code> in <code>main()</code> are unused variables and should be omitted from the program.</p>\n\n<h2>Fix your formatting</h2>\n\n<p>There are inconsistent spaces at the beginning of lines and inconsistent indentation. Being consistent helps others read and understand your code.</p>\n\n<h2>Use only required <code>#include</code>s</h2>\n\n<p>The code has a number of <code>#include</code>s that are not needed. In this code, for instance, nothing from <code><string.h></code> is used, so that header can and should be omitted. Only include files that are actually needed. This makes the code easier to understand and maintain and also may slightly speed up compiling.</p>\n\n<h2>Understand what standards <em>don't</em> guarantee</h2>\n\n<p>A knowledgeable reader of this code (and possibly the compiler) is likely to be puzzled by this line of code:</p>\n\n<pre><code>printf(\"The address in the structure is network byte order:(Big- Endian) %X %d\\n\", addr, addr);\n</code></pre>\n\n<p>The reason is that \"%X\" expects an <code>unsigned int</code> and \"%d\" expects an <code>int</code> but what you're passing is <code>struct in_addr</code>. The <code>man</code> page tells us that the relevant defintion for that is as follows:</p>\n\n<pre><code>typedef uint32_t in_addr_t;\n\nstruct in_addr {\n in_addr_t s_addr;\n};\n</code></pre>\n\n<p>This means that on machines where <code>int</code> is not the same size as <code>uint32_t</code>, there is a potential for trouble. Specifically, if the code is compiled for a machine with a 16-bit <code>int</code>, this won't give the results you intend. Better would be to have the compiler check to make sure that this doesn't happen. One way to do this is to add these lines to the program:</p>\n\n<pre><code>#include <limits.h>\n#if UINT_MAX == 65535\n#error \"This program requires at least a 32-bit unigned int.\"\n#endif\n</code></pre>\n\n<p>Note that <code>sizeof</code> can't be used for the preprocessor, which is why we use the definition of <code>UINT_MAX</code>. This isn't foolproof, since there are <a href=\"http://www.quadibloc.com/comp/cp0303.htm\" rel=\"nofollow noreferrer\">real machines using 24-bit words</a>, but catches the more common case of a 16-bit. To be completely sure, we can't really use the preprocessor. We could do this:</p>\n\n<pre><code>if (sizeof(int) < 4) {\n printf(\"This program requires at least 32-bit int, but yours has a %ld-bit int\\n\", sizeof(int) * 8);\n return 1;\n}\n</code></pre>\n\n<p>Then instead of passing <code>addr</code> to your <code>printf</code>, pass <code>addr.s_addr</code> instead.</p>\n\n<h2>Try to write portable code</h2>\n\n<p>Things that are guaranteed by the C standard are absolutely portable to conforming compilers on all platforms. Things that are specified by POSIX standards are portable to the subset of machines that conform to POSIX. Your life will be easier if you aim for those. Things that are compiler extensions, such as <code>error</code> are not necessarily portable to other machines. For that reason, I'd suggest that instead of using <code>error</code> in this program (which is a GNU extension), you could use the form shown above and use <code>printf</code> and <code>return</code>. It's also worth noting that <code>inet_aton</code> is not actually in the POSIX standard, but is widely used (and much better than the poorly defined but standard <code>inet_addr</code>). However, it may have some surprising attributes. For example, it will interpret a single number as an IP address. If we give the argument <code>3232236027</code> it will interpret this as the address <code>192.168.1.251</code>. If that's what you want, that's fine. If not, you might consider instead using <code>inet_pton</code> (which is POSIX):</p>\n\n<pre><code>ret = inet_pton(AF_INET, IP, &addr);\n</code></pre>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>The code declares and uses a global variable, <code>bin</code>. Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult. It also makes the code harder to reuse. For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them. That way the linkage is explicit and may be altered more easily if needed. In this case, you could define <code>bin</code> within <code>main</code> like this:</p>\n\n<pre><code>int bin[32];\n</code></pre>\n\n<p>And then call <code>print</code> like this:</p>\n\n<pre><code>printf(\"Class - A\\n\");\nprint(1, 7, bin, 32);\n</code></pre>\n\n<h2>Eliminate complexity where practical</h2>\n\n<p>The <code>convert_to_binary()</code> function is rather complex internally. I'd recommend simplifying it or eliminating it entirely. Here's one way to simplify it:</p>\n\n<pre><code>void convert_to_binary(uint32_t decimal, int *bin, size_t size)\n{\n bin += size - 1;\n for ( ; size; --size) {\n *bin-- = decimal & 1u;\n decimal >>= 1;\n }\n}\n</code></pre>\n\n<h2>Rethink function interfaces</h2>\n\n<p>The essential piece of work done in the program is to identify the address class of the passed IPv4 address. I'd put that into a function like this:</p>\n\n<pre><code>char address_class(uint32_t addr) {\n const struct class_mask {\n uint32_t mask;\n uint32_t classbits;\n char designator;\n } class_mask[3] = {\n { 0x80000000u, 0x00000000u, 'A' },\n { 0xc0000000u, 0x80000000u, 'B' },\n { 0xe0000000u, 0xc0000000u, 'C' },\n };\n for (unsigned i=0; i < 3; ++i) {\n if ((addr & class_mask[i].mask) == class_mask[i].classbits) {\n return class_mask[i].designator;\n }\n }\n return '?';\n}\n</code></pre>\n\n<p>With a small change, we could actually turn this into the print function. If we do so, the entire program then looks like this:</p>\n\n<pre><code>#include <stdio.h>\n#include <arpa/inet.h>\n\nchar print_classification(uint32_t addr) {\n const struct class_mask {\n uint32_t mask;\n uint32_t classbits;\n uint32_t netmask;\n uint32_t hostmask;\n char designator;\n } class_mask[3] = {\n { 0x80000000u, 0x00000000u, 0x40000000u, 0x00800000u, 'A' },\n { 0xc0000000u, 0x80000000u, 0x20000000u, 0x00008000u, 'B' },\n { 0xe0000000u, 0xc0000000u, 0x10000000u, 0x00000080u, 'C' },\n };\n for (unsigned i=0; i < 3; ++i) {\n if ((addr & class_mask[i].mask) == class_mask[i].classbits) {\n printf(\"class = %c\\nThe network bits are:\\n\", class_mask[i].designator);\n for (uint32_t mask = class_mask[i].netmask; mask; mask >>= 1) {\n if (mask == class_mask[i].hostmask) {\n printf(\"\\nThe host bits are:\\n\");\n }\n printf(\"%c \", addr & mask ? '1' : '0');\n }\n printf(\"\\n\");\n return class_mask[i].designator;\n }\n }\n printf(\"Unknown address class\\n\");\n return '?';\n}\n\nint main(int argc, char **argv)\n{\n struct in_addr addr;\n\n if (sizeof(int) < 4) {\n printf(\"This program requires at least 32-bit int, but yours has a %ld-bit int\\n\", sizeof(int) * 8);\n return 1;\n }\n if (argc != 2) {\n printf(\"Usage: %s ipv4addr\\nwhere ipv4addr is of the form xxx.xxx.xxx.xxx\\n\", argv[0]);\n return 1;\n }\n if (inet_pton(AF_INET, argv[1], &addr) == 0) {\n printf(\"Error: couldn't interpret %s as an IPv4 address\\n\", argv[1]);\n } \n print_classification(ntohl(addr.s_addr));\n}\n</code></pre>\n\n<h2>Rethink the purpose of the program</h2>\n\n<p>Perhaps this was just a programming exercise, but it's probably worth pointing out that the use of IPv4 address classes has been obsolete since the introduction of <a href=\"https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing\" rel=\"nofollow noreferrer\">CIDR</a> in 1993.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T10:29:44.520",
"Id": "477270",
"Score": "0",
"body": "You seem to think class B is /12 and class C is /16. This is wrong. Class B is /16 and class C is /24. OP had this right. The sizes you are using are the size of the private use blocks in the classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T13:36:28.697",
"Id": "477281",
"Score": "0",
"body": "@DavidG. You're right. Thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T15:45:35.510",
"Id": "243150",
"ParentId": "243072",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243150",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T18:12:56.053",
"Id": "243072",
"Score": "3",
"Tags": [
"c",
"linux",
"socket",
"unix"
],
"Title": "Finding the class to which the IP address belongs"
}
|
243072
|
<p><strong>Background</strong></p>
<p>A few months ago, I asked <a href="https://codereview.stackexchange.com/questions/234731/sudoku-solver-with-gui-in-java">this</a> and <a href="https://codereview.stackexchange.com/questions/234801/sudoku-solver-follow-up">this</a> question on my implementation of a Sudoku-Solver. I now tried to further improve this little project.</p>
<p><strong>Changes</strong></p>
<ul>
<li>Minor GUI-changes</li>
<li>Input validation</li>
<li>"Reset"-button</li>
<li>Check if solution is unique (This <a href="https://stackoverflow.com/questions/62063330/sudoku-backtracking-with-solution-counter/62068452#62068452">question</a> on stackoverflow helped)</li>
<li>Naming</li>
<li>Structuring Code with Classes</li>
<li>Added tests</li>
</ul>
<p><strong>Code</strong></p>
<p><code>Control.java</code> (Starting the application)</p>
<pre><code>import javax.swing.SwingUtilities;
public class Control {
public static void main(String[] args) {
SwingUtilities.invokeLater(Gui::new);
}
}
</code></pre>
<p><code>Gui.java</code> (responsible for the UI)</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.text.NumberFormatter;
public class Gui {
private final int GUI_SIZE = 700;
private final int GRID_SIZE = 9;
private JTextField[][] sudokuGrid;
private JButton buttonOK;
public Gui() {
JFrame frame = new JFrame("Sudoku-Solver");
frame.setSize(GUI_SIZE, GUI_SIZE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JPanel gridPanel = new JPanel(new GridLayout(GRID_SIZE, GRID_SIZE));
/*
* The following lines ensure that the user can only enter numbers.
*/
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
/*
* 81 text fields are now created here, which are used by the user to enter the Sudoku, which he
* wants to solve.
*/
sudokuGrid = new JFormattedTextField[GRID_SIZE][GRID_SIZE];
Font font = new Font("Verdana", Font.BOLD, 40);
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
sudokuGrid[i][j] = new JFormattedTextField(formatter);
/*
* "0" = empty field
*/
sudokuGrid[i][j].setText("0");
sudokuGrid[i][j].setHorizontalAlignment(JTextField.CENTER);
sudokuGrid[i][j].setEditable(true);
sudokuGrid[i][j].setFont(font);
gridPanel.add(sudokuGrid[i][j]);
}
}
JPanel buttonPanel = new JPanel();
/*
* When the user presses the OK-button, the program will start to solve the Sudoku.
*/
buttonOK = new JButton("OK");
buttonOK.addActionListener(e -> ok());
/*
* Reset-button makes it possible to solve another Sudoku without reopening the whole program.
*/
JButton buttonReset = new JButton("Reset");
buttonReset.addActionListener(e -> reset());
buttonPanel.add(buttonOK);
buttonPanel.add(buttonReset);
panel.add(gridPanel, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.PAGE_END);
frame.add(panel);
frame.setVisible(true);
}
private void ok() {
SudokuSolver solver = new SudokuSolver();
/*
* The program now writes the enter numbers in an array.
*/
int board[][] = new int[GRID_SIZE][GRID_SIZE];
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
String s = sudokuGrid[i][j].getText();
board[i][j] = Integer.valueOf(s);
}
}
/*
* Are there only numbers between 0 and 9?
*/
if (solver.inputValidation(board)) {
int solve = solver.solver(board, 0);
if(solve == 0) {
JOptionPane.showMessageDialog(null, "Not solvable.");
}
if (solve >= 1) {
/*
* Output of solved Sudoku.
*/
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
sudokuGrid[i][j].setText("" + solver.getSolution(i, j));
sudokuGrid[i][j].setEditable(false);
}
}
}
if(solve > 1) {
JOptionPane.showMessageDialog(null, "Multiple solutions possible.");
}
buttonOK.setEnabled(false);
} else {
JOptionPane.showMessageDialog(null, "Invalid input.");
}
}
private void reset() {
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
sudokuGrid[i][j].setText("0");
sudokuGrid[i][j].setEditable(true);
}
}
buttonOK.setEnabled(true);
}
}
</code></pre>
<p><code>SudokuSolver.java</code> (responsible for the logic)</p>
<pre><code>public class SudokuSolver {
private final int GRID_SIZE = 9;
private final int EMPTY = 0;
private int[][] solution = new int[GRID_SIZE][GRID_SIZE];
public int getSolution(int i, int j) {
return solution[i][j];
}
//Are there only numbers between 0 and 9 in the Sudoku?
public boolean inputValidation(int[][] board) {
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
if (board[i][j] < EMPTY || board[i][j] > GRID_SIZE) {
return false;
}
for (int k = 0; k < GRID_SIZE; k++) {
// More than one appearance in one row
if (k != j && board[i][k] == board[i][j] && board[i][j] != EMPTY) {
return false;
}
// More than one appearance in one column
if (k != i && board[k][j] == board[i][j] && board[i][j] != EMPTY) {
return false;
}
}
// More than one appearance in one 3x3-box
int row = i - i % 3;
int column = j - j % 3;
for (int m = row; m < row + 3; m++) {
for (int n = column; n < column + 3; n++) {
if (board[i][j] == board[m][n] && (m != i || n != j) && board[i][j] != EMPTY) {
return false;
}
}
}
}
}
return true;
}
// Backtracking-Algorithm
public int solver(int[][] board, int count) { // Starts with count = 0
for (int i = 0; i < GRID_SIZE; i++) { //GRID_SIZE = 9
for (int j = 0; j < GRID_SIZE; j++) {
/*
* Only empty fields will be changed
*/
if (board[i][j] == EMPTY) { //EMPTY = 0
/*
* Try all numbers between 1 and 9
*/
for (int n = 1; n <= GRID_SIZE && count < 2; n++) {
/*
* Is number n safe?
*/
if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
board[i][j] = n;
int cache = solver(board, count);
if (cache > count) {
count = cache;
for (int k = 0; k < board.length; k++) {
for (int l = 0; l < board.length; l++) {
if (board[k][l] != EMPTY) {
solution[k][l] = board[k][l];
}
}
}
board[i][j] = EMPTY;
} else {
board[i][j] = EMPTY;
}
}
}
return count;
}
}
}
return count + 1;
}
// Is number n already in the row?
private boolean checkRow(int[][] board, int row, int n) {
for (int i = 0; i < GRID_SIZE; i++) {
if (board[row][i] == n) {
return false;
}
}
return true;
}
// Is number n already in the column?
private boolean checkColumn(int[][] board, int column, int n) {
for (int i = 0; i < GRID_SIZE; i++) {
if (board[i][column] == n) {
return false;
}
}
return true;
}
// Is number n already in the 3x3-box?
private boolean checkBox(int[][] board, int row, int column, int n) {
row = row - row % 3;
column = column - column % 3;
for (int i = row; i < row + 3; i++) {
for (int j = column; j < column + 3; j++) {
if (board[i][j] == n) {
return false;
}
}
}
return true;
}
}
</code></pre>
<p><strong>Tests</strong></p>
<p>I've used the sudokus presented <a href="http://www.aisudoku.com/index_en.html" rel="nofollow noreferrer">here</a> and <a href="https://sandwalk.blogspot.com/2007/06/i-knew-it-there-can-be-more-than-one.html" rel="nofollow noreferrer">here</a> to test my application:</p>
<pre><code>import org.junit.Test;
import org.junit.Assert;
public class Tests {
//Test: Uniquely solveable sudoku
@Test
public void testOne() {
SudokuSolver solver = new SudokuSolver();
int[][] sudoku = {
{8, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 6, 0, 0, 0, 0, 0},
{0, 7, 0, 0, 9, 0, 2, 0, 0},
{0, 5, 0, 0, 0, 7, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 7, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 3, 0},
{0, 0, 1, 0, 0, 0, 0, 6, 8},
{0, 0, 8, 5, 0, 0, 0, 1, 0},
{0, 9, 0, 0, 0, 0, 4, 0, 0}};
int[][] solution = {
{8, 1, 2, 7, 5, 3, 6, 4, 9},
{9, 4, 3, 6, 8, 2, 1, 7, 5},
{6, 7, 5, 4, 9, 1, 2, 8, 3},
{1, 5, 4, 2, 3, 7, 8, 9, 6},
{3, 6, 9, 8, 4, 5, 7, 2, 1},
{2, 8, 7, 1, 6, 9, 5, 3, 4},
{5, 2, 1, 9, 7, 4, 3, 6, 8},
{4, 3, 8, 5, 2, 6, 9, 1, 7},
{7, 9, 6, 3, 1, 8, 4, 5, 2}};
int result = solver.solver(sudoku, 0);
Assert.assertEquals(1, result);
for (int i = 0; i < solution.length; i++) {
for (int j = 0; j < solution.length; j++) {
Assert.assertEquals(solution[i][j], solver.getSolution(i, j));
}
}
}
//Test: Not uniquely solveable sudoku
@Test
public void testTwo() {
SudokuSolver solver = new SudokuSolver();
int[][] sudoku = {
{9, 0, 6, 0, 7, 0, 4, 0, 3},
{0, 0, 0, 4, 0, 0, 2, 0, 0},
{0, 7, 0, 0, 2, 3, 0, 1, 0},
{5, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 4, 0, 2, 0, 8, 0, 6, 0},
{0, 0, 3, 0, 0, 0, 0, 0, 5},
{0, 3, 0, 7, 0, 0, 0, 5, 0},
{0, 0, 7, 0, 0, 5, 0, 0, 0},
{4, 0, 5, 0, 1, 0, 7, 0, 8},};
int[][] solution = {
{9, 2, 6, 5, 7, 1, 4, 8, 3,},
{3, 5, 1, 4, 8, 6, 2, 7, 9,},
{8, 7, 4, 9, 2, 3, 5, 1, 6,},
{5, 8, 2, 3, 6, 7, 1, 9, 4,},
{1, 4, 9, 2, 5, 8, 3, 6, 7,},
{7, 6, 3, 1, 9, 4, 8, 2, 5,},
{2, 3, 8, 7, 4, 9, 6, 5, 1,},
{6, 1, 7, 8, 3, 5, 9, 4, 2,},
{4, 9, 5, 6, 1, 2, 7, 3, 8,}};
int result = solver.solver(sudoku, 0);
Assert.assertEquals(2, result);
for (int i = 0; i < solution.length; i++) {
for (int j = 0; j < solution.length; j++) {
Assert.assertEquals(solution[i][j], solver.getSolution(i, j));
}
}
}
}
</code></pre>
<p>Github-Repository : <a href="https://github.com/vulpini99/Sudoku-Solver" rel="nofollow noreferrer">https://github.com/vulpini99/Sudoku-Solver</a></p>
<p><strong>Question(s)</strong></p>
<ul>
<li>What do you think about the codestructure?</li>
<li>What is your opinion on the solving-algorithm?</li>
<li>How can the code be improved in general?</li>
</ul>
<hr>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T08:07:13.110",
"Id": "477422",
"Score": "1",
"body": "Please do not update the code in your question after receiving feedback in answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T08:08:37.607",
"Id": "477423",
"Score": "0",
"body": "I only updated code on which I didn't receive feedback, but I will not do that in the future. Thanks for the hint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T08:19:24.777",
"Id": "477425",
"Score": "0",
"body": "Thanks for changing it back for me."
}
] |
[
{
"body": "<blockquote>\n <p>What is your opinion on the solving-algorithm?</p>\n</blockquote>\n\n<p>Let's do a performance test, here's my test case:</p>\n\n<pre><code>int[][] sudoku = {\n {0,0,0,0,0,0,0,0,0},\n {0,0,0,0,0,3,0,8,5},\n {0,0,1,0,2,0,0,0,0},\n {0,0,0,5,0,7,0,0,0},\n {0,0,4,0,0,0,1,0,0},\n {0,9,0,0,0,0,0,0,0},\n {5,0,0,0,0,0,0,7,3},\n {0,0,2,0,1,0,0,0,0},\n {0,0,0,0,4,0,0,0,9}};\n</code></pre>\n\n<p>On my PC, it took about 10 seconds. As Sudoku solving algorithms go, that's not horrible, but it's also not great. I can wait 10 seconds, but 10 seconds is a lot for a computer, it would be more reasonable to take some miliseconds (or less).</p>\n\n<p>An important technique in constraint solving is propagating the consequences of choosing a particular value for a variable (the cells of a sudoku are variables in Constraint Satisfaction jargon). Propagating the consequences of filling in a cell means filling in other cells that have become \"fillable\". Doing this prevents the main recursive solver from trying options that are not consistent with the board, but <code>checkRow/checkColumn/checkBlock</code> still think are OK because the cell that would block that value is still empty. Roughly speaking, the more propagation, the better (up to a point).</p>\n\n<p>The easiest propagation strategy is filling in <a href=\"http://hodoku.sourceforge.net/en/tech_singles.php#n1\" rel=\"nofollow noreferrer\">Naked Singles</a>. This can be done by trying all values for all empty cells, but a more efficient technique is collecting a set (or bitmask) of the possible values for all cells at once, and then going through them and promoting the singleton sets to filled-in cells. This is iterated until no more Naked Singles can be found. I benchmarked some code that implements that, that brings the test case that I'm using to around 2.2 seconds.</p>\n\n<p>There are more propagation strategies for Sudoku, for example <a href=\"http://hodoku.sourceforge.net/en/tech_singles.php#h1\" rel=\"nofollow noreferrer\">Hidden Singles</a>. Again they could be found by brute force, but an alternative strategy is re-using the sets/masks from filling in the Naked Singles and using them to find values that are in exactly one of the cells in a row/column/block. There are various ways to do it. I benchmarked this as well, and by analysing the rows and columns (but not blocks) for Hidden Singles, the time improved to less than 0.3 miliseconds.</p>\n\n<p>I can make that code available if you'd like, but perhaps you'd like to try your own approached to these techniques first.</p>\n\n<p>More advanced propagation strategies are possible. Ultimately Sudoku is a game of intersecting AllDifferent constraints, for which there are special propagation techniques based on graph algorithms. There is a video about that <a href=\"https://www.coursera.org/lecture/solving-algorithms-discrete-optimization/3-2-3-inside-alldifferent-asyks\" rel=\"nofollow noreferrer\">on Coursera</a>.</p>\n\n<p>An other possible technique is filling the board in a different order: by order of most-constrained variable (aka cell) first (a common technique in Constraint Satisfaction). The same bitmasks/sets can be used for that as are used for finding Naked Singles. For this benchmark, this technique only helped when not filling Hidden Singles, improving the time to around 80 miliseconds.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T20:36:14.730",
"Id": "243190",
"ParentId": "243074",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243190",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T18:31:36.503",
"Id": "243074",
"Score": "1",
"Tags": [
"java",
"swing",
"gui",
"sudoku",
"backtracking"
],
"Title": "Sudoku-Solver with GUI - follow-up"
}
|
243074
|
<p>I have the default code snippet that comes with the nvidia nsight eclipse V10.2, but I've modified it to do some profiling:</p>
<pre><code>/*
============================================================================
Name : Project1.cu
Author : []
Version :
Copyright : If you find this, by pure chance, feel free to use the code!
Description : CUDA compute reciprocals
============================================================================
*/
#include <iostream>
#include <numeric>
#include <stdlib.h>
#include <chrono>
static void CheckCudaErrorAux (const char *, unsigned, const char *, cudaError_t);
#define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__,__LINE__, #value, value)
/**
* CUDA kernel that computes reciprocal values for a given vector
*/
__global__ void reciprocalKernel(float *data, unsigned vectorSize) {
unsigned idx = blockIdx.x*blockDim.x+threadIdx.x;
if (idx < vectorSize)
{
data[idx] = 1.0/data[idx];
}
}
/**
* Host function that copies the data and launches the work on GPU
*/
void gpuReciprocal(float* gpuData,unsigned size)
{
//CUDA_CHECK_RETURN(
//);
//CUDA_CHECK_RETURN(//);
static const int BLOCK_SIZE = 512;
const int blockCount = (size+BLOCK_SIZE-1)/BLOCK_SIZE;
reciprocalKernel<<<blockCount, BLOCK_SIZE>>> (gpuData, size);
//CUDA_CHECK_RETURN(
//);
//CUDA_CHECK_RETURN(
//);
}
float* copyMemoryFromDevice(float*& gpuData, unsigned size){
float *rc = new float[size];
cudaMemcpy(rc, gpuData, sizeof(float)*size, cudaMemcpyDeviceToHost);
return rc;
}
void copyMemoryToDevice(float*& gpuData, float* data, unsigned size){
cudaMemcpy(gpuData, data, sizeof(float)*size, cudaMemcpyHostToDevice);
}
void allocateGPUMemory(float*& gpuData, unsigned size){
cudaMalloc((void **)&gpuData, sizeof(float)*size);
}
void unAllocateGPUMemory(float*& gpuData){
cudaFree(gpuData);
}
float* cpuReciprocal(float*& data, unsigned size)
{
float *rc = new float[size];
for (unsigned cnt = 0; cnt < size; ++cnt) rc[cnt] = 1.0/data[cnt];
return rc;
}
void initialize(float *data, unsigned size)
{
for (unsigned i = 0; i < size; ++i)
data[i] = .1*(i+1);
}
uint64_t getCurrentTimeMs()
{
return std::chrono::system_clock::now().time_since_epoch().count();
}
std::string getCommaFormattedNumber( uint64_t number ){
std::string toreturn = std::to_string(number);
int placeholder = 3;
while(placeholder < toreturn.size()){
toreturn.insert(toreturn.size()-placeholder, ",");
placeholder += 4;
}
return toreturn;
}
int main(void)
{
uint64_t startCPU,endCPU,CPUTime
,startGPU,endGPU,GPUTime
,startAcum,endAcum,ACUMTime
,startMalloc,endMalloc,mallocTime
,startCopy,endCopy,copyTime
,startCompute,endCompute,computeTime
,percentDiff;
std::string CPUTimeFormatted,GPUTimeFormatted,ACUMTimeFormatted,mallocTimeFormatted,copyTimeFormatted,computeTimeFormatted,percentDiffFormatted;
static const int WORK_SIZE = 292565536;
float* data = new float[WORK_SIZE];
initialize (data, WORK_SIZE);
cudaSetDevice(0);
//CPU computation phase
std::cout<<"Started CPU"<<std::endl;
startCPU = getCurrentTimeMs();
float *recCpu = cpuReciprocal(data, WORK_SIZE);
endCPU = getCurrentTimeMs();
//GPU computation phase
std::cout<<"Started GPU"<<std::endl;
startGPU = getCurrentTimeMs();
startMalloc = getCurrentTimeMs();
float* gpuData;
allocateGPUMemory(gpuData, WORK_SIZE);
endMalloc = getCurrentTimeMs();
startCopy = getCurrentTimeMs();
copyMemoryToDevice(gpuData, *&data, WORK_SIZE);
endCopy = getCurrentTimeMs();
startCompute = getCurrentTimeMs();
gpuReciprocal(gpuData, WORK_SIZE);
endCompute = getCurrentTimeMs();
startCopy += getCurrentTimeMs();
float *recGpu = copyMemoryFromDevice(gpuData, WORK_SIZE);
endCopy += getCurrentTimeMs();
startMalloc += getCurrentTimeMs();
unAllocateGPUMemory(gpuData);
endMalloc += getCurrentTimeMs();
endGPU = getCurrentTimeMs();
//Accumulation phase
std::cout<<"Started acum"<<std::endl;
startAcum = getCurrentTimeMs();
float cpuSum = std::accumulate (recCpu, recCpu+WORK_SIZE, 0.0);
float gpuSum = std::accumulate (recGpu, recGpu+WORK_SIZE, 0.0);
endAcum = getCurrentTimeMs();
//Results calculation
CPUTime = (endCPU - startCPU)/1000;
GPUTime = (endGPU - startGPU)/1000;
ACUMTime = (endAcum - startAcum)/1000;
mallocTime = (endMalloc - startMalloc)/1000;
copyTime = (endCopy - startCopy)/1000;
computeTime = (endCompute - startCompute)/1000;
percentDiff = (CPUTime*100)/GPUTime;
CPUTimeFormatted = getCommaFormattedNumber(CPUTime);
GPUTimeFormatted = getCommaFormattedNumber(GPUTime);
ACUMTimeFormatted = getCommaFormattedNumber(ACUMTime);
mallocTimeFormatted = getCommaFormattedNumber(mallocTime);
copyTimeFormatted = getCommaFormattedNumber(copyTime);
computeTimeFormatted = getCommaFormattedNumber(computeTime);
percentDiffFormatted = getCommaFormattedNumber(percentDiff);
/* Verify the results */
std::cout<<"gpuSum = "<<gpuSum<< " cpuSum = " <<cpuSum<<std::endl;
std::cout<<"CPU: "<<CPUTimeFormatted<<"us "
<<std::endl<<"GPU: "<<GPUTimeFormatted<<"us "
<<std::endl<<" MALLOC: "<<mallocTimeFormatted<<"us "
<<std::endl<<" COPY: "<<copyTimeFormatted<<"us "
<<std::endl<<" COMPUTE: "<<computeTimeFormatted<<"us "
<<std::endl<<"ACUM: "<<ACUMTimeFormatted<<"us"
<<std::endl;
std::cout<<"The GPU is "<<percentDiffFormatted<<"% faster than the CPU.";
/* Free memory */
delete[] data;
delete[] recCpu;
delete[] recGpu;
return 0;
}
/**
* Check the return value of the CUDA runtime API call and exit
* the application if the call has failed.
*/
static void CheckCudaErrorAux (const char *file, unsigned line, const char *statement, cudaError_t err)
{
if (err == cudaSuccess)
return;
std::cerr << statement<<" returned " << cudaGetErrorString(err) << "("<<err<< ") at "<<file<<":"<<line << std::endl;
exit (1);
}
</code></pre>
<p>And the code produces the following results:</p>
<blockquote>
<p>CPU: 1,069,778us<br>
GPU: 562,895us<br>
MALLOC: 43,535us<br>
COPY: 519,350us<br>
COMPUTE: 7us<br>
ACUM: 1,630,715us<br>
The GPU is 190% faster than the CPU.</p>
</blockquote>
<p>As one can see, the copying from RAM to GPU and back costs the most time, and the malloc / demalloc also takes a large amount of time. This seems very strange, as the GPU I'm using is on a 8X PCIE lane. I also have a NVidia Jetson Xavier, and when I run this code on that system, I get the following output:</p>
<blockquote>
<p>CPU: 774,552us<br>
GPU: 446,498us<br>
MALLOC: 103,619us<br>
COPY: 342,860us<br>
COMPUTE: 14us<br>
ACUM: 967,493us<br>
The GPU is 173% faster than the CPU.logout </p>
</blockquote>
<p>As one can see, the compute call is by far the least intensive call, and the malloc/copy calls are almost ludicrous in terms of real time operation. </p>
<p>How can I optimize this snippet to have faster copy and or malloc times?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T21:15:25.517",
"Id": "477055",
"Score": "1",
"body": "The profiling code is wrong, for a common reason: no synchronization (meaning that what was measured is kernel *launch* time, not kernel *execution* time). That might invalidate this whole question.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T21:28:35.480",
"Id": "477057",
"Score": "0",
"body": "@harold even if the execution is not synchronized, the malloc and demalloc times are still valid and are still large in comparison"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T00:14:53.560",
"Id": "477162",
"Score": "0",
"body": "Firstly, as harold says, you should use CUDA events for measuring performance: [How to Implement Performance Metrics in CUDA C/C++](https://devblogs.nvidia.com/how-implement-performance-metrics-cuda-cc/). Nonetheless, your observation is valid – the memory (de)allocation and transfer times are considerable compared to the computation time. The reason is that your computation is simply too trivial to take any substantial amount of time. You can improve CPU <-> GPU transfer speed using pinned memory; read https://devblogs.nvidia.com/how-optimize-data-transfers-cuda-cc/."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:13:02.083",
"Id": "243079",
"Score": "1",
"Tags": [
"performance",
"memory-optimization",
"cuda"
],
"Title": "How does one increase effeciency of the memory functions of CUDA code?"
}
|
243079
|
<p>What my code try to do here is to sort items trough 2 dictionaries. If they are similar or the same, I create a new list to append them.</p>
<p>The test file is relatively big, around 2000 data each dictionary.</p>
<p>My concern is that i need to maintain a linear time complexity trough out the code and i am not sure that my code is on a linear complexity.</p>
<p>I would like an opinion on the complexity of this code. Is it linear? If it is not is there any way to improve it?</p>
<pre><code>import pandas as pd
import string
import textdistance as td
import time
start_time = time.time()
amazon = pd.read_csv('amazon.csv')
google = pd.read_csv('google.csv')
title1 = amazon['title']
title2 = google['name']
id1 = amazon['idAmazon']
id2 = google['id']
out_amazon = {}
out_google = {}
list_a =[]
list_b =[]
list_c =[]
list_d =[]
list_e =[]
list_f =[]
list_g =[]
list_h =[]
list_i =[]
list_j =[]
list_k =[]
list_l =[]
list_m =[]
list_n =[]
list_o =[]
list_p =[]
list_q =[]
list_r =[]
list_s =[]
list_t =[]
list_u =[]
list_v =[]
list_w =[]
list_x =[]
list_y =[]
list_z =[]
list_unknown = []
duplicate_list = []
amazon_labeled = ([(name, 'Amazon') for name in title1])
google_labeled = ([(name, 'Google') for name in title2])
amazon_dict = dict(zip(amazon.idAmazon, amazon_labeled))
google_dict = dict(zip(google.id, google_labeled))
z = {**amazon_dict, **google_dict}
keys = sorted((z.values()))
i = 0
while i < (len(keys)) - 1:
if (keys[i][0][0]) == 'a':
list_a.append(keys[i])
elif (keys[i][0][0]) == 'b':
list_b.append(keys[i])
elif (keys[i][0][0]) == 'c':
list_c.append(keys[i])
elif (keys[i][0][0]) == 'd':
list_d.append(keys[i])
elif (keys[i][0][0]) == 'e':
list_e.append(keys[i])
elif (keys[i][0][0]) == 'f':
list_f.append(keys[i])
elif (keys[i][0][0]) == 'g':
list_g.append(keys[i])
elif (keys[i][0][0]) == 'h':
list_h.append(keys[i])
elif (keys[i][0][0]) == 'i':
list_i.append(keys[i])
elif (keys[i][0][0]) == 'j':
list_j.append(keys[i])
elif (keys[i][0][0]) == 'k':
list_k.append(keys[i])
elif (keys[i][0][0]) == 'l':
list_l.append(keys[i])
elif (keys[i][0][0]) == 'm':
list_m.append(keys[i])
elif (keys[i][0][0]) == 'n':
list_n.append(keys[i])
elif (keys[i][0][0]) == 'o':
list_o.append(keys[i])
elif (keys[i][0][0]) == 'p':
list_p.append(keys[i])
elif (keys[i][0][0]) == 'q':
list_q.append(keys[i])
elif (keys[i][0][0]) == 'r':
list_r.append(keys[i])
elif (keys[i][0][0]) == 's':
list_s.append(keys[i])
elif (keys[i][0][0]) == 't':
list_t.append(keys[i])
elif (keys[i][0][0]) == 'u':
list_u.append(keys[i])
elif (keys[i][0][0]) == 'v':
list_v.append(keys[i])
elif (keys[i][0][0]) == 'w':
list_w.append(keys[i])
elif (keys[i][0][0]) == 'x':
list_x.append(keys[i])
elif (keys[i][0][0]) == 'y':
list_y.append(keys[i])
elif (keys[i][0][0]) == 'z':
list_z.append(keys[i])
else:
list_unknown.append(keys[i])
i += 1
def check_based_alphabet(alphabetList, k = 0, j = 0):
while k < len(alphabetList) - 1:
if alphabetList[k][1] != alphabetList[j][1]:
distance = td.jaccard(alphabetList[k][0], alphabetList[j][0])
if distance > 0.7:
duplicate_list.append([alphabetList[k][0], alphabetList[j][0]])
j += 1
else:
j += 1
if j == len(alphabetList):
j = 1
k += 1
check_based_alphabet(list_a)
check_based_alphabet(list_b)
check_based_alphabet(list_c)
check_based_alphabet(list_d)
check_based_alphabet(list_e)
check_based_alphabet(list_f)
check_based_alphabet(list_g)
check_based_alphabet(list_h)
check_based_alphabet(list_i)
check_based_alphabet(list_j)
check_based_alphabet(list_k)
check_based_alphabet(list_l)
check_based_alphabet(list_m)
check_based_alphabet(list_n)
check_based_alphabet(list_o)
check_based_alphabet(list_p)
check_based_alphabet(list_q)
check_based_alphabet(list_r)
check_based_alphabet(list_s)
check_based_alphabet(list_t)
check_based_alphabet(list_u)
check_based_alphabet(list_v)
check_based_alphabet(list_w)
check_based_alphabet(list_x)
check_based_alphabet(list_y)
check_based_alphabet(list_z)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T21:25:30.193",
"Id": "477056",
"Score": "2",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of CR: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles. Also, while it isn't exactly a mirror scenario [the consensus is that questions about the complexity of code are off-topic](https://codereview.meta.stackexchange.com/q/8373/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T23:42:58.583",
"Id": "477061",
"Score": "0",
"body": "sorted() takes O(nlog(n)) time, so not linear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T04:56:39.840",
"Id": "477078",
"Score": "0",
"body": "@LeoAdberg do you mean sorted() in keys = sorted((z.values())) ? Lets set i change it into keys = z.values(). Would this change anything ? Because i don't really need to sort them in the first place"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T06:44:08.550",
"Id": "477084",
"Score": "1",
"body": "@Bobby Anyone that actually want to help you learn about big o wouldn't just give you the answer. Why do _you_ think it's linear? Where are your workings out?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T17:28:56.087",
"Id": "477134",
"Score": "1",
"body": "If all you wanna know Is the time complexity of your code, then you've come to the wrong place. If you dont know how to determine that from the code itself, why dont you try the obvious naive solution and make some meassurements for various input sizes and see if it scales lineary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T08:43:03.880",
"Id": "477193",
"Score": "5",
"body": "I’m voting to close this question because it poses a specific question, there is no request for review. Please take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>Even if you didn't ask, I would just go ahead and comment on the code.\nPlease use the following so that you don't need so many lists.</p>\n\n<p>Initialize a dictionary:</p>\n\n<pre><code>list_dict = {}\n\nfor i in range (97, 123):\n list_dict[chr(i)] = []\n</code></pre>\n\n<p>First use a dictionary:</p>\n\n<pre><code>i = 0\nwhile i < (len(keys)) - 1:\n if 'a' <= (keys[i][0][0]) <= 'z':\n list_dict[keys[i][0][0]].append(keys[i])\n else:\n #ignore\n pass\n i += 1\n</code></pre>\n\n<p>And second use loop.</p>\n\n<pre><code>for alpha, ll in list_dict.items():\n check_based_alphabet(ll)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:11:00.610",
"Id": "477327",
"Score": "1",
"body": "While I agree that the code should be vastly simplified, your solution overwrites the entries instead of grouping them by their first letter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:56:30.420",
"Id": "477337",
"Score": "1",
"body": "Thanks for pointing this out. just wrote that quickly by mistake. corrected."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T13:49:38.767",
"Id": "243146",
"ParentId": "243080",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:34:38.180",
"Id": "243080",
"Score": "-2",
"Tags": [
"python",
"strings",
"hash-map"
],
"Title": "Sorting through two dictionaries"
}
|
243080
|
<p>Im refactoring a large internal legacy application and part of the stuff I want to get rid is the widespread code repetition. </p>
<p>I'm starting with the way the website checks if a User can access a route e.g., '/admin` and which parts should be rendered or not. </p>
<p>I made this little function and works pretty well but wanted to see if you could take a look into it and suggest improvements or point out problems with the way I built it.</p>
<p>Anyway, here's the code:</p>
<pre><code>export default async function isAdmin(alias, policyOverride = null) {
try {
var authResult = false;
const url = 'https://xxx.execute-api.us-west-2.amazonaws.com/local/xxxx/';
var adminRolePolicy = ['Admin', 'Dev', 'BaseUser']; //Default Admin Policy.
var rolesBoundToAlias = (await axios.get(url + alias)).data //Fetch roles that the alias holds.
if(policyOverride){
adminRolePolicy = policyOverride;
} //If a new policy is, override the default adminRolePolicy.
authResult =
rolesBoundToAlias.some(role => adminRolePolicy.includes(role)); //If alias has any of the roles in the policy grant access.
return authResult;
} catch (error) {
console.error("Error when attempting to authorize user " + alias
+ ". Access for this user has been denied, please try again."
+ "\nError: " + error);
return false;
}
}
</code></pre>
<p>I added the <code>policyOverride</code> as an optional param so the function can accept an array with different roles... allowing for more flexibility.</p>
<p>One of the most simple applications for this function would be as follows:</p>
<pre><code>import isAdmin from '../utils/authorization.js';
//Other stuff happens here.
//...
isAdmin(alias)
.then((authResult) => {
if(authResult) {
//Authorized to view content render this.
}
else {
//Else render a 403 or something...
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-09T15:13:18.807",
"Id": "478157",
"Score": "1",
"body": "I have rolled back Rev 4 → 2 Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>If you're going to use <code>const</code> for some variables, then use that (or <code>let</code>) for all variables. Avoid <code>var</code> unless you have a good reason - e.g. you really need a global variable and/or hoisting.</p>\n\n<p>The variable <code>authResult</code> can be eliminated from function <code>isAdmin</code> since it only gets a default value assigned, which then gets overwritten before it is returned. The function could merely return the value from the call to <code>rolesBoundToAlias.some()</code>. The arrow function passed to <code>.some()</code> could be declared on the previous line if you want, in an effort to decrease line length. Actually you might be able to just use <code>Array.includes()</code> bound to the array of roles instead of an extra arrow function. </p>\n\n<p>The name <code>adminRolePolicy</code> might be better named as <code>DEFAULT_ROLES</code>. I use all caps since it is more like a real constant that wouldn't change much - and could be declared outside the function if deemed appropriate. And while there is likely some overlap, <code>Dev</code> and <code>BaseUser</code> seem separate from the concept of <code>admin</code>.</p>\n\n<p>Instead of calling the second parameter <code>policyOverride</code>, you could call it <code>roles</code> with the default of <code>DEFAULT_ROLES</code> - then there would be no need to assign the parameter to a different variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-05T00:19:08.680",
"Id": "243397",
"ParentId": "243082",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243397",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:59:48.973",
"Id": "243082",
"Score": "3",
"Tags": [
"javascript",
"asynchronous",
"async-await",
"ecmascript-8"
],
"Title": "User Access Authorization for Web Resources"
}
|
243082
|
<p>Very new to coding, so please don't bully me.</p>
<p><strong>Implement the legendary caesar cipher:</strong></p>
<p>In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.</p>
<p><strong>Question: Write a function that takes a string to be encoded and a shift factor and then returns the encoded string:</strong></p>
<p>caesar('A', 1) // simply shifts the letter by 1: returns 'B' the cipher should retain capitalization:</p>
<p>caesar('Hey', 5) // returns 'Mjd; should not shift punctuation:</p>
<p>caesar('Hello, World!', 5) //returns 'Mjqqt, Btwqi!' the shift should wrap around the alphabet:</p>
<p>caesar('Z', 1) // returns 'A' negative numbers should work as well:</p>
<p>caesar('Mjqqt, Btwqi!', -5) // returns 'Hello, World!'</p>
<p><strong>My Solution:</strong></p>
<pre><code>function caesar(string, num) {
let arr = [];
for(let i=0;i<string.length;i++)
{if(!(/[a-zA-Z]/.test(string[i])))
{arr[i]=string[i]; continue;}
let n = string.charCodeAt(i) + num;
if (string[i] == string[i].toLowerCase())
{if(n>122)
{while(n>122)
{n-=26;}}
else
{while(n<97)
{n+=26;}
}
}
else
{if(n>90)
{while(n>90)
{n-=26;}
}
else
{while(n<65)
{n+=26;}
}
}
arr[i]=String.fromCharCode(n);
}
console.log(arr.join(''));
}
caesar("Hello, World!", 2);
caesar("Hello, World!", 75);
</code></pre>
<p><strong>The code is working perfectly as per requirement, but please help me with a <em>better solution</em> if possible.</strong></p>
<p>And if you do, please use comments to extensively explain the working process, as I'm quite the noob.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T00:22:59.470",
"Id": "477067",
"Score": "1",
"body": "Welcome to code review. We can't provide alternate code solutions, we do review the code and make comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T02:36:48.757",
"Id": "477072",
"Score": "0",
"body": "@pacmaninbw Okay, then. Thank you for your time. :)"
}
] |
[
{
"body": "<p>Welcome to Code Review, some considerations that can help you to simplify your code:</p>\n\n<ol>\n<li>you have an alphabet of 26 letters, so if the shifting operation is\nlimited to a 26 characters range you can use the mod operation <code>%26</code>\nto determine the final position.</li>\n<li>you can have a shift negative operation <code>num</code> (ex. -5), for a 26\nset of elements shift this is equal to a positive shift of <code>Math.abs(26 - Math.abs(num))</code> , so for 5 the positive shift is 21.</li>\n</ol>\n\n<p>So if you have a <code>c</code> character and you want to obtain the ascii code of the corresponding shifted char of <code>num</code> positions you can obtain it in the following way:</p>\n\n<pre><code>const start = c === c.toLowerCase() ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0);\nconst diff = c.charCodeAt(0) - start;\nconst sh = num >= 0 ? diff + num : diff + Math.abs(26 - Math.abs(num));\nconst code = sh % 26 + start;\n</code></pre>\n\n<p>The first line returns the ascii code of 'a' or 'A' depending if the char <code>c</code> is lowercase or uppercase called <code>start</code>, the second gives you the difference between <code>c</code> and <code>start</code>, the last two lines calculate the code of the shifted corresponding character.</p>\n\n<p>After your function can be rewritten in the following way:</p>\n\n<pre><code>'use strict';\n\nfunction caesar(str, num) {\n const arr = [];\n const re = /[a-zA-Z]/;\n for (const c of str) {\n if (re.test(c)) {\n const start = c === c.toLowerCase() ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0);\n const diff = c.charCodeAt(0) - start;\n const sh = num >= 0 ? diff + num : diff + Math.abs(26 - Math.abs(num));\n const code = sh % 26 + start;\n arr.push(String.fromCharCode(code));\n } else { \n arr.push(c); \n }\n }\n\n return arr.join('');\n}\n</code></pre>\n\n<p>I set arr and <code>regex</code> as const and instead of iterate over string using the index, I preferred the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for ... of</a> construct.</p>\n\n<p>Note: I'm a javascript beginner too, so every suggestion to improve my code as for the original question is highly appreciated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T12:41:08.740",
"Id": "477106",
"Score": "0",
"body": "Yes yes, stupid me totally forgot about [absolute value function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs). And yes, using [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) does help a lot in solidifying the code and making it more readable. Thank you for the help. Certainly appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T15:42:29.417",
"Id": "477127",
"Score": "1",
"body": "@AdilAhmed You are welcome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T07:44:18.460",
"Id": "506263",
"Score": "1",
"body": "Given you stated: “_every suggestion to improve my code as for the original question is highly appreciated._” Feel free to create a new question, linking to this post, and use the tag [_rags-to-riches_](https://codereview.stackexchange.com/tags/rags-to-riches/info)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T08:05:36.187",
"Id": "506264",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thank you for your suggestion and for the link, I was not aware about the `rags-to-riches` tag."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T10:40:41.237",
"Id": "243097",
"ParentId": "243085",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243097",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T00:04:52.697",
"Id": "243085",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"html",
"functional-programming",
"console"
],
"Title": "Caesar Cipher [The Odin Project-Javascript Exercise]"
}
|
243085
|
<p>following is My Code for Collapsing div on Click using JavaScript It is Working Fine But i Want to Precise the onClick Function in Script Any Suggestion will Highly appreciated.Thnx In Advanced.</p>
<pre><code><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet" />
<style>
body,
button {
font-family: "Montserrat", sans-serif;
}
h2 {
font-weight: "bold";
}
.chevron-up {
height: 30px;
width: 30px;
display: inline-block;
background-repeat: no-repeat;
background-position: center;
background-image: url('data:image/svg+xml;base64,PHN2ZyBhcmlhLWhpZGRlbj0idHJ1ZSIgZm9jdXNhYmxlPSJmYWxzZSIgZGF0YS1wcmVmaXg9ImZhcyIgZGF0YS1pY29uPSJjaGV2cm9uLXVwIiBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtY2hldnJvbi11cCBmYS13LTE0IiByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDQ0OCA1MTIiPjxwYXRoIGZpbGw9IiMzNjM2MzYiIGQ9Ik0yNDAuOTcxIDEzMC41MjRsMTk0LjM0MyAxOTQuMzQzYzkuMzczIDkuMzczIDkuMzczIDI0LjU2OSAwIDMzLjk0MWwtMjIuNjY3IDIyLjY2N2MtOS4zNTcgOS4zNTctMjQuNTIyIDkuMzc1LTMzLjkwMS4wNEwyMjQgMjI3LjQ5NSA2OS4yNTUgMzgxLjUxNmMtOS4zNzkgOS4zMzUtMjQuNTQ0IDkuMzE3LTMzLjkwMS0uMDRsLTIyLjY2Ny0yMi42NjdjLTkuMzczLTkuMzczLTkuMzczLTI0LjU2OSAwLTMzLjk0MUwyMDcuMDMgMTMwLjUyNWM5LjM3Mi05LjM3MyAyNC41NjgtOS4zNzMgMzMuOTQxLS4wMDF6Ii8+PC9zdmc+');
}
.chevron-down {
height: 30px;
width: 30px;
display: inline-block;
background-repeat: no-repeat;
background-position: center;
background-image: url('data:image/svg+xml;base64,PHN2ZyBhcmlhLWhpZGRlbj0idHJ1ZSIgZm9jdXNhYmxlPSJmYWxzZSIgZGF0YS1wcmVmaXg9ImZhcyIgZGF0YS1pY29uPSJjaGV2cm9uLWRvd24iIGNsYXNzPSJzdmctaW5saW5lLS1mYSBmYS1jaGV2cm9uLWRvd24gZmEtdy0xNCIgcm9sZT0iaW1nIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0NDggNTEyIj48cGF0aCBmaWxsPSIjMzYzNjM2IiBkPSJNMjA3LjAyOSAzODEuNDc2TDEyLjY4NiAxODcuMTMyYy05LjM3My05LjM3My05LjM3My0yNC41NjkgMC0zMy45NDFsMjIuNjY3LTIyLjY2N2M5LjM1Ny05LjM1NyAyNC41MjItOS4zNzUgMzMuOTAxLS4wNEwyMjQgMjg0LjUwNWwxNTQuNzQ1LTE1NC4wMjFjOS4zNzktOS4zMzUgMjQuNTQ0LTkuMzE3IDMzLjkwMS4wNGwyMi42NjcgMjIuNjY3YzkuMzczIDkuMzczIDkuMzczIDI0LjU2OSAwIDMzLjk0MUwyNDAuOTcxIDM4MS40NzZjLTkuMzczIDkuMzcyLTI0LjU2OSA5LjM3Mi0zMy45NDIgMHoiPjwvcGF0aD48L3N2Zz4=');
}
.collapsible {
cursor: pointer;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 13px;
display: flex;
justify-content: space-between;
align-items: center;
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
font-size: 11px;
border-bottom: 1px solid #e7e7e7;
}
.content a {
color: #f7941d;
}
</style>
</head>
<body>
<h2>How can we help?</h2>
<button class="collapsible">
How to Redeem a Voucher
<span class="chevron-down" />
</button>
<div class="content">
<p>
Making Redemption through App is easy, Here’s how it goes:
</p>
<ol>
<li>Tap on the offer you want to redeem.</li>
<li>Ask the merchant to enter their PIN.</li>
<li>
You’ll get the smiley screen showing your estimated savings amount.
</li>
<li>Make sure to activate Bogo App first, <a href="www.google.com">Haven’t purchased it yet?</a></li>
</ol>
</div>
<button class="collapsible">
How to Activate my account
<span class="chevron-down" />
</button>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
</p>
</div>
<button class="collapsible">
I forgot my Password
<span class="chevron-down" />
</button>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
</p>
</div>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].onclick = function () {
if (this.classList.contains('active')) {
this.classList.remove('active');
this.firstElementChild.classList.remove("chevron-up")
this.firstElementChild.classList.add("chevron-down")
this.style.maxHeight = null;
this.nextElementSibling.style.maxHeight = null;
} else {
for (let j = 0; j < coll.length; j++) {
coll[j].classList.remove('active');
coll[j].style.maxHeight = null;
coll[j].nextElementSibling.style.maxHeight = null;
coll[j].firstElementChild.classList.remove("chevron-up")
coll[j].firstElementChild.classList.add("chevron-down")
}
this.classList.add("active");
this.firstElementChild.classList.remove("chevron-down")
this.firstElementChild.classList.add("chevron-up")
var panel = this.nextElementSibling;
panel.style.maxHeight = panel.scrollHeight + 'px'
}
}
}
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Avoid repeating in the CSS. The rules for the classes <code>chevron-up</code> and <code>chevron-down</code> are identical except for the image. Have a separate rule für the common properties like this:</p>\n\n<pre><code>.chevron-up, .chevron-down {\n height: 30px;\n width: 30px;\n display: inline-block;\n background-repeat: no-repeat;\n background-position: center;\n}\n\n.chevron-up {\n background-image: url(...);\n}\n\n.chevron-down {\n background-image: url(...);\n}\n</code></pre>\n\n<p>(NB, unless it's just for this example, don't use <code>data:</code> URLs. They bloat the CSS.)</p>\n\n<p>Or, if you have more similar icons, use a separate class:</p>\n\n<pre><code>.icon {\n height: 30px;\n width: 30px;\n display: inline-block;\n background-repeat: no-repeat;\n background-position: center;\n}\n\n.chevron-up {\n background-image: url(...);\n}\n\n.chevron-down {\n background-image: url(...);\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code><span class=\"icon chevron-up\"></span>\n</code></pre>\n\n<p>BTW, it's invalid HTML to use self-closing tags (<code><span /></code>) on elements such as <code>span</code>. They must be written with explicit start and end tags.</p>\n\n<p>You should consider removing these icon elements anyway. HTML should contain content and empty elements like that aren't content. Instead use the CSS pseudo-element <code>::after</code>:</p>\n\n<pre><code>.collapsible::after {\n content: \"\";\n height: 30px;\n width: 30px;\n display: inline-block;\n background-repeat: no-repeat;\n background-position: center;\n background-image: url(...); // chevron-down icon\n}\n\n.collapsible.active::after {\n background-image: url(...); // chevron-up icon\n}\n</code></pre>\n\n<p>This way you also don't need to switch the <code>chevron-up</code>/<code>chevron-down</code> classes in the JavaScript.</p>\n\n<p>In JavaScript don't use the <code>on...</code> event properties. The <code>on...</code> properties only allow a single event handler, that can be overwritten by a different script. Instead us <code>addEventListener</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T09:00:16.163",
"Id": "243093",
"ParentId": "243086",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T02:25:09.797",
"Id": "243086",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Collapsing The Divs Using JavaScript"
}
|
243086
|
<p>I've made a sudoku solver which solves a sudoku, given user input, and can also extract digits from a picture of a sudoku to solve it. I've used OpenCV and GTK+ 2.0 to achieve the above. I am very open to any kind of suggestion on how write proper and understandable C++ code. I have the following question:</p>
<ol>
<li>How would you rate my code? What to improve?</li>
<li>How to improve its readability? (I tried an object oriented implementation in order to improve readability, I don't know whether that's right)</li>
<li>Is there a best practice I'm not following or missing ?</li>
<li>I've used some global varibles, is that bad?</li>
<li>I've just heard the term unit test cases. Does this program require that?</li>
</ol>
<p>The code:</p>
<pre><code> #include <gtk/gtk.h>
#include <iostream>
#include <string.h>
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core/core.hpp"
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
using namespace cv;
// Sudoku grid
static int grid[9][9];
// Sudoku grid displayed, main window
static GtkWidget *wid [9][9] , *window;
// Whether to show pre-processing steps
bool to_show;
// To initiate solver
void solver();
// To show pre-processing steps
static void show_steps_event( GtkWidget *widget , gpointer data );
// To get user inputted elements
static void get_element( GtkWidget *widget , gpointer data );
// To clear the grid
static void new_event( GtkWidget *widget , gpointer data );
// To upload a picture and put digits into grid
static void upload_element( GtkWidget *widget , gpointer data );
// For a single datapoint of KNN algorithm dataset
struct datapoint
{
int val; // Group of datapoint
Mat digit; // Feature values
double distance; // 'Distance' from test point
};
// To enable sorting to find the k nearest neighbour
bool comparison ( datapoint a , datapoint b )
{
return (a.distance < b.distance);
}
// KNN algorithm
class KNearestNeighbors
{
private:
int k;
vector <datapoint> imgs;
public:
// Constructor
KNearestNeighbors ( int n_neighbors = 5 ) { k = n_neighbors; }
// To find the 'distance' between two datapoints ; Note: cosine similarity can also be used
double dist ( Mat a , Mat b );
// To load an image from the dataset
void load(string s,int group);
// To load the dataset
void fit_transform();
// To predict a number between 1-9 given its image
int predict ( Mat img );
// Destructor
~KNearestNeighbors(){}
};
// Sudoku solver
class sudoku
{
private:
int arr[9][9];
public:
// Constructor
sudoku(){}
// To start the solving of sudoku
void initiate ();
// To return the solved array to global variable
void finish ( int x[][9] , int m , int n );
// To the find the center of small 3x3 squares in 9x9
void findc ( int &c );
// To check whether num is valid at index (x,y)
bool isValid ( int arr[][9] , int x , int y , int num );
// To solve and dislay final array
void solve ( int arr[][9] );
// Displays the array once solved
void whenDone ();
// Destructor
~sudoku(){}
};
// For image preprocessing
class scanner
{
private:
Mat img;
KNearestNeighbors k;
public:
// Constructor
scanner ( string s , KNearestNeighbors temp );
// Returns a number using the KNN algorithm
int getNum ( Mat img );
// Finds the Euclidean distance between two points
float distance ( Point p , int i , int j );
// To find corresponding points for homography transformation
int findQuad ( Point p , Mat img );
// Returns a 900x900 resized version of a binary image of the sudoku grid
Mat preprocessing ( Mat img );
// To scan each square of the grid and return the digit it contains
void getDigits ();
// Destructor
~scanner(){}
};
double KNearestNeighbors :: dist ( Mat a , Mat b )
{
double val = 0;
for ( int i = 0 ; i < 20 ; i++ )
{
for ( int j = 0 ; j < 20 ; j++ )
{
val = val + (a.at<uchar>(i,j)-b.at<uchar>(i,j))*(a.at<uchar>(i,j)-b.at<uchar>(i,j));
}
}
return sqrt(val);
}
void KNearestNeighbors :: load(string s,int group)
{
vector<cv::String> fn;
glob(s, fn, false);
vector<Mat> images;
size_t count = fn.size(); //number of png files in images folder
for (size_t i=0; i<count; i++)
{
Mat temp = imread(fn[i],0);
datapoint t;
t.val = group;
t.digit = temp;
imgs.push_back(t);
}
}
void KNearestNeighbors :: fit_transform()
{
string direct = "Data/";
string temp = "/*.png";
for ( int i = 0 ; i <= 9 ; i++ )
{
string new_direct = direct + to_string(i) + temp;
load(new_direct,i);
}
}
int KNearestNeighbors :: predict ( Mat img )
{
for ( int i = 0 ; i < imgs.size() ; i++ )
{
imgs[i].distance = dist ( imgs[i].digit , img );
}
sort(imgs.begin(),imgs.end(),comparison);
int freq[10] = {0};
for ( int i = 0 ; i < k ; i++ )
{
for ( int j = 0 ; j < 10 ; j++ )
{
if ( imgs[i].val == j )
{
freq[j]++;
}
}
}
return max_element(freq, freq + sizeof(freq)/sizeof(int)) - freq ;
}
void sudoku :: finish ( int x[][9] , int m , int n )
{
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
grid[i][j] = x[i][j];
}
}
}
void sudoku :: findc ( int &c )
{
switch(c)
{
case 0:
case 1:
case 2: c = 1;
return;
case 3:
case 4:
case 5: c = 4;
return;
case 6:
case 7:
case 8: c = 7;
return;
}
}
bool sudoku :: isValid ( int arr[9][9] , int x , int y , int num )
{
bool check = true;
int i,j;
for ( i = 0 ; i < 9 ; i++ )
{
if ( i == x )
continue;
if ( arr[i][y] == num && check == true )
{
check = false;
return check;
}
}
for ( j = 0 ; j < 9 ; j++ )
{
if ( j == y )
continue;
if ( arr[x][j] == num && check == true )
{
check = false;
return check;
}
}
i = x;
j = y;
findc(i);
findc(j);
for ( int k = i-1 ; k < i+2 ; k++ )
{
for ( int l = j-1 ; l < j+2 ; l++ )
{
if ( k == x && l == y )
continue;
if ( arr[k][l] == num && check == true )
{
check = false;
return check;
}
}
}
return check;
}
void sudoku :: solve ( int arr[9][9] )
{
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
if ( arr[i][j] == 0 )
{
for ( int k = 1 ; k <= 9 ; k++ )
{
if ( isValid (arr,i,j,k) == true )
{
arr[i][j] = k;
whenDone();
solve(arr);
arr[i][j] = 0;
}
if ( k == 9 )
{
arr[i][j] = 0;
return;
}
}
if ( !( isValid(arr,i,j,1) || isValid(arr,i,j,2) || isValid(arr,i,j,3) || isValid(arr,i,j,4) || isValid(arr,i,j,5) || isValid(arr,i,j,6) || isValid(arr,i,j,7) || isValid(arr,i,j,8) || isValid(arr,i,j,9) ) )
{
arr[i][j] = 0;
return;
}
}
}
}
finish(arr,9,9);
}
void sudoku :: initiate ()
{
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
arr[i][j] = grid[i][j];
}
}
solve(arr);
}
void sudoku :: whenDone()
{
for ( int i = 0 ; i < 9 ; i++ )
{
int sum = 0;
for ( int j = 0 ; j < 9 ; j++ )
{
sum = sum + arr[i][j];
}
if ( sum != 55 )
{
return;
}
}
finish(arr,9,9);
}
scanner :: scanner ( string s , KNearestNeighbors temp )
{
img = imread(s,0);
k = temp;
k.fit_transform();
}
int scanner :: getNum ( Mat img )
{
return k.predict(img);
}
float scanner :: distance ( Point p , int i , int j )
{
return (i-p.x)*(i-p.x) + (j-p.y)*(j-p.y);
}
int scanner :: findQuad ( Point p , Mat img )
{
vector<Point> s;
Point p1(0,0) , p2(img.cols,0) , p3(img.cols,img.rows) , p4(0,img.rows);
s.push_back(p1);
s.push_back(p2);
s.push_back(p3);
s.push_back(p4);
double d = 0;
int min = 0;
for ( int i = 0 ; i < 4 ; i++ )
{
if ( distance(p,s[i].x,s[i].y) > d )
{
d = distance(p,s[i].x,s[i].y);
min = i;
}
}
return min;
}
Mat scanner :: preprocessing ( Mat img )
{
Mat img_blur , canny_output , warp_output , binary_output , square ;
if ( to_show == true )
{
namedWindow("Input Image",0);
imshow("Input Image",img);
waitKey(1);
}
GaussianBlur( img , img_blur , Size(3,3) , 0 ); //blurring to remove noise ; Note: we can use an edge preserving filter
if ( to_show == true )
{
namedWindow("Gaussian blur",0);
imshow("Gaussian blur",img_blur);
waitKey(1);
}
double otsu_thresh_val = threshold(img_blur, img_blur , 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); // Using Otsu thresholding to find the thresholds for Canny Edge detection
double high_thresh_val = otsu_thresh_val, lower_thresh_val = otsu_thresh_val * 0.5;
Canny ( img_blur , canny_output , lower_thresh_val , high_thresh_val ); //Canny edge detection
if ( to_show == true )
{
namedWindow("Canny",0);
imshow("Canny",canny_output);
waitKey(1);
}
vector<vector<Point>> contours; //contour detection ; Note: needs improvement as in some cases it detects some random contour and not the grid
findContours( canny_output , contours , CV_RETR_EXTERNAL , CV_CHAIN_APPROX_SIMPLE );
double max_area = 0;
int temp = 0;
for ( int i = 0 ; i < contours.size() ; i++ )
{
if ( contourArea(contours[i]) >= max_area )
{
max_area = contourArea(contours[i]); //finding contour of maximum area ; Note: can also use sort function and use contour at index 0
temp = i;
}
}
double peri = arcLength ( contours[temp] , true ); //perimeter of outer rectangle
vector<Point> rect;
approxPolyDP ( contours[temp] , rect , 0.02*peri , true ); //approxiating the contour to a rectangle
Point2f inputQuad[4]; //Input Quadilateral or Image plane coordinates
Point2f outputQuad[4]; //Output Quadilateral or World plane coordinates
Mat perspectiveMatrix( 2, 4, CV_32FC1 ); //perspectiveMatrix
perspectiveMatrix = Mat::zeros( img.rows, img.cols, img.type() ); //setting it as same type as input image
for ( int i = 0 ; i < 4 ; i++ )
{
inputQuad[findQuad(rect[i],img)] = rect[i];
}
outputQuad[0] = Point2f( img.cols , img.rows );
outputQuad[1] = Point2f( 0 , img.rows );
outputQuad[2] = Point2f( 0 , 0 );
outputQuad[3] = Point2f( img.cols , 0 );
perspectiveMatrix = getPerspectiveTransform( inputQuad, outputQuad ); //Get the Perspective Transform Matrix i.e. perspectiveMatrix
warpPerspective(img,warp_output,perspectiveMatrix,warp_output.size() ); //Apply the Perspective Transform to the input image
if ( to_show == true )
{
namedWindow("Homography",0);
imshow("Homography",warp_output);
waitKey(1);
}
int size = warp_output.rows*warp_output.cols/2188; //Get the kernel size for adaptive threshold
if ( size%2 == 0 ) size++; //Making it odd
adaptiveThreshold( warp_output , binary_output , 255 , ADAPTIVE_THRESH_MEAN_C , THRESH_BINARY , size , 0 ); //Using adaptive thresholding to obtain binary image
if ( to_show == true )
{
namedWindow("Thresholding",0);
imshow("Thresholding",binary_output);
waitKey(1);
}
Size s(900,900);
resize(binary_output,square,s);
if ( to_show == true )
{
namedWindow("Final Image",0);
imshow("Final Image",square);
waitKey(1);
}
return square;
}
void scanner :: getDigits ()
{
Mat square = preprocessing(img);
for ( int x = 0 ; x < 9 ; x++ )
{
for ( int y = 0 ; y < 9 ; y++ )
{
grid[x][y] = 0;
Mat elm( square.rows*0.13 , square.cols*0.13, CV_8UC1 , Scalar(0) ); //Making an image containing a square of the grif
for ( int i = 0 ; i < elm.rows ; i++ )
{
for ( int j = 0 ; j < elm.cols ; j++ )
{
if ( i+int(square.rows*x/9) < square.rows && j+int(square.cols*y/9) < square.cols ) //Checking the pixel is valid
elm.at<uchar>(i,j) = square.at<uchar>(i+int(square.rows*x/9),j+int(square.cols*y/9)); //Extracting a square
else
elm.at<uchar>(i,j) = 0;
}
}
vector<vector<Point>> num;
findContours( elm , num , CV_RETR_EXTERNAL , CV_CHAIN_APPROX_SIMPLE );
double area = 0;
int idx = 0;
for ( int i = 0 ; i < num.size() ; i++ )
{
if ( contourArea(num[i]) >= area )
{
area = contourArea(num[i]); //Finding contour of maximum area
idx = i;
}
}
Rect n = boundingRect(num[idx]);
Mat number = elm(n); //Cropping out the number from the cell
Mat fin (number.rows-10,number.cols-10, CV_8UC1 , Scalar(0) );
for ( int i = 5 ; i < number.rows-5 ; i++ )
{
for ( int j = 5 ; j < number.cols-5 ; j++ )
{
fin.at<uchar>(i-5,j-5) = number.at<uchar>(i,j);
}
}
resize(fin,fin,Size(20,20));
grid[x][y] = getNum ( fin ); //Assigning the corresponding numbber to the array
}
}
}
void solver ()
{
sudoku x;
x.initiate();
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
char c[2];
sprintf(c,"%d",grid[i][j]);
gtk_entry_set_text(GTK_ENTRY(wid[i][j]),c);
}
}
}
static void show_steps_event( GtkWidget *widget , gpointer data )
{
if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget) ))
{
to_show = true;
}
else
{
to_show = false;
}
}
static void get_element( GtkWidget *widget , gpointer data )
{
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
if ( gtk_entry_get_text(GTK_ENTRY(wid[i][j])) == " " )
grid[i][j] = 0;
else
grid[i][j] = atoi(gtk_entry_get_text(GTK_ENTRY(wid[i][j])));
}
}
solver();
}
static void new_event( GtkWidget *widget , gpointer data )
{
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
grid[i][j] = 0;
gtk_entry_set_text(GTK_ENTRY(wid[i][j])," ");
}
}
}
static void upload_element( GtkWidget *widget , gpointer data )
{
GtkWidget *dialog;
dialog = gtk_file_chooser_dialog_new("Choose a file",GTK_WINDOW(window),GTK_FILE_CHOOSER_ACTION_OPEN,GTK_STOCK_OK,GTK_RESPONSE_OK,GTK_STOCK_CANCEL,GTK_RESPONSE_CANCEL,NULL);
gtk_widget_show_all(dialog);
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog),g_get_home_dir());
gint resp = gtk_dialog_run(GTK_DIALOG(dialog));
if ( resp == GTK_RESPONSE_OK )
{
string s = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
KNearestNeighbors knn (1);
scanner scan (s,knn);
scan.getDigits();
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 ; j++ )
{
char c[2];
if( grid[i][j] != 0 )
sprintf(c,"%d",grid[i][j]);
else
sprintf(c," ");
gtk_entry_set_text(GTK_ENTRY(wid[i][j]),c);
}
}
}
gtk_widget_destroy(dialog);
}
int main(int argc, char* argv[])
{
gtk_init(&argc,&argv); // Initialising GTK+
GtkWidget *vbox , *hbox , *separator , *button , *toggle , *file_menu , *menu_bar , *menu_item;
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL); // if X is pressed then program is exited
vbox = gtk_vbox_new(0,0);
for ( int i = 0 ; i < 9 ; i++ ) // Making grid full of entry boxes
{
hbox = gtk_hbox_new(0,0);
for ( int j = 0 ; j < 9 ; j++ )
{
wid[i][j] = gtk_entry_new();
gtk_entry_set_max_length(GTK_ENTRY(wid[i][j]),1);
gtk_widget_set_size_request(wid[i][j],50,50);
gtk_box_pack_start(GTK_BOX(hbox),wid[i][j],1,1,0);
if ( (j+1)%3 == 0 ) // Adding separator at columns multiple of 3
{
separator = gtk_vseparator_new();
gtk_box_pack_start(GTK_BOX(hbox),separator,1,1,0);
separator = gtk_vseparator_new();
gtk_box_pack_start(GTK_BOX(hbox),separator,1,1,0);
}
}
gtk_box_pack_start(GTK_BOX(vbox),hbox,1,1,0);
if ( (i+1)%3 == 0 ) // Adding separator at rows multiple of 3
{
separator = gtk_hseparator_new();
gtk_box_pack_start(GTK_BOX(vbox),separator,1,1,0);
separator = gtk_hseparator_new();
gtk_box_pack_start(GTK_BOX(vbox),separator,1,1,0);
}
}
hbox = gtk_hbox_new(0,0);
button = gtk_button_new_with_label("Solve"); // Solve button
g_signal_connect(button,"clicked",G_CALLBACK(get_element),NULL);
gtk_box_pack_start(GTK_BOX(hbox),button,1,1,0);
button = gtk_button_new_with_label("Upload"); // Upload image button
g_signal_connect(button,"clicked",G_CALLBACK(upload_element),NULL);
gtk_box_pack_start(GTK_BOX(hbox),button,1,1,0);
button = gtk_button_new_with_label("New"); // Clearing grid for new input
g_signal_connect(button,"clicked",G_CALLBACK(new_event),NULL);
gtk_box_pack_start(GTK_BOX(hbox),button,1,1,0);
toggle = gtk_check_button_new_with_mnemonic("Show steps"); // To show image processing steps
gtk_box_pack_start(GTK_BOX(hbox),toggle,0,0,0);
g_signal_connect(toggle,"toggled",G_CALLBACK(show_steps_event),NULL);
gtk_box_pack_start(GTK_BOX(vbox),hbox,0,0,0);
gtk_container_add(GTK_CONTAINER(window),vbox);
gtk_window_set_title(GTK_WINDOW(window),"Sudoku Solver");
gtk_widget_show_all(window);
gtk_main();
waitKey(0);
return 0;
}
</code></pre>
<p><strong>Note:</strong> I've not included the data files which contains templates of images of digits 0-9 for the KNN algorithm.</p>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n\n<blockquote>\n <p>How would you rate my code? What to improve?</p>\n</blockquote>\n\n<p>It is certainly not the worst code, but there are areas of improvement, which I'll discuss below.</p>\n\n<blockquote>\n <p>How to improve its readability? (I tried an object oriented implementation in order to improve readability, I don't know whether that's right)</p>\n</blockquote>\n\n<p>I would start to use a code formatter to ensure the code is formatted in a consistent way. Your use of spaces is very inconsistent, some lines have spaces between literally everything where spaces are possible, and in others there is no space to be seen except for the indentation.</p>\n\n<p>Apart from that, avoid abbreviating variable and function names unnecessarily. For example, instead of <code>wid</code> write <code>widget</code>, instead of <code>imgs</code> write <code>images</code>. Unnecessary abbreviations might make it harder to search the code, and make things confusing. (For example, if you didn't see its declaration before, can you tell if <code>wid</code> a widget, a width or a window ID?)</p>\n\n<blockquote>\n <p>Is there a best practice I'm not following or missing?</p>\n</blockquote>\n\n<p>Yes, we'll discuss them.</p>\n\n<blockquote>\n <p>I've used some global varibles, is that bad?</p>\n</blockquote>\n\n<p>It's best to avoid using global variables as much as possible. If they are really necessary then by all means use them, but the issue is that they pollute the global namespace, make it harder to modularize your code, and might result in issues if you have multithreaded code.</p>\n\n<blockquote>\n <p>I've just heard the term unit test cases. Does this program require that?</p>\n</blockquote>\n\n<p>No, programs don't require unit test cases. They are however a method for ensuring your code has a high quality.</p>\n\n<h1>When writing C++ code, prefer to use C++ libraries</h1>\n\n<p>Instead of using the C version of GTK, I strongly advise you to use <a href=\"https://www.gtkmm.org/en/\" rel=\"nofollow noreferrer\">gtkmm</a> instead. It should result in shorter, cleaner code, and will probably help get rid of the global <code>GtkWidget</code> variables.</p>\n\n<h1>Avoid forward declarations</h1>\n\n<p>Unless you have functions with circular dependencies, you should not need to write forward declarations of functions. Just ensure that a function that is called by other functions comes before those other functions in your source code.</p>\n\n<p>Doing this avoids repeating yourself.</p>\n\n<h1>Avoid <code>using namespace std</code></h1>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this StackOverflow question</a> for a rationale.</p>\n\n<h1>Class member value initialization</h1>\n\n<p>Instead of initializing values in the body of the constructor, prefer using a member initializer list, like so:</p>\n\n<pre><code>class KNearestNeighbors {\n int k;\n ...\n KNearestNeighbors (int n_neighbors = 5): k(n_neighbors) {}\n</code></pre>\n\n<p>While it is trivial here, once you have member variables with non-trivial types it has <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list\">certain advantages</a>.</p>\n\n<h1>Avoid writing empty constructors and destructors</h1>\n\n<p>C++ provides default constructors and destructors for you if you don't specify them yourself. So for example in <code>class sudoku</code>, you can avoid writing the constructor and destructor. In general, don't write what you don't need to write.</p>\n\n<h1>Have <code>sudoku::solve()</code> return a <code>sudoku</code></h1>\n\n<p>What is the difference between an unsolved Sudoku and a finished one? It's just that some more of its squares have been filled with numbers. So the solution to a Sudoku is just another Sudoku (albeit a trivial one). You can use this to return the result of the <code>solve()</code> function, and this also gets rid of another global variable. Also, instead of passing in a whole new array to <code>solve()</code>, I would expect the member function <code>solve()</code> to solve the current sudoku.</p>\n\n<p>Another issue is that a given configuration might not have a solution, so apart from the resulting 9x9 squares, it might be nice to return a value indicating whether it was solved correctly or not. There are several ways to do this, you could use a <code>std::pair<sudoku, bool></code> to return the 9x9 squares and a boolean, or maybe add a <code>bool solved</code> member variable to <code>class sudoku</code> itself, or use the C++17 <code>std::optional<sudoku></code>.</p>\n\n<p>With this in place, it should be possible to rewrite your <code>solve()</code> to not have an <code>int arr[9][9]</code> parameter.</p>\n\n<h1>Use <code>hypotf()</code> to calculate the distance between two points</h1>\n\n<p>For example, in <code>scanner::distance()</code>, you could write:</p>\n\n<pre><code>return std::hypotf(i - p.x, j - p.y);\n</code></pre>\n\n<h1>Try to separate computation from presentation</h1>\n\n<p>To avoid the different components of your program depending too much on each other, you should try to separate computation from presentation. For example, in <code>scanner::preprocessing()</code>, you are showing the intermediate results in windows. However, now you've tightly coupled this function with the way you output those results. It would be better to just optionally return the intermediate results, and leave it up to the GUI code to present those results if desired.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T06:09:25.333",
"Id": "477406",
"Score": "0",
"body": "Thank you so much for such a detailed answer! I really liked the idea of passing a Pair. I just have one more doubt. I didn't get the last part - 'Separate Computation from Presentation'. In the GUI, I've kept an option of whether to show steps or not, which is directly linked to 'scanner::preprocessing()'. Are you saying that I should store those images first, instead of writing multiple if statements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T06:29:44.157",
"Id": "477410",
"Score": "0",
"body": "You can still have an if statement to decide whether or not to store those intermediate images at all, but the main point is that you shouldn't create a window, display the image and wait for a keypress in a function whose main job is to do some computations. (Of course, if you quickly want to debug something, go ahead and do exactly that anyway, but then remove it once you have finished debugging the code.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T06:42:10.287",
"Id": "477412",
"Score": "0",
"body": "Ohh okay. Thanks a lot! Cheers!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T21:36:42.033",
"Id": "243233",
"ParentId": "243087",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T05:48:37.867",
"Id": "243087",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"sudoku",
"opencv",
"gtk"
],
"Title": "Made a sudoku solver with basic GUI in C++"
}
|
243087
|
<p>This is a follow-up (somewhat) to <a href="https://codereview.stackexchange.com/q/239997/61966">this post</a>. I said <em>somewhat</em> because I've kinda changed most of the logic.</p>
<p><strong>Changes:</strong></p>
<ul>
<li>I've changed the project name</li>
<li>I've changed the CLI UX</li>
<li>I've added encryption / decryption</li>
<li>I've added a <code>setup.py</code> for easier installation.</li>
<li>I've added <a href="https://github.com/pallets/click" rel="noreferrer"><code>click</code></a></li>
<li>Temporarily removed type annotations & docstrings.</li>
</ul>
<p><strong>Review:</strong></p>
<ul>
<li><p>I'm not quite confident about my SQLAlchemy models (<code>models.py</code>) and how I used the <code>PasswordMixin</code> (if it's even worth adding it for only two models). Any advice on this?</p></li>
<li><p>The same as above goes for the <code>PasswordViewMixin</code> (<code>views.py</code>). Also, I don't like it how I kinda duplicated the logic of the methods in a model and it's specific <code>view</code> class. Any way of avoiding that?</p></li>
<li><p>Any OOP paradigms that I might have misused / not used etc.</p></li>
<li><p>I'd also like an overall review on the project as a whole even on small things like: <strong>project structure</strong>, naming best practices (e.g: I don't know if the <code>views.py</code> file should be called like that but it seemed right at that moment of writing.), the content of README.md, the setup.py file and so on.</p></li>
<li><p>Improvements regarding encryption/decryption workflow</p></li>
<li><p>Improvement regarding usage of the click library</p></li>
</ul>
<p><strong>Code</strong></p>
<p>For those of you who want to run this locally, <a href="https://github.com/alexandru-grajdeanu/dinopass/" rel="noreferrer">here is the github repository</a>.</p>
<p>models.py</p>
<pre class="lang-py prettyprint-override"><code>import os
import sys
from psycopg2 import OperationalError
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
ENGINE = create_engine(f'sqlite:///{os.path.dirname(os.path.dirname(__file__))}/dinopass.db')
SESSION = sessionmaker(bind=ENGINE)
Base = declarative_base()
class PasswordMixin:
id = Column(Integer, primary_key=True)
@classmethod
def create(cls, **kwargs):
return cls(**kwargs)
@classmethod
def get(cls, session):
return session.query(cls).first()
@classmethod
def has_records(cls, session):
return cls.get(session)
@classmethod
def purge(cls, session):
return session.query(cls).delete()
class MasterPassword(Base, PasswordMixin):
__tablename__ = 'master_password'
salt = Column(String, nullable=False)
hash_key = Column(String, nullable=False)
def __init__(self, salt, hash_key):
self.salt = salt
self.hash_key = hash_key
class Password(Base, PasswordMixin):
__tablename__ = 'passwords'
name = Column(String, nullable=False, unique=True)
value = Column(String, nullable=False)
def __repr__(self):
return f"<Password(name='{self.name}')>"
def __str__(self):
return f"<Password(name='{self.name}', value='***')>"
def __init__(self, name, value):
self.name = name
self.value = value
@classmethod
def get_all(cls, session):
return session.query(cls).all()
@classmethod
def get_by_name(cls, name, session):
return session.query(cls).filter_by(name=name).first()
@classmethod
def update_by_field(cls, field, value, field_to_update, new_value, session):
if not getattr(cls, field) and not isinstance(field, str):
raise AttributeError(f'Invalid attribute name: {field}')
if not getattr(cls, field_to_update) and not isinstance(field_to_update, str):
raise AttributeError(f'Invalid field_to_update name: {field_to_update}')
return session.query(cls).filter_by(**{field: value}).update({field_to_update: new_value})
@classmethod
def delete_by_name(cls, name, session):
return session.query(cls).filter_by(name=name).delete()
def to_dict(self):
record = vars(self)
record.pop('_sa_instance_state')
record.pop('id')
return record
try:
Base.metadata.create_all(ENGINE)
except OperationalError as operational_error:
sys.exit(f'Error when connecting to DB: {operational_error}. '
f'Please make sure you have correctly set up your DB!')
</code></pre>
<p>views.py</p>
<pre class="lang-py prettyprint-override"><code>from dinopass.encryption import encrypt, decrypt
from dinopass.models import MasterPassword, Password
from sqlalchemy.exc import IntegrityError
class PasswordViewMixin:
model = None
def __init__(self, db_session):
if not self.model:
raise NotImplementedError('Please specify a model!')
self._db_session = db_session
def get(self):
return self.model.get(self._db_session)
def purge(self):
self.model.purge(self._db_session)
self._db_session.commit()
def has_records(self):
return self.model.has_records(self._db_session)
class MasterPasswordView(PasswordViewMixin):
model = MasterPassword
@property
def salt(self):
return self.model.get(self._db_session).salt
@property
def hash_key(self):
return self.model.get(self._db_session).hash_key
def create(self, **kwargs):
try:
record = self.model.create(**kwargs)
self._db_session.add(record)
self._db_session.commit()
return record
except IntegrityError as integrity_error:
self._db_session.rollback()
return {'error': f'{str(integrity_error)}'}
def is_valid(self, hash_key):
return hash_key == self.hash_key
class PasswordView(PasswordViewMixin):
model = Password
@property
def name(self):
return self.model.get(self._db_session).name
@property
def value(self):
return self.model.get(self._db_session).value
def create(self, key, name, value):
encrypted_value = encrypt(key, value)
try:
record = self.model.create(name=name, value=encrypted_value)
self._db_session.add(record)
self._db_session.commit()
return record
except IntegrityError as integrity_error:
self._db_session.rollback()
return {'error': f'{str(integrity_error)}'}
def get_all(self, key):
records = []
for record in self.model.get_all(self._db_session):
record.value = decrypt(key, record.value)
records.append(record.to_dict())
return records
def get_by_name(self, key, name):
record = self.model.get_by_name(name, self._db_session)
if record:
record.value = decrypt(key, record.value)
return [record.to_dict()]
return []
def update(self, key, field, value, field_to_update, new_value):
if field_to_update == 'value':
new_value = encrypt(key, new_value)
try:
self.model.update_by_field(
field=field,
value=value,
field_to_update=field_to_update,
new_value=new_value,
session=self._db_session
)
self._db_session.commit()
return f'Successfully updated record matching {field}={value} ' \
f'with {field_to_update}={new_value}.'
except IntegrityError as integrity_error:
self._db_session.rollback()
return f'{str(integrity_error)}'
def delete(self, name):
try:
self.model.delete_by_name(name=name, session=self._db_session)
self._db_session.commit()
return f'Successfully deleted record with name={name}.'
except IntegrityError as integrity_error:
self._db_session.rollback()
return f'{str(integrity_error)}'
</code></pre>
<p>encryption.py</p>
<pre class="lang-py prettyprint-override"><code>import base64
import hashlib
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def generate_hash_key(master_password):
return hashlib.sha512(master_password.encode()).hexdigest()
def generate_key_derivation(salt, master_password):
"""Generate Fernet Key:
salt: os.urandom(16)
password: bytes
"""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(master_password.encode()))
return key
def encrypt(key, value_to_encrypt):
f = Fernet(key)
encrypted_value = f.encrypt(value_to_encrypt.encode())
return encrypted_value
def decrypt(key, encrypted_value):
f = Fernet(key)
try:
return f.decrypt(encrypted_value).decode()
except InvalidToken:
return b''
</code></pre>
<p>helpers.py</p>
<pre class="lang-py prettyprint-override"><code>from rich.console import Console
from rich.table import Table
def pp(title, data):
title = f'[bold red][u]{title}[/u][/bold red]'
table = Table(title=title, show_lines=True)
console = Console()
table.add_column("NAME", justify="center", style="magenta", no_wrap=True)
table.add_column("PASSWORD", justify="center", style="bold green", no_wrap=True)
for item in data:
table.add_row(item['name'], item['value'])
console.print(table)
</code></pre>
<p>cli.py</p>
<pre class="lang-py prettyprint-override"><code>import os
import sys
from dinopass.encryption import generate_hash_key, generate_key_derivation
from dinopass.helpers import pp
from dinopass.models import SESSION
from dinopass.views import MasterPasswordView, PasswordView
import click
SALT_LENGTH = 16
@click.group(help="Simple CLI Password Manager for personal use")
@click.pass_context
def main(ctx):
session = SESSION()
password_view = PasswordView(session)
master_password_view = MasterPasswordView(session)
if master_password_view.has_records():
master_password = click.prompt('Please enter your master password: ', hide_input=True)
hash_key = generate_hash_key(master_password)
key_derivation = generate_key_derivation(
master_password_view.salt,
master_password
)
if master_password_view.is_valid(hash_key):
ctx.obj['key_derivation'] = key_derivation
ctx.obj['password_view'] = password_view
else:
sys.exit('Invalid master password')
else:
if click.confirm(f'It looks like you do not have a master password yet. '
f'Would you like to create one now?', abort=True):
master_password = click.prompt('Please enter your master password: ', hide_input=True)
salt = os.urandom(SALT_LENGTH)
hash_key = generate_hash_key(master_password)
key_derivation = generate_key_derivation(salt, master_password)
master_password_view.create(salt=salt, hash_key=hash_key)
ctx.obj['key_derivation'] = key_derivation
ctx.obj['password_view'] = password_view
@main.command(help='List all credentials.')
@click.pass_context
def all(ctx):
password_view = ctx.obj['password_view']
key_derivation = ctx.obj['key_derivation']
data = password_view.get_all(key_derivation)
if not data:
click.echo('\n\nThere are no credentials stored yet\n\n')
pp(title='ALL CREDENTIALS', data=data)
@main.command(help='Purge all credentials.')
@click.pass_context
def purge(ctx):
if click.confirm(f'Are you sure you want to purge ALL the records?', abort=True):
password_view = ctx.obj['password_view']
password_view.purge()
click.echo('\n\nALL the records have been deleted!\n\n')
@main.command(help='Create a new password with a specific name.')
@click.option('--name', prompt=True, help='Name of the password.')
@click.option('--password', prompt=True, hide_input=True, help='Your new password.')
@click.pass_context
def create(ctx, name: str, password: str):
password_view = ctx.obj['password_view']
key_derivation = ctx.obj['key_derivation']
record = password_view.create(key_derivation, name, password)
if hasattr(record, 'name'):
click.echo(f'\n\nSuccessfully created record with name={name}\n\n')
else:
click.echo(f'\n\n{record["error"]}\n\n')
@main.command(help='Get a specific credential by name.')
@click.option('--name', prompt=True, help='Name of the password.')
@click.pass_context
def get(ctx, name: str):
password_view = ctx.obj['password_view']
key_derivation = ctx.obj['key_derivation']
data = password_view.get_by_name(key_derivation, name)
if not data:
click.echo(f'\n\nThere is no record with name={name}\n\n')
return
pp(title=f'CREDENTIAL for {name}', data=data)
@main.command(help='Update a credential field matching a specific condition with a new value.')
@click.option('--field', prompt=True, help='Name of the field.')
@click.option('--value', prompt=True, help='Value of the field.')
@click.option('--field_to_update', prompt=True, help='Name of the field to update.')
@click.option('--new_value', prompt=True, help='New value')
@click.pass_context
def update(ctx, field: str, value: str, field_to_update: str, new_value: str):
password_view = ctx.obj['password_view']
key_derivation = ctx.obj['key_derivation']
password_view.update(key_derivation, field, value, field_to_update, new_value)
@main.command(help='Delete a specific credential by name.')
@click.option('--name', prompt=True, help='Name of the password.')
@click.pass_context
def delete(ctx, name: str):
if click.confirm(f'Are you sure you want to delete {name} record?', abort=True):
password_view = ctx.obj['password_view']
password_view.delete(name)
click.echo(f'The record with name={name} has been deleted!')
def start():
main(obj={})
if __name__ == '__main__':
start()
</code></pre>
<p><strong>What the code does</strong></p>
<p>This is basically a simple CLI Password manager which, via CLI, should let you manage your passwords. For this, the application needs a master password and ask for one each time you're doing an action (At first run you'll be asked to create one which is going to be saved in <code>MasterPassword</code> model. All the other credentials are going to be saved to the <code>Password</code> model.</p>
<p>The following actions can be done:</p>
<ul>
<li>List all your passwords (WARNING: It's going to be in clear text!)</li>
<li>Purge all your passwords (WARNING: This is permanent so do it at your own risk!)</li>
<li>Create a new password</li>
<li>Update an existing password</li>
<li>Retrieve an existing password (by name)</li>
<li>Delete an existing password</li>
</ul>
<p>Running a command is as simple as: </p>
<pre><code>python3 cli.py <command>
</code></pre>
<p>Or, if you've installed the app via <code>setup.py</code>:</p>
<pre><code>dinopass <command>
</code></pre>
|
[] |
[
{
"body": "<p>Looks like you got a good start, but there's plenty left to improve. Considering you're doing this as a one-man project, I imagine there will always be minor issues.</p>\n<p>First of all, initial set-up. On a fresh, barebones Python installation your program will miss a lot of dependencies. It looks like some of those will be hauled in during the installation, but not completely:</p>\n<p><code>cryptography</code> has a tricky installation, possibly due to requiring Microsoft Visual C++ as an external dependency itself.</p>\n<p><code>sqlalchemy typing-extensions pygments colorama commonmark pprintpp psycopg2</code> were still missing after the set-up as well.</p>\n<p>There's inconsistent use of interpunction in your usermessages and I haven't found a method of destroying the master record completely (<code>purge</code> removes everything but the master password). When trying to pass arguments to the commands like the usage example, it ignores the arguments, asks for the parameters anyway like when not passing getting passed any arguments and then fails for no reason but having unexpected arguments.</p>\n<pre><code>>dinopass create NewUser Passw3\nPlease enter your master password: :\nName:\nName:\nName: NewUser\nPassword:\nUsage: dinopass create [OPTIONS]\nTry 'dinopass create --help' for help.\n\nError: Got unexpected extra arguments (NewUser Passw3)\n</code></pre>\n<p>Note that the usage guide states:</p>\n<pre><code>Usage: dinopass [OPTIONS] COMMAND [ARGS]...\n</code></pre>\n<p>Turns out the arguments are <em>named</em>.</p>\n<pre><code>>dinopass create --help\nPlease enter your master password: :\nUsage: dinopass create [OPTIONS]\n\n Create a new password with a specific name.\n\nOptions:\n --name TEXT Name of the password.\n --password TEXT Your new password.\n --help Show this message and exit.\n</code></pre>\n<p>That could've been more explicit, I guess. Do note that it requires a master password just to get to the <code>--help</code> of a command. You know, the password that can't be purged. So the UX could use a bit of work.</p>\n<p>Now, the code.</p>\n<p>You have the <code>PasswordMixin</code>, <code>Password</code> and <code>MasterPassword</code> in the same file. That's good. They're all very much tied together. I'm not sure <code>models.py</code> is the best name for it, but it will definitely suffice. Good use of decorators too. Is it worth having <code>PasswordMixin</code> just for the two other classes? I think so. Classes usually grow in size faster than they shrink again, so the value may become even greater in time. It's a great way of keeping things simpler and not repeating yourself.</p>\n<p>The next file is called <code>helpers.py</code>. With a function called <code>pp</code>. <code>pp</code> is a terrible name. What are you doing here, redefining prettyprint? It handles the printing of the data table, but you can't tell by the name of the function.</p>\n<pre><code>def pp(title, data):\n title = f'[bold red][u]{title}[/u][/bold red]'\n table = Table(title=title, show_lines=True)\n</code></pre>\n<p>That's 5 <code>title</code> in 3 lines of code and it's actually 2 variations. You're redefining <code>title</code> here. Perhaps one of them could be named better to differentiate between them.</p>\n<p>You got a decent separation of concerns going on between your files. However, I do think checking for the <code>IntegrityError</code> should be part of the <code>MasterPassword</code> class itself and not of the <code>MasterPasswordViewer</code>. The viewer shouldn't be concerned with something relatively low-level like that. But moving it is going to be non-trivial. Almost like your viewer is doing too much already.</p>\n<p>The encryption definitely isn't the worst I've seen with hobby projects so I wouldn't worry too much about that at the moment. The usage of <code>click</code> is sensible too. It saves you a lot of boilerplate, that's usually a good thing with projects like this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T17:51:52.587",
"Id": "478710",
"Score": "0",
"body": "To expand on \"were still missing after the set-up as well.\" It is possible to test this by simply using Tox/Nox as they setup a new virtual environment as part of the testing procedure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T18:19:33.093",
"Id": "478712",
"Score": "1",
"body": "@Peilonrayz Feel free to expand on that in an answer. I've lined it up, you bring it home."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T17:32:39.600",
"Id": "243871",
"ParentId": "243095",
"Score": "5"
}
},
{
"body": "<p>This is an expansion of <a href=\"https://codereview.stackexchange.com/a/243871\">@Mast's great answer</a>.</p>\n<blockquote>\n<p><code>sqlalchemy typing-extensions pygments colorama commonmark pprintpp psycopg2</code> were still missing after the set-up as well.</p>\n</blockquote>\n<p>Whilst when I installed it just now, I got most of these packages I didn't have <code>psycop2</code>. This is coming from an improperly configured setuptools package. We can see neither <code>setup.py</code> or <code>requirements.txt</code> have all of these packages listed.</p>\n<p>You can test for this by using <a href=\"https://pypi.org/project/tox/\" rel=\"nofollow noreferrer\">Tox</a> or <a href=\"https://pypi.org/project/nox/\" rel=\"nofollow noreferrer\">Nox</a>. This is because both build a virtualenv for each test environment. Whilst this is primarily to be able to test one project over multiple Python versions, it has the benefit of being able to test your package before deployment. If you use a <code>src</code> layout then you can only import your code from the installed package, rather than from the current working directory. Meaning you can test if the built package works and contains all the information you need. This is useful if you're deploying assets with your Python package and need to test that they are built and deployed correctly.</p>\n<p>As a contributor to Nox I'm more familiar with it then Tox and so I'll be focusing on that. But they both work in a similar way, it just comes down to which configuration file you want to use Python or an INI.</p>\n<ol>\n<li><p>We need to have a unit test. This can simply just be an <code>assert True</code>.</p>\n</li>\n<li><p>We have to import your package and hope it imports all the needed imports. As your tests grow to cover all of your files (not lines of code) then all imports should be hit and this will be properly tested.</p>\n</li>\n<li><p>We get <a href=\"https://docs.pytest.org/en/latest/\" rel=\"nofollow noreferrer\">pytest</a> or <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unittest</a> to run stand alone.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>$ pytest\n</code></pre>\n</li>\n<li><p>We build the Tox/Nox file running the single command from ¶3</p>\n</li>\n</ol>\n<p><code>tests/test_dinopass.py</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>import dinopass\n\n\ndef test_dinopass():\n assert True\n</code></pre>\n<p><code>noxfile.py</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>import nox\n\n\n@nox.session()\ndef test(session):\n session.install("-e", ".")\n session.install("pytest")\n session.run("pytest")\n</code></pre>\n<p>Now you can just test your packages are installed correctly by using <code>nox</code>. Later you can add more tests and also run these just from one <code>nox</code> call. Personally <a href=\"https://github.com/Peilonrayz/skeleton_py/blob/master/noxfile.py\" rel=\"nofollow noreferrer\">I use <code>nox</code> to run all tests, coverage, linters, hinters and documentation</a>. Integration with CI tools is then super simple. For example my <a href=\"https://github.com/Peilonrayz/skeleton_py/blob/master/.travis.yml\" rel=\"nofollow noreferrer\"><code>.travis.yml</code></a> just builds the test matrix and simply calls <code>nox</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T19:44:43.603",
"Id": "243877",
"ParentId": "243095",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243871",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T10:31:29.133",
"Id": "243095",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"console",
"sqlalchemy"
],
"Title": "Follow Up DinoPass - CLI Password Manager"
}
|
243095
|
<p>With a specific requirement of showing/hiding the pages, the following implementation has been carried out.</p>
<p>The pages which needs to be hidden will be provided through an array </p>
<pre><code>this.unshowPages = ['menuPage', 'aboutusPage','linkedInPage'];
</code></pre>
<p>The corresponding HTML file,</p>
<pre><code> <ng-container *ngIf="showaboutPages">
<li>
<a routerLink="#" routerLinkActive="active">
About us Page
</a>
</li>
</ng-container>
<ng-container *ngIf="showlkdPages">
<li>
<a routerLink="#" routerLinkActive="active">
LinkedIN Page
</a>
</li>
</ng-container>
</code></pre>
<p>The ts file will be </p>
<pre><code>unshowPages= [];
showMenuPages: boolean = true;
showaboutPages: boolean = true;
showlkdPages: boolean = true;
ngOnInit() {
//this.unshowPages = ['menuPage', 'aboutusPage','linkedInPage'];
this.unshowPages = ['menuPage'];
this.unshowPages.forEach((x:string)=> {
console.log(x)
switch(x){
case 'menuPage': this.showMenuPages = false; break;
case 'aboutusPage': this.showaboutPages = false; break;
case 'linkedInPage': this.showlkdPages = false; break;
}
});
</code></pre>
<p>The problem comes here is when pages gets updated, the switch case should be modified to adapt new pages. Is there any optimized way to achieve this.</p>
<p>The minimal reproducible working code : <a href="https://stackblitz.com/edit/angular-ivy-1antde" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-1antde</a></p>
|
[] |
[
{
"body": "<p>To handle such dynamic cases, you need to have dynamic code in both <code>ts</code> and <code>html</code> side.<a href=\"https://stackblitz.com/edit/angular-ivy-p4cyne?file=src/app/app.component.ts\" rel=\"noreferrer\">Take a look at this demo code</a> which can be refactored furthur.</p>\n\n<p>Here we have changed <strong>HTML</strong> </p>\n\n<pre><code> <ul>\n <ng-container *ngFor=\"let page of pages\">\n <li *ngIf=\"page.showDOM\">\n <a routerLink=\"page.routing\" routerLinkActive=\"active\">\n {{page.title}}\n </a>\n </li>\n </ng-container>\n </ul>\n</code></pre>\n\n<p>and similarly we created a dynamic array </p>\n\n<pre><code>pages = [\n {\n id: 'menuPage',\n routing: '#',\n title: 'Menu Pages',\n showDOM: true\n },\n {\n id: 'aboutusPage',\n routing: '#',\n title: 'About US Pages',\n showDOM: true\n },\n {\n id: 'linkedInPage',\n routing: '#',\n title: 'LinkedIn Pages',\n showDOM: true\n }\n]\n</code></pre>\n\n<p>It's still in a very crude format because your case will surely require more things from it. But this would help you to get the idea on how you should proceed. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T12:24:31.527",
"Id": "477570",
"Score": "0",
"body": "Thank you , Will try your implementation :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:50:04.143",
"Id": "243106",
"ParentId": "243102",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "243106",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T13:11:35.390",
"Id": "243102",
"Score": "6",
"Tags": [
"javascript",
"html",
"typescript",
"angular-2+"
],
"Title": "Code Refactoring for Dynamic List in Angular 8"
}
|
243102
|
<p>I applied for Junior Java Developer in some company.
Got a task:"Listing words (without duplicates) from text, provide lines where appears, count them."
Output should looks like:</p>
<p>Alphacoronavirus - 3 - pozycje -> [1,3,2]</p>
<p>gatunki - 4 - pozycje -> [1,3,2,7]</p>
<p>Koronawirusy - 2 - pozycje -> [3,2]</p>
<p>Wirusów - 1 - pozycje -> [1]</p>
<p>Did not receive any feedback form them for two weeks so i will ask for judgment here.
Waiting for roast</p>
<p>Data structure:</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
public class PatternStats implements Comparable<PatternStats>{
private String word;
private int amountOfAppearances = 1;
private List<Integer> linesContains = new ArrayList<>();
public PatternStats(String word){
this.word = word;
}
public String getWord() {
return word;
}
public int getAmountOfAppearances() {
return amountOfAppearances;
}
public List<Integer> getLinesContains() {
return linesContains;
}
public void increaseAOA(){
this.amountOfAppearances++;
}
public void addLineToList(int lineNO){
this.linesContains.add(lineNO);
}
@Override
public int compareTo(PatternStats o) {
int compareInt = this.word.toLowerCase().compareTo(o.word.toLowerCase());
if(compareInt < 0) return -1;
if(compareInt > 0) return 1;
return 0;
}
}
</code></pre>
<p>WordLister</p>
<pre><code>import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordListingWithMap {
private Map<String, PatternStats> patternStatsMap = new HashMap<>();
public List<PatternStats> listWords(String filePath) {
patternStatsMap.clear();
String regex = "\\b[^\\d\\P{L}]+\\b";
try {
FileInputStream fis = new FileInputStream(filePath);
Scanner sc = new Scanner(fis);
scanTextCollectWords(sc, regex);
} catch (IOException e) {
e.printStackTrace();
}
List<PatternStats> patternStats = new ArrayList<>(patternStatsMap.values());
Collections.sort(patternStats);
return patternStats;
}
private void scanTextCollectWords(Scanner sc, String regex) {
int lineCounter = 0;
while (sc.hasNextLine()){
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sc.nextLine());
lineCounter++;
while (m.find()) {
if (patternStatsMap.containsKey(m.group(0))) {
increaseExist(m.group(0), lineCounter);
} else {
createNewAddToMap(m.group(0), lineCounter);
}
}
}
}
private void createNewAddToMap(String word, int line) {
PatternStats tempPatternStats = new PatternStats(word);
tempPatternStats.addLineToList(line);
patternStatsMap.put(word, tempPatternStats);
}
private void increaseExist(String word, int line) {
if (!patternStatsMap.get(word).getLinesContains().contains(line))
patternStatsMap.get(word).addLineToList(line);
patternStatsMap.get(word).increaseAOA();
}
}
</code></pre>
<p>and Main</p>
<pre><code>import java.util.List;
public class Main {
public static void main(String[] args) {
final String filePatch = "C:\\vaTast\\src\\zadanie.txt";
WordListingWithMap wlwm = new WordListingWithMap();
toPrint = wlwm.listWords(filePatch);
for (PatternStats each : toPrint){
System.out.println(each.getWord() + " - " +
each.getAmountOfAppearances() + " - pozycje - > " +
each.getLinesContains());
}
}
}
</code></pre>
<p>repo: <a href="https://github.com/krukarkonrad/vaRepo/" rel="nofollow noreferrer">https://github.com/krukarkonrad/vaRepo/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T20:44:18.900",
"Id": "477244",
"Score": "0",
"body": "Welcome to Code Review, I have a question : words like Apple and apple are considered equal ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T08:06:04.703",
"Id": "477261",
"Score": "0",
"body": "I asked company the same(while sending repo), didn't get any answare.\nImo it's just to add .toLowerCase() in right place"
}
] |
[
{
"body": "<p>Your code and output are correct, for me there is a hint in the description of the task :</p>\n\n<blockquote>\n <p>Listing words (without duplicates) from text, provide lines where\n appears, count them.</p>\n</blockquote>\n\n<p>For me the words <em>without duplicates</em> mean that a structure like <code>Set</code> well adapts to the constraint so instead of:</p>\n\n<blockquote>\n<pre><code>public class PatternStats implements Comparable<PatternStats>{\n private String word;\n private int amountOfAppearances = 1;\n private List<Integer> linesContains = new ArrayList<>();\n}\n</code></pre>\n</blockquote>\n\n<p>you could define the <code>PatternStats</code> class the following way:</p>\n\n<pre><code>public class PatternStats implements Comparable<PatternStats>{\n private int amountOfAppearances;\n private SortedSet<Integer> linesContains; \n private String word;\n\n public PatternStats(String word){\n this.amountOfAppearances = 1;\n this.linesContains = new TreeSet<>();\n this.word = word;\n }\n\n ...other methods\n}\n</code></pre>\n\n<p>Your comparing method:</p>\n\n<pre><code>@Override\npublic int compareTo(PatternStats o) {\n int compareInt = this.word.toLowerCase().compareTo(o.word.toLowerCase());\n if(compareInt < 0) return -1;\n if(compareInt > 0) return 1;\n return 0;\n}\n</code></pre>\n\n<p>can be rewritten in this way using <code>compareToIgnoreCase</code>:</p>\n\n<pre><code>@Override\npublic int compareTo(PatternStats o) {\n return word.compareToIgnoreCase(o.word);\n}\n</code></pre>\n\n<p>You can override the <code>toString</code> method returning the output you expect so your class can be rewritten in this way :</p>\n\n<p><strong>PatternStats.java</strong></p>\n\n<pre><code>public class PatternStats implements Comparable<PatternStats>{\n private int amountOfAppearances;\n private SortedSet<Integer> linesContains; \n private String word;\n\n public PatternStats(String word){\n this.amountOfAppearances = 1;\n this.linesContains = new TreeSet<>();\n this.word = word;\n }\n\n public String getWord() {\n return word;\n }\n\n public int getAmountOfAppearances() {\n return amountOfAppearances;\n }\n\n public SortedSet<Integer> getLinesContains() {\n return linesContains;\n }\n\n public void increaseAOA(){\n ++amountOfAppearances;\n }\n\n public void addLineToSet(int lineNO){\n this.linesContains.add(lineNO);\n }\n\n @Override\n public int compareTo(PatternStats o) {\n return word.compareToIgnoreCase(o.word);\n }\n\n @Override\n public String toString() {\n return String.format(\"%s - %d - pozycje - > %s\", word, amountOfAppearances, linesContains);\n }\n\n}\n</code></pre>\n\n<p>In your class <code>WordListingWithMap</code> you are reading a file line by line compiling and using the same regex for every line to match words: you can compile the regex one time like below:</p>\n\n<pre><code>public class WordListingWithMap {\n private static final String REGEX = \"\\\\b[^\\\\d\\\\P{L}]+\\\\b\";\n private static final Pattern PATTERN = Pattern.compile(REGEX);\n private int lineCounter;\n private Map<String, PatternStats> patternStatsMap;\n\n public WordListingWithMap() {\n this.patternStatsMap = new HashMap<>();\n this.lineCounter = 1;\n }\n\n ...other methods\n}\n</code></pre>\n\n<p>Instead of reading a file using a <code>FileInputStream</code> you can use the <code>Files</code> class to make the code shorter like below:</p>\n\n<p><strong>WordListingWithMap.java</strong></p>\n\n<pre><code>public class WordListingWithMap {\n private static final String REGEX = \"\\\\b[^\\\\d\\\\P{L}]+\\\\b\";\n private static final Pattern PATTERN = Pattern.compile(REGEX);\n private int lineCounter;\n private Map<String, PatternStats> patternStatsMap;\n\n public WordListingWithMap() {\n this.patternStatsMap = new HashMap<>();\n this.lineCounter = 1;\n }\n\n public List<PatternStats> listWords(String filePath) {\n try(Stream<String> lines = Files.lines(Paths.get(filePath))) {\n lines.forEach(l -> scanTextCollectWords(l, lineCounter++)); \n } catch (IOException e) {\n e.printStackTrace();\n }\n List<PatternStats> patternStats = new ArrayList<>(patternStatsMap.values());\n Collections.sort(patternStats);\n return patternStats;\n }\n\n private void scanTextCollectWords(String line, int lineCounter) {\n Matcher m = PATTERN.matcher(line);\n\n while (m.find()) {\n String word = m.group(0);\n if (patternStatsMap.containsKey(word)) {\n increaseExist(word, lineCounter);\n } else {\n createNewAddToMap(word, lineCounter);\n }\n }\n }\n\n private void createNewAddToMap(String word, int line) {\n PatternStats tempPatternStats = new PatternStats(word);\n tempPatternStats.addLineToSet(line);\n patternStatsMap.put(word, tempPatternStats);\n }\n\n private void increaseExist(String word, int line) {\n patternStatsMap.get(word).addLineToSet(line);\n patternStatsMap.get(word).increaseAOA();\n }\n}\n</code></pre>\n\n<p>Your <code>Main</code> class can be rewritten in this way:</p>\n\n<p><strong>Main.java</strong></p>\n\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n final String filePath = \"zadanie.txt\";\n\n WordListingWithMap wlwm = new WordListingWithMap();\n wlwm.listWords(filePath).forEach(System.out::println);\n }\n}\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:27:01.260",
"Id": "477330",
"Score": "0",
"body": "Holy Moly!\nDidn't expect that! Thank You! For sure I will learn sth more by this answer!\nBTW: Overall what do you think about my solution as a Junior Dev assignment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:53:53.473",
"Id": "477334",
"Score": "1",
"body": "@Konrad You are welcome. Your code is certainly correct and for me your solution is surely good as a Junior Dev assignment. The only advice I can give you is to check std library if functions you need are already implemented to make the code shorter, for me your solution you would have passed the test without any effort."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T14:54:21.393",
"Id": "243175",
"ParentId": "243108",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243175",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T14:14:41.597",
"Id": "243108",
"Score": "3",
"Tags": [
"java",
"strings",
"regex"
],
"Title": "Listing words from text, provide lines where appears, count them"
}
|
243108
|
<p>I have the following function which works properly and returns all of the rows from a specific table, then loops through each row to add data related to it as a subarray.</p>
<pre><code>public function fetch_products() {
$return = $this->db->all("SELECT * FROM consumables_products");
foreach($return as &$r) {
$r['consumables'] = $this->db->all("SELECT A.*, B.description FROM consumables_product_consumables as A, consumables_consumables as B WHERE product_id=? AND B.uid=A.consum_id", [$r['uid']]);
}
return $return;
}
</code></pre>
<p>The result looks like this:</p>
<pre><code>Array
(
[0] => Array
(
[uid] => 1
[description] => Test
[consumables] => Array
(
[0] => Array
(
[uid] => 1
[consum_id] => 186
[product_id] => 1
[amount] => 5
[description] => 3 X 1" GREEN Direct Thermal
)
[1] => Array
(
[uid] => 2
[consum_id] => 185
[product_id] => 1
[amount] => 1
[description] => 3 X 1" ORANGE Direct Thermal
)
)
)
)
</code></pre>
<p>This could get very inefficient with hundreds or thousands of rows in my <code>consumables_products</code> table, and an unknown number of rows in the <code>consumables_product_consumables</code> table.</p>
<p>I'm wondering if there is a way that I can do this in a single query, so that I don't have to do a separate call for every row in my <code>consumables_products</code> table.</p>
|
[] |
[
{
"body": "<p>A single query could be used to get all results. This would require formatting the results differently...</p>\n<p>The table <code>consumables_products</code> could be added as a (n INNER) JOIN.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>JOIN consumables_products P on P.uid = A.product_id --or is it B. product_id instead of A.uid??\n</code></pre>\n<p>The implicit join on <code>consumables_consumables</code> could also be written in a similar fashion.</p>\n<pre><code>$results = $this->db->all("SELECT P.uid as productUid, P.description as productDesc, A.*, B.description \n FROM consumables_product_consumables as A\n JOIN consumables_consumables as B ON B.uid = A.consum_id\n JOIN consumables_products P on P.uid = A.product_id\n");\n</code></pre>\n<p>From there <a href=\"https://www.php.net/array_reduce\" rel=\"nofollow noreferrer\"><code>array_reduce()</code></a> (or else a <code>foreach</code> loop) could be used to return the data in the specified format:</p>\n<p><strong>Note</strong> this is untested code...</p>\n<pre><code>return array_values(array_reduce(function($carry, $row) {\n $key = $row['productUid'];\n if (!isset($carry[$key])) {\n $carry[$key] = [\n 'uid' => $row['productUid'],\n 'description' => $row['productDesc'],\n 'consumables' => []\n ];\n } \n $carry[$key]['consumables'][] = array_diff_key($row, array_flip(['productUid', 'productDesc']));\n return $carry;\n}, []));\n</code></pre>\n<p>That <code>array_flip(['productUid', 'productDesc'])</code> could be stored in a variable outside the loop though it would need to be brought in using a <code>use</code> statement or if PHP 7.4+ is used then an <a href=\"https://www.php.net/manual/en/functions.arrow.php\" rel=\"nofollow noreferrer\">arrow function</a> could be used, which would allow use of that variable without the need for a <code>use</code> statement.</p>\n<p>e.g.</p>\n<pre><code>$keysToUnset = array_flip(['productUid', 'productDesc']);\nreturn array_values(array_reduce(function($carry, $row) {\n ...\n $carry[$key]['consumables'][] = array_diff_key($row, $keysToUnset);\n return $carry;\n}, []));\n</code></pre>\n<hr />\n<p>Also consider if all fields from <code>consumables_product_consumables</code> are needed. If not, select only the fields needed in order to minimized the returned data set.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T19:57:01.080",
"Id": "477144",
"Score": "0",
"body": "This doesn't seem to work. See, consumables_product_consumables can have 1+ rows associated with the UID from the first table. Your answer seems to only return one of these rows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T20:47:55.290",
"Id": "477149",
"Score": "0",
"body": "Oops I made a mistake with the JOIN condition for `consumables_products` - it should be either `P.uid = A.product_id` or `P.uid = B.product_id`, depending on where that product_id field is. Please see revised answer, which also has a shorter method for adding consumables to the list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T18:12:59.957",
"Id": "243119",
"ParentId": "243109",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243119",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T14:33:09.483",
"Id": "243109",
"Score": "1",
"Tags": [
"php",
"sql",
"mysql",
"pdo",
"iteration"
],
"Title": "Reduce database touches for one to many data pull"
}
|
243109
|
<p>I have the below code for a A* pathfinder, however it is taking upwards of 10 minutes to find a solution using a simple 1024 x 1024 array. </p>
<p>I had to comment out <code>//Collections.sort(this.openList);</code> as it was throwing a <code>comparison method violates its general contract!</code> error when running.</p>
<p>Is the algorithm correct and any idea why the bottleneck? Some people using C++ are getting a response time of 40ms, not 10+ mins!</p>
<pre><code>import java.util.List;
import javax.imageio.ImageIO;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
class AStarPathfinding {
// Closed list, open list and calculatedPath lists
private final List<Node> openList;
private final List<Node> closedList;
private final List<Node> calcPath;
// Collision Map to store tha map in
private final int[][] collisionMap;
// Current node the program is executing
private Node currentNode;
// Define the start and end coords
private final int xstart;
private final int ystart;
private int xEnd, yEnd;
// Node class for convenience
static class Node implements Comparable {
public Node parent;
public int x, y;
public double g;
public double h;
Node(Node parent, int xpos, int ypos, double g, double h) {
this.parent = parent;
this.x = xpos;
this.y = ypos;
this.g = g;
this.h = h;
}
// Compare f value (g + h)
@Override
public int compareTo(Object o) {
Node that = (Node) o;
return (int)((this.g + this.h) - (that.g + that.h));
}
}
// construct and initialise
AStarPathfinding(int[][] collisionMap, int xstart, int ystart) {
this.openList = new ArrayList<>();
this.closedList = new ArrayList<>();
this.calcPath = new ArrayList<>();
this.collisionMap = collisionMap;
this.currentNode = new Node(null, xstart, ystart, 0, 0);
this.xstart = xstart;
this.ystart = ystart;
}
// returns a List<> of nodes to target
public List<Node> findPathTo(int xTo, int yTo) {
this.xEnd = xTo;
this.yEnd = yTo;
// Add this to the closed list
this.closedList.add(this.currentNode);
// Add neighbours to openList for iteration
addNeigborsToOpenList();
// Whilst not at our target
while (this.currentNode.x != this.xEnd || this.currentNode.y != this.yEnd) {
// If nothing in the open list then return with null - handled in error message in main calling func
if (this.openList.isEmpty()) {
return null;
}
// get the lowest f value and add it to the closed list, f calculated when neighbours are sorted
this.currentNode = this.openList.get(0);
this.openList.remove(0);
this.closedList.add(this.currentNode);
addNeigborsToOpenList();
}
// add this node to the calculated path
this.calcPath.add(0, this.currentNode);
while (this.currentNode.x != this.xstart || this.currentNode.y != this.ystart) {
this.currentNode = this.currentNode.parent;
this.calcPath.add(0, this.currentNode);
}
return this.calcPath;
}
// Searches the current list for neighbouring nodes returns bool
private static boolean checkNeighbourHasBeenSearched(List<Node> array, Node node) {
return array.stream().anyMatch((n) -> (n.x == node.x && n.y == node.y));
}
// Calculate distance from current node to the target
private double distance(int dx, int dy) {
return Math.hypot(this.currentNode.x + dx - this.xEnd, this.currentNode.y + dy - this.yEnd); // return hypothenuse
}
// Add neighbouring nodes to the open list to iterate through next
@SuppressWarnings("unchecked")
private void addNeigborsToOpenList() {
Node node;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
node = new Node(this.currentNode, this.currentNode.x + x, this.currentNode.y + y, this.currentNode.g, this.distance(x, y));
// if we are not on the current node
if ((x != 0 || y != 0)
&& this.currentNode.x + x >= 0 && this.currentNode.x + x < this.collisionMap[0].length // check collision map boundaries
&& this.currentNode.y + y >= 0 && this.currentNode.y + y < this.collisionMap.length
&& this.collisionMap[this.currentNode.y + y][this.currentNode.x + x] != -1) { // check if tile is walkable (-1)
// and finally check we haven't already searched the nodes
if(!checkNeighbourHasBeenSearched(this.openList, node) && !checkNeighbourHasBeenSearched(this.closedList, node)){
node.g = node.parent.g + 1.; // Horizontal/vertical cost = 1.0
node.g += collisionMap[this.currentNode.y + y][this.currentNode.x + x]; // add movement cost for this square
// Add diagonal movement cost sqrt(hor_cost² + vert_cost²) + 0.4
if (x != 0 && y != 0) {
node.g += .4;
}
// Add the node to the List<>
this.openList.add(node);
}
}
}
}
// sort in ascending order
//Collections.sort(this.openList);
}
public static void main(String[] args) {
// Define the size of the grid
final int sizeOf = 1024;
int[][] collisionMap = new int[sizeOf][];
for(int i=0;i < sizeOf; i++) {
// -1 = blocked
// 0+ = cost
collisionMap[i] = new int[sizeOf];
}
// set the value of the nodes
for (int k = 0; k < sizeOf; k++) {
for (int j = 0; j < sizeOf; j++) {
if(j == 0 && k < 100) {
collisionMap[k][j] = -1;
} else if (j == 50 && k > 230) {
collisionMap[k][j] = -1;
}else {
collisionMap[k][j] = 0;
}
}
}
AStarPathfinding as = new AStarPathfinding(collisionMap, 103, 300);
List<Node> path = as.findPathTo(0,0);
if(path == null) {
System.out.println("Unable to reach target");
}
// create image buffer to write output to
BufferedImage img = new BufferedImage(sizeOf, sizeOf, BufferedImage.TYPE_INT_RGB);
// Set colours
int r = 255;
int g = 0;
int b = 0;
int colRed = (r << 16) | (g << 8) | b;
r = 0;
g = 255;
b = 0;
int colGreen = (r << 16) | (g << 8) | b;
r = 0;
g = 0;
b = 255;
int colBlue = (r << 16) | (g << 8) | b;
r = 255;
g = 255;
b = 255;
int colWhite = (r << 16) | (g << 8) | b;
int i = 0;
int j = 0;
if (path != null) {
path.forEach((n) -> {
System.out.print("[" + n.x + ", " + n.y + "] ");
collisionMap[n.y][n.x] = 1;
});
System.out.printf("\nTotal cost: %.02f\n", path.get(path.size() - 1).g);
for (int[] maze_row : collisionMap) {
for (int maze_entry : maze_row) {
switch (maze_entry) {
// normal tile
case 0:
img.setRGB(j, i, colWhite);
break;
// final path
case 1:
img.setRGB(j, i, colBlue);
break;
// Object to avoid
case -1:
img.setRGB(j, i, colRed);
break;
// Any other value
default:
img.setRGB(j, i, colGreen);
}
j++;
}
// count j - reset as if it were a for loop
if(i != sizeOf-1) {
j=0;
}
i++;
System.out.println();
}
}
// output file
File f = new File("aStarPath.png");
try {
ImageIO.write(img, "PNG", f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i: " + i + ", j: " + j);
}
}
</code></pre>
|
[] |
[
{
"body": "<h2><a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Single_Responsibility_Principle_SRP\" rel=\"nofollow noreferrer\">Single Responsibility</a></h2>\n\n<p>your code is a <em>little bit*)</em> monolithic, you try to do all in one class</p>\n\n<ul>\n<li>creating a map</li>\n<li>calculating path</li>\n<li>drawing images</li>\n</ul>\n\n<p>this makes it really hard to understand your code! it would greatly improve readability if you would split your code into proper classes</p>\n\n<p>*) honestly: the whole code is just <strong>ONE BIG</strong> monolith</p>\n\n<h2>programm flaws</h2>\n\n<p>you have already identified the source of your problems, it happens here</p>\n\n<pre><code>// get the lowest f value and add it to the closed list, f calculated when neighbours are sorted\nthis.currentNode = this.openList.get(0);\n</code></pre>\n\n<p>this does not work because you do not sort the list by the f-value, \nas already declared in your question. But <strong>that part is essential</strong> to have an <strong>optimized path-finding algorithm</strong>, and that is why you have performance issues. See <a href=\"https://stackoverflow.com/questions/5245093/how-do-i-use-comparator-to-define-a-custom-sort-order\">this answer</a> for some more hints on how to sort a list according to custom properties.</p>\n\n<p>instead of following your heuristic you now have programmed a <a href=\"https://en.wikipedia.org/wiki/Flood_fill\" rel=\"nofollow noreferrer\">Flood-Fill-Algorithm</a> that will inspect all fields (untill it finds the lucky target one)</p>\n\n<h2>programm flaws 2</h2>\n\n<p>when you expand your node (<code>addNeigborsToOpenList()</code>) and check the candidates, the algorithm says:</p>\n\n<blockquote>\n <p>if the path (g) is better than any previous, then add it</p>\n</blockquote>\n\n<p>but you don't check that condition:</p>\n\n<pre><code>node.g = node.parent.g + 1.; // Horizontal/vertical cost = 1.0\nnode.g += collisionMap[this.currentNode.y + y][this.currentNode.x + x]; // add movement cost for this square\n\n// Add diagonal movement cost sqrt(hor_cost² + vert_cost²) + 0.4\nif (x != 0 && y != 0) {\n node.g += .4; \n}\n\n// Add the node to the List <--WRONG HERE:\nthis.openList.add(node);\n</code></pre>\n\n<h2>summary code flaws</h2>\n\n<p>These bugs in your code prevent the efficent execution of your astar search, if you solve them your code will gain the desired performance.</p>\n\n<h2>additional performance hints</h2>\n\n<p>on top of this if you would also apply the guidance from <a href=\"https://codereview.stackexchange.com/users/58360/coderodde\">coderodde</a> to optimize the new <em>flawless</em> code.</p>\n\n<h2>other issues</h2>\n\n<p>some very basic issues</p>\n\n<ul>\n<li>use a formatter and apply the java code style rules</li>\n<li>apply java naming conventions (e.g. <code>boolean checkNeighbourHasBeenSearched()</code> should be renamed into <code>hasNeighbourHasBeenSearched()</code>)</li>\n<li>primitive obseesion - why is <code>collisionMap</code> an array of <code>int</code> - should it not be an array of <code>Field</code> where each <code>Field</code> has the attribute <code>isAccessable</code></li>\n<li>why do you suppress warnings when you could use proper data types (<code>@SuppressWarnings(\"unchecked\")</code>)?</li>\n<li><a href=\"https://clean-code-developer.com/grades/grade-4-green/#Tell_dont_ask\" rel=\"nofollow noreferrer\">tell - don't ask</a> (instead of writing comments give your methods proper names)</li>\n<li><a href=\"https://codeburst.io/software-anti-patterns-magic-numbers-7bc484f40544\" rel=\"nofollow noreferrer\">magic numbers</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T14:56:57.320",
"Id": "243269",
"ParentId": "243110",
"Score": "1"
}
},
{
"body": "<p><strong>Wrong data structures</strong></p>\n\n<p>First of all, your poor efficiency is due to the fact that you use array lists for the open and closed sets. Change the open set to <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/PriorityQueue.html\" rel=\"nofollow noreferrer\"><code>PriorityQueue</code></a> and your closed set to <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/HashSet.html\" rel=\"nofollow noreferrer\"><code>HashSet</code></a>. In order to work, you will need to overwrite <code>equals</code>, <code>hashCode</code> and <code>compareTo</code> for your class <code>Node</code>. </p>\n\n<p>If you don't mind \"picking\", you can find something relevant <a href=\"https://codereview.stackexchange.com/questions/144376/nba-very-efficient-bidirectional-heuristic-search-algorithm-in-java-follow-u\">here</a> (see AStarPathfinder.java).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T16:36:58.157",
"Id": "243272",
"ParentId": "243110",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T15:27:38.977",
"Id": "243110",
"Score": "5",
"Tags": [
"java",
"performance",
"algorithm",
"pathfinding",
"a-star"
],
"Title": "Performance Enhancement of A Star Path Finder algorithm with 1024 multidimentional array"
}
|
243110
|
<p>I have to write a simple web application using the Java Spring framework as my course project. So I decided to write a simple Stack Overflow clone. My application has the following features:</p>
<ul>
<li>Authorization (using Spring Security);</li>
<li>Posting new questions and answers;</li>
<li>Voting up/down for questions/answers.</li>
</ul>
<p>I am very new in Java, Spring, and web-backend world so I think there is much room for improvement.</p>
<hr>
<p>Some of my thoughts about problems in my Java code:</p>
<ul>
<li><p>The <a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/VotesController.java" rel="nofollow noreferrer"><code>VotesController</code></a> class consists of several almost identical methods. I know that copy-paste is bad, but I have no idea how to deal with it in this case.</p></li>
<li><p>I am not sure about naming conventions in Spring. Have I properly named controllers, entities, fields, etc.?</p></li>
<li><p><strong>I really hate the way I pass information to the Mustache templates</strong>. For example, I need to display a question's creation date in this form: <code>May 27 '20 at 15:40</code>, but if I just use <a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/Question.java#L32" rel="nofollow noreferrer"><code>Date creationDateTime</code></a> field from the <a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/Question.java" rel="nofollow noreferrer"><code>Question</code></a> entity Mustache will display it in form <code>2020-05-27 15:40:49.0</code>.</p>
<p>To solve this problem I have created the <a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/Question.java#L80" rel="nofollow noreferrer"><code>String formattedCreationDateTime</code></a> field in the <code>Question</code> entity and call the <a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/Question.java#L131" rel="nofollow noreferrer"><code>Question.formatCreationDateTime</code></a> method just before passing the question entity to Mustache.</p>
<p>And then I can <a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/resources/templates/index.mustache#L32" rel="nofollow noreferrer">use <code>formattedCreationDateTime</code> in the template</a>. It is not the single one example.</p></li>
<li><p>I also do not like the way I store votes for questions/answers. At this time I have four different join tables:</p>
<pre><code>question_vote_up(question_id, user_id)
question_vote_down(question_id, user_id)
answer_vote_up(answer_id, user_id)
answer_vote_down(answer_id, user_id)
</code></pre>
<p>I know that it would be better to create only two tables like this:</p>
<pre><code>question_vote(question_id, user_id, vote)
answer_vote(answer_id, user_id, vote)
</code></pre>
<p>But I don't know how to implement this database structure in Spring.</p></li>
</ul>
<hr>
<p>I would really appreciate any advice on how to improve my code. I would be glad to see review on my JavaScript and CSS, but it is not a priority.</p>
<p>I've published all the code in <a href="https://github.com/Eanmos/StackCanary/tree/bad73b47d1f54e9109acdceb75f000179b7f5d73" rel="nofollow noreferrer">the GitHub repository</a>.</p>
<hr>
<h2>Controllers</h2>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/AddAnswerController.java" rel="nofollow noreferrer"><strong><code>addAnswerController.java</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.controllers;
import java.util.*;
import com.sstu.StackCanary.domain.Answer;
import com.sstu.StackCanary.domain.Question;
import com.sstu.StackCanary.domain.User;
import com.sstu.StackCanary.repositories.AnswerRepository;
import com.sstu.StackCanary.repositories.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class AddAnswerController {
@Autowired
private QuestionRepository questionRepository;
@Autowired
private AnswerRepository answerRepository;
@PostMapping("/q")
public String postQuestion(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
@RequestParam String body,
Map<String, Object> model) {
// Assuming that the question with given ID always exists.
Question q = questionRepository.findById(questionId).get();
// Add new answer to the database.
answerRepository.save(new Answer(user, q, body));
// Redirect to the question page.
return "redirect:/q?id=" + questionId;
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/AskQuestionPageController.java" rel="nofollow noreferrer"><strong><code>AskQuestionPageController</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.controllers;
import java.util.*;
import com.sstu.StackCanary.domain.Question;
import com.sstu.StackCanary.domain.Tag;
import com.sstu.StackCanary.domain.User;
import com.sstu.StackCanary.repositories.QuestionRepository;
import com.sstu.StackCanary.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class AskQuestionPageController {
@Autowired
private QuestionRepository questionRepository;
@Autowired
private TagRepository tagRepository;
@GetMapping("/askQuestion")
public String main(@AuthenticationPrincipal User user,
Map<String, Object> model) {
model.put("authorizedUser", user);
return "askQuestion";
}
@PostMapping("/askQuestion")
public String postQuestion(@AuthenticationPrincipal User user,
@RequestParam String title,
@RequestParam String body,
@RequestParam("tag") String [] tagNames,
Map<String, Object> model) {
// Create empty set of tags.
HashSet<Tag> tags = new HashSet<Tag>();
// Fill this set with tags with given name from database.
// If the tag not exist create such new one.
for (String name : tagNames) {
Tag tag = tagRepository.findByName(name);
if (tag == null)
tag = new Tag(name);
tagRepository.save(tag);
tags.add(tag);
}
// Create new question and save it in the database.
Question q = new Question(user, title, body, tags);
questionRepository.save(q);
// Redirect to the new question's page.
return "redirect:/q?id=" + q.getId();
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/IndexController.java" rel="nofollow noreferrer"><strong><code>IndexController.java</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.controllers;
import java.util.Map;
import com.sstu.StackCanary.domain.Question;
import com.sstu.StackCanary.domain.User;
import com.sstu.StackCanary.repositories.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@Autowired
private QuestionRepository questionRepository;
@GetMapping
public String main(@AuthenticationPrincipal User user,
Map<String, Object> model) {
Iterable<Question> questions = questionRepository.findAll();
// Prepare transient fields
//
// — formattedCreationDateTime
// — votes
//
// that will be used in the template.
questions.forEach(Question::calculateVotes);
questions.forEach(Question::formatCreationDateTime);
model.put("questions", questions);
model.put("authorized", (user != null));
return "index";
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/QuestionPageController.java" rel="nofollow noreferrer"><strong><code>QuestionPageController</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.controllers;
import java.util.Map;
import com.sstu.StackCanary.domain.Answer;
import com.sstu.StackCanary.domain.Question;
import com.sstu.StackCanary.domain.User;
import com.sstu.StackCanary.repositories.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class QuestionPageController {
@Autowired
private QuestionRepository questionRepository;
@GetMapping("/q")
public String main(@AuthenticationPrincipal User user,
@RequestParam Integer id,
Map<String, Object> model) {
// Assuming that the question with
// given ID always exists.
Question q = questionRepository.findById(id).get();
// Prepare transient fields
//
// — formattedCreationDateTime
// — votes
// — answersCount
// — bodyInHTML
//
// that will be used in the template.
q.calculateVotes();
q.calculateAnswersCount();
q.formatCreationDateTime();
q.convertBodyFromMarkdownToHTML();
q.setVotedByActiveUser(user);
// Prepare transient fields of the each answer as well
// as we have done with the question.
q.answers.forEach(Answer::formatCreationDateTime);
q.answers.forEach(Answer::calculateVotes);
q.answers.forEach(Answer::convertBodyFromMarkdownToHTML);
q.answers.forEach(a -> a.setVotedByActiveUser(user));
model.put("question", q);
model.put("authorized", (user != null));
return "question";
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/RegistrationController.java" rel="nofollow noreferrer"><strong>RegistrationController</strong></a>:</p>
<pre><code>package com.sstu.StackCanary.controllers;
import com.sstu.StackCanary.domain.Role;
import com.sstu.StackCanary.domain.User;
import com.sstu.StackCanary.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Collections;
import java.util.Map;
@Controller
public class RegistrationController {
@Autowired
private UserRepository userRepository;
@GetMapping("/registration")
public String main(Map<String, Object> model) {
return "registration";
}
@PostMapping("/registration")
public String registerUser(User user, Map<String, Object> model) {
if (userWithThisUsernameAlreadyExists(user)) {
model.put("userWithThisUsernameAlreadyExistsMessage", "User with this username already exists.");
return "registration";
}
user.setActive(true);
user.setRoles(Collections.singleton(Role.USER));
userRepository.save(user);
return "redirect:/login";
}
private boolean userWithThisUsernameAlreadyExists(User u) {
return userRepository.findByUsername(u.getUsername()) != null;
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/controllers/VotesController.java" rel="nofollow noreferrer"><strong><code>VotesController</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.controllers;
import com.sstu.StackCanary.domain.Answer;
import com.sstu.StackCanary.domain.Question;
import com.sstu.StackCanary.domain.User;
import com.sstu.StackCanary.repositories.AnswerRepository;
import com.sstu.StackCanary.repositories.QuestionRepository;
import com.sstu.StackCanary.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
@Controller
public class VotesController {
@Autowired
private AnswerRepository answerRepository;
@Autowired
private QuestionRepository questionRepository;
@Autowired
private UserRepository userRepository;
@PostMapping("/voteUpForAnswer")
public String voteUpForAnswer(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
@RequestParam Integer answerId,
Map<String, Object> model) {
Answer answer = answerRepository.findById(answerId).get();
answer.votedUpByUsers.add(user);
answer.votedDownByUsers.remove(user);
user.voteUpForAnswer(answer);
answerRepository.save(answer);
userRepository.save(user);
return "redirect:/q?id=" + questionId;
}
@PostMapping("/undoVoteUpForAnswer")
public String undoVoteUpForAnswer(@AuthenticationPrincipal User user,
@RequestParam Integer answerId,
Map<String, Object> model) {
Answer answer = answerRepository.findById(answerId).get();
answer.votedUpByUsers.remove(user);
user.getVotedUpAnswers().remove(answer);
answerRepository.save(answer);
userRepository.save(user);
return "redirect:/q?id=" + answerId;
}
@PostMapping("/voteDownForAnswer")
public String voteDownForAnswer(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
@RequestParam Integer answerId,
Map<String, Object> model) {
Answer answer = answerRepository.findById(answerId).get();
answer.votedDownByUsers.add(user);
answer.votedUpByUsers.remove(user);
user.voteDownForAnswer(answer);
answerRepository.save(answer);
userRepository.save(user);
return "redirect:/q?id=" + questionId;
}
@PostMapping("/undoVoteDownForAnswer")
public String undoVoteDownForAnswer(@AuthenticationPrincipal User user,
@RequestParam Integer answerId,
Map<String, Object> model) {
Answer answer = answerRepository.findById(answerId).get();
answer.votedDownByUsers.remove(user);
user.getVotedDownAnswers().remove(answer);
answerRepository.save(answer);
userRepository.save(user);
return "redirect:/q?id=" + answerId;
}
@PostMapping("/voteUpForQuestion")
public String voteUpForQuestion(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
Map<String, Object> model) {
Question question = questionRepository.findById(questionId).get();
question.votedUpByUsers.add(user);
question.votedDownByUsers.remove(user);
user.voteUpForQuestion(question);
questionRepository.save(question);
userRepository.save(user);
return "redirect:/q?id=" + questionId;
}
@PostMapping("/undoVoteUpForQuestion")
public String undoVoteUpForQuestion(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
Map<String, Object> model) {
Question question = questionRepository.findById(questionId).get();
question.votedUpByUsers.remove(user);
user.getVotedUpQuestions().remove(question);
questionRepository.save(question);
userRepository.save(user);
return "redirect:/q?id=" + questionId;
}
@PostMapping("/voteDownForQuestion")
public String voteDownForQuestion(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
Map<String, Object> model) {
Question question = questionRepository.findById(questionId).get();
question.votedDownByUsers.add(user);
question.votedUpByUsers.remove(user);
user.voteDownForQuestion(question);
questionRepository.save(question);
userRepository.save(user);
return "redirect:/q?id=" + questionId;
}
@PostMapping("/undoVoteDownForQuestion")
public String undoVoteDownForQuestion(@AuthenticationPrincipal User user,
@RequestParam Integer questionId,
Map<String, Object> model) {
Question question = questionRepository.findById(questionId).get();
question.votedDownByUsers.remove(user);
user.getVotedDownQuestions().remove(question);
questionRepository.save(question);
userRepository.save(user);
return "redirect:/q?id=" + questionId;
}
}
</code></pre>
<h2>Entities</h2>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/Answer.java" rel="nofollow noreferrer"><strong><code>Answer.java</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.domain;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import javax.persistence.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
@Entity
public class Answer {
//==========================================
//
// Database Columns
//
//==========================================
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(columnDefinition = "LONGTEXT")
private String body;
@Column(name = "creationDateTime", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date creationDateTime;
//==========================================
//
// Relations
//
//==========================================
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "author")
private User author;
@ManyToOne
@JoinColumn(name = "question", nullable = false)
private Question question;
@ManyToMany
@JoinTable(
name = "answer_vote_up",
joinColumns = @JoinColumn(name = "answer_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
public Set<User> votedUpByUsers;
@ManyToMany
@JoinTable(
name = "answer_vote_down",
joinColumns = @JoinColumn(name = "answer_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
public Set<User> votedDownByUsers;
//==========================================
//
// Transient Fields
//
// This fields must be initialized manually by
// calling the corresponding entity's method.
//==========================================
@Transient
private String formattedCreationDateTime;
@Transient
public Integer votes;
@Transient
public String bodyInHTML;
@Transient
public boolean votedUpByActiveUser;
@Transient
public boolean votedDownByActiveUser;
//==========================================
//
// Constructors
//
//==========================================
protected Answer() {}
public Answer(User author, Question question, String body) {
this.author = author;
this.question = question;
this.body = body;
// Assign current date and time.
this.creationDateTime = new Date();
}
//==========================================
//
// Methods
//
//==========================================
public void formatCreationDateTime() {
DateFormat d = new SimpleDateFormat("MMM d ''yy 'at' HH:mm");
formattedCreationDateTime = d.format(creationDateTime);
}
public void calculateVotes() {
votes = votedUpByUsers.size() - votedDownByUsers.size();
}
public void convertBodyFromMarkdownToHTML() {
Node document = Parser.builder().build().parse(body);
HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
bodyInHTML = renderer.render(document);
}
public void setVotedByActiveUser(User user) {
if (user == null) {
this.votedUpByActiveUser = false;
this.votedDownByActiveUser = false;
} else if (user.getVotedUpAnswers().contains(this)) {
this.votedUpByActiveUser = true;
this.votedDownByActiveUser = false;
} else if (user.getVotedDownAnswers().contains(this)) {
this.votedUpByActiveUser = false;
this.votedDownByActiveUser = true;
} else {
this.votedUpByActiveUser = false;
this.votedDownByActiveUser = false;
}
}
@Override
public boolean equals(Object that) {
if (this == that)
return true;
if (!(that instanceof Answer))
return false;
Answer thatAnswer = (Answer) that;
return this.id.equals(thatAnswer.id);
}
@Override
public int hashCode() {
final int PRIME = 37;
return PRIME * id.hashCode();
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/Question.java" rel="nofollow noreferrer"><strong><code>Question.java</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.domain;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import javax.persistence.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
@Entity
public class Question {
//==========================================
//
// Database Columns
//
//==========================================
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
@Column(columnDefinition = "LONGTEXT")
private String body;
@Column(name = "creationDateTime", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date creationDateTime;
//==========================================
//
// Relations
//
//==========================================
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "author")
private User author;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "question_tag",
joinColumns = @JoinColumn(name = "question_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private Set<Tag> tags;
@OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
public Set<Answer> answers;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "question_vote_up",
joinColumns = @JoinColumn(name = "question_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
public Set<User> votedUpByUsers;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "question_vote_down",
joinColumns = @JoinColumn(name = "question_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
public Set<User> votedDownByUsers;
//==========================================
//
// Transient Fields
//
// This fields must be initialized manually by
// calling the corresponding entity's method.
//==========================================
@Transient
public String formattedCreationDateTime;
@Transient
public Integer votes;
@Transient
public Integer answersCount;
@Transient
public String bodyInHTML;
@Transient
public boolean votedUpByActiveUser;
@Transient
public boolean votedDownByActiveUser;
//==========================================
//
// Constructors
//
//==========================================
protected Question() {}
public Question(User author, String title, String body, Set<Tag> tags) {
this.author = author;
this.title = title;
this.body = body;
this.tags = tags;
// Assign current date and time.
this.creationDateTime = new Date();
}
//==========================================
//
// Getters and Setters
//
//==========================================
public Integer getId() {
return id;
}
//==========================================
//
// Methods
//
//==========================================
public void formatCreationDateTime() {
DateFormat d = new SimpleDateFormat("MMM d ''yy 'at' HH:mm");
formattedCreationDateTime = d.format(creationDateTime);
}
public void calculateVotes() {
votes = votedUpByUsers.size() - votedDownByUsers.size();
}
public void calculateAnswersCount() {
answersCount = this.answers.size();
}
public void convertBodyFromMarkdownToHTML() {
Node document = Parser.builder().build().parse(body);
HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
bodyInHTML = renderer.render(document);
}
public void setVotedByActiveUser(User user) {
if (user == null) {
this.votedUpByActiveUser = false;
this.votedDownByActiveUser = false;
} else if (user.getVotedUpQuestions().contains(this)) {
this.votedUpByActiveUser = true;
this.votedDownByActiveUser = false;
} else if (user.getVotedDownQuestions().contains(this)) {
this.votedUpByActiveUser = false;
this.votedDownByActiveUser = true;
} else {
this.votedUpByActiveUser = false;
this.votedDownByActiveUser = false;
}
}
@Override
public boolean equals(Object that) {
if (this == that)
return true;
if (!(that instanceof Question))
return false;
Question thatQuestion = (Question) that;
return this.id.equals(thatQuestion.id);
}
@Override
public int hashCode() {
final int PRIME = 37;
return PRIME * id.hashCode();
}
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/java/com/sstu/StackCanary/domain/User.java" rel="nofollow noreferrer"><strong><code>User.java</code></strong></a>:</p>
<pre><code>package com.sstu.StackCanary.domain;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Set;
@Entity
public class User implements UserDetails {
//==========================================
//
// Database Columns
//
//==========================================
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private String password;
private Boolean active;
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
@Column(name = "role")
private Set<Role> roles;
//==========================================
//
// Relations
//
//==========================================
@ManyToMany(mappedBy = "votedUpByUsers", fetch = FetchType.EAGER)
private Set<Question> votedUpQuestions;
@ManyToMany(mappedBy = "votedDownByUsers", fetch = FetchType.EAGER)
private Set<Question> votedDownQuestions;
@ManyToMany(mappedBy = "votedUpByUsers", fetch = FetchType.EAGER)
private Set<Answer> votedUpAnswers;
@ManyToMany(mappedBy = "votedDownByUsers", fetch = FetchType.EAGER)
private Set<Answer> votedDownAnswers;
//==========================================
//
// Constructors
//
//==========================================
protected User() {}
//==========================================
//
// Getters and Setters
//
//==========================================
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<Question> getVotedUpQuestions() {
return votedUpQuestions;
}
public void setVotedUpQuestions(Set<Question> votedUpQuestions) {
this.votedUpQuestions = votedUpQuestions;
}
public Set<Question> getVotedDownQuestions() {
return votedDownQuestions;
}
public void setVotedDownQuestions(Set<Question> votedDownQuestions) {
this.votedDownQuestions = votedDownQuestions;
}
public Set<Answer> getVotedUpAnswers() {
return votedUpAnswers;
}
public void setVotedUpAnswers(Set<Answer> votedUpAnswers) {
this.votedUpAnswers = votedUpAnswers;
}
public Set<Answer> getVotedDownAnswers() {
return votedDownAnswers;
}
public void setVotedDownAnswers(Set<Answer> votedDownAnswers) {
this.votedDownAnswers = votedDownAnswers;
}
@Override
public boolean equals(Object that) {
if (this == that)
return true;
if (!(that instanceof User))
return false;
User thatUser = (User) that;
return this.id.equals(thatUser.id);
}
@Override
public int hashCode() {
final int PRIME = 37;
return PRIME * id.hashCode();
}
public void voteUpForQuestion(Question q) {
votedUpQuestions.add(q);
votedDownQuestions.remove(q);
}
public void voteDownForQuestion(Question q) {
votedDownQuestions.add(q);
votedUpQuestions.remove(q);
}
public void voteUpForAnswer(Answer q) {
votedUpAnswers.add(q);
votedDownAnswers.remove(q);
}
public void voteDownForAnswer(Answer q) {
votedDownAnswers.add(q);
votedUpAnswers.remove(q);
}
//==========================================
//
// UserDetails abstract methods implementation
//
//==========================================
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return getActive();
}
}
</code></pre>
<h2>JS scripts:</h2>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/resources/static/scripts/questionAndAnswersBodyRendering.js" rel="nofollow noreferrer"><strong><code>questionAndAnswersBodyRendering.js</code></strong></a>:</p>
<pre><code>"use strict";
function renderQuestionAndAnswersBodies() {
convertQuestionBodyToHTML();
convertAnswersBodiesToHTML();
highlightCodeInQuestion();
highlightCodeInAnswers();
}
function convertQuestionBodyToHTML() {
let questionBody = document.getElementById("questionBody");
questionBody.innerHTML = replaceHTMLEntitiesWithRealCharacters(questionBody.innerHTML);
// Add support for HTML tags inside Markdown code
// that comes from the server.
for (let e of questionBody.getElementsByTagName("*"))
if (e.tagName !== "CODE" && e.tagName !== "PRE")
e.innerHTML = replaceHTMLEntitiesWithRealCharacters(e.innerHTML);
}
function convertAnswersBodiesToHTML() {
let answersBodies = document.getElementsByClassName("answerBody");
for (let a of answersBodies) {
a.innerHTML = replaceHTMLEntitiesWithRealCharacters(a.innerHTML);
// Add support for HTML tags inside Markdown code
// that comes from the server.
for (let e of a.getElementsByTagName("*"))
if (e.tagName !== "CODE")
e.innerHTML = replaceHTMLEntitiesWithRealCharacters(e.innerHTML);
}
}
function replaceHTMLEntitiesWithRealCharacters(string) {
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
string = replaceAll(string, "&lt;", "<");
string = replaceAll(string, "&gt;", ">");
// This HTML entity should be the last since
// it can affect on the other entities.
string = replaceAll(string, "&amp;", "&");
return string;
}
function highlightCodeInQuestion() {
let questionBody = document.getElementById("questionBody");
highlightCodeInsideElement(questionBody);
}
function highlightCodeInAnswers() {
let answersBodies = document.getElementsByClassName("answerBody");
for (let a of answersBodies)
highlightCodeInsideElement(a);
}
function highlightCodeInsideElement(element) {
let children = element.getElementsByTagName("*");
for (let c of children)
if (c.tagName === "CODE" && c.parentElement.tagName === "PRE")
hljs.highlightBlock(c);
}
</code></pre>
<p><a href="https://github.com/Eanmos/StackCanary/blob/master/src/main/resources/static/scripts/questionEditor.js" rel="nofollow noreferrer"><strong><code>questionEditor.js</code></strong></a>:</p>
<pre><code>"use strict";
let tagsList = [];
const MAX_TAGS_COUNT = 5;
function tagEditorInputOnInput() {
var tagEditorInput = document.getElementById("tagEditorInput");
function clearInput() {
tagEditorInput.value = "";
}
let value = tagEditorInput.value;
let length = value.length;
const firstCharacter = getStringFirstCharacter(value);
const lastCharacter = getStringLastCharacter(value);
if (tagsList.length >= MAX_TAGS_COUNT) {
clearInput();
} else if (length < 2 && firstCharacter === " ") {
clearInput();
} else if (lastCharacter === " ") {
const tagName = value.toLowerCase().trim();
tagsList.push(tagName);
clearInput();
renderTags();
updateTagInputs();
}
}
function renderTags() {
removeAllRenderedTags();
let renderedTags = document.getElementById("renderedTags");
for (let t of tagsList)
renderedTags.appendChild(createRendererTagElement(t));
}
function createRendererTagElement(tagName) {
let tag = document.createElement("span");
addClass(tag, "renderedTag");
tag.innerHTML = '<span class="tagName">' + tagName + '</span>';
tag.innerHTML += '<svg onmouseup="removeRenderedTag(this.parentElement.firstChild);" class="removeTagButton" width="14" height="14" viewBox="0 0 14 14"><path d="M12 3.41L10.59 2 7 5.59 3.41 2 2 3.41 5.59 7 2 10.59 3.41 12 7 8.41 10.59 12 12 10.59 8.41 7z"></path></svg>';
return tag;
}
function removeAllRenderedTags() {
let renderedTags = document.getElementById("renderedTags");
renderedTags.innerHTML = "";
}
function removeRenderedTag(element) {
const tagName = getFirstWordInString(element.innerHTML);
const tagIndex = tagsList.indexOf(tagName);
removeItemFromArray(tagsList, tagIndex);
renderTags();
}
function updateTagInputs() {
for (let i = 0; i < 5; ++i) {
let tag = document.getElementById("tag" + i);
if (tagsList[i] === undefined)
tag.name = "emptyTag";
else
tag.name = "tag";
tag.value = tagsList[i];
}
}
function removeLastCharacterInString(s) {
return s.substring(0, s.length - 1);
}
function getStringLastCharacter(s) {
return s.slice(s.length - 1);
}
function getStringFirstCharacter(s) {
return s[0];
}
function getFirstWordInString(s) {
const spaceIndex = s.indexOf(" ");
if (spaceIndex === -1)
return s;
else
return s.substr(0, spaceIndex);
};
function removeItemFromArray(array, index) {
array.splice(index, 1);
}
function addClass(element, className) {
element.classList.add(className);
}
function removeClass(element, className) {
if (element.classList.contains(className))
element.classList.remove(className);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:35:45.123",
"Id": "477378",
"Score": "1",
"body": "Dang, now that's a lot of files to review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T23:49:29.937",
"Id": "477522",
"Score": "0",
"body": "@eanmos, i added more feedback. take a look"
}
] |
[
{
"body": "<p><strong>General Feedback</strong></p>\n\n<ul>\n<li><p>the package 'StackCanary' can follow Java standard naming. Ref: <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html</a></p></li>\n<li><p>You do not need to type Tag on both side. Update all instances.</p></li>\n</ul>\n\n<pre><code> HashSet<Tag> tags = new HashSet<Tag>(); // not so good\n HashSet<Tag> tags = new HashSet<>(); //this is better\n Set<Tag> tags = new HashSet<>(); //this is even better\n</code></pre>\n\n<ul>\n<li>Answer and Question can be combined to a single Entity (let's name it POST) and provide a Type column ( can be Enum) to indicate the type of post. It would remove lots of duplications in your code.</li>\n</ul>\n\n<pre><code> Post {\n\n Type type;\n List<Post> answers; //only post of type 'Question' can have answers\n\n }\n</code></pre>\n\n<ul>\n<li>User entity is doing too much.\nMove votedUpQuestions, votedDownQuestions, votedUpAnswers, votedDownAnswers to a new table. Name it Vote with post_id and user_id as composite key. Just add a new record </li>\n</ul>\n\n<pre><code> Vote{\n Post post;\n User user;\n VoteType type; //can be enum so that you can add thumbs up, like, haha etc easily later\n }\n</code></pre>\n\n<ul>\n<li><p>IndexController.main()\nUse separate query to find votes. You can use caching for performance. Similar feedback on QuestionPageController</p></li>\n<li><p>Question.convertBodyFromMarkdownToHTML\nIts better to keep the entity classes as POJO.</p></li>\n<li><p>When fetching a large entity and child object, use JOIN-Fetch or @EntityGraph. Lookup N+1 problem in ORM to know more about it</p></li>\n<li><p>application.properties\nUse in-memory db like H2 so its easy to test your app. You can use Spring's @Profiles to use H2 locally and mariadb in some other profile.</p></li>\n<li><p>resources/static/**\nYou can use Webjar instead of copying javascript/css etc manually</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Regarding your questions,</strong></p>\n\n<blockquote>\n <p>The VotesController class consists of several almost identical\n methods. I know that copy-past is bad, but I have no idea how to deal\n with it in this case.</p>\n</blockquote>\n\n<ul>\n<li>You can create a VoteService and have a single method vote(User, Post, Type). You can keep your methods on controller but compose the Type parameter and delegate the call to service. If you merge Answer and Question table, lots of duplications can be avoided.</li>\n</ul>\n\n<blockquote>\n <p>I am not sure about naming conventions in Spring. Have I properly\n named controllers, entities, fields, etc?</p>\n</blockquote>\n\n<ul>\n<li>They looks good to me. You can use Constructor injection and also use Lombok to remove a lot of code. See this <a href=\"https://github.com/gtiwari333/spring-boot-web-application-seed/blob/master/core/src/main/java/gt/app/modules/bookmark/BookmarkService.java#L17\" rel=\"nofollow noreferrer\">https://github.com/gtiwari333/spring-boot-web-application-seed/blob/master/core/src/main/java/gt/app/modules/bookmark/BookmarkService.java#L17</a> for reference</li>\n</ul>\n\n<blockquote>\n <p>I really hate the way I pass information to the Mustache templates.</p>\n</blockquote>\n\n<ul>\n<li>You can either map your entity object to another POJO with String date field and return that on Controller method. Or use utilities provided by Mustache to format date while rendering. I'm not familiar with Mustache but Thymeleaf has the option. See this <a href=\"https://github.com/gtiwari333/spring-boot-web-application-seed/blob/master/core/src/main/resources/templates/article.html#L59\" rel=\"nofollow noreferrer\">https://github.com/gtiwari333/spring-boot-web-application-seed/blob/master/core/src/main/resources/templates/article.html#L59</a></li>\n</ul>\n\n<p>Finally, I noticed you are using JDK8. Is there any reason to must use JDK8? Your code runs fine with JDK11 without any update. You should try that.</p>\n\n<p>Also, you can check the following repos for a reference \n- <a href=\"https://github.com/gtiwari333/spring-boot-web-application-seed\" rel=\"nofollow noreferrer\">https://github.com/gtiwari333/spring-boot-web-application-seed</a></p>\n\n<p>--</p>\n\n<p><strong>Update 1</strong></p>\n\n<ul>\n<li><a href=\"https://github.com/Eanmos/stackcanary/commit/90a22d1477c87c9d9a3e6418861e38c77e6b3e96#diff-600376dffeb79835ede4a0b285078036R23\" rel=\"nofollow noreferrer\">https://github.com/Eanmos/stackcanary/commit/90a22d1477c87c9d9a3e6418861e38c77e6b3e96#diff-600376dffeb79835ede4a0b285078036R23</a></li>\n</ul>\n\n<p>Lombok's version is managed by Spring. You don't need to provide version here. See this for the list \n- <a href=\"https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-dependencies/build.gradle\" rel=\"nofollow noreferrer\">https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-dependencies/build.gradle</a>\n- <a href=\"https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/2.3.0.RELEASE/spring-boot-dependencies-2.3.0.RELEASE.pom\" rel=\"nofollow noreferrer\">https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/2.3.0.RELEASE/spring-boot-dependencies-2.3.0.RELEASE.pom</a></p>\n\n<p>That way you can get rid of compatibility between various libraries because Spring Boot takes care of that for you.</p>\n\n<ul>\n<li>AddAnswerController and other places</li>\n</ul>\n\n<p>Since you have Lombok in place, you can replace the following code by Constructor injection using @RequiredArgsConstructor</p>\n\n<pre><code>@Controller\npublic class AddAnswerController {\n @Autowired\n private QuestionRepository questionRepository;\n\n @Autowired\n private AnswerRepository answerRepository; \n\n\n@Controller\n@RequiredArgsConstructor\npublic class AddAnswerController { \n private final QuestionRepository questionRepository;\n private final AnswerRepository answerRepository; \n..\n</code></pre>\n\n<ul>\n<li>Don't fetch all voted*ByUsers records just to find the size. Imagine billions of Vote records per Question. You are currently fetching billions of DB records and doing size() operation just to get the count. It would be a single COUNT query on DB.\nRemember always delegate count, exists, search operation to DB. </li>\n</ul>\n\n<pre><code> public void calculateVotes() {\n votes = votedUpByUsers.size() - votedDownByUsers.size();\n }\n\n //here we are fetching all answers from DB to memory just to get the size. \n public void calculateAnswersCount() {\n answersCount = this.answers.size();\n }\n\n public void setVotedByActiveUser(User user) {\n if (user == null) {\n this.votedUpByActiveUser = false;\n this.votedDownByActiveUser = false;\n } else if (user.getVotedUpQuestions().contains(this)) { //FIX THIS\n this.votedUpByActiveUser = true;\n this.votedDownByActiveUser = false;\n } else if (user.getVotedDownQuestions().contains(this)) { //FIX THIS\n ...\n }\n\n\n</code></pre>\n\n<ul>\n<li>You can move this to a util/service class so that it will be reusable and easily unit tested </li>\n</ul>\n\n<pre><code> public void convertBodyFromMarkdownToHTML() {\n Node document = Parser.builder().build().parse(body);\n HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();\n bodyInHTML = renderer.render(document);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T10:03:20.933",
"Id": "477559",
"Score": "1",
"body": "I very appreciate your answer. You helped me a lot. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:18:42.927",
"Id": "243235",
"ParentId": "243111",
"Score": "7"
}
},
{
"body": "<p>I haven't done much Java development since I was a univeristy student 15 years ago so my assistance there will be limited. The bulk of this review will be on the JavaScript code. </p>\n\n<h2>Java</h2>\n\n<h3>Comments</h3>\n\n<p>There are single line comments used for multiple lines of text - <a href=\"https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html#format\" rel=\"nofollow noreferrer\">Doc comments</a> or <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-comments.html\" rel=\"nofollow noreferrer\">Block comments</a> could be used instead to follow common conventions.</p>\n\n<p>For example, instead of :</p>\n\n<blockquote>\n<pre><code>// Prepare transient fields\n//\n// — formattedCreationDateTime\n// — votes\n//\n// that will be used in the template.\n</code></pre>\n</blockquote>\n\n<p>Use a block comment:</p>\n\n<pre><code>/* \n* Prepare transient fields\n*\n* — formattedCreationDateTime\n* — votes\n*\n* that will be used in the template.\n*/\n</code></pre>\n\n<p>And also:</p>\n\n<blockquote>\n<pre><code>//==========================================\n//\n// Database Columns\n//\n//==========================================\n</code></pre>\n</blockquote>\n\n<p>Use a block comment:</p>\n\n<pre><code>/*\n* ==========================================\n*\n* Database Columns\n*\n* ==========================================\n*/\n</code></pre>\n\n<h3>Braces</h3>\n\n<p>It is better to use braces around control structures even if they contain a single statement. If you or a colleague adds a statement intending to add a block then missing braces could lead to logical errors.</p>\n\n<h3>Exception/Error handling</h3>\n\n<p>While it may be a rare scenario, what would happen if a question or answer wasn't found when a user attempts to vote - e.g. if deleting is possible. </p>\n\n<h2>JavaScript</h2>\n\n<p>There are many things I spot. Using a linter like <a href=\"https://jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a>, <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">esLint</a>, etc. would find many of these things.</p>\n\n<h3>Braces</h3>\n\n<p>As mentioned above for Java, braces aren't required for control structures but it helps avoid bugs when you or a colleague need to add lines to blocks within those control structures.</p>\n\n<h3>Semicolons</h3>\n\n<p>Semicolons aren't required for all lines except <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">a handful of statements</a> so <a href=\"https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/\" rel=\"nofollow noreferrer\">as this blog post</a> explains it is best to use them to avoid unintentional behavior in your code. </p>\n\n<h3>Varible scope, initilization</h3>\n\n<p>Some variables are declared using <code>let</code> - e.g. <code>questionBody</code> in <code>convertQuestionBodyToHTML()</code>, but these are never re-assigned. It is best to default to using <code>const</code> and then when it is determined that re-assignment is necessary use <code>let</code>. This even applies to arrays when elements are only pushed into them.</p>\n\n<p>There is the variable <code>tagEditorInput</code> in <code>tagEditorInputOnInput()</code> declared with <code>var</code>. This should also be declared with <code>const</code> since there is no need to re-assign that variable, and it doesn't need to be accessed in any context other than the function.</p>\n\n<blockquote>\n<pre><code>for (let e of questionBody.getElementsByTagName(\"*\"))\n if (e.tagName !== \"CODE\" && e.tagName !== \"PRE\")\n e.innerHTML = replaceHTMLEntitiesWithRealCharacters(e.innerHTML);\n</code></pre>\n</blockquote>\n\n<h3>Selecting elements</h3>\n\n<p>I typically see code that uses <code>document.querySelectorAll()</code> just to select items by tag or class name, but here I would recommend using <code>querySelectorAll()</code> with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:not\" rel=\"nofollow noreferrer\">CSS <code>:not()</code> selector</a> because it can eliminate the need to have the <code>if</code> inside the loop and reduce the number of elements looped over.</p>\n\n<p>For example in <code>convertQuestionBodyToHTML()</code></p>\n\n<pre><code>for (let e of questionBody.querySelectorAll('*:not(code):not(pre)'))\n e.innerHTML = replaceHTMLEntitiesWithRealCharacters(e.innerHTML);\n</code></pre>\n\n<p>And the same applies to <code>convertAnswersBodiesToHTML()</code></p>\n\n<p>The function <code>highlightCodeInsideElement()</code> could be simplified to <em>only</em> select elements that are <code><code></code> elements with a parent element that is a <code><pre></code> element using the CSS <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator\" rel=\"nofollow noreferrer\">child combinator</a>:</p>\n\n<pre><code>const codeElements = element.querySelectorAll(\"pre > code\");\n\nfor (let c of codeElements)\n hljs.highlightBlock(c);\n</code></pre>\n\n<p>It may be appropriate to use <code>codeElements.forEach(highlightBlock)</code> unless the parameters don't align properly.</p>\n\n<h3>Replacing characters</h3>\n\n<p>The function <code>replaceHTMLEntitiesWithRealCharacters()</code> appears to decode HTML entities by replacing three characters. Each call to <code>replaceAll</code> splits the string with the search string and joins using the replace string as the glue. Did you consider using <code>String.replace()</code> with a regex? I <a href=\"https://jsbin.com/zesize/3/edit?js,console,output\" rel=\"nofollow noreferrer\">my experiments</a> it seems faster to use regular expressions to </p>\n\n<pre><code>function replaceHTMLEntitiesWithRealCharacters(string) {\n string = string.replace(/&lt;/g, \"<\");\n string = string.replace(/&gt;/g, \">\");\n\n // This HTML entity should be the last since\n // it can affect on the other entities.\n string = string.replace(/&amp;/g, \"&\");\n return string;\n}\n</code></pre>\n\n<p>As <a href=\"https://stackoverflow.com/a/34064434/1575353\">this SO answer suggests</a> the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMParser\" rel=\"nofollow noreferrer\">DOMParser API</a> could be used but it seems to be a bit slower, likely because it does more than just replacing those three characters.</p>\n\n<h3>Event handlers</h3>\n\n<p>The function <code>createRendererTagElement()</code> creates span tags with an svg element that has an <code>onmouseup</code> event handler. It is better to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>Element.addEventListener()</code></a> for multiple reasons:</p>\n\n<ul>\n<li>separation of JS logic from HTML</li>\n<li>allows multiple event handlers if necessary</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T10:07:32.817",
"Id": "477561",
"Score": "0",
"body": "Thanks you very much for the answer! I would like to give a bounty for your answer, too. But I do not see a «start bounty» button anymore. Is it possible to give two bounties under the single one question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T16:43:26.527",
"Id": "477607",
"Score": "0",
"body": "I wasn't expecting to earn the bounty as I didn't really answer any of the main questions you had. Either it won't let you because it hasn't been long enough, or you don't have enough reputation, since \"_[if you offer multiple bounties on the same question, the minimum spend doubles with each subsequent bounty](https://codereview.stackexchange.com/help/bounty)_\" so you'd have to offer 600 reputation. Another user could be convinced to offer a bounty in your place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T17:42:33.133",
"Id": "477616",
"Score": "0",
"body": "Anyway, you spent your time to answer my question and it helped me a lot. I really appreciate it. Thank you a lot, again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T17:50:54.317",
"Id": "243274",
"ParentId": "243111",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243235",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T15:54:08.830",
"Id": "243111",
"Score": "12",
"Tags": [
"java",
"javascript",
"css",
"spring",
"spring-mvc"
],
"Title": "Stack Overflow clone"
}
|
243111
|
<p>I have an input dataframe like below, where 'ID' is unique identifier, 'Signals_in_Group' is a derived field containing list of all unique 'Signal' column values present in a 'Group'. And 'Signals_Count' is also a derived field whose values are count of items in 'Signals_in_Group'.</p>
<pre><code>groups_df
ID Timestamp Signal Group Signals_in_Group Signals_Count
1 5 1590662170 A 1 [A, B, C] 3
2 2 1590662169 B 1 [A, B, C] 3
3 6 1590662169 C 1 [A, B, C] 3
4 8 1590662171 D 2 [A, D] 2
5 7 1590662172 A 2 [A, D] 2
6 10 1590662185 B 3 [A, B, C, D] 4
7 9 1590662185 D 3 [A, B, C, D] 4
8 3 1590662188 C 3 [A, B, C, D] 4
9 1 1590662186 D 3 [A, B, C, D] 4
10 11 1590662189 A 3 [A, B, C, D] 4
11 4 1590662192 C 4 [C, D] 2
12 12 1590662192 D 4 [C, D] 2
13 13 1590662204 B 5 [B, C] 2
14 14 1590662204 C 5 [B, C] 2
15 15 1590662204 B 5 [B, C] 2
</code></pre>
<p>Below is another input, which is a list of lists</p>
<pre><code>clusters = [['A', 'B'], ['B', 'C'], ['A', 'D'], ['A', 'B', 'C'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['C', 'D', 'E', 'F']]
</code></pre>
<p>I need to find whether in each group 'Signals_in_Group' contains any of the clusters. And for each cluster matched in a group, find the first occurring 'Signal' based on 'Timestamp'. If 'Timestamp' is same for more than 1 row, consider the 'Signal' having the lowest 'ID'.</p>
<p>Example for Group 1:
'Signals_in_Group' ([A, B, C]) contains 'clusters' [A, B], [B, C] and [A, B, C].
For cluster [A, B] in 'Group' 1, rows with index 1 and 2 match. Row 2 has the least 'Timestamp' among them, so the corresponding 'Signal' value 'B' becomes the output.
For cluster [B, C] in 'Group' 1, rows with index 2 and 3 match. Both of them have same timestamp, so find the lowest 'ID' among them which is 2, and corresponding 'Signal' value 'B' becomes the output.
For cluster [A, B, C] in 'Group' 1, rows with index 1, 2 and 3 match. Rows 2 and 3 have lowest and same timestamp, so find the lowest 'ID' among them which is 2, and corresponding 'Signal' value 'B' becomes the output.
Likewise, this should be done for all groups.</p>
<p>The output should look like below:
Each item in 'clusters' become the column names and each row is one 'Group'.</p>
<pre><code>Group
A,B B,C A,D A,B,C B,C,D A,B,C,D C,D,E,F
1 B B NaN B NaN NaN NaN
2 NaN NaN D NaN NaN NaN NaN
3 B B D B D D NaN
5 NaN B NaN NaN NaN NaN NaN
</code></pre>
<p>I achieved this using the code below, first by iterating groups and then for each group, iterating clusters.
However, it takes too long to complete. So, I'm looking for a more Pythonic and optimized solution to make it faster.
I tested for 763k rows with 52k groups, number of clusters are 200. It took around 4 hrs.</p>
<p>Any suggestion to improve the runtime would be appreciated. Thanks.</p>
<pre><code>cls = [','.join(ele) for ele in clusters]
cls.insert(0, 'Group')
result = pd.DataFrame(columns=cls)
result.set_index('Group', inplace = True)
groups = groups_df['Group'].unique()
for group in groups:
# Get all records belonging to the group
group_df = groups_df.groupby(['Group']).get_group(group)
# Remove clusters containing no. of items less than no. of items in 'Signals_in_Group'
clusters_fil = [x for x in clusters if len(x) <= group_df['Signals_Count'].iloc[0]]
for cluster in clusters_fil:
if all(elem in group_df['Signals_in_Group'].iloc[0] for elem in cluster):
cluster_df = group_df[group_df['Signal'].isin(cluster)]
inter = cluster_df.loc[cluster_df['Timestamp'] == cluster_df['Timestamp'].min()]
result.loc[group, ','.join(cluster)] = inter.loc[inter.ID == inter.ID.min(), 'Signal'].iat[0]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T17:08:56.057",
"Id": "477233",
"Score": "0",
"body": "@Graipher Would it be possible for you to please help me with this? Thanks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T16:57:04.113",
"Id": "243114",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"pandas"
],
"Title": "Match lists and get value of one column based on values of other columns from dataframe optimization"
}
|
243114
|
<p>I'm writing a small program to plot new COVID-19 infections. As of right now, I have it so the program reads the given data file, pulls out the daily cases and dates for each country, and adds together all the cases for a given date. However, because both of the lists generated have lengths of over 2000, it currently runs extremely slowly. Is there any change I can make to improve the speed of my program?</p>
<pre><code>import pylab as pl
cases = pd.read_csv("daily-cases-covid-19.csv")
dc = cases.loc[:,'Daily confirmed cases (cases)']
dd = cases.loc[:,'Date']
worldCases = []
for i in range(0,len(dd)):
count = 0
for j in range(0,len(dd)):
if dd[j]==dd[i]:
count+=dc[i]
worldCases.append(count)
</code></pre>
<p>Here is an example of the CSV I am reading through. The purpose of the nested loops is to add together all of the confirmed cases in each country on a given date.</p>
<pre><code>Afghanistan,AFG,"Jan 1, 2020",0
Afghanistan,AFG,"Jan 2, 2020",0
Afghanistan,AFG,"Jan 3, 2020",0
Afghanistan,AFG,"Jan 4, 2020",0
Afghanistan,AFG,"Jan 5, 2020",0
Afghanistan,AFG,"Jan 6, 2020",0
Afghanistan,AFG,"Jan 7, 2020",0
Afghanistan,AFG,"Jan 8, 2020",0
Afghanistan,AFG,"Jan 9, 2020",0
Afghanistan,AFG,"Jan 10, 2020",0
Afghanistan,AFG,"Jan 11, 2020",0
Afghanistan,AFG,"Jan 12, 2020",0
Afghanistan,AFG,"Jan 13, 2020",0
Afghanistan,AFG,"Jan 14, 2020",0
Afghanistan,AFG,"Jan 15, 2020",0
Afghanistan,AFG,"Jan 16, 2020",0
Afghanistan,AFG,"Jan 17, 2020",0
Afghanistan,AFG,"Jan 18, 2020",0
Afghanistan,AFG,"Jan 19, 2020",0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T22:08:44.380",
"Id": "477152",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>So it seams like you have a Pandas dataframe you are working with.\nAt the moment it looks like this section of code does the following</p>\n\n<pre><code>worldCases = [] \n\nfor i in range(0,len(dd)): #iterate through all dates\n count = 0 #setup a counter\n for j in range(0,len(dd)): #iterate through all dates\n if dd[j]==dd[i]: \n count+=dc[i] #add one to counter if inner date == outer date\n worldCases.append(count) #track number of times a unique date occurs\n</code></pre>\n\n<p>You are effectively binning your data, getting a count of the number of times each unique date occurs. Pandas offers you more efficient and convenient tools for doing this. Specifically look into the <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html?highlight=groupby#pandas.DataFrame.groupby\" rel=\"nofollow noreferrer\">groupby</a> method. </p>\n\n<p>A much faster way to get the same output for <code>worldCases</code> would be to do the following:</p>\n\n<pre><code># group the daily cases data by the date and then compute \n# the sum of cases within each date group\n\ndc = 'Daily confirmed cases (cases)'\nworldCases = cases.loc[:, dc].groupby(cases['Date']).sum()\n</code></pre>\n\n<p>Also, if you find yourself writing lots of loops like the above, you may want to check out the <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html\" rel=\"nofollow noreferrer\">user guide for \"group by\" operations in the pandas documentation.</a> It is a very powerful way of handling situations like this, and more, but can take a bit of getting used to. It can feel like a whole different way of thinking about your data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T23:10:38.257",
"Id": "243127",
"ParentId": "243124",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T22:05:01.027",
"Id": "243124",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"csv",
"covid-19"
],
"Title": "Calculating the total daily amount of confirmed cases of Coronavirus"
}
|
243124
|
<p>I have written a series of functions that are designed to create a space-filling curve (similar to a Hilbert Curve) that is intended for symmetric matrices (as opposed to a square region).</p>
<p>I plan to ultimately use the function in <code>R</code>, but decided to write it in <code>c++</code> for the sake of speed. </p>
<p>Also, you may notice that I am using 64 bit integers. This is because I am converting 2d coordinates that can be in the million, so the 1d vector will be extremely long and will need very large integers to index it. </p>
<p>Also, if you see anywhere I make save time by implementing bitwise operations, please point them out.</p>
<hr>
<pre><code>#include <Rcpp.h>
using namespace Rcpp;
# include <bitset>
# include <cstdint>
# include <ctime>
# include <iomanip>
# include <iostream>
using namespace std;
# include "hilbert_curve_copy.hpp"
//****************************************************************************80
// [[Rcpp::export]]
void rot ( int n, uint64_t &x, uint64_t &y, int rx, int ry )
//****************************************************************************80
//
// Purpose:
//
// ROT rotates and flips a quadrant appropriately
//
// Modified:
//
// 24 December 2015
//
// Parameters:
//
// Input, int N, the length of a side of the square. N must be a power of 2.
//
// Input/output, int &X, &Y, the input and output coordinates of a point.
//
// Input, int RX, RY, the region (left/right -- upper/lower)
//
{
int t;
// 0 3 0--1 14-15 Only rotate and/or flip if in the upper y quadrant (ry == 1).
// | | | |
// 1--2 --> 3--2 13-12 Reflect vertically and horizontally BEFORE swapping x and y
// | | only for the upper left side (rx == 0 and ry == 1)
// 4 7--8 11
// | | | |
// 5--6 9--10
if ( ry == 1 )
{
//
// Reflect horizonally AND veritcally
//
if ( rx == 0 )
{
x = n - 1 - x;
y = n - 1 - y;
}
//
// Flip (i.e. reflect accross the line y = x, i.e. swap x and y)
//
t = x;
x = y;
y = t;
}
return;
}
//****************************************************************************80
// [[Rcpp::export]]
Rcpp::NumericVector makeInt64(std::vector<int64_t> v) {
size_t len = v.size();
Rcpp::NumericVector n(len); // storage vehicle we return them in
// transfers values 'keeping bits' but changing type
// using reinterpret_cast would get us a warning
std::memcpy(&(n[0]), &(v[0]), len * sizeof(int64_t));
n.attr("class") = "integer64";
return n;
}
//****************************************************************************80
// [[Rcpp::export]]
uint64_t i4_power ( int i, int j )
//****************************************************************************80
//
// Purpose:
//
// I4_POWER returns the value of I^J.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, J, the base and the power. J should be nonnegative.
//
// Output, int I4_POWER, the value of I^J.
//
{
int k;
uint64_t value;
if ( j < 0 )
{
if ( i == 1 )
{
value = 1;
}
else if ( i == 0 )
{
cerr << "\n";
cerr << "I4_POWER - Fatal error!\n";
cerr << " I^J requested, with I = 0 and J negative.\n";
exit ( 1 );
}
else
{
value = 0;
}
}
else if ( j == 0 )
{
if ( i == 0 )
{
cerr << "\n";
cerr << "I4_POWER - Fatal error!\n";
cerr << " I^J requested, with I = 0 and J = 0.\n";
exit ( 1 );
}
else
{
value = 1;
}
}
else if ( j == 1 )
{
value = i;
}
else
{
value = 1;
for ( k = 1; k <= j; k++ )
{
value = value * i;
}
}
return value;
}
//****************************************************************************80
// [[Rcpp::export]]
Rcpp::NumericVector xy2d ( int m, uint64_t x, uint64_t y )
//****************************************************************************80
{
const uint64_t n = i4_power ( 2, m );
if ( x > n - 1 || y > n - 1) {
throw std::range_error("Neither x nor y may be larger than (2^m - 1)\n");
}
uint64_t d = 0;
int state = 0;
for ( uint64_t s = n / 2; s > 0; s = s / 2 )
{
// rx = x region (right = 1, left equals 0)
// ry = y region (top = 1, bottom = 0)
int rx = ( x & s ) > 0;
int ry = ( y & s ) > 0;
if (state == 0) {
// # *--2 | 0 -> *--2 | 1 -> 0 3 | 2 -> 2 |
// # | | | | | | | / |
// # 0--1 | 0--1 | 1--2 | 1--0 |
// # if x on right region, add lower left triangle (region 0)
// # (s * (s + 1) / 2) * rx
// # if y on upper region, add lower right square as well (both regions 0 and 1)
// # (s * s) * ry
d += (s * (s + 1) / 2) * rx + (s * s) * ry;
// # change the state
// # rx ry | (rx + ry)
// # 0 0 | 0
// # 1 0 | 1
// # 1 1 | 2
state = rx + ry;
}else if (state == 1) {
// # Determine how many squares to add
// # equals number in s-by-s square times it's order in the curve
// # rx ry | (3 * rx) ^ (1 - ry)
// # 0 1 | 0 ^ 0 = [00] ^ [00] = 00 = 0
// # 0 0 | 0 ^ 1 = [00] ^ [01] = 01 = 1
// # 1 0 | 3 ^ 1 = [11] ^ [01] = 10 = 2
// # 1 1 | 3 ^ 0 = [11] ^ [00] = 11 = 3
d += s * s * ((3 * rx) ^ (1 - ry));
//**********************************************************************80
// # ROTATE
// 0 3 0--1 14-15 Only rotate and/or flip if in the upper y
// | | | | quadrant (ry == 1).
// 1--2 --> 3--2 13-12
// | | Reflect vertically and horizontally BEFORE
// 4 7--8 11 swapping x and y only for the upper left
// | | | | side (rx == 0 and ry == 1)
// 5--6 9--10
//
// # 0 3 | 0 -> 0--1 | 1,2 -> 0 3 | 3 -> 2--3 |
// # | | | | | | | | | |
// # 1--2 | 3--2 | 1--2 | 1--0 |
//
rot(n, x, y, rx, ry); // FIXME rot(n, &x, &y, rx, ry);
}else if (state == 2) {
// # 2 | 0 -> 2--1 | 1 -> 2 | 3 -> 2 |
// # / | | | | / | | |
// # 1--0 | 3 0 | 1--0 | 0--1 |
d += (s * s) * (rx == ry) + (s * (s + 1) / 2) * (rx == 1 && ry == 1);
// # rx ry | Target | state - (rx + ry)
// #_________|_________|__________________
// # 1 0 | 1 | 2 - (1 + 0) = 1
// # 0 0 | 2 | 2 - (0 + 0) = 2
// # 1 1 | 0 | 2 - (1 + 1) = 0
// # new_state = current_state - (rx + ry)
state = 2 - (rx + ry);
if (state == 1) {
// # If the state goes from state-2 to state-1, then rotate the hilbert
// # curve 180 degrees (i.e. reflect horizonally and vertically)
x = n-1 - x;
y = n-1 - y;
}
}
}
const std::vector<uint64_t> v(1, d);
const size_t len = v.size();
// storage vehicle we return the value to R
Rcpp::NumericVector nn(len);
// transfers values 'keeping bits' but changing type
// using reinterpret_cast would get us a warning
std::memcpy(&(nn[0]), &(v[0]), len * sizeof(uint64_t));
// Make the return value compatible with the bit64 R package
nn.attr("class") = "integer64";
return nn;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T22:07:00.623",
"Id": "243125",
"Score": "3",
"Tags": [
"c++",
"r",
"bitwise",
"rcpp"
],
"Title": "Implementing a Hilbert-like space-filling-curve conversion in Rcpp"
}
|
243125
|
<hr>
<p>I have written a simple <strong><code>Integrator</code></strong> class in C++17 that can perform either a definite single integration of a single variable or a definite double integration of a single variable using the same integrand. </p>
<hr>
<p>Here's my Integrator class: </p>
<p><strong>Integrator.h</strong></p>
<pre><code>#pragma once
#include <algorithm>
#include <utility>
#include <functional>
struct Limits {
double lower;
double upper;
Limits(double a = 0, double b = 0) : lower{ a }, upper{ b } {
if (a > b) std::swap(lower, upper);
}
void applyLimits(double a, double b) {
lower = a;
upper = b;
if (a > b) std::swap(lower, upper);
}
};
class Integrator {
private:
Limits limits_;
std::function<double(double)> integrand_;
double dx_;
double dy_;
double integral_;
int step_size_;
public:
Integrator(Limits limits, int stepSize, std::function<double(double)> integrand)
: limits_{ limits },
step_size_{ stepSize },
integrand_{ integrand },
dx_{ 0 }, dy_{ 0 }
{}
~Integrator() = default;
constexpr double dx() const { return this->dx_; }
constexpr double dy() const { return this->dy_; }
constexpr double integral() const { return this->integral_; }
Limits limits() const { return limits_; }
std::function<double(double)>* integrand() { return &this->integrand_; }
// This is always a 1st order of integration!
constexpr double evaluate() {
double distance = limits_.upper - limits_.lower; // Distance is defined as X0 to XN. (upperLimit - lowerLimit)
dx_ = distance / step_size_; // Calculate the amount of iterations by dividing
// the x-distance by the dx stepsize
integral_ = 0; // Initialize area to zero
for (auto i = 0; i < step_size_; i++) { // For each dx step or iteration calculate the area at Xi
dy_ = integrand_(limits_.lower + i * dx_);
double area = dy_ * dx_; // Where the width along x is defines as dxStepSize*i
integral_ += area; // and height(dy) is f(x) at Xi. Sum all of the results
}
return integral_;
}
// This will perform a second order of integration where the inner limits are defined
// by [lower, y] where "upper" is not used directly. This may be expanded in the future...
double integrate(double lower = 0.0, double upper = 0.0) {
// Since we are not using the inner upper limit directly
// make sure that it is still greater than the lower limit
if (upper <= lower) {
upper = lower + 1;
}
// As the code currently stands this temporary is not necessary as I could have
// used the values from the arguments directly, but I wanted to keep it
// for consistency reasons as this might be expanded in the future where the use
// of the upper bound inner limit will be taken into context.
Limits limits(lower, upper);
double outerSum = 0;
dy_ = static_cast<double>(limits_.upper - limits_.lower) / step_size_;
for (int i = 0; i < step_size_; i++) {
double yi = limits_.lower+i*dy_;
double dx_ = static_cast<double>(yi - limits.lower) / step_size_;
double innerSum = 0;
for (int j = 0; j < step_size_; j++) {
double xi = limits.lower + dx_ * j;
double fx = integrand_(xi);
double innerArea = fx*dx_;
innerSum += innerArea;
}
double outerArea = innerSum * dy_;
outerSum += outerArea;
}
integral_ = outerSum;
return integral_;
}
};
</code></pre>
<p>This is my driver application:</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <exception>
#include <cmath>
#include "Integrator.h"
constexpr double PI = 3.14159265358979;
constexpr double funcA(double x) {
return x;
}
constexpr double funcB(double x) {
return (x*x);
}
constexpr double funcC(double x) {
return ((0.5*(x*x)) + (3*x) - (1/x));
}
double funcD(double x) {
return sin(x);
}
int main() {
//using namespace util;
try {
std::cout << "Integration of f(x) = x from a=3.0 to b=5.0\nwith an expected output of 8\n";
Integrator integratorA(Limits(3.0, 5.0), 10000, &funcA);
std::cout << integratorA.evaluate() << '\n';
std::cout << "\n\nIntegration of f(x) = x^2 from a=2.0 to b=20.0\nwith an expected output of 2664\n";
Integrator integratorB(Limits(2.0, 20.0), 10000, &funcB);
std::cout << integratorB.evaluate() << '\n';
std::cout << "\n\nIntegration of f(x) = (1\\2)x^2 + 3x - (1\\x) from a=1.0 to b=10.0\nwith an expected output of 312.6974\n";
Integrator integratorC(Limits(1.0, 10.0), 10000, &funcC);
std::cout << integratorC.evaluate() << '\n';
std::cout << "\n\nIntegration of f(x) = sin(x) from a=0.0 to b=" <<PI<< "\nwith an expected output of 2\n";
Integrator integratorD(Limits(0.0, PI), 10000, &funcD);
std::cout << integratorD.evaluate() << '\n';
std::cout << "\n\nTesting Double Integration of f(x) = (1\\2)x^2 + 3x - (1\\x) from [3,5] and [1,y]\nwith an expected output of 65.582\n";
Integrator integratorE(Limits(3, 5), 500, &funcC);
//double dy = integratorE.limits().upper - integratorE.limits().lower;
integratorE.integrate(1);
std::cout << integratorE.integral() << '\n';
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
</code></pre>
<p>And this is my output to the console when I run the program:</p>
<pre><code>Integration of f(x) = x from a=3.0 to b=5.0
with an expected output of 8
7.9998
Integration of f(x) = x^2 from a=2.0 to b=20.0
with an expected output of 2664
2663.64
Integration of f(x) = (1\2)x^2 + 3x - (1\x) from a=1.0 to b=10.0
with an expected output of 312.6974
312.663
Integration of f(x) = sin(x) from a=0.0 to b=3.14159
with an expected output of 2
2
Testing Double Integration of f(x) = (1\2)x^2 + 3x - (1\x) from [3,5] and [1,y]
with an expected output of 65.582
65.3933
</code></pre>
<hr>
<p>Here are my questions and concerns about the above code:</p>
<ul>
<li>What kind of improvements can be made to this code? I'm referring to "readability", "generically", and "portability".
<ul>
<li>I know that this isn't within a <code>namespace</code> as that is not primary concern within the context of this question. I can always put this in some defined <code>namespace</code>! </li>
</ul></li>
<li>Are there any apparent "code smells"?</li>
<li>I have comments in my <code>integrate</code> function on not using the inner upper bounds...
<ul>
<li>How would I be able to incorporate the use of a defined inner upper bound? </li>
</ul></li>
<li>How can I extend my <code>integrate</code> function to perform even high orders of integration?</li>
<li>Considering that the current implementation of performing a double integration has an <code>O(n^2)</code> complexity is there a way to reduce to this <code>O(n)</code> or <code>O(log N)</code>? If so, how?</li>
<li>Are there any other optimizations that can be incorporated?</li>
<li>Would the use of <code>threads</code>, <code>multithreading</code>, and <code>parallel-programming</code> be applicable here? </li>
<li>Should I template this class? </li>
<li>I'm also interested in any and all suggestions, tips, and feedback!</li>
</ul>
<hr>
<hr>
<p><em>Extra useful information in regards to the design and implementation of my class</em></p>
<p>Its user-defined constructor requires three parameters/arguments in order to create an instance of an <strong><code>Integrator</code></strong> object. </p>
<ul>
<li>Its first requirement is the limits of integration that is defined by a simple <strong><code>Limits</code></strong> struct. </li>
<li>Its second requirement is the <code>step_size</code>, normally the width of <code>dx</code> or the number of divisions in calculating the area of integration by parts.</li>
<li>The third and final requirement is an <code>std::function<double(double)></code> object. </li>
</ul>
<p>About the <strong><code>Limits</code></strong> struct: </p>
<ul>
<li>It contains the <code>lower</code> and <code>upper</code> bounds of integration from <code>a</code> to <code>b</code>. </li>
<li>It has a basic user-defined default constructor that takes the <code>lower</code> and <code>upper</code> bounds of integration as arguments. Both arguments can default to 0. </li>
<li>It also contains an <code>applyLimits(lower,upper)</code> function. This simply acts as its constructor does with respect to its members by setting them or updating them.</li>
<li>Access is purely public as these limits can be changed by the user at any given time. There is no restriction on the changing of the limits of integration. </li>
<li>Both its constructor and its <code>applyLimits()</code> function will check if <code>lower</code> is greater than <code>upper</code> and if so it will swap them. </li>
</ul>
<p>About the <strong><code>function-objects</code></strong>:</p>
<ul>
<li>They can be any of the following:
<ul>
<li>function object</li>
<li>function pointer</li>
<li>functor</li>
<li>lambda expression. </li>
</ul></li>
<li>These function objects can be defined as either <code>constexpr</code> or <code>non-constexpr</code>.</li>
<li>Any are valid as long as they have the signature <code>double(double)</code> and can be stored in an <code>std::function<></code> object. </li>
</ul>
<p>About the construction and the use of the <strong><code>Integrator</code></strong> class object:</p>
<ul>
<li><strong>What it can do</strong>
<ul>
<li>It can perform a definite integral of a single variable through the use of its <code>evaluate()</code> function.</li>
<li>It can also perform a second integral of the same integrand of a single variable through its function <code>integrate(lower, upper)</code>.</li>
<li>It can also give you both the current <code>dy</code> and <code>dx</code> values, the <code>integrand</code>, and the current <code>integral</code> as well as the <code>limits</code> of integration.</li>
</ul></li>
<li><strong>Construction</strong>
<ul>
<li>The limits or outer limits are defined when the object is instantiated through its user-defined constructor.
<ul>
<li>This is the default behavior for both single and double integrations. </li>
</ul></li>
<li>The higher the <code>step_size</code> the more accurate the approximation.
<ul>
<li>Trade-offs: accuracy versus decrease in performance, time of execution taken.</li>
</ul></li>
<li>The function object is stored as its <code>integrand</code>. </li>
<li>Versatility in being able to retrieve it back from the Integrator object and being able to use it at any time.</li>
<li>The inner limits are defined when calling its <code>integrate()</code> function.
<ul>
<li>The inner limits of integration are from <code>[lower,y]</code>.</li>
<li><code>lower</code> is passed into the function as an argument and </li>
<li><code>y</code> is calculated on each iteration. </li>
<li>Currently within this context, <code>upper</code> is ignored for the inner limits and will default to <code>1>lower</code> so that the <code>Limits</code> struct doesn't swap them.</li>
</ul></li>
<li>See the note below in regards to expanding this class...</li>
</ul></li>
</ul>
<hr>
<p>I'm considering expanding this to also allow for the user input of the inner upper limit of integration to be defined by the user and apply it within the algorithm to generate the appropriate values of integration. This has yet to be implemented and is one of my concerns. I would also like to incorporate an easy way to perform triple, quad, and quint integrations if performance bottlenecks can be reduced to a minimum while still being able to give an accurate approximation without a major decrease in performance. I would like to have the capabilities of an Integrator object to possibly accept another Integrator object as an argument. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:46:44.650",
"Id": "477207",
"Score": "2",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:48:16.853",
"Id": "477209",
"Score": "0",
"body": "@Mast, you're right, it's been a while since I've posted here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:49:31.917",
"Id": "477210",
"Score": "0",
"body": "@Mast Should I move the extra information of the class below the questions and concerns? Having the class, the driver application and its results before towards the beginning of the post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:54:05.017",
"Id": "477212",
"Score": "1",
"body": "Now answers have arrived, the preferred choice is for you accept the current answer if it was useful to you, to wait 24h between posting questions and post a follow-up linking back to this question. Your new question can contain all the extra information (which probably should've been part of this question in the first revision). Do note that you raise a lot of questions in your question that are actually feature requests. You can note them as points of interest for a next iteration, a goal you're working towards, but they can not be the goal of the question itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:57:14.897",
"Id": "477213",
"Score": "0",
"body": "@Mast I just made an edit or update to this post. I didn't change anything except I moved the section of the class design towards the bottom of the post. I'd prefer to have the class towards the top with the question and concerns following it. Then the extra information. It just has a better look to the post, it has to do with an aesthetic, a look or a feel of the post that I want to portray to the readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T19:35:51.463",
"Id": "477633",
"Score": "1",
"body": "Here's a follow-up question: https://codereview.stackexchange.com/questions/243339/integrator-2-0-a-simple-integrator-in-c17"
}
] |
[
{
"body": "<p>You made multiple non-trivial edits while I wrote my answer, so there might be some divergence. (Personal annotation: Code should be (mostly) self explanatory. Don’t add a wall of text beforehand that words out what the code says anyway.)</p>\n\n<p>Due to lack of expertise, I will not comment on possible mathematical improvements or multithreading. </p>\n\n<h3>Clear interface</h3>\n\n<p>I am bit confused by the Integrator class. The usage as shown in your main is as expected, but why are <code>dx_</code>, <code>dy_</code> and <code>integral_</code> member variables, which can be accessed, but do not contain any meaningful content (Or are even unitialized for <code>integral_</code>!) until <code>evaluate()</code> or <code>integrate()</code> was called?</p>\n\n<p>If this is meant to be some kind of result caching, then it should happen completely internally, maybe with an <code>std::optional<double> integral_</code>, which is set the first time something is calculated and then returned the next time. Also, both functions should not share the cached result. Since this is nothing but a wild guess, I’ll assume the smallest sensible interface as depicted by the main in the following.</p>\n\n<h3>struct Limits</h3>\n\n<p>In my opinion, <code>applyLimits</code> is completely redundant to the non-default constructor and introduces code duplication. It should be completely removed, since it can be replaced as follows:</p>\n\n<pre><code>some_limits.applyLimits(3., 4.); //your function call\nsome_limits = Limits{3., 4.}; //shorter and clearer replacement\n</code></pre>\n\n<p><code>lower</code> and <code>upper</code> should not be public (although you mention that this is intended) as <code>lower <= upper</code> is an invariant which cannot be guaranteed if the user meddles with the variables directly.</p>\n\n<h3>class Integrator</h3>\n\n<p>In the name of <a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"nofollow noreferrer\">RAII</a>, never have a constructor not initialize a member variable, in this case <code>integral_</code>!</p>\n\n<p>As mentioned above, I will argue for a simplified interface here: Remove the member variables <code>dx_</code>, <code>dy_</code> and <code>integral_</code> as well as their respective getters completely and initialize them locally whereever needed. According to the <a href=\"https://www.fluentcpp.com/2019/04/23/the-rule-of-zero-zero-constructor-zero-calorie/\" rel=\"nofollow noreferrer\">rule of zero</a>, do not explicitely default the destructor, as it is redundant and even deletes the move constructors!</p>\n\n<p>Since your algorithm breaks for negative <code>step_size_</code>, use <code>size_t</code> instead of <code>int</code> as its type.</p>\n\n<p>The loop over <code>i</code> in <code>evaluate</code> and the one over <code>j</code> in <code>integrate</code> are again code duplication, consider refactoring that. I would suggest something like this, with a reasonable name of course (ommited comments for brevity):</p>\n\n<pre><code>constexpr double evaluate() {\n double distance = limits_.upper - limits_.lower;\n auto dx = distance / step_size_;\n\n return mathematically_descriptive_name(dx, limits_);\n}\n\nprivate:\ndouble mathematically_descriptive_name(double dx, const Limits& limits) {\n double result = 0.;\n for (size_t i = 0; i < step_size_; ++i) {\n auto dy = integrand_(limits.lower + i * dx);\n auto area = dy * dx;\n result += area;\n }\n return result;\n}\n</code></pre>\n\n<p>The loop in <code>integrate</code> can then be replaced with:</p>\n\n<pre><code>auto innerSum = mathematically_descriptive_name(dx, limits);\n</code></pre>\n\n<p>Whilst implementing this, I tripped over the fact that in <code>integrate</code> both the member variable <code>limits_</code> as well as the local variable <code>limits</code> are used, you should make the names more distinguishable from each other to avoid confusion.</p>\n\n<h3>General style</h3>\n\n<p>Since you are using C++17, I would suggest a widespread use of <a href=\"https://en.cppreference.com/w/cpp/language/attributes/nodiscard\" rel=\"nofollow noreferrer\"><code>[[nodiscard]]</code></a>. Additionally, now that those additional member variables disappeared, all your functions can be const! With my interpretation of your interface, you could even make everything <code>constexpr</code>* and calculate everything at compile time – you would need to replace <code>std::function</code> though, maybe by templating the class over the function used.</p>\n\n<p>Nowadays curly initialization, as already used by your constructors, is the way to go, e.g. use</p>\n\n<pre><code>Integrator integratorA{Limits{3.0, 5.0}, 10000, &funcA};\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>auto integratorA = Integrator{Limits{3.0, 5.0}, 10000, &funcA};\n</code></pre>\n\n<p>for the main.</p>\n\n<h3>About templates</h3>\n\n<p>I would template both the struct and the class over a <code>template<typename Field></code> instead of using <code>double</code> to increase flexibility of usage. Additionally, as mentioned earlier, for a constexpr evaluation you could consider using <code>template<typename Func></code> and throwing lambdas in as parameters.</p>\n\n<hr>\n\n<p>*<a href=\"https://en.cppreference.com/w/cpp/algorithm/swap\" rel=\"nofollow noreferrer\"><code>std::swap</code></a> is not constexpr before C++20. Until then, one could do a small trick to work around this like</p>\n\n<pre><code>constexpr Limits(double a = 0., double b = 0.) :\n lower{ a < b ? a : b },\n upper{ a < b ? b : a }\n{}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:12:03.643",
"Id": "477202",
"Score": "0",
"body": "I moved the structured information below the class and the questions and concerns as a reference to the thought in the design and implementation of my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:22:57.673",
"Id": "477204",
"Score": "0",
"body": "I like your response and the points you made. It took me a while to get the `double-integration` to work. Originally I tried to create a temporary instance of an `Integrator` object within the `integrate()` function that would invoke its `evaluate()` function locally on the stack, but it wasn't working correctly. As for making it `constexpr` that was the intended goal except the `Limits` are preventing me due to `swap`. As for `dy` & `dx` being members, I did this to possibly allow for an integrator to accept another integrator that may need to retrieve the other's current `dx` or `dy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:25:25.343",
"Id": "477205",
"Score": "0",
"body": "I don't want direct public access to them and have accessors for a reason. If they are within thread pools, the member can be retrieved when the timing of the threads allows for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:31:55.300",
"Id": "477206",
"Score": "0",
"body": "I fixed the issue with the `RAII` of `integral_` not being initialized, that was just something I simply overlooked... I removed the destructor that was set as `default`. I also changed the name of `limits` to `innerLimits` to be more descriptive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:47:35.197",
"Id": "477208",
"Score": "2",
"body": "@FrancisCugler We take answer invalidation quite seriously here, please do not add to or modify the code in the question after the first answer arrives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:50:49.293",
"Id": "477211",
"Score": "0",
"body": "@Mast that's fine, but is it okay to restructure or reorder what is already there without changing any of its contents or context? I was in the middle of a major edit before there were any answers provided and after I was done editing was when the first answer had appeared."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:57:50.813",
"Id": "477214",
"Score": "1",
"body": "@FrancisCugler That's unfortunate, but that risk is yours. To avoid this risk, make sure the first revision of your post is complete and correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:59:58.330",
"Id": "477216",
"Score": "0",
"body": "@Mast It is still the original or first revision, I only moved a section to another location. I didn't change any context. It should not need any more edits except for maybe spelling or grammar errors outside of the `code` sections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T12:01:12.320",
"Id": "477217",
"Score": "1",
"body": "@FrancisCugler And that's why I haven't rolled it back :-) But any edit carries a risk and that risk is yours the moment answers have come in. That's all I'm saying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T12:01:45.223",
"Id": "477218",
"Score": "0",
"body": "@Mast then as long as there are no spelling or grammar errors it's a perfect initial post!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T12:41:56.107",
"Id": "477219",
"Score": "2",
"body": "@FrancisCugler I made an edit about constexpr-ness of std::swap.\n\nAbout having other Instances of the class use dx and dy: Consider calculating those values on the fly since it isn’t expensive. Having getters to values which might be set to \"meaningless\" default values is bad style. Independent of how you choose to do this, it should still be private, as it is an implementation detail. Instances of the same class can access private members, see [this simple example on godbolt](https://godbolt.org/z/ohGBw4)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T19:36:06.027",
"Id": "477634",
"Score": "0",
"body": "Here's a follow-up question: https://codereview.stackexchange.com/questions/243339/integrator-2-0-a-simple-integrator-in-c17"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:00:43.987",
"Id": "243141",
"ParentId": "243130",
"Score": "5"
}
},
{
"body": "<p>You've implemented <a href=\"https://en.wikipedia.org/wiki/Riemann_sum\" rel=\"nofollow noreferrer\">Riemann sums</a> to numerically integrate functions. That's a good method if you may have very ugly/discontinuous functions and you don't care how long the integrals take. Plus it's simple and generally well understood. If the simplest choice is good enough for your application, then stick with it by all means.</p>\n\n<p>However, there are other algorithms that will evaluate the integrand at fewer points and can handle definite integrals with infinite bounds.</p>\n\n<p>I'm not going to dive into the alternative methods here, but I'll point you to two resources that explain the methods better than I can:</p>\n\n<ul>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Numerical_integration#Methods_for_one-dimensional_integrals\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Numerical_integration#Methods_for_one-dimensional_integrals</a>. This is a really good article. I think the pictures show how you can get a more accurate integral with fewer evaluations.</p></li>\n<li><p><a href=\"https://www.boost.org/doc/libs/1_73_0/libs/math/doc/html/math_toolkit/gauss.html\" rel=\"nofollow noreferrer\">https://www.boost.org/doc/libs/1_73_0/libs/math/doc/html/math_toolkit/gauss.html</a>. <code>boost::math::quadrature</code> is Boost's version of your code. You may enjoy reading the docs and/or the source code to see how they implement more performant algorithms. As a general rule, whenever you implement something general in C++ it's worth checking if one of the major C++ general purpose libraries has a version.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>Integrator(..., int stepSize, ...)\n</code></pre>\n\n<p><code>stepSize</code> is only useful in some integration algorithms. IMO that implies this argument is a leaky abstraction. Also, why should this be an <code>int</code>?</p>\n\n<p>I think what you really want is a way to control the precision of your answer. Maybe a <code>double maximumError</code> argument could achieve that?</p>\n\n<hr>\n\n<p>Why is <code>Integrator</code> a class rather than a function?</p>\n\n<hr>\n\n<p>Typically, <code>integral(from: a, to:b) == -integral(from:b, to:a)</code> (<a href=\"https://en.wikipedia.org/wiki/Integral#Conventions\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Integral#Conventions</a>). In your implementation, they are equivalent.</p>\n\n<hr>\n\n<blockquote>\n <p>definite double integration of a single variable</p>\n</blockquote>\n\n<p>This confused me because you actually introduce a second variable in the limits of integration of the inner integral. Also you have some little bugs in the integrate function which I think you would have easily caught if you added more test cases.</p>\n\n<p>Imagine your single definite integral functions had the signature <code>template<typename F> double integrate1x(double lower, double upper, F f)</code>. Then you could implement your outer integral with the same method:</p>\n\n<pre><code>// \\int_(L)^(U) \\int_(g(y))^(h(y)) f(x) dx dy\ntemplate <typename F, G, H>\ndouble integrate2x(double L, double U, G g, H h, F f) {\n return integrate1x(L, U, [&](double y) {\n return integrate1x(g(y), h(y), f);\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T19:36:15.357",
"Id": "477635",
"Score": "0",
"body": "Here's a follow-up question: https://codereview.stackexchange.com/questions/243339/integrator-2-0-a-simple-integrator-in-c17"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T17:36:13.013",
"Id": "243185",
"ParentId": "243130",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243141",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T02:51:08.733",
"Id": "243130",
"Score": "4",
"Tags": [
"c++",
"performance",
"algorithm",
"c++17",
"numerical-methods"
],
"Title": "A simple definite integrator class of a single variable in C++"
}
|
243130
|
<p>This code below, was for my school project, first year. I am new to C programming, before which I learned Python. Hence, I do not know the tweaks and tricks in C language. What are the various ways to improve the code? Moreover, my requirement requires me to have indentation. I am unsure how to apply that indentation in my code. My code needs to be user-friendly and must have smooth execution ( nice to view ).</p>
<pre><code>#include <stdio.h>
#include <stdlib.h> //For functions like system() and exit()
#include <windows.h> //For function Sleep()
#include <math.h> //For functions like pow(), sin(), cos(), tan()
#define PI 3.141592654 //Function is being referred at first so as to use it in main.
int main(void)
{
int i = 1; /* */
int Reuse; /* */
double x, xy, y; /* */
char Opt; /* Declaring the type variables */
int Numbering; /* */
int N, F; /* */
float Num1, Num2 ,ans; /* */
char oper; /* */
printf("Welcome to our calculator.\n");
while (1){ //While loop that never ends, unless exit(0) is used
printf("\n\nWhich mode do you want to use?\n1.Normal maths operations\n2.Trigonometric functions\n3.Fibonacci Series\n4.Exit\n\nYour input: ");
scanf(" %c", &Opt);
if (Opt == '1'){
printf("Welcome to Normal maths operation Mode.\n\nYour two numbers: ");
scanf("%f%f", &Num1, &Num2);
printf("\nAVAILABLE SYMBOLS:\n\n+ for Addition\n- for Subtraction\n/ for Division\n* for Multiplication\n^ for Power function\n\nYour input: ");
scanf(" %c", &oper);
if (oper == '+'){
ans = (Num1 + Num2);
printf("Here is your answer:\n%f %c %f = %.5f (To 5 decimal places)\n\n", Num1, oper, Num2, ans);
Sleep(2450);
} else if (oper == '-'){
ans = (Num1 - Num2);
printf("Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n", Num1, oper, Num2, ans);
Sleep(2450);
} else if (oper == '/'){
ans = (Num1 / Num2);
printf("Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n", Num1, oper, Num2, ans);
Sleep(2450);
} else if (oper == '*'){
ans = (Num1 * Num2);
printf("Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n", Num1, oper, Num2, ans);
Sleep(2450);
} else if (oper == '^'){
ans = (pow (Num1 , Num2));
printf("Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n", Num1, oper, Num2, ans);
Sleep(2450);
} else{
printf("\n\nYour input operator is incorrect; ERROR 1 Sintek\n");
Sleep(2450);
system("cls");
}
}
if (Opt == '2'){
printf("Welcome to Trigonometric Function Mode.\n\nInput your angle in degrees: ");
scanf("%f", &Num1);
printf("The trigo you are going to use\ns for sine\nc for cosine\nt for tangent\nYour input: ");
scanf(" %c", &oper);
if (oper == 's'){
ans = (sin (Num1 * PI/180));
printf("\nHere is your answer:\nAngle: %f\nSin%f = %f", Num1, Num1, ans);
Sleep(2450);
} else if (oper == 'c'){
ans = (cos (Num1 * PI/180));
printf("\nHere is your answer:\nAngle: %f\nCos%f = %f", Num1, Num1, ans);
Sleep(2450);
} else if (oper == 't'){
ans = (tan (Num1 * PI/180));
printf("\nHere is your answer:\nAngle: %f\nTan%f = %f", Num1, Num1, ans);
Sleep(2450);
} else{
printf("\n\nWrong operator used for Trigo; ERROR 1 Sintek");
Sleep(2450);
system("cls");
}
}
if (Opt == '3'){
printf("Welcome to Fibonacci Series Mode.\n\nEnter how many numbers do you want from the series, from the start: ");
scanf("%d", &N);
x = 0;
y = 1;
F = 3;
Numbering = 3;
printf("Here is Your Series:\n\n");
if (N == 1){
printf("[1] 0\n");
Sleep(1000);
}
if (N == 2){
printf("[1] 0\n");
Sleep(250);
printf("[2] 1\n");
Sleep(1000);
}
if (N == 3){
printf("[1] 0\n");
Sleep(250);
printf("[2] 1\n");
Sleep(250);
printf("[3] 1\n");
Sleep(250);
}
if (N > 3){
printf("[1] 0\n");
Sleep(250);
printf("[2] 1\n");
Sleep(250);
}
while ( N > 3 && F <= N ){
xy = x + y;
printf("[%.0d] %.0lf\n", Numbering, xy);
Sleep(250);
x = y;
y = xy;
F++;
Numbering++;
}
Sleep(1000);
}
if (Opt == '4'){
printf("Thank you for using my calculator. Hope to see you again!!");
Sleep(1990);
system("cls");
exit(0);
}
if (Opt != '1' && Opt!= '2' && Opt!= '3' && Opt != '4'){
printf("Wrong Option. Please retype your option correctly");
Sleep(2450);
system("cls");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T14:31:08.963",
"Id": "477225",
"Score": "1",
"body": "Why are there so many `Sleep` statements in your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T02:10:40.227",
"Id": "477253",
"Score": "0",
"body": "@AniruddhaDeb Oh, cause need to load, like i am trying not to display the output instantly, but with time gap, so it looks more appropriate. What are you views?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T03:10:48.057",
"Id": "477254",
"Score": "4",
"body": "I don't think you should do that in this case. It would be embarrassing if a pocket calculator finds the answer quicker than yours :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T10:53:31.503",
"Id": "477274",
"Score": "3",
"body": "You only display loading animations to give the user something to look at if you actually take a long time to load... If your app can load instantly, then there's no point in wasting time to display animations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T04:08:05.400",
"Id": "478323",
"Score": "0",
"body": "@UnfreeHeX It doesn't look more appropriate. It looks just like any other braindead bloatware that wastes people's time to do the simplest of things. Do not emulate stupidity. It doesn't make it look good. Those \"loading\" screens are horrible, they are an usually an indicator that the software is crap. Please, don't propagate this. Be happy you can have something that can be easily made fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T04:10:33.337",
"Id": "478324",
"Score": "0",
"body": "@ReinstateMonica Ouh, cause for school project, just for the content, i added it. will remove it. Thanks fro the suggestion. But the question is will unanswered though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T16:09:26.097",
"Id": "478378",
"Score": "0",
"body": "You probably want to decorate more. [Look here](https://codereview.stackexchange.com/a/243723/224270)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:42:56.910",
"Id": "478696",
"Score": "0",
"body": "Fwiw the header file `windows.h` is not standard and neither is using the command `cls` as that's a Windows (or I guess DOS) thing. In other words your program isn't portable. That might not be a problem for your case but just thought you should know (maybe someone else already said this but in case not)."
}
] |
[
{
"body": "<blockquote>\n <p>My requirement requires me to have indentation. I am unsure how to apply that indentation in my code.</p>\n</blockquote>\n\n<p>Just indent your C code exactly the same way you'd indent Python code. Start at the left margin (column 0), and then each time you \"go in a level\" (in the body of a function, or an <code>if</code> or <code>while</code> or <code>for</code>, or when breaking an expression across multiple lines), just space over by 4. For example, you wrote this before:</p>\n\n<pre><code> if (Opt == '1'){\n printf(\"Welcome to Normal maths operation Mode.\\n\\nYour two numbers: \");\n scanf(\"%f%f\", &Num1, &Num2);\n printf(\"\\nAVAILABLE SYMBOLS:\\n\\n+ for Addition\\n- for Subtraction\\n/ for Division\\n* for Multiplication\\n^ for Power function\\n\\nYour input: \");\n scanf(\" %c\", &oper);\n if (oper == '+'){\n ans = (Num1 + Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (To 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n } else if (oper == '-'){\n ans = (Num1 - Num2);\n</code></pre>\n\n<p>Instead, just think \"What would Python do?\" and then do that.</p>\n\n<pre><code> if (Opt == '1') {\n printf(\"Welcome to Normal maths operation Mode.\\n\\n\");\n printf(\"Your two numbers: \");\n scanf(\"%f%f\", &Num1, &Num2);\n printf(\n \"\\nAVAILABLE SYMBOLS:\\n\\n\"\n \"+ for Addition\\n\"\n \"- for Subtraction\\n\"\n \"/ for Division\\n\"\n \"* for Multiplication\\n\"\n \"^ for Power function\\n\\n\"\n );\n printf(\"Your input: \");\n scanf(\" %c\", &oper);\n if (oper == '+') {\n ans = Num1 + Num2;\n printf(\"Here is your answer:\\n\");\n printf(\n \"%f %c %f = %.5f (To 5 decimal places)\\n\\n\",\n Num1, oper, Num2, ans\n );\n Sleep(2450);\n } else if (oper == '-') {\n ans = Num1 - Num2;\n</code></pre>\n\n<p>Another good solution is to run <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"noreferrer\"><code>clang-format</code></a> over your source file, or use a text editor that understands curly braces and can indent for you.</p>\n\n<hr>\n\n<pre><code>#define PI 3.141592654\nload(); //Function is being referred at first so as to use it in main.\nint main(void)\n</code></pre>\n\n<p>Whoa — there's a comment on that line! I didn't even see it in your question, because you'd put it insanely far over to the right. Don't do that. You <em>want</em> people to see these comments; that's why you wrote them, right? So indent them just as you would in Python.</p>\n\n<p>Secondly: <code>load();</code> is a function call expression (or in this case, an expression statement). You can't have a function call just dangling out at file scope. Every statement must go inside some function (e.g. <code>main</code>).</p>\n\n<p>But, I can tell from context that what you mean was to <em>forward-declare</em> the function <code>load</code>. The way you write a function declaration in C is, exactly the same as a function definition — except you omit the body! So, to forward-declare</p>\n\n<pre><code>void load() {\n ...\n}\n</code></pre>\n\n<p>you would write</p>\n\n<pre><code>//Function is being referred at first so as to use it in main.\nvoid load();\n</code></pre>\n\n<p>(The comment is pretty pointless, actually. I just included it to show how you should indent comments, i.e., nothing special.)</p>\n\n<hr>\n\n<p>Finally, that <code>#define</code> for <code>PI</code>:</p>\n\n<ul>\n<li><p>The C standard library already defines <code>M_PI</code> in <code><math.h></code>. So you could have just used that.</p></li>\n<li><p>You only ever use <code>PI</code> as part of the expression <code>x * PI/180</code>. This looks a lot like \"converting <code>x</code> to radians.\" That's a named operation in English; it should be a named function in your C program.</p>\n\n<pre><code>#define PI 3.141592654\ndouble to_radians(double degrees) {\n return degrees * PI / 180;\n}\n</code></pre></li>\n</ul>\n\n<p>Now you have only a single use of <code>PI</code> in your whole program, and so you don't save anything by giving it a name. Eliminate the macro:</p>\n\n<pre><code>double to_radians(double degrees) {\n return degrees * (3.141592654 / 180.0);\n}\n</code></pre>\n\n<p>I've also parenthesized the constant part in hopes that the constant-folder will do the arithmetic ahead of time. That might be unnecessary, but it certainly can't hurt anything.</p>\n\n<hr>\n\n<p>In general, your <code>main</code> function is much much too long. Figure out some logical way to split it up into functions. For example, you might say</p>\n\n<pre><code>if (Opt == '1') {\n do_normal_maths_mode();\n} else if (Opt == '2') {\n do_trigonometric_function_mode();\n} else if (Opt == '3') {\n do_fibonacci_series_mode();\n} else if (Opt == '4') {\n print_greeting_and_exit();\n} else {\n printf(\"Wrong Option. Please retype your option correctly\\n\");\n Sleep(2450);\n system(\"cls\");\n}\n</code></pre>\n\n<p>Notice that I'm using a terminal <code>else</code> clause on my <code>if</code> — just like I would in Python! (although Python uses <code>elif</code> instead of <code>else if</code>) — so that any <code>Opt</code> other than 1, 2, 3, or 4 will drop into the <code>else</code> branch and print \"Wrong Option.\" You don't have to test <code>(Opt != '1' && Opt!= '2' && Opt!= '3' && Opt != '4')</code> manually.</p>\n\n<p>C does provide a control-flow structure that Python doesn't: the <em>switch</em>. It would look like this:</p>\n\n<pre><code>switch (Opt) {\n case '1':\n do_normal_maths_mode();\n break;\n case '2':\n do_trigonometric_function_mode();\n break;\n case '3':\n do_fibonacci_series_mode();\n break;\n case '4':\n print_greeting_and_exit();\n break;\n default:\n printf(\"Wrong Option. Please retype your option correctly\\n\");\n Sleep(2450);\n system(\"cls\");\n break;\n}\n</code></pre>\n\n<p>However, I wouldn't really recommend a <code>switch</code> in this case, because it's more lines of code and easier to mess up. (For example, you might accidentally forget one of those <code>break</code> statements.) Any mainstream compiler will generate equally efficient code for either version: the <code>if-else</code> chain or the <code>switch</code> statement.</p>\n\n<hr>\n\n<p>There's more that can be said, but I'll stop here. The big giant enormous issue is \"you need to break your code up into functions.\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T15:33:18.073",
"Id": "477228",
"Score": "3",
"body": "The constant macro `M_PI` in `math.h` is not in the C-standard, although it is in Posix (https://pubs.opengroup.org/onlinepubs/009695399/basedefs/math.h.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T17:01:13.323",
"Id": "477231",
"Score": "3",
"body": "\"Now you have only a single use of `PI` in your whole program, and so you don't save anything by giving it a name. Eliminate the macro\" It's fairly obvious in this case, but now you have a magic number that doesn't explain what the value is. There's also an extra `);` in your second code block after `printf`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T17:05:37.557",
"Id": "477232",
"Score": "0",
"body": "Extra `);`: fixed! Thanks. Re the self-explanatoriness of `3.14` in a function named `to_radians`: I suspect we agree more than we disagree. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T20:17:13.490",
"Id": "477242",
"Score": "2",
"body": "Please note that `load();`, in that position, is actually a declaration of a function that takes an unspecified number of parameters of unknown type implicitly returning an `int`. https://godbolt.org/z/cCyhfa"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:06:07.883",
"Id": "477389",
"Score": "0",
"body": "\"The C standard library already defines M_PI in <math.h>\" is false. [Using M_PI with C89 standard](https://stackoverflow.com/questions/5007925/using-m-pi-with-c89-standard). Applies to C99, C11, C17 too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T23:30:23.290",
"Id": "477398",
"Score": "2",
"body": "You use `system(\"cls\")` a lot. It would be more efficient to use [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) IF your terminal emulator supports them. From memory (not sure tho) newer Windows Console versions support them, as does Windows Terminal. The main advantage to this approach is the lack of an external process. Example Usage: `printf(\"\\x1B[2J\\x1B[H\");`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T13:30:24.407",
"Id": "478357",
"Score": "0",
"body": "@Quuxplusone \n\nHi sir, I have tried to improve from my past version; Are you able to rate it again? Sorry for bothering you too much though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:47:48.813",
"Id": "478699",
"Score": "0",
"body": "@UnfreeHeX If it bothers anyone it's their problem and not yours. Don't ever apologising for wanting to learn and trying to learn. It's nothing to be sorry for but something to be commended. Keep it up! A lot of people cannot ask for directions or any kind of help and they're the ones who stay behind."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T05:14:18.187",
"Id": "243134",
"ParentId": "243131",
"Score": "11"
}
},
{
"body": "<p>Please use a small function for print, sleep and clear screen:</p>\n\n<pre><code>void output(const char* msg, int sleep_time, int clear) {\n printf(\"%s\", msg);\n sleep(sleep_time);\n if (clear) system(\"cls\");\n}\n</code></pre>\n\n<p>Order of these functions can be you choice and you can control the sleep time using parameter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T13:40:23.850",
"Id": "477223",
"Score": "1",
"body": "Welcome to Code Review! It looks like your last sentence is incomplete. Did you perhaps mean to write a more complete answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T13:43:04.787",
"Id": "477224",
"Score": "0",
"body": "Thanks for the Welcome :)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T13:23:06.900",
"Id": "243144",
"ParentId": "243131",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>What are the various ways to improve the code(?)</p>\n</blockquote>\n\n<p><strong>PI</strong></p>\n\n<p>Why code a coarse machine pi as used in <code>double</code> math (good to 15+ decimal places) when a better value is a copy and paste away?</p>\n\n<p>Some systems provide <code>M_PI</code>. That is non-standard.</p>\n\n<pre><code>#ifdef M_PI\n#define PI M_PI\n#else\n// #define PI 3.141592654\n#define PI 3.1415926535897932384626433832795\n#endif\n</code></pre>\n\n<p><strong>Old style declaration</strong></p>\n\n<p><code>load();</code> does not declare the return type nor the parameters.</p>\n\n<pre><code>// load(); \nvoid load(void); \n</code></pre>\n\n<p><strong>FP precision</strong></p>\n\n<p><code>\"%.5f\"</code> makes small answers all \"0.00000\" and large values verbose 123456789012345.00000. Recommend instead <code>%.5g</code> which shifts to exponential notation for large and small values.</p>\n\n<p><strong>Code re-use</strong></p>\n\n<p>Below code repeated many times. Use a helper function.</p>\n\n<pre><code>void print_results(double NUm1, int oper, double Num2, double ans) {\n printf(\"Here is your answer:\\n%f %c %f = %.5f (To 5 decimal places)\\n\\n\", \n Num1, oper, Num2, ans);\n Sleep(2450);\n}\n</code></pre>\n\n<p>Samples calls</p>\n\n<pre><code> ...\n } else if (oper == '-'){\n print_results(Num1, oper, Num2, Num1 - Num2);\n } else if (oper == '/'){\n print_results(Num1, oper, Num2, Num1 / Num2);\n }\n ...\n</code></pre>\n\n<p><strong>Advanced: <code>sind(deg)</code> for large <code>deg</code></strong></p>\n\n<p>When code is attempting to do trig on large degree values, rather than scale by <code>PI/180</code> and then call <code>sin(), cos(), ...</code>, perform argument reduction in degrees as that can be done exactly - then scale. You will get better answers for large degree values. <a href=\"https://stackoverflow.com/q/31502120/2410359\">Sin and Cos give unexpected results for well-known angles</a>. Of course when only printing a few digits, you may not <em>see</em> this improvement often, yet it is there.</p>\n\n<pre><code> // ans = (sin (Num1 * PI/180));\n ans = fmod(Num1, 360);\n ans = sin(Num1 * PI/180);\n</code></pre>\n\n<p><strong>Simplify</strong></p>\n\n<p>With digits, a range test can be used</p>\n\n<pre><code>// if (Opt != '1' && Opt!= '2' && Opt!= '3' && Opt != '4'){\nif (Opt < '1' || Opt > '4') { \n</code></pre>\n\n<blockquote>\n <p>My requirement requires me to have indentation. I am unsure how to apply that indentation in my code.</p>\n</blockquote>\n\n<p>Life is too short to <em>manually</em> indent. Use (or find) your IDE's code formatter and use that.</p>\n\n<pre><code> // OP's\n if (oper == '+'){\n ans = (Num1 + Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (To 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n } else if (oper == '-'){\n ans = (Num1 - Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (to 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n } else if (oper == '/'){\n ans = (Num1 / Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (to 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code> // Eclipse\n if (oper == '+') {\n ans = (Num1 + Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (To 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n } else if (oper == '-') {\n ans = (Num1 - Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (to 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n } else if (oper == '/') {\n ans = (Num1 / Num2);\n printf(\"Here is your answer:\\n%f %c %f = %.5f (to 5 decimal places)\\n\\n\", Num1, oper, Num2, ans);\n Sleep(2450);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-14T15:45:11.077",
"Id": "478697",
"Score": "0",
"body": "I suppose the word `sind` is a typo in your answer for `sin` ? Oh and have a +1 for the well rounded answer - and for pointing out the range check (I was going to make an answer or comment about that but saw you already had that done)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T00:11:55.697",
"Id": "478742",
"Score": "0",
"body": "@Pryftan `sind(angle)` implies `angle` is in _degrees_, not _radians_."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:00:34.550",
"Id": "243234",
"ParentId": "243131",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243134",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T03:13:20.870",
"Id": "243131",
"Score": "8",
"Tags": [
"beginner",
"c"
],
"Title": "Math Calculator in C"
}
|
243131
|
<p>This question is related to my previous two questions, in which I have implemented <a href="https://codereview.stackexchange.com/questions/242900/implement-hash-table-using-linear-congruential-probing-in-python"><code>HashTable</code></a>, and also <a href="https://codereview.stackexchange.com/questions/243113/implement-sorted-list-and-bst-as-sorted-maps-in-python"><code>SortedListMap</code> and <code>BinarySearchTree</code></a>. Since the three types of mappings have similar interfaces, if I wrote three separate tests for them there would be lots of boilerplate codes. Instead I decided to write a single test script (using pytest) to test all three at once. It was tricky and took me a lot of time to set up the fixtures correctly, but finally I managed it and all tests were passed.</p>
<p><strong>Summary of the three types of mappings and what I want to do in the test code:</strong></p>
<ol>
<li>All three types of mappings are subclasses of the abstract base class <code>MutableMapping</code>. They all have the methods <code>__len__</code>, <code>__iter__</code>, <code>__getitem__</code>, <code>__setitem__</code>, <code>__delitem__</code> required by <code>MutableMapping</code>, so I need to write test classes to test these methods on all three of them.</li>
<li><code>SortedListMap</code> and <code>BinarySearchTree</code> are also sorted mappings. Although I didn't make <code>SortedMapping</code> into an explicit abstract base class, as sorted mappings they both have the <code>minimum</code>, <code>maximum</code>, <code>predecessor</code> and <code>successor</code> methods, which needs separate test classes than those mentioned in 1.</li>
<li>I want to test on a small number of fixed inputs as well as a large number of random inputs.</li>
<li>In total I need four test classes: unsorted maps and fixed inputs, unsorted maps and random inputs, sorted maps and fixed inputs, sorted maps and random inputs.</li>
</ol>
<p>Below is my test code:</p>
<pre><code>import collections
import random
from string import ascii_lowercase
from itertools import product
import pytest
from hash_table import HashTable
from sorted_list_map import SortedListMap
from binary_search_tree import BinarySearchTree
"""Map Classes that we are testing."""
UNSORTED_MAPS = [HashTable, SortedListMap, BinarySearchTree]
SORTED_MAPS = [SortedListMap, BinarySearchTree]
"""Constants and a fixture for testing small fixed inputs.
The keys are deliberately repeated to test whether the maps contain repeated keys.
"""
KEYS = ['A', 'B', 'C', 'C', 'A', 'D', 'E', 'F',
'G', 'G', 'G', 'H', 'E', 'I', 'A', 'J',
'K', 'L', 'D', 'J', 'F', 'L', 'B', 'K']
KEY_SET = set(KEYS)
SORTED_KEYS = sorted(KEY_SET)
ITEMS = [(key, i) for i, key in enumerate(KEYS)]
DICT_ITEMS = dict(ITEMS).items()
SORTED_ITEMS = sorted(DICT_ITEMS)
@pytest.fixture(scope='class')
def fixed_input_map(request):
"""Return a map of the requested map class with the given fixed items."""
my_map = request.param(ITEMS)
return my_map
"""Constants, fixtures and helper functions for testing large random inputs.
The keys are drawn at random from the list of all strings of 3 lowercase letters.
"""
KEY_LEN = 3
POSSIBLE_KEYS = [''.join(chars) for chars in product(ascii_lowercase,
repeat=KEY_LEN)]
@pytest.fixture(scope='class')
def map_pair(request):
"""Return a map of the requested map class and also a python dictionary.
In the tests, we would compare our maps with the python dicts.
Since the scope is 'class', this fixture actually return the same
my_map and python_dict instances for every test within the same test class.
This means all modifications to my_map and python_dict done by previous tests
are carried over to later tests.
"""
my_map = request.param()
python_dict = {}
return my_map, python_dict
def random_setitem(my_map, python_dict):
"""Helper function for adding random items into my_map and python_dict.
Number of added items equals number of possible keys.
But since there are repeated added keys, not all possible keys are added.
"""
added_keys = random.choices(POSSIBLE_KEYS, k=len(POSSIBLE_KEYS))
for i, key in enumerate(added_keys):
my_map[key] = i
python_dict[key] = i
return my_map, python_dict
def random_delitem(my_map, python_dict):
"""Helper function for removing random items from my_map and python_dict.
Number of removed items is chosen to be 2/3 of the existing items.
"""
num_dels = len(python_dict) * 2 // 3
removed_keys = random.sample(python_dict.keys(), k=num_dels)
for key in removed_keys:
del my_map[key]
del python_dict[key]
return my_map, python_dict
"""Test classes"""
@pytest.mark.parametrize('fixed_input_map', UNSORTED_MAPS, indirect=True)
class TestUnsortedMapFixedInput:
"""Test class for unsorted maps with small fixed inputs."""
def test_len(self, fixed_input_map):
"""Test the __len__ method."""
assert len(fixed_input_map) == len(KEY_SET)
def test_iter(self, fixed_input_map):
"""Test the __iter__method.
Since we don't care about the ordering, we cast the iterator into a set.
"""
assert set(key for key in fixed_input_map) == KEY_SET
@pytest.mark.parametrize('key, value', DICT_ITEMS)
def test_getitem(self, fixed_input_map, key, value):
"""Test the __getitem__ method for all (key, value) pair."""
assert fixed_input_map[key] == value
@pytest.mark.parametrize('key', KEY_SET)
def test_delitem(self, fixed_input_map, key):
"""Test the __delitem__ method for all keys. After deleting a key,
getting and deleting the same key should raise a KeyError.
"""
del fixed_input_map[key]
with pytest.raises(KeyError):
fixed_input_map[key]
with pytest.raises(KeyError):
del fixed_input_map[key]
def test_empty(self, fixed_input_map):
"""After deleting all items, the map should be empty."""
assert len(fixed_input_map) == 0
@pytest.mark.parametrize('map_pair', UNSORTED_MAPS, indirect=True)
class TestUnsortedMapRandomInput:
"""Test class for unsorted maps with large random inputs.
We added a large number of random items to each map and assert that the length
of the map and the set of items are correct, then we randomly remove 2/3 of
the items and assert again. The process is repeated three times.
"""
def test_first_setitem(self, map_pair):
my_map, python_dict = random_setitem(*map_pair)
assert len(my_map) == len(python_dict)
assert set(my_map.items()) == set(python_dict.items())
def test_first_delitem(self, map_pair):
my_map, python_dict = random_delitem(*map_pair)
assert len(my_map) == len(python_dict)
assert set(my_map.items()) == set(python_dict.items())
def test_second_setitem(self, map_pair):
my_map, python_dict = random_setitem(*map_pair)
assert len(my_map) == len(python_dict)
assert set(my_map.items()) == set(python_dict.items())
def test_second_delitem(self, map_pair):
my_map, python_dict = random_delitem(*map_pair)
assert len(my_map) == len(python_dict)
assert set(my_map.items()) == set(python_dict.items())
def test_third_setitem(self, map_pair):
my_map, python_dict = random_setitem(*map_pair)
assert len(my_map) == len(python_dict)
assert set(my_map.items()) == set(python_dict.items())
def test_third_delitem(self, map_pair):
my_map, python_dict = random_delitem(*map_pair)
assert len(my_map) == len(python_dict)
assert set(my_map.items()) == set(python_dict.items())
@pytest.mark.parametrize('fixed_input_map', SORTED_MAPS, indirect=True)
class TestSortedMapFixedInput:
"""Test class for sorted maps with small fixed inputs."""
def test_minimum(self, fixed_input_map):
"""Test the minimum method."""
assert fixed_input_map.minimum() == SORTED_ITEMS[0]
def test_maximum(self, fixed_input_map):
"""Test the maximum method."""
assert fixed_input_map.maximum() == SORTED_ITEMS[-1]
def test_no_predecessor(self, fixed_input_map):
"""Test the predecessor method for the smallest key,
which results in a KeyError."""
with pytest.raises(KeyError):
fixed_input_map.predecessor(SORTED_KEYS[0])
def test_no_successor(self, fixed_input_map):
"""Test the successor method for the largest key,
which results in a KeyError."""
with pytest.raises(KeyError):
fixed_input_map.successor(SORTED_KEYS[-1])
@pytest.mark.parametrize('key', SORTED_KEYS[1:])
def test_predecessor(self, fixed_input_map, key):
"""Test the predecessor method for all but the smallest key."""
prev_item = SORTED_ITEMS[SORTED_KEYS.index(key) - 1]
assert fixed_input_map.predecessor(key) == prev_item
@pytest.mark.parametrize('key', SORTED_KEYS[:-1])
def test_successor(self, fixed_input_map, key):
"""Test the successor method for all but the largest key."""
next_item = SORTED_ITEMS[SORTED_KEYS.index(key) + 1]
assert fixed_input_map.successor(key) == next_item
@pytest.mark.parametrize('map_pair', SORTED_MAPS, indirect=True)
class TestSortedMapRandomInput:
"""Test class for sorted maps with large random inputs.
Similar to TestUnsortedMapRandomInput, we randomly add and remove items
three times, but we test whether the lists of keys are sorted instead.
"""
def test_first_setitem(self, map_pair):
my_map, python_dict = random_setitem(*map_pair)
assert list(my_map) == sorted(python_dict)
def test_first_delitem(self, map_pair):
my_map, python_dict = random_delitem(*map_pair)
assert list(my_map) == sorted(python_dict)
def test_second_setitem(self, map_pair):
my_map, python_dict = random_setitem(*map_pair)
assert list(my_map) == sorted(python_dict)
def test_second_delitem(self, map_pair):
my_map, python_dict = random_delitem(*map_pair)
assert list(my_map) == sorted(python_dict)
def test_third_setitem(self, map_pair):
my_map, python_dict = random_setitem(*map_pair)
assert list(my_map) == sorted(python_dict)
def test_third_delitem(self, map_pair):
my_map, python_dict = random_delitem(*map_pair)
assert list(my_map) == sorted(python_dict)
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li>Is using <code>@pytest.mark.parametrize</code> to test different classes with similar interfaces a good idea?</li>
<li>There are tests that depend on the results of previous tests, especially when it comes to deleting items and random inputs. Is this a bad practice?</li>
<li>It is difficult to test <code>__setitem__</code> separately since all other methods depend on it. How can I write a separate test case for <code>__setitem__</code>?</li>
<li>Did I use too many global constants in the test script?</li>
<li>What else can I improve my test code?</li>
</ol>
|
[] |
[
{
"body": "<p>Please consider below as opinions, not the source of truth. I write what 'should' be but read it as 'I think it should...'</p>\n\n<p>As for your questions:</p>\n\n<p>1) \nIt is not a good idea. For me, <code>parametrize</code> decorator means 'those are the inputs to the function you are testing' not 'this is the function that you are testing'.</p>\n\n<p>2) \nI think it is a bad practice. Unit tests should be designed to be not dependend on anything else except fixture (or any other setup). I've seen E2E tests being done in the way that you desceibe and it always lead to cascading tests which slowed down pipelines for no reason.</p>\n\n<p>Also, by doing dependency like this you are violating an important rule: 'UT should break for one reason', it should not break because some other test broke. </p>\n\n<p>Lastly, you are preventing yourself from running those concurrently which is very important should your codebase ever become very big. </p>\n\n<p>3) I agree it is not convinient but not impossible. For most of the tests you can simply mock this method to return what you want it to return. However, I can imagine that this might be too time consuming and maybe hard to maintain (?). I would let it slide, I don't think it would provide much gain vs cost. </p>\n\n<p>4) I personally would use inheritance to pass the values around, global variables take away a freedom of modyfying input to test one specific thing.\nHowever, I think it is personal choice, if you would be working with a team you would probably have some guidelines about that. </p>\n\n<p>5)</p>\n\n<p>a)\nAs I expressed in 1), I would not utilize your approach. I would rather create a base class for all the tests and create one test class per class tested. There are multiple reasons for that however, the most important one is that the classes might diverge in the future and you would have to rewrite your suite. I don't mind duplication a long as it is justified. </p>\n\n<p>b)\nIn general, I would prefer to use <code>self.assert*</code> instead of <code>assert x == y</code> (see <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unittest.TestCase</a>). It gives much more information than just simple True/False.</p>\n\n<p>c)\nI would not add any randomness to UT. From my experience, it only provides confusion and <a href=\"https://en.wikipedia.org/wiki/Heisenbug\" rel=\"nofollow noreferrer\">heisenbugs</a>. Imagine that you have a pipeline with tests, one test failes, you rerun the pipeline and the test passes. Now, you can do two things:\n1. Say it was a transient issue so you will not look into it, maybe some build problems, maybe one of the test servers failed - who knows.\n2. Spend time to rerun the test X times until the random generator creates a failing test case. </p>\n\n<p>However, if you would create non-random tests, you <em>could</em> detect the problem locally (you might as well not detect it as well). I prefer reproducibility. Furthermore, it might be the case that you will never randomise a failing sequence because your local setup has a different random sequences than the ones on the server. My opinion on this is strictly for unit tests. For random tests I would use <a href=\"https://en.wikipedia.org/wiki/Fuzzing\" rel=\"nofollow noreferrer\">fuzzy testing</a> approach and make it in a different test suite.\nSee <a href=\"https://stackoverflow.com/q/32458/3809977\">this SO question</a> to choose what is the best for you as it all depends. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T01:55:11.990",
"Id": "477536",
"Score": "0",
"body": "Thank you for your advice! Could you give an overview or some pseudocodes of how you would write the tests in this case (testing three types of mappings)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T10:16:49.307",
"Id": "243216",
"ParentId": "243132",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243216",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T03:54:33.897",
"Id": "243132",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"unit-testing"
],
"Title": "Is this a good unit test for testing three types of mappings all at once?"
}
|
243132
|
<p>Intending to reuse the installation process of a <a href="https://extensions.gnome.org/" rel="noreferrer">GNOME extension</a>, I wrote the following script:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
# It installs a target gnome shell extension defined via url
STORE_URL="https://extensions.gnome.org/extension-data"
EXTENSIONS_PATH="$HOME/.local/share/gnome-shell/extensions/"
ZIP="gnome-extension.zip"
cd ~/Downloads
wget $STORE_URL/$1 -O ./$ZIP
UUID=$(unzip -c $ZIP metadata.json | grep uuid | cut -d \" -f4)
if [[ ! -d $EXTENSIONS_PATH/$UUID ]]; then
mkdir $EXTENSIONS_PATH/$UUID
unzip -q ./$ZIP -d $EXTENSIONS_PATH/$UUID
gnome-shell-extension-tool -e $UUID
fi
rm $ZIP
gnome-shell --replace &
</code></pre>
<blockquote>
<p>It expects to receive as argument the <em>target extension zip name</em>, one available from <a href="https://extensions.gnome.org/" rel="noreferrer">official GNOME extensions index</a>. The zip file, after downloaded, will be unzipped in its <code>UUID</code> directory inside GNOME extensions' location and then enable.</p>
</blockquote>
<p>Is there something else could be done to improve this installation process?
Any of the executed commands could be improved or code get better readability?</p>
|
[] |
[
{
"body": "<p>First off, install <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">Shellcheck</a> and routinely run it on your scripts, or configure your editor to run it automatically. Now, Shellcheck is <em>pretty rigorous</em> and you would be forgiven for not solving all its warnings, but at the very least be aware of them.</p>\n<blockquote>\n<pre><code>#!/bin/bash\n</code></pre>\n</blockquote>\n<p>On some systems there’s a more up to date bash installed in a different location. In general you’d want to use</p>\n<pre><code>#!/usr/bin/env bash\n</code></pre>\n<p>Though in the case of Bash on Linux I think yours is OK.<sup>1</sup></p>\n<p>Next, enable stricter error checking:</p>\n<pre><code>set -euo pipefail\n</code></pre>\n<p>From <code>help set</code>:</p>\n<blockquote>\n<ul>\n<li><code>-e</code> Exit immediately if a command exits with a non-zero status.</li>\n<li><code>-u</code> Treat unset variables as an error when substituting.</li>\n<li><code>-o</code> <code>pipefail</code> the return value of a pipeline is the status of\nthe last command to exit with a non-zero status,\nor zero if no command exited with a non-zero status</li>\n</ul>\n</blockquote>\n\n<p>Regarding your variables, there’s a convention to use <code>UPPER_CASE</code> for environment variables, and <code>snake_case</code> for others. Not mandatory, but a nice way to distinguish them.</p>\n<blockquote>\n<pre><code>wget $STORE_URL/$1 -O ./$ZIP\n</code></pre>\n</blockquote>\n<p>Even though <em>in this specific case</em> there are no spaces or other special characters in your variables, <em>always</em> double-quote them to prevent string splitting — there’s simply no reason ever not to do so, and it gets you into the habit of spotting potential errors when quotes are missing.</p>\n<blockquote>\n<pre><code>cd ~/Downloads\n</code></pre>\n</blockquote>\n<p>That directory might or might not exist. As we’re talking about a GNOME environment, you might want to use something like <code>$(xdg-user-dir DOWNLOAD)</code> to get the actual download directory. The same is <em>usually</em> true for the path <code>~/.local/share</code>, but <a href=\"https://help.gnome.org/admin/system-admin-guide/stable/extensions.html.en\" rel=\"nofollow noreferrer\">the GNOME shell extensions documentation</a> makes it sound as if the path is actually hard-coded.</p>\n<blockquote>\n<pre><code>rm $ZIP\n</code></pre>\n</blockquote>\n<p>This will not be executed if the script failed earlier due to an error. To ensure cleanup on error or if the user aborted the script, replace this with a <a href=\"https://ss64.com/bash/trap.html\" rel=\"nofollow noreferrer\">trap</a>.</p>\n<p>Resulting script:</p>\n<pre><code>#!/usr/bin/env bash\n\n# Install a target gnome shell extension defined via url\n\nset -euo pipefail\n\nstore_url="https://extensions.gnome.org/extension-data"\nextensions_path="$HOME/.local/share/gnome-shell/extensions/"\nzip="gnome-extension.zip"\n\ncd "$(xdg-user-dir DOWNLOAD)"\nwget "$store_url/$1" -O "$zip"\ntrap 'rm "$zip"' ERR INT TERM EXIT\n\nuuid=$(unzip -c "$zip" metadata.json | grep uuid | cut -d \\" -f4)\n\nif [[ ! -d "$extensions_path/$uuid" ]]; then\n mkdir "$extensions_path/$uuid"\n unzip -q "$zip" -d "$extensions_path/$uuid"\n gnome-shell-extension-tool -e "$uuid"\nfi\n\ngnome-shell --replace &\n</code></pre>\n<hr />\n<p><sup>1</sup> On macOS, on the other hand, it’s a <em>bad idea</em> since the Bash version of <code>/bin/bash</code> is eternally stuck at 3.2 <a href=\"https://thenextweb.com/dd/2019/06/04/why-does-macos-catalina-use-zsh-instead-of-bash-licensing/\" rel=\"nofollow noreferrer\">due to licensing issues</a>, and if you want to use any more recent Bash features you need to rely on a user-installed version with a different path.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T01:21:14.467",
"Id": "477535",
"Score": "0",
"body": "Thanks for the revision! Trap, double quotes and error checking will get in to my bash code mores"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T13:39:41.040",
"Id": "243145",
"ParentId": "243133",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "243145",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T04:52:25.023",
"Id": "243133",
"Score": "9",
"Tags": [
"bash"
],
"Title": "Installing GNOME extension via CLI"
}
|
243133
|
<p>I'm working on a program that takes website links and extracts the website name. Right now, it works perfectly, but it is very much a brute force approach and very ugly in my opinion.</p>
<p>Some of the properties of the links are as follows:
- entirely random
- will all contain https:// and .com
- may not contain www.</p>
<p>Here's a random link that I pulled up while shopping to give an example of what I'm talking about. Just to be 100% clear.</p>
<pre><code>https://www.walmart.com/ip/Glencairn-Crystal-Whiskey-Glass-Set-of-2-Hailed-as-The-Official-Whiskey-Glass/183116827
remove 'https://www.'
remove '.com/....827'
result = walmart
</code></pre>
<p>And here is the code for it all:</p>
<pre><code>f = open("Links.txt").read().split("\n")
f.remove('')
results = []
for i in f:
if 'https://' in i:
results.append(i[8:])
f = results
results = [f[0]]
for i in f:
if 'www.' in i:
results.append(i[4:])
f = results
results = []
for i in f:
results.append(i[:i.find('.com')])
f = open("Results.txt", 'w')
for i in results:
f.write(i + "\n")
f.close()
</code></pre>
<p>I tried cleaning it up with the <code>re</code> module, but it was throwing some errors when trying to search using <code>re.search('www.(.*).com', f)</code>.</p>
<p>I was thinking about using the <code>[a:]</code> through <code>[:b]</code> notation in python, but since each link may not have <code>'www.'</code> it seemed like it would be a faulty solution.</p>
<p>As I mentioned, this code works perfectly well. It's just such a simple thing that I want to get some practice in computer science and make it look like an elegant-ish solution.</p>
|
[] |
[
{
"body": "<p>You described the idea very clearly, thanks for the example that you gave.</p>\n\n<p>The code looks only half-baked though.</p>\n\n<p>The most important part in getting the code right is to know all involved concepts and how these are called officially. When you know the correct names, you can search for them, and most probably someone else has already programmed everything you need, you just need to stick the parts together.</p>\n\n<p>The official term for the lines from <code>Links.txt</code> is URL or URI. These have a well-known format, and Python provides a module to extract the various parts from URLs. For example, googling for \"python split url\" directly links to the <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"nofollow noreferrer\">Python urllib module</a>, which provides a few examples with their corresponding code.</p>\n\n<p>The part of the URL that you are interested in is called the <code>hostname</code>. For the Walmart URL you gave, this would be <code>www.walmart.com</code>.</p>\n\n<p>Finding the \"most interesting part\" of a hostname is not as trivial as it may seem at first. There are countries in which the \"top-level domain\" actually consists of two parts, for example the University of London can be found at <code>london.ac.uk</code>. Once you know the terms \"domain\" and \"top-level\" and \"second-level\", you can google for it at find <a href=\"https://stackoverflow.com/questions/4916890/extract-2nd-level-domain-from-domain-python\">this question</a>.</p>\n\n<p>To test and improve your code, you should split up the work into several small tasks. One of these tasks is to find the \"interesting part of the host name\" of a URL. In Python, you define a function for this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def main_host_name(url: str) -> str:\n ...\n</code></pre>\n\n<p>By giving a name to this function and explicitly declaring the parameter and return type, you give the reader of your code a lot of helpful information. It's also easier to test simple pieces of code like this function, rather than the code that reads a whole file and transforms all the links in it.</p>\n\n<p>The variable names in your code are mostly confusing. The computer does not care how you name the variables, but human readers do. By convention, the variable <code>f</code> stands for a file. In your code though, you store a list of lines in it. Therefore a better name for the <code>f</code> at the top of the code is <code>lines</code>.</p>\n\n<p>Next, you wrote <code>for i in f</code>. This is too cryptic. It's much easier if the code reads <code>for line in lines</code>.</p>\n\n<p>At the bottom of the code you do something very unusual. You assign a value of a <em>different type</em> to the same variable that you already used before. In the upper half of the code, <code>f</code> is a list of strings, and in the lowest part of the code, it's a file. That's confusing for human readers.</p>\n\n<p>There is no need that you only use 3 different variable names. You can (almost) choose whatever name you want for the variables. There is absolutely no requirement to have single-letter names. That was common in the 1970s and still is in code from mathematicians or physicists, but that's only because these people are accustomed to abbreviated names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T01:12:41.347",
"Id": "477307",
"Score": "0",
"body": "Thanks for the info! I actually do come from math/physics, which I suppose would explain my use of single letter variable names. But you are right. I will go spruce them up. I think the hardest part of any problem is beginning to accurately describe it. Thanks for laying things out! It's a great answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T09:51:01.820",
"Id": "243140",
"ParentId": "243136",
"Score": "1"
}
},
{
"body": "<p>As mentioned in the answer by Roland Illig, there is a module for that.</p>\n\n<p>Example:</p>\n\n<pre><code>from urllib.parse import urlparse\n\ndef get_domain_name(url: str) -> str:\n \"\"\"Return domain name from URL\n \"\"\"\n parsed_uri = urlparse(url)\n return parsed_uri.hostname\n\n\nget_domain_name('https://www.ucl.ac.uk/alumni/services')\n</code></pre>\n\n<p>Result:</p>\n\n<pre>\n'www.ucl.ac.uk'\n</pre>\n\n<p>NB: this requires a full URL with http/https scheme.</p>\n\n<p>Third-level domain extensions are handled with no problems. This is the prefered approach. The Python philosophy is that there should be one obvious way of accomplishing a given task. It doesn't have to be more complicated.</p>\n\n<p>if you know all domain names will end in .com and want to get rid of it, just add <code>.replace('.com', '')</code>.</p>\n\n<p>A regular expression can also get the job done. Something like this will return <code>walmart</code>:</p>\n\n<pre><code>^https://(?:www\\.)?([a-z0-9_\\-]+)\\.com\n</code></pre>\n\n<p>Assuming that the URL always starts with <code>https://</code>, and the domain name ends in .com, with <code>www.</code> optional and not included in the <strong>capture group</strong>. </p>\n\n<p>To explain this bit: <code>(?:www\\.)?</code>\nThe rightmost question mark means the expression in parentheses is optional. <code>?:</code> means: match the expression but do not capture it.</p>\n\n<p>This is not an all-purpose expression, it is adjusted to your circumstances and should be good enough for your needs but that's it.</p>\n\n<p>Let's say you have more complicated cases with subdomains, as an example:</p>\n\n<pre><code>url = 'www.subdomain.walmart.com'\n</code></pre>\n\n<p>Once you've got the full domain name, you could do some splitting then extract the relevant portions starting from the right, knowing that .com will be the last element:</p>\n\n<pre><code>bits=url.split('.')\nprint(bits)\n['www', 'subdomain', 'walmart', 'com']\nprint(bits[-2])\nwalmart\n</code></pre>\n\n<p>I think this is slightly more flexible than working with fixed lengths like you're doing.</p>\n\n<p>As for reading/writing files have a look at <strong>context managers</strong> (using the <code>with</code> statement).</p>\n\n<p>Your code is not very long but you would still benefit by keeping the parsing in one dedicated function (possibly two), out of your loop. That would make the whole code easier to read and maintain.</p>\n\n<p>One remark regarding <code>www.</code>: at some point you will find that some sites do redirect to <code>ww1</code> or <code>ww2</code> or stuff like that. Not to mention other types of subdomains. It is not safe to assume that the domain name will always be prefixed with <code>www.</code> or nothing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T01:32:39.917",
"Id": "477308",
"Score": "0",
"body": "This is great information! Thanks a lot! I'll get to work making the changes you guys suggested!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T04:59:27.430",
"Id": "477315",
"Score": "0",
"body": "Regarding the extraction of the \"interesting part\" from the host name: there's a module for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:01:21.270",
"Id": "477316",
"Score": "0",
"body": "And how would `replace` know that it should only remove the `.com` at the end, and not in `www.complicated.org`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T13:33:23.033",
"Id": "477354",
"Score": "0",
"body": "The OP said all his/her URLs would end in .com, so the code is clearly tailored to the situation. But it's not an all-purpose solution. It is 'good enough' and simple enough for the task."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T15:26:41.820",
"Id": "243149",
"ParentId": "243136",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243149",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T06:03:38.620",
"Id": "243136",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Extracting website names from link code cleanup"
}
|
243136
|
<p>I am just trying to understand the algorithm of the <a href="https://www.geeksforgeeks.org/maximum-sum-absolute-difference-array/" rel="nofollow noreferrer">problem statement</a> </p>
<blockquote>
<p>Given an array, we need to find the maximum sum of absolute difference of any permutation of the given array.</p>
</blockquote>
<p>Here is my implementation after following the algorithm mentioned in the link</p>
<pre><code>static int sumOfMaxAbsDiff(int[] arr) {
Arrays.sort(arr);
int len = arr.length;
int[] temp = new int[len];
int sum = 0;
for (int i = 0, j = 1, k = 0; i < len / 2; i++, j++, k++) {
temp[k] = arr[i];
temp[++k] = arr[len - j];
}
if (len % 2 != 0) { // Odd numbered length
temp[len - 1] = arr[len / 2]; // copy the middle element of arr to last place in temp
}
// Now accumulate sum
for (int i = 0; i + 1 < len; i++) {
sum += Math.abs(temp[i] - temp[i + 1]);
}
// max abs diff at last index - NOT sure of this
sum += Math.abs(temp[len - 1] - temp[0]); // assuming array size is >= 2
return sum;
}
</code></pre>
<p>I know why we have to sort, as we are trying to find max diff, it's obviously the least-highest
If we arrange the sequence as firstSmallest, firstLargest, and so on for a given input arr <code>[1,2,4,8]</code>
it would be <code>[1,8,2,4]</code>
Now, checking the max diff in forward direction, max diff at each index, it would be <code>7,6,2,?</code></p>
<p>2 questions</p>
<ol>
<li>For odd numbered length arr <code>[1,2,3,4,8]</code> why place middle at the end of arr?</li>
<li>And, for last index, why do we have to find abs difference between val at last index and first index?</li>
</ol>
<p>Is there is any better and clear algorithm to think about or links to apply for this</p>
|
[] |
[
{
"body": "<blockquote>\n <p>For odd numbered length arr [1,2,3,4,8] why place middle at the end of\n arr?</p>\n</blockquote>\n\n<p>The middle element in an odd numbered array, is the next highest element to be paired up. But since it is also the next lower element it doesn't have a pair, so it gets added by itself.</p>\n\n<blockquote>\n <p>And, for last index, why do we have to find abs difference between val\n at last index and first index?</p>\n</blockquote>\n\n<p>To my mind, the problem states 'maximum sum of absolute difference of any permutation'. The permutation of the lowest number on the high side of the sorted array and the lowest number wouldn't get added to the max sum otherwise.</p>\n\n<blockquote>\n <p>Is there is any better and clear algorithm to think about</p>\n</blockquote>\n\n<p>I believe there is. The idea of calculating the differences on the fly and adding to the max sum directly, has merit. It just needed tweaking a bit. Heres some working code for that concept:</p>\n\n<pre><code>static int MaxSumDifference2(int []a, int n) {\n Arrays.sort(a);\n int maxSum = 0;\n int low = 0;\n int high = a.length - 1;\n for(;low < high; ++low, --high){\n maxSum += a[high] - a[low] + a[high] - a[low + 1];\n }\n maxSum += a[low] - a[0];\n return maxSum;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T04:00:48.237",
"Id": "243197",
"ParentId": "243137",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T06:53:53.383",
"Id": "243137",
"Score": "3",
"Tags": [
"java",
"algorithm",
"programming-challenge"
],
"Title": "Max sum of abs difference in array"
}
|
243137
|
<p>Find the limit to the number of items that can be prepared with given amount of ingredients - </p>
<p>Let's try to understand with input/output pattern:<br>
<strong>Input</strong> </p>
<pre><code>4
2 5 6 3
20 40 90 50
</code></pre>
<p><strong>Output</strong> </p>
<pre><code>8
</code></pre>
<p>1st Line: Number Of Ingredients<br>
2nd Line: Each unit required from total ingredients given<br>
3rd Line: Each value represent total number of ingredients in our hand. </p>
<p><strong>Explanation:</strong><br>
for each item:</p>
<p>2 units will be used from 20<br>
5 units will be used from 40<br>
6 units will be used from 90<br>
3 units will be used from 50</p>
<p>until we run out of any ingredient.<br>
After 8th attempt we are running out with ingredient 40, and hence maximum items can be prepared will be 8.</p>
<p>I have proposed the below solution, written in Java and it is working fine for all the test cases, but for some test cases it is taking 1 sec of time to execute, I want to improve the code, Please suggest me some best practices applicable which is helpful in order to optimize the code.</p>
<pre><code>package com.mzk.poi;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class PowerPuffGirls {
private static final String SPACE = " ";
private static final Integer INITAL_IDX = 0;
private static final Integer LOWER_IDX = 1;
private static final Integer SECOND_IDX = 2;
private static final Integer MAX_LINES = 3;
private static final Integer UPPER_IDX = 10000000;
private static long[] quantityOfIngredients;
private static long[] quantityOfLabIngredients;
private static int size = 0;
private static long numberOfIngredients = 0;
/**
* This method will terminate the execution
*/
private static void terminate() {
System.exit(INITAL_IDX);
}
/**
* This method validated the input as per the specified range
*
* @param eachQunatity
* @return boolean
*/
private static boolean validateQuantityOfEachIngredients(long eachQunatity) {
return eachQunatity >= INITAL_IDX && eachQunatity > Long.MAX_VALUE ? true : false;
}
/**
* This helper method will parse the string and return long value
*
* @param input
* @return long
*/
private static long getNumberOfIngredients(String input) {
return Long.parseLong(input);
}
/**
* This method validates the first input
*
* @param noOfIngredients
* @return boolean
*/
private static boolean validateNumberOfIngredients(String noOfIngredients) {
numberOfIngredients = getNumberOfIngredients(noOfIngredients);
return numberOfIngredients >= LOWER_IDX && numberOfIngredients <= UPPER_IDX ? true : false;
}
/**
* This utility method convert the String array to Integer array
*
* @param size
* @param specifiedArrayOfUnits
* @return long[]
*/
private static long[] convertToLongArray(String[] arrayToBeParsed) throws NumberFormatException {
long array[] = new long[size];
for (int i = INITAL_IDX; i < size; i++) {
array[i] = Long.parseLong(arrayToBeParsed[i]);
}
return array;
}
public static void main(String[] args) {
String[] arrOfQuantityOfIngredients = null;
String[] arrOfQuantityOfLabIngredients = null;
Set<Long> maxPowerPuffGirlsCreationList = new HashSet<Long>();
Scanner stdin = new Scanner(System.in);
String[] input = new String[MAX_LINES];
try {
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
}
} finally {
stdin.close();
}
if (!validateNumberOfIngredients(input[INITAL_IDX])) {
terminate();
}
String quantityOfEachIngredients = input[LOWER_IDX];
String quantityOfEachLabIngredients = input[SECOND_IDX];
arrOfQuantityOfIngredients = quantityOfEachIngredients.split(SPACE);
arrOfQuantityOfLabIngredients = quantityOfEachLabIngredients.split(SPACE);
size = arrOfQuantityOfIngredients.length;
try {
quantityOfIngredients = convertToLongArray(arrOfQuantityOfIngredients);
for (int i = 0; i <= quantityOfIngredients.length - 1; i++) {
if (validateQuantityOfEachIngredients(quantityOfIngredients[i])) {
terminate();
}
}
quantityOfLabIngredients = convertToLongArray(arrOfQuantityOfLabIngredients);
for (int i = 0; i <= quantityOfLabIngredients.length - 1; i++) {
if (validateQuantityOfEachIngredients(quantityOfLabIngredients[i])) {
terminate();
}
}
for (int i = 0; i < numberOfIngredients; i++) {
long min = quantityOfLabIngredients[i] / quantityOfIngredients[i];
maxPowerPuffGirlsCreationList.add(quantityOfLabIngredients[i] / quantityOfIngredients[i]);
}
System.out.println(Collections.min(maxPowerPuffGirlsCreationList));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T11:58:50.603",
"Id": "477215",
"Score": "0",
"body": "Thanks @greybeard, any suggestion or best practice from your side"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T15:14:32.120",
"Id": "477227",
"Score": "0",
"body": "With *mathematics*, best practice is looking for generalisations, simplifications and abstractions. There is one applying to *subtract until what is left is too small*. \"Improving the code\" would mean a *code review* - probably not even when the sun is down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T15:45:14.240",
"Id": "477229",
"Score": "1",
"body": "Please come again, I am not able to understand what exactly you meant for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T03:48:09.123",
"Id": "477255",
"Score": "0",
"body": "(Now you've got [Gilbert Le Blanc's answer](https://codereview.stackexchange.com/a/243152/93149) for the math angle and [Bobby's](https://codereview.stackexchange.com/a/243153/93149) with coding advice: The grey is natural, my energy limited, and I've got to judiciously spend it.)"
}
] |
[
{
"body": "<p>I'm not going to rewrite the code.</p>\n\n<p>There's a simple mathematical way to get the answer to the problem. Using your example,</p>\n\n<pre><code>4\n2 5 6 3\n20 40 90 50\n</code></pre>\n\n<p>You can divide the total by the amount used in each recipe. Using integer division:</p>\n\n<pre><code>20 / 2 = 10\n40 / 5 = 8\n90 / 6 = 15\n50 / 3 = 16\n</code></pre>\n\n<p>The smallest answer is the answer.</p>\n\n<pre><code>8\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T07:23:19.427",
"Id": "477258",
"Score": "0",
"body": "Hi Gilbert, My code has been already working on the same logic, please see the single SOP statement, where I print the minimum value"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T17:05:44.970",
"Id": "243152",
"ParentId": "243138",
"Score": "4"
}
},
{
"body": "<p>Everything in your class is static, that's most likely not what you wanted.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class PowerPuffGirls {\n</code></pre>\n\n<p>Funny...or maybe not, stop that. In my experience, trying to be funny when writing code only results in somebody having to undo the funny. So don't do it in the first place.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static final String SPACE = \" \";\n</code></pre>\n\n<p>There's a fine line between obvious and useful variable names. This should rather be called <code>SEPARATOR</code> or <code>VALUE_SEPARATOR</code>.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static final Integer INITAL_IDX = 0;\n</code></pre>\n\n<p>That sounds like something that would never change and does not need to be a static variable, because you can always deduce the meaning from the context.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static final Integer INITAL_IDX = 0;\n</code></pre>\n\n<p>You might as well write <code>INTIAL_INDEX</code> here, you're not going to gain anything from shortening it.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void terminate() {\n System.exit(INITAL_IDX);\n}\n</code></pre>\n\n<p>Now that sounds wrong. First, <code>System.exit</code> does not terminate the JVM, it <em>exits</em>. The difference being that terminating the JVM would give it time to shutdown, execute finalizers and so on, <code>System.exit</code> will simply stop and kill the process. This might not be what you wanted.</p>\n\n<p>Also...why are you calling it with that constant?</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>return eachQunatity >= INITAL_IDX && eachQunatity > Long.MAX_VALUE ? true : false;\n</code></pre>\n\n<p>You can directly return the boolean expression:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>return eachQunatity >= INITAL_IDX && eachQunatity > Long.MAX_VALUE;\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>String[] arrOfQuantityOfIngredients = null;\n</code></pre>\n\n<p>Again, there is a fine line between obvious and useful names, <code>ingredientsQuantities</code> would be a better name.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>Scanner stdin = new Scanner(System.in);\n</code></pre>\n\n<p>That is a badly chosen variable name, <code>inputScanner</code> or <code>scanner</code> or even <code>input</code> would be a better one. <code>stdin</code> refers to the standard input stream, which is not the case here.</p>\n\n<p>Also you could use try-with-resources here:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (Scanner scanner = new Scanner(System.in)) {\n // TODO\n}\n</code></pre>\n\n<p>The resource will be automatically closed when leaving the block.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (!validateNumberOfIngredients(input[INITAL_IDX])) {\n terminate();\n}\n</code></pre>\n\n<p>Error reporting would be a nice addition.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i <= quantityOfIngredients.length - 1; i++) {\n</code></pre>\n\n<p>I'm still a fan of using descriptive names, like <code>index</code> or <code>counter</code>, but that just might be me.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>maxPowerPuffGirlsCreationList.add(quantityOfLabIngredients[i] / quantityOfIngredients[i]);\n</code></pre>\n\n<p>You want <a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">to read up in autoboxing</a>, it might not be important in this case, but it is something you should be aware of.</p>\n\n<hr>\n\n<p>Overall, if you wanted to have an object-oriented solution to your problem, you want more explicitness, a lot more. That starts by the input, something like this:</p>\n\n<pre><code>Please enter number of ingredients: 4\nPlease enter needed amount for ingredient #1: 2\nPlease enter needed amount for ingredient #2: 5\nPlease enter needed amount for ingredient #3: 6\nPlease enter needed amount for ingredient #4: 3\nPlease enter available amount for ingredient #1: 20\nPlease enter available amount for ingredient #1: 40\nPlease enter available amount for ingredient #1: 90\nPlease enter available amount for ingredient #1: 50\nYou can fabricate 8 items.\n</code></pre>\n\n<p>You could create a <code>Ingredient</code> class which holds the required amount as well as the available amount and use that throughout your program. Also, you might want to reconsider of having everything static, and you want to extract reading from stdin into its own class, so that you can, for example, easily add reading from a file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T20:25:55.447",
"Id": "477243",
"Score": "0",
"body": "I had expected that you commented on `System.exit` being called with an _index_, as that doesn't make sense at all. If you missed that, I can totally understand that, since the code offers so many other things to comment on. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T04:59:41.143",
"Id": "477256",
"Score": "0",
"body": "Actually, I saw it, then forgot to comment on it...thanks for reminding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T07:35:36.767",
"Id": "477259",
"Score": "0",
"body": "Thank Bobby for all the suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T07:36:13.230",
"Id": "477260",
"Score": "0",
"body": "Hey Roland, you can also comment on that and let me know the best practice or suggestions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T17:31:18.970",
"Id": "243153",
"ParentId": "243138",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243153",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T07:00:09.843",
"Id": "243138",
"Score": "2",
"Tags": [
"java"
],
"Title": "number of items that can be prepared with given ingredients"
}
|
243138
|
<p>This is my implementation of Clojure's <code>assoc-in</code> function. I am looking for tips on making it more idiomatic and in general, better.</p>
<pre class="lang-clj prettyprint-override"><code>(defn my-assoc-in
[m [& ks] v]
(let [sorted-keys (reverse ks)]
(loop [curr-key (first sorted-keys)
rem-keys (rest sorted-keys)
curr-map (get-in m (reverse rem-keys))
acc-val (assoc curr-map curr-key v)]
(if (empty? rem-keys)
acc-val
(let [next-key (first rem-keys)
next-rem (rest rem-keys)
next-map (get-in m next-rem)
next-val (assoc next-map next-key acc-val)]
(recur next-key next-rem next-map next-val))))))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T12:17:25.317",
"Id": "243143",
"Score": "2",
"Tags": [
"functional-programming",
"clojure",
"lisp"
],
"Title": "My implementation of Clojure's assoc-in"
}
|
243143
|
<p>So, I made this in order to practice my Python OOP and algorithms skills, and refactored it a bit after a few months of s tale. May anybody review it in a PR please? Want to see the flaws that could be fixed, considering I didn't improve much since the initial development of this.
<a href="https://github.com/fen0s/TABSlike/" rel="noreferrer">https://github.com/fen0s/TABSlike/</a>
One that especially makes me worries is the implementation of getting a 3x3 area around the unit to check for enemy units... Is it fine, and can you understand it overall?</p>
<pre><code>def check_surroundings(self, y_coord, x_coord):
y_coord -= 1 #to check y level above unit
enemies = []
for _ in range(3):
if self.engine.check_inbounds(y_coord, x_coord-1) and self.engine.check_inbounds(y_coord, x_coord+2):
for entity in self.engine.techmap[y_coord][x_coord-1:x_coord+1]:
if entity and entity.team != self.team:
enemies.append(entity)
y_coord+=1
return enemies
</code></pre>
|
[] |
[
{
"body": "<p>Your use of <code>y_coord</code> and <code>range</code> is suboptimal here. You're iterating over a <code>range(3)</code> and ignoring the produced number, while <em>also</em> using <code>y_coord</code> as an iteration variable.</p>\n\n<p>Just iterate over the range of numbers that you want from the start:</p>\n\n<pre><code>def check_surroundings(self, y_coord, x_coord):\n enemies = []\n for cur_y in range(y_coord - 1, y_coord + 2): # Exclusive end\n if self.engine.check_inbounds(cur_y, x_coord - 1) and self.engine.check_inbounds(cur_y, x_coord + 2):\n for entity in self.engine.techmap[cur_y][x_coord - 1:x_coord + 1]:\n if entity and entity.team != self.team:\n enemies.append(entity)\n return enemies\n</code></pre>\n\n<p>The main benefit here is the boost to readability. Ideally, it should be easy to tell what a <code>for</code> loop is iterating for just by looking at it.</p>\n\n<pre><code>for entity in self.engine.techmap[cur_y][x_coord - 1:x_coord + 1]:\n</code></pre>\n\n<p>It's obvious that you're getting all the matching entities from <code>techmap</code>, then doing something with each.</p>\n\n<pre><code>for _ in range(3):\n</code></pre>\n\n<p>Here though, you're ignoring the iteration variable, so it isn't clear what is actually changing each iteration. Superficially, it looks like you're just repeating the same body three times, which is odd. It takes a second step of thinking to realize that you're using <code>y_coord</code> to iterate.</p>\n\n<hr>\n\n<p>This is also arguably a good place to use a list comprehension (although 2D+ list-comprehensions usually tend a little on the ugly side). The point of your nested loops is to produce a filtered list from existing collections (the iterable returned by <code>techmap</code>, and <code>range</code> in this case). That is exactly the use-case for list comprehensions.</p>\n\n<pre><code>def check_surroundings(self, y_coord, x_coord):\n return [entity\n for cur_y in range(y_coord - 1, y_coord + 2)\n if self.engine.check_inbounds(y_coord, x_coord - 1) and self.engine.check_inbounds(y_coord, x_coord + 2)\n for entity in self.engine.techmap[cur_y][x_coord - 1:x_coord + 1]\n if entity and entity.team != self.team]\n</code></pre>\n\n<p>You may want to save that into a variable then return the variable. It depends on your style. I can't say that I <em>necessarily</em> recommend using the comprehension here, but I thought I'd show that such an option is available. I'll note too that I didn't test this; I eyeballed it. It looks like it should be equivalent though. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T21:45:40.080",
"Id": "243191",
"ParentId": "243147",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T14:41:56.130",
"Id": "243147",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"game"
],
"Title": "A little Python roguelike with mostly using standard libraries"
}
|
243147
|
<p>I submitted my solution for palindrome Index coding challenge but I get "test cases terminated due to time out error". My code is working and so I don't know what else to do to optimize it. Please help:</p>
<pre><code>function palindromeIndex(s) {
let palindrome = s === s.split('').reverse().join('')
if(!palindrome) {
let i = 0
let integerIndex = []
let arr = s.split('')
while(i < s.length) {
arr.splice(i,1)
if(arr.join('') === arr.reverse().join('')) {
integerIndex.push(i)
}
arr = s.split('')
i++
}
return integerIndex.length > 0 ? integerIndex[0] : - 1
}else {
return -1
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T17:54:52.527",
"Id": "477236",
"Score": "2",
"body": "Could you please add the text of the question and a link to the coding challenge to the body of this question? We need the exact specification of the coding challenge."
}
] |
[
{
"body": "<p>It may well be an error @ <a href=\"https://www.hackerrank.com/challenges/palindrome-index/problem\" rel=\"nofollow noreferrer\">Hackerrank</a>. If I'm not mistaken the nodejs-code expects you to provide console input. Or you may have accidentally changed something in the surrounding code.</p>\n\n<p>Concerning your code: writing ES20xx, it's good practice to terminate lines with a semicolon (<code>;</code>), because not doing so may result in <a href=\"https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/\" rel=\"nofollow noreferrer\">nasty bugs</a>. </p>\n\n<blockquote>\n <p><code>let palindrome = s === s.split('').reverse().join('')</code></p>\n</blockquote>\n\n<p>You don't need this variable. It could've been:</p>\n\n<p><code>if(s !== s.split('').reverse().join('')) {</code></p>\n\n<p>Furthermore, if you wanted to declare a variable, it could've been a <code>const</code> here (you are not modifying it afterwards).</p>\n\n<p>Just for fun, here's an alternative approach, using substrings from the original given string:</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>\"hannach,ava,reopaper,annana,ewve,blob,otto,michael,racecaar,wasitacatiwsaw\"\n .split(\",\")\n .forEach(name => console.log(`[${name}] => ${palindromeIndex(name)}`));\n \nfunction palindromeIndex(s) {\n if (`${[...s]}` === `${[...s].reverse()}`) { return \"is palindrome\"; }\n let i = 0;\n while(i < s.length) {\n const sx = `${i < 1 ? s.substr(1, 0) : s.substr(0, i)}${s.substr(i + 1)}`; \n const rsx = `${[...sx].reverse().join(\"\")}`;\n if (sx === rsx) {\n return `removing '${s[i]}' (@ position ${i}): '${sx}'`;\n };\n i += 1;\n }\n return -1;\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T18:14:12.273",
"Id": "243155",
"ParentId": "243151",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243155",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T16:55:29.267",
"Id": "243151",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"palindrome"
],
"Title": "Optimizing code solution for Palindrome Index-Hackerrank"
}
|
243151
|
<p><strong>note:</strong> You might be scared seeing the length of the post, but it's actually not that long because you don't need to read the compiler logs or the python code to understand my code (I wish StackExchange allowed foldable code like <a href="https://github.com/dear-github/dear-github/issues/166#issuecomment-236342209" rel="nofollow noreferrer">github</a>).</p>
<hr>
<p>I've been reading CodeReview for a while but this is my first post here. This is also my first Haskell program. I've tried to learn Haskell unsuccessfully before, so I was looking for a puzzle to program in haskell, to go head first in the world of pure functionnal programming.</p>
<p>The code bellow is basically a brute-force solution to <a href="https://youtu.be/M_YOCQaI5QI" rel="nofollow noreferrer">Matt Parker's Unique Distancing Problem</a>. The challenge is to find a way of arranging N counters on a N by N grid such that every distance is different, <a href="https://youtu.be/M_YOCQaI5QI" rel="nofollow noreferrer">Matt Parker's video</a> explains it well. I stepped up the difficulty a bit by generalising this to any dimensions (2 by 3 by 4 grid for example) and any number of counters.</p>
<p>So having nowhere to start, I made a python script in imperative style and gradually removed assignations and mutable object in favor of list comprehensions and functions. I then rewrote the program in Haskell, and spends countless hours searching things on the web. (I know my python code is very very bad but please focus on the haskell version.)</p>
<p>
Python Code</p>
<pre class="lang-py prettyprint-override"><code>import math
def nd_range(d):
return ((j,) + i for i in nd_range(d[1:]) for j in range(d[0])) if d else ((),)
def g(candidate, dists, counters, n, dims):
return () if counters and any((not d or d in dists or dists.add(d)) for d in (math.dist(candidate, counter) for counter in counters))else f(n - 1, dims, counters | {candidate})
def f(n, dims, counters=set()):
dists = {math.dist(i, j) for i in counters for j in counters}
return {x for candidate in nd_range(dims) for x in g(candidate, dists.copy(), counters, n, dims)} if n else {frozenset(counters)} if counters else set()
if __name__ == "__main__":
print(len(f(6, (6, 6))))
</code></pre>
<p></p>
<p>So, I have no idea on how to optimise Haskell code, I did A-B testing every time i made a modification to see if it was faster or slower. For 6 counters and a 6 by 6 grid, the Haskell code now takes 33s on my computer while Python takes 170s (unfair comparison since i've not writen good python).</p>
<p>
Haskell Code</p>
<pre class="lang-hs prettyprint-override"><code>import qualified Data.Set as Set
type P = [Int] -- Point
type S = Set.Set P -- Solution (Set of Point) :: Set [Int]
type SS = Set.Set S -- Set of possible Solutions (Set of Set of Points) :: Set Set [Int]
-- List the points of an N-Dimentionnal grid with dimentions given as [width, height, depth,...]
-- Example: nd_range [1,2,3] gives us [[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2]]
nd_range :: [Int] -> [P]
nd_range [] = [[]]
nd_range d = [(j : i) | j <- [0..(pred(head d))], i <- nd_range (tail d)]
-- returns the square of the distance between two N-Dimentionnal points
dist :: P -> P -> Int
dist a = sum . zipWith (((^2).).(-)) a
-- This function comes from https://codegolf.stackexchange.com/a/70539 and is noticeably faster than mine:
-- dist a b = sum (map (^2) (zipWith (-) a b))
countDists candidate i (dists, n)
| Set.member d dists = (dists, n)
| otherwise = (Set.insert d dists, n+1)
where d = dist candidate i
-- returns the set of all distances between points of a set
dists :: S -> Set.Set Int
dists counter = Set.fromList [ dist i j | i <- Set.toList counter, j <- Set.toList counter]
-- returns True if the point given satisfies the unique distancing constrain given the other points
isPossible :: P -> S -> Bool
isPossible candidate counter = snd (foldr (countDists candidate) (dists counter, 0) counter) == length counter
-- recursively runs for every possible points (back-tracking style) and flattens result into a set
f :: Int -> [Int] -> S -> SS
f 0 dims counter = Set.singleton counter
f n dims counter = Set.fromList [ x |
candidate <- nd_range dims,
x <- Set.toList (if isPossible candidate counter
then f (n-1) dims (Set.insert candidate counter)
else Set.empty)]
-- calls the main recursive function with initial empty set of point
solve :: Int -> [Int] -> SS
solve n dims = f n dims Set.empty
ans = solve 6 [6, 6]
main = print ans >> print ( length ans )
</code></pre>
<p></p>
<p>The majority of the ressources are utilised to compute distances, as you can see using the profiler, I think it says that the dist function was called 352542672 times (maybe it's not what it means), but since there are only 648 possible pairs of points, I was wondering on how to improve on the performances.</p>
<p>
Profiler log</p>
<pre><code> total time = 134.88 secs (134876 ticks @ 1000 us, 1 processor)
total alloc = 216,038,138,480 bytes (excludes profiling overheads)
COST CENTRE MODULE SRC %time %alloc
dist Main parker_dist.hs:15:1-38 66.2 73.9
countDists Main parker_dist.hs:(19,1)-(22,30) 16.3 12.3
isPossible Main parker_dist.hs:30:1-110 8.2 3.8
dists Main parker_dist.hs:26:1-91 3.9 5.5
countDists.d Main parker_dist.hs:22:11-30 2.2 0.0
nd_range Main parker_dist.hs:(10,1)-(11,73) 2.0 4.2
f Main parker_dist.hs:(34,1)-(39,40) 1.2 0.3
individual inherited
COST CENTRE MODULE SRC no. entries %time %alloc %time %alloc
MAIN MAIN <built-in> 138 0 0.0 0.0 100.0 100.0
CAF Main <entire-module> 275 0 0.0 0.0 100.0 100.0
ans Main parker_dist.hs:45:1-20 278 1 0.0 0.0 100.0 100.0
solve Main parker_dist.hs:43:1-33 279 1 0.0 0.0 100.0 100.0
f Main parker_dist.hs:(34,1)-(39,40) 280 2090329 1.2 0.3 100.0 100.0
isPossible Main parker_dist.hs:30:1-110 282 74837124 8.2 3.8 96.8 95.5
countDists Main parker_dist.hs:(19,1)-(22,30) 283 352542672 16.3 12.3 76.5 77.6
countDists.d Main parker_dist.hs:22:11-30 284 352542672 2.2 0.0 60.3 65.3
dist Main parker_dist.hs:15:1-38 285 352542672 58.1 65.3 58.1 65.3
dists Main parker_dist.hs:26:1-91 286 2078808 3.9 5.5 12.1 14.1
dist Main parker_dist.hs:15:1-38 287 46638684 8.1 8.6 8.1 8.6
nd_range Main parker_dist.hs:(10,1)-(11,73) 281 6236427 2.0 4.2 2.0 4.2
main Main parker_dist.hs:46:1-40 276 1 0.0 0.0 0.0 0.0
CAF Data.Set.Internal <entire-module> 274 0 0.0 0.0 0.0 0.0
CAF GHC.Conc.Signal <entire-module> 238 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Encoding <entire-module> 219 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Encoding.Iconv <entire-module> 217 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Handle.FD <entire-module> 208 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Handle.Text <entire-module> 206 0 0.0 0.0 0.0 0.0
main Main parker_dist.hs:46:1-40 277 0 0.0 0.0 0.0 0.0
</code></pre>
<p></p>
<p>My guess is that memoization is not possible as easily as in python because it uses mutable state to work (in python, you just add <code>@lru_cache(maxsize=n)</code> in front of your function). So if you have any suggestions on how to implement memoization or on how to improve my code, feel free to share them.</p>
<hr>
<h1>Update 1</h1>
<p>Achieved 25% better performance by using memoization. Problem: I need to know the number of dimensions of the key to build the HashMap (Here I just assume it's [6, 6]).</p>
<pre class="lang-hs prettyprint-override"><code>dist' a = sum . zipWith (((^2).).(-)) a
distHash = HashMap.fromList [((i, j), dist' i j) | i <- nd_range [6, 6], j <- nd_range [6, 6]]
dist i j = case HashMap.lookup (i, j) distHash of
Just d -> d
Nothing -> dist' i j
</code></pre>
<h1>Update 2</h1>
<p>I realized that I could define <code>dims</code> and the number of counters as global constants, now I don't have to pass it around to functions.</p>
<pre class="lang-hs prettyprint-override"><code>dims = [6, 6]
nCounters = 6
</code></pre>
<h1>Update 3</h1>
<p>I'm going to revert this whole memoization thing because it improves by 25% the speed when running with the profiler but it is twice slower when running without the profiler. (51s without profiler with memoization, 28s without profiler without memoization) Here is the logs, as we can see, it worked, <code>dist'</code> is now called <code>1296</code> times. But maybe I should ask myself why the function <code>dist</code> was called 350 million times in the first place. Also, <code>hashingWithSalt1</code> is slow, I wonder if there is a faster hashmap for memoization.</p>
<pre><code> total time = 105.05 secs (105051 ticks @ 1000 us, 1 processor)
total alloc = 66,890,764,984 bytes (excludes profiling overheads)
COST CENTRE MODULE SRC %time %alloc
dist Main parker_dist.hs:(26,1)-(28,24) 38.2 14.3
hashWithSalt1 Data.Hashable.Class Data/Hashable/Class.hs:271:1-45 22.7 19.1
countDists Main parker_dist.hs:(30,1)-(33,30) 17.5 39.7
isPossible Main parker_dist.hs:41:1-110 8.3 12.2
hash Data.HashMap.Base Data/HashMap/Base.hs:166:1-28 4.6 0.0
dists Main parker_dist.hs:37:1-91 3.8 13.7
f Main parker_dist.hs:(45,1)-(50,40) 1.9 1.0
sparseIndex Data.HashMap.Base Data/HashMap/Base.hs:1867:1-42 1.4 0.0
countDists.d Main parker_dist.hs:33:11-30 1.1 0.0
individual inherited
COST CENTRE MODULE SRC no. entries %time %alloc %time %alloc
MAIN MAIN <built-in> 153 0 0.0 0.0 100.0 100.0
CAF Main <entire-module> 305 0 0.0 0.0 100.0 100.0
ans Main parker_dist.hs:56:1-21 308 1 0.0 0.0 100.0 100.0
solve Main parker_dist.hs:54:1-23 309 1 0.0 0.0 100.0 100.0
f Main parker_dist.hs:(45,1)-(50,40) 311 2090329 1.9 1.0 100.0 100.0
isPossible Main parker_dist.hs:41:1-110 315 74837124 8.3 12.2 98.1 99.0
countDists Main parker_dist.hs:(30,1)-(33,30) 316 352542672 17.5 39.7 78.0 69.2
countDists.d Main parker_dist.hs:33:11-30 317 352542672 1.1 0.0 60.5 29.5
dist Main parker_dist.hs:(26,1)-(28,24) 318 352542672 33.5 12.6 59.4 29.5
sparseIndex Data.HashMap.Base Data/HashMap/Base.hs:1867:1-42 335 435640214 1.2 0.0 1.2 0.0
hash Data.HashMap.Base Data/HashMap/Base.hs:166:1-28 319 352542672 4.1 0.0 24.6 16.9
hashWithSalt1 Data.Hashable.Class Data/Hashable/Class.hs:271:1-45 320 705085344 20.1 16.9 20.5 16.9
defaultHashWithSalt Data.Hashable.Class Data/Hashable/Class.hs:290:1-50 321 2115256032 0.5 0.0 0.5 0.0
dists Main parker_dist.hs:37:1-91 336 2078808 3.8 13.7 11.8 17.6
dist Main parker_dist.hs:(26,1)-(28,24) 337 46638684 4.6 1.7 8.0 3.9
sparseIndex Data.HashMap.Base Data/HashMap/Base.hs:1867:1-42 341 56733713 0.2 0.0 0.2 0.0
hash Data.HashMap.Base Data/HashMap/Base.hs:166:1-28 338 46638684 0.5 0.0 3.2 2.2
hashWithSalt1 Data.Hashable.Class Data/Hashable/Class.hs:271:1-45 339 93277368 2.6 2.2 2.7 2.2
defaultHashWithSalt Data.Hashable.Class Data/Hashable/Class.hs:290:1-50 340 279832104 0.1 0.0 0.1 0.0
dims Main parker_dist.hs:9:1-13 314 1 0.0 0.0 0.0 0.0
distHash Main parker_dist.hs:24:1-90 322 1 0.0 0.0 0.0 0.0
dist' 'Main parker_dist.hs:20:1-39 326 1296 0.0 0.0 0.0 0.0
nd_range Main parker_dist.hs:(15,1)-(16,73) 324 6 0.0 0.0 0.0 0.0
fromList Data.HashMap.Strict.Base Data/HashMap/Strict/Base.hs:598:1-64 323 1 0.0 0.0 0.0 0.0
unsafeInsert Data.HashMap.Base Data/HashMap/Base.hs:(784,1)-(814,76) 327 1296 0.0 0.0 0.0 0.0
copy Data.HashMap.Array Data/HashMap/Array.hs:(328,1)-(333,30) 333 1800 0.0 0.0 0.0 0.0
sparseIndex Data.HashMap.Base Data/HashMap/Base.hs:1867:1-42 334 1474 0.0 0.0 0.0 0.0
hash Data.HashMap.Base Data/HashMap/Base.hs:166:1-28 328 1296 0.0 0.0 0.0 0.0
hashWithSalt1 Data.Hashable.Class Data/Hashable/Class.hs:271:1-45 329 2592 0.0 0.0 0.0 0.0
defaultHashWithSalt Data.Hashable.Class Data/Hashable/Class.hs:290:1-50 330 7776 0.0 0.0 0.0 0.0
new_ Data.HashMap.Array Data/HashMap/Array.hs:256:1-28 332 900 0.0 0.0 0.0 0.0
main Main parker_dist.hs:57:1-27 306 1 0.0 0.0 0.0 0.0
nCounters Main parker_dist.hs:10:1-13 310 1 0.0 0.0 0.0 0.0
f Main parker_dist.hs:(45,1)-(50,40) 312 0 0.0 0.0 0.0 0.0
nd_range Main parker_dist.hs:(15,1)-(16,73) 313 3 0.0 0.0 0.0 0.0
CAF Data.HashMap.Base <entire-module> 303 0 0.0 0.0 0.0 0.0
bitsPerSubkey Data.HashMap.Base Data/HashMap/Base.hs:1858:1-17 331 1 0.0 0.0 0.0 0.0
empty Data.HashMap.Base Data/HashMap/Base.hs:464:1-13 325 1 0.0 0.0 0.0 0.0
CAF GHC.Conc.Signal <entire-module> 254 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Encoding <entire-module> 235 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Encoding.Iconv <entire-module> 233 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Handle.FD <entire-module> 224 0 0.0 0.0 0.0 0.0
CAF GHC.IO.Handle.Text <entire-module> 222 0 0.0 0.0 0.0 0.0
main Main parker_dist.hs:57:1-27 307 0 0.0 0.0 0.0 0.0
</code></pre>
<h1>Update 4</h1>
<p>It looks like the compiler is smarter than me for memoization, so I changed strategy, I try to call dist less by memorizing the distances and only looking at the possible points (instead of all the points). Now my code runs under 10secs.</p>
<pre class="lang-hs prettyprint-override"><code>
import qualified Data.Set as Set
type P = [Int] -- Point
type S = Set.Set P -- Solution (Set of Point) :: Set [Int]
type SS = Set.Set S -- Set of possible Solutions (Set of Set of Points) :: Set Set [Int]
type Dists = Set.Set Int
dims = [6, 6]
nCounters = 6
-- List the points of an N-Dimentionnal grid with dimentions given as [width, height, depth,...]
-- Example: ndRange [1,2,3] gives us [[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2]]
ndRange :: [Int] -> [P]
ndRange [] = [[]]
ndRange d = [j : i | j <- [0..(pred(head d))], i <- ndRange (tail d)]
-- returns the square of the distance between two N-Dimentionnal points
dist :: P -> P -> Int
dist a = sum . zipWith (((^2).).(-)) a
check :: P -> [P] -> (Dists, Bool) -> (Dists, Bool)
check candidate counters (dists, bool)
| null counters = (dists, True)
| Set.member d dists = (dists, False)
| otherwise = check candidate (tail counters) (Set.insert d dists, True)
where d = dist candidate (head counters)
f :: Int -> S -> Dists -> S -> SS
f 0 counters dists grid = Set.singleton counters
f n counters dists grid = Set.fromList [x |
(newDists, _, candidate) <- Set.toList goods,
x <- Set.toList (f (n-1) (Set.insert candidate counters) newDists newGrid)
] where
res = Set.map (\candidate ->
let (newDists, isValid) = check candidate (Set.toList counters) (dists, True)
in (newDists, isValid, candidate)) grid
goods = Set.filter (\(_,x,_) -> x) res
newGrid = Set.map (\(_,_,x) -> x) goods
-- calls the main recursive function with initial empty set of point
solve :: Int -> SS
solve n = f n Set.empty (Set.singleton 0) (Set.fromList (ndRange dims))
ans = solve nCounters
main = print ans
</code></pre>
<hr>
<p>Congratulations, you've read until the end, what did we learn?</p>
<ol>
<li>Memoization works, but it slows the program</li>
<li>Let the compiler do its thing</li>
<li>Focus on the complexity of your function</li>
<li>Try to pass the partial results down the tree instead of computing something multiple times</li>
<li>Folding is great but you can't interrupt it, folding is trivial to re-implement using recursion and it allows you to stop whenever you want, which can <em>reduce</em> complexity (no pun intended).</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T20:13:17.157",
"Id": "243156",
"Score": "3",
"Tags": [
"python",
"performance",
"haskell",
"memoization"
],
"Title": "Unique Distancing Problem, Memoization in Haskell"
}
|
243156
|
<p>I have the following short function code that converts Exponential (e-Notation) Numbers to Decimals, <strong><em>allowing the output of large number of decimal places</em></strong>. </p>
<p>I needed to cover all the e-notation syntax permitted by Javascript which include the following:</p>
<pre><code>Valid e-notation numbers in Javascript:
123e1 ==> 1230
123E1 ==> 1230
123e+1 ==> 1230
123.e+1 ==> 1230 (with missing fractional part)
123e-1 ==> 12.3
0.1e-1 ==> 0.01
.1e-1 ==> 0.01 (with missing whole part)
-123e1 ==> -1230
</code></pre>
<p>The function does not attempt to trap NaN or undefined inputs but does attempt to cater for normal (non-e-notation) numbers; such numbers are returned "as is".</p>
<p>I have tried to provide enough comments on each line and tried to avoid (as far as possible!) the use of short-circuiting and conditional (ternary) operators for better clarity.</p>
<p>I have used the <code>toLocaleString()</code> method to automatically detect the decimal separator sign, but this, of course, assumes that the input string representing the number follows the machine's locale (especially when manually passed to the function).</p>
<p>For your review, comments, and improvements.</p>
<p>Thanks in advance.</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>/********************************************************
* Converts Exponential (e-Notation) Numbers to Decimals
********************************************************
* @function numberExponentToLarge()
* @version 1.00
* @param {string} Number in exponent format.
* (other formats returned as is).
* @return {string} Returns a decimal number string.
* @author Mohsen Alyafei
* @date 12 Jan 2020
*
* Notes: No check is made for NaN or undefined inputs
*
*******************************************************/
function numberExponentToLarge(numIn) {
numIn +=""; // To cater to numric entries
var sign=""; // To remember the number sign
numIn.charAt(0)=="-" && (numIn =numIn.substring(1),sign ="-"); // remove - sign & remember it
var str = numIn.split(/[eE]/g); // Split numberic string at e or E
if (str.length<2) return sign+numIn; // Not an Exponent Number? Exit with orginal Num back
var power = str[1]; // Get Exponent (Power) (could be + or -)
if (power ==0 || power ==-0) return sign+str[0]; // If 0 exponents (i.e. 0|-0|+0) then That's any easy one
var deciSp = 1.1.toLocaleString().substring(1,2); // Get Deciaml Separator
str = str[0].split(deciSp); // Split the Base Number into LH and RH at the decimal point
var baseRH = str[1] || "", // RH Base part. Make sure we have a RH fraction else ""
baseLH = str[0]; // LH base part.
if (power>0) { // ------- Positive Exponents (Process the RH Base Part)
if (power> baseRH.length) baseRH +="0".repeat(power-baseRH.length); // Pad with "0" at RH
baseRH = baseRH.slice(0,power) + deciSp + baseRH.slice(power); // Insert decSep at the correct place into RH base
if (baseRH.charAt(baseRH.length-1) ==deciSp) baseRH =baseRH.slice(0,-1); // If decSep at RH end? => remove it
} else { // ------- Negative Exponents (Process the LH Base Part)
num= Math.abs(power) - baseLH.length; // Delta necessary 0's
if (num>0) baseLH = "0".repeat(num) + baseLH; // Pad with "0" at LH
baseLH = baseLH.slice(0, power) + deciSp + baseLH.slice(power); // Insert "." at the correct place into LH base
if (baseLH.charAt(0) == deciSp) baseLH="0" + baseLH; // If decSep at LH most? => add "0"
}
return sign + baseLH + baseRH; // Return the long number (with sign)
}
// ------------- tests for e-notation numbers ---------------------
console.log(numberExponentToLarge("123E0")) // 123
console.log(numberExponentToLarge("-123e+0")) // -123
console.log(numberExponentToLarge("123e1")) // 1230
console.log(numberExponentToLarge("123e3")) // 123000
console.log(numberExponentToLarge("123e+3")) // 123000
console.log(numberExponentToLarge("123E+7")) // 1230000000
console.log(numberExponentToLarge("-123.456e+1")) // -1234.56
console.log(numberExponentToLarge("123.456e+4")) // 1234560
console.log(numberExponentToLarge("123E-0")) // 123
console.log(numberExponentToLarge("123.456e+50")) // 12345600000000000000000000000000000000000000000000000
console.log(numberExponentToLarge("123e-0")) // 123
console.log(numberExponentToLarge("123e-1")) // 12.3
console.log(numberExponentToLarge("123e-3")) // 0.123
console.log(numberExponentToLarge("-123e-7")) // -0.0000123
console.log(numberExponentToLarge("123.456E-1")) // 12.3456
console.log(numberExponentToLarge("123.456e-4")) // 12.3456
console.log(numberExponentToLarge("123.456e-50")) //0.00000000000000000000000000000000000000000000000123456
console.log(numberExponentToLarge("1.e-5")) // 0.00001 (handle missing base fractional part)
console.log(numberExponentToLarge(".123e3")) // 123 (handle missing base whole part)
// The Electron's Mass:
console.log(numberExponentToLarge("9.10938356e-31")) // 0.000000000000000000000000000000910938356
// The Earth's Mass:
console.log(numberExponentToLarge("5.9724e+24")) // 5972400000000000000000000
// Planck constant:
console.log(numberExponentToLarge("6.62607015e-34")) // 0.000000000000000000000000000000000662607015
// ------------- testing for Non e-Notation Numbers -------------
console.log(numberExponentToLarge("12345.7898")) // 12345.7898 (no exponent)
console.log(numberExponentToLarge(12345.7898)) // 12345.7898 (no exponent)
console.log(numberExponentToLarge(0.00000000000001)) // 0.00000000000001 (from 1e-14)
console.log(numberExponentToLarge(-0.0000000000000345)) // -0.0000000000000345 (from -3.45e-14)
console.log(numberExponentToLarge(-0)) // 0</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T04:51:00.867",
"Id": "477314",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:02:52.527",
"Id": "477317",
"Score": "0",
"body": "@Mast nothing was added to the code from code feedback. In fact (as you can see) updates/typos were done before any review or code comments. Posts below are suggested alternative codes and are completely different codes and none address the code posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:38:46.237",
"Id": "477319",
"Score": "0",
"body": "Please save the updates for a follow-up question."
}
] |
[
{
"body": "<p>You can simply use the <code>Number</code> function to convert a string in scientific notation to a number</p>\n\n<pre><code>Number(\"123e1\") === 1230\n</code></pre>\n\n<p>For converting number to string for big numbers, you can use:</p>\n\n<pre><code>// https://stackoverflow.com/a/50978675\nmyNumb.toLocaleString('fullwide', { useGrouping: false })\n</code></pre>\n\n<p>Here's a snippet:</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 strings = [\"1e+21\",\"123E1\",\"123e+1\",\"123.e+1\",\"123e-1\",\"0.1e-1\",\".1e-1\",\"-123e1\"];\n\nconsole.log(\n strings.map(s => Number(s).toLocaleString('fullwide', { useGrouping: false }))\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T08:29:15.970",
"Id": "477264",
"Score": "0",
"body": "The `Number` function does not handle this. e.g. `Number(\"1e+21\")` gives the output back again in e-notation as `1e+21` not as a decimal number. The function can handle very large decimal digits and fractions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T08:29:44.053",
"Id": "477266",
"Score": "1",
"body": "That's how javascript displays numbers. Since, you want to get a string, you can convert it to a string. Updated the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T08:34:12.757",
"Id": "477267",
"Score": "0",
"body": "For `\"1e+21\"` you can use the new `BigInt`, so `BigInt(Number(\"1e+21\")).toLocaleString()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T08:38:08.053",
"Id": "477269",
"Score": "0",
"body": "@KooiInc `BigInt` doesn't work for decimals. I think OP is fine with losing precision for numbers > MAX_SAFE_INTEGER"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T10:43:59.083",
"Id": "477272",
"Score": "1",
"body": "@KooiInc `BigInt(Number(\"1e+24\")).toLocaleString())` gives `999,999,999,999,999,983,222,784`. `BigInt(Number(\"1e+33\")).toLocaleString())` gives `999,999,999,999,999,945,575,230,987,042,816`. `BigInt(Number(\"1e+55\")).toLocaleString())` gives `10,000,000,000,000,000,102,350,670,204,085,511,496,304,388,135,324,745,728`. Accuracy is lost of large numbers because you cannot use BigInt with e-notations directly."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T08:23:44.893",
"Id": "243167",
"ParentId": "243164",
"Score": "2"
}
},
{
"body": "<p>Instead of <code>console.log</code>, you should write a proper unit test that actually compares the actual output with your expected output and only logs the failures.</p>\n\n<p>The code itself looks good to me at first sight. It needs to be formatted consistently though, especially the spacing around operators.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:25:07.293",
"Id": "477318",
"Score": "0",
"body": "Thanks. In fact, I did write a test function that tests all possibilities and updated the code, but \"@Mast\" deleted the added test function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:17:00.323",
"Id": "243202",
"ParentId": "243164",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T05:27:04.493",
"Id": "243164",
"Score": "5",
"Tags": [
"javascript",
"parsing",
"number-systems"
],
"Title": "Convert Exponential (e-Notation) Numbers to Decimals"
}
|
243164
|
<p>I am working on a project where I want to generate random throughput on a particular method so that I can do some performance testing on it. This way I can test my method by generating random throughputs and see how my method works under all those scenarios.</p>
<p><strong>For example:</strong> I need to call my <code>doIOStuff</code> method at an approximate rate of <code>x requests per second</code> from multiple threads where x will be less than <code>2000</code> mostly but it really doesn't matter in this case. It doesn't have to be accurate so there is some room for an error but the overall idea is I need to make sure that my method <code>doIOStuff</code> is executed no more than x times in a sliding window of y seconds.</p>
<p>Assuming we start <code>n threads</code> and want a maximum of <code>m calls per second</code>. We can achieve this by having each thread generate a random number between 0 and 1, k times per second and call <code>doIOStuff</code> method only if the generated number is less than m / n / k.</p>
<p>Below is the code I got which uses global variables and it does the job but I think it can be improved a lot where I can use some cancellation tokens as well and make it more efficient and clean.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp
{
class Program
{
const int m_threads = 100;
const int n_throughput = 2000;
const int k_toss_per_second = 2000; // Note that k_toss_per_second x m_threads >= n_throughput
static void Main(string[] args)
{
var tasks = new List<Task>();
for (int i = 0; i < m_threads; i++)
tasks.Add(Task.Factory.StartNew(() => doIOStuff()));
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All threads complete");
}
static void callDoIOStuff()
{
int sleep_time = (int) (1000 * 1.0d / k_toss_per_second);
double threshold = (double) n_throughput / m_threads / k_toss_per_second;
Random random = new Random();
while (true) {
Thread.Sleep(sleep_time);
if (random.NextDouble() < threshold)
doIOStuff();
}
}
static void doIOStuff()
{
// do some IO work
}
}
}
</code></pre>
<p>I wanted to see what can we do here to make it more efficient and clean so that it can used in production testing for generating random throughput load. Also I should keep an eye to the completion of the tasks that are started otherwise number of pending tasks would keep increasing every second? Right.</p>
|
[] |
[
{
"body": "<p>Welcome to CR. There is a lot of room for improvement with your code. Let's start with the simple stuff and work our way up.</p>\n\n<p>CR prefers use of braces always with <code>if</code> or <code>for</code> or <code>foreach</code>.</p>\n\n<p>Hungarian Notation is heavily frowned upon, so get rid of names prefaced with <code>m_</code>.</p>\n\n<p>Underscores internal to variable names are also frowned upon, so <code>sleep_time</code> would be better as <code>sleepTime</code> (or better altogether with a different name: see further below).</p>\n\n<p>Names should meaningful and create clarity rather than confusion. So <code>m_threads</code> isn't the number of threads running, but rather its the number of tasks you will start. Thus that variable name should have \"tasks\" in it rather than \"threads\".</p>\n\n<p>You should place your code into its own class. For instance, <code>class ThroughputTester</code>. There would be class level properties or fields named <code>TaskCount</code>, <code>TargetThroughput</code>, and <code>TossesPerSecond</code>. I would not have these as constant fields, since it makes your code rigid and only applicable to the one set of values. Rather these could be readonly properties set in the constructor, which allows for experimentation with different sets of values.</p>\n\n<p>You could also have a <code>CreateDefault</code> method to create an instance with the same values as your constants.</p>\n\n<pre><code>public class ThroughputTester\n{\n public ThroughputTester(int taskCount, int targetThroughput, int tossesPerSecond)\n {\n TaskCount = taskCount;\n TargetThroughput = targetThroughput;\n TossesPerSecond = tossesPerSecond;\n }\n\n public int TaskCount { get; }\n public int TargetThroughput { get; }\n public int TossesPerSecond { get; }\n\n public static ThroughputTester CreateDefault => new ThroughputTester(100, 2000, 2000);\n\n}\n</code></pre>\n\n<p>Your use of <code>Random</code> is fragile and runs into issues, particularly since you have it in a method with a loop. The better usage would be to define the <code>Random</code> instance at the class level instead of inside a method.</p>\n\n<p><code>sleep_time</code> leaves me wondering what it represents. Is it seconds or milliseconds? Can't tell from a vague name like <code>time</code>. It could be renamed <code>sleepMilliseconds</code>. Alternatively, you could use the <code>Thread.Sleep(TimeSpan)</code> signature (see <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.sleep?view=netcore-3.1#System_Threading_Thread_Sleep_System_TimeSpan_\" rel=\"nofollow noreferrer\">link here</a>) along with the <code>TimeSpan.FromMilliseconds</code> or <code>TimeSpan.FromSeconds</code> methods.</p>\n\n<p>That said, even <code>Thread.Sleep</code> has some negativity associated with it. You should read this answer for <a href=\"https://stackoverflow.com/a/8815944/2152078\">Why is Thread.Sleep so harmful</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T17:13:03.583",
"Id": "477285",
"Score": "0",
"body": "thanks for your suggestion. How about overall code? Do you think anything else can be improved in terms of logic? Apart from using `cancellation tokens` here we can keep also an eye to the completion of the tasks that are started otherwise pending task can keep increasing right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T15:56:18.340",
"Id": "243179",
"ParentId": "243165",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T06:43:56.747",
"Id": "243165",
"Score": "3",
"Tags": [
"c#",
"performance",
"multithreading"
],
"Title": "Rate limit a method by generating particular load on demand in C#"
}
|
243165
|
<p>I can't find out which loop is better performance than another, if you know help me.</p>
<p>I try about loops in js and performance in this <a href="https://jsben.ch/CHso0" rel="nofollow noreferrer">site</a>
and this is code snippet, you can run and check.
<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 array1 = [];
for (let i = 0; i <= 50000; i++) {
array1.push(i);
}
//for...
var forT0 = performance.now()
for (let element = 0; element < array1.length; element++) {
console.log(element);
}
var forT1 = performance.now()
console.log("Call to doSomething took " + (forT1 - forT0) + " milliseconds.")
//for...in
var forInT0 = performance.now()
for (const element in array1) {
console.log(element);
}
var forInT1 = performance.now()
console.log("Call to doSomething took " + (forInT1 - forInT0) + " milliseconds.")
//for...of
var forOfT0 = performance.now()
for (const element of array1) {
console.log(element);
}
var forOfT1 = performance.now()
console.log("Call to doSomething took " + (forOfT1 - forOfT0) + " milliseconds.")
//forEach
var forEachT0 = performance.now()
array1.forEach(element => console.log(element));
var forEachT1 = performance.now()
console.log("Call to doSomething took " + (forEachT1 - forEachT0) + " milliseconds.")</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T19:59:47.153",
"Id": "477301",
"Score": "2",
"body": "Besides being [off-topic](https://codereview.stackexchange.com/help/on-topic): `[for-loop] performance in javascript` would that be a *language characteristic of JavaScript*, one measurement on one particular machine running one implementation, or a commonality of 2020 implementations?"
}
] |
[
{
"body": "<p>Only a single contribution:</p>\n\n<pre><code>for (var i = 0, len = myArray.length; i < len; i++) { }\n</code></pre>\n\n<p>A standard for loop with length caching.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T17:31:01.207",
"Id": "477288",
"Score": "2",
"body": "When it is questionable if it is a code review or not, better not to answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T12:31:11.343",
"Id": "243170",
"ParentId": "243169",
"Score": "2"
}
},
{
"body": "<p>Not sure if this is a right fit for this site, as this is clearly not 'real' code, but let me give you an answer anyway.</p>\n\n<p>First, in your test code, the \"for\" case is clearly set up incorrectly. It should look more like this:</p>\n\n<pre><code>for (let i = 0; i < array1.length; i++) {\n console.log(array1[i]);\n}\n</code></pre>\n\n<p>Second, I don't think you are asking the right question. This is clearly a case of premature optimisation. There will be differences obviously, but in real life situations the difference will probably be marginal. It is much wiser to optimise for readability and developer comfort when writing code. Use the loop that makes most sense for you in your current situation. If you run into performance issues you can start looking at optimising then, but not before.</p>\n\n<p>There are too many variables to draw conclusions from your test case. The size of the array you loop over for instance. On large arrays <code>for</code> will be probably be fastest (probably even a bit slower than a <code>while</code> loop). On small arrays a <code>forEach</code> is possibly faster, unless you do complex operations inside the loop. And all that is dependant on the javascript engine implementation and the hardware it runs on.</p>\n\n<p>So as I said, don't worry about this stuff before you run into performance issues. And when you do, test your performance with real code and real data, not oversimplified testcode.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T17:30:22.707",
"Id": "477287",
"Score": "1",
"body": "When it is questionable if it is a code review or not, better not to answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T18:43:41.267",
"Id": "477298",
"Score": "1",
"body": "When I'm not sure, I prefer giving people the benefit of the doubt"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:53:18.487",
"Id": "477320",
"Score": "0",
"body": "While that may be your personal preference, it's [against site policy](https://codereview.meta.stackexchange.com/q/8945/52915)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T13:04:55.873",
"Id": "243173",
"ParentId": "243169",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "243173",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T11:20:45.873",
"Id": "243169",
"Score": "1",
"Tags": [
"javascript",
"performance",
"memory-optimization"
],
"Title": "which for loop has better performance in javascript?"
}
|
243169
|
<p>I was just reviewing the source code of Nifi, see <a href="https://www.cloudera.com/products/open-source/apache-hadoop/apache-nifi.html" rel="nofollow noreferrer">explanation</a> and public version of the <a href="https://github.com/apache/nifi" rel="nofollow noreferrer">source</a>. This got me wondering whether there are any obvious improvements here to increase the performance of the random generation.</p>
<p>As there are many people using this, the size of the random array could be anything, but probably it usually be somewhere in the range of 100b to 10mb. The message generation frequency will typically be between 1 and 1000 times per second.</p>
<pre><code>private static final char[] TEXT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-_=+/?.,';:\"?<>\n\t ".toCharArray();
private byte[] generateData(final ProcessContext context) {
final int byteCount = context.getProperty(FILE_SIZE).asDataSize(DataUnit.B).intValue();
final Random random = new Random();
final byte[] array = new byte[byteCount];
if (context.getProperty(DATA_FORMAT).getValue().equals(DATA_FORMAT_BINARY)) {
random.nextBytes(array);
} else {
for (int i = 0; i < array.length; i++) {
final int index = random.nextInt(TEXT_CHARS.length);
array[i] = (byte) TEXT_CHARS[index];
}
}
return array;
}
</code></pre>
<p>Just looking at this with my experience in other languages, I would think the inside of the loop is the most interesting. E.g. by avoiding to generate all numbes one by one, or indexing so many individual times into the set of characters.</p>
<p>I am looking for tips that may/will improve the speed without changing the behavior of the code too much, though some compromise on quality of randomness should be acceptable. If it looks great, then that would be also good to know of course.</p>
<p>----g</p>
<h1>Update</h1>
<p>Though I did not write these lines I do understand them. Furthermore I believe I am a maintainer of the code. Based on the suggestions here I will test the options presented and aim to improve the code and submit a pull request. (I have submitted earlier improvements to the Nifi project, so on a project level I should definitely be considered a maintainer). - Of course it would be more practical if I wrote the code myself, but based on the help section the context in which I ask this question should be OK.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T06:54:43.197",
"Id": "477321",
"Score": "3",
"body": "If you are not the author of the code, you should not ask for it to be reviewed. Please see the help center for more info. https://codereview.stackexchange.com/help/on-topic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T14:23:07.097",
"Id": "477446",
"Score": "0",
"body": "Though I did not write these lines I do understand them. Furthermore I believe I am a maintainer of the code. Based on the suggestions here I will test the options presented and aim to improve the code and submit a pull request. (I have submitted earlier improvements to the Nifi project, so on a project level I should definitely be considered a maintainer). - Of course it would be more practical if I wrote the code myself, but based on the help section the context in which I ask this question should be OK. Hence my request to re-open the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T15:39:19.963",
"Id": "477464",
"Score": "1",
"body": "Please [edit] your post to include such information about how you intend to maintain/extend the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T12:33:25.713",
"Id": "243171",
"Score": "2",
"Tags": [
"java",
"random"
],
"Title": "Random generation java logic used in Nifi"
}
|
243171
|
<p>I have written a function that prints all the prime factors for a given number. Here is my code</p>
<pre><code>static void printPrimeFactorization(int number) {
if (number <= 1 || isPrime(number)) { // If given number is already prime, no more factors for it
System.out.println(number);
return;
}
// check divisibility of given number starting from 2 to nextPrime(that is less than given number)
for (int nextPrime = 2; nextPrime < number; nextPrime = getNextPrimeNumber(nextPrime)) {
while (number % nextPrime == 0) { // check divisibility, until number is not divisible
System.out.println(nextPrime);
number = number / nextPrime;
if (isPrime(number)) {
System.out.println(number);
return;
}
}
}
}
</code></pre>
<p>For brevity I am not writing the <code>isPrime()</code> and <code>getNextPrimeNumber()</code> here</p>
<p>I am learning to calculate time complexity, and space complexity.
What is the exact time complexity of my code above starting from <code>for loop having while loop in it</code></p>
<p>I guess Time complexity is O(log n) - Logarithmic time - as the total number of iterations is <= n/2 Correct me if my understanding is wrong
Space complexity is O(1) - constant time - As no extra space used other than simple variable assignments.</p>
<p><strong>UPDATE:</strong></p>
<pre><code>static boolean isPrime(int number) {
if (number == 0 || number == 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
</code></pre>
<pre><code>static int getNextPrimeNumber(int number) {
while (!isPrime(++number)) {
}
return number;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T14:17:24.237",
"Id": "477282",
"Score": "7",
"body": "It is impossible to say without knowing the time/space complexity of the functions in the loop (`isPrime()` and `getNextPrimeNumber()`), but you haven't provided those. However, looping \\$n/2\\$ times does not mean \\$O(\\log n)\\$. If n was one million, you would iterate 500,000 times where as an \\$O(\\log n)\\$ algorithm might iterate around 20 times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T14:30:50.960",
"Id": "477283",
"Score": "0",
"body": "Updated question with `isPrime()` and `getNextPrimeNumber()` function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T04:37:21.320",
"Id": "477310",
"Score": "0",
"body": "(You would need more math than counting nested loops and exponentiating *n*, like density of primes. Then again, you leave ample room for avoiding doing the same time and again. (Darn - someone else noticed and edited out the *cyclomatic* tag…))"
}
] |
[
{
"body": "<p>We can break down calculating the time complexity as below:</p>\n\n<ul>\n<li><p>The method <code>isPrime()</code> is <code>O(n^(1/2))</code> i.e <code>root(n)</code>.</p></li>\n<li><p>The method <code>getNExtPrimeNumber()</code> is called for <code>k times</code> where <code>k</code> is the difference between the given prime number and the next prime number.It is calling <code>isPrime()</code> method in every iteration. So it is <code>O(k * root(n))</code> times.</p></li>\n<li><p>The <code>while loop</code> is calling <code>isPrime(n)</code> method in every iteration and will run <code>log base nextPrimeNumber(n)</code> times.For example, if <code>nextPrimeNumber</code> is 2 then it is <code>log base 2(n)</code>.So total time complexity of <code>while loop</code> is <code>O(log base nextPrimeNumber(n) * root(n))</code>.</p></li>\n<li><p>Now <code>for loop</code> is trying to find out the number of prime numbers between 2 and given number(n). As far as I know there is no math formula present to get that based on given number. So lets assume that iteration to be <code>p</code>. For every iteration of <code>for loop</code>, <code>getNextPrimeNumber()</code> is called and the <code>while loop</code> is called. So total time complexity of your <code>for loop</code> would be : <code>O( p * (k * root(n)) * (log base nextPrimeNumber(n) * root(n)) )</code></p></li>\n</ul>\n\n<p>This gives <code>O(p*k*n*log(n))</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T16:28:05.797",
"Id": "243181",
"ParentId": "243172",
"Score": "4"
}
},
{
"body": "<h1>isPrime()</h1>\n\n<h2>Complexity</h2>\n\n<p>This function contains a simple loop that iterates up to <code>Math.sqrt(number)</code> times, so assuming <code>Math.sqrt(...)</code> can be computed in <span class=\"math-container\">\\$O(1)\\$</span> time, the function has <span class=\"math-container\">\\$O(\\sqrt N)\\$</span> time complexity.</p>\n\n<h2>Review</h2>\n\n<p>This function is terribly inefficient. <code>Math.sqrt(number)</code> is computed <span class=\"math-container\">\\$\\lfloor \\sqrt N \\rfloor\\$</span> times, yet the value is a constant. This should be moved out of the loop.</p>\n\n<p>The function fails when given a negative number. The square-root is returned as <code>NaN</code>, the <code>for</code> loop executes zero times, and <code>true</code> is returned.</p>\n\n<p><code>2</code> is the only even prime number. It can easily be called out as a special case (like you are doing for <code>0</code> and <code>1</code>, allowing the <code>for</code> loop to consider only odd numbers starting at 3, which should cut the function time in half.</p>\n\n<hr>\n\n<h1>Main Function - Outer loop</h1>\n\n<h2>Complexity</h2>\n\n<p>Consider this loop:</p>\n\n<pre><code> for (int nextPrime = 2; nextPrime < number; nextPrime = getNextPrimeNumber(nextPrime)) {\n ...\n }\n</code></pre>\n\n<p>The <code>getNextPrimeNumber(int number)</code> is a simple function which increments a number by one, and tests whether or not it is prime. These two can be combined into an equivalent simpler loop, which is easier to reason about:</p>\n\n<pre><code> for (int nextPrime = 2; nextPrime < number; nextPrime++) {\n if (isPrime(nextPrime)) {\n ...\n }\n }\n</code></pre>\n\n<p>Now, we can see that this loop iterates <code>number - 2</code> times, so <code>isPrime(nextPrime)</code> is called <code>number - 2</code> times. This gives us a time complexity of <span class=\"math-container\">\\$O(N^{3/2})\\$</span> without considering the inner loop.</p>\n\n<hr>\n\n<h1>Inner Loop</h1>\n\n<h2>Complexity</h2>\n\n<p>The inner statement (the <code>while</code> loop) is executed for each prime number the outer loop finds. From the <a href=\"https://en.wikipedia.org/wiki/Prime_number_theorem\" rel=\"noreferrer\">Prime Number Theorem</a>, we know that the number of primes <span class=\"math-container\">\\$π(N)\\$</span> is approximately <span class=\"math-container\">\\$\\frac{N}{\\log N}\\$</span>.</p>\n\n<p>Since the <code>while</code> loop is dividing the number by a constant factor, <code>p</code>, the prime number from the outer loop, it will execute a maximum of <span class=\"math-container\">\\$log_{p} N\\$</span> times. After each division, <code>isPrime(number)</code> is called. This means <span class=\"math-container\">\\$log N\\$</span> executions of a <span class=\"math-container\">\\$O(\\sqrt N)\\$</span> algorithm, so the inner statement is <span class=\"math-container\">\\$O(\\log N \\sqrt N)\\$</span>.</p>\n\n<p>Executed for each prime number, this gives <span class=\"math-container\">\\$O(\\frac{N}{\\log N} \\log N \\sqrt N)\\$</span>, or <span class=\"math-container\">\\$O(N^{3/2})\\$</span>.</p>\n\n<p>Since both portions have <span class=\"math-container\">\\$O(N^{3/2})\\$</span> complexity, the overall complexity is <span class=\"math-container\">\\$O(N^{3/2})\\$</span>.</p>\n\n<h2>Review</h2>\n\n<p>The trial division <code>while(number % nextPrime == 0)</code> loop will exit once all of the factors of <code>nextPrime</code> have been divided out of <code>number</code>. <code>isPrime(number)</code> can't become <code>true</code> while more than one factor of <code>nextPrime</code> exist, and since <code>isPrime()</code> is an \"expensive\" <span class=\"math-container\">\\$O(\\log N)\\$</span> operation, it would be more efficient to remove as many multiples of <code>nextPrime</code> as possible, and only then checking if the resulting <code>number</code> is prime. In short, when the <code>while</code> loop executes one or more iterations, the <code>isPrime()</code> should execute once, but if the <code>while</code> loop executes 0 times, <code>isPrime()</code> shouldn't be executed at all.</p>\n\n<hr>\n\n<h1>Overall</h1>\n\n<p>You've separated <code>isPrime()</code> out from determining the factors of <code>number</code>, but <code>isPrime()</code> determines whether a number is prime or not by doing trial divisions, and you need to do trial divisions to remove factors from number. One function which does both operations would be more efficient:</p>\n\n<ul>\n<li>divide out as many factors of 2 as possible</li>\n<li>starting with a divisor of 3, and increasing by 2:\n\n<ul>\n<li>if number can be divided by the divisor:</li>\n<li>repeat as many times as possible:\n\n<ul>\n<li>number /= divisor</li>\n</ul></li>\n<li>stop, if number < divisor * divisor</li>\n</ul></li>\n<li>if stopped, and number > 1:\n\n<ul>\n<li>number is last factor</li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T22:51:06.473",
"Id": "243193",
"ParentId": "243172",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "243193",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T13:03:16.230",
"Id": "243172",
"Score": "4",
"Tags": [
"java",
"algorithm",
"complexity"
],
"Title": "Time and Space Complexity of Prime factorization"
}
|
243172
|
<p>Is this <code>my_upgrade_mutex</code> class a valid implementation of <code>boost::upgrade_mutex</code> semantics? (Ignoring the <code>try_*</code> and <code>*_for</code>/<code>*_until</code> part.)</p>
<pre><code>class my_upgrade_mutex
{
std::mutex xmutex;
std::shared_mutex smutex;
public:
void lock_shared()//u->s
{
smutex.lock_shared();
}
void unlock_shared()//s->u
{
smutex.unlock_shared();
}
void lock()//u->x
{
xmutex.lock();
smutex.lock();
}
void unlock()//x->u
{
smutex.unlock();
xmutex.unlock();
}
void lock_upgrade()//u->g
{
xmutex.lock();
smutex.lock_shared();
}
void unlock_upgrade()//g->u
{
smutex.unlock_shared();
xmutex.unlock;
}
void unlock_upgrade_and_lock()//g->x
{
smutex.unlock_shared();
smutex.lock();
}
void unlock_and_lock_upgrade()//x->g
{
smutex.unlock();
smutex.lock_shared();
}
void unlock_and_lock_shared()//x->s
{
smutex.unlock();
smutex.lock_shared()
xmutex.unlock();
}
void unlock_upgrade_and_lock_shared()//g->s
{
xmutex.unlock();
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T16:36:26.463",
"Id": "477284",
"Score": "2",
"body": "I'm new here. Does anyone have any hints about the down votes, please?"
}
] |
[
{
"body": "<p>I think it actually is valid.</p>\n\n<p>Here's all of the possible states of the two mutexes.</p>\n\n<pre><code>/* u: unlocked, s: shared locked, g: upgrade locked, x: exclusive locked\n (state): of which upgrade_mutex state, the states are as this line\n (inter-state): in the middle of these transitions, the states might be as this line\n Xab means the original state is of symbol X,\n and the thread is doing the lock/unlock of a->b\n symbol xmutex smutex (state) (inter-state)\n A u u u\n B x u Aux Axu Aug Agu Agx Axg Axs Dgu Dgx Exu Exg Exs\n C u s s Cs\n D x s g Axs Bs Cux Cug Ds Dgu Dgx Exs\n E x x x\n*/\n</code></pre>\n\n<ol>\n<li>The 10 lock/unlock methods all behave reasonably good in all of the states</li>\n<li>Given the prior-method state is in the set, the during-/post-method state is in the set</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T00:58:00.797",
"Id": "243195",
"ParentId": "243177",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T15:26:16.447",
"Id": "243177",
"Score": "1",
"Tags": [
"c++",
"boost",
"stl"
],
"Title": "Implementing boost::upgrade_mutex using only standard locks"
}
|
243177
|
<p>I'm new to <code>std::atomic</code>, <code>std::mutex</code>, <code>std::unique_lock</code>, <code>std::condition_variable</code> and more or less c++11 <code>std::thread</code>, so I wrote this little Job_Queue class, where you can submit a <code>void()</code> function and it will be distributed among some threads. I wonder if there's room for improvement or if I made to beginner's mistakes. The idea is, that you can have multiple job_queues waiting, but not running at the same time.</p>
<h1><strong>job_queue.hpp</strong></h1>
<pre><code>#ifndef SNIPPETS_JOB_QUEUE_HPP
#define SNIPPETS_JOB_QUEUE_HPP
#include <atomic>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
class Job_Queue
{
public:
static std::mutex job_mutex;
void start();
void stop();
void terminate();
Job_Queue();
void add(const std::function<void()>& f);
void add(std::function<void()>&& f);
private:
static bool is_running;
static unsigned int n_cores;
std::atomic<bool> terminate_after_current_job;
std::atomic<bool> stop_when_queue_is_empty;
std::vector<std::thread> threads;
std::condition_variable thread_cv;
std::mutex queue_mutex;
std::queue<std::function<void()>> job_queue;
void thread_loop();
};
#endif //SNIPPETS_JOB_QUEUE_HPP
</code></pre>
<h1><strong>job_queue.cpp</strong></h1>
<pre><code>#include "job_queue.hpp"
void Job_Queue::start()
{
if( is_running )
{
std::cerr << "Error: Another JobQueue is currently running. Please end it first.\n";
return;
}
is_running = true;
threads.clear();
terminate_after_current_job = false;
stop_when_queue_is_empty = false;
threads.reserve(n_cores);
for( unsigned int k = 0; k < n_cores; ++k )
{
threads.emplace_back(&Job_Queue::thread_loop, this);
}
}
void Job_Queue::terminate()
{
terminate_after_current_job = true;
stop();
}
void Job_Queue::stop()
{
stop_when_queue_is_empty = true;
thread_cv.notify_all();
for( unsigned int k = 0; k < n_cores; ++k )
{
thread_cv.notify_all();
threads[k].join();
}
threads.clear();
is_running = false;
}
void Job_Queue::add(const std::function<void()>& f)
{
job_queue.push(f);
thread_cv.notify_all();
}
void Job_Queue::add(std::function<void()>&& f)
{
job_queue.emplace(f);
thread_cv.notify_all();
}
Job_Queue::Job_Queue()
: queue_mutex(std::mutex())
{
if ( Job_Queue::n_cores == 0)
{
n_cores = std::thread::hardware_concurrency();
if (n_cores == 0)
{
std::cerr << "Error: Could not find number of available cores.\n";
}
}
}
void Job_Queue::thread_loop()
{
{
std::unique_lock<std::mutex> mu(Job_Queue::job_mutex);
}
bool job_q_empty = false;
while( true )
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
thread_cv.wait(lock, [this, &job_q_empty] { job_q_empty = job_queue.empty(); return !job_queue.empty() || terminate_after_current_job || stop_when_queue_is_empty; });
}
if( !job_q_empty )
{
std::function<void()> f;
{
std::unique_lock<std::mutex> lock(queue_mutex);
f = job_queue.front();
job_queue.pop();
std::cout << "jobs left in Q: " << job_queue.size() << "\n";
}
f();
}
else
{
if( stop_when_queue_is_empty )
{
break;
}
}
if( terminate_after_current_job )
{
break;
}
}
}
std::mutex Job_Queue::job_mutex = std::mutex();
bool Job_Queue::is_running = false;
unsigned int Job_Queue::n_cores = 0;
</code></pre>
<h1><strong>main.cpp</strong></h1>
<pre><code>#include "job_queue.hpp"
void short_job(std::size_t i)
{
std::this_thread::sleep_for(std::chrono::seconds(5));
std::unique_lock<std::mutex> lock(Job_Queue::job_mutex);
std::cout << "Finished S job: " << i << " on thread: " << std::this_thread::get_id() << "\n" << std::flush;
}
void middle_job(std::size_t i)
{
std::this_thread::sleep_for(std::chrono::seconds(10));
std::unique_lock<std::mutex> lock(Job_Queue::job_mutex);
std::cout << "Finished M job: " << i << " on thread: " << std::this_thread::get_id() << "\n" << std::flush;
}
void long_job(std::size_t i)
{
std::this_thread::sleep_for(std::chrono::seconds(15));
std::unique_lock<std::mutex> lock(Job_Queue::job_mutex);
std::cout << "Finished L job: " << i << " on thread: " << std::this_thread::get_id() << "\n" << std::flush;
}
int main()
{
Job_Queue job_queue;
job_queue.start();
for( std::size_t k = 0; k < 100; ++k )
{
if( k%3 == 0 )
{
job_queue.add(std::move(std::bind(short_job, k)));
}
else if( k%3 == 1 )
{
job_queue.add(std::move(std::bind(middle_job, k)));
}
else
{
job_queue.add(std::move(std::bind(long_job, k)));
}
}
job_queue.stop();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h2>Observations:</h2>\n<p>I must say I was never very fond of <code>std::bind</code> and since the advent of lambdas I don't really see much need for it.</p>\n<pre><code> job_queue.add(std::move(std::bind(short_job, k)));\n job_queue.add(std::move(std::bind(middle_job, k)));\n job_queue.add(std::move(std::bind(long_job, k)));\n</code></pre>\n<p>I would write:</p>\n<pre><code> job_queue.add([k](){short_job(k);});\n job_queue.add([k](){middle_job(k);});\n job_queue.add([k](){long_job(k);});\n</code></pre>\n<hr />\n<p>Don't see the need for a start/stop paradigm:</p>\n<pre><code>{\n Job_Queue job_queue;\n job_queue.start();\n // STUFF\n job_queue.stop();\n}\n</code></pre>\n<p>That is what we have constructor/destructor for.</p>\n<pre><code>{\n Job_Queue job_queue; // Started by constructor.\n // STUFF\n} // Stopped by destructor\n</code></pre>\n<p>The advantage of this is that the user can't accidentally forget to call start/stop. It is done automatically for you.</p>\n<hr />\n<p>Why do these user functions have accesses to the queues lock?</p>\n<pre><code>void short_job(std::size_t i)\n{\n std::this_thread::sleep_for(std::chrono::seconds(5));\n std::unique_lock<std::mutex> lock(Job_Queue::job_mutex); // WHY !!!!!! \n // After reading the code\n // it is not used by the class\n // just the external functions\n // So it should not be a\n // member of the class it should\n // simply defined before these\n // functions.\n\n\n std::cout << "Finished S job: " << i << " on thread: " << std::this_thread::get_id() << "\\n" << std::flush;\n}\n</code></pre>\n<hr />\n<h2>Code Review</h2>\n<p>You seem to have forgotten your namespace!!!</p>\n<hr />\n<p>I would not have made the mutex static.</p>\n<pre><code> static std::mutex job_mutex;\n</code></pre>\n<p>Make it a normal member of the class.\nOtherwise all your queues will be waiting on other queues to finish using the lock.</p>\n<hr />\n<p>Why are these static.</p>\n<pre><code>static bool is_running;\nstatic unsigned int n_cores;\n</code></pre>\n<p>I can't have more than one job queue?</p>\n<hr />\n<p>As mentioned above I would not have an explicit start stop.</p>\n<pre><code> void start();\n void stop();\n</code></pre>\n<p>This is likely to cause issues with incorrect usage.</p>\n<hr />\n<p>Just have the move version of add.</p>\n<pre><code> void add(const std::function<void()>& f);\n void add(std::function<void()>&& f);\n</code></pre>\n<hr />\n<p>Why can't I have multiple queues?</p>\n<pre><code> if( is_running )\n {\n std::cerr << "Error: Another JobQueue is currently running. Please end it first.\\n";\n\n // Does not actually stop you having multiple queues!\n // Just seems to print a warning message.\n // The code is still running\n return;\n }\n</code></pre>\n<hr />\n<pre><code>void Job_Queue::add(std::function<void()>&& f)\n{\n job_queue.emplace(f);\n thread_cv.notify_all(); // There is only one new job.\n // You don't need to wake all the threads.\n // Simply notify one thread.\n}\n</code></pre>\n<hr />\n<p>Why are you using the copy constructor!</p>\n<pre><code>: queue_mutex(std::mutex())\n</code></pre>\n<p>This is the same as:</p>\n<pre><code>: queue_mutex()\n</code></pre>\n<hr />\n<p>Why are you doing this here?</p>\n<pre><code>{\n if ( Job_Queue::n_cores == 0)\n {\n n_cores = std::thread::hardware_concurrency();\n }\n}\n</code></pre>\n<p>Why not simply do this when you declare <code>c_cores</code>?</p>\n<pre><code> unsigned int Job_Queue::n_cores = std::thread::hardware_concurrency();\n</code></pre>\n<hr />\n<p>Is this an actual issue?</p>\n<pre><code> if (n_cores == 0)\n {\n std::cerr << "Error: Could not find number of available cores.\\n";\n }\n</code></pre>\n<p>Will this ever return 0?<br />\nCan it return 0? Will a machine not always have at least one core? If it had zero cores can you run the code?</p>\n<hr />\n<p>This is pointless:</p>\n<pre><code> {\n std::unique_lock<std::mutex> mu(Job_Queue::job_mutex);\n }\n</code></pre>\n<hr />\n<p>You are declaring a variable outside the lambda. Passing it in by reference. Then just using it like a local variable in the lambda.</p>\n<pre><code> bool job_q_empty = false;\n</code></pre>\n<p>Why? Just declare <code>job_q_empty</code> boolean inside the lambda!</p>\n<p>Your current lambda looks like this:</p>\n<pre><code>bool job_q_empty = false;\n[this, &job_q_empty]()\n{\n job_q_empty = job_queue.empty();\n return !job_queue.empty() || \n terminate_after_current_job || \n stop_when_queue_is_empty;\n}\n</code></pre>\n<p>You could have simply done this:</p>\n<pre><code>[this]()\n{\n bool job_q_empty = job_queue.empty(); // Notice the bool here.\n return !job_queue.empty() || \n terminate_after_current_job || \n stop_when_queue_is_empty;\n}\n</code></pre>\n<hr />\n<p>You are locking/unlocking/re-locking/unlocking the queue. The problem is that the check used in the <code>test()</code> includes <code>job_queue.empty()</code> and you release the lock and thus allow other threads to be released from the queue before this thread has extracted its job from the queue.</p>\n<p><strong>THIS IS A SERIOUS BUG</strong></p>\n<pre><code> {\n std::unique_lock<std::mutex> lock(queue_mutex);\n thread_cv.wait(lock, test());\n }\n if( !job_q_empty )\n {\n std::function<void()> f;\n {\n std::unique_lock<std::mutex> lock(queue_mutex);\n f = job_queue.front();\n job_queue.pop();\n std::cout << "jobs left in Q: " << job_queue.size() << "\\n";\n }\n f();\n }\n</code></pre>\n<p>I would do this:</p>\n<pre><code>void Job_Queue::thread_loop()\n{\n if (!terminated)\n {\n std::function<void()> nextJob = getNextJob();\n // Either get a job.\n // Or a do nothing empty job. Simply run it either way.\n nextJob();\n }\n}\n\n\nstd::function<void()> Job_Queue::getNextJob()\n{\n std::unique_lock<std::mutex> lock(queue_mutex);\n thread_cv.wait(lock, [&job_queue](){return !job_queue.empty() || terminated;});\n\n std::function<void()> result = [](){}; // default empty job.\n if (!terminated) {\n // If its not terminated then we know there is a job\n // in the job_queue to get the front one.\n result = job_queue.front();\n job_queue.pop();\n }\n return result;\n}\n</code></pre>\n<hr />\n<p>You can check out my attempt here:</p>\n<p><a href=\"https://codereview.stackexchange.com/q/47122/507\">A simple Thread Pool</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T10:00:21.927",
"Id": "477339",
"Score": "0",
"body": "Thanks for pointing out some obvious flaws! I will definitely adapt! To address some of your (very welcomed) critic: 1) You can have multiple Queues, but not have multple Queues running. The reason is, if one Queue uses all threads, then multiple queues would need to share processor power, and ultimately everything slows down. 2) [hardware_concurrency()](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) can return 0. 3) Thanks for pointing out the bug, that is indeed quite severe. 4) The variables are static so that through all instances it is known whether it's running"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T10:37:02.953",
"Id": "477347",
"Score": "0",
"body": "You could want to create a queue, but not run it yet, until resources are available. That's why there's the start function. I will add the destructor so it stops automatically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T15:19:35.300",
"Id": "477364",
"Score": "0",
"body": "`The reason is, if one Queue uses all threads, then multiple queues would need to share processor power` Are confusing multiple threads with multiple cores. You can have many more threads than cores (not a good idea but I should be able to do it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T15:22:50.257",
"Id": "477365",
"Score": "0",
"body": "`then multiple queues would need to share processor power, and ultimately everything slows down` You are making the assumption that all queues are being used at full capacity all the time. That is rarely the case. Threads can be blocked on operations then you have wasted parallelism. As the generic queue builder you can't know what an application is doing. I as the specific application developer will have more context and may be able to utilize two queues effectively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T00:06:39.163",
"Id": "477399",
"Score": "0",
"body": "Thinking on this more. Sure you can design this to have one and only one thread queue (that is a design decision). But if that is your use case you should be creating a singleton object. Note: Use a factory method to construct your singleton so that you can replace it with an alternative in debug mode."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T04:27:45.117",
"Id": "243199",
"ParentId": "243180",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T16:02:25.640",
"Id": "243180",
"Score": "4",
"Tags": [
"c++",
"performance",
"multithreading",
"thread-safety"
],
"Title": "Job_Queue (Thread_Pool) Program"
}
|
243180
|
<h1>Implementing A Simple Singly Linked List</h1>
<p>I'm trying to learn Go and wanted to implement various data structures and algorithms from scratch.</p>
<p>I wanted to try and implement a singly linked list without using slices.</p>
<p>In the sake of keeping things simple, I am not taking into account concurrent access to this list and am exposing a very limited API.</p>
<p>My focus is on adhering to Go best principles and style (as well as logical correctness, of course).</p>
<p>One of the things I struggled with was how to design tests for the <code>SinglyLinkedList</code> <code>struct</code>, particularly around naming test cases.</p>
<p>I saw <a href="https://golang.org/pkg/testing/#hdr-Examples" rel="nofollow noreferrer">a recommendation from the <code>testing</code> Go documentation</a> as well as <a href="https://stackoverflow.com/questions/155436/unit-test-naming-best-practices">this discussion on <code>StackOverflow</code></a>.</p>
<p>Another thing I had questions about was how to test generic values that could be inputted into the list.</p>
<p>I used <code>interface{}</code> to represent the values that could be inserted into the list to avoid restricting the list values to a given type - for this type of API, what is the best practice around testing?</p>
<p>Is it to create an array of possible input types and to iterate over that array for each test case?</p>
<h2>Implementation</h2>
<pre class="lang-golang prettyprint-override"><code>package main
type node struct {
value interface{}
next *node
}
// SinglyLinkedList represents a basic singly linked list data structure
type SinglyLinkedList struct {
size int
head *node
tail *node
}
// IsEmpty returns true if list has no elements and false if list has elements
func (list SinglyLinkedList) IsEmpty() (isEmpty bool) {
return list.size == 0
}
// Push adds an element with the specified value to the end of the list - it will return true
func (list *SinglyLinkedList) Push(value interface{}) (pushed bool) {
next := &node{value: value}
if list.IsEmpty() {
list.head = next
} else {
list.tail.next = next
}
list.tail = next
list.size++
return true
}
// Peek returns the value at the head of the list, but does not remove the element at the head of the list
func (list SinglyLinkedList) Peek() (value interface{}, ok bool) {
if list.IsEmpty() {
return nil, false
}
return list.head.value, true
}
// Pop returns the value at the head of the list, and removes the element at the head of the list
func (list *SinglyLinkedList) Pop() (value interface{}, ok bool) {
if list.IsEmpty() {
return nil, false
}
value = list.head.value
list.head = list.head.next
if list.size == 1 {
list.tail = nil
}
list.size--
return value, true
}
</code></pre>
<h2>Tests</h2>
<pre class="lang-golang prettyprint-override"><code>package main
import "testing"
func TestSinglyLinkedList_IsEmpty_IsTrueWhenInitialized(t *testing.T) {
list := SinglyLinkedList{}
if list.IsEmpty() != true {
t.Errorf("Expected list to be empty")
}
}
func TestSinglyLinkedList_IsEmpty_IsFalseWhenElementIsPushed(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
if list.IsEmpty() == true {
t.Errorf("Expected list to not be empty")
}
}
func TestSinglyLinkedList_IsEmpty_IsTrueWhenListHasElementPushedThenPopped(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
list.Pop()
if list.IsEmpty() != true {
t.Errorf("Expected list to be empty")
}
}
func TestSinglyLinkedList_IsEmpty_IsTrueWhenListHasElementPushedTwiceThenPoppedTwice(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
list.Push(2)
list.Pop()
list.Pop()
if list.IsEmpty() != true {
t.Errorf("Expected list to be empty")
}
}
func TestSinglyLinkedList_IsEmpty_IsFalseWhenListHasElementPushedTwiceThenPoppedOnce(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
list.Push(2)
list.Pop()
if list.IsEmpty() != false {
t.Errorf("Expected list not to be empty")
}
}
func TestSinglyLinkedList_Push_ReturnsTrue(t *testing.T) {
list := SinglyLinkedList{}
if list.Push(100) != true {
t.Errorf("Expected Push to return true")
}
}
func TestSinglyLinkedList_Peek_ReturnFalseOkValueWhenListIsEmpty(t *testing.T) {
list := SinglyLinkedList{}
_, ok := list.Peek()
if ok != false {
t.Errorf("Expected peeking empty list to not be ok")
}
}
func TestSinglyLinkedList_Peek_ReturnsNilValueWhenListIsEmpty(t *testing.T) {
list := SinglyLinkedList{}
value, _ := list.Peek()
if value != nil {
t.Errorf("Expected value from peeking empty list to be nil and not %v", value)
}
}
func TestSinglyLinkedList_Peek_ReturnTrueOkValueWhenListIsNotEmpty(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
_, ok := list.Peek()
if ok != true {
t.Errorf("Expected peeking single element list to be ok")
}
}
func TestSinglyLinkedList_Peek_ReturnsFirstPushedValueWhenListHasBeenPushedToOnce(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
value, _ := list.Peek()
if value != 1 {
t.Errorf("Expected value to be 1 instead of %d", value)
}
}
func TestSinglyLinkedList_Peek_ReturnsFirstPushedValueWhenListHasBeenPushedToTwice(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
list.Push(2)
value, _ := list.Peek()
if value != 1 {
t.Errorf("Expected value to be 1 instead of %d", value)
}
}
func TestSinglyLinkedList_Pop_ReturnFalseOkValueWhenListIsEmpty(t *testing.T) {
list := SinglyLinkedList{}
_, ok := list.Pop()
if ok != false {
t.Errorf("Expected peeking empty list to not be ok")
}
}
func TestSinglyLinkedList_Pop_ReturnsNilValueWhenListIsEmpty(t *testing.T) {
list := SinglyLinkedList{}
value, _ := list.Pop()
if value != nil {
t.Errorf("Expected value from peeking empty list to be nil and not %v", value)
}
}
func TestSinglyLinkedList_Pop_ReturnTrueOkValueWhenListIsNotEmpty(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
_, ok := list.Pop()
if ok != true {
t.Errorf("Expected peeking single element list to be ok")
}
}
func TestSinglyLinkedList_Pop_ReturnsFirstPushedValueWhenListHasBeenPushedToOnce(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
value, _ := list.Pop()
if value != 1 {
t.Errorf("Expected value to be 1 instead of %d", value)
}
}
func TestSinglyLinkedList_Pop_ReturnsFirstPushedValueWhenListHasBeenPushedToTwice(t *testing.T) {
list := SinglyLinkedList{}
list.Push(1)
list.Push(2)
value, _ := list.Pop()
if value != 1 {
t.Errorf("Expected value to be 1 instead of %d", value)
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T17:15:24.387",
"Id": "243183",
"Score": "2",
"Tags": [
"go"
],
"Title": "Implementing A Simple Singly Linked List"
}
|
243183
|
<p>I am writing a game via SFML. In difference places I want to use loaded fonts. So I decided to write the fonts loader, so that load fonts only one time and use them in the future from class. My code:</p>
<pre><code>enum class FontsID
{
PIXEBOY,
DIGITAL7
};
class FontObject
{
public:
FontObject::FontObject(const std::string &texturePath)
{
font->loadFromFile(texturePath);
}
std::shared_ptr<sf::Font> font = std::make_shared<sf::Font>();
};
class FontsLoader
{
public:
static FontsLoader &getInstance()
{
static FontsLoader instance;
return instance;
}
const std::shared_ptr<sf::Font> getFont(FontsID fontID) const
{
return allFonts[static_cast<int>(fontID)].font;
}
private:
FontsLoader()
{
allFonts.push_back(FontObject("data/fonts/pixeboy.ttf"));
allFonts.push_back(FontObject("data/fonts/digital-7.ttf"));
}
std::vector<FontObject> allFonts;
};
static FontsLoader &fontsLoader = FontsLoader::getInstance();
</code></pre>
<p>I don't think using an enum is good solution, for example, enum count may be more or less than <code>allFonts</code> vector items count, adding in the constuctor in proper sequence also not good , but <code>fontsObject.getFont(FontsID::PIXEBOY);</code> is convenient for me, I will never confuse fonts name. Is there a better way?</p>
|
[] |
[
{
"body": "<p><strong>FontObject</strong></p>\n\n<ul>\n<li><p>Since all your data members and methods are <code>public</code>, consider making it a <code>struct</code> instead of a <code>class</code>. Makes no difference to a compiler, but makes your intention clearer.</p></li>\n<li><p>Consider using a <code>unique_ptr</code> instead of <code>shared_ptr</code>, since only one instance of GameObject <em>owns</em> the object. </p></li>\n</ul>\n\n<p><strong>FontsLoader</strong></p>\n\n<ul>\n<li><p>I'm sure they are many people who will explain why you shouldn't use the Singleton pattern. Ultimately, it comes down to whether you (and people you're coding with) are okay with. I've seen various large projects (~100K-1M lines) use the Singleton pattern, so I'm not going to tell you whether you should or shouldn't use it.</p></li>\n<li><p>Use something like an <code>std::unordered_map<FontsID, FontsObject></code>. That way, you won't have to cast it into an integer and access a vector.</p></li>\n<li><p>On a side note, for vector access, use <code>size_t</code>.</p></li>\n<li><p>Consider passing the <code>sf::Font</code> object as a raw pointer or a const reference. Remember, non-owning raw pointers is FINE, even recommended. Whatever calls the <code>getFont</code> method is not concerned with ownership of the object, just the object itself. Don't pass smart pointers around unless you want the calling code to have ownership of the object.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T22:50:22.557",
"Id": "243192",
"ParentId": "243187",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243192",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T19:24:35.763",
"Id": "243187",
"Score": "5",
"Tags": [
"c++",
"sfml"
],
"Title": "C++ SFML fonts loader"
}
|
243187
|
<p>I have stumbled across these unit tests in a code review that are using in memory db:</p>
<pre><code>private DatabaseContext _context;
private Fixture _fixture;
[SetUp]
public void Setup()
{
_fixture = new Fixture();
_fixture.Customize(new AutoNSubstituteCustomization());
var options = new DbContextOptionsBuilder<DatabaseContext>()
.UseInMemoryDatabase(databaseName: "testdb")
.Options;
_context = new DatabaseContext(options);
}
[TearDown]
public void CleanUp()
{
var context = _context;
if (context == null || context.Database.ProviderName != "Microsoft.EntityFrameworkCore.InMemory")
{
return;
}
context.Database.EnsureDeleted();
_context = null;
}
#region EmptyDB
[Test]
public void Test1()
{
// Setup
var logger = _fixture.Freeze<ILogger<UserRepository>>();
var userRepo = new UserRepository(_context, logger);
var userViews = new List<UserView>();
userViews.AddRange(_fixture.CreateMany<UserView>(10));
// ACT
userRepo.UpdateUsers(userViews, CancellationToken.None).GetAwaiter().GetResult();
// ASSERT
Assert.AreEqual(10, _context.Users.CountAsync().GetAwaiter().GetResult());
}
[Test]
public void Test2()
{
// Setup
var logger = _fixture.Freeze<ILogger<UserRepository>>();
var userRepo = new UserRepository(_context, logger);
var identityViews = new List<IdentityView>();
_fixture.Register<IEnumerable<UserView>>(() =>
{
return new UserView[] { new UserView("fish") };
});
userViews.AddRange(_fixture.CreateMany<UserView>(10));
// ACT
userRep.UpdateUsers(userViews, CancellationToken.None).GetAwaiter().GetResult();
// ASSERT
Assert.AreEqual(10, _context.Users.CountAsync().GetAwaiter().GetResult());
}
</code></pre>
<p>As you can see, the tests are using the same in memory db, which I really don't like. I also don't like the new UserRepository(_context, logger). Is it a bad practice to use the new-keyword like this?</p>
<p>I would prefer something like this instead:</p>
<pre><code>[Test]
public void Test1()
{
// Setup
var provider = RegisterServices();
var logger = _fixture.Freeze<ILogger<UserRepository>>();
var userRepo = provider.GetRequiredService<IUserRepository>();
var userViews = new List<UserView>();
userViews.AddRange(_fixture.CreateMany<UserView>(10));
// ACT
userRepo.UpdateUsers(userViews, CancellationToken.None).GetAwaiter().GetResult();
// ASSERT
Assert.AreEqual(10, _context.Users.CountAsync().GetAwaiter().GetResult());
}
private ServiceProvider RegisterServices([CallerMemberName] string memberName = "")
{
var services = new ServiceCollection();
services.AddDbContext<IDatabaseContext, DatabaseContext>(options =>
options.UseInMemoryDatabase(memberName));
services.AddPersistence("https://localhost");
return services.BuildServiceProvider();
}
</code></pre>
<p>As you can see, I have added a RegisterService method that takes the calling test as a parameter, and then uses this to create the inmemorydb. I really like this because you are isolating your tests more this way. I also think it's cleaner to read.</p>
<p>How would you guys do in this case? Is the first approach the way to go, or is my approach the more "right" way to do it? Or is it another better and more best practice way to do it?</p>
<p>I just want to know your opinions about this and about the two approaches above.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T21:15:04.393",
"Id": "477302",
"Score": "1",
"body": "To anyone down voting or voting to close, while the first block of code is indeed copied, the second block is the posters attempt to rewrite it. They are looking for a comparison."
}
] |
[
{
"body": "<p>Generally speaking whenever we are about to write unit tests we should follow the <strong>F.I.R.S.T.</strong> principles. It is an acronym, which stand for:</p>\n\n<ul>\n<li><strong>Fast</strong>: The execution time should be measured in milliseconds. If it takes a second or two then it can be considered as slow and should be revised.</li>\n<li><strong>Isolated</strong>: Each test is self-contained and does not rely on any other data. They can be run in any order.</li>\n<li><strong>Repeatable</strong>: The test runs must be repeated over and over again. In each and every run they should either pass every time or always fail.</li>\n<li><strong>Self-validating</strong>: There is no need for human interpretation whether or not the test succeeded or failed. The test result should be self-explanatory.</li>\n<li><strong>Timely</strong>: The code and related tests should be written in almost the same time. A new code without relevant unit tests should not be deployed.</li>\n</ul>\n\n<p>Let's examine these ideas for your proposals:</p>\n\n<h3>Single database and cleanup</h3>\n\n<ul>\n<li>Fast: If for whatever reason a previous cleanup phase missed / failed then your database will have some trash data in it, which might impact the performance of your database operations. Executing the cleanup during setup and teardown might solve the problem, but it will definitely have performance impact.</li>\n<li>Isolated: They are sharing the same database, so they are not truly isolated. It might be the case that they can't run in parallel, because ordering might matter.</li>\n<li>Repeatable: Because they are using the same database, that's why order might affect the result of your assertions. In case of MSTest you can define ordering but if you need to use them that means your tests are not really isolated.</li>\n<li>Self-validating: Because there is a chance for race condition your test results are non-deterministic, which means human-intervention is needed to interpret several resultsets, reproduce the issues (if it is even possible) and fix them. </li>\n<li>Timely: It is irrelevant in our discussion </li>\n</ul>\n\n<h3>Separate database for each test case</h3>\n\n<ul>\n<li>Fast: Creating new in-memory database for each test should not impose performance penalty onto tests if there not too many tables and constraints.</li>\n<li>Isolated: Separate databases are used for each test, means no shared resource is being used, which helps isolation.</li>\n<li>Repeatable: Because each and every time you run your test against a brand new database, there won't be any trash data, which could cause race condition.</li>\n<li>Self-validating: By being deterministic, no human intervention is needed to understand the test results.</li>\n<li>Timely: It is irrelevant in our discussion</li>\n</ul>\n\n<hr>\n\n<p>If you don't want to examine the test data manually, then you don't really need use the test name in the database name. You can use any random value:</p>\n\n<pre><code>int jitter = idGenerator.Next();\nvar condigBuilder = DbContextOptionsBuilder<TestContext>()\n .UseInMemoryDatabase(databaseName: $\"TestDb{jitter}\") \n .Options;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Guid jitter = Guid.NewGuid();\nvar condigBuilder = DbContextOptionsBuilder<TestContext>()\n .UseInMemoryDatabase(databaseName: $\"TestDb{jitter}\") \n .Options;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T10:26:20.603",
"Id": "243257",
"ParentId": "243188",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T19:47:40.500",
"Id": "243188",
"Score": "3",
"Tags": [
"c#",
".net",
"unit-testing",
"comparative-review"
],
"Title": "In Memory Database in Unit tests, isolate the tests"
}
|
243188
|
<p>please roast my code, I hope this is the good place to look for some advice on where I can improve.</p>
<p><strong>Problem definition:</strong></p>
<p>Apply modifications on values depending on date ranges.</p>
<p><strong>Data:</strong></p>
<p>Base array - holds dictionaries in the following format:</p>
<p>[{'date': 20200101, 'value': 1}, {'date': 20200102, 'value': 2}]</p>
<p>Modifier array - holds dictionaries with similar format:</p>
<p>[{'date': 20200101, 'value': 1}, {'date': 20200201, 'value': 2}]</p>
<p>Edit: Both arrays are holding values with dates sorted in ascending order.</p>
<p><strong>Goal:</strong>
Add the respective value of the modifier array to the base array lining up the date ranges. Dates are exclusive, for example when the modifier array contains 2020-01-01 you have to add the value '1' to all values in the base array that have a date less than 2020-01-01. Base array has a lot of elements while modifier array relatively few. In practice this splits the base array into a couple of date ranges. If the last modification date is less than the date in base array no modification is required.</p>
<p><strong>My solution:</strong></p>
<p>This is assuming the comparing of dates will work, I have translated this from perl for an easier read.</p>
<pre class="lang-py prettyprint-override"><code>mod_index = 0
mod_size = len(mod_arr)
for elem in base_arr:
if elem['date'] > mod_arr[mod_size - 1]['date']:
break
else:
if elem['date'] < mod_arr[mod_index]['date']:
elem['value'] += mod_arr[mod_index]['value']
else:
elem['value'] += mod_arr[mod_index + 1]['value']
mod_index += 1
</code></pre>
|
[] |
[
{
"body": "<p>To preface, PEP8 recommends <a href=\"https://stackoverflow.com/questions/1125653/python-using-4-spaces-for-indentation-why\">4 spaces</a> instead of 2 spaces for indentation, so I've written all below code as such.</p>\n\n<p>There is a subtle bug in your program (and may be nonexistent at all, the requirements are ambiguous here), but:</p>\n\n<pre><code>if elem['date'] < mod_arr[mod_index]['date']:\n elem['value'] += mod_arr[mod_index]['value']\nelse:\n elem['value'] += mod_arr[mod_index + 1]['value']\n mod_index += 1\n</code></pre>\n\n<p>assumes that <code>mod_array[mod_index + 1][\"date\"] > mod_array[mod_index][\"date\"]</code>, though your requirements never say that <code>\"date\"</code> is <em>strictly</em> increasing (and <code>mod_array</code> being sorted doesn't imply this).</p>\n\n<p>We can handle this by changing the <code>if / else</code> to a <code>while</code>:</p>\n\n<pre><code>while elem['date'] >= mod_arr[mod_index]['date']:\n mod_index += 1\n\nelem['value'] += mod_arr[mod_index]['value']\n</code></pre>\n\n<p>Note that this also increments <code>mod_index</code> before the mutation of <code>elem[\"value\"]</code>, allowing us to de-duplicate its mutation. </p>\n\n<p>Since we are only moving forward in <code>mod_arr</code>, we actually don't need <code>mod_index</code> at all. We can do <code>mod_array_iter = iter(mod_array)</code>, and replace <code>mod_index += 1</code> with <code>mod = next(mod_array_iter)</code>. This also helps us avoid any off-by-one errors.</p>\n\n<p>Another benefit of using <code>iter</code> here is it opens up an easy way to exit the function if <code>mod_array</code> is empty (implying no mutations to <code>base_arr</code> should be done, the original program didn't account for this) <em>or</em> if we've traversed through all of <code>mod_array_iter</code> (implying necessary mutations to <code>base_arr</code> have been done, original program accounted for this with the <code>if</code> and inner <code>break</code>). We can use a <code>try / except</code> for both of those cases, and get rid of the initial <code>if</code> with inner <code>break</code>.</p>\n\n<p>Final code ends up looking like (wrapped is a function for reusability):</p>\n\n<pre><code>def mutate_base_arr(base_arr, mod_arr):\n mod_arr_iter = iter(mod_arr)\n\n try:\n mod = next(mod_arr_iter)\n\n for elem in base_arr:\n while elem['date'] >= mod['date']:\n mod = next(mod_arr_iter)\n\n elem['value'] += mod['value']\n except StopIteration:\n return\n</code></pre>\n\n<p>If you really wanted to take this a step further, you could get rid of the <code>while</code> and duplicate <code>next</code>s by using <code>itertools</code>, yielding this version of the function:</p>\n\n<pre><code>def mutate_base_arr(base_arr, mod_arr):\n mod_arr_iter = iter(mod_arr)\n\n try:\n for elem in base_arr:\n valid_mod = next(mod for mod in mod_arr_iter if elem[\"date\"] < mod[\"date\"])\n mod_arr_iter = itertools.chain([valid_mod], mod_arr_iter)\n\n elem['value'] += valid_mod['value']\n except StopIteration:\n return\n</code></pre>\n\n<p>Though I'm not sure if I'd recommend this, as having to prepend <code>valid_mod</code> with <code>mod_arr_iter</code> each iteration so it can be re-checked next iteration of the <code>for</code> is a bit unusual. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T03:47:52.163",
"Id": "243196",
"ParentId": "243189",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "243196",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-31T20:21:39.820",
"Id": "243189",
"Score": "4",
"Tags": [
"python",
"array",
"datetime"
],
"Title": "Apply additions on a base array based on date ranges"
}
|
243189
|
<p>I'm going through the book Grokking Algorithms which is in Python but wanted to write everything in C++. Up to this point everything's been pretty straightforward translation but the code for Dijkstra's algorithm really exploits nested dictionaries and weak typing which I used as an excuse to try out <code>std::optional</code>. I also am playing around with <code>std::set</code>, <code>std::unordered_map</code>, and using <code>typedef</code> to alias ugly types for the first time.</p>
<p>I've retained the original script-like functionality of the original code and have thrown everything into <code>main</code>, and know that a real implementation would be nicely put into a separate function. I am also aware that a real implementation would use a priority queue for finding the minimum cost edge rather than a linear search and wasn't really interested in Dijkstra's but moreso in the C++.</p>
<h1>What to Review</h1>
<p>Primarily interested in knowing about my usage of <code>typedef</code> in this way, as well as if there was a better way than using <code>std::optional</code> and <code>std::nullopt</code> to handle translating from Python's <code>None</code> type.</p>
<h1>C++17 Code</h1>
<p>Translated from <a href="https://github.com/egonSchiele/grokking_algorithms/blob/master/07_dijkstras_algorithm/python/01_dijkstras_algorithm.py" rel="nofollow noreferrer">Python</a> from Grokking Algorithms book.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <iostream>
#include <limits>
#include <optional>
#include <set>
#include <unordered_map>
using namespace std;
typedef unordered_map<string, double> CostGraph;
typedef unordered_map<string, optional<string>> ParentGraph;
typedef unordered_map<string, unordered_map<string, double>> WeightedGraph;
auto find_lowest_cost_node(CostGraph costs, const set<string>& processed) {
auto lowest_cost = numeric_limits<double>::max();
optional<string> lowest_cost_node = nullopt;
for (const auto [node, cost] : costs) {
if (cost < lowest_cost && find(processed.begin(), processed.end(), node) == processed.end()) {
lowest_cost = cost;
lowest_cost_node = node;
}
}
return lowest_cost_node;
}
int main() {
WeightedGraph graph;
graph["start"] = {};
graph["start"]["a"] = 6;
graph["start"]["b"] = 2;
graph["a"] = {};
graph["a"]["fin"] = 1;
graph["b"] = {};
graph["b"]["a"] = 3;
graph["b"]["fin"] = 5;
graph["fin"] = {};
CostGraph costs;
costs["a"] = 6;
costs["b"] = 2;
costs["fin"] = numeric_limits<double>::max();
ParentGraph parents;
parents["a"] = "start";
parents["b"] = "start";
parents["fin"] = {};
auto processed = set<string>{};
while (const auto node = find_lowest_cost_node(costs, processed)) {
const auto cost = costs[node.value()];
const auto neighbours = graph[node.value()];
for (const auto [n, c] : neighbours) {
const auto new_cost = cost + c;
if (costs[n] > new_cost) {
costs[n] = new_cost;
parents[n] = node;
}
}
processed.insert(node.value());
}
cout << "Costs\n";
for (const auto [k, v] : costs) {
cout << k << ": " << v << "\n";
}
cout << "Parents\n";
for (const auto [k, v] : parents) {
if (v) {
cout << k << ": " << v.value() << "\n";
} else {
cout << k << ": None\n";
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T14:44:11.303",
"Id": "477363",
"Score": "2",
"body": "Small comment to get you started: [Don't use `using namespace std`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), and use [`using` instead of `typedef`](https://stackoverflow.com/questions/10747810/what-is-the-difference-between-typedef-and-using-in-c11), e.g. `using CostGraph = std::unordered_map<std::string, double>;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T03:59:34.580",
"Id": "477403",
"Score": "0",
"body": "Literal translations of algorithms between languages is unwise. The standard idioms of the language will not be used correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T04:01:54.960",
"Id": "477404",
"Score": "0",
"body": "Here is a close translation: https://stackoverflow.com/a/3448361/14065"
}
] |
[
{
"body": "<h1>Avoid translating Pythonisms</h1>\n\n<blockquote>\n <p>Dijkstra's algorithm really exploits nested dictionaries and weak typing which I used as an excuse to try out std::optional.</p>\n</blockquote>\n\n<p>No, <a href=\"https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"nofollow noreferrer\">Dijkstra's algorithm</a> does not require nested dictionaries nor weak typing. Maybe the Python implementation you are translating used these things, but maybe just because it was convenient in Python.</p>\n\n<p>I strongly advise you to try to write idiomatic C++ code, not idiomatic Python translated to C++. What is convenient in Python might not be the best fit for C++, especially not when it comes to performance. I recommend you try to implement Dijkstra's using a <a href=\"https://en.cppreference.com/w/cpp/container/priority_queue\" rel=\"nofollow noreferrer\">priority queue</a>.</p>\n\n<p>Furthermore, putting everything into <code>main()</code> is bad practice. It's better to organize your code into functions and classes as appropriate, and that's true even in Python.</p>\n\n<h1>Use of typedefs</h1>\n\n<p>It's always a good idea to give a name to things, including types, that you use in multiple places in your code. However, in this case I think it would be better to create a <code>class WeightedGraph</code> that contains all the information about a graph with weighted edges. Then you can add member functions to this graph to add and remove vertices and edges, and a member function <code>get_shortest_path()</code> that uses Dijkstra's to calculate the shortest path between two given vertices and returns the list of vertices.</p>\n\n<h1>Use of <code>std::optional</code></h1>\n\n<p>While it's possible to use <code>std::optional</code> here to represent the parent of a vertex, it might not be necessary. If you represent vertices by their name, then an empty string for the name might be used as the equivalent of <code>None</code>. And a more idiomatic C++ implementation of this algorithm would probably store each vertex's parent vertex using a pointer, in which case the <code>nullptr</code> would be the equivalent of <code>None</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:02:16.457",
"Id": "243227",
"ParentId": "243200",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243227",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:14:23.160",
"Id": "243200",
"Score": "0",
"Tags": [
"c++",
"c++17"
],
"Title": "Translating Dijkstra's Algorithm from Python to C++"
}
|
243200
|
<p>There are probably a lot better ways to do it, but take it as a learning exercise. Basically below is the JSON InputValidation and parsing using <code>nlohmann::json</code> which takes expected fields, objects arrays and verifies its presence and (optionally) parses them into an appropriate c++ structure.</p>
<p><strong>inputvalidation.hpp:</strong></p>
<pre><code>namespace iv
{
template<typename _Tp>
class Field;
template<typename... _Ts>
class Object;
template<typename _Tp>
class Array;
template<typename _Old, typename _New>
class Deprecated;
namespace detail
{
template<class _Tp, template<class...> class Template>
struct is_specialization : ::std::false_type {};
template<template<class...> class Template, class... Args>
struct is_specialization<Template<Args...>, Template> : ::std::true_type {};
template<typename _Tp>
struct remove_opt { using type = _Tp; };
template<typename _Tp>
struct remove_opt<::std::optional<_Tp>> { using type = _Tp; };
template<typename _Tp>
using remove_opt_t = typename remove_opt<_Tp>::type;
template<typename _Tp>
using decay_t = ::std::decay_t<remove_opt_t<_Tp>>;
#define _CONSTEVAL constexpr
template<typename _pack, std::size_t N>
_CONSTEVAL std::size_t elem_size(std::size_t& ref, std::array<std::size_t, std::tuple_size_v<_pack>>& offsets) noexcept
{
using _Tp = std::conditional_t<
is_specialization<std::tuple_element_t<N, _pack>, std::optional>{},
std::optional<typename decay_t<std::tuple_element_t<N, _pack>>::value_type>,
typename decay_t<std::tuple_element_t<N, _pack>>::value_type>;
while (ref % alignof(_Tp) != 0)
++ref;
offsets[N] = ref;
ref += sizeof(_Tp);
return alignof(_Tp);
}
template<typename _pack, typename std::size_t... Indices>
_CONSTEVAL const std::tuple<
const size_t,
const size_t,
const std::array<std::size_t, std::tuple_size_v<_pack>>>
structure_type_helper(std::index_sequence<Indices...>)
{
std::size_t size = 0;
std::array<std::size_t, std::tuple_size_v<_pack>> offsets = {};
auto pad = (elem_size<_pack, Indices>(size, offsets) | ...);
std::size_t padding = 1;
while (pad >>= 1)
padding *= 2;
return std::make_tuple(size, padding, offsets);
}
template<typename _Tp>
struct structure_type
{
static constexpr const auto _storage = structure_type_helper<_Tp>(std::make_index_sequence<std::tuple_size_v<_Tp>>());
using type = typename std::aligned_storage_t<std::get<0>(_storage), std::get<1>(_storage)>;
static constexpr const std::array<std::size_t, std::tuple_size_v<_Tp>>& offsets = std::get<2>(_storage);
};
template<typename _Tp>
using structure_type_t = typename structure_type<_Tp>::type;
#undef _CONSTEVAL
template<typename _pack, typename std::size_t... Indices>
inline bool typeCheck(const nlohmann::json& j, const _pack& tuple, std::index_sequence<Indices...>) noexcept;
template<typename _pack, typename std::size_t... Indices>
inline void fromTuple(const _pack& tuple, const nlohmann::json& j, uint8_t* where, std::index_sequence<Indices...>);
}
template<typename _Tp>
class Field
{
static_assert(!std::is_reference_v<_Tp> && !std::is_pointer_v<_Tp>,
"Field type can not have a reference or a pointer type");
static_assert(!detail::is_specialization<_Tp, Field>{},
"Field type can not have field as a value type");
public:
using value_type = _Tp;
using comparator_type = bool(const value_type&);
constexpr Field() = default;
constexpr explicit Field(const char* tp) : _name(tp) {}
constexpr explicit Field(const char* tp, comparator_type f) : _name(tp), _comp(f) {}
bool check(const nlohmann::json& j) const noexcept
{
try
{
auto value = j.get<value_type>();
if (_comp)
{
return _comp(value);
}
return true;
}
catch (...)
{
return false;
}
}
value_type parse(const nlohmann::json& j) const
{
return j.get<value_type>();
}
constexpr const char* name() const noexcept { return _name; }
private:
const char* _name = nullptr;
comparator_type* _comp = nullptr;
};
template<typename... _Ts>
class Object
{
static_assert(sizeof...(_Ts), "Object must have at least one field");
public:
using tuple_type = std::tuple<_Ts...>;
using value_type = typename detail::structure_type_t<tuple_type>;
constexpr Object() = default;
constexpr explicit Object(const char* tp, tuple_type&& fields) : _name(tp), _pack(std::move(fields)) {}
constexpr explicit Object(const char* tp, const Object& ref) : _name(tp), _pack(ref._pack) {}
bool check(const nlohmann::json& j) const noexcept
{
if (j.is_object() != true)
{
return false;
}
if constexpr (sizeof...(_Ts) != 0)
{
return detail::typeCheck(j, _pack, std::make_index_sequence<std::tuple_size_v<tuple_type>>());
}
}
value_type parse(const nlohmann::json& j) const
{
value_type storage;
uint8_t* ptr = reinterpret_cast<uint8_t*>(&storage);
detail::fromTuple(_pack, j, ptr, std::make_index_sequence<std::tuple_size_v<tuple_type>>());
return storage;
}
constexpr const char * name() const noexcept { return _name; }
constexpr const tuple_type& pack() const noexcept { return _pack; }
private:
const char* _name = nullptr;
tuple_type _pack;
};
template<typename _Tp>
class Array
{
static_assert(!std::is_reference_v<_Tp> && !std::is_pointer_v<_Tp>,
"Can not create an array of pointers or references");
static_assert(!detail::is_specialization<_Tp, std::optional>{},
"Can not create an array of optionals");
public:
using value_type = std::vector<typename _Tp::value_type>;
constexpr Array() = default;
constexpr explicit Array(const char* tp) : _name(tp) {}
constexpr explicit Array(const char* tp, std::size_t limit) : _name(tp), _lim(limit) {}
constexpr explicit Array(const char* tp, const _Tp& check, std::size_t limit = 0)
: _name(tp), _comp(check), _lim(limit) {}
bool check(const nlohmann::json& j) const noexcept
{
if (j.is_array() != true)
{
return false;
}
if (_lim && j.size() > _lim)
{
return false;
}
for (const auto& elem : j)
{
if (_comp.check(elem) != true)
{
return false;
}
}
return true;
}
value_type parse(const nlohmann::json& j) const
{
value_type ret; ret.reserve(16);
for (const auto& elem : j)
{
ret.push_back(_comp.parse(elem));
}
return ret;
}
constexpr const char * name() const noexcept { return _name; }
constexpr std::size_t limit() const noexcept { return _lim; }
private:
const char* _name = nullptr;
_Tp _comp;
std::size_t _lim = 0;
};
template<typename _Old, typename _New>
class Deprecated
{
static_assert(!detail::is_specialization<_Old, Deprecated>{} && !detail::is_specialization<_New, Deprecated>{},
"Deprecation of deprecated type is not allowed");
public:
using depr_type = _Old;
using new_type = _New;
using value_type = std::variant<typename depr_type::value_type, typename new_type::value_type>;
constexpr Deprecated() = default;
constexpr explicit Deprecated(_Old&& depr, _New&& replacement) : _old(depr), _new(replacement) {}
bool check(const nlohmann::json& j) const noexcept
{
return _new.check(j) || _old.check(j);
}
value_type parse(const nlohmann::json& j) const
{
return _new.check(j) ? _new.parse(j) : _old.parse(j);
}
constexpr const char * name() const noexcept { return _new.name(); }
_Old _old;
_New _new;
};
namespace detail
{
#define _RUNTIME inline
template<std::size_t N, class... _Ts>
_RUNTIME const decay_t<std::tuple_element_t<N, std::tuple<_Ts...>>>& getVal(const std::tuple<_Ts...>& tuple) noexcept
{
if constexpr (is_specialization<std::decay_t<std::tuple_element_t<N, std::tuple<_Ts...>>>, std::optional>{})
{
return std::get<N>(tuple).value();
}
else
{
return std::get<N>(tuple);
}
}
template<std::size_t N, class... _Ts>
_RUNTIME bool typeCheckHelper(const nlohmann::json& j, const std::tuple<_Ts...>& tuple) noexcept
{
auto it = j.find(getVal<N>(tuple).name());
if (it == j.end() || it->is_null()) // element not found
{
if constexpr (is_specialization<std::decay_t<std::tuple_element_t<N, std::tuple<_Ts...>>>, std::optional>{})
{
return true;
}
//TODO: Handle error - field not found
return false;
}
if (getVal<N>(tuple).check(*it) == false)
{
//TODO: handle error - invalid field type
return false;
}
return true;
}
template<typename _pack, typename std::size_t... Indices>
_RUNTIME bool typeCheck(const nlohmann::json& j, const _pack& tuple, std::index_sequence<Indices...>) noexcept
{
return (typeCheckHelper<Indices>(j, tuple) && ...);
}
template<typename _Tp>
_RUNTIME const decay_t<_Tp>& getVal(const _Tp& ref)
{
if constexpr (is_specialization<std::decay_t<_Tp>, std::optional>{})
{
return ref.value();
}
else
{
return ref;
}
}
template<typename _Tp>
_RUNTIME void fromTupleImpl(_Tp&& element, const nlohmann::json& data, uint8_t* where)
{
using _Ty = std::conditional_t<
is_specialization<_Tp, std::optional>{},
std::optional<typename decay_t<_Tp>::value_type>,
typename decay_t<_Tp>::value_type>;
new (where) _Ty(getVal(element).parse(data[getVal(element).name()]));
}
template<typename _pack, typename std::size_t... Indices>
_RUNTIME void fromTuple(const _pack& tuple, const nlohmann::json& j, uint8_t* where, std::index_sequence<Indices...>)
{
((void)fromTupleImpl(std::get<Indices>(tuple), j, where + structure_type<_pack>::offsets[Indices]), ...);
}
#undef _RUNTIME
}
template<typename... _Ts>
constexpr Object<_Ts...> make_object(const char* name, _Ts&& ...args)
{
return Object<_Ts...>{name, std::make_tuple(std::forward<decltype(args)>(args)...)};
}
template<typename... _Ts>
constexpr std::optional<Object<_Ts...>> make_nullable_object(const char* name, _Ts&& ...args)
{
return Object<_Ts...>{name, std::make_tuple(std::forward<decltype(args)>(args)...)};
}
template<typename _Tp, typename... _Ts>
constexpr _Tp get(const Object<_Ts...>& ref, const nlohmann::json& j)
{
static_assert(alignof(detail::structure_type_t<std::tuple<_Ts...>>) == alignof(_Tp)
&& alignof(detail::structure_type_t<std::tuple<_Ts...>>) == alignof(_Tp),
"Invalidly calculated structure alignment and/or size.");
auto _storage = ref.parse(j);
return *reinterpret_cast<_Tp*>(&_storage);
}
}
</code></pre>
<p><strong>Usage:</strong> </p>
<pre><code>// this is 'read' from the file
nlohmann::json j;
j["first"] = 1;
j["second"] = "string";
j["third"]["subfield1"] = "asdf";
j["third"]["subfield2"] = 1954;
j["third"]["subfield3"].push_back(1);
j["third"]["subfield3"].push_back(8);
j["third"]["subfield3"].push_back(27);
// structure metadata - tell the validator what do you expect in JSON
auto obj = make_object("",
Field<int>{"first"},
Field<std::string>{"second"},
make_object("third",
Field<std::string>{"subfield1"},
Field<int>{"subfield2"},
Array<Field<double>>{"subfield3"}
)
);
// create a structure that reflects the JSON layout
struct s1 {
int a;
std::string b;
struct {
std::string a;
int b;
std::vector<double> c;
} c;
};
// verify that it has everything you're expecting and parse it
if (obj.check(j))
{
s1 s = get<s1>(obj, j);
// do whatever you want with the structure
}
</code></pre>
<p>You can also have an array of objects if you want. Go ahead and experiment if you want.. </p>
<hr>
<p><em>Side note: At the moment having std::vector of structure containing std::string have unexpected effects when accessing the string on clang and gcc. Works with MSVC tho. I don't know what the problem is unfortunately. I've track that to the std::vector itself so far.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T02:38:57.447",
"Id": "477401",
"Score": "0",
"body": "I did something similar yu should check out: [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer/blob/master/doc/example1.md)"
}
] |
[
{
"body": "<h2>Observatoion</h2>\n<p>I don't really have much to say on this code.<br />\nLooks good.If this was at work (and it had unit tests) I would say fine to check in.</p>\n<p>The below are very minor comments.</p>\n<h2>Code Review</h2>\n<p>Please stop using the leading underscore.<br />\nIdentifiers with a leading underscore are usually reserved. The rules are not obvious (you break them) but because they are not obvious you should avoid putting the <code>_</code> at the beginning of an identifier.</p>\n<p>Note: The end is fine.</p>\n<p>see: <a href=\"https://stackoverflow.com/q/228783/14065\">What are the rules about using an underscore in a C++ identifier?</a></p>\n<hr />\n<p>I very rarely see the leading <code>::</code> used to specify an absolute namespace.</p>\n<pre><code>::std::false_type \n</code></pre>\n<p>Sure that works.</p>\n<hr />\n<p>Good use of template meta programming.</p>\n<hr />\n<p>Not sure I like these.</p>\n<pre><code>#define _CONSTEVAL constexpr\n#define _RUNTIME inline\n</code></pre>\n<p>Since they are always defined why have them at all?</p>\n<p>Also in the class you don't need <code>inline</code> its redundant when used in the class. The general rule is don't use it unless you must. The only time you must is out of class definitions in the header file.</p>\n<hr />\n<p>I find this hard to read:</p>\n<pre><code> using _Tp = std::conditional_t<\n is_specialization<std::tuple_element_t<N, _pack>, std::optional>{},\n std::optional<typename decay_t<std::tuple_element_t<N, _pack>>::value_type>,\n typename decay_t<std::tuple_element_t<N, _pack>>::value_type>;\n</code></pre>\n<p>When I build types I do it over a couple of lines so it easy to read (by the next person to look at the code).</p>\n<pre><code> using NthElement = std::tuple_element_t<N, _pack>\n using DecayNthElement = typename decay_t<NthElement>::value_type;\n using IsSpecNthElement = is_specialization<NthElement, std::optional>;\n\n using Type = std::conditional_t<\n IsSpecNthElement{},\n std::optional<DecayNthElement>,\n DecayNthElement::value_type\n >;\n</code></pre>\n<hr />\n<p>I would simplify this:</p>\n<pre><code> if (_comp)\n {\n return _comp(value);\n }\n return true;\n\n // This is just as easy\n // But now I think about it yours is fine.\n return _comp ? _comp(value) : true;\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T14:25:05.997",
"Id": "477447",
"Score": "0",
"body": "are underscores followed by an uppercase letter reserved in template parameters as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T15:44:47.130",
"Id": "477465",
"Score": "1",
"body": "@Quest They are reserved everywhere."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T03:50:12.090",
"Id": "243246",
"ParentId": "243208",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T07:53:55.580",
"Id": "243208",
"Score": "2",
"Tags": [
"c++",
"json",
"c++17"
],
"Title": "JSON Input validator and Parser"
}
|
243208
|
<p>In a part of our system a lot (I'm not sure how many, probably a couple thousand) of emails are being sent to the users at a specific time of the month. It seems this kills the server.
So I was asked to add the mailing of these emails to another part of the system that uses a Scheduler to do calculations.
The idea being that the Scheduler can then handle the sending of emails in parallel etc.</p>
<p>So I began looking at the code that I need to integrate with, and began reading on the Internet, and I'm thinking that perhaps I don't need to overhaul the emails into the Scheduler just yet.</p>
<p>It looks like they (the original programmers who no longer work at the company) didn't implement the sending of the emails asynchronously, so no wonder the server is being killed. It also made me wonder where the actual bottleneck is, would it even help to have the Scheduler implement a bunch of threads but still call the synchronous Send method...?</p>
<p>I have seen that SmtpClient has a SendMailAsync method. I have also seen that SmtpClient is considered obsolete and that MailKit is preferred.
The system uses .Net 4.5.2.</p>
<p>I haven't used Postman before, but I have managed to do some tests with a small number of email addresses. I compare the time between the current synchronous way of sending emails, and then I implemented async methods using SendMailAsync. The SendMailAsync functionality takes less time according to Postman.</p>
<p>So I want to change the implementation to use SendMailAsync, then after that I want to change it to use MailKit.</p>
<p>However, I'm not sure whether I am making other mistakes.</p>
<p>Here is the changed method to use SendMailAsync:</p>
<pre><code>public async virtual Task<string> SendMailAsync(string[] emailAddresses, Dictionary<string, string> replacements, string body)
{
try
{
body = ReplaceProductName(replacements, body);
// Intercept email if test email address is setup
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["testEmailAddress"]))
{
string emailAddress = ConfigurationManager.AppSettings["testEmailAddress"];
using (MailMessage mail = mailDefinition.CreateMailMessage(emailAddress, replacements, body, new System.Web.UI.Control()))
{
{
await client.SendMailAsync(mail);
log.Info("The following email was sent to " + emailAddress + " Replacements: " + replacements.ToDebugString());
}
}
}
else
{
using (MailMessage mail = mailDefinition.CreateMailMessage(string.Join(",", emailAddresses), replacements, body, new System.Web.UI.Control()))
{
{
await client.SendMailAsync(mail);
log.Info("The following email was sent to " + string.Join(",", emailAddresses) + " Replacements: " + replacements.ToDebugString());
}
}
}
}
catch (Exception ex)
{
log.Error("The following email could not be sent. Replacements: " + replacements.ToDebugString());
log.Error(ex.Message);
throw ex;
}
return string.Join(",", emailAddresses);
}
</code></pre>
<p>Is it okay to use the using block? I read somewhere something about it, but perhaps it was concerning the method SendAsync. I'm not sure.</p>
<p>Any further advice and suggestions would be appreciated. :-)</p>
<p><strong>UPDATE</strong></p>
<p>It seems the emails are sent through Gmail's smtp server. I found this in a helper class:</p>
<pre><code>public void Send(string toEmail, string subject, string body)
{
new SmtpClient
{
Port = 587,
Host = "smtp.gmail.com",
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("somenoreply@gmail.com", "SomePassword")
}.Send(new MailMessage("some.lab@gmail.com", toEmail, subject, body)
{
IsBodyHtml = true,
BodyEncoding = Encoding.UTF8,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
});
}
</code></pre>
<p><strong>UPDATE 2</strong></p>
<p>Upon further investigation, it seems that some emails are being sent from a Microsoft SQL server stored procedure which uses a cursor. This causes trouble on the SQL server.
I initially thought it was a different server being affected, but it is actually the SQL server being slowed down by this stored proc sending emails.
This stored proc calls another stored procedure, which with a few more methods inbetween eventually calls the method given above (SendMailAsync).
However, currently the synchronous version of the above method is still the one being used in the system.</p>
<p>It seems that less emails than I originally thought are being sent via Gmail's smtp. The limit on Gmail's side (I think 2000 per day) is not being hit at present.</p>
<p>So my question is, would implementing the asynchronous version, SendMailAsync also be an improvement to the performance of the SQL Server, or is the cursor in the stored procedure itself a greater problem?</p>
<p>Here is the stored proc:</p>
<pre><code>DROP PROCEDURE [dbo].[sp_Interface_PayslipEmails]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[sp_Interface_PayslipEmails](@Periods VARCHAR(MAX),@Resourcetag INT = 0)
AS
BEGIN
DECLARE @Collection VARCHAR(50)
DECLARE @Periodid INT
DECLARE @PortalURL VARCHAR(500) = (SELECT TOP 1 Value from [System Variables] WHERE [Variable] = 'Portal URL')
DECLARE @PeriodTable TABLE ([Period id] INT )
IF @Resourcetag = 0 SET @Resourcetag = NULL
INSERT INTO @PeriodTable
(
[Period id]
)
select [Value] FROM dbo.fn_Split(@Periods,',')
SET @Periodid = (SELECT MAX([period id]) FROM @PeriodTable)
SET @Collection = (SELECT dbo.fn_GetCalendarCollectionfromPeriod(@Periodid))
SET @Collection = UPPER(REPLACE(@Collection,'Payrun ',''))
UPDATE I
SET I.[Status] = 'Processed'
FROM [dbo].[PER REM Infoslip] I
INNER JOIN @PeriodTable P
ON I.[Period id] = P.[Period id]
INNER JOIN [dbo].[Calendar Periods] cp
ON P.[Period id] = cp.[Period ID]
AND [cp].[RunType] = 'Normal'
AND I.[Resource Tag] =ISNULL(@Resourcetag,I.[Resource Tag])
SELECT DISTINCT I.[Resource Tag],[I].[E-mail Address]
INTO #Employees
FROM [dbo].[PER REM Infoslip] I
INNER JOIN @PeriodTable P
ON I.[Period id] = P.[Period id]
INNER JOIN [dbo].[Calendar Periods] cp
ON P.[Period id] = cp.[Period ID]
AND [cp].[RunType] = 'Normal' --only normal periods available for now
WHERE ISNULL([I].[E-mail Address],'') != ''
AND I.[status] = 'Processed'
AND I.[Resource Tag] = ISNULL(@Resourcetag,I.[Resource Tag])
/* declare variables */
DECLARE @RT INT
DECLARE @EmailAddress VARCHAR(150)
DECLARE @Message VARCHAR(MAX) =''
IF @Collection LIKE '%Feb%2020%'
SET @Message = 'Friendly Reminder. All excess leave will be forfeited on the 28th February as per previous communications.'
DECLARE cursor_name CURSOR FOR SELECT [Resource Tag],[E-mail Address] FROM #Employees
OPEN cursor_name
FETCH NEXT FROM cursor_name INTO @RT,@EmailAddress
WHILE @@FETCH_STATUS = 0
BEGIN
--API Call to send email
PRINT @Collection
PRINT @PortalURL
EXEC Sp_SendPayslipEmail @PortalURL,@RT,@EmailAddress,@Collection,@Message
FETCH NEXT FROM cursor_name INTO @RT,@EmailAddress
END
CLOSE cursor_name
DEALLOCATE cursor_name
END
GO
</code></pre>
<p>Here is the next stored procedure:</p>
<pre><code>DROP PROCEDURE [dbo].[Sp_SendPayslipEmail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Sp_SendPayslipEmail](
@Hostname NVARCHAR(MAX)
, @ResourceTag INT
, @Email VARCHAR(256)
, @Period NVARCHAR(256)
, @Message VARCHAR(MAX))
AS
DECLARE @now VARCHAR(MAX) = CONVERT(NVARCHAR(MAX), GETDATE(), 13)
DECLARE @OBJECT INT
DECLARE @RESPONSETEXT VARCHAR(8000)
DECLARE @URL NVARCHAR(MAX) = 'https://' + @Hostname + '/payslip/sendpayslipemail?resourceTag=' + CAST(@ResourceTag AS VARCHAR(50))+ '&emailAddress=' + @Email + '&period=' + @Period + '&message=' + ISNULL(@Message,'') + '&_=' + @now
EXEC sp_OACreate 'Msxml2.ServerXMLHTTP.6.0', @OBJECT OUT
EXEC sp_OAMethod @OBJECT, 'setTimeouts', NULL, 5000, 5000, 30000, 300000
EXEC sp_OAMethod @OBJECT, 'open', NULL, 'get', @URL, 'false'
EXEC sp_OAGetErrorInfo @object
EXEC sp_OAMethod @OBJECT, 'send'
EXEC sp_OAGetErrorInfo @object
EXEC sp_OAMethod @OBJECT, 'responseText',@RESPONSETEXT OUTPUT
SELECT @RESPONSETEXT
EXEC sp_OADestroy @OBJECT
EXEC sp_OAGetErrorInfo @object
GO
</code></pre>
<p>Here is the action method:</p>
<pre><code>public ActionResult SendPayslipEmail(int resourceTag, string emailAddress, string period, string message = "")
{
using (ESSDataContext ctx = new ESSDataContext())
{
try
{
string systemUrl = Request.Url.GetLeftPart(UriPartial.Authority);
var displayName = MyDetailsDataManager.GetDisplayName(resourceTag);
new PayslipNotificationMailSender().SendPayslipReadyNotification(emailAddress, systemUrl, period, displayName, message);
ctx.sp_ESS_PayslipEmailAudit(resourceTag, emailAddress, period, "Sent", "");
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
ctx.sp_ESS_PayslipEmailAudit(resourceTag, emailAddress, period, "Failed", ex.Message);
log.Error($"Error sending payslip email. Error: {ex.Message}");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
}
</code></pre>
<p>Here is the method that calls the SendMail message, which I have tried to change to SendMailAsync above:</p>
<pre><code>public void SendPayslipReadyNotification(string employeeEmail, string systemUrl, string period, string displayName, string message = "")
{
try
{
mailDefinition.Subject = "Payslip Generated";
string body =
System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory +
"App_Data/Templates/MailTemplates/PayslipNotification.html");
Dictionary<string, string> replacements = new Dictionary<string, string>();
replacements.Add("<%LoginUrl%>", systemUrl);
replacements.Add("<%PayslipPeriod%>", period);
replacements.Add("<%UserName%>", displayName);
replacements.Add("<%Message%>", message);
SendMail(employeeEmail, replacements, body);
}
catch (Exception e)
{
log.Error("SendPayslipReadyNotification failed for :" + employeeEmail);
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
throw e;
}
}
</code></pre>
<p>I didn't write these last methods /stored procedures. It's just what is in the system currently, and I want to improve it. I'm not knowledgeable regarding web programming nor sql, which in this case is definitely a disadvantage.
So I don't know whether implementing async functionality in the C# methods will actually improve the SQL server's performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T10:15:18.077",
"Id": "477343",
"Score": "2",
"body": "Welcome to CodeReview. While the question itself is well-suited to this site, your code isn't completely reviewable on its own. Some further information might be necessary for reviewers, e.g. `ReplaceProductName` or `CreateMailMessage` and what `client` is. Note that I personally don't know anything about the .NET platform, and you might disregard this comment if both are well-known in the community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T14:24:11.393",
"Id": "477360",
"Score": "1",
"body": "Sending a couple thousand emails at once isn't a good idea. You might be better off using a service like https://postmarkapp.com/ ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T16:15:59.493",
"Id": "477366",
"Score": "1",
"body": "In support of the don't do this argument I have a story - I have worked on a website running on an on-premise box and emails were routed through the office Exchange Server - a feature was implemented that did something similar (actuall sending around 50,000 emails) - this flooded Exchange Server meaning that no-one in the office was able to send/receive emails for around eight hours --- SMTP is just the protocol, you need to understand how the emails are going to be handled downstream"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T10:31:49.867",
"Id": "477432",
"Score": "0",
"body": "@Zeta, thank you, you make a valid point. For now, it doesn't seem too relevant to the main thrust of my question though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T10:32:19.860",
"Id": "477433",
"Score": "0",
"body": "@BCdotWEB, thank you, I will be looking at their services as an option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T10:59:17.870",
"Id": "477563",
"Score": "0",
"body": "@StewartRitchie, please see the update. I found that Gmail's smtp server is being used. Would it be an improvement to use a service such as Postmark then? \nWould it still make a difference to implement the async methods?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T09:49:02.977",
"Id": "478244",
"Score": "1",
"body": "Rate limits may apply when using Google's smtp server https://github.com/dotnet/announcements/issues/157"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T09:55:27.087",
"Id": "478245",
"Score": "0",
"body": "If you are sending transactional emails one at time in response to user actions, for example verifying an email address when a user registers, then dispatching then asynchronously is going to be good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T09:56:54.370",
"Id": "478246",
"Score": "1",
"body": "For a batch send scenario - use a provider like PostMark or MailChimp etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:28:51.917",
"Id": "478861",
"Score": "0",
"body": "@StewartRitchie, please see Update 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T19:48:44.677",
"Id": "478867",
"Score": "0",
"body": "Not really a code review question, but you should be aware of SQL Server database mail, that's a standard way to send mail from SQL Server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T10:20:51.933",
"Id": "478964",
"Score": "0",
"body": "@GeorgeBarwood, yes this started out as a Code Review for the SendMailAsync method, but after the initial comments and further investigation that I have done, the focus has shifted. So this code works, but I'm wondering how it could be improved and optimised, and in that sense, I think it suits Code Review rather than Stack Overflow. But I'm open to move it if others feel it doesn't fit here."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:58:57.407",
"Id": "243215",
"Score": "1",
"Tags": [
"c#",
"asynchronous",
"email"
],
"Title": "Sending emails asynchronously"
}
|
243215
|
<p>I'm solving yet another problem in HackerRank (<a href="https://www.hackerrank.com/challenges/determining-dna-health/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/determining-dna-health/problem</a>). In short: you are given 2 arrays (<code>genes</code> and <code>health</code>), one of which have a 'gene' name, and the other - 'gene' weight (aka <em>health</em>). You then given a bunch of strings, each containing values <code>m</code> and <code>n</code>, which denote the start and end of the slice to be applied to the <code>genes</code> and <code>health</code> arrays, and the 'gene'-string, for which we need to determine healthiness. Then we need to return health-values for the most and the least healthy strings.</p>
<p>My solution is below, and it works, but it's not scalable, i.e. it fails testcases with a lot of values.</p>
<pre><code>import re
if __name__ == '__main__':
n = int(input())
genes = input().rstrip().split()
health = list(map(int, input().rstrip().split()))
s = int(input())
weights = []
for s_itr in range(s):
m,n,gn = input().split()
weight = 0
for i in range(int(m),int(n)+1):
if genes[i] in gn:
compilt = "r'(?=("+genes[i]+"))'"
matches = len(re.findall(eval(compilt), gn))
weight += health[i]*matches
weights.append(weight)
print(min(weights), max(weights))
</code></pre>
<p>Can you advise on how to apply generators here? I suspect that the solution fails because of the very big list that's being assembled. Is there a way to get min and max values here without collecting them all?</p>
<p>Example values:</p>
<pre><code>genes = ['a', 'b', 'c', 'aa', 'd', 'b']
health = [1, 2, 3, 4, 5, 6]
gene1 = "1 5 caaab" (result = 19 = max)
gene2 = "0 4 xyz" (result = 0 = min)
gene3 = "2 4 bcdybc" (result = 11)
</code></pre>
<p>This case returns <code>0 19</code></p>
<p>UPD: Follow-up question on optimized (but still not working) solution <a href="https://codereview.stackexchange.com/questions/243254/finding-min-and-max-values-of-an-iterable-on-the-fly">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T23:08:47.237",
"Id": "477396",
"Score": "6",
"body": "I have rolled back your most recent edit. Code Review does not permit the question to be substantially changed after answers have been posted (accepted or not) as it becomes ambiguous as to which version of the question the answer post is answering. If you have an improved version of the code, and want feedback on it, you must post a new question. See \"What should I do when someone answers my question\" in the [help]. Note the recommendation about adding a link from this question to the new question, as well as a back link from the new question to this one."
}
] |
[
{
"body": "<h1>eval(...)</h1>\n\n<p>What is the purpose of:</p>\n\n<pre><code>compilt = \"r'(?=(\" + genes[i] + \"))'\"\n... eval(compilt), ...\n</code></pre>\n\n<p>It takes a string like <code>\"aa\"</code>, and forms a new string <code>\"r'(?=(aa))'\"</code>, which is source code for the raw string <code>r'(?=(aa))'</code>, which when <code>eval</code>uated yields the string <code>\"(?=(aa))\"</code>.</p>\n\n<p>There is no escaping being done, no obvious reason to do the raw string formation and subsequent evaluation, and no prevention of a syntax error due to a stray <code>'</code> character in the <code>genes[i]</code> array. So ... why not simply:</p>\n\n<pre><code>regex = \"(?=(\" + gene[i] + \"))\"\n</code></pre>\n\n<p>and no call to <code>eval(...)</code> at all?</p>\n\n<h1>Regex Capturing</h1>\n\n<p>The regex subexpression <code>(...)</code> is a \"capturing group\", which copies the matching characters into an internal buffer, for returning in the match group.</p>\n\n<pre><code>>>> re.findall('(?=(aa))', \"caaab\")\n['aa', 'aa']\n</code></pre>\n\n<p>Without the capturing group, the matching characters do not have to be copied to the internal buffer, to be returned.</p>\n\n<pre><code>>>> re.findall('(?=aa)', \"caaab\")\n['', '']\n</code></pre>\n\n<p>Given that you are only interested in the <code>len(...)</code> of the list returned from <code>re.findall()</code>, the capturing group seems like unnecessary overhead, which can be eliminated for faster execution.</p>\n\n<h1>Compiled Regex</h1>\n\n<p>As Python uses regular expressions, it maintains a cache of the most recently used regular expressions. This cache has a limited size, to prevent an excessive memory load.</p>\n\n<p>In this exercise, you are repeatedly using the same gene regular expressions for each \"healthy string\" test. If the number of genes exceeds the cache size, Python will be tossing out compiled regular expressions, only to compile them again moments later.</p>\n\n<p>You can preempt this by compiling and storing all the gene regular expressions ahead of time. Leveraging Python 3.6's f-strings, and list comprehension:</p>\n\n<pre><code> genes = input().rstrip().split()\n genes_rx = [re.compile(f\"(?={gene})\") for gene in genes]\n</code></pre>\n\n<p>Used as:</p>\n\n<pre><code> matches = len(re.findall(genes_rx[i], gn))\n</code></pre>\n\n<p>Now the gene to regular expression string, to compiled regular expression is done once per gene, instead of once per \"healthy string\" test.</p>\n\n<h1>Computing min/max weight without creating a list</h1>\n\n<p>How about:</p>\n\n<pre><code> min_weight = math.inf\n max_weight = -math.inf\n\n for ...:\n\n weight = ...\n\n if weight < min_weight:\n min_weight = weight\n if weight > max_weight:\n max_weight = weight\n\n print(min_weight, max_weight)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T20:13:04.603",
"Id": "477386",
"Score": "0",
"body": "AJNeufeld, I would need to take some time digesting your answer: some of the concepts you mentioned are not yet familiar to me, but right now I would like to thank you: your effort is really appreciated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T20:14:36.730",
"Id": "477387",
"Score": "0",
"body": "As for the 'what's the purpose' questions - I'm fairly new to the language, I learn stuff from various sources, and that is the best I could come up with. You are definitely right about it not being clean or optimal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:22:55.477",
"Id": "477390",
"Score": "0",
"body": "I tried the things you mentioned, but the code still fails due to timeout. See full solution in the question body."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T23:12:54.733",
"Id": "477397",
"Score": "1",
"body": "That too bad. It should be faster. Does it pass more test cases, or is it just one super large case that fails with a timeout?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T06:11:51.253",
"Id": "477407",
"Score": "0",
"body": "@DenisShvetsov Can you test and profile your code locally to see the difference in execution time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T07:21:09.817",
"Id": "477416",
"Score": "0",
"body": "@AJNeufeld, as far as I can tell, the same number of testcases fail as with my original solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T07:22:10.853",
"Id": "477417",
"Score": "0",
"body": "@Mast, will try"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T20:00:13.933",
"Id": "243231",
"ParentId": "243217",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243231",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T11:31:48.013",
"Id": "243217",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "How to apply Python generators to finding min and max values?"
}
|
243217
|
<p>I'm working on a Node.js chat app project using the <code>ws</code> library. I have it up and running but I'm still making improvements and adding stuff like authentication, etc. Before I get too far, I am wondering what the best functional approach to handling messages (and other events) is. For example, right now I have the following code to handle a message from the client (I cut out most of it, just keeping in one function to use as an example):</p>
<pre><code>wss.on('connection', (ws, req) => {
// Give them the funtions (uses local ws)
function handleMessage(msgJSON) {
let incMsg = {};
try {
incMsg = JSON.parse(msgJSON); // message from client
} catch {
console.error("Could not parse sent JSON");
return;
}
switch (incMsg.type) {
case "message":
ws.send("Message sent.");
// send the message to other clients:
wss.clients.forEach(client => {
// send message to all open clients but not this client
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`${client.username}: ${incMsg.message}`);
}
}
// some more cases, like for "meta"
}
}
// more functions ...
ws.on('message', message => {
handleMessage(message);
});
}
</code></pre>
<p>This strategy takes advantage of having the <code>ws</code> variable inside the inner function, but this makes the <code>wss.on('connection')</code> handler full of a lot of functions. Is it better practice to use this approach or to make a global sort of function that you then pass the client into? My alternate idea looks like this:</p>
<pre><code>function handleMessage(msgJSON, ws) { // accepts the current client
let incMsg = {};
try {
incMsg = JSON.parse(msgJSON); // message from client
} catch {
console.error("Could not parse sent JSON");
return;
}
switch (incMsg.type) {
case "message":
ws.send("Message sent.");
// send the message to other clients:
wss.clients.forEach(client => {
// send message to all open clients but not this client
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`${client.username}: ${incMsg.message}`);
}
}
break;
// some more cases, like for "meta" ...
}
}
// more functions ...
wss.on('connection', (ws, req) => {
ws.on('message', message => {
handleMessage(message, ws); // pass along the ws client
});
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T22:18:33.847",
"Id": "477659",
"Score": "0",
"body": "Is this question closed because it is too general and I should move it to Stack Overflow or is my code just bad? I omitted most of it because it's repetitive and I am looking for best practice advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T17:29:07.593",
"Id": "477723",
"Score": "0",
"body": "Did you read [the linked meta answer](https://codereview.meta.stackexchange.com/a/3652/120114) in the close reason? If that doesn't answer your question, perhaps help center pages like [_Asking\nHow do I ask a good question?_](https://codereview.stackexchange.com/help/how-to-ask) and [_What topics can I ask about here?_](https://codereview.stackexchange.com/help/on-topic) would be helpful..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-05T19:21:44.700",
"Id": "477823",
"Score": "0",
"body": "I did but I don't think my code is broken, hypothetical, or non-existent. As the [topics help page](https://codereview.stackexchange.com/help/on-topic) said, my question was about \"application of best practices and design pattern usage.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-05T20:13:12.040",
"Id": "477827",
"Score": "1",
"body": "The users who voted to close were likely deterred by comments like `// some more cases, like for \"meta\"`, and would have referred you to the partial paragraph: \"_Excerpts of large projects are fine, but if you have omitted too much, then reviewers are left imagining how your program works._\". The user that supplied an answer didn't have much context about the other code yet to be implemented or even a broad view of what the websocket application did other than showing messages. If you have more questions then please [ask on meta](https://codereview.meta.stackexchange.com/questions/ask)."
}
] |
[
{
"body": "<p>\"Before going too far\" - is the tip of the iceberg as I see it :)</p>\n\n<p>If it's just a simple lab, nothing fancy, tutorial for the sake of testing some functionality and everything should remain small and in one file \nthen ignore the rest of what I'm saying. </p>\n\n<p>Otherwise, if that is a long ongoing project, it should be production-ready and etc.., there are lots of aspects to consider so it still a hard question to answer.</p>\n\n<p>To simplify and I'm sure many would not agree with me.</p>\n\n<p>I consider a single source, a monolith chat application.</p>\n\n<p>Try to disconnect the WebSocket from the business logic and create a clear cut boundary.</p>\n\n<p>Because you want to unit test all parts of the system you should plan your code around testing - so business logic should be seeing as a black box that you can test as unit.</p>\n\n<p>Imagine that from one side of the boundary you are passing a generic message package.\nInside the boundary, the message package is broken and the real action/parameters are extracted and a function is dispatched based on these values to handle the request.</p>\n\n<p>This actually starts forming a request/response flow - that flow should have validation, use case handler, presentation handler along the way.</p>\n\n<p>your action handler should be generic and allow adding more functionality into the communication protocol, so you should use a factory pattern to create action handlers by name.</p>\n\n<p>I hope this helps</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T17:31:32.343",
"Id": "477612",
"Score": "0",
"body": "Are you saying use encapsulation with `module.exports` or something to keep the files separate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T22:01:48.060",
"Id": "477654",
"Score": "0",
"body": "1) That's not all that I said.\n2) But yes, you should use modules to break you project into multiple files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T10:51:18.357",
"Id": "243313",
"ParentId": "243220",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T14:46:08.920",
"Id": "243220",
"Score": "-2",
"Tags": [
"node.js",
"functional-programming",
"websocket"
],
"Title": "Node.js ws server: global or local functions?"
}
|
243220
|
<p>A user applies for a lease for a car and on approval, can submit the car they want to buy. The service is consumed like so in the controller one layer above:</p>
<pre><code>$application = constructApplication();
$service->sendApplication($application);
$url = $service->sendCart($application);
redirectToUrl($url);
</code></pre>
<p>Service:</p>
<pre><code><?php
class ApplicationService
{
const DEV_BASE = "localhost:8000";
/** @var string */
private $baseUrl;
/** @var string */
private $environment;
/** @var ApiWrapper */
private $api;
/** @var EntityManagerInterface */
private $em;
/** @var ShoppingCartService */
private $cartService;
/** @var ParameterBagInterface */
private $parameterBag;
/** @var SerializerInterface */
private $serializer;
/** @var UrlGeneratorInterface */
private $urlGenerator;
// dependencies injected via constructor, omitted for brevity
public function sendApplication(Application $application)
{
/** @var ApiResponse $response */
$response = $this->api->application($application);
$this->em->persist($response);
$this->em->flush();
if ($response->getHttpCode() == 400)
throw (new ValidationException())->setErrors($response->getArrayResponse());
if ($response->getHttpCode() == 500)
throw new 500ErrorException();
$this->handleApplicationOkResponse($response, $application);
}
private function handleApplicationOkResponse(ApiResponse $response, Application $application)
{
$this->validateResponse($response);
$data = $response->getArrayResponse();
$application->setApprovalId($data['approvalId'])
->setApprovalAmount($data['approvalAmount'])
->setApprovalExpirationDate(new \DateTime($data['approvalExpirationDate']))
->setCart($this->cartService->getCurrentShoppingCart());
$this->em->persist($application);
$this->em->flush();
}
private function validateResponse(ApiResponse $response)
{
if ($response->isDeclined())
throw new GenericDeclineException();
if (!$response->canApplicantBeVerified())
throw new VerificationException();
if ($response->alreadyApplied())
throw new AlreadyAppliedException();
$cart = $this->cartService->getCurrentShoppingCart();
$cartTotal = $cart->getTotal();
if ($response->getArrayResponse()['approvalAmount'] < $cartTotal) {
throw new InsufficientCreditException(sprintf(
ErrorMessages::INSUFFICIENT_CREDIT,
$response->getArrayResponse()['approvalAmount'],
$cartTotal
));
}
}
public function sendCart(Application $application)
{
$Cart = new Cart($this->parameterBag->get("_store_id"));
$Cart->setFinalizedLeaseRedirectUrl($this->getRedirectUrl())
->setFinalizedLeasePostBackUrl($this->getPostbackUrl($application));
ApplicationToCartMapper::map($application, $Cart);
AppCartToCartMapper::map($this->cartService->getCurrentShoppingCart(), $Cart);
$cartResponse = $this->api->cart($this->serializer->serialize($Cart, 'json'));
$this->em->persist($cartResponse);
$this->em->flush();
if ($cartResponse->getHttpCode() == 200)
return $this->handleCartOkResponse($cartResponse);
throw new 500ErrorException(ErrorMessages::ERROR_SUBMITTING_CART);
}
private function getRedirectUrl()
{
$route = $this->urlGenerator->generate('success');
if ($this->environment == "dev" || $this->environment == "test") {
return self::DEV_BASE.$route;
}
return $this->baseUrl.$route;
}
private function getPostbackUrl(Application $Application)
{
return $this->getRedirectUrl()."?".http_build_query([
"approvalId" => $Application->getApprovalId()
]);
}
private function handleCartOkResponse(ApiResponse $cartResponse)
{
if ($cartResponse->isDeclined())
throw new CartDeclinedException();
return $cartResponse->getRedirectUrl();
}
}
</code></pre>
<p>I have an integration test that has to mock 6 services, return stub methods, etc. This service is a nightmare to test and I want to refactor it. However, I'm unsure how to decouple the various private functions without injecting more dependencies into the service.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T17:25:45.703",
"Id": "477368",
"Score": "0",
"body": "In case we don't agree on what constitutes refactoring, here's my understanding: a series of small, safe changes to the structure of the code that do not effect its behaviour.\n\nAnd it sounds like you already have a suite of tests covering this code - and that you would end up having to refactor your tests each time you refactored your code.\n\nIs this right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T17:59:34.987",
"Id": "477369",
"Score": "0",
"body": "Yes to the refactoring question. My concern isn't so much the refactoring of the tests per se, but rather how I approached the problem in my code. My test suite for this service is a bit convoluted and I wanted to know if there was a design pattern I could use to make this code more easily testable and cleaner. I think this particular class is doing too much but I don't know how I can decouple the various parts to make testing more easy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T18:59:42.847",
"Id": "477371",
"Score": "0",
"body": "I have found that have a large convoluted test suite can be a hindrance to refactoring the code. Especially if I have lots of tests that share common setup of the classes under test - so as soon as a parameter is added to the class constructor, a load of tests need to be changed - In this case, I start by adding a test builder in my test suite to handle constructing the object under test (and performing any mocking) - all the tests then use the builder to create objects and I end up with only one place to change as I refactor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:06:22.840",
"Id": "477372",
"Score": "0",
"body": "I'd like to refactor how I am handling the business logic rather than how I'm writing the tests. I feel like if I could break this service into multiple classes, then my tests would be a lot more straightforward as a result. I'm just unsure how to do this without sticking injecting a bunch of dependencies either in the controller or the service."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:13:54.120",
"Id": "477373",
"Score": "0",
"body": "Before I start refactoring, I like to think about the end state that I am aiming for.\n\nLooking at your code example, I'd say that the two **public** functions are not particularly related to each other.\n\nWould it improve matters if you extracted `sendCart` into a new `CartService`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:19:03.680",
"Id": "477374",
"Score": "0",
"body": "I would probably aim for `Applications` with a single `send(Application $a)` method; and `Carts` with a `send(Cart $c)` and a `create(Application $a)` method that returns a new `Cart` object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:20:16.600",
"Id": "477375",
"Score": "0",
"body": "Would you just inject these services into the controller then? I am all for abstracting the class out further, however, I'll have 7+ services to inject instead of the 6 I have now. I'm wondering if there's a better pattern to handle this or if I should just be okay with injecting 7 services into a controller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:25:36.857",
"Id": "477376",
"Score": "0",
"body": "Are you using a dependency injection framework - or wiring things up manually?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:29:17.017",
"Id": "477377",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/108757/discussion-between-stewart-ritchie-and-robert-calove)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T16:18:42.897",
"Id": "243221",
"Score": "0",
"Tags": [
"php"
],
"Title": "This service submits an application to a 3rd party API and returns a URL to redirect to. It does too many things. How can I refactor it?"
}
|
243221
|
<p>I am writing a simple merge algorithm in Haskell. I wanted to add simple logging, hence am using the Writer Monad to include logging.</p>
<pre><code>type ArrayWithLogging a = WriterT [String] Identity [a]
merge :: (Show a, Ord a) => ArrayWithLogging a -> ArrayWithLogging a -> ArrayWithLogging a
merge al bl = do
a <- al
b <- bl
case (a, b) of
([], b') -> tell ["Returning " ++ show b'] >> return b'
(a', []) -> tell ["Returning " ++ show a'] >> return a'
(a'@(x:xs), b'@(y:ys)) -> if (x <= y)
then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
>> ((merge (return xs) (return b')) >>= \z -> return (x : z))
else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
>> ((merge (return a') (return ys)) >>= \z -> return (y : z))
</code></pre>
<p>I feel there are too many returns inside the monadic context. Is this style correct?</p>
|
[] |
[
{
"body": "<p>Let's start simple. First of all, your code seems fine. However, as you've noticed yourself, there's an abundance of <code>returns</code>. Several of them don't seem necessary, so let us inspect some patterns:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>((merge (return a') (return ys)) >>= \\z -> return (y : z))\n</code></pre>\n\n<p>The pattern <code>x >>= \\z -> return (f z)</code> is the same as <code>fmap f x</code>. That already reduces the number of returns by two:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type ArrayWithLogging a = WriterT [String] Identity [a]\n\nmerge :: (Show a, Ord a) => ArrayWithLogging a -> ArrayWithLogging a -> ArrayWithLogging a\nmerge al bl = do\n a <- al\n b <- bl\n case (a, b) of\n ([], b') -> tell [\"Returning \" ++ show b'] >> return b'\n (a', []) -> tell [\"Returning \" ++ show a'] >> return a'\n (a'@(x:xs), b'@(y:ys)) -> if (x <= y)\n then tell [\"Min \" ++ show x ++ \" merging \" ++ show xs ++ \" with \" ++ show b] \n >> fmap (x:) (merge (return xs) (return b'))\n else tell [\"Min \" ++ show y ++ \" merging \" ++ show a ++ \" with \" ++ show ys] \n >> fmap (y:) (merge (return a') (return ys))\n</code></pre>\n\n<p>Now, for the next step, let's get rid of the <code>WriterT</code> monad in the first two arguments. There's no reason for that, and it further removes the <code>return</code>:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a\nmerge a b = do\n case (a, b) of\n ([], b') -> tell [\"Returning \" ++ show b'] >> return b'\n (a', []) -> tell [\"Returning \" ++ show a'] >> return a'\n (a'@(x:xs), b'@(y:ys)) -> if (x <= y)\n then tell [\"Min \" ++ show x ++ \" merging \" ++ show xs ++ \" with \" ++ show b] \n >> fmap (x:) (merge xs b')\n else tell [\"Min \" ++ show y ++ \" merging \" ++ show a ++ \" with \" ++ show ys] \n >> fmap (y:) (merge a' ys)\n</code></pre>\n\n<p>We can still get the old variant by using the following <code>merge'</code>:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>merge' a1 b1 =\n a <- a1\n b <- b1\n merge a b\n</code></pre>\n\n<p>Now that we've reduced function pretty far (but didn't lose any functionality!), we can go ahead and change some indentation to make our intend more clear. Furthermore, let us also introduce a small helper called <code>message</code>:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a\nmerge a b = do\n case (a, b) of\n ([], b') -> tell [\"Returning \" ++ show b'] >> return b'\n (a', []) -> tell [\"Returning \" ++ show a'] >> return a'\n (a'@(x:xs), b'@(y:ys)) -> \n if (x <= y)\n then message x xs b >> fmap (x:) (merge xs b')\n else message y a ys >> fmap (y:) (merge a' ys)\n where\n message e ls rs = tell [\"Min \" ++ show e ++ \" merging \" ++ show ls ++ \" with \" ++ show rs]\n</code></pre>\n\n<p>OK, let's reiterate our steps:</p>\n\n<ol>\n<li>We changed <code>x >>= \\z -> (f z)</code> to <code>fmap f x</code></li>\n<li>We changed the arguments into their non-monad variant</li>\n<li>We introduced another function to keep the old behaviour (if necessary)</li>\n<li>We changed the indentation to make sure that it looks nicer.</li>\n<li>We introduced a small helper to make sure that we don't repeat ourselves.</li>\n</ol>\n\n<p>And those are all the non-opinionated (well, except the last one) changes I'd recommend to you. In my personal opinion, the function gets even a little bit nicer if we use pattern matching on the arguments:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type ArrayWithLogging a = WriterT [String] Identity [a]\n\nmerge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a\nmerge a [] = tell [\"Returning \" ++ show a] >> return a\nmerge [] b = tell [\"Returning \" ++ show b] >> return b\nmerge a@(x:xs) b@(y:ys)\n | x <= y = message x xs b >> fmap (x:) (merge xs b)\n | otherwise = message y a ys >> fmap (y:) (merge a ys)\n where\n message e ls rs = tell [\"Min \" ++ show e ++ \" merging \" ++ show ls ++ \" with \" ++ show rs]\n\nmerge' :: (Show a, Ord a) => ArrayWithLogging a-> ArrayWithLogging a-> ArrayWithLogging a\nmerge' a b = do\n a1 <- a\n b1 <- b\n merge a1 b1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T11:42:50.777",
"Id": "477437",
"Score": "0",
"body": "Beautiful! I had a follow up question. I am reading \"Haskell Programming From First Principles\", and the author says not to use Writer because its either too lazy or too strict for the problem you are solving, uses a lot of memory and we cannot retrieve the logged values till computation is complete. Is there a better alternative to Writer for logging?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T17:31:51.800",
"Id": "477613",
"Score": "0",
"body": "@RohitG Sorry, I've been away from the Haskell ecosystem for too long to give an adequate answer for a `Writer` alternative :("
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:33:36.857",
"Id": "243229",
"ParentId": "243223",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243229",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T17:27:42.117",
"Id": "243223",
"Score": "4",
"Tags": [
"haskell"
],
"Title": "Feedback on simple Merge algorithm"
}
|
243223
|
<p>I am implementing an algorithm for estimating light at the ocean surface as a function of wind (waves, surface roughness), chlorophyll, and zenith angle. I want to do this using climate projections from CMIP6 as input for the period 1950-2100 on a monthly basis. I use Python and Jupyter notebook to read global values of <em>clouds</em>, <em>chlorophyll</em>, and <em>wind</em> from <a href="https://cloud.google.com/blog/products/data-analytics/new-climate-model-data-now-google-public-datasets" rel="nofollow noreferrer">Google cloud available CMIP6 climate models</a>. </p>
<p><strong>Full code is <a href="https://github.com/trondkr/cmip6-cloud/blob/master/albedo_cmip6.ipynb" rel="nofollow noreferrer">here</a> available as Jupyter notebook.</strong></p>
<p>I use the <a href="https://pvlib-python.readthedocs.io/en/stable/" rel="nofollow noreferrer">Python library</a> <code>pvlib</code> to calculate direct and diffuse light at the ocean surface as a function of time of year, geographic location, and clouds from CMIP6 models. I use the Seferian et al. 2018 approach to calculate the albedo on estimated light from chlorophyll and waves for the same time and place. The bottle-neck in my code seems to be estimating the effects of waves and chlorophyll on light albedo in the function <code>def calculate_OSA</code>which estimates the reflection spectrally at all wavelengths 200-4000nm at 10 nm intervals. I use <code>numpy vectorized</code> to loop over all wavelengths for a given geographic grid point and I use <code>dask.delayed</code> to loop over all gridpoints. Gridpoints are 180x360 for global coverage. </p>
<pre><code>def calculate_OSA(µ_deg, uv, chl, wavelengths, refractive_indexes, alpha_chl, alpha_w, beta_w, alpha_wc, solar_energy):
if (µ_deg<0 or µ_deg>180):
µ_deg=0
µ = np.cos(np.radians(µ_deg))
# Solar zenith angle
# wind is wind at 10 m height (m/s)
σ = np.sqrt(0.003+0.00512*uv)
# Vectorize the functions
vec_calculate_direct_reflection=np.vectorize(calculate_direct_reflection)
vec_calculate_diffuse_reflection=np.vectorize(calculate_diffuse_reflection)
vec_calculate_direct_reflection_from_chl=np.vectorize(calculate_direct_reflection_from_chl)
vec_calculate_diffuse_reflection_from_chl=np.vectorize(calculate_diffuse_reflection_from_chl)
# Direct reflection
alpha_direct = vec_calculate_direct_reflection(refractive_indexes,µ,σ)
# Diffuse reflection
alpha_diffuse = vec_calculate_diffuse_reflection(refractive_indexes,σ)
# Reflection from chlorophyll and biological pigments
alpha_direct_chl = vec_calculate_direct_reflection_from_chl(wavelengths, chl, alpha_chl, alpha_w, beta_w, σ, µ, alpha_direct)
# Diffuse reflection interior of water from chlorophyll
alpha_diffuse_chl = vec_calculate_diffuse_reflection_from_chl(wavelengths, chl, alpha_chl, alpha_w, beta_w, σ, alpha_direct)
# OSA
return
</code></pre>
<p>The entire script is written as a <a href="https://github.com/trondkr/cmip6-cloud/blob/master/albedo_cmip6.ipynb" rel="nofollow noreferrer">Jupyer notebook found here</a> although it uses one <a href="https://github.com/trondkr/cmip6-cloud/tree/master/subroutines" rel="nofollow noreferrer">subroutine</a> for reading CMIP6 data and one <a href="https://github.com/trondkr/cmip6-cloud/blob/master/albedo.ipynb" rel="nofollow noreferrer">notebook for albedo calculations</a>. I know the script is long and complex but the main function that I believe could be improved is <code>def calculate_OSA</code> and the main calculate_light function. In <code>calculate_light</code> I believe I could improve on how I use <code>dask</code> and perhaps chunking, and perhaps how vectorizing the main loop in <code>calculate_light</code> could speed things up. </p>
<p>Currently, it takes 2.27 minutes to run one timestep on a mac mini with 16GB of RAM.</p>
<pre><code>%%time
def calculate_light(config_pices_obj):
selected_time=0
wavelengths, refractive_indexes, alpha_chl, alpha_w, beta_w, alpha_wc, solar_energy = albedo.setup_parameters()
startdate=datetime.datetime.now()
regional=True
create_plots=True
southern_limit_latitude=45
for key in config_pices_obj.dset_dict.keys():
var_name = key.split("_")[0]
model_name = key.split("_")[3]
if var_name=="uas":
key_v="vas"+key[3:]
key_chl="chl"+key[3:]
key_clt="clt"+key[3:]
key_sisnconc="sisnconc"+key[3:]
key_sisnthick="sisnthick"+key[3:]
key_siconc="siconc"+key[3:]
key_sithick="sithick"+key[3:]
var_name_v = key_v.split("_")[0]
model_name_v = key_v.split("_")[3]
print("=> model: {} variable name: {}".format(key, var_name))
print("=> model: {} variable name: {}".format(key_v, var_name_v))
if model_name_v==model_name:
ds_uas=config_pices_obj.dset_dict[key].isel(time=selected_time)
ds_vas=config_pices_obj.dset_dict[key_v].isel(time=selected_time)
ds_chl=config_pices_obj.dset_dict[key_chl].isel(time=selected_time)
ds_clt=config_pices_obj.dset_dict[key_clt].isel(time=selected_time)
ds_sisnconc=config_pices_obj.dset_dict[key_sisnconc].isel(time=selected_time)
ds_sisnthick=config_pices_obj.dset_dict[key_sisnthick].isel(time=selected_time)
ds_siconc=config_pices_obj.dset_dict[key_siconc].isel(time=selected_time)
ds_sithick=config_pices_obj.dset_dict[key_sithick].isel(time=selected_time)
if regional:
ds_uas=ds_uas.sel(y=slice(southern_limit_latitude,90))
ds_vas=ds_vas.sel(y=slice(southern_limit_latitude,90))
ds_chl=ds_chl.sel(y=slice(southern_limit_latitude,90))
ds_clt=ds_clt.sel(y=slice(southern_limit_latitude,90))
ds_sisnconc=ds_sisnconc.sel(y=slice(southern_limit_latitude,90))
ds_sisnthick=ds_sisnthick.sel(y=slice(southern_limit_latitude,90))
ds_siconc=ds_siconc.sel(y=slice(southern_limit_latitude,90))
ds_sithick=ds_sithick.sel(y=slice(southern_limit_latitude,90))
# Regrid to cartesian grid:
# For any Amon related variables (wind, clouds), the resolution from CMIP6 models is less than
# 1 degree longitude x latitude. To interpolate to a 1x1 degree grid we therefore first interpolate to a
# 2x2 degrees grid and then subsequently to a 1x1 degree grid.
ds_out_amon = xe.util.grid_2d(-180,180,2,southern_limit_latitude,90,2)
ds_out = xe.util.grid_2d(-180,180,1,southern_limit_latitude,90,1) #grid_global(1, 1)
dr_out_uas_amon=regrid_variable("uas",ds_uas,ds_out_amon,transpose=True).to_dataset()
dr_out_uas=regrid_variable("uas",dr_out_uas_amon,ds_out,transpose=False)
dr_out_vas_amon=regrid_variable("vas",ds_vas,ds_out_amon,transpose=True).to_dataset()
dr_out_vas=regrid_variable("vas",dr_out_vas_amon,ds_out,transpose=False)
dr_out_clt_amon=regrid_variable("clt",ds_clt,ds_out_amon,transpose=True).to_dataset()
dr_out_clt=regrid_variable("clt",dr_out_clt_amon,ds_out,transpose=False)
dr_out_chl=regrid_variable("chl",ds_chl,ds_out,transpose=False)
dr_out_sisnconc=regrid_variable("sisnconc",ds_sisnconc,ds_out,transpose=False)
dr_out_sisnthick=regrid_variable("sisnthick",ds_sisnthick,ds_out,transpose=False)
dr_out_siconc=regrid_variable("siconc",ds_siconc,ds_out,transpose=False)
dr_out_sithick=regrid_variable("sithick",ds_sithick,ds_out,transpose=False)
# Calculate scalar wind and organize the data arrays to be used for given timestep (month-year)
wind=np.sqrt(dr_out_uas**2+dr_out_vas**2).values
lat=dr_out_uas.lat.values
lon=dr_out_uas.lon.values
clt=dr_out_clt.values
chl=dr_out_chl.values
sisnconc=dr_out_sisnconc.values
sisnthick=dr_out_sisnthick.values
siconc=dr_out_siconc.values
sithick=dr_out_sithick.values
m=len(wind[:,0])
n=len(wind[0,:])
month=6
all_direct=[]
all_OSA=[]
for hour_of_day in range(12,13,1):
print("Running for hour {}".format(hour_of_day))
calc_radiation = [dask.delayed(radiation)(clt[j,:],lat[j,0],month,hour_of_day) for j in range(m)]
# https://github.com/dask/dask/issues/5464
rad = dask.compute(calc_radiation, scheduler='processes')
rads=np.asarray(rad).reshape((m, n, 3))
zr = [dask.delayed(calculate_OSA)(rads[i,j,2], wind[i,j], chl[i,j], wavelengths, refractive_indexes,
alpha_chl, alpha_w, beta_w, alpha_wc, solar_energy)
for i in range(m)
for j in range(n)]
OSA = np.asarray(dask.compute(zr)).reshape((m, n, 2))
nlevels=np.arange(0.01,0.04,0.001)
irradiance_water = (rads[:,:,0]*OSA[:,:,0]+rads[:,:,1]*OSA[:,:,1])/(OSA[:,:,0]+OSA[:,:,1])
print("Time to finish {} with mean OSA {}".format(datetime.datetime.now()-startdate,
np.mean(irradiance_water)))
# Write to file
data_array=xr.DataArray(data=irradiance_water,dims={'lat':lat,'lon':lon})
if not os.path.exists("ncfiles"):
os.mkdir("ncfiles")
data_array.to_netcdf("ncfiles/irradiance.nc")
</code></pre>
<p>Since I need to run this script for several CMIP6 models for 3 socio-economic pathways (SSP). For each model and SSP I have to calculate monthly light values for 150 years, spectrally for 140 wavelengths, on a global scale of 1x1 degrees resolution. This is CPU and memory consuming and I wonder if there are ways of improving my vectorization or better approaches for utilizing <a href="https://docs.dask.org/en/latest/delayed.html" rel="nofollow noreferrer">Dask</a>. It would be great if someone could point me in the right direction for how to improve speedup.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T16:28:57.583",
"Id": "477717",
"Score": "1",
"body": "Did you try profiling your code to see where the bottleneck is? Something that can help with profiling (and readability) is splitting your code in functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T16:40:50.617",
"Id": "477720",
"Score": "0",
"body": "@MaartenFabré Yes I did and the problem is the call `zr = [dask.delayed(calculate_OSA).... This loops over m x n grid points and then for each grid points loops over 140 wavelengths using numpy vectorized. I am hoping that the structure of my code could be changed to improve speed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T16:47:27.163",
"Id": "477721",
"Score": "1",
"body": "From the `np.vectorize` documentation: `The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.`. This will not result in a speedup. I would look into [`numba`](http://numba.pydata.org/). I've seen it give a large speedup"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T18:32:59.883",
"Id": "477728",
"Score": "0",
"body": "@MaartenFabré That was a good suggestion. I removed the use of Dask on `calculate_OSA`and instead inserted use of `numba`. That reduced time of execution from 2 min 47s to 1 min 35s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T22:37:25.317",
"Id": "477750",
"Score": "1",
"body": "Hey, I've manually removed the change in Rev 3, as your change made half of Reinderien's answer invalid. Please understand that invalidating answers goes against the Q&A format as new users that come to the post can be confused by the disconnect between your question and the answers. In the future you can [post a follow up question](https://codereview.meta.stackexchange.com/q/1763) to get more feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T23:00:28.223",
"Id": "477751",
"Score": "0",
"body": "Additionally I have edited the code so it's the same as Rev 1 but with the indentation that you added in Rev 2. The only difference is now there are no SyntaxErrors."
}
] |
[
{
"body": "<p>These will not impact performance, but are useful to address nonetheless:</p>\n\n<h2>Type hints</h2>\n\n<p>Some wild guesses here, but:</p>\n\n<pre><code>def calculate_OSA(\n µ_deg: float,\n uv: float,\n chl: float,\n wavelengths: ndarray,\n refractive_indexes: ndarray,\n alpha_chl: float,\n alpha_w: float,\n beta_w: float,\n alpha_wc: float,\n solar_energy: float,\n):\n</code></pre>\n\n<p>That said, given the high number of parameters, it may be easier to make a <code>@dataclass</code> with typed members and either pass that as an argument or make a method on it.</p>\n\n<h2>No-op return</h2>\n\n<p>Your final return can be deleted. But it's suspicious that <code>alpha_diffuse</code>, <code>alpha_direct_chl</code> and <code>alpha_diffuse_chl</code> are unused. Looking at your Github, it seems that you forgot to copy the call to <code>calculate_spectral_and_broadband_OSA</code> here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T02:59:21.577",
"Id": "477541",
"Score": "0",
"body": "Thank you! I had forgotten to add the continued call to calculate_spectral_and_broadband_OSA. I agree explicit type makes it more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T02:22:06.377",
"Id": "243294",
"ParentId": "243224",
"Score": "5"
}
},
{
"body": "<p>Looking at the jupyter notebook, I wonder if a bit of caching might help? How many of those datapoints are really unique? Something as simple as wrapping the often-called functions in a <a href=\"https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize\" rel=\"nofollow noreferrer\">memoization</a> decorator might help. Any of the calculate_ functions that take just floats are good candidates - I don't think memoizing anything that takes vectors would help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T18:53:56.477",
"Id": "477731",
"Score": "0",
"body": "Unfortunately, most of the functions vary for each calculation as they take input such as clouds, sun position, waves etc. as input which varies for each timestep"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T19:08:20.007",
"Id": "477735",
"Score": "0",
"body": "They may vary less than you think, based on measurement precision - you'd have to look at the dataset to be sure. Might be worth trying memoization anyway - shouldn't cost much time and _could_ gain you a bit. `calculate_alpha_dir`, in particular, looks ripe - it often gets called with a constant 1.34 as its initial value, so any time µ repeats in the data, memoization will save a bit of time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T20:59:38.510",
"Id": "477739",
"Score": "1",
"body": "Thanks for your help. I tested with the use of `memoized` and I am sure it would have a great improvement, but the code can not be combined with the use of `numba`. I have now tested with `numba` as suggested by @MaartenFabré and reduced the time of calculation to half of what it used to be. If you know of a way to mix these tools that would be great, but I assume I have to pick one approach."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-04T18:18:16.330",
"Id": "243389",
"ParentId": "243224",
"Score": "1"
}
},
{
"body": "<h1>Readability</h1>\n<h2>formatting</h2>\n<p>You have very long lines, and don't follow the <code>PEP8</code> suggestions everywhere. The quickest way to solve both problems in one go is to use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\"><code>black</code></a>. this can be integrated in most IDEs and in <a href=\"https://jupyterlab-code-formatter.readthedocs.io/en/latest/index.html\" rel=\"nofollow noreferrer\">jupyterlab</a></p>\n<h2>type hints</h2>\n<p>In this I have to agree with Reinderein. Now it is not clear which parameters to your function are scalars, and which are arrays. That makes it difficult for other people (this includes you in a few months of not working with this code) to understand what happens. I have a rather strict <code>mypy</code> configuration</p>\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n<p>but this has allowed me to remove some bugs that would have been hard to spot otherwise.</p>\n<p>To type a notebook, I use <a href=\"https://github.com/mwouts/jupytext\" rel=\"nofollow noreferrer\">jupytext</a> to sync the notebook with a python file, open that python file in an IDE and run a battery of linters (pylama, pydocstyle, ..), code formatters (isort and black), type check (mypy), adapt the code to the suggestions. then I go back to the notebook, and run everything to make sure the changes did not affect the calculations' correctness.</p>\n<p>This <code>.py</code> file can then also be more easily versioned.</p>\n<h1>speedup</h1>\n<p>Vectorise as much as possible. You can use <a href=\"http://numba.pydata.org/\" rel=\"nofollow noreferrer\"><code>numba</code></a> to speed up some calculations.</p>\n<p>As an outsider it is difficult to see what parameters to function tend to change, and which stay constant. <code>memoization</code> can cache intermediate results. <code>arrays</code> are not hashable, so you won't be able to use <code>functools.lru_chache</code>, but there are third party modules that can help, like <a href=\"https://joblib.readthedocs.io/en/latest/auto_examples/memory_basic_usage.html#sphx-glr-auto-examples-memory-basic-usage-py\" rel=\"nofollow noreferrer\"><code>joblib.Memory</code></a></p>\n<h1>rearrange</h1>\n<p>your <code>calculate_light</code> is too complex. It also mixes in system input (<code>datetime.datetime.now()</code>), calculations and sytem output (<code>print</code> and writing the file to disc)</p>\n<h2>logging</h2>\n<p>Instead of <code>print</code>, I would use the <code>logging</code> module. This allows you, or users of this code to later very easily switch off printing,, allows you to write it to a log file and inspect later, ...)</p>\n<h2>output</h2>\n<p>Doesn't <code>data_array.to_netcdf("ncfiles/irradiance.nc")</code> overwrite the results in every iterations.</p>\n<p>Apart from that I have 2 problems with this. You hardcode the output path in this function. If ever you want the results somewhere else, this is difficult to do.</p>\n<p>But I would not write the results in this method. I would <code>yield</code> the results, and let the caller of this method worry on what to do with them. If the results are intermediate, you don't need them afterwards, you can keep em in memory if you have enough RAM, or write them to a <a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory\" rel=\"nofollow noreferrer\">temporary directory</a></p>\n<h1>negative checks / <code>continue</code></h1>\n<p>You have some checks like <code>if var_name=="uas":</code> and <code>if model_name_v==model_name:</code>. If you reverse those checks, you save a level of indentation</p>\n<pre><code>if var_name != "uas":\n continue\n...\n</code></pre>\n<h1>DRY</h1>\n<p>You have a lot of repetition. For example the <code>key[3:]</code> If you need to change this to the 4th number, you need to think about changing all these intermediate positions. Extract that into its own variable. This will also serve as extra documentation</p>\n<h1>General</h1>\n<p>Try to implement these changes already. If you do, the code will be a lot more readable and understandable for outsiders, so we can give better advice on how to speed up certain parts, then you can post a new question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-05T08:49:56.083",
"Id": "243413",
"ParentId": "243224",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "243413",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T17:37:33.780",
"Id": "243224",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"jupyter"
],
"Title": "Increase speed of global calculations of light under climate change using Dask"
}
|
243224
|
<p>This outputs the <a href="https://en.wikipedia.org/wiki/CPUID#EAX=0:_Highest_Function_Parameter_and_Manufacturer_ID" rel="nofollow noreferrer">manufacturer string associated with your CPU using the CPUID instruction</a>. I wrote this up for a homework assignment, then found out that I didn't need to.</p>
<p>When run on my (virtual) machine, I get the following output:</p>
<pre><code>EAX: 16
EBX: 756e6547
ECX: 6c65746e
EDX: 49656e69
GenuineIntel
</code></pre>
<p>What I'd like commented on:</p>
<ul>
<li><p>I'm not super-proficient yet in bit manipulation. Originally, <code>print_register</code> had a <code>for</code> loop that iterated the <code>mask</code> directly, like</p>
<pre><code>for (int32_t mask = 0xFF;; mask <<= 8) {
</code></pre>
<p>This worked until I realized that I needed to right-shift the result of the bitwise AND, and couldn't figure out how to get the bits shifted from the <code>mask</code>. I ended up going for a less efficient solution of iterating bit-counts and creating the mask each iteration. This feels like a naïve approach though.</p></li>
<li><p>Anything else notable. I'm starting to venture into increasingly unknown territory here, so anything would help.</p></li>
</ul>
<p>Note that although inline <code>asm</code> seems to be considered bad practice to use in many cases, using it was the point of the exercise here. I know wrapper macros exist that would clean this up a bit.</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
void print_register(int32_t reg_value) {
for (int shifted = 0; shifted < 0x20; shifted += 8) {
int32_t mask = 0xFF << shifted;
int32_t matched = (reg_value & mask) >> shifted;
printf("%c", matched);
}
}
int main() {
int32_t out_eax = -1;
int32_t out_ebx = -1;
int32_t out_ecx = -1;
int32_t out_edx = -1;
int32_t leaf = 0;
asm volatile ("cpuid"
: "=a"(out_eax), // 0
"=b"(out_ebx),
"=c"(out_ecx),
"=d"(out_edx)
: "0"(leaf));
printf("EAX: %x\nEBX: %x\nECX: %x\nEDX: %x\n\n",
out_eax, out_ebx, out_ecx, out_edx);
print_register(out_ebx);
print_register(out_edx);
print_register(out_ecx);
printf("\n");
}
</code></pre>
|
[] |
[
{
"body": "<h1>Use <code>uint32_t</code></h1>\n\n<p>You have to be careful with shift operations on signed integers. In particular, right shifts on signed integers have implementation-defined behaviour, so it is hard to write portable code for it. It might work out in this case, but it is better to treat the values as unsigned integers here.</p>\n\n<h1>Bit shifting</h1>\n\n<p>While you have written a correct function to print the individual bytes of a 32-bit integer, it is a bit overkill. You can write it like so:</p>\n\n<pre><code>void print_register(uint32_t value) {\n printf(\"%c%c%c%c\",\n (int)value,\n (int)(value >> 8),\n (int)(value >> 16),\n (int)(value >> 24));\n}\n</code></pre>\n\n<p>This uses the fact that when printing a character, the value will already by truncated to 8 bits as if you would have written <code>value & 0xFF, (value >> 8) & 0xFF,</code> and so on. The cast to <code>int</code> might be necessary because the <code>%c</code> conversion expects an <code>int</code>, but <code>int32_t</code> might have a different size than an <code>int</code> on some platforms (for example, on an Arduino with an AVR CPU, <code>int</code> will be 16 bits).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T18:51:53.473",
"Id": "477370",
"Score": "0",
"body": "Thanks. Both points make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T00:49:27.470",
"Id": "477400",
"Score": "0",
"body": "Corner; `printf(\"%c%c%c%c\", value, value >> 8, value >> 16, value >> 24);` relies on `int/unsigned` is 32+ bits. As 16-bit, code is UB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T06:35:57.073",
"Id": "477411",
"Score": "0",
"body": "@chux-ReinstateMonica: you mean the arguments should be `(int)value, (int)(value >> 8), ...`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T13:19:31.120",
"Id": "477442",
"Score": "0",
"body": "... or `(int8_t) value, ....` as those will re-promote to `int` and is closer to the concept of what code does here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T18:37:46.320",
"Id": "243226",
"ParentId": "243225",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T18:25:56.440",
"Id": "243225",
"Score": "2",
"Tags": [
"c"
],
"Title": "Outputting the Manufacturer ID of a processor using CPUID with inline ASM"
}
|
243225
|
<p>I recently have been very interested in custom allocators, so I decided to make the very basic (this should be faster than <code>malloc</code>) bump allocator. Here is my code in C:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/mman.h>
#include <unistd.h>
#define KB(size) ((size_t) size * 1024)
#define MB(size) (KB(size) * 1024)
#define GB(size) (MB(size) * 1024)
#define HEAP_SIZE GB(1)
typedef intptr_t word_t;
void* free_ptr = NULL;
void* start_ptr;
word_t end_ptr;
void init() {
free_ptr = mmap(NULL, HEAP_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (free_ptr == MAP_FAILED) {
printf("unable to map memory\n");
abort();
}
start_ptr = free_ptr;
end_ptr = (word_t) start_ptr + HEAP_SIZE;
}
void* bump_alloc(size_t size) {
void* new_ptr = free_ptr;
free_ptr = (char*) free_ptr + size;
return new_ptr;
}
void free_all_mem() {
munmap(start_ptr, HEAP_SIZE);
}
int main() {
init();
int* x = (int*) bump_alloc(sizeof(int));
assert(x != NULL);
*x = 10000;
printf("x: %d\n", *x);
free_all_mem();
}
</code></pre>
<p>This is my first custom allocator so could I get some tips on optimization, etc.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T08:58:51.587",
"Id": "477426",
"Score": "1",
"body": "`GB(10*1024)` etc will overflow. Don't use function-like macros for these, use absolute numeric constants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T10:59:27.487",
"Id": "477434",
"Score": "3",
"body": "[Don't cast `malloc` returns](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) (applies to your malloc as well)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T14:29:05.300",
"Id": "477448",
"Score": "1",
"body": "@Lundin Are you concerned `GB(10*1024)` overflows 32-bit math? Overwise `(size_t)10* 1024 * 1024 *1024` looks OK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T19:47:40.240",
"Id": "477490",
"Score": "1",
"body": "If you are concerned with efficiency, shouldn't bump allocators always allocate memory downwards instead of upwards?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T19:55:44.300",
"Id": "477492",
"Score": "0",
"body": "@GlenYates -- Ah, yes-- I seem to have forgot that! Good catch! ty!"
}
] |
[
{
"body": "<h2>Unit pedantry</h2>\n\n<p>Technically those are <code>KiB</code> and <code>MiB</code> since they're multiples of 1024 and not 1000.</p>\n\n<h2>Empty arguments</h2>\n\n<p>This was a difficult lesson for me to drill into my head, but in C empty arguments() and <code>(void)</code> arguments are not the same thing, particularly for function declarations. Technically for definitions they are, but I don't like relying on inconsistent rules and recommend that <code>(void)</code> be used uniformly - even though you only have definitions without declarations.\n<code>(void)</code> is safer and more explicit. <code>()</code> is closer to meaning \"an unspecified number of arguments\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T20:10:14.747",
"Id": "477495",
"Score": "1",
"body": "Except that nobody (to within rounding error) uses KiB and MiB. :-) The definitions are clear visible; I don't think this is a big point of confusion. In fact, as Lundin suggested in the comments, it would be even clearer to eschew the use of the macros and just multiply inline. Agreed completely with your second point, although an empty parameter list isn't just \"closer\" to meaning that. It does mean *exactly* that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T14:08:03.917",
"Id": "477586",
"Score": "0",
"body": "@CodyGray if Jonathan Leffler uses it, everybody must use it. Are you better than him? No way. No possibility."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:45:13.363",
"Id": "243236",
"ParentId": "243228",
"Score": "7"
}
},
{
"body": "<blockquote>\n <p>could I get some tips on optimization, etc.</p>\n</blockquote>\n\n<p><strong>Alignment loss</strong></p>\n\n<p><code>free_ptr = (char*) free_ptr + size;</code> simply increases the next available allocation to so many bytes later. This differs from <code>malloc()</code> whose allocations meets all possible system alignment needs. </p>\n\n<p>Either document that <code>bump_alloc()</code> does not provide aligned allocations or change code to do so.</p>\n\n<p><strong>Error messages</strong></p>\n\n<p>I'd expect the error message to go out <code>stderr</code> - yet your call.</p>\n\n<pre><code>// printf(\"unable to map memory\\n\");\nfprintf(stderr, \"Unable to map memory\\n\");\n</code></pre>\n\n<p><strong>Missing include</strong></p>\n\n<p><code>intptr_t</code> is define in <code><stdint.h></code>. Best to include that rather than rely of a hidden inclusion.</p>\n\n<p><strong>Good type math</strong></p>\n\n<p>The below avoids <a href=\"https://stackoverflow.com/a/40637622/2410359\"><code>int</code> overflow</a>. </p>\n\n<pre><code>#define KB(size) ((size_t) size * 1024)\n</code></pre>\n\n<p>Better code would <code>()</code> each macro parameter.</p>\n\n<pre><code>#define KB(size) ((size_t) (size) * 1024)\n</code></pre>\n\n<p>Yet I'd recommend rather than type-casting, which may narrow the math, allow gentle widening. The below multiplication will occur with the wider of <code>size_t</code> and the type of <code>size</code>.</p>\n\n<pre><code>#define KB(size) ((size_t) 1024 * (size))\n</code></pre>\n\n<p><strong>Unneeded cast, simplify</strong></p>\n\n<p>Casting not needed going from <code>void *</code> to an object pointer. Size to the de-referenced type. Easier to code right, review and maintain.</p>\n\n<pre><code>// int* x = (int*) bump_alloc(sizeof(int));\nint* x = bump_alloc(sizeof *x);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T22:45:58.083",
"Id": "243237",
"ParentId": "243228",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "243237",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T19:28:59.570",
"Id": "243228",
"Score": "11",
"Tags": [
"performance",
"c",
"mmap"
],
"Title": "C - Fast & simple bump allocator"
}
|
243228
|
<p>I have an array of colors for my app to choose from. My goal was to have the app cycle through the array of colors, apply it to my object, and reset to the beginning once each color has been used. This is simple enough to implement, but I am looking to see if it's possible to clean it up slightly. The one complication I have is that I am trying to prevent duplicate colors. </p>
<p>E.g. If I choose to use the size of the array of the object that has the color affected - when an item (or multiple) is deleted and a new one is added, it might have a duplicate color as the previous card leading to a visual design that I don't want. </p>
<p>To prevent this I decided to make a new counter variable that counts each time a new card is created, regardless of deletions. I feel like there might be a more elegant solution that I am not thinking of so any feedback or alternative approaches would be very appreciated!</p>
<p>All of the necessary code can be seen here:</p>
<pre><code>class BrowseHabitsActivity : Activity() {
private lateinit var recyclerView: RecyclerView
private lateinit var addHabitButton: FloatingActionButton
private val habits: ArrayList<Habit> = Habit.createHabitList(25)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_browse_habits)
recyclerView = findViewById(R.id.rvHabits)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = BrowseHabitsAdapter(habits)
var cardCount = 0
addHabitButton = findViewById(R.id.addHabitButton)
addHabitButton.setOnClickListener {
habits.add(Habit("New Habit", 1234, chooseCardColor(cardCount++)))
(recyclerView.adapter as BrowseHabitsAdapter).notifyItemInserted(habits.size)
}
}
private fun chooseCardColor(cardCount: Int): Int {
val colors = resources.getIntArray(R.array.cardColors)
return colors[cardCount % colors.size]
}
}<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The code you've written seems to be reasonably elegant (to me at least!). You can make this slightly simpler by:</p>\n<ul>\n<li>storing the colors array rather than getting each time (I've used a <code>by lazy</code> but you could use a <code>nullable var</code> or a <code>lateinit var</code> if you prefer)</li>\n<li>Store the cardCount elsewhere rather than locally and incrementing it each time</li>\n</ul>\n<p>I've put an example of these changes below. I would strongly recommend extracting out the color logic into its own class in order to make it more testable, reusable and better separation of concern.</p>\n<pre><code>private val colors: IntArray by lazy{\n resources.getIntArray(R.array.cardColors)\n}\n\nprivate val cardCount = 0\n\nprivate fun getCardColor(): Int {\n val color = colors[cardCount % colors.size] \n cardCount.inc()\n return color\n} \n</code></pre>\n<p>Also, you could use the <a href=\"https://developer.android.com/reference/androidx/annotation/ColorInt\" rel=\"nofollow noreferrer\"><code>@ColorInt</code></a> annotation to make it clear that the Int being returned is a ColorInt.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:16:48.897",
"Id": "481242",
"Score": "0",
"body": "Thanks! :) Took a break from this project for awhile but I'll be going back to it soon and I will definitely use your recommendations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:08:23.443",
"Id": "245056",
"ParentId": "243232",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T20:03:43.907",
"Id": "243232",
"Score": "1",
"Tags": [
"android",
"kotlin"
],
"Title": "Cycle through an array of available colors repeatedly"
}
|
243232
|
<p>First time posting and first <em>real</em> Python program that I use fairly frequently. I needed a way to pull a large amount of containers, re-tag them, save them (docker save) and clean up the recently pulled containers.</p>
<p>I did this pretty easily with bash, though depending on the container and depending how many containers I quickly did not like how slow it was and wanted a way to do it faster. </p>
<p>I am looking to make any improvements possible, it works, and it works well (at least I think). I tend to always come across more Pythonic ways to do things and would love the additional feedback.</p>
<p>Couple things that I am currently tracking:</p>
<ul>
<li>I need docstrings (I know, small program, but I want to learn to do it
<em>right</em>)</li>
<li>I tossed in the <code>if __name__ == "__main__":</code>, and if I am being honest, I am not confident I did that right.</li>
<li>I know, I am <em>terrible</em> at naming functions and variables :(</li>
</ul>
<pre><code>#!/usr/bin/env python3
import sys
import os
from os import path
import concurrent.futures # https://docs.python.org/3/library/concurrent.futures.html
import docker # https://docker-py.readthedocs.io/en/stable/
cli = docker.APIClient(base_url="unix://var/run/docker.sock")
current_dir = os.getcwd()
repository = sys.argv[2]
tar_dir = os.path.join(current_dir, "move")
if path.exists(tar_dir) is not True:
os.mkdir(tar_dir)
def the_whole_shebang(image):
img_t = image.split(":")
img = img_t[0].strip()
t = img_t[1].strip()
image = f"{img}:{t}"
print(f"Pulling, retagging, saving and rmi'ing: {image}")
# Pulls the container
cli.pull(image)
# Tags the container with the new tag
cli.tag(image, f"{repository}/{img}", t)
new_image_name = f"{img}{t}.tar"
im = cli.get_image(image)
with open(os.path.join(tar_dir, new_image_name), "wb+") as f:
for chunk in im:
f.write(chunk)
# Deletes all downloaded images
cli.remove_image(image)
cli.remove_image(f"{repository}/{image}")
if __name__ == "__main__":
with concurrent.futures.ProcessPoolExecutor() as executor:
f = open(sys.argv[1], "r")
lines = f.readlines()
executor.map(the_whole_shebang, lines)
</code></pre>
<p>Anyways, I assume there are many things that I can do better, I would love to have any input so that I can improve and learn.</p>
<p>Thank you!</p>
|
[] |
[
{
"body": "<h2>Global variables</h2>\n\n<p>These:</p>\n\n<pre><code>cli = docker.APIClient(base_url=\"unix://var/run/docker.sock\")\ncurrent_dir = os.getcwd()\nrepository = sys.argv[2]\ntar_dir = os.path.join(current_dir, \"move\")\n</code></pre>\n\n<p>probably shouldn't live in the global namespace. Move them to a function, and feed them into other functions or class instances via arguments.</p>\n\n<h2>Command-line arguments</h2>\n\n<p>Use the built-in <code>argparse</code> library, if not something fancier like <code>Click</code>, rather than direct use of <code>sys.argv</code>. It will allow nicer help generation, etc.</p>\n\n<h2>Boolean comparison</h2>\n\n<pre><code>if path.exists(tar_dir) is not True:\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>if not path.exists(tar_dir):\n</code></pre>\n\n<h2>Pathlib</h2>\n\n<p>Use it; it's nice! For instance, if <code>tar_dir</code> is an instance of <code>Path</code>, then you can replace the above with <code>if not tar_dir.exists()</code>.</p>\n\n<p>It should also be preferred over manual path concatenation like <code>f\"{repository}/{img}\"</code>; i.e.</p>\n\n<pre><code>Path(repository) / img\n</code></pre>\n\n<p>there are other instances that should also use <code>pathlib</code>; for instance rather than manually appending <code>.tar</code>, use <code>with_suffix</code>.</p>\n\n<h2>Split unpack</h2>\n\n<pre><code>img_t = image.split(\":\")\nimg = img_t[0].strip()\nt = img_t[1].strip()\nimage = f\"{img}:{t}\"\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>image, t = image.split(':')\nimage_filename = f'{image.strip()}:{t.strip()}'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T02:14:10.323",
"Id": "243293",
"ParentId": "243239",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "243293",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T00:13:04.447",
"Id": "243239",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Pull, Tag, Save, Delete Multiple Docker Containers"
}
|
243239
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.