body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I've written a simple web scraper in Python. As it is my first venture in Python, I'd like to ask for a code review from more experienced coders. All input is welcome.</p>
<p>A little bit of background:</p>
<p>I'm a huge fan of video games. In Japan, there is a company called Media Create which tracks all sales of games and consoles and releases them weekly (in Japanese language). Another site (www.gematsu.com) translates those charts and releases them weekly on their website. My script fetches the data and saves it to a text file.</p>
<p>The script should run <em>as-is</em>, but it is dependent on a text file of the previous week existing in <em>script-location</em>/data.</p>
<p>The name of the script needs to be something like <code>media-create-sales-11-26-18-12-2-18.txt</code> (replacing the start and end dates with any dates other than the dates of the most recently released data).</p>
<p>I am not affiliated with Media Create or Gematsu and this script serves no commercial purpose.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import datetime
import glob
import os
def getLatestFilename():
list_of_files = glob.glob('data/*')
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
def parseUrl(dateString):
dateString = dateString.split('-')
lastdateString = str("-".join(dateString[6:9])).split('.')[0]
lastdate_object = datetime.datetime.strptime(lastdateString, "%m-%d-%y")
current_startdatetime_object = lastdate_object + datetime.timedelta(days=1)
current_enddatetime_object = lastdate_object + datetime.timedelta(days=7)
cur_startDateString = current_startdatetime_object.strftime("%m-%d-%y").lstrip("0").replace("0", "")
cur_endDateString = current_enddatetime_object.strftime("%m-%d-%y").lstrip("0").replace("0", "")
return (cur_startDateString + '-' + cur_endDateString)
def getUrl(filename):
curIntervalString = parseUrl(filename)
now = datetime.datetime.now()
url = list()
url.append("https://gematsu.com/")
url.append(str(now.year))
url.append('/')
url.append(str(now.month))
url.append('/')
url.append('media-create-sales-')
url.append(curIntervalString)
return url
def fetchContentForUrl(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
outputfile = open("data/media" + url.split('media')[1] + ".txt", "w")
outputfile.write(url + '\n' + '\n')
content = soup.find(class_='entry')
gameCharts = content.findNext('ol')
gameEntries = gameCharts.find_all('li')
for idx,entry in enumerate(gameEntries,start=1):
outputfile.write(str(idx) + "." + entry.get_text() + "\n")
print ('\n')
consoleCharts = gameCharts.find_next_sibling("ol")
consoleEntries = consoleCharts.find_all('li')
for entry in consoleEntries:
outputfile.write(entry.get_text() + "\n")
def main():
latestFilename = getLatestFilename()
print (latestFilename)
url = ''.join(getUrl(latestFilename))
print (url)
fetchContentForUrl(url)
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>This is a very good attempt for the first Python venture!</p>\n\n<hr>\n\n<p>Here is what I would consider improving:</p>\n\n<ul>\n<li><p><strong>stylistic / <code>PEP8</code></strong></p>\n\n<ul>\n<li><em>naming</em>. In Python, it is recommended to use <a href=\"https://www.python.org/dev/peps/pep-0008/#id36\" rel=\"nofollow noreferrer\"><code>lower_case_with_underscores</code> notation</a>. Your function and variable names are inconsistent and there is a mix of styles - e.g. <code>cur_startDateString</code> follows both <code>camelCase</code> and <code>lower_case_with_underscores</code></li>\n<li><em>the user of blank lines</em>. In Python, it is recommended to have <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">2 blank lines between top-level blocks of the code</a> and have an extra new-line at the end of the script</li>\n<li><p><em>the use of whitespaces</em>. Watch for whitespaces after commas in expressions, e.g.:</p>\n\n<pre><code>for idx,entry in enumerate(gameEntries,start=1):\n ^ ^\n</code></pre></li>\n<li><p><em>import grouping and order</em>. See <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Imports section of the PEP8</a></p></li>\n<li>parenthesis around the <code>return</code> value are redundant</li>\n<li>consider adding docstrings explaining what your functions are about. For instance, <code>getLatestFilename</code> would benefit from a note about how does it define which file is the latest. And, <code>parseUrl</code> is not really easy to understand just by reading the code</li>\n<li>if you are using Python 3.5+, consider adding <a href=\"https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5\">Type Hints</a></li>\n</ul></li>\n<li><p><strong>Design and modularity</strong></p>\n\n<ul>\n<li>it is a good thing that you tried to logically separate scraping from parsing</li>\n<li>I would also separate parsing and dumping the results into a CSV file</li>\n</ul></li>\n<li><p><strong>HTML Parsing</strong></p>\n\n<ul>\n<li>if performance is a concern, consider switching from <code>html.parser</code> to <code>lxml</code> - see <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser\" rel=\"nofollow noreferrer\">\"Installing a Parser\"</a> section of the documentation</li>\n<li><p>you could also improve performance of the parsing stage by using a <code>SoupStrainer</code> which allows you to parse the desired part of the HTML tree in the first place:</p>\n\n<pre><code>from bs4 import BeautifulSoup, SoupStrainer\n\nparse_only = SoupStrainer(class_='entry')\nsoup = BeautifulSoup(page.text, 'lxml', parse_only=parse_only)\n</code></pre></li>\n<li><p><code>.findNext()</code> is deprecated in favour of <code>.find_next()</code></p></li>\n</ul></li>\n<li><p><strong>Other</strong></p>\n\n<ul>\n<li><p><code>getUrl()</code> method feels a little bit overcomplicated and you can definitely improve its readability and simplify it at the same time. Plus, I would make it return the URL as a string and not as a list to avoid any extra external code needed to make it a string. If you are using Python 3.6+, f-strings would be handy:</p>\n\n<pre><code>def get_url(filename: str) -> str:\n \"\"\"Constructs a complete URL based on the filename and current date.\"\"\"\n current_interval = parse_url(filename)\n\n now = datetime.datetime.now()\n\n return f\"https://gematsu.com/{now.year}/{now.month}/media-create-sales-{current_interval}\"\n</code></pre>\n\n<p>Having the complete URL string with placeholders helps to see what the end result might look like.</p></li>\n</ul></li>\n</ul>\n\n<p>Note that most of the PEP8 violations mentioned above could be caught by running a linter (like <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\"><code>flake8</code></a>, or <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\"><code>pylint</code></a>) against your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T02:47:40.117",
"Id": "209581",
"ParentId": "209575",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T01:11:09.163",
"Id": "209575",
"Score": "2",
"Tags": [
"python",
"web-scraping"
],
"Title": "A simple web scraper"
} | 209575 |
<p>I created a graph to show the change in the percentage of questions answered over time and <a href="https://codereview.stackexchange.com/q/196439/120114">the first version</a> fetched data from chat transcripts using PHP. The sub-domain I have registered for my webspace doesn't offer HTTPS so the calls to <code>file_get_contents()</code> would fail when run there. Because of this, I started looking at alternatives.</p>
<p>I looked at using other scripting languages and found that github offered <a href="https://pages.github.com/" rel="nofollow noreferrer">github pages</a> and noted that it was secure but didn't allow any server-side scripting. So tried using client-side JavaScript with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="nofollow noreferrer"><code>fetch</code> API</a>. Initially there were CORS issues and after a little research I found <a href="https://medium.com/netscape/hacking-it-out-when-cors-wont-let-you-be-great-35f6206cc646" rel="nofollow noreferrer">this post</a>, which mentioned a Heroku page that would act as a proxy. I used the proxy to get the data, and I have been interested in the new ES-8 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" rel="nofollow noreferrer">async functions</a> and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await" rel="nofollow noreferrer"><code>await</code></a> operator so I utilized those.</p>
<p>How does the code look? What would you change about it?</p>
<p>Can you help make the chart results go up by providing a good answer? And remember to vote on any answer that is helpful.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const url = 'https://chat.stackexchange.com/search?q=%22RELOAD!+There+are%22&user=125580&room=8595&pagesize=150';
const pUrl = 'https://cors-escape.herokuapp.com/' + url;
const chartOptions = {
title: {
display: true,
text: 'Answered percentage in recent months'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Percentage'
}
}]
}
};
const dataset = {
label: 'Answered Percentage',
backgroundColor: window.chartColors.red,
borderColor: window.chartColors.red,
fill: false
};
async function getGraphData() {
const loadingImage = document.getElementById('loading');
try {
const response = await fetch(pUrl);
const container = document.createElement('div');
container.innerHTML = await response.text();
const timestamps = container.getElementsByClassName('timestamp');
const contents = container.getElementsByClassName('content');
const labels = [],
data = [];
if (contents.length === timestamps.length) {
let i = 0;
for (contentElement of contents) {
const matches = contentElement.innerHTML.match(/\d{2}.\d{4}/);
if (matches.length) {
data.unshift(matches[0]);
labels.unshift(timestamps[i++].innerHTML);
}
}
if (data.length) {
loadingImage.style.display = 'none';
drawChart(data, labels);
}
}
} catch (err) {
loadingImage.parentNode.innerHTML = 'Error loading data';
}
}
document.addEventListener('DOMContentLoaded', getGraphData)
const drawChart = (data, labels) => {
Chart.defaults.global.legend.display = false;
const config = {
type: 'line',
data: {
labels,
datasets: [Object.assign(dataset, {data})]
},
options: chartOptions
};
const ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//www.chartjs.org/dist/2.7.2/Chart.bundle.js"></script>
<script src="//www.chartjs.org/samples/latest/utils.js"></script>
<h1>
Graph of Answered Question Percentage on Code Review SE
</h1>
<div style="width:75%;">
<canvas id="canvas"></canvas>
<img src="https://loading.io/spinners/bars/index.progress-bar-facebook-loader.gif" id="loading" />
</div></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h1>An error and a logic problem.</h1>\n<p>The code would fail if you ran it as a module or in strict mode due to undefined variable. There is also a problem when parsing the HTML, if there is missing data the timestamps and the percentages will go out of sync because you fail to increase <code>i</code>.</p>\n<p>Async functions handle errors by assigning them to the returned promise catch callback. You have wrapped a <code>try catch</code> around code that may throw unrelated development error which you would see as "Error loading data" and not differentiate a legit error from source/logic error.</p>\n<p>It is unclear what you intend to happen when fetched data is bad (eg 404 page) asd this will not throw error and you ignore such errors without giving any feedback.</p>\n<p>A clearer separation of roles with fetch and parsing as functions rather than the single async function.</p>\n<p>Data is also all over the place with the graph settings declared at the top and then more in the function that creates the graph.</p>\n<h2>General points</h2>\n<ul>\n<li><p>You use an undeclared variable <code>contentElement</code> in <code>getGraphData</code></p>\n</li>\n<li><p>Why the <code>if (matches.length) {</code> Will that ever happen??? And if it does doesn't that mean that <code>i</code> as index to <code>timeStamps</code> no longer matches the the for loop position?</p>\n</li>\n<li><p><code>window</code> is the default object and not needed for direct references. If you are defining globals, clearly define them in the global scope. If they are external use comments to indicate that they external globals.</p>\n</li>\n<li><p>Why assign to a variable that is never used? <code>window.myLine = new Chart(</code></p>\n</li>\n<li><p>Keep it DRY. Axis object could be a function, also several other parts can be reduced using functions.</p>\n</li>\n<li><p>Reduce number of lines of source code by avoiding single use variable declarations.</p>\n</li>\n<li><p>Avoid using <code>innerHTML</code> when possible as it is much slower than <code>textContent</code>.</p>\n</li>\n<li><p>Use direct element id referencing when you are in control of content.</p>\n</li>\n<li><p>Only wrap the relevant code in try catch. ECMAScript 2018 lets you drop the error object after the catch token. Better yet separate the async part of the function and use promise catch function.</p>\n</li>\n<li><p>Use the shortest form when possible. Eg you used <code>datasets: [Object.assign(dataset, {data})]</code> that can be <code>datasets: [{...dataset, data}]</code></p>\n</li>\n<li><p>Why the <code>if (contents.length === timestamps.length)</code> and no warning if the data is bad?.</p>\n</li>\n<li><p>Double/same line open <code>[{</code>, <code>({</code>, or <code>[[</code>... etc should be followed by single indent and matching double close. See rewrite.</p>\n</li>\n<li><p>Redundant repeated X axis label content <code>" 12:00 AM"</code> can be removed</p>\n</li>\n<li><p>Graph heading and page heading are different. Maybe assign the graph heading from the page heading??</p>\n</li>\n</ul>\n<h2>Possible rewrite</h2>\n<p>This rewrite reduces the number of lines and encapsulates most of the requirements within a single function reducing the global namespace pollution.</p>\n<p>Data vetting was a little unclear so just added that to the graphing function to show a warning if no data found.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\n// uses chartColors defined in ???.js\n\ndocument.addEventListener(\"DOMContentLoaded\", displayAnswerRate);\n\nfunction displayAnswerRate() {\n const CORS_PROXY = \"https://cors-escape.herokuapp.com/\"; \n const url = \"https://chat.stackexchange.com/search?q=%22RELOAD!+There+are%22&user=125580&room=8595&pagesize=150\";\n \n const showError = message => {\n errorEl.style.display = \"block\";\n errorEl.textContent = message;\n }\n getDataURL(url)\n .then(parseDataAndChart)\n .catch(() => {\n loading.style.display = \"none\";\n showError(\"Error loading data\");\n });\n\n async function getDataURL(url) { return (await fetch(CORS_PROXY + url)).text() } \n\n function parseDataAndChart(markup){ \n const elsByClass = cName => [...html.querySelectorAll(\".\" + cName)].reverse();\n const html = document.createElement('div');\n html.innerHTML = markup;\n drawChart(\n elsByClass(\"content\").map(el => el.textContent.split(\"(\")[1].split(\"%\")[0]),\n elsByClass(\"timestamp\").map(el => el.textContent.replace(\" 12:00 AM\",\"\"))\n );\n loading.style.display = \"none\";\n }\n\n function drawChart(data, labels) {\n const axis = name => [{display: true, scaleLabel: {display: true, labelString: name}}]; \n if (data.length > 0) {\n Chart.defaults.global.legend.display = false;\n new Chart(canvas.getContext('2d'), {\n type: 'line',\n data: {\n labels,\n datasets: [{\n label: 'Answered Percentage',\n backgroundColor: chartColors.red,\n borderColor: chartColors.red,\n data,\n fill: false\n }]\n },\n options: {\n title: {display: true, text: heading.textContent},\n scales: { xAxes: axis(\"Date\"), yAxes: axis(\"Percentage\") }\n }\n });\n } else {\n showError(\"No data found???\");\n }\n } \n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-family: Arial, \"Helvetica Neue\", Helvetica, sans-serif;\n}\nh2 {\n text-align : center;\n}\n#errorEl { \n display : none;\n color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"//www.chartjs.org/dist/2.7.2/Chart.bundle.js\"></script>\n<script src=\"//www.chartjs.org/samples/latest/utils.js\"></script>\n\n<div style=\"width:75%;\">\n <h2 id=\"heading\">Answered percentage in recent months</h2>\n <div id=\"errorEl\"></div>\n <canvas id=\"canvas\"></canvas>\n \n <img src=\"https://loading.io/spinners/bars/index.progress-bar-facebook-loader.gif\" id=\"loading\" />\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": "2018-12-13T21:15:21.943",
"Id": "209639",
"ParentId": "209576",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209639",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T01:24:30.730",
"Id": "209576",
"Score": "2",
"Tags": [
"javascript",
"html5",
"ajax",
"async-await",
"ecmascript-8"
],
"Title": "Chart of answered CR posts percentages over time - Part 2"
} | 209576 |
<p>ECMAScript 2017 (also known as ECMAScript 8) is the <a href="https://www.ecma-international.org/ecma-262/8.0/index.html" rel="nofollow noreferrer">2017 specification</a> for the <a href="/questions/tagged/ecmascript" class="post-tag" title="show questions tagged 'ecmascript'" rel="tag">ecmascript</a> language. ES2017 adds a few updates to the language and its implementation in major JavaScript engines is in progress but quite good in the recent releases of ones that release often.</p>
<p>The <a href="/questions/tagged/ecmascript-8" class="post-tag" title="show questions tagged 'ecmascript-8'" rel="tag">ecmascript-8</a> tag or its alias <a href="/questions/tagged/es2017" class="post-tag" title="show questions tagged 'es2017'" rel="tag">es2017</a> should be used when your question covers one of the ES2017/ES8 features.</p>
<hr>
<h3>Features</h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" rel="nofollow noreferrer">Async functions</a></li>
<li>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await" rel="nofollow noreferrer"><code>await</code> operator</a></li>
</ul>
<hr>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T01:28:32.403",
"Id": "209577",
"Score": "0",
"Tags": null,
"Title": null
} | 209577 |
The 2017 version of the ECMAScript specification, now a standard (ECMAScript 2017). Only use this tag where the question specifically relates to new features or technical changes provided in ECMAScript 2017. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T01:28:32.403",
"Id": "209578",
"Score": "0",
"Tags": null,
"Title": null
} | 209578 |
<p>I've been using <a href="https://flask-jwt-extended.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>flask-jwt-extended</code></a> for my application and one of the problems I had was logging a session out and making sure the token is not usable anymore.</p>
<p>I've based my solution on the <a href="https://flask-jwt-extended.readthedocs.io/en/latest/blacklist_and_token_revoking.html" rel="nofollow noreferrer">Blacklist and Token Revoking documentation page</a> with a custom <code>RevokedToken</code> model:</p>
<pre><code>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class RevokedToken(db.Model):
"""
Model is used as a storage to keep invalid/revoked tokens.
Currently used for log out functionality.
"""
__tablename__ = 'revoked_tokens'
id = db.Column(db.Integer, primary_key=True)
jti = db.Column(db.String(120))
@classmethod
def is_jti_blacklisted(cls, jti):
query = cls.query.filter_by(jti=jti).first()
return bool(query)
</code></pre>
<p>Logout resource:</p>
<pre><code>class LogoutResource(Resource):
@jwt_required
def post(self):
jti = get_raw_jwt()['jti']
# invalidate access token
revoked_token = RevokedToken(jti=jti)
session.add(revoked_token)
session.commit()
return {}, 200
</code></pre>
<p>And the <code>token_in_blacklist_loader()</code> <code>jwt</code> function:</p>
<pre><code>from flask_jwt_extended import JWTManager
jwt = JWTManager(app)
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
jti = decrypted_token['jti']
return models.RevokedToken.is_jti_blacklisted(jti)
</code></pre>
<p>This looks straightforward enough, but, as we are talking about authentication, I thought I would ask if anyone sees any flaws or potential improvements to this approach?</p>
| [] | [
{
"body": "<p>As far as I can tell, </p>\n\n<ul>\n<li>This looks like a pretty solid implementation of blacklisting.</li>\n<li>I can't see any obvious code mistakes.</li>\n</ul>\n\n<p>I you are worried about security it can be wise to check the <a href=\"https://www.owasp.org/index.php/JSON_Web_Token_(JWT)_Cheat_Sheet_for_Java\" rel=\"nofollow noreferrer\">corresponding OWASP documentation</a></p>\n\n<p><em>This is for Java, but the security considerations should be similar</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T08:33:10.527",
"Id": "209595",
"ParentId": "209582",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T03:13:09.143",
"Id": "209582",
"Score": "1",
"Tags": [
"python",
"authentication",
"flask",
"jwt"
],
"Title": "Expiring JWT tokens in Flask"
} | 209582 |
<p>I have a large data frame that I want to merge with another dataset. In order to do so I need to get the names of individuals into a certain format. The function below converts the name in 'column' to the desired format (mostly) and stores it in <code>newColumn</code>.</p>
<p>My question is, is there a better (faster and/or more pythonic) way to do this?</p>
<p>The main aim is to transform full names into surname and initials, such as:</p>
<ul>
<li>Novak Djokovic = Djokovic N.</li>
<li>Jo-Wilfred Tsonga = Tsonga J.W.</li>
<li>Victor Estrella Burgos = Estrella Burgos V.</li>
<li>Juan Martin Del Potro = Del Potro J.M.</li>
</ul>
<p></p>
<pre><code>def convertNames(df,column, newColumn):
df[newColumn] = 'none'
for player in df[column]:
names = player.split(' ')
if len(names) == 2:
if (len(names[0].split('-')) > 1):
newName = names[1]+' '+names[0].split('-')[0][0]+'.'+names[0].split('-')[1][0]+'.'
else:
newName = names[1]+' '+names[0][0]+'.'
elif len(names) == 3:
newName = names[1]+' '+names[2]+' '+names[0][0]+'.'
else:
newName = names[2]+' '+names[3]+' '+names[0][0]+'.'+names[1][0]+'.'
df[newColumn][df[column] == player] = newName
return df
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T04:10:46.287",
"Id": "405080",
"Score": "4",
"body": "Your code doesn’t match your sample output. The code converts “Victor Estrella Burgos” into “Estrella Burgos V.”, not “Burgos V.E.” Which represents the desired behaviour: the sample output or the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T08:34:08.697",
"Id": "405090",
"Score": "1",
"body": "What about `Alex De Minaur`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T04:33:19.497",
"Id": "405210",
"Score": "0",
"body": "@AJNeufeld, Sorry, that was me just trying to copy and past everything. You are right. The sample code produces the sample code produces the correct output. I have corrected the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T04:34:42.183",
"Id": "405211",
"Score": "0",
"body": "@Stefan, the desired result for Alex De Minaur is De Minaur A."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T11:03:24.807",
"Id": "405239",
"Score": "0",
"body": "Still inconsistent. Sample code produces “Estrella Burgos V.”, not “Burgos Estrella V.”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T18:48:12.450",
"Id": "405288",
"Score": "1",
"body": "What about `John Patrick Smith`? Any rule converting `Alex De Minaur` to `De Minaur A.` will convert `John Patrick Smith` to `Patrick Smith J.`. Spaniards mostly have two surnames, others mostly one. Any simple approach will fail."
}
] | [
{
"body": "<p>You are doing way too much <code>split()</code>-ing. You split on ‘-‘, and if you find the length of the split is greater than 1, you split on the ‘-‘ twice more, to get the first and the second part of the hyphenated name. Split once, and save the result in a list, and access the list elements!</p>\n\n<p>You are doing too much in <code>convertNames()</code>. It would be better to create a <code>convertName()</code> method, which just processes the player name into the desired form. Then you could call that method from <code>convertNames()</code>.</p>\n\n<pre><code>def convertName(player):\n names = player.split(' ')\n\n if len(names) == 2:\n names[0:1] = names[0].split('-', 1)\n\n surname = min(len(names)-1, 2)\n\n return ' '.join(names[surname:]) + ' ' + ''.join(name[0]+'.' for name in names[:surname])\n\n# Test data\nfor player in ('Novak Djorkovic', 'Jo-Wilferd Tsonga', 'Victor Estrella Burgos', 'Juan Martin Del Potro'):\n print(player, ':', convertName(player))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T03:54:22.370",
"Id": "209585",
"ParentId": "209583",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209585",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T03:19:34.243",
"Id": "209583",
"Score": "2",
"Tags": [
"python",
"strings"
],
"Title": "Transforming full names to surname and initial"
} | 209583 |
<p>I was wondering how efficient my code is creating custom indexOf for strings in JavaScript using regex instead of looping with a <code>for</code> statement the whole way in most solution I find and I believe this got <span class="math-container">\$O(1)\$</span> since no loop is needed.</p>
<p>The idea is to use regex that put either the key or any list of word that is not key; this way I know that the value will be either in <code>arr[0]</code> or <code>arr[1]</code>. I also check using regex earlier whether the key exist in the value or not; this way I created non-looping indexOf with regex. This way I just return <code>0</code> if the key is in <code>arr[0]</code> or <code>arr[0].length</code> if it not in <code>arr[0]</code>.</p>
<pre><code>function findindex(value,key){
let regex = RegExp( "((?!"+key+").)+|"+key , "ig" ); //regex for separating keys in the array
let regex2 = RegExp(key,"ig"); // regex for checking if the key is exist in the value or not
//first check before looping whether key is available in array or not
if( !regex2.test(value) || value.length < key.length ){
return -1;
}
let arr = value.match(regex); //make an array
//alternative with condition statement
return ( arr[0] === key || regex2.test(arr[0]) ) ? 0 : arr[0].length;
}
</code></pre>
| [] | [
{
"body": "<p>Too sad, it's not O(1).\nThere is a cost for: </p>\n\n<ul>\n<li>Constructing the regex into a DFA</li>\n<li>Calling <code>test()</code> or <code>match()</code> on the regex for the value</li>\n</ul>\n\n<p>Complexities:</p>\n\n<ul>\n<li>A well implemented regex construction will be <code>O(M)</code> where M is the length of the key.</li>\n<li>While test/matching it afterwards will be <code>O(N)</code> where N is the length of the value. (best case, e.g. regexes with backtracking can result in horrible complexities) </li>\n</ul>\n\n<p>So a couple of improvements can be:</p>\n\n<ul>\n<li>if the key is always the same. Construct the regex for the key only once.</li>\n<li>first start with comparing the length of the value and key before calling the more expensive test()-match() methods.</li>\n<li><p>apart from that, the idea of a regex is ok but I don't know if it's the most understandable way of writing an indexOf.</p></li>\n<li><p>Reference: <a href=\"https://stackoverflow.com/questions/5892115/whats-the-time-complexity-of-average-regex-algorithms\">Regex Complexities on SO</a></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:24:25.350",
"Id": "405100",
"Score": "0",
"body": "I do agree that this not a really understandable way of writing indexOf, just though I could make it faster by reducing the loop. As I just learned regex I though it's a cheap way to avoid looping to get a value. never thought calling test() and match() is really expensive. thanks a lot for the suggestion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:47:24.777",
"Id": "405113",
"Score": "0",
"body": "I wouldn't say \"really expensive\", in general it will be quite similar to a normal loop. And far better than a naïve implementation using 2 loops with worst case O(NM). You can have a look at some popular string search algorithms like \"Rabin-Karp\", \"Boyer-Moore\" or my favourite \"Knuth-Morris-Pratt\" that is construction a DFA and using it which can give you more insights in this topic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T09:36:12.383",
"Id": "209597",
"ParentId": "209594",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T08:28:26.683",
"Id": "209594",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"interview-questions",
"regex",
"ecmascript-6"
],
"Title": "Custom indexOf for strings javascript with regex"
} | 209594 |
<p>This is a programming exercise from chapter 8 of a C learning book by K N King. The program should prompt a user for a message, and return it after translating it to B1ff speak. e.g A->4, b->8 etc</p>
<p>The program works as asked in the exercise, however how can I create a more efficient declaration of the <code>message[]</code> array? Currently it is initialized to size <code>N</code> which is defined as 100 (large enough for most messages), instead of the size of the message from the user.</p>
<pre><code>#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <ctype.h>
#define N 100
int main(int argc, const char * argv[]) {
//Initialize
char message[N] = {' '};
char ch;
int i = 0, j = 0, k= 0;
//Prompt user for message
printf("Enter a message: ");
//Get message and put each character into an array
while((ch = getchar()) != '\n'){
ch = toupper(ch);
message[i] = ch;
i++;
}
//Print the B1ff speak converting characters
printf("In B1FF-speak: ");
for(k = 0; k<i; k++){
switch(message[k]){
case 's':
printf("5");
break;
case 'O':
printf("0");
break;
case 'I':
printf("1");
break;
case 'E':
printf("3");
break;
case 'B':
printf("8");
break;
case 'A':
printf("4");
break;
default:
printf("%c", message[k]);
break;
}
}
//Print 10 or so exclamation marks and be a citizen
printf("!!!!!!!!!!!!!!\n");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:54:02.927",
"Id": "405130",
"Score": "2",
"body": "What made you think `getchar` gets a char? :) It doesn't do that, `ch = getchar()` actually needs to be `int ch`. These old junk stdio functions aren't exactly intuitive to use and dangerous in general."
}
] | [
{
"body": "<p>Unused: we don't use <code>j</code>, and we don't need to include <code><stdbool.h></code>, <code><stdlib.h></code> or <code><time.h></code>.</p>\n<p>We have two loops - one that reads input into <code>message[]</code> and one that converts and outputs the content of <code>message[]</code>. We can avoid the storage by combining the two loops into one:</p>\n<pre><code>while ((ch = getchar()) != '\\n') {\n ch = toupper(ch);\n\n switch (ch) {\n /* ... */\n }\n</code></pre>\n<p>There's a couple of fixes needed above. Firstly, we need to check that <code>ch</code> is not <code>EOF</code>, or we'll loop indefinitely if the input stream is closed before the first newline. <code>ch</code> needs to be an <code>int</code> value here, as the distinction between a character and end-of-file is lost when we narrow to <code>char</code>.</p>\n<p>Secondly, <code>ch</code> holds values of a (possibly signed) char, but <code>toupper()</code> (like all the <code><ctype.h></code> functions) works on an <code>int</code> representation of <code>unsigned char</code> value. Fixing those gives us:</p>\n<pre><code>int ch;\nwhile ((ch = getchar()) != '\\n' && ch != EOF) {\n ch = toupper((unsigned char)ch);\n</code></pre>\n<hr />\n<p>Instead of the <code>switch</code>, we might consider a table-driven approach. That would work something like this:</p>\n<pre><code>char conversions[UCHAR_MAX];\n/* identity mapping for most chars */\nfor (unsigned i = 0; i < sizeof conversions; ++i) {\n conversions[i] = (char)i;\n}\n/* exceptions */\nconversions['S'] = '5';\nconversions['O'] = '0';\nconversions['I'] = '1';\nconversions['E'] = '3';\nconversions['B'] = '8';\nconversions['A'] = '4';\n\n\nint ch;\nwhile ((ch = getchar()) != '\\n' && ch != EOF) {\n putchar(conversions[toupper(ch)]);\n}\n</code></pre>\n<hr />\n<p>Finally, <code>puts()</code> is simpler than <code>printf()</code> for simple strings ending in newline, and we don't need to return 0 from <code>main()</code>.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <ctype.h>\n#include <limits.h>\n#include <stdio.h>\n\nint main(void)\n{\n char conversions[UCHAR_MAX];\n /* identity mapping for most chars */\n for (unsigned i = 0; i < sizeof conversions; ++i) {\n conversions[i] = (char)i;\n }\n /* exceptions */\n conversions['S'] = '5';\n conversions['O'] = '0';\n conversions['I'] = '1';\n conversions['E'] = '3';\n conversions['B'] = '8';\n conversions['A'] = '4';\n\n\n printf("Enter a message: ");\n\n int ch;\n while ((ch = getchar()) != '\\n' && ch != EOF) {\n putchar(conversions[toupper(ch)]);\n }\n\n // Finish the sentence\n puts("!!!!!!!!!!!!!!");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T05:28:33.383",
"Id": "405325",
"Score": "0",
"body": "It says not to add comments like this, however thank you very much! You pointed out many insightful ways I can improve my code. Just curious, is it better practice to use `//` or `/* */` for commenting sections?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-09T09:34:58.313",
"Id": "408302",
"Score": "0",
"body": "I don't think there's an objectively-better comment syntax. It's a personal preference - but be aware that the `//` form was introduced in C99, and older code will use only `/* */`. I'd advise being consistent if possible (unlike my modified code - oops!)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:30:43.143",
"Id": "209606",
"ParentId": "209601",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>however how can I create a more efficient declaration of the message[] array?</p>\n</blockquote>\n\n<p>This is an efficient declaration. </p>\n\n<p>Given that the array is \"large enough\". A statically allocated array is the fastest option. Though it is of course good practice to check that the input never goes out of bounds of the array.</p>\n\n<p>Trying to save a couple of hundred bytes of memory by implementing some sort of dynamic allocation <code>realloc</code> scheme isn't sensible. It would slow down the program significantly.</p>\n\n<p>There exists two kinds of computer systems. Systems where dynamic heap allocation makes sense, such as a PC, and systems where it doesn't, such as microcontroller embedded systems. </p>\n\n<p>In case of the former, you have plenty of RAM and you don't need to worry about 100 bytes here or there on the stack. In case of the latter, you could be short on RAM, but neither dynamic memory allocation nor user input from stdin make sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:54:27.107",
"Id": "209613",
"ParentId": "209601",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209613",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:30:50.500",
"Id": "209601",
"Score": "1",
"Tags": [
"beginner",
"c"
],
"Title": "\"B1ff filter\" reads and returns message"
} | 209601 |
<p>I have question regarding best practices. I've decided instead having config inside either app.config or xml file to have my config file inside SQLite file database. This config will contain basic information for specific class. Config will be managed from SQLite database browser. My question is is it fine assuming that config information is in single db file to have still call to it directly from for instance Email class (this is just example class i want to use the same way in other classes required default config information)? I know it's db call but in fact it's also call to config default values therefore i assume it's fine to have it like this. Nevertheless would like to get your opinion. Look below:</p>
<pre><code>public class Email : IEmail
{
public string To { get; private set; }
public string Cc { get; private set; }
public string Body { get; private set; }
public string SmtpIp { get; private set; }
public string Subject { get; private set; }
public string LogPath { get; private set; }
public string FromName { get; private set; }
public string Signature { get; private set; }
public string FromAddress { get; private set; }
public void ResolveConfig(string memberEntryName = "Default")
{
IDbManager dbMansdager = new DbManager(ConnectionDbType.SqlLite);
LogPath = dbMansdager.GetDataTable("SELECT Value FROM Config WHERE Member='Path'", CommandType.Text).Rows[0][0].ToString();
To = dbMansdager.GetDataTable($"SELECT To FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
Body = dbMansdager.GetDataTable($"SELECT Body FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
SmtpIp = dbMansdager.GetDataTable($"SELECT SmtpIp FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
Subject = dbMansdager.GetDataTable($"SELECT Subject FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
Signature = dbMansdager.GetDataTable($"SELECT Signature FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
FromName = dbMansdager.GetDataTable($"SELECT FromName FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
FromAddress = dbMansdager.GetDataTable($"SELECT FromAddress FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
Cc = dbMansdager.GetDataTable($"SELECT Cc FROM Email WHERE Member='{memberEntryName}'", CommandType.Text).Rows[0][0].ToString();
}
/// <summary>
/// Default values comming from database from Email table nevertheless you can override some values in method arguments
/// memberEntryName is entry in Email table that information for particural email will be used default set is default entry
/// If new entry is needed it has to be added to Email table and Member's name has to be specified in method argument
/// To and CC in table if more email required all has to be separated by ;
/// </summary>
/// <param name="memberEntryName"></param>
/// <param name="customBody"></param>
/// <param name="customSubject"></param>
/// <param name="attachementsPaths"></param>
/// <returns></returns>
public async Task Send(string memberEntryName = "Default", string customBody = "", string customSubject = "", IEnumerable<string> attachementsPaths = null)
{
ResolveConfig(memberEntryName);
try
{
using (var smtp = new SmtpClient(SmtpIp))
{
smtp.UseDefaultCredentials = true;
using (var mail = new MailMessage())
{
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
mail.From = new MailAddress(FromAddress, FromName);
if (To != null && !string.IsNullOrEmpty(To))
{
var mails = To.Split(';');
foreach (var m in mails)
mail.To.Add(m);
}
if (Cc != null && !string.IsNullOrEmpty(Cc))
{
var mails = Cc.Split(';');
foreach (var m in mails)
mail.CC.Add(m);
}
mail.Subject = !string.IsNullOrEmpty(customSubject) ? customSubject : Subject;
mail.Body = !string.IsNullOrEmpty(customBody) ? customBody : Body;
if (attachementsPaths != null)
{
foreach (var attachment in attachementsPaths)
{
if (File.Exists(attachment))
mail.Attachments.Add(new Attachment(attachment));
}
}
await smtp.SendMailAsync(mail);
}
}
}
catch (Exception ex) { throw new NotSupportedException(ex.ToString()); }
finally
{
if (attachementsPaths != null)
{
foreach (var attachment in attachementsPaths)
{
if (File.Exists(attachment))
File.Delete(attachment);
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:21:30.703",
"Id": "405117",
"Score": "1",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:22:40.583",
"Id": "405118",
"Score": "0",
"body": "@Heslacher ahh sorry forgive .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:23:44.053",
"Id": "405119",
"Score": "0",
"body": "no problem. You are new here so you couldn't know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:25:19.383",
"Id": "405121",
"Score": "0",
"body": "@Heslacher thanks, can you respond to my question at the top to your answer please"
}
] | [
{
"body": "<blockquote>\n<pre><code>IDbManager dbMansdager = new DbManager(ConnectionDbType.SqlLite); \n</code></pre>\n</blockquote>\n\n<p>Small typo here. It should be named <code>dbManager</code>should't it? </p>\n\n<ul>\n<li><p><code>ResolveConfig()</code> is a <code>public</code> method hence you should validate the passed methodparameter. One could pass <code>null</code> and your queries would throw an exception. </p></li>\n<li><p><code>Send()</code> you are using <code>using</code> statements for disposable objects which is good but you could do better by stacking the <code>using</code>s like so </p>\n\n<pre><code>using (var smtp = new SmtpClient(SmtpIp))\nusing (var mail = new MailMessage())\n{\n smtp.UseDefaultCredentials = true;\n\n\n} \n</code></pre>\n\n<p>This will save one level of indentation. </p></li>\n<li><p>It seems you expect that <code>To</code> may be <code>null</code> or empty. You can simplify the check by only calling <code>string.IsNullOrEmpty()</code> or much better <code>string.IsNullOrWhiteSpace()</code>. But wait, if <code>To</code> is either <code>null</code> or empty calling <code>SendMailAsync()</code> would throw an <code>ArgumentNullException</code>. </p></li>\n<li><code>Finally</code> this could be a problem because the <code>finally</code> will be executed no matter if an exception had been thrown or not. Meaning the attachment will be deleted. This will happen e.g the smtp-server is down as well. Is this the desired behaviour ? </li>\n<li>Omitting braces <code>{}</code> whould be avoided althought they might be optional. Omitting braces can lead to hidden and therefor hard to find bugs. \n\n<hr></li>\n</ul>\n\n<blockquote>\n <p>Is it fine approach to call config like this generally in that example\n class? </p>\n</blockquote>\n\n<p>If you want to make quick adjustments to some config this isn't the way you should go because changing e.g a xml-file just needs an editor but changing some db entries adds a lot of overhead. It also depends on the use case. If you consider to make mass-mailings then the db version would be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:23:47.780",
"Id": "405120",
"Score": "0",
"body": "Yes that was a typo and yes ResolveConfig should be private because if user want to override some staff he can do it from Send method by specifying memberEntryName. I also agree with all other propositions however main question is: Is it fine approach to call config like this generally in that example class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:50:21.797",
"Id": "405126",
"Score": "0",
"body": "Can you answer please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:54:31.857",
"Id": "405127",
"Score": "0",
"body": "See my edit (at the end)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:22:03.207",
"Id": "405140",
"Score": "0",
"body": "but it is in fact db version. I would say modifying it is very same as changing in xml file. Nevertheles is comparable. Hpowever looking at designing model itself it's acceptable right? I mean putting callers like i did by IDbManager interface it's fine from the class itself rigth? The same way as i would call xml file. I am asking only about the approach itself calling from Email for xml config file or db config file. Hope you get my point"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:24:14.013",
"Id": "405141",
"Score": "0",
"body": "You may better ask this question at https://softwareengineering.stackexchange.com/ but make sure to read their help-center first."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:11:04.370",
"Id": "209604",
"ParentId": "209602",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:45:11.840",
"Id": "209602",
"Score": "1",
"Tags": [
"c#",
"email",
"sqlite",
"configuration"
],
"Title": "Database as a config and class structure to call it"
} | 209602 |
<p>So, I'm building export/import CSV helper. I have some performance issues in the code below. it takes me to parse CSV of 25,000 rows at 7 seconds.
If someone can help, it will be awesome! </p>
<pre><code>public System.IO.Stream ParseContent<T>(IEnumerable<T> entities) where T : class
{
if (entities == null)
throw new ArgumentException(nameof(entities), "List accepted is empty.");
Type type = entities.First().GetType();
PropertyInfo[] properties = type.GetProperties();
string headers = GenerateTemplate(properties);
//No headers accepted - cannot export the content
if (string.IsNullOrEmpty(headers))
return null;
string contentToExport = $"{headers}{NewLineDelimiter}";
foreach (T entity in entities)
{
if (entity == null)
continue;
string template = this.ExportLine(entity, properties);
contentToExport += $"{template}{NewLineDelimiter}";
}
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(contentToExport);
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes);
return memoryStream;
}
private string ExportLine<T>(T entity, PropertyInfo[] properties) where T : class
{
if (entity == null || properties == null)
return string.Empty;
string template = "";
foreach (PropertyInfo property in properties)
{
string value = null;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type underlyingType = property.PropertyType.GetGenericArguments()[0];
if (underlyingType.IsValueType || underlyingType == typeof(string))
{
System.Collections.IEnumerable list = (System.Collections.IEnumerable)property.GetValue(entity);
value = string.Join(EnumerableValueDelimiter, list.Cast<string>());
}
}
else if (property.PropertyType.IsClass && (!property.PropertyType.IsPrimitive && !property.PropertyType.IsEnum) && property.PropertyType != typeof(string))
{
//Object type. need to be serialized
object propertyValue = property.GetValue(entity);
if (propertyValue != null)
value = JsonConvert.SerializeObject(propertyValue);
else
value = "null";
}
else
{
value = property.GetValue(entity)?.ToString();
}
if (string.IsNullOrEmpty(value))
value = "";
template += $"{value}{LineValuesDelimiter}";
}
//Removing the last delimiter at the row.
if (template.Length > 0)
template = template.Remove(template.Length - 1, 1);
return template;
}
</code></pre>
| [] | [
{
"body": "<p><code>ParseContent()</code> </p>\n\n<ul>\n<li><code>Type type = entities.First().GetType();</code> can throw an exception if <code>entities</code> doesn't contain any items. I may be wrong but you could use the <code>T</code> as well like <code>Type type = typeof(T);</code>.</li>\n<li>If <code>entities</code> is <code>null</code> an <code>ArgumentNullException</code> should be thrown instead of an <code>ArgumentException</code>. </li>\n<li>The <code>foreach</code> could be simplified and you should use a <code>StringBuilder</code> instead of concating strings in a loop. Thats because strings are immutable and for each <code>contentToExport += $\"{template}{NewLineDelimiter}\";</code> you create a new string object. </li>\n<li>If the right hand side of an assignment makes the type clear one should use <code>var</code> instead of the concrete type. </li>\n<li>Omitting braces <code>{}</code> althought they might be optional can lead to hidden and therefor hard to find bugs. I would like to encourage you to always use them. </li>\n<li>Having a variable <code>memoryStream</code> doesn't buy you anything. Just return the new memorystream. </li>\n</ul>\n\n<p>Applying these points will lead to </p>\n\n<pre><code>public System.IO.Stream ParseContent<T>(IEnumerable<T> entities) where T : class\n{\n if (entities == null)\n {\n throw new ArgumentNullException(nameof(entities), \"List accepted is empty.\");\n }\n if (!entities.Any())\n {\n //assuming thats the desired behaviour\n return null;\n }\n\n Type type = typeof(T);\n\n PropertyInfo[] properties = type.GetProperties();\n\n string headers = GenerateTemplate(properties);\n\n //No headers accepted - cannot export the content\n if (string.IsNullOrEmpty(headers))\n {\n return null;\n }\n\n StringBuilder contentToExport = new StringBuilder( $\"{headers}{NewLineDelimiter}\");\n\n foreach (T entity in entities.Where(e=>e!=null))\n {\n\n string template = this.ExportLine(entity, properties);\n contentToExport.Append($\"{template}{NewLineDelimiter}\");\n }\n\n byte[] bytes = System.Text.Encoding.UTF8.GetBytes(contentToExport.ToString());\n\n return new System.IO.MemoryStream(bytes);\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:56:05.857",
"Id": "405131",
"Score": "0",
"body": "I knew strings are immutables, didn't think that it would cause that performance.\nThank you very much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:13:55.067",
"Id": "405136",
"Score": "1",
"body": "Some small additions: It's generally not advised to enumerate an `IEnumerable` more than once, it may not support multiple enumerations or it could be backed by an expensive database query. `typeof(T)` and `entities.First().GetType()` can be different types and not every element in `entities` is guaranteed to be the same type as `entities.First().GetType()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:01:52.793",
"Id": "209610",
"ParentId": "209607",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:30:52.240",
"Id": "209607",
"Score": "2",
"Tags": [
"c#",
"csv",
"reflection"
],
"Title": "Reflection optimization for export CSV on large scale"
} | 209607 |
<p>As in classical bin packing problem, this is an algorithm that optimises the number of bins of a certain size used to hold a list of objects of varying size.</p>
<p>In my variant I also work with a second constraint that is the bins must hold a certain minimum size in them. For example :
<code>max_pm = 10, min_pm = 5 ;</code> If we input <code>[8,2,3]</code> then the packing <code>[[8, 2], [3]]</code> is not valid. Some problems also don't hold any solution in which case we should return <code>None</code>.</p>
<p>I implemented this simply as a post-processing solution validation, is there any more optimised way to do it ? I need an optimised solution if it exists, heuristics are not good which is why I've choosed a recursive branching approach.</p>
<p>Items here are size 4 tuples, last value is weight.</p>
<pre><code>from copy import deepcopy
def bin_pack(items, min_pm, max_pm, current_packing=None, solution=None):
if current_packing is None:
current_packing = []
if not items:
# Stop conditions: we have no item to fit in packages
if solution is None or len(current_packing) < solution:
# If our solution doesn't respect min_pm, it's not returned, return best known solution instead
for pack in current_packing:
if sum((item[3] for item in pack)) < min_pm:
return solution
# Solutions must be cleanly copied because we pop and append in current_packing
return deepcopy(current_packing)
return solution
# We iterate by poping items and inserting in a list of list of items
item = items.pop()
# Try to fit in current packages
for pack in current_packing:
if sum((item[3] for item in pack)) + item[3] <= max_pm:
pack.append(item)
solution = bin_pack(items, min_pm, max_pm, current_packing, solution)
pack.remove(item)
# Try to make a new package
if solution is None or len(solution) > len(current_packing):
current_packing.append([item])
solution = bin_pack(items, min_pm, max_pm, current_packing, solution)
current_packing.remove([item])
items.insert(-1, item)
return solution
</code></pre>
<p>Execution example:</p>
<pre><code>print bin_pack([(0,0,0,1), (0,0,0,5), (0,0,0,2), (0,0,0,6)], 3, 6)
# displays [[(0, 0, 0, 6)], [(0, 0, 0, 2), (0, 0, 0, 1)], [(0, 0, 0, 5)]]
print bin_pack([(0,0,0,1), (0,0,0,5), (0,0,0,2), (0,0,0,6)], 4, 6)
# displays None
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:02:41.280",
"Id": "405143",
"Score": "1",
"body": "When I try your program I hit an error `TypeError: '<' not supported between instances of 'int' and 'list'` on line `if solution is None or len(current_packing) < solution:` . Should that be `len(solution) > len(current_packing)` instead?Or could you please give an example of how to run the function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:29:59.930",
"Id": "405146",
"Score": "0",
"body": "Another thing, `items = [(0,0,0,11)];print(bin_pack(items, 5, 10))` prints `[[(0,0,0,11)]] ` but I expected `None`, shouldn't the `max_pm` condition be checked also when you try to make a new package?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:56:09.633",
"Id": "405151",
"Score": "0",
"body": "Ah, that is true some inputs might not be handled, I only had items below max_pm. I'll add an running example as well."
}
] | [
{
"body": "<h3>1. Bugs</h3>\n\n<ol>\n<li><p>If any item has weight greater than <code>max_pm</code>, no solution is possible but the code may return a solution anyway. It would be more robust to raise an exception in this case.</p></li>\n<li><p>This condition is wrong:</p>\n\n<pre><code>len(current_packing) < solution\n</code></pre>\n\n<p>Here <code>len(current_packing)</code> is an <code>int</code> but <code>solution</code> is a <code>list</code> so in Python 2.7, where you can compare any two values even if they have different types, this always evaluates to <code>True</code>. This can cause the code to return a worse solution when a better solution was discovered earlier. The condition should be:</p>\n\n<pre><code>len(current_packing) < len(solution)\n</code></pre>\n\n<p>In Python 3 you couldn't have missed this bug because you would have got an exception:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>TypeError: '<' not supported between instances of 'int' and 'list'\n</code></pre></li>\n</ol>\n\n<h3>2. Review</h3>\n\n<ol>\n<li><p>The use of the <code>print</code> statement suggests that you are using Python 2, but this version will <a href=\"https://www.python.org/dev/peps/pep-0373/#update\" rel=\"nofollow noreferrer\">no longer be supported from 2020</a>. It would be better to use Python 3. Even if you are stuck on Python 2 for some reason, it would be better to use <code>from __future__ import print_function</code> so that your code can more easily be ported to Python 3 when the time comes.</p></li>\n<li><p>There's no docstring. What does <code>bin_pack</code> do? What arguments does it take? What does it return?</p></li>\n<li><p>Returning <code>None</code> when there is no solution is risky—the caller might forget to check. It is more robust to handle an exceptional case by raising an exception.</p></li>\n<li><p>Some of the names could be improved—since this is a <em>bin</em> packing, the thing being packed ought to be called <code>bin</code> rather than <code>pack</code>. The names <code>min_pm</code> and <code>max_pm</code> are quite obscure: what does <code>pm</code> stand for? Names like <code>min_weight</code> or <code>min_cost</code> or <code>min_size</code> would be clearer.</p></li>\n<li><p>Getting the weight of the items using <code>item[3]</code> is not very flexible—it forces the caller to represent items in a particular way. It would be better for <code>bin_pack</code> to take a function that can be applied to the item to get its weight. Then the caller could pass <a href=\"https://docs.python.org/3/library/operator.html#operator.itemgetter\" rel=\"nofollow noreferrer\"><code>operator.itemgetter(3)</code></a>.</p></li>\n<li><p>Calling the <code>remove</code> method on a list is not efficient: this method searches along the list to find the first matching item, which takes time proportional to the length of the list. In all the cases where the code uses <code>remove</code>, in fact the item to be removed is the last item in the list and so the <code>pop</code> method could be used instead.</p></li>\n<li><p>It's not clear why the code restores the item at the next-to-last position in the list of items:</p>\n\n<pre><code>items.insert(-1, item)\n</code></pre>\n\n<p>Since the item came from the last position in the list, using <code>items.pop()</code>, I would have expected it to be put back at the last position (not the next-to-last) by calling <code>items.append(item)</code>.</p></li>\n<li><p>There are some cases where the same information has to be recomputed over and over again: (i) before returning a solution, the code have to check whether all bins have the minimum weight. But this fact could be remembered as part of the current state of the algorithm, so that it doesn't have to be recomputed all the time. (ii) Before deciding whether an item can go into a bin, the code adds up the weights of all the items in the bin. But again, the current weight of each bin could be remembered.</p></li>\n<li><p>Making a deep copy of the solution ends up copying out the contents of the items as well as their organization into the solution. This is unnecessary and possibly harmful—in some use cases the items may not be copyable. A two-level copy is all that's needed here.</p></li>\n<li><p>A bunch of difficulties arise because <code>bin_pack</code> is recursive: (i) passing <code>min_pm</code> and <code>max_pm</code> through all the recursive calls even though these never change; (ii) initializing <code>current_packing</code> on every recursive call even though this ought to only need to be done once; (iii) the best solution has to be pass and returned through all the recursive calls. These difficulties could all be avoided by defining a local function that does the recursion. See below for how you might do this.</p></li>\n<li><p>There is an easy small speedup if you prune branches of the search that can't get you a better solution. See the revised code for how to do this.</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>def bin_pack(items, weight, min_weight, max_weight):\n \"\"\"Pack items (an iterable) into as few bins as possible, subject to\n the constraint that each bin must have total weight between\n min_weight and max_weight inclusive.\n\n Second argument is a function taking an item and returning its\n weight.\n\n If there is no packing satisfying the constraints, raise\n ValueError.\n\n \"\"\"\n items = [(item, weight(item)) for item in items]\n if any(w > max_weight for _, w in items):\n raise ValueError(\"No packing satisfying maximum weight constraint\")\n bins = [] # current packing in the search\n bin_weights = [] # total weight of items in each bin\n best = [None, float('inf')] # [best packing so far, number of bins]\n def pack():\n if best[1] <= len(bins):\n return # Prune search here since we can't improve on best.\n if items:\n item, w = item_w = items.pop()\n for i in range(len(bins)):\n bin_weights[i] += w\n if bin_weights[i] <= max_weight:\n bins[i].append(item)\n pack()\n bins[i].pop()\n bin_weights[i] -= w\n if len(bins) + 1 < best[1]:\n bins.append([item])\n bin_weights.append(w)\n pack()\n bin_weights.pop()\n bins.pop()\n items.append(item_w)\n elif all(w >= min_weight for w in bin_weights):\n best[:] = [[bin[:] for bin in bins], len(bins)]\n pack()\n if best[0] is None:\n raise ValueError(\"No packing satisfying minimum weight constraint\")\n return best[0]\n</code></pre>\n\n<p>Because this needs to run in Python 2.7, I had to make <code>best</code> into a list so that it can be updated from inside the locally defined function <code>pack</code>. In Python 3 we'd have two variables:</p>\n\n<pre><code>best = None\nbest_bins = float('inf')\n</code></pre>\n\n<p>and then inside <code>pack</code> we could declare these as nonlocal variables:</p>\n\n<pre><code>nonlocal best, best_bins\n</code></pre>\n\n<p>and just assign to them like any other variables. But this doesn't work in Python 2.7 because there's no equivalent of the <code>nonlocal</code> statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T17:26:01.297",
"Id": "209630",
"ParentId": "209608",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "209630",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:40:13.603",
"Id": "209608",
"Score": "3",
"Tags": [
"python",
"python-2.x"
],
"Title": "Bin packing variant"
} | 209608 |
<p>I'm required to perform a slight conversion on a string which contains html.</p>
<p>The conversion should transform <code>a</code> elements such that they become <code>span</code> elements. The conversion should also place the <code>href</code> attribute from the original <code>a</code> element into the span.</p>
<p>I have what I think is a working solution, but the code feels overcomplicated. I had hoped this may be possible with relatively little code, so I was wondering if anyone could suggest ways to make this code neater.</p>
<p>Browser compatibility is not an issue, as this will be transpiled by babel.</p>
<p>Here's what I have:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const testHtml = `
<p>This is a test paragraph</p>
<a style="font-weight: bold;" href="http://www.google.co.uk">Google is here</a>
<a style="font-weight: bold;" href="http://www.msn.co.uk">Msn is here</a>
<h2>This is a heading</h2>
`
const splitByLinkEnds = html => {
const split = html.split('</a>')
const allButLast = split.slice(0, -1)
const last = split.slice(-1)[0]
return [
...allButLast.map(x => `${x}</a>`),
last
]
}
const splitByLinks = html => {
const split = html.split('<a');
const [
first,
...result
] = split
const withReaddedOpeningTags = [
first,
...result.map(x => `<a${x}`)
]
return withReaddedOpeningTags
.reduce((prev, curr) => [
...prev,
curr.indexOf('<a') > -1 ?
splitByLinkEnds(curr) : curr
], []).flat()
}
const transformLinkToTextOnly = linkHtml => {
const linkHref = linkHtml
.match('href="[^"]*"')[0]
.replace('href="', '')
.replace('"', '')
const htmlWithSpan = linkHtml
.replace('<a', '<span')
.replace('</a>', '')
return `${htmlWithSpan} (${linkHref})</span>`
}
const transformLinksToTextOnly = html =>
splitByLinks(html)
.map(x => x.indexOf('<a') > - 1 ?
transformLinkToTextOnly(x) : x
).join('')
const result = transformLinksToTextOnly(testHtml)
document.body.innerHTML += testHtml
document.body.innerHTML += '<hr />'
document.body.innerHTML += result</code></pre>
</div>
</div>
</p>
<hr>
<p><strong>Edit</strong>
I should note that the solution ought to work in node, ideally. I appreciate that the fact I include dom manipulation in the question is quite misleading, I included this more to attempt to create an easy working example that to demonstrate how the code might actually be used.</p>
<p>A further note, the performance of this code is not particularly important. It's only for relatively small amounts of html and gets run once when the application loads.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:03:52.667",
"Id": "405132",
"Score": "1",
"body": "Thanks for this great question - I hope you get some good reviews, and I hope to see more of your contributions here in future!"
}
] | [
{
"body": "<p>One thing to consider is the whole working with HTML as string. In the answer I'll assume you work within the web-browser. The web-browser can parse the HTML for you, this way you'll only have to work with nodes.</p>\n\n<p>Here is an example:</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 testHtml = `\n <p>This is a test paragraph</p>\n <a style=\"font-weight: bold;\" href=\"http://www.google.co.uk\">Google is here</a>\n <a style=\"font-weight: bold;\" href=\"http://www.msn.co.uk\">Msn is here</a>\n <h2>This is a heading</h2>\n`;\n\nfunction transformLinksToTextOnly(htmlString) {\n const root = document.createElement('root');\n root.innerHTML = htmlString;\n const anchors = root.querySelectorAll('a');\n\n anchors.forEach(anchor => {\n const span = document.createElement('span');\n\n span.innerHTML = anchor.innerHTML;\n if (anchor.href) \n span.innerHTML += ` (${anchor.href})`;\n\n anchor\n .getAttributeNames()\n .forEach(attrName => {\n const attrValue = anchor.getAttribute(attrName);\n span.setAttribute(attrName, attrValue);\n });\n\n anchor.parentNode.replaceChild(span, anchor);\n });\n\n return root.innerHTML;\n}\n\nconst result = transformLinksToTextOnly(testHtml);\n\ndocument.body.innerHTML += testHtml;\ndocument.body.innerHTML += '<hr />';\ndocument.body.innerHTML += result;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:58:15.817",
"Id": "405152",
"Score": "0",
"body": "Thanks for this; I was actually thinking of using this in node, which I should have probably mentioned in the question, but it may be that I can take a similar approach using a library"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:55:27.220",
"Id": "209621",
"ParentId": "209609",
"Score": "4"
}
},
{
"body": "<h1>Highly inefficient</h1>\n\n<p>The code is highly inefficient, wasting CPU cycles and memory due to poor use of Javascript API's. It is also badly formatted and thus hard to read and follow and poor naming also made working out what you were doing difficult.</p>\n\n<h2>Code Points.</h2>\n\n<ul>\n<li>Better naming alround. Example, you have two functions <code>transformLinkToTextOnly</code> and <code>transformLinksToTextOnly</code> Now I might be a bit blind but without spaces its not at all clear that these are two separate functions. If you consider the context of the functions and encapsulate them you can reduce the complex names to <code>transformLink</code> and <code>transformLinks</code> making the plural stand out, the rest is inferred due to context.</li>\n<li>Indent chained functions.</li>\n<li>Use semicolons to end lines. There are many arguments for and against using semicolons. Semicolons are required by the language, and are inserted automatically when javascript is parsed, however there are many edge cases that most people are unaware of and can catch you out. The rule of thumb is \"Can you list all edge cases where semicolon insertion can cause problems?\" if not use them. It is even more important that you are consistent. Even if you know all the rules, using semicolons in some places and not in others breaks the style rule \"Be consistent\".</li>\n<li>Avoid single use variable declarations.</li>\n<li>If you use terneries in multi expression lines, put them inside <code>(...)</code> for clarity. See example A</li>\n<li>Know your javascript. It is important that you are thoroughly familiar with the language you write in. You need to regularly review the JS reference and know the most concise and performant forms to achieve what you desire. Your code is very GC (garbage collection) unfriendly creating many arrays and thrashing memory and slowuing down the code, all of which can be avoided . See example B</li>\n</ul>\n\n<h2>Example A</h2>\n\n<pre><code> return withReaddedOpeningTags\n .reduce((prev, curr) => [\n ...prev,\n curr.indexOf('<a') > -1 ?\n splitByLinkEnds(curr) : curr\n ], []).flat()\n</code></pre>\n\n<p>Better syntax written as </p>\n\n<pre><code>return withReaddedOpeningTags\n .reduce((prev, curr) =>\n [...prev, (curr.indexOf('<a') > -1 ? splitByLinkEnds(curr) : curr)]\n , [])\n .flat();\n</code></pre>\n\n<p>As I am at this function I will point out that for every iteration you make a new copy of the array, add it as another array, and in the end you are forced to flatten the result to get what you want. </p>\n\n<p>The same can be done with.</p>\n\n<pre><code>return withReaddedOpeningTags\n .map(item => item.indexOf('<a') > -1 ? splitByLinkEnds(item) : item);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>return withReaddedOpeningTags\n .map(item => item.includes('<a') ? splitByLinkEnds(item) : item);\n</code></pre>\n\n<h2>Example B</h2>\n\n<p>An example function <code>splitByLinkEnds</code> create 5 arrays</p>\n\n<pre><code>const splitByLinkEnds = html => {\n const split = html.split('</a>'); // array 1\n\n const allButLast = split.slice(0, -1); // array 2\n const last = split.slice(-1)[0]; // creates array 3 an uses first item\n\n return [\n ...allButLast.map(x => `${x}</a>`), // map creates an array 4 that is then \n // copied to the return array 5\n last \n ];\n} \n</code></pre>\n\n<p>It can be done using only one new array.</p>\n\n<pre><code>const splitEnds = markup => {\n const parts = markup.split(\"</a>\");\n const end = parts.pop();\n parts.forEach((x, i) => parts[i] = x + \"</a>\");\n parts.push(end);\n return parts;\n}\n</code></pre>\n\n<p>or as</p>\n\n<pre><code>const splitEnds = markup => {\n return markup.split(\"</a>\").forEach((x, i, a) => a[i] = x + (i < a.length - 1 ? \"</a>\" : \"\"));\n}\n</code></pre>\n\n<h2>Rewrites</h2>\n\n<p>I have include 4 ways of achieving the same result. Javascript is very expressive so there is no single right way to do anything.</p>\n\n<h3>Rewrite using only strings and arrays</h3>\n\n<p>This method does not require the DOM and splits the markup at anchor boundaries creating an array of anchor descriptions which is then used to replace the anchors in the original markup.</p>\n\n<pre><code>function replaceAnchors(markup) {\n function findLinks(markup) {\n return markup.substring(markup.indexOf(\"<a\") + 2).split(\"<a\")\n .map(markup => ({\n markup : \"<a\" + markup.split(\"</a>\")[0] + \"</a>\",\n anchor : markup.split(\">\")[0],\n href : markup.split(\"href=\\\"\")[1].split(\"\\\"\")[0],\n text : markup.split(\">\")[1].split(\"</a\")[0],\n }));\n } \n findLinks(markup).forEach(link => {\n markup = markup.replace(link.markup,`<span${link.anchor}>${link.text}(${link.href})</span>`);\n });\n return markup;\n}\n</code></pre>\n\n<p>Second version does away with the intermediate array and does it in one pass. </p>\n\n<pre><code>function replaceAnchors(markup) {\n markup.substring(markup.indexOf(\"<a\") + 2).split(\"<a\")\n .forEach(a => {\n const href = a.split(\"href=\\\"\")[1].split(\"\\\"\")[0];\n const text = a.split(\">\")[1].split(\"</a\")[0];\n\n markup = markup.replace(\n `<a${a.split(\"</a>\")[0]}</a>`,\n `<span${a.split(\">\")[0]}>${text}(${href})</span>`\n );\n });\n return markup;\n}\n</code></pre>\n\n<h3>Rewrite with memory and performance in mind.</h3>\n\n<p>This uses named properties to determine what to do with each character in turn. If a <code>match[current]</code> is found then <code>actions[current].add</code> and <code>actions[current].action</code> are performed, each action sets up the next expected match and actions by setting the string <code>current</code> to the correct name. It is very fast and has a little room to go even faster. It is also very memory efficient</p>\n\n<pre><code>function replaceAnchors(markup) {\n const match = {\n get anchorStart() { return markup[idx] === \"<\" && markup[idx+1] === \"a\" },\n get hrefStart() { return markup.substring(idx,idx + 6) === \"href=\\\"\" },\n get hrefEnd() { return markup[idx] === \"\\\"\" },\n get tagClose() { return markup[idx] === \"<\" && markup[idx+1] === \"/\" && markup[idx+2] === \"a\" },\n };\n const actions = {\n anchorStart: {\n add() { idx += 2; return \"<span\" },\n action() { current = \"hrefStart\" }\n },\n hrefStart: {\n add() { idx += 6; return \"href=\\\"\"}, \n action() { hrefStart = idx; current = \"hrefEnd\" }\n },\n hrefEnd: {\n add() { idx += 1; return \"\\\"\"}, \n action() { href = markup.substring(hrefStart, idx -1); current = \"tagClose\" }\n },\n tagClose: {\n add() { idx += 4; return \"(\" + href + \")</span>\" },\n action() { current = \"anchorStart\" }\n },\n }\n var result = \"\", idx = 0, hrefStart, href, current = \"anchorStart\";\n while (idx < markup.length) {\n if (match[current]) {\n result += searchs[current].add();\n searchs[current].action();\n } else {\n result += markup[idx++]; \n }\n }\n return result;\n}\n</code></pre>\n\n<h3>Rewrite using the DOM</h3>\n\n<p>This method uses the Markup parser to help locate anchor tags and then just replaces the start and end tag with span and the additional href</p>\n\n<pre><code>function replaceAnchors(markup) {\n const nodes = document.createElement(\"span\");\n nodes.innerHTML = markup;\n for (const a of nodes.querySelectorAll(\"a\")) {\n const anchor = a.outerHTML;\n markup = markup.replace(anchor, anchor\n .replace(\"</a>\",`(${a.getAttribute(\"href\")})</span>`)\n .replace(\"<a\",\"<span\")\n );\n\n }\n return markup;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:57:12.940",
"Id": "405231",
"Score": "0",
"body": "Thanks for your detailed response. I completely agree about the indenting: I put the code together in jsfiddle and must have been using a mixture of tabs and spaces, sorry about that. It's corrected now. I like your point about wrapping the ternary statement in parentheses; I think that'd make things quite a bit more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T09:01:18.083",
"Id": "405232",
"Score": "0",
"body": "Some of the suggestions you make seem to go against the direction in which javascript is heading these days. Do you think that your style (`for` loops, `while` loops, manipulating state, avoiding single use variables etc.) is the better way of doing things? It's how I used to write javascript, but the trend of the language is very much against that these days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T09:04:24.000",
"Id": "405233",
"Score": "0",
"body": "I also agree with your comments on semicolons; I see some style recommendations against them, but it seems like they're a useful part of the language which both prevent bugs and improve readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T09:52:35.780",
"Id": "405235",
"Score": "0",
"body": "@OliverRadini You asked \"Do you think that your style...\" \"...is the better way of doing things?\" The aim is to reduce the code size. The number of lines of code is by far the most reliable metric used to determine code quality. Each coder will have an error rate measured in bugs per lines of code, reduce the number of lines to do a task and you reduce the number of bugs. This is consistent across languages and paradigms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T10:00:22.200",
"Id": "405236",
"Score": "0",
"body": "That's interesting; it's new to me to have the reduction of the number of lines of code as a primary aim. It seems like, if you're looking for a quantifiable metric then it's quite useful, but this leads me to think that quantifiable metrics are unlikely to give a good indication of the quality of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T10:40:48.543",
"Id": "405237",
"Score": "0",
"body": "@OliverRadini You had 41 lines of code (excluding blank lines, setup, and testing) that (with blank lines) spanned over a page and thus needed interaction just to read, for a task that can be done in 12 lines. Now imagine a project with 1,000 tasks. Would you rather manage 41,000 lines of code or 12,000 lines of code? Concise compact code is always a sign of quality. Adding code just to satisfy readability is a sign that the coder is not comfortable with the language, task to complete, or lacking experience and not a sign of quality code IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T10:57:39.350",
"Id": "405238",
"Score": "0",
"body": "I just don't think that you can use number of lines of code as a sole metric by which to judge the quality of code. I was originally wondering why the examples you gave go against the trends of modern javascript. Nowadays, the trend is towards avoiding loops, and avoiding mutating state. What is interesting to me is that in your examples you seem to suggest that it's better to mutate state and use loops. What I'd like to know more about is _why_ you suggest what you do, I'm just unsure as to what the number of lines of code has to do with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T11:24:00.227",
"Id": "405240",
"Score": "0",
"body": "@OliverRadini By mutate state I assume you mean \"No side effects\" (sfx) as in functional programming. In single threaded Javascript it's impossible to have no sfx, multi threaded (workers) gets closer but still to communicate requires using the context global state. I use lexical scope (encapsulation) to maintain state, you will notice that all variables and functions are encapsulated within the higher function, only relevant code can manipulate it. Javascript is built on lexical scope, to ignore it bloats code, slows execution chews power, and makes spaghetti out of simple tasks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T11:40:53.713",
"Id": "405241",
"Score": "0",
"body": "I see; so you think that the modern trend towards using functional patterns is problematic because this way of writing javascript is typically less performant than those which are happy to have side effects? I can see the validity to this point of view, though I also believe that code which aims to keep variables immutable, and avoid side effects, is typically far easier to debug and reason about. This may just be my experience of working with the two approaches, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T12:07:01.340",
"Id": "405242",
"Score": "0",
"body": "@OliverRadini No not quite, functional programing is great, but not in javascript, it does not enforce immutability. It is trivial to forget a reference `const a = [{}]` and `foo(...a) { a[0].b = 1}` mutates `a` There is no way to catch such a violation making the whole no side effects tenant collapse and untrustable. Languages must enforce the paradigm or it is just a waste of time. Asking coders to be careful does nothing to fix the problem. It is impossible to write functional javascript because javascript can not enforce the segregation of state needed to make it trustable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T12:54:53.833",
"Id": "405244",
"Score": "0",
"body": "That makes sense; it's interesting that so much development is moving in a functional direction when the language doesn't support it. Perhaps this is why we're starting to see an increased interest in functional languages which can be compiled to javascript (ReasonML seems to be growing in popularity)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T01:01:41.787",
"Id": "209655",
"ParentId": "209609",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:00:37.070",
"Id": "209609",
"Score": "5",
"Tags": [
"javascript",
"html"
],
"Title": "Replace anchor tags with spans, and place the href attribute into the span"
} | 209609 |
<p>I wrote the Game Of Life algorithm with Go. There are a million ways that we can implement the algorithm, but I want to know is it implemented in good-way or not? </p>
<p>I wonder how can I improve the performance and the code quality? </p>
<pre><code>package main
import (
"math"
"math/rand"
"strconv"
"time"
"github.com/nsf/termbox-go"
)
type Cell struct {
X int
Y int
Dead bool
}
type GameOfLife struct {
cells [][]Cell
Generation int
Alives int
}
var (
maxRow, maxCol int
pause bool
speed time.Duration
random bool
)
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
func main() {
pause = true
err := termbox.Init()
if err != nil {
panic(err)
}
speed = 100
random = false
defer termbox.Close()
termbox.SetInputMode(termbox.InputMouse)
maxRow, maxCol = termbox.Size()
maxCol -= 3
rand.Seed(time.Now().UTC().UnixNano())
b := initiate(false)
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
loop:
for {
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Key == termbox.KeyCtrlC {
break loop
}
if ev.Key == termbox.KeyCtrlS {
pause = !pause
}
if ev.Key == termbox.KeyCtrlN {
b = initiate(false)
pause = true
}
if ev.Key == termbox.KeyCtrlI {
speed++
}
if ev.Key == termbox.KeyCtrlD {
speed--
}
if ev.Key == termbox.KeyCtrlR {
b = initiate(true)
}
}
if ev.Type == termbox.EventMouse {
if ev.MouseX <= maxRow && ev.MouseY <= maxCol {
b.cells[ev.MouseY][ev.MouseX].Dead = false
}
}
b.Print()
termbox.Flush()
default:
if !pause {
b.NextGen()
time.Sleep(speed * time.Millisecond)
}
b.Print()
termbox.Flush()
}
}
}
func initiate(random bool) *GameOfLife {
b := &GameOfLife{
cells: make([][]Cell, int(math.Max(float64(maxCol), float64(maxRow)))),
}
for i := 0; i <= maxCol; i++ {
for j := 0; j <= maxRow; j++ {
dead := true
if random {
if randInt(0, 100) < 50 {
dead = false
}
}
c := Cell{
X: i,
Y: j,
Dead: dead,
}
b.cells[i] = append(b.cells[i], c)
}
}
return b
}
func (b *GameOfLife) NextGen() {
duplicate := make([][]Cell, len(b.cells))
for i := range b.cells {
duplicate[i] = make([]Cell, len(b.cells[i]))
copy(duplicate[i], b.cells[i])
}
b.Alives = 0
for i := 0; i <= maxCol; i++ {
for j := 0; j <= maxRow; j++ {
ncnt := b.Nighbors(b.cells[i][j])
if ncnt < 2 || ncnt > 3 {
duplicate[i][j].Dead = true
}
if b.cells[i][j].Dead && ncnt == 3 {
duplicate[i][j].Dead = false
}
if ncnt == 2 {
duplicate[i][j] = b.cells[i][j]
}
if !duplicate[i][j].Dead {
b.Alives++
}
}
}
b.Generation++
b.cells = duplicate
}
func (b *GameOfLife) Nighbors(cell Cell) int {
cnt := 0
for x1 := cell.X - 1; x1 <= cell.X+1; x1++ {
for y1 := cell.Y - 1; y1 <= cell.Y+1; y1++ {
if x1 == cell.X && y1 == cell.Y {
continue
}
if x1 < 0 || x1 >= maxCol {
continue
}
if y1 < 0 || y1 >= maxRow {
continue
}
if !b.cells[x1][y1].Dead {
cnt++
}
}
}
return cnt
}
func (b *GameOfLife) Print() {
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
for i := 0; i <= maxCol; i++ {
for j := 0; j <= maxRow; j++ {
ch := '█'
if b.cells[i][j].Dead {
ch = '░'
}
termbox.SetCell(j, i, ch, termbox.ColorDefault, termbox.ColorDefault)
}
}
b.PrintStatus()
}
func (b *GameOfLife) PrintStatus() {
statuses := []string{
"Generation: " + strconv.Itoa(b.Generation) + " | Alives: " + strconv.Itoa(b.Alives) + " | Speed: " + (speed * time.Microsecond).String(),
"Shortcuts: New (Ctrl+N) | Start/Pause(Ctrl+S) | Random (Ctrl+R) | Set Cell Alive (Mouse Click) | Speed Up (Ctrl+D) | Speed Down (Ctrl+I)",
}
for c, status := range statuses {
for x, ch := range status {
termbox.SetCell(x+1, maxCol+c+1, ch, termbox.ColorCyan, termbox.ColorDefault)
}
}
}
</code></pre>
<p>Edit: source code updated</p>
<p><a href="https://github.com/smoqadam/go-game-of-life" rel="noreferrer">github repository</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T13:58:06.117",
"Id": "405251",
"Score": "0",
"body": "Cross posteed on reddit: https://www.reddit.com/r/golang/comments/a6278n/code_review_needed_for_conways_game_of_life/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T21:16:32.510",
"Id": "454282",
"Score": "0",
"body": "great to see you used termbox. have had a look at `tcell` ?"
}
] | [
{
"body": "<p>I really liked the way you used <code>Termbox</code>; you should try <code>Tcell</code> as well for fun.</p>\n<h1>Review</h1>\n<p>The function <code>initiate</code> is doing 2 jobs: generate the world and randomize.</p>\n<p>They could be 2 functions as below:</p>\n<pre><code>func initiate(maxCol, maxRow) *GameOfLife {\n\n b := &GameOfLife{\n cells: make([][]Cell, int(math.Max(float64(maxCol), float64(maxRow)))),\n }\n}\n</code></pre>\n<p>and Randomization could be a separate function.</p>\n<p>Also, <code>randInt</code> could be better achieved with a seed:</p>\n<pre><code>seed := rand.New(rand.NewSource(time.Now().Unix()))\n</code></pre>\n<p>and then you may call <code>seed.Intn(30)</code> 30 here being the upper limit</p>\n<p>Neighbors function <code>Nighbors</code> is bit messy; you could add more readability here. Which will just return Count of Neighbors and pass it to <code>Cell.NextState</code></p>\n<p>The <code>Cell</code> could be a struct and have the method <code>NextState</code>\ne.g.</p>\n<pre><code>func (c *Cell) NextState(neighbours int) {\n if c.Alive && (neighbours < 2 || neighbours > 3) {\n c.Alive = false\n }\n\n if c.Alive && (neighbours == 2 || neighbours == 3) {\n c.Alive = true\n }\n\n if !c.Alive && neighbours == 3 {\n c.Alive = true\n }\n}\n</code></pre>\n<hr />\n<p>You could have a separate directions struct and loop through each <code>Direction</code>,\nand have another method to get the Direction Cell e.g.</p>\n<pre><code>func (b GameOfLife) getCell(x, y int) Cell {\n return b.cells[x+(y*wl.width)]\n}\n \nfunc(b GameOfLife) Plus(x, y int, direction Vector) Cell {\n return b.getCell(x+direction.x, y+direction.y)\n}\n\nvar DirectionNames = strings.Split("n ne e se s sw w nw", " ")\nvar Directions = map[string]Vector{\n "n": {0, -1},\n "ne": {1, -1},\n "e": {1, 0},\n "se": {1, 1},\n "s": {0, 1},\n "sw": {-1, 1},\n "w": {-1, 0},\n "nw": {-1, -1},\n}\n</code></pre>\n<p>In the same way, I see <code>NextGen</code> could be refactored into more functions to have better readability here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T12:47:59.963",
"Id": "232641",
"ParentId": "209612",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "232641",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:37:20.177",
"Id": "209612",
"Score": "7",
"Tags": [
"go",
"game-of-life"
],
"Title": "Game of life in Go"
} | 209612 |
<p>Almost like this <a href="https://codereview.stackexchange.com/questions/163171/a-failablet-that-allows-safe-returning-of-exceptions">question here</a>, I'm playing with some methods that may fail, but in my case, the method failing is not a exceptional case; it just means I need to try running it again.</p>
<p>The method I'm writing is inherently stochastic, so running it multiple times yields different results. Some are valid, some are invalid.</p>
<p>Like in the other question, I created a class that represents a successful / unsuccessful run.</p>
<pre><code>public readonly struct Maybe<T> {
public readonly bool ContainsValue;
public readonly T Value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Maybe(bool containsValue, T value) {
ContainsValue = containsValue;
Value = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Maybe<T> Just(T value) {
return new Maybe<T>(
containsValue: true,
value: value);
}
public static Maybe<T> Empty { get; } = new Maybe<T>(
containsValue: false,
value: default
);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Maybe<T>(T value) => Maybe.Just(value);
}
// This class is used just to make the syntax of Maybe<T> cleaner
public static class Maybe {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Maybe<T> Just<T>(T value) => Maybe<T>.Just(value);
}
</code></pre>
<p>In the end of my method I can just check if the result is valid and return Maybe.Just(Result) or Maybe.Empty() if it's not.</p>
<p>Review questions about <code>Maybe<T></code> and <code>Maybe</code>:</p>
<ul>
<li>Is this struct design ok? I opted for a struct to reduce allocations. I do not intend to store references to it. Just return it, check it's results and forget about it.</li>
<li>Is the creation of a non-generic class just to enable a prettier syntax legitimate? I prefer writing <code>Maybe.Just(whatever)</code> than <code>Maybe<LongType>.Just(whatever)</code>.</li>
</ul>
<p>I then noticed that I tend to wrap my "try methods" inside a loop... So I "hoisted" the code to a different class:</p>
<pre><code>public static class ProcessRetrier {
public static Maybe<T> Run<T>(int maximumRetries, Func<Maybe<T>> func) {
if (maximumRetries < 0)
throw new ArgumentOutOfRangeException(nameof(maximumRetries) + " must be >= 0");
if (func == null)
throw new ArgumentNullException(nameof(func));
for (int i = 0; i <= maximumRetries; i++) {
var result = func();
if (result.ContainsValue)
return result;
}
return Maybe<T>.Empty;
}
}
</code></pre>
<p>Review question about <code>ProcessRetrier</code>:</p>
<ul>
<li>Is this class design legit?</li>
<li>Do you have any suggestions?</li>
</ul>
<p>Finally, I decided that it would be cool if I could run the different attempts in different threads, so I created this monstrosity here:</p>
<pre><code>public static Maybe<T> RunParallel<T>(int maximumRetries, Func<Maybe<T>> func) {
if (maximumRetries < 0)
throw new ArgumentOutOfRangeException(nameof(maximumRetries) + " must be >= 0");
if (func == null)
throw new ArgumentNullException(nameof(func));
var retries = 0;
var tasks = new Task<Maybe<T>>[Environment.ProcessorCount];
var finished = 0;
for (int i = 0; i < tasks.Length; i++) {
tasks[i] = Task.Run(() => {
while (true) {
if (retries >= maximumRetries || finished > 0)
return Maybe<T>.Empty;
var attempt = func();
if (attempt.ContainsValue) {
Interlocked.Increment(ref finished);
return attempt;
} else {
Interlocked.Increment(ref retries);
}
}
});
}
Task.WaitAny(tasks);
foreach (var t in tasks) {
if (t.Result.ContainsValue)
return t.Result;
}
return Maybe<T>.Empty;
}
</code></pre>
<p>And now is the meat of the problem:</p>
<ul>
<li>Is this parallel implementation correct?</li>
<li>When the lambda "swallows" <code>retries</code> and <code>finished</code>, are the different threads seeing the same values? Or each task will try <code>maximumRetries</code>?</li>
<li>If each thread task is reading / modifying it's own copy of <code>retries</code>, how can I make them all use the same value?</li>
</ul>
<p><strong>Edit: I tested the "RunParallel" logic with the snippet bellow, it looks like that each threading is running roughly N / number_of_processors attempts. But just because it's works now doesn't mean the implementation is correct; hence the review question.</strong></p>
<pre><code>var retries = 0;
var maximumRetries = 10 * 1000 * 1000;
var tasks = new Task<int>[Environment.ProcessorCount];
var finished = 0;
for (int i = 0; i < tasks.Length; i++) {
tasks[i] = Task.Run(() => {
var taskAttempts = 0;
while (true) {
if (retries >= maximumRetries || finished > 0)
return taskAttempts;
Interlocked.Increment(ref retries);
taskAttempts += 1;
}
});
}
Task.WaitAll(tasks);
var attempts = tasks.Select(t => t.Result).ToArray();
Console.WriteLine(attempts.Sum());
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:40:55.613",
"Id": "405142",
"Score": "0",
"body": "\"Is this parallel implementation correct?\" Did you test it? How?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T15:53:31.513",
"Id": "405159",
"Score": "0",
"body": "Yes. Updated the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T17:31:56.050",
"Id": "405170",
"Score": "0",
"body": "You should use the `CancellationTokenSource` and the `CancellationToken` to stop the loop and the tasks. I also think that it's easier to use `Task.FromX` than `Maybe`. `Task` allows you to act exactly the same and has even some more features."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T20:19:01.803",
"Id": "405182",
"Score": "0",
"body": "Task.FromX? What's that?"
}
] | [
{
"body": "<h2>Concurrency</h2>\n\n<blockquote>\n <p><em>Is this parallel implementation correct?</em></p>\n</blockquote>\n\n<p>I would expect a method called <code>RunParallel<T></code> to use processor affinity (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel?view=netframework-4.8\" rel=\"nofollow noreferrer\">Parallel.For</a>) specially since you take the processor count into account <code>var tasks = new Task<Maybe<T>>[Environment.ProcessorCount];</code>. But instead, you use thread affinity <code>tasks[i] = Task.Run(() => ..</code> </p>\n\n<p>Either refactor <code>RunParallel<T></code> to actually be parallel, or keep it asynchronous and rename it to something in the likes of <code>Any<T></code>. You might also want to use the <a href=\"https://www.dotnetperls.com/async\" rel=\"nofollow noreferrer\">async/await pattern</a> when choosing the latter.</p>\n\n<hr>\n\n<h2>Syntax</h2>\n\n<blockquote>\n <p><em>Is the creation of a non-generic class just to enable a prettier syntax legitimate? I prefer writing <code>Maybe.Just(whatever)</code> than\n <code>Maybe<LongType>.Just(whatever)</code>.</em></p>\n</blockquote>\n\n<p>Have you considered an extension method:</p>\n\n<pre><code>public static class Maybe {\n\n public static Maybe<T> Just<T>(this T value) => Maybe<T>.Just(value);\n}\n</code></pre>\n\n<p>And usage:</p>\n\n<pre><code>int myValue = 5;\nvar maybe = myValue.Just(); // Maybe<int>();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:21:10.787",
"Id": "227033",
"ParentId": "209615",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:16:10.443",
"Id": "209615",
"Score": "3",
"Tags": [
"c#",
"thread-safety",
"task-parallel-library"
],
"Title": "Repeating a task that may fail (in parallel)"
} | 209615 |
<p>I'm working to implement some simple bigint functions for addition, multiplication and powers. They work correctly but the larger the numbers the longer the time it takes.
For example 2<sup>10000</sup> takes a very long time.
Here are all the functions I'm using.</p>
<pre><code>char *ft_strnew(size_t size)
{
char *temp;
size_t i;
if (!(temp = (char*)malloc(sizeof(char) * (size + 1))))
return (NULL);
i = 0;
while (i < size)
{
temp[i] = '\0';
i++;
}
temp[i] = '\0';
return (temp);
}
char *ft_strjoin(char const *s1, char const *s2)
{
char *temp;
int i;
int j;
if (!(temp = (char*)malloc(sizeof(char) *
(ft_strlen(s1) + ft_strlen(s2) + 1))))
return (NULL);
i = 0;
j = 0;
while (s1[i])
{
temp[j] = s1[i];
i++;
j++;
}
i = 0;
while (s2[i])
{
temp[j] = s2[i];
i++;
j++;
}
temp[j] = '\0';
return (temp);
}
int left_one(int *i, char c)
{
if (--(*i) < 0)
return (0);
else
return (c - '0');
}
char *add_char(char *nbr1, char *nbr2)
{
int i;
int j;
int left[4];
char *temp;
left[0] = 0;
temp = ft_strnew(0);
i = ft_strlen(nbr1);
j = ft_strlen(nbr2);
if (i > j)
left[3] = i;
else
left[3] = j;
while (--left[3] >= 0)
{
left[1] = left_one(&i, nbr1[i - 1]);
left[2] = left_one(&j, nbr2[j - 1]);
left[0] += left[1] + left[2];
temp = ft_charjoin((left[0] % 10) + '0', temp, 'l');
left[0] /= 10;
}
if (left[0] > 0)
temp = ft_charjoin((left[0] % 10) + '0', temp, 'l');
return (temp);
}
char *multi1_char(char *nbr1, int nbr2)
{
int i;
char *temp;
if (nbr1[0] == '0' || nbr2 == 0)
return ("0");
i = -1;
temp = ft_strdup(nbr1);
while (++i < nbr2 - 1)
temp = add_char(temp, nbr1);
return (temp);
}
char *multi_char(char *nbr1, char *nbr2)
{
int i;
char *temp;
int j;
char *temp1;
int t;
char *mul;
mul = ft_strnew(0);
temp = ft_strnew(1);
j = 0;
i = ft_strlen(nbr2);
while (--i >= 0)
{
t = -1;
temp1 = multi1_char(nbr1, nbr2[i] - '0');
//temp1 = multi1_char(temp1, 10*j);
/*while (++t < j)
temp1 = ft_strjoin(temp1, "0");*/
temp1 = ft_strjoin(temp1, mul);
temp = add_char(temp, temp1);
mul = ft_strjoin("0", mul);
j++;
}
return (temp);
}
char *power_char(int nbr1, int nbr2)
{
char *temp;
temp = ft_strnew(0);
if (nbr2 == 1)
return (ft_itoa(nbr1));
if (nbr2 % 2 == 0)
{
temp = power_char(nbr1, nbr2 / 2);
return (multi_char(temp, temp));
}
else
{
nbr2 -= 1;
temp = power_char(nbr1, nbr2 / 2);
return(multi_char(ft_itoa(nbr1), multi_char(temp, temp)));
}
}
</code></pre>
<p>I came up with a way to make the function that handles powers work faster but still the multiplication function is slow for big numbers.</p>
<p>Is there any way of improving my functions or are they bad from the start and I should start all over?</p>
| [] | [
{
"body": "<p>It seems you're allergic to <code>for</code> loops for some reason; for example, in <code>ft_strnew</code>:</p>\n\n<pre><code>for (size_t i = 0; i < size; i++)\n</code></pre>\n\n<p>There are examples elsewhere.</p>\n\n<p>Don't predeclare your variables, e.g.</p>\n\n<pre><code>int i;\nint j;\n</code></pre>\n\n<p>This hasn't been needed for 20 years. Declare them where they're used.</p>\n\n<p>Replace this entire loop:</p>\n\n<pre><code>size_t i;\ni = 0;\nwhile (i < size)\n{\n temp[i] = '\\0';\n i++;\n}\ntemp[i] = '\\0';\n</code></pre>\n\n<p>With this:</p>\n\n<pre><code>memset(temp, '\\0', size+1);\n</code></pre>\n\n<p>Otherwise, your entire approach to arbitrary-size integer math is a quite slow one. (Other libraries have solved this, but it's nice that you're trying to learn.) You can't be doing this character by character; rather you need to do it integer by integer. Do some googling about arbitrary-precision integer arithmetic on 64-bit architectures.</p>\n\n<p>A comment on something you said:</p>\n\n<blockquote>\n <p>They work correctly but the larger the numbers the longer the time it takes.</p>\n</blockquote>\n\n<p>No arbitrary-precision library can escape this. The execution time of even the best libraries will scale according to the size of the input when it exceeds the size of the machine word.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T23:01:25.017",
"Id": "405198",
"Score": "0",
"body": "Thank you,\nabout the \"for loop \" is something that i am not allowed to use only the \"While loop\"\nand for the predeclared variables its also something thats im forced to because of the norm\nYou are correct my approach is very slow thank you for you informations i will look for what you suggested right away\nAgain thank you very much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T23:02:50.713",
"Id": "405199",
"Score": "2",
"body": "Not \"being allowed\" to use a `for` loop is ridiculous."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T23:17:49.740",
"Id": "405201",
"Score": "0",
"body": "Yes i know but because using while while takes a bigger space and im not allowed to have more than 25lines in any function so i need to make the best out of my space"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T21:54:14.977",
"Id": "405378",
"Score": "0",
"body": "@HamzaElBouazizi Commenting about restrictions to code after a review is ineffective. Far better to post coding restrictions in the initial question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T15:13:15.310",
"Id": "209623",
"ParentId": "209617",
"Score": "5"
}
},
{
"body": "<p>You seem to be missing some required headers; at least <code><stdlib.h></code>, and also whatever defines <code>ft_strlen</code>, <code>ft_strdup</code>, <code>ft_itoa</code> and <code>ft_charjoin</code>.</p>\n\n<hr>\n\n<p>Let's start with the first function, <code>ft_strnew()</code>:</p>\n\n<p>This allocation is very long-winded:</p>\n\n<blockquote>\n<pre><code>temp = (char*)malloc(sizeof(char) * (size + 1))\n</code></pre>\n</blockquote>\n\n<p>Firstly, it's not necessary or desirable to cast the result of <code>malloc()</code> - that's usually a symptom of not including <code><stdlib.h></code>. Secondly <code>sizeof (char)</code> is always 1, because <code>sizeof</code> measures in units of <code>char</code>. Thirdly, that's followed by a loop that zeroes out the storage; that's more efficiently achieved by using <code>calloc()</code> instead of <code>malloc()</code>:</p>\n\n<pre><code>char *ft_strnew(size_t size)\n{\n return calloc(size + 1, 1);\n}\n</code></pre>\n\n<hr>\n\n<p>Next up, <code>ft_strjoin()</code>. This appears to be simply an allocating version of <code>strcat()</code>, so let's use that instead of hand-rolled loops:</p>\n\n<pre><code>#include <string.h>\n\nchar *ft_strjoin(char const *s1, char const *s2)\n{\n char *result = malloc(strlen(s1) + strlen(s1) + 1);\n if (result) {\n strcpy(result, s1);\n strcat(result, s2);\n }\n return result;\n}\n</code></pre>\n\n<p>Or a little more efficiently:</p>\n\n<pre><code>#include <string.h>\n\nchar *ft_strjoin(char const *s1, char const *s2)\n{\n const size_t len1 = strlen(s1);\n const size_t len2 = strlen(s2);\n\n char *result = malloc(len1 + len2 + 1);\n if (result) {\n strcpy(result, s1);\n strcpy(result + len1, s2);\n }\n return result;\n}\n</code></pre>\n\n<p>Either of those is much clearer and easier to read, IMO.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int left_one(int *i, char c)\n</code></pre>\n</blockquote>\n\n<p>This function signature is very uninformative. What are <code>i</code> and <code>c</code> meant to represent? What's the result mean?</p>\n\n<p>Perhaps this is intended to be internal (in which case it should be declared with <code>static</code> linkage), but even in that case, it still needs at least some guidance for the unfortunate maintenance engineer (which may well be Future You, so worth the investment!).</p>\n\n<p>Even with the body, the intent is still mysterious:</p>\n\n<blockquote>\n<pre><code>if (--*i < 0)\n return 0;\nelse\n return c - '0';\n</code></pre>\n</blockquote>\n\n<p>(I've removed the extraneous parentheses for clarity). I would certainly expect at least one comment here.</p>\n\n<hr>\n\n<p>Now on to <code>add_char</code>:</p>\n\n<p>I don't understand what the array <code>left[]</code> is for - it seems to be used as four independent <code>int</code> variables rather than as an array. It's hard to give the function a full review due to the lack of its dependencies, particularly <code>ft_charjoin()</code> - does that function <code>realloc()</code> the passed <code>temp</code>? It's hard to reason about allocation and deallocation when they are so separated.</p>\n\n<hr>\n\n<p>I'm going to abandon function-by-function review at this point, where it becomes clear that there's problems with the data representation - big-endian variable-length decimal strings are an unwieldy format, and we really need to improve on that first.</p>\n\n<p>Little-endian strings are more suitable, as they don't need shuffling when overflow adds an extra digit, and we can store more than one decimal digit in an <code>unsigned char</code> (at least 2 decimal digits, or <code>CHAR_BIT</code> binary ones).</p>\n\n<p>We should be able to reduce the number of memory allocations by implementing more in-place algorithms, rather than copying to new memory as much as we do.</p>\n\n<hr>\n\n<p>A final general comment: this would have been much easier to review if the code were complete, and particularly if a sample <code>main()</code> had been included (perhaps the 2^10000 calculation mentioned in the text would be apposite?). Then I would have been able to run the code and perhaps even benchmark any suggestions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T23:12:05.610",
"Id": "405200",
"Score": "0",
"body": "First off, Thank you sir for the time,\nthe thing about casting malloc and using sizeof is because i have to...its something i agreed on, and for the way you made ft_strjoin using strcpy what can i say i feel stupid especialy since i implemented strcpy myself,\nthe function left_one is used to make sure i dont go in a place in mystring that doesnt exist (exemple : nbr1[-1]) instead it takes it as a 0,\nfor the way im approaching the problem is bad as it seems so i will have to do some research.\nOverall you are right i should make my code more understandable using comments and provide a main"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:11:20.123",
"Id": "405219",
"Score": "0",
"body": "If your team style guide insists on writing `sizeof (char)` and useless/harmful casts, there's an argument that it needs to be reconsidered. Unfortunately, you probably have to gain your experience under these crazy constraints to get into a position where you can correct them! Good luck!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:24:17.370",
"Id": "209627",
"ParentId": "209617",
"Score": "1"
}
},
{
"body": "<p><strong>Drip, drip, drip</strong></p>\n\n<p>The is the sound a leak makes. This code also \"drips\" and leaks memory. The various allocations are lost. Instead code should</p>\n\n<pre><code>ptr = function_that_allocates(...);\n\n// use ptr;\n\nfree(ptr); // free memory when done.\n</code></pre>\n\n<p><strong>Much too inefficient</strong></p>\n\n<p>Example: <code>multi1_char(char *nbr1, int nbr2)</code> performs <code>O(nbr1 * nbr2)</code> allocations and <code>O(nbr1 * nbr1)</code> runtime.</p>\n\n<p>Consider the following which does 1 allocation and <code>O(nbr1)</code> run time. The below is untested, so consider it advanced pseudo code. This is much like grade school math.</p>\n\n<pre><code>char *multi1_char(const char *nbr1, int nbr2) {\n assert(nbr2 >= 0 && nbr2 < 10);\n size_t len = strlen(nbr1); // If you cannot use strlen(), write your own\n\n // Make space for potential overflow, len, and \\0\n char *product = malloc(1 + len + 1); \n char *p = product + 1 + len;\n *p = '\\0';\n\n int carry = 0;\n const char *n1 = nbr1 + len; // start at the \\0\n while (n1 > nbr1) {\n n1--;\n int sum = (*n1 - '0')*nbr2 + carry;\n p--;\n *p = (sum%10) + '0';\n carry = sum/10;\n }\n if (carry) {\n p--;\n *p = carry + '0';\n } else {\n // Shift left\n for (size_t i = 0; i<len+1; i++) { // Use a while loop is you must\n p[i] = p[i+1]; \n }\n }\n return product;\n}\n</code></pre>\n\n<p>Many other functions can similarly be improved. Allocate once for the result and avoid <code>O(N to some power)</code> solutions when a <code>O(N to some smaller power</code>) solution exists.</p>\n\n<p>Deeper: <code>multi1_char()</code> is not even needed as <code>multi_char(a,b)</code> can be re-written with the above idea: allocate <code>strlen(a) + strlen(b) + 1)</code> memory and perform <a href=\"https://en.wikipedia.org/wiki/Multiplication_algorithm#Long_multiplication\" rel=\"nofollow noreferrer\">long multiplication</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:30:27.083",
"Id": "209742",
"ParentId": "209617",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:08:57.130",
"Id": "209617",
"Score": "1",
"Tags": [
"performance",
"c",
"strings",
"integer"
],
"Title": "Functions to handle big numbers in C"
} | 209617 |
<p>Given a camelcase string and an index, return the subword of the string that includes that index, e.g.:</p>
<pre><code>find_word('CamelCaseString', 6) -> 'Case'
find_word('ACamelCaseString', 0) -> 'A'
</code></pre>
<p>My code:</p>
<pre><code>def find_word(s, index):
for i in range(index, 0, -1):
if s[i].isupper():
left = i
break
else:
left = 0
for i in range(index, len(s)-1):
if s[i].islower() and s[i+1].isupper() or s[i:i+2].isupper():
right = i
break
else:
right = len(s) - 1
return s[left:right+1]
</code></pre>
<p>Can this be made more concise/efficient?</p>
| [] | [
{
"body": "<h1>Review</h1>\n\n<ul>\n<li><p>Add docstrings and tests... or both in the form of doctests!</p>\n\n<pre><code>def find_word(s, index):\n \"\"\"\n Finds the CamalCased word surrounding the givin index in the string\n\n >>> find_word('CamelCaseString', 6)\n 'Case'\n >>> find_word('ACamelCaseString', 0)\n 'A'\n \"\"\"\n\n ...\n</code></pre></li>\n<li><p>Loop like a native.</p>\n\n<p>Instead of going over the indexes we can loop over the item directly</p>\n\n<blockquote>\n<pre><code>range(index, 0, -1)\n</code></pre>\n</blockquote>\n\n<p>We can loop over the item and index at the same time using enumerate</p>\n\n<pre><code>for i, s in enumerate(string[index:0:-1])\n</code></pre>\n\n<p>However this would be slower since it will create a new string object with every slice.</p></li>\n<li><p>If we can be sure that the givin string is a CamalCase string</p>\n\n<p>Then we can drop some of your second if statement</p>\n\n<blockquote>\n<pre><code>if s[i].islower() and s[i+1].isupper() or s[i:i+2].isupper():\n</code></pre>\n</blockquote>\n\n<p>Would be </p>\n\n<pre><code> if s[i+1].isupper():\n</code></pre></li>\n<li><p>Actually your code (from a performance aspect) is quite good</p>\n\n<p>We could however use a while loop to increment both side at once, for a little performance gain.</p></li>\n</ul>\n\n<h1>(slower, yet more readable) Alternative</h1>\n\n<p>A different approach to finding CamalCase words can be done with regex,</p>\n\n<p>We can find all CamalCase words with the following regex: <code>r\"([A-Z][a-z]*)\"</code></p>\n\n<p>And we can use <code>re.finditer</code> to create a generator for our matches and loop over them, and return when our index is in between the end and the start.</p>\n\n<pre><code>import re\n\ndef find_word_2(string, index):\n for match in re.finditer(r\"([A-Z][a-z]*)\", string):\n if match.start() <= index < match.end():\n return match.group()\n</code></pre>\n\n<p><em>NOTE This yields more readable code, but it should be alot slower for large inputs.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T15:43:19.697",
"Id": "209626",
"ParentId": "209619",
"Score": "7"
}
},
{
"body": "<p>An alternative approach may involve <strong>trading space for time</strong> and pre-calculate mappings between letter indexes and the individual words. That would make the actual lookup function perform at <span class=\"math-container\">\\$O(1)\\$</span> with <span class=\"math-container\">\\$O(n)\\$</span> sacrifice for space. This may especially be useful if this function would be executed many times and needs a constant time response for the same word. </p>\n\n<p>And, as this is tagged with <a href=\"/questions/tagged/interview-questions\" class=\"post-tag\" title=\"show questions tagged 'interview-questions'\" rel=\"tag\">interview-questions</a>, I personally think it would be beneficial for a candidate to mention this idea of pre-calculating indexes for future constant-time lookups.</p>\n\n<p>We could use a list to store the mappings between indexes and words:</p>\n\n<pre><code>import re\n\n\nclass Solver:\n def __init__(self, word):\n self.indexes = []\n for match in re.finditer(r\"([A-Z][a-z]*)\", word):\n matched_word = match.group()\n for index in range(match.start(), match.end()):\n self.indexes.append(matched_word)\n\n def find_word(self, index):\n return self.indexes[index]\n\n\nsolver = Solver('CamelCaseString')\nprint(solver.find_word(2)) # prints \"Camel\"\nprint(solver.find_word(5)) # prints \"Case\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T22:51:45.803",
"Id": "209648",
"ParentId": "209619",
"Score": "2"
}
},
{
"body": "<p>Actually you found an example where looping over indices is ok. What you messed up is the search for the right end. When doing slicing the second value is not included <code>'abc[0:2]</code>gives <code>'ab'</code>. So your <code>right</code> shall be past the last included character, that is the next uppercase one. We rewrite the second loop to follow the style of the first one</p>\n\n<pre><code>for i in range(index+1, len(s)):\n if s[i].isupper():\n right = i\n break\nelse:\n right = len(s)\n</code></pre>\n\n<p>and return the slice</p>\n\n<pre><code>return s[left:right]\n</code></pre>\n\n<p>That is IMHO also the most readable solution following the KISS principle (and some python Zen)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T20:35:15.497",
"Id": "209696",
"ParentId": "209619",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:30:47.663",
"Id": "209619",
"Score": "6",
"Tags": [
"python",
"strings",
"interview-questions"
],
"Title": "Function to return subword of a camelcase string"
} | 209619 |
<p>The problem: find and return the first nonrepeating character in a string, if the string does not have a nonrepeating character return an empty string. For purposes of finding the nonrepeating character it's case insensitive so 't' and 'T' appearing in the string would imply that that 't' and 'T' are not candidates for a nonrepeating character. When you return the character you must return it as its original case.</p>
<p>My Solution:</p>
<pre><code>def non_repeat(_str):
counts = {}
for pos, letter in enumerate(_str.lower()):
if letter not in counts:
counts[letter] = (0, pos)
incr_val = counts[letter][0] + 1
counts[letter] = (incr_val, pos)
for letter in _str.lower():
if counts[letter][0] == 1:
return _str[counts[letter][1]]
return ''
</code></pre>
<p>How can I improve the readability of my solution? In particular, I don't like:</p>
<ul>
<li><code>counts[letter][0]</code> because the 0 index is a bit ambiguous.</li>
<li>calculating the incremented value as another line, <code>incr_val</code>; it'd be nice to do the incrementing and updating of the dict in one line. </li>
</ul>
<p>Anything else you could make more readable? I should add that I'm aware of <code>collections.Counter</code>; for this solution I'd like to avoid using it. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:11:31.713",
"Id": "405163",
"Score": "5",
"body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T19:50:01.480",
"Id": "405180",
"Score": "1",
"body": "Can you explain why you want to avoid `collections.Counter`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T21:14:52.407",
"Id": "405186",
"Score": "0",
"body": "There's no logical reason for avoiding collections.Counter (that I'm aware of). I wrote my question that way because I wanted to keep the presentation of the algorithm more apparent to the reader, and because I already knew how to make the function much shorter by using collections.Counter which would essentially eliminate the 3-4 lines from the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T07:04:44.187",
"Id": "405214",
"Score": "0",
"body": "it might be easier to iterate over the string backwards"
}
] | [
{
"body": "<p>I would <em>separate counting from keeping the initial positions</em>. This would allow to use <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>collections.defaultdict</code></a> for counting and simplify the code and contribute to readability:</p>\n\n<pre><code>from collections import defaultdict\n\n\ndef non_repeat(input_string):\n counts = defaultdict(int)\n positions = {}\n\n for position, letter in enumerate(input_string.lower()):\n counts[letter] += 1\n positions[letter] = position\n\n for letter in input_string.lower():\n if counts[letter] == 1:\n return input_string[positions[letter]]\n\n return ''\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T15:44:35.033",
"Id": "405156",
"Score": "0",
"body": "I think you're on the right track. What if a defaultdict(int) was also used for initial_positions? This simplifies your line \"if letter not in initial_positions\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T15:57:36.327",
"Id": "405160",
"Score": "0",
"body": "@KevinS well, I think the `initial_positions` has to stay as a regular dictionary as we are only recording the first position of the letter, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:09:27.863",
"Id": "405162",
"Score": "2",
"body": "We only care about characters that have one occurrence, and in particular we only care about the first character that has one occurrence. As a result the initial position for the character we care about will be correct, the others won't, but we don't care that they're not accurate, they're not what we're after"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:13:59.340",
"Id": "405164",
"Score": "1",
"body": "@KevinS yeah, this means that we don't really need the `if letter not in initial_positions` check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:20:44.170",
"Id": "405165",
"Score": "0",
"body": "@KevinS readability wise, I think we are at a good stage. We might though save on memory and think of encoding the position into the `counts` values to avoid storing positions separately in `positions`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:26:37.533",
"Id": "405166",
"Score": "0",
"body": "indeed, I very much like your current solution. Though if we combine positions into counts I think we will get back to my original solution which wasn't as readable and would encounter my two issues with readability I mentioned in my original post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T20:04:33.730",
"Id": "405181",
"Score": "0",
"body": "If we want to be nitpicky: Note that using `lower` with unicode input will not produce the correct results for something like 95% of the world population. Actually it'd be naïve to assume it works 100% of the time for English text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T07:58:02.603",
"Id": "405216",
"Score": "1",
"body": "Excuse me if I'm wrong, but wouldn't `input_string[positions[letter]]` just be the same as `letter`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:02:12.583",
"Id": "405217",
"Score": "0",
"body": "Also, if you replace the `defaultdict` for an `OrderedDict`, you can store the letters and their counts in the order that they first occured in the string. Then you only have to loop over the dictionary instead of the entire string and return the first key that has value 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:26:40.227",
"Id": "405223",
"Score": "0",
"body": "@JAD they are not the same because `letter` is always lower case and `input_string` is not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:27:51.373",
"Id": "405224",
"Score": "0",
"body": "@MattEllen ah right, what a bother :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:29:26.063",
"Id": "405225",
"Score": "1",
"body": "@JAD If `lower ()` wasn't called on the input string, it would. But in any case the `positions` dictionary is unnecessary as you can either lowercase each letter individually to check for its count or use `enumerate` to retrieve the position."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:31:14.250",
"Id": "405226",
"Score": "0",
"body": "@MathiasEttinger so moving the `lower()` to `if counts[letter.lower()] == 1:` could work. I would still advocate looping over the counts though."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T15:31:51.490",
"Id": "209625",
"ParentId": "209622",
"Score": "6"
}
},
{
"body": "<p>Going further from <a href=\"https://codereview.stackexchange.com/a/209625/9452\">alecxe's answer</a>:</p>\n\n<ul>\n<li>you could use the Counter collections instead of performing the counting yourself - I didn't see that this was avoided on purpose.</li>\n<li>you can ensure <code>lower</code> is called only once</li>\n</ul>\n\n<p>You'd get something like:</p>\n\n<pre><code>from collections import Counter\n\ndef non_repeat(input_string):\n lower = input_string.lower()\n count = Counter(lower)\n for c, l in zip(input_string, lower):\n if count[l] == 1:\n return c\n return ''\n</code></pre>\n\n<p>or, for a Counter-less solution:</p>\n\n<pre><code>def non_repeat(input_string):\n lower = input_string.lower()\n count = defaultdict(int)\n for c in lower:\n count[c] += 1\n for c, l in zip(input_string, lower):\n if count[l] == 1:\n return c\n return ''\n</code></pre>\n\n<p>Also, here's a quick test suite I wrote:</p>\n\n<pre><code>tests = [\n ('', ''),\n ('AA', ''),\n ('AAABBB', ''),\n ('AAABBBc', 'c'),\n ('azerty', 'a'),\n ('aazzeerty', 'r'),\n ('azerAZERty', 't'),\n]\n\nfor inp, out in tests:\n assert non_repeat(inp) == out\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:52:40.650",
"Id": "405167",
"Score": "1",
"body": "The question did specifically state that Kevin is avoiding `collections.Counter`, so that's not such a helpful suggestion. The rest makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T17:04:51.473",
"Id": "405168",
"Score": "1",
"body": "@TobySpeight Thanks for spotting this, I completely missed in the the original question. I've updated my answer accordingly but it is not that relevant anymore :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T22:47:49.517",
"Id": "405195",
"Score": "0",
"body": "Is `Counter` still slower than `defaultdict`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T22:53:45.593",
"Id": "405197",
"Score": "0",
"body": "I didn't know it had been the case. I'll try a benchmark if I think about it"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T16:47:27.933",
"Id": "209629",
"ParentId": "209622",
"Score": "5"
}
},
{
"body": "<p>IMHO looping twice over the input string is not acceptable for multiple reasons</p>\n\n<ul>\n<li>the string is of unknown size</li>\n<li>you invalidate your code for generators</li>\n</ul>\n\n<p>While this might not be necessary for your project you should learn to think like that. So a single pass algorithm should collect all necessary data to answer the question (e. g. the letter in original case).</p>\n\n<pre><code>import sys\nassert sys.version_info >= (3, 6)\n\ndef non_repeat(s):\n repeated = set()\n candidates = dict()\n for original_case in s:\n lower_case = original_case.lower()\n if lower_case not in repeated:\n if lower_case not in candidates:\n candidates[lower_case] = original_case\n else:\n repeated.add(lower_case)\n del candidates[lower_case]\n\n if candidates:\n return next(iter(candidates.values()))\n else:\n return ''\n</code></pre>\n\n<p>This code makes use of the insertion order of a dict which is already implemented in 3.6 and guaranteed in 3.7.</p>\n\n<hr>\n\n<p>Edit: generator example</p>\n\n<p>Say you want to check a big file that does not fit into memory (for brevity I assume a line fits into memory). Yor write a little character generator and run your algorithm on the generator.</p>\n\n<pre><code>def char_gen(f):\n for line in f:\n for c in line.strip():\n yield c\n\nwith open('bigfile.txt') as f:\n print(non_repeat(char_gen(f)))\n</code></pre>\n\n<p>also you might use the algorithm on a generator expression</p>\n\n<pre><code>print(non_repeat(c for c in \"aabbcd\" if c != 'c'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:04:07.430",
"Id": "405218",
"Score": "0",
"body": "You could also use `collections.OrderedDict` to make the dependence on the dictionary being ordered more explicit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:21:26.937",
"Id": "405265",
"Score": "0",
"body": "This could be leveraged on versions of python before 3.6 by importing OrderedDict from the collections module and then using an OrderedDict for candidates instead of dict. I like this solution for readability. Can you expand upon your statement \"you invalidate your code for generators\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T21:57:01.600",
"Id": "405310",
"Score": "0",
"body": "Would it make sense to check the length of the string for zero or 1 and just return the argument in that case, to avoid instantiating the collections?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T19:41:53.737",
"Id": "405365",
"Score": "0",
"body": "@phoog I would not introduce complexity unless it is needed. Every extra line may introduce an error. Optimisation is not required for small data but for big data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T20:52:50.083",
"Id": "405372",
"Score": "0",
"body": "@stefan thanks for your comment. I'm coming to this as a .NET programmer whose employer appears to be preparing for a push to increase the use of python. In the .NET world, for a high throughput scenario with a large volume of strings and a high proportion of empty or one-character strings, the reduced garbage collection pressure might indeed be desirable. Would similar considerations not apply here, at least for that use case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T20:58:44.407",
"Id": "405374",
"Score": "0",
"body": "@phoog Measure! When you prove the need, go for the extra lines of code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T19:12:51.147",
"Id": "209631",
"ParentId": "209622",
"Score": "8"
}
},
{
"body": "<p>A version which doesn't use any imports, works on Py2.7+ and relies almost solely on set operations to achieve a single <code>O(len(s))</code> pass + constant time:</p>\n\n<pre><code>def non_repeat(s):\n LEN_CHAR_SET_LOWERED = XXX # length of your char set adjusted for .lower()\n seen_order = [] # Store the order for figuring out which came first\n seen_set = set() # Store whether we've seen the character\n dupe_set = set() # Store whether we've seen it more than once\n\n # Scan the string\n for ch in s:\n chl = ch.lower() # lowered character for seen/dupe sets\n if chl not in seen_set:\n seen_order.append(ch) # This uses the non-lowered version to preserve case\n seen_set.add(chl)\n else:\n dupe_set.add(chl)\n if len(dupe_set) == LEN_CHAR_SET_LOWERED: # Set len is O(1)\n return '' # If dupe set contains all possible characters, exit early\n\n # Find uniques\n unique_set = seen_set - dupe_set\n\n # Find the first one, if any\n if unique_set:\n for ch in seen_order:\n if ch.lower() in unique_set:\n return ch\n return ''\n</code></pre>\n\n<p>Some notes on speed:</p>\n\n<ul>\n<li><p><code>O(len(s))</code> average case, <code>O(1)</code> best case (see early exit) - to build the list/sets - set membership, additions and list appends are all average <code>O(1)</code> operations, worst case <code>O(len(set/list))</code>*</p></li>\n<li><p><code>O(1)</code> - Set difference on average, worst case <code>O(len(set))</code>*</p></li>\n<li><p><code>O(len(list))</code>* for the final check</p></li>\n</ul>\n\n<p>*<code>O(len(list))</code> and <code>O(len(set))</code> both have upper bounds of <code>LEN_CHAR_SET_LOWERED</code>, which means they end up constant time, <code>O(1)</code>, as the string grows</p>\n\n<p>This is also interesting because of the early exit: If your string contains all characters duplicated, it will only scan until it has seen every character at least twice and then exit, knowing there will be no unique characters. An alphanumeric string could exit after scanning as few as 72 characters, regardless of the actual length.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T23:32:44.660",
"Id": "209652",
"ParentId": "209622",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209631",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:56:13.747",
"Id": "209622",
"Score": "10",
"Tags": [
"python",
"python-3.x"
],
"Title": "First non-repeating letter"
} | 209622 |
<p>On looking at the <code>components(separatedBy separator: String) -> [String]</code> method from the <strong>Swift Standard Library</strong>, I tried to come up with an implementation just for practice. Your comments are welcome to improve the same. Thanks.</p>
<hr>
<p><strong>Input:</strong></p>
<pre><code>func main() {
let sampleString = "Do not be sorry. Be better."
print(sampleString.components(separatedBy: "."))
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>["Do not be sorry", " Be better", ""]
</code></pre>
<p><strong>Implementation:</strong></p>
<pre><code>extension StringProtocol {
func components<T>(separatedBy separatorString: T) -> [String] where T: StringProtocol {
var currentIndex = 0; var stringBuffer = ""; var separatedStrings:[String] = []
forEach { (character) in
if String(character) == separatorString {
separatedStrings.append(stringBuffer); stringBuffer = ""
} else {
stringBuffer += .init(character)
}
if currentIndex == lastIndex { separatedStrings.append(stringBuffer) }
currentIndex += 1
}
return separatedStrings
}
}
extension Collection {
var lastIndex:Int {
get {
return self.count - 1
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T13:15:36.590",
"Id": "405405",
"Score": "0",
"body": "Could you please point to the SL implementation of `components(separatedBy separator: String) -> [String]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T08:16:02.647",
"Id": "414543",
"Score": "0",
"body": "@Carpsen90 Sorry I am not able to find it. I just tried to implement out of my own interest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T19:26:56.107",
"Id": "414926",
"Score": "2",
"body": "@Carpsen90 - It’s found in `swift-corelibs-foundation`: https://github.com/apple/swift-corelibs-foundation/blob/6119b3328d65644b0af16baf04ae9ce58559f6bb/Foundation/NSString.swift#L987. When looking for stuff like this, go to the repo in question and then search for [\"func components\"](https://github.com/apple/swift-corelibs-foundation/search?q=%22func+components%22&unscoped_q=%22func+components%22) (with the quotes)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T19:43:37.617",
"Id": "414928",
"Score": "1",
"body": "Martin has answered your questions. But let’s assume for a second that you really did want to advance `currentIndex` yourself. I would not make it an `Int`. I’d also eliminate that `lastIndex` property. Instead, define `startIndex` as `var currentIndex = startIndex`, advance it with `currentIndex = index(after: currentIndex)` and then check if I’m at the end with `if currentIndex == endIndex { ... }`. It’s all moot, as this should be refactored out, as Martin points out, but just a few observations."
}
] | [
{
"body": "<h3>Coding style</h3>\n\n<p>This is of course a matter of personal taste, but would split multiple statements like</p>\n\n<blockquote>\n<pre><code>var currentIndex = 0; var stringBuffer = \"\"; var separatedStrings:[String] = []\n</code></pre>\n</blockquote>\n\n<p>into separate lines </p>\n\n<pre><code>var currentIndex = 0\nvar stringBuffer = \"\"\nvar separatedStrings:[String] = []\n</code></pre>\n\n<p>I would also start new lines for nested code blocks, i.e.</p>\n\n<blockquote>\n<pre><code>if currentIndex == lastIndex { separatedStrings.append(stringBuffer) }\n</code></pre>\n</blockquote>\n\n<p>becomes</p>\n\n<pre><code>if currentIndex == lastIndex {\n separatedStrings.append(stringBuffer)\n}\n</code></pre>\n\n<h3>Correctness</h3>\n\n<p>Your function takes a separator of type <em>string (protocol)</em> as an argument, but actually works only for separators consisting of a single character. Example:</p>\n\n<pre><code>let sampleString = \"Do not be sorry. Be better.\"\nprint(sampleString.components(separatedBy: \". \"))\n// [\"Do not be sorry. Be better.\"]\n</code></pre>\n\n<p>The reason is that here</p>\n\n<blockquote>\n<pre><code>if String(character) == separatorString\n</code></pre>\n</blockquote>\n\n<p>a single character of the source string is compared with the separator.</p>\n\n<p>Your method also behaves differently from the standard library version when called with an empty string, </p>\n\n<pre><code>\"\".components(separatedBy: \".\")\n</code></pre>\n\n<p>returns an empty array <code>[]</code> instead of a single-element array <code>[\"\"]</code>. The reason is that the check</p>\n\n<blockquote>\n<pre><code>if currentIndex == lastIndex { separatedStrings.append(stringBuffer) }\n</code></pre>\n</blockquote>\n\n<p>is never done for an empty input string. (Checking for the last iteration <em>inside</em> a loop always makes me suspicious.)</p>\n\n<h3>Simplifications</h3>\n\n<p>Instead of converting a character to a string for appending</p>\n\n<blockquote>\n<pre><code>stringBuffer += .init(character)\n</code></pre>\n</blockquote>\n\n<p>you can append it directly:</p>\n\n<pre><code>stringBuffer.append(character)\n</code></pre>\n\n<p>Keeping track of the current character position can be done with\n<code>enumerated()</code></p>\n\n<pre><code>for (currentIndex, character) in self.enumerated() {\n // ...\n}\n</code></pre>\n\n<p>instead of incrementing <code>var currentIndex</code>.</p>\n\n<h3>Efficiency</h3>\n\n<p>The main bottleneck is the</p>\n\n<pre><code>var lastIndex:Int\n</code></pre>\n\n<p>extension method. For Strings (and other collections which are not random accessible) determining <code>self.count</code> is a O(N) operation (N = number of characters). It requires traversing the entire string.</p>\n\n<p>This method is called for each character in the source string, so that this contributes O(N^2) to the execution time.</p>\n\n<p>It would also be more efficient to locate the next occurrence of the separator and append an entire substring to the result array, instead of appending single characters repeatedly.</p>\n\n<h3>Alternative implementation</h3>\n\n<p>Here is an alternative implementation, considering the above suggestions:</p>\n\n<pre><code>func components<T>(separatedBy separatorString: T) -> [String]\n where T: StringProtocol, Index == String.Index {\n var separatedStrings: [String] = []\n var pos = startIndex\n while let range = self[pos...].range(of: separatorString) {\n separatedStrings.append(String(self[pos..<range.lowerBound]))\n pos = range.upperBound\n }\n separatedStrings.append(String(self[pos...]))\n return separatedStrings\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T10:29:36.803",
"Id": "405804",
"Score": "0",
"body": "@Carpsen90: I doubt it. I *assume* that the subscript transforms `pos...` to `pos..<endIndex` using [this](https://github.com/apple/swift/blob/master/stdlib/public/core/Range.swift#L582) method, so there should be no difference. – See also https://github.com/apple/swift-evolution/blob/master/proposals/0172-one-sided-ranges.md#detailed-design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T10:40:48.763",
"Id": "405805",
"Score": "0",
"body": "Thanks. I had a faint doubt that *that* transformation would cost some extra work, either at compile or run times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-04T15:39:58.450",
"Id": "407675",
"Score": "0",
"body": "Thank you so much for your review, @MartinR! "
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T22:46:32.627",
"Id": "209647",
"ParentId": "209643",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209647",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T21:54:28.090",
"Id": "209643",
"Score": "1",
"Tags": [
"algorithm",
"swift",
"complexity"
],
"Title": "Implementing `components(separatedBy:)` method in Swift"
} | 209643 |
<p>This is my first React/Redux project. I'm pulling down a list of Google Fonts, then displaying a list of 3 randomly selected ones. I want the list of random fonts to be populated automatically after the data is fetched, but also to be able to be triggered manually. </p>
<p>So, I've decided to put the fetch code in the action creator and the randomizing code in the component. The fetch is activated from <code>componentWillMount()</code> while the randomizing function is called from <code>componentDidUpdate()</code>. </p>
<p>This is the only combination I was able to come up with that works without any errors, but it sure looks janky. Is this considered acceptable?</p>
<pre><code>import React, { Component } from 'react';
import Font from './Font';
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import WebFont from 'webfontloader';
import { fetchFonts, setRandomFonts } from '../actions/fontActions'
export class Fonts extends Component {
static propTypes = {
allFonts: PropTypes.array,
randomFonts: PropTypes.array.isRequired,
sampleSentence: PropTypes.string.isRequired,
categoriesWanted: PropTypes.array.isRequired,
fontCount: PropTypes.number.isRequired,
fetchFonts: PropTypes.func.isRequired
}
componentWillMount() {
this.props.fetchFonts();
}
componentDidUpdate() {
if (this.props.randomFonts.length === 0) {
this.randomizeFonts();
}
}
getRandomFont = arr => arr[this.random(arr.length) - 1];
random = max => Math.floor(Math.random() * max) + 1;
randomizeFonts = () => {
const { categoriesWanted, fontCount, allFonts } = this.props;
const fontList = [];
if (allFonts.length === 0) return;
while (fontList.length < fontCount) {
const font = this.getRandomFont(allFonts);
// add the font if it's the right category and it's not
// already in the list
if (categoriesWanted.includes(font.category)
&& !fontList.includes(font)) {
fontList.push(font);
}
}
WebFont.load({
google: {
families: fontList.map(font => font.family)
}
});
this.props.setRandomFonts(fontList);
}
render() {
return (
<div className="container">
{this.props.randomFonts.map(
font => (<Font
key={font.family}
font={font}
sampleSentence={this.props.sampleSentence}
/>)
)}
</div>
)
}
}
const mapStateToProps = state => ({
allFonts: state.fonts.allFonts,
randomFonts: state.fonts.randomFonts,
sampleSentence: state.fonts.sampleSentence,
categoriesWanted: state.fonts.categoriesWanted,
fontCount: state.fonts.fontCount
});
export default connect(mapStateToProps, { fetchFonts, setRandomFonts })(Fonts);
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T21:56:38.197",
"Id": "209644",
"Score": "1",
"Tags": [
"react.js",
"jsx",
"redux"
],
"Title": "In React/Redux, fetch a list from a server and create a randomized subset with lifecycle methods"
} | 209644 |
<blockquote>
<h1>The task:</h1>
<p>You will be given several lines of messages containing data. You have
to check for the validity of the lines. A valid line should be in the
format: <code>""s:{sender};r:{receiver};m--"{message}"</code></p>
<ul>
<li><code>sender</code> – could contain any ASCII character except for <code>;</code></li>
<li><code>receiver</code> – could contain any ASCII character except for <code>;</code></li>
<li><code>message</code> – should contain only letters and spaces</li>
</ul>
<p>In each valid message there is a hidden size of data transfer. The
size of the data transfer is calculated by the sum of all digits in
the names of the sender and receiver. After each valid message print a
line in the format: <code>"{senderName} says "{currentMessage}" to
{recieverName}"</code>. The printed names should contain only letters and
spaces.</p>
<p>Example: sender <code>"P@e$5sh#o Go^4sh5ov"</code> is valid and matches, but when
printing his name, we only print "Pesho Goshov". At the end print a
line in the format "Total data transferred: {totalData}MB".</p>
</blockquote>
<h3>Example 1</h3>
<pre>
=== Input ===
3
s:P5%es4#h@o;r:G3#o!!s2h#2o;m--"Attack"
s:G3er%6g43i;r:Kak€$in2% re3p5ab3lic%an;m--"I can sing"
s:BABAr:Ali;m-No cave for you
=== Output ===
Pesho says "Attack" to Gosho
Gergi says "I can sing" to Kakin repablican
Total data transferred: 45MB
</pre>
<h3>Example 2</h3>
<pre>
=== Input ===
5
s:B^%4i35454l#$l;r:Mo5l#$34l%y;m--"Run"
s:Ray;r:To^^5m;m--"Hidden Message"
bla;r:1234a;m--Hello
s:M#$%$#^6767687654545e;r:Yo54$#@#u5;m--"$$$"
s:M#$@545e;r:You241$@#23;m"Hello"
=== Output ===
Bill says "Run" to Molly
Ray says "Hidden Message" to Tom
Total data transferred: 42MB
</pre>
<h3>My Solution</h3>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
class Program
{
class MessageInfo
{
public bool isOk = true;
public int messageSize;
string sender;
string reciver;
public string Sender
{
get
{
return Regex.Replace(sender, @"\s+", " ");
}
set
{
StringBuilder temp = new StringBuilder();
foreach (var c in value)
{
if (Char.IsDigit(c))
{
messageSize += (c - '0');
}
if (Char.IsLetter(c) || Char.IsWhiteSpace(c))
{
temp.Append(c);
}
}
sender = temp.ToString();
}
}
public string Reciver
{
get
{
return Regex.Replace(reciver, @"\s+", " ");
}
set
{
StringBuilder temp = new StringBuilder();
foreach (var c in value)
{
if (Char.IsDigit(c))
{
messageSize += (c - '0');
}
if (Char.IsLetter(c) || Char.IsWhiteSpace(c))
{
temp.Append(c);
}
}
reciver = temp.ToString();
}
}
public string Message { get; set; }
}
static void Main()
{
int n = int.Parse(Console.ReadLine());
int totalMessageSize = 0;
MessageInfo[] chatLog = new MessageInfo[n];
for (int i = 0; i < n; i++)
{
string line = Console.ReadLine();
chatLog[i] = CoreAction(line);
if (chatLog[i].isOk)
{
totalMessageSize += chatLog[i].messageSize;
}
}
for (int i = 0; i < chatLog.Length; i++)
{
if (chatLog[i].isOk)
{
Console.WriteLine("{0} says \"{1}\" to {2}", chatLog[i].Sender, chatLog[i].Message, chatLog[i].Reciver);
}
}
Console.WriteLine("Total data transferred: {0}MB",totalMessageSize);
}
private static MessageInfo CoreAction(string line1)
{
MessageInfo a = new MessageInfo();
int indexer = 0;
StringBuilder sender = new StringBuilder();
StringBuilder reciver = new StringBuilder();
StringBuilder message = new StringBuilder();
Regex matchLine = new Regex("^s:[^;]+;r:[^;]+;m--\"[\\w\\s]+\"$");
if (matchLine.IsMatch(line1))
{
lineSplitter(line1, ref indexer, ref sender, ref reciver, ref message);
}
else
{
a.isOk = false;
}
a.Sender = sender.ToString();
a.Reciver = reciver.ToString();
a.Message = message.ToString();
return a;
}
private static void lineSplitter(string line1, ref int indexer, ref StringBuilder sender, ref StringBuilder reciver, ref StringBuilder message)
{
while (true)
{
if (line1[indexer + 1] == ':')
{
if (line1[indexer] == 's')
{
sender = stringFill(line1, ref indexer, 2, ';');
}
if (line1[indexer] == 'r')
{
reciver = stringFill(line1, ref indexer, 2, ';');
}
}
if (line1[indexer] == 'm' && line1[indexer + 1] == '-' &&
line1[indexer + 2] == '-' && line1[indexer + 3] == '"')
{
message = stringFill(line1, ref indexer, 4, '"');
}
if (indexer >= line1.Length - 1)
{
break;
}
indexer++;
}
}
private static StringBuilder stringFill(string line1, ref int indexer, int offSet, char charBreak)
{
StringBuilder temp = new StringBuilder();
indexer += offSet;
while (line1[indexer] != charBreak)
{
temp.Append(line1[indexer]);
indexer++;
}
return temp;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T23:03:37.877",
"Id": "405318",
"Score": "0",
"body": "This looks like it was copied directly from an exam published by a school in Bulgaria. Is that where you found it, @Cecobent?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T23:17:23.623",
"Id": "405383",
"Score": "0",
"body": "Yes,all the credit for the task condition goes to \"SoftUni\", **but the solution is solely mine.**"
}
] | [
{
"body": "<p>We are using regular expressions to recognise the valid message but then manually extracting the values.</p>\n\n<p>If we change the regex pattern to <code>^s:([^;]+);r:([^;]+);m--\\\"([\\\\w\\\\s]+)\\\"$</code> we can use the groups with the regex (the parentheses indicate the groups)</p>\n\n<ul>\n<li>The sender is match.Groups[1].Value</li>\n<li>The receiver is match.Groups[2].Value</li>\n<li>The message is match.Groups[3].Value</li>\n</ul>\n\n<p>We can be a bit fancier if desired and use named groups <code>^s:(?<sender>[^;]+);r:(?<receiver>[^;]+);m--\\\"(?<message>[\\\\w\\\\s]+)\\\"$</code></p>\n\n<ul>\n<li>The sender is match.Groups[\"sender\"].Value</li>\n<li>The receiver is match.Groups[\"receiver\"].Value</li>\n<li>The message is match.Groups[\"message\"].Value</li>\n</ul>\n\n<p>We can simplify things an amount by placing all the active code in the validation/parsing piece and using the <code>MessageInfo</code> so hold the results.\nIf we ever need to make changes, we now have them all localized to <code>ProcessLine</code> not split between <code>CoreAction/lineSplitter</code> and the <code>MessageInfo</code> class</p>\n\n<p><strong>e.g.</strong></p>\n\n<pre><code>private class MessageInfo\n{\n public MessageInfo(string sender, string receiver, string message, int score)\n {\n Sender = sender;\n Receiver = receiver;\n Message = message;\n Score = score;\n }\n public string Sender { get; }\n public string Receiver { get; }\n public string Message { get; }\n public int Score { get; }\n}\n\n\n\nstatic void Main(string[] args)\n{\n var count = int.Parse(System.Console.ReadLine());\n var total = 0;\n for(var index = 0; index < count; index++)\n {\n var info = ProcessLine(System.Console.ReadLine());\n if (info == null) continue;\n total += info.Score;\n System.Console.WriteLine($@\"{info.Sender} says \"\"{info.Message}\"\" to {info.Receiver}\");\n }\n System.Console.WriteLine($\"Total data transferred: {total}MB\");\n\n}\n\nprivate const string Pattern = @\"^s:(?<sender>[^;]+);r:(?<receiver>[^;]+);m--\"\"(?<message>[\\w\\s]+)\"\"$\";\nprivate readonly static Regex Regex = new Regex(Pattern);\n\nprivate static MessageInfo ProcessLine(string line)\n{\n var match = Regex.Match(line);\n if (!match.Success) return null;\n\n var score = 0;\n var sender = CleanName(match.Groups[\"sender\"].Value, ref score);\n var receiver = CleanName(match.Groups[\"receiver\"].Value, ref score);\n\n return new MessageInfo(sender, receiver, match.Groups[\"message\"].Value, score);\n}\n\nprivate static string CleanName(string input, ref int score)\n{\n var builder = new StringBuilder();\n foreach (var ch in input)\n {\n if (char.IsDigit(ch))\n {\n score += ch - '0';\n continue;\n }\n if (char.IsLetter(ch) || ch == ' ')\n {\n builder.Append(ch);\n }\n }\n return builder.ToString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:26:45.147",
"Id": "209896",
"ParentId": "209649",
"Score": "3"
}
},
{
"body": "<p><strong>I can tell you're concerned about performance</strong> (and not just because of the tag on the question). This is a good impulse, because it helps you avoid selecting terribly inefficient algorithms. But it can also hurt, when it leads you to micromanage details that would be better left to (for example) a regular expression engine.</p>\n\n<p><strong>You have some good habits.</strong> I love to see <code>foreach</code> loops. I'm very glad that you used a <code>StringBuilder</code> rather than just the <code>+</code> operator. Putting sanitization logic in the public setter for a property so that you can maintain a \"clean\" private backing field is a great idea.</p>\n\n<p><strong>Passing <code>ref</code> parameters</strong> generally makes code more difficult to maintain. In fact, I'll go farther than that: Anything that increases the scope of a variable usually makes code more difficult to maintain. Imagine I'm reading your <code>lineSplitter</code> function, I've never seen it before, and I'm in a big hurry because there's a bug in the company's legacy chat log parsing program that's costing us thousands of dollars for every minute it's down. <em>I can't tell</em> what I am and am not allowed to change with how the <code>indexer</code> variable is treated, without reading other functions. I can't tell what it will be when it's passed in, I can't tell how it will change when I pass it to <code>stringFill</code>, and I don't know if I'll break anything in <code>CoreAction</code> if I change its value within <code>lineSplitter</code>.</p>\n\n<p>Now, the fact that you've made all three of those functions private is a big help - I can be sure that there are no other places in the codebase that I might be breaking with edits to <code>lineSplitter</code>. But it would still be vastly preferable to find an approach that doesn't require <code>ref</code> variables at all.</p>\n\n<p><strong>An object should always be valid.</strong> Take this contrived example:\n</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public class Foo\n{\n public string Value;\n public int Length()\n {\n return value.Length;\n }\n}\n\n// elsewhere\nvar a = new Foo();\na.Value = \"hello\";\nConsole.WriteLine(a.Length()); // Prints \"5\"\n\nvar b = new Foo();\nConsole.WriteLine(b.Length()); // Error!\n</code></pre>\n\n<p>I've heard this called \"temporal coupling\". It's unfriendly because there's no warning that I <em>can't</em> call <code>Length()</code> on an invalid object - just the error when I try. My favorite approach to provide that warning is by required constructor arguments; simply don't allow invalid objects to exist.\n</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public class Foo\n{\n public string Value { get; } // no \"set\" -> must be assigned at construction\n\n /// <param name=\"value\">\n /// The value used for <see cref=\"Length()\"/>. Cannot be null.\n /// </param>\n public Foo(string value)\n {\n Value = value ?? throw new ArgumentNullException(\"Foo requires a non-null value\");\n }\n\n public int Length()\n {\n return Value.Length;\n }\n}\n\n// elsewhere\nvar a = new Foo(\"hello\");\nConsole.WriteLine(a.Length()); // Prints \"5\"\n\nvar b = new Foo(); // Doesn't compile\n\nvar c = new Foo(null); // *Immediate* feedback\n</code></pre>\n\n<p>Why am I ranting about this? It applies to your strategy of creating a list of MessageInfo objects, only some of which are valid. That works, so long as you <em>always remember to check</em>. I would much rather see the invalid input lines completely filtered out.</p>\n\n<p><strong>String.Join is often nicer than StringBuilder,</strong> in the same way Linq is often nicer than a for- or foreach-loop. A <code>StringBuilder</code> generally requires four lines of code:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>var builder = new StringBuilder();\nforeach (var w in words)\n builder.Append(w + \" \");\nreturn builder.ToString()\n</code></pre>\n\n<p>Whereas <code>string.Join</code> (which has similar performance characteristics), often requires only one (or perhaps two for readability):</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>return string.Join(\" \", words);\n</code></pre>\n\n<p><strong>Regex Capture Groups</strong> are your friends, as Alan T pointed out. <a href=\"http://rubular.com/r/EcwWznsfu4\" rel=\"nofollow noreferrer\">Here's a demo</a> you can play around with and see live results (That site uses the Ruby regex engine rather than the .NET regex engine, but the differences are minor enough that you can ignore them here).</p>\n\n<p><strong>Linq is a beautiful library</strong> in C# for transforming sequences, with extension functions on <code>IEnumerable</code> like <code>Select(mapper)</code>, <code>Where(filter)</code>, and <code>ToList()</code>. To me, this task is <em>begging</em> for the application of Linq. My solution uses <code>foreach</code> in 1 place, Linq in 5 places, and 0 <code>for</code>s or <code>while</code>s. I'll show you more below.</p>\n\n<p><strong>Separate classes to hold separate logic.</strong> You've already done some of this; I would take it even further. Here's how I sliced it all up:</p>\n\n<ul>\n<li>A <code>Program</code> class to hold <code>Main</code> (and almost nothing else)</li>\n<li>A <code>ChatLog</code> class to hold the messages and drive the validation/parsing</li>\n<li>A <code>LineParser</code> class to validate each line, and construct a <code>ChatMessage</code></li>\n<li>A <code>ChatMessage</code> class to hold each message's info</li>\n<li>A <code>NameParser</code> class to calculate payload sizes, and sanitize names</li>\n</ul>\n\n<p><strong>An outline of my solution</strong> - brace yourself, because I may have gone a little too far (but I'll let you be the judge):\n</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>// Program - \"build these objects, then ask them questions\"\npublic class Program\n{\n static void Main()\n {\n var log = new ChatLog(Console.ReadLine);\n foreach (var message in log.Messages)\n {\n Console.WriteLine($@\"{message.Sender} says \"\"{message.Message}\"\" to {message.Receiver}\");\n }\n Console.WriteLine($\"Total data transferred: {log.TotalPayloadSize}MB\");\n }\n}\n</code></pre>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>using System.Collections.Generic;\nusing System.Linq;\n\n// ChatLog - \"Filter bad lines, build ChatMessages, and summarize\"\npublic class ChatLog\n{\n public IEnumerable<ChatMessage> Messages { get; }\n public int TotalPayloadSize { get; }\n\n public ChatLog(Func<string> readLine)\n {\n var numberOfLines = int.Parse(readLine())\n var lines = Enumerable // My Linq approach to avoid a foreach loop:\n .Range(1, numberOfLines) // Generate a sequence of N integers\n .Select(_ => readLine()) // Replace each integer with a string from the input\n\n Messages = Parse(lines);\n TotalPayloadSize = Messages.Sum(message => message.PayloadSize);\n }\n\n private List<ChatMessages> Parse(IEnumerable<string> lines)\n {\n // Here I used Linq to\n // transform each line to a LineParser object (Select)\n // filter out invalid lines (Where)\n // transform each remaining LineParser to a ChatMessage (Select)\n // return a list, to avoid the multiple enumeration trap (ToList)\n }\n}\n</code></pre>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>// LineParser - \"Filter out junk and calculate size\"\npublic class LineParser\n{\n public bool Success { get; }\n\n private ChatMessage _message;\n public ChatMessage Message => _message ?? throw new InvalidOperationException(\"Line could not be parsed\");\n\n private static Regex _format { get; } = new Regex(\"...\");\n public LineParser(string line)\n {\n Success = match.Success;\n\n if (Success)\n {\n // set the _message variable to a new ChatMessage from on match.Groups\n }\n }\n}\n</code></pre>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>// ChatMessage - \"Hold\"\npublic class ChatMessage\n{\n public int PayloadSize { get; }\n public string Sender { get; }\n public string Receiver { get; }\n public string Message { get; }\n\n public ChatMessage(string rawSender, string rawReceiver, string message)\n {\n // Construct two NameParsers, and set field values\n }\n}\n</code></pre>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>// NameParser - \"Filter out junk and calculate size\"\npublic class NameParser\n{\n public string CleanName { get; }\n public int PayloadSize { get; }\n\n public NameParser(string rawName)\n {\n // set field values\n }\n\n private int SumOfDigitCharacters(string rawName)\n {\n // Here I used Linq to\n // transform rawName to an array of characters\n // filter out non-digit characters\n // transform each digit character to an int\n // sum them\n }\n\n private static Regex _letterOrSpace { get; } = new Regex(\"...\");\n private string StripNonAlphaCharacters(string rawName)\n {\n var lettersAndSpaces = // Here I used Linq to\n // transform rawName to an array of chars\n // filter out invalid chars\n\n return string.Join(\n separator: string.Empty,\n values: lettersAndSpaces);\n }\n}\n</code></pre>\n\n<p><strong>Why so many classes?</strong> It might look awkward, but it's hugely valuable in terms of testability. The same goes for the <code>Func<string></code> parameter to <code>ChatLog</code> - it feels strange but it allows <code>ChatLog</code> to be completely independent of <code>Console</code>, which is a big win. This means that I can create a suite of unit tests automatically verifying the behavior of the program without manually inspecting what was printed to the console after each run of the program. For example:</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>[TestClass]\npublic class NameParserTests\n{\n [TestMethod]\n public void NameParser_CalculatesSizeCorrectly()\n {\n var testCases = new List<(string rawName, int expectedSize)>\n {\n (\"s1ender\", 1),\n (\"sen2d3r\", 5),\n (\"s123der\", 6),\n (\"s10nd11\", 3),\n };\n\n foreach (var (rawName, expectedSize) in testCases)\n {\n var parser = new NameParser(rawName);\n Assert.AreEqual(expectedSize, parser.PayloadSize, $\"'{rawName}' should have a payload of size {expectedSize}, not {parser.PayloadSize}\");\n }\n }\n}\n</code></pre>\n\n<p>Now that I've verified the behavior of <code>NameParser</code> directly, I don't need to worry about it in any of my other tests. If I make any changes, I can run all of my tests again in a matter of seconds. If there are any problems, the tests immediately show what went wrong.</p>\n\n<p><strong>A final note about performance.</strong> The three situations where you should be concerned about code performance, in my opinion, are these:</p>\n\n<ul>\n<li>You know your code that will be called thousands of times per second in a tight loop</li>\n<li>You are entering a coding competition where you will be judged on speed</li>\n<li>You have noticed performance problems in your application</li>\n</ul>\n\n<p>Short of those situations, the <em>maintainability</em> of your code is far more important than the speed. <em>I don't know</em> whether my solution is faster than yours, but</p>\n\n<ul>\n<li>If it is, I'll bet it's too small of a difference for a human to notice</li>\n<li>If there's a bug, I'd rather be troubleshooting the one with unit tests</li>\n<li>When the requirements change, I'd rather be expanding the one with unit tests</li>\n</ul>\n\n<p><strong>I've gone on long enough</strong>, so I'll spare you any more preaching about Separation of Concerns and Unit Testing. Let me just include some snippets from my other tests:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>// NameParser should sanitize like this\n(\"sender\", \"sender\"),\n(\"SENDER\", \"SENDER\"),\n(\"S12end3456er\", \"Sender\"),\n(\"@$s e^&*\", \"s e\"),\n\n// LineParser should reject these\n\"\",\n\"asdf\",\n\"s:sender;r:receiver;m:\\\"message\\\"\",\n\"s:sender;r:receiver;m-\\\"message\\\"\",\n\"s:sender;r:receiver;m--\\\"message\",\n\"s:sender; r:receiver;m--\\\"message\\\"\",\n\"s:sender;r:receiver; m--\\\"message\\\"\",\n\"s:sen;er;r:receiver;m--\\\"message\\\"\",\n\"s:sender;r:rece;iver;m--\\\"message\\\"\",\n\"s:sender;r:receiver;m--\\\"me55age\\\"\",\n\"s:sender;r:receiver;m--\\\"mess@ge\\\"\",\n\"s:sender;r:receiver;m--\\\"mess;ge\\\"\",\n\"s:sender;r:receiver;m--\\\"mes\\\"ge\\\"\",\n\" s:sender;r:receiver;m--\\\"message\\\"\",\n\"s:sender;r:receiver;m--\\\"message\\\" \",\n\n// LineParser should accept these\n\"s:sender;r:receiver;m--\\\"message\\\"\",\n\"s:SENDER;r:receiver;m--\\\"message\\\"\",\n\"s:123456;r:receiver;m--\\\"message\\\"\",\n\"s:@$ ^&*;r:receiver;m--\\\"message\\\"\",\n\"s:sender;r:receiver;m--\\\"message\\\"\",\n\"s:sender;r:RECEIVER;m--\\\"message\\\"\",\n\"s:sender;r:12345678;m--\\\"message\\\"\",\n\"s:sender;r:!@#$ ^&*;m--\\\"message\\\"\",\n\"s:sender;r:receiver;m--\\\"THIS is a MESSAGE\\\"\",\n\n// Helper function to test ChatLog\nprivate Func<string> Enumerate(params string[] lines)\n{\n var enumerator = lines.GetEnumerator();\n\n return () => enumerator.MoveNext()\n ? (string)enumerator.Current\n : throw new InvalidOperationException($\"There were only {lines.Length} lines of input!\");\n}\n\n// Helper function usage:\nvar log = new ChatLog(Enumerate(\n \"3\",\n \"s:P5%es4#h@o;r:G3#o!!s2h#2o;m--\\\"Attack\\\"\",\n \"s:G3er%6g43i;r:Kak€$in2% re3p5ab3lic%an;m--\\\"I can sing\\\"\",\n \"s:BABAr:Ali;m-No cave for you\"));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:23:17.873",
"Id": "209948",
"ParentId": "209649",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209948",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T22:55:39.637",
"Id": "209649",
"Score": "3",
"Tags": [
"c#",
"performance",
"programming-challenge"
],
"Title": "Data Transfer Task"
} | 209649 |
<p>I wrote my first project in Python and I would like to know if this is correct. I prepared some guidelines I want to ask. (<strong>I know that I don't have any documentation yet</strong>). In the future I want to extend my project about new algorithms such as search, crypto, machine learning, hashes, graphs and so on. Also, I would like to add some data structures. For easier review I can share my files if needed. </p>
<ol>
<li>Is my code compatible with PEP8?</li>
<li>Is my code compatible with ZenOfPython?</li>
<li>Is my code compatible with OOP?</li>
<li>Is my code easy to expand? (Extended with new algorithms and classes) </li>
<li>Is my code readable?</li>
<li>Are my subclasses easy to build for testcases?</li>
<li>Are my unit tests correct (don't really know what I should ask about)?</li>
<li>Should I use some design patterns in such a project? </li>
</ol>
<p><strong>initiate.py</strong></p>
<pre><code>from dsal.algorithm_list import algorithms
class Initiate:
def __init__(self, algorithm_name, **kwargs):
self.algorithm_name = algorithm_name
self.result = {}
self.args = kwargs
@staticmethod
def get_algorithm(name):
algorithm = None
for key, alg in algorithms.items():
if name in key:
algorithm = alg
break
if algorithm is None:
raise TypeError('Algorithm not defined !')
return algorithm
def set_params(self, name):
algorithm, params = Initiate.get_algorithm(name), dict()
for k, v in algorithm.check_params(self).items():
val = self.args.get(k, None)
if val is not None and v(val):
params[k] = val
return algorithm(**params)
def run(self):
algorithm = self.set_params(self.algorithm_name)
return algorithm.run()
def run_time(self):
algorithm = self.set_params(self.algorithm_name)
return algorithm.time_task()
</code></pre>
<p><strong>algorithm_list.py</strong></p>
<pre><code>from dsal.algorithms.sorting.simple_sort.bubble_sort import bubble_sort
algorithms = {"BubbleSortV1": bubble_sort.BubbleSortV1,
"BubbleSortV2": bubble_sort.BubbleSortV2}
</code></pre>
<p><strong>allgorithms\sorting\simple_sort\bubble_sort\bubble_sort.py</strong></p>
<pre><code>from dsal.core.algorithms.sorting.simple_sort import SimpleSort
class BubbleSortV1(SimpleSort):
def run_task(self):
# setting up variables
length = len(self.container)
changed = True
while changed:
changed = False
for i in range(length - 1):
if self.container[i] > self.container[i + 1]:
self.container[i], self.container[i + 1] = self.container[i + 1], self.container[i]
changed = True
length -= 1
return self.container
class BubbleSortV2(SimpleSort):
def run_task(self):
# setting up variables
length = len(self.container)
while length >= 1:
changed_times = 0
for i in range(1, length):
if self.container[i - 1] > self.container[i]:
self.container[i - 1], self.container[i] = self.container[i], self.container[i - 1]
changed_times = i
length = changed_times
return self.container
</code></pre>
<p><strong>core\algorithms\algorithm.py</strong></p>
<pre><code>import time
class Algorithm:
def __init__(self, **kwargs):
self.set_params(**kwargs)
def set_params(self, **kwargs):
pass
def check_params(self, **kwargs):
pass
def run_task(self):
return None
def time_task(self):
t1 = time.time()
self.run_task()
t2 = time.time()
return (t2 - t1) * 1000
def run(self):
return self.run_task()
</code></pre>
<p><strong>core\algorithms\simple_sort\simple_sort.py</strong></p>
<pre><code>from dsal.core.algorithms.algorithm import Algorithm
class SimpleSort(Algorithm):
def set_params(self, **kwargs):
self.container = kwargs["container"]
def check_params(self):
return {
'container': lambda x: isinstance(x, list)
}
def run_task(self):
return None
</code></pre>
<p><strong>tests\run_tests.py</strong></p>
<pre><code>import unittest
if __name__ == '__main__':
testsuite = unittest.TestLoader().discover('./algorithms')
for test in testsuite:
unittest.TextTestRunner(verbosity=3).run(test)
</code></pre>
<p><strong>tests\algorithms\test.py</strong></p>
<pre><code>from unittest import TestCase
from dsal.core.algorithms.algorithm import Algorithm
class AlgorithmBaseTestCase(TestCase):
def setUp(self):
self.algorithm = Algorithm()
def test_run(self):
self.assertEqual(self.algorithm.run(), None)
def test_run_task(self):
self.assertEqual(self.algorithm.run_task(), None)
def test_time_task(self):
self.assertEqual(self.algorithm.time_task(), 0.0)
def test_set_params(self):
self.assertEqual(self.algorithm.set_params(), None)
self.assertEqual(self.algorithm.set_params(container=[1, 2, 3, 4]), None)
def test_check_params(self):
self.assertEqual(self.algorithm.set_params(), None)
self.assertEqual(self.algorithm.set_params(container=[1, 2, 3, 4]), None)
class AlgorithmTestCase(TestCase):
def algorithm_run_test(self, algorithm):
return algorithm.run()
</code></pre>
<p><strong>tests\algorithm\sorting\test.py</strong></p>
<pre><code>from tests.algorithms.test import AlgorithmTestCase
class SortTestCase(AlgorithmTestCase):
def setUp(self):
super(AlgorithmTestCase, self).setUp()
def _test_sort_single_func(self, input_list, **kwargs):
expected_list = sorted(input_list)
result = AlgorithmTestCase.algorithm_run_test(self, self.function_name(**kwargs))
self.assertEqual(result, expected_list)
</code></pre>
<p><strong>tests\algorithms\sorting\simple_sort\tests.py</strong></p>
<pre><code>from dsal.algorithms.sorting.simple_sort.bubble_sort.bubble_sort import BubbleSortV1
from tests.algorithms.sorting.test import SortTestCase
class SimpleSortTestCase(SortTestCase):
def setUp(self):
self.function_name = BubbleSortV1
super(SortTestCase, self).setUp()
def test_sort_empty_list(self):
input_list = []
self._test_sort_single_func(input_list, container = sorted(input_list))
def test_sort_one_element(self):
input_list = [0]
self.container = input_list
self._test_sort_single_func(input_list, container = sorted(input_list))
def test_sort_same_numbers(self):
input_list = [1, 1, 1, 1]
self.container = input_list
self._test_sort_single_func(input_list, container = sorted(input_list))
def test_sort_already_sorted(self):
input_list = [1, 2, 3, 4]
self.container = input_list
self._test_sort_single_func(input_list, container = sorted(input_list))
def test_sort_reversed(self):
input_list = [4, 3, 2, 1]
self.container = input_list
self._test_sort_single_func(input_list, container = sorted(input_list))
def test_sort_disorder_with_repetitions(self):
input_list = [3, 5, 3, 2, 4, 2, 1, 1]
self.container = input_list
self._test_sort_single_func(input_list, container = sorted(input_list))
</code></pre>
<p><strong>tests\algorithms\sorting\simple_sort\bubble_sort</strong></p>
<pre><code>from dsal.algorithms.sorting.simple_sort.bubble_sort.bubble_sort import BubbleSortV1, BubbleSortV2
from tests.algorithms.sorting.simple_sort.test import SimpleSortTestCase
class BubbleSortV1TestCase(SimpleSortTestCase):
def test_bubble_sort_v1(self):
self.function_name = BubbleSortV1
super(SimpleSortTestCase, self).setUp()
class BubbleSortV2TestCase(SimpleSortTestCase):
def test_bubble_sort_v2(self):
self.function_name = BubbleSortV2
super(SimpleSortTestCase, self).setUp()
</code></pre>
| [] | [
{
"body": "<pre><code> algorithm = None\n for key, alg in algorithms.items():\n if name in key:\n algorithm = alg\n break\n if algorithm is None:\n raise TypeError('Algorithm not defined !')\n return algorithm\n</code></pre>\n\n<p>A few things, here. First of all, are you sure you want to be doing substring searching through the keys of a dictionary? Shouldn't you just do regular key lookup on algorithm name?</p>\n\n<p>Don't name your key \"key\". If it's an algorithm name, call it \"alg_name\" or something.</p>\n\n<p>Also, you can simplify your return logic. Something like:</p>\n\n<pre><code>try:\n return algorithms[name]\nexcept KeyError:\n raise TypeError('Algorithm not defined !')\n</code></pre>\n\n<p>For this line:</p>\n\n<pre><code>val = self.args.get(k, None)\n</code></pre>\n\n<p><code>None</code> is the default anyway, so you can simply write <code>val = self.args.get(k)</code>.</p>\n\n<p>For this:</p>\n\n<pre><code>for k, v in algorithm.check_params(self).items():\n</code></pre>\n\n<p>Apparently <code>v</code> is callable, but you wouldn't know by looking at it. Give it a meaningful name. <code>validate</code>?</p>\n\n<pre><code>if val is not None and v(val):\n</code></pre>\n\n<p>My best guess is that this runs validation on the parameter, and if the validation fails, the parameter is silently dropped. This is bad. You want to know if your validation fails, and probably abort execution of the algorithm.</p>\n\n<p>This path:</p>\n\n<pre><code>allgorithms\\sorting\\simple_sort\\bubble_sort\\bubble_sort.py\n</code></pre>\n\n<p>has a typo in it. It's \"algorithms\", not \"allgorithms\" (unless you intended a portmanteau of \"all algorithms\").</p>\n\n<pre><code>def time_task(self):\n t1 = time.time()\n self.run_task()\n t2 = time.time()\n return (t2 - t1) * 1000\n</code></pre>\n\n<p>This is fragile. Consider calling <code>timeit</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:52:27.727",
"Id": "405272",
"Score": "0",
"body": "`allgorithms\\sorting\\simple_sort\\bubble_sort\\bubble_sort.py` this is a typo. I edited the `time_task` function so function contains only \n`return timeit.timeit(stmt=\"self.run_task()\",globals={'self' : self})`. Fallowing your advices i changed the searching function for algorithm. Yes its simpler now. Let's talk about `if val is not None and v(val):` if the `**kwargs` don't contains the keyword and value it's returning an error. As you can see in `simple_sort.py`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:58:08.420",
"Id": "405273",
"Score": "0",
"body": "Even if `kwargs` missing an arg returns an error from the algorithm itself, that's not good enough - you should fail earlier, as soon as validation fails. That's the whole purpose of validation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:59:00.553",
"Id": "405274",
"Score": "0",
"body": "Ok i added a try expection on validate arguments."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:32:41.580",
"Id": "209679",
"ParentId": "209650",
"Score": "1"
}
},
{
"body": "<h3>1. Stop writing frameworks!</h3>\n\n<p>This code seems very \"enterprisey\" to me — by which I mean that there is a big framework of classes that don't do anything except add complexity. If you come from a Java background you might be used to writing this kind of framework, but the sheer volume of code is a maintenance burden that you should not take on unless you are sure that the returns will justify the costs.</p>\n\n<p>In Python, we can nearly always avoid this kind of framework, or at least postpone writing it until it becomes worthwhile.</p>\n\n<p>Let's take the elements of the framework in turn:</p>\n\n<ol>\n<li><p><code>Initiate</code> is a class which provides the features: (i) looking up an algorithm by name; (ii) running an algorithm; (iii) timing how long an algorithm takes. Instead of (i) you could use <a href=\"https://docs.python.org/3/library/functions.html#globals\" rel=\"nofollow noreferrer\"><code>globals</code></a>; instead of (ii) you could just call the function; and instead of (iii) you could use the <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> module. But the code doesn't use the <code>Initiate</code> class anywhere, so you could delete it.</p></li>\n<li><p><code>Algorithm</code> is a class which provides the features: (i) calling a function with some keyword arguments; (ii) timing how long the function takes. Instead of (i) you could just call the function, and instead of (ii) you could use the <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> module. So you could delete this class and use functions instead.</p></li>\n<li><p><code>algorithm_list.py</code> provides a table mapping algorithm name to algorithm class. But this is only needed by <code>Initiate.get_algorithm</code>, and that isn't used anywhere, so you could delete this file. In Python, if you really need to look up a function by name, you can use the <a href=\"https://docs.python.org/3/library/functions.html#globals\" rel=\"nofollow noreferrer\"><code>globals</code></a> built-in. But this is rarely necessary.</p></li>\n<li><p><code>SimpleSort</code> is a subclass of <code>Algorithm</code> providing specialized features for sorting algorithms. This class isn't needed (for the same reasons that <code>Algorithm</code> isn't needed) and you could delete this class.</p></li>\n<li><p><code>BubbleSortV1</code> and <code>BubbleSortV2</code> are subclasses of <code>SimpleSort</code> that implement the bubble sort algorithm. These classes aren't needed (for the same reasons that <code>Algorithm</code> isn't needed). All you need to keep is the sort function.</p></li>\n<li><p><code>AlgorithmBaseTestCase</code> is a class of unit tests for the <code>Algorithm</code> class. But if you deleted the <code>Algorithm</code> class, then you wouldn't need to test it, and so you could delete <code>AlgorithmBaseTestCase</code> too.</p></li>\n<li><p><code>SortTestCase</code> checks that an algorithm sorts a sequence correctly. This is fine!</p></li>\n<li><p><code>SimpleSortTestCase</code> provides tests of a sorting algorithm on various input lists. This is fine, except that the tests are very repetitive. It would be better to refactor the code so that it is table driven. See the <code>test_cases</code> method below for how to do this.</p></li>\n<li><p><code>run_tests.py</code> runs <code>unittest</code> test discovery. But you can do this using the <a href=\"https://docs.python.org/3/library/unittest.html#command-line-interface\" rel=\"nofollow noreferrer\"><code>unittest</code> command-line interface</a> without having to write any code: <code>python -m unittest discover -s algorithms</code>. So you could delete this file.</p></li>\n</ol>\n\n<h3>2. Other review comments</h3>\n\n<ol>\n<li><p>The argument to the sorting algorithms needs to be a <a href=\"https://docs.python.org/3/glossary.html#term-sequence\" rel=\"nofollow noreferrer\"><em>sequence</em></a> (so that you can index it), not any old container. So <code>sequence</code> would be a better name.</p></li>\n<li><p>The sorting algorithms are <em>destructive</em> — they modify the input sequence, like the <code>list.sort</code> method. In Python it is conventional for destructive functions and methods to return <code>None</code>. This makes it harder to accidentally confuse them with non-destructive equivalents like <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\"><code>sorted</code></a>, which return a fresh result but leave the original data unchanged.</p></li>\n<li><p>The tests are not very thorough. This is a case where you have a <a href=\"https://en.wikipedia.org/wiki/Test_oracle\" rel=\"nofollow noreferrer\">test oracle</a> in the form of the built-in function <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\"><code>sorted</code></a>, making this suitable for <a href=\"https://en.wikipedia.org/wiki/Random_testing\" rel=\"nofollow noreferrer\">random testing</a>. See the <code>test_random</code> method below.</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>def bubble_sort_v1(seq):\n length = len(seq)\n changed = True\n while changed:\n changed = False\n for i in range(length - 1):\n if seq[i] > seq[i + 1]:\n seq[i], seq[i + 1] = seq[i + 1], seq[i]\n changed = True\n length -= 1\n\ndef bubble_sort_v2(seq):\n length = len(seq)\n while length >= 1:\n changed_times = 0\n for i in range(1, length):\n if seq[i - 1] > seq[i]:\n seq[i - 1], seq[i] = seq[i], seq[i - 1]\n changed_times = i\n length = changed_times\n\n\nimport random\nfrom unittest import TestCase\n\nclass TestSort:\n def check(self, seq):\n expected = sorted(seq)\n found = list(seq) # take a copy since self.function is destructive\n self.function(found)\n self.assertEqual(expected, found)\n\n CASES = [\n (), # empty\n (0,), # one element\n (1, 1, 1, 1), # same numbers\n (1, 2, 3, 4), # already sorted\n (4, 3, 2, 1), # reversed\n (3, 5, 3, 2, 4, 2, 1, 1), # disorder with repetitions\n ]\n\n def test_cases(self):\n for case in self.CASES:\n self.check(case)\n\n def test_random(self):\n for k in range(100):\n self.check(random.choices(range(k), k=k))\n\nclass TestBubbleSortV1(TestSort, TestCase):\n function = staticmethod(bubble_sort_v1)\n\nclass TestBubbleSortV2(TestSort, TestCase):\n function = staticmethod(bubble_sort_v2)\n</code></pre>\n\n<p>Notes</p>\n\n<ol>\n<li><p>The reason that <code>TestSort</code> does not inherit from <code>unittest.TestCase</code> is so that it is not run by <code>unittest</code> test discovery: it won't work because it \ndoesn't have a <code>function</code> attribute.</p></li>\n<li><p>The reason for using <a href=\"https://docs.python.org/3/library/functions.html#staticmethod\" rel=\"nofollow noreferrer\"><code>staticmethod</code></a> is that we need <code>self.function</code> to be a plain function, not an <a href=\"https://docs.python.org/3/reference/datamodel.html#index-35\" rel=\"nofollow noreferrer\">instance method</a>.</p></li>\n<li><p>I made the test cases tuples so that they can't be modified by accident. <code>TestSort.check</code> makes a copy in the form of a list so that it can be modified by the function under test.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T19:26:44.350",
"Id": "405292",
"Score": "0",
"body": "Ok, so i have one more question probably. When i will add let's say 10 sorting algorithms, 10 searching algorithms, hashes, graphs, data structures and so on i should stay with one file with functions and one file with tests ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T23:29:01.160",
"Id": "405320",
"Score": "0",
"body": "You can organize the files in whatever way is most convenient. It's easy to move stuff around, so start with a small number of files and then add more as you need them. You don't have to plan everything in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T01:15:04.080",
"Id": "405322",
"Score": "0",
"body": "So, in my own case, I should take a position from general to specific? Not from general to specific. Should not i at first plan 'classes', functions and so on and then start writing them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T08:36:25.800",
"Id": "405330",
"Score": "2",
"body": "From specific to general, you mean? If so, that's what I would recommend. By trying to plan a big framework of abstractions in advance, you give up one of the key advantages of software, namely that it's *soft* (cheap to modify). Better to start with concrete stuff you need right away, and then add abstractions when you are sure you'll benefit from them."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T19:08:13.183",
"Id": "209693",
"ParentId": "209650",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "209693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T22:59:44.710",
"Id": "209650",
"Score": "7",
"Tags": [
"python",
"beginner",
"sorting",
"unit-testing"
],
"Title": "Sorting algorithms with Python project"
} | 209650 |
<p>Problem: find the number of distinct quantities of money that a pile of coins can make. </p>
<p>The vector <code>coins</code> contains the values of the coins, and the corresponding vector <code>quantity</code> contains the number of coin there are (let's say <code>coins = {1}</code> and <code>quantity = {5}</code>, this means I have 5 pennies). </p>
<p>Although I have solved this problem, I would like to make it more time efficient. Could someone give me some pointers?</p>
<p>Miscellaneous info: the variable <code>ctq</code> stands for "coins to quantity". I solved this by systematically iterating through all possible combinations of coins and putting their sum into a set. There has to be a better way to solve this problem, because this problem is supposed to be a dynamic programming question and I solved this problem without any knowledge of what that's supposed to be.</p>
<pre><code>#include<iostream>
#include<vector>
#include<map>
#include<set>
int money(std::map<int, int> x)
{
int sum=0;
for(auto it=x.begin(); it!=x.end(); ++it)
{
sum+=it->first*it->second;
}
return sum;
}
int rec
(
std::set<int> &sums,
std::map<int, int> ctq,
std::vector<int> coins,
std::vector<int> quantity,
int m
)
{
for(int k=quantity[m]; k>=0; k--)
{
ctq[coins[m]] = k;
sums.insert(money(ctq));
if(m != 0)
{
rec(sums, ctq, coins, quantity, m-1);
}
}
return sums.size()-1;
}
int possibleSums(std::vector<int> coins, std::vector<int> quantity)
{
std::map<int, int> ctq;
for(std::size_t i=0; i<coins.size(); i++)
{
if(ctq.find(coins[i]) == ctq.end())
{
ctq.insert(std::make_pair(coins[i], quantity[i]));
}
else
{
ctq[coins[i]] += quantity[i];
}
}
std::vector<int> n_coins, n_quantity;
for(auto it = ctq.begin(); it != ctq.end(); ++it)
{
n_coins.push_back(it->first);
n_quantity.push_back(it->second);
}
std::set<int> sums;
return rec(sums, ctq, n_coins, n_quantity, n_coins.size()-1);
}
int main()
{
std::vector<int> coins = {10, 50, 100, 200};
std::vector<int> quantity = {511, 22, 30, 50};
std::cout << possibleSums(coins, quantity) << "\n";
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Instead of calculating each combination recursively, you can build up the list one coinage type at a time. This would involve fewer iterations in the case that any combinations form the same total, and more importantly wouldn't require adding up each combination separately. For example:</p>\n\n<pre><code>std::set<int> sums;\nfor(int c = 0; c < coins.size(); ++c)\n{\n // Include zero on the initial list, but not subsequent ones\n if(sums.empty()) \n {\n for(int q = 0; q <= quantity[c]; ++q) \n {\n sums.insert(q * coins[c]);\n }\n }\n else\n {\n std::vector<int> current(sums.begin(), sums.end());\n for(int q = 1; q <= quantity[c]; ++q)\n {\n for(int sum : current) \n {\n sums.insert(sum + q * coins[c]);\n }\n }\n }\n} \n</code></pre>\n\n<p>Using a vector instead of a set to accumulate sums (removing duplicates at the end) might be faster, and would eliminate the need for a temporary copy (current). However, it wouldn't eliminate the redundant loops based off the same total, so some measurements would be needed to see which is better.</p>\n\n<pre><code>std::vector<int> sums;\nfor(int c = 0; c < coins.size(); ++c)\n{\n // Include zero on the initial list, but not subsequent ones\n if(sums.empty()) \n {\n for(int q = 0; q <= quantity[c]; ++q) \n {\n sums.push_back(q * coins[c]);\n }\n }\n else\n {\n int oldSize = sums.size();\n for(int q = 1; q <= quantity[c]; ++q)\n {\n for(int i = 0; i < oldSize; ++i) \n {\n sums.push_back(sums[i] + q * coins[c]);\n }\n }\n }\n} \n\nstd::sort(sums.begin(), sums.end());\nsums.erase(std::unique(sums.begin(), sums.end()), sums.end());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T13:10:39.010",
"Id": "405247",
"Score": "0",
"body": "The type of problem solving where you accumulate answers from before is new to me. Is that dynamic programming or what is it called? That's a really cool way to solve this problem"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T01:20:53.317",
"Id": "209656",
"ParentId": "209651",
"Score": "3"
}
},
{
"body": "<p>You already have a good review of the algorithm; I'll just look at the implementation here.</p>\n<hr />\n<h1>Representation</h1>\n<p>A pair of corresponding containers is more error-prone to use than a container of pairs. Prefer to keep related data together.</p>\n<p>In this case, what we have is a <em>bag</em> (aka <em>multiset</em>), which might be best represented as a map from denomination to count.</p>\n<h1>Pass by reference</h1>\n<p>Don't pass large objects by value unless you really need a copy. It seems that <code>x</code>, <code>coins</code> and <code>quantity</code> can all be passed as reference to <code>const</code> (this change alone reduced my run times by over 50%).</p>\n<h1>Loops</h1>\n<p>Unless you're stuck with C++03, the loops can be made clearer (and therefore less error-prone) by using range-based <code>for</code>. For example:</p>\n<pre><code>int money(const std::map<int, int>& x)\n{\n int sum=0;\n for (auto const& element: x) {\n sum += element.first * element.second;\n }\n return sum;\n}\n</code></pre>\n<p>With a structured binding (since C++17), the intent can be clearer:</p>\n<pre><code> for (auto const [denomination, quantity]: x) {\n sum += denomination * quantity;\n }\n</code></pre>\n<p>You will find that a container-of-pairs representation lends itself better to range-based <code>for</code>, as we don't need to track corresponding indexes.</p>\n<h1>Let <code>operator[]</code> create entries</h1>\n<p>This code looks to me like unnecessary work:</p>\n<blockquote>\n<pre><code> if(ctq.find(coins[i]) == ctq.end())\n {\n ctq.insert(std::make_pair(coins[i], quantity[i]));\n }\n else\n {\n ctq[coins[i]] += quantity[i];\n }\n</code></pre>\n</blockquote>\n<p>If <code>coins[i]</code> isn't present in <code>ctq</code>, then simply accessing <code>ctq[coins[i]]</code> will do exactly what we need: create an entry with a default-initialised value (i.e. <code>0</code>). So we can simplify that <code>if</code>/<code>else</code> to just:</p>\n<pre><code> ctq[coins[i]] += quantity[i];\n</code></pre>\n<h1>Consider using unsigned types</h1>\n<p>Since coin denominations and quantities can't be negative, an unsigned type may be more appropriate. That would double the range that you can represent (the current input set isn't in imminent danger of exceeding <code>INT_MAX</code> - which must be at least 32767 - but it wouldn't take much to overstep that mark).</p>\n<h1>Explain corrective factors</h1>\n<p>Here, we have a correction of <code>-1</code>:</p>\n<blockquote>\n<pre><code>return sums.size()-1;\n</code></pre>\n</blockquote>\n<p>It's my <em>guess</em> that the <code>-1</code> is because we don't consider <code>0</code> to be one of the valid results to be counted. It would be worthwhile to have a comment to confirm that guess (or to provide the correct explanation if I'm wrong).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T13:19:55.710",
"Id": "405250",
"Score": "0",
"body": "Yeah, you -1 because you don't consider 0 to be one of the valid results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-09T09:24:24.990",
"Id": "408301",
"Score": "0",
"body": "I meant, the *code* should contain the explanatory comment! But thanks anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T09:16:03.463",
"Id": "209663",
"ParentId": "209651",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209656",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T23:00:38.290",
"Id": "209651",
"Score": "2",
"Tags": [
"c++",
"performance",
"algorithm",
"recursion"
],
"Title": "A recursive algorithm to find the number of distinct quantities of money from a pile of coins"
} | 209651 |
<p>This is a solution to Advent of Code Day 13 (<a href="https://adventofcode.com/2018/day/13" rel="nofollow noreferrer">problem specification</a>, <a href="https://adventofcode.com/2018/day/13/input" rel="nofollow noreferrer">test input</a>), for which I was asked to read a layout of tracks and mine carts and detect 1) where the first crash would occur and 2) where the final remaining cart would be after the rest had crashed.</p>
<p>The tracks consist of:<br>
spaces: there's nothing there<br>
straight pieces: <code>-</code>s and <code>|</code>s<br>
Curves: <code>\</code>s, which connect top/right and bottom/left, and <code>/</code>s which do the opposite<br>
Intersections: <code>+</code>s, for which carts alternate between going left/straight/right<br>
Carts: <code>v</code>, <code>^</code>, <code><</code>, <code>></code> start on straight tracks facing the direction of the arrow</p>
<p>Carts move in an order determined by their position. Lower y-values move first, lower-x values break ties, they move one unit along their track per tick, and when carts crash they both disappear.</p>
<p>My code consists of the main function <code>day13</code> and a Cart class. The Cart class stores the track layout. Each cart keeps track of its position, direction, and which turn it will take next. It exposes its position and a move function.</p>
<p>The main function reads the input to initialize the track layout and puts all the carts in a map using keys sorted by move-order. And the main loop moves each cart, checks for collisions, and continues until there's only one cart left.</p>
<p>Without further ado, the Cart.h/Cart.cpp code:
</p>
<pre><code>#pragma once
#include<array>
using std::array;
#include<utility>
using std::pair;
constexpr auto infile = "Day13Input.txt";
constexpr auto track_size = 150;
namespace Day13 {
enum Track {
None = 0,
Vert = 1,
Flat = 2,
Cross = 3,
Hack = 4,
Slash = 5,
};
enum Dir {
Up = 0,
Right = 1,
Down = 2,
Left = 3,
};
enum Turn {
LeftTurn = -1,
Straight = 0,
RightTurn = 1,
};
class Cart {
private:
Dir _dir;
Turn _turn_dir;
void derail ( ) const;
void turn ( const Track t );
pair<int, int> dest ( ) const;
Track lookup_dest ( const pair<int, int> ) const;
public:
static array<array<Track, track_size>, track_size> tracks;
int _x, _y;
Cart ( int x, int y, Dir dir ) : _x ( x ), _y ( y ), _dir ( dir ), _turn_dir ( Turn::LeftTurn ) { };
int move ( );
bool operator<( const Cart& rhs ) const;
bool operator==( const Cart& rhs ) const;
bool operator>( const Cart& rhs ) const;
};
}
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "Day13CartClass.h"
using Day13::Turn;
using Day13::Dir;
using Day13::Track;
using Day13::Cart;
#include<utility>
using std::pair;
#include<exception>
using std::exception;
#include<array>
using std::array;
//not sure if this is obvious enough behavior for overloaded ++
Turn operator++( Turn& orig ) {
orig = (Turn) ( orig == 1 ? -1 : orig + 1 );
return orig;
}
Turn operator++( Turn& orig, int ) {
Turn ret = orig;
++orig;
return ret;
}
Dir make_turn ( const Dir initial_dir, const Turn turn_type ) {
return (Dir) ( ( initial_dir + turn_type + 4 ) % 4 );
}
Dir follow_curve ( const Dir initial_dir, const Track curve ) {
Dir new_dir;
switch ( curve ) {
case Track::Hack:
new_dir = (Dir) ( 3 - initial_dir );
break;
case Track::Slash:
new_dir = (Dir) ( initial_dir ^ 1 );
break;
default:
throw exception ( "tried to follow a curve that wasn't curved\n" );
}
return new_dir;
}
array<array<Track, track_size>, track_size> Cart::tracks;
pair<int, int> Cart::dest ( ) const {
int new_x = _x, new_y = _y;
switch ( _dir ) {
case Up:
new_y--;
break;
case Down:
new_y++;
break;
case Left:
new_x--;
break;
case Right:
new_x++;
break;
}
return std::pair<int, int> ( new_x, new_y );
}
void Cart::turn ( const Track t ) {
switch ( t ) {
case Vert:
if ( _dir == Right || _dir == Left )
derail ( );
break;
case Flat:
if ( _dir == Up || _dir == Down )
derail ( );
break;
case Hack:
case Slash:
_dir = follow_curve ( _dir, t );
break;
case Cross:
_dir = make_turn ( _dir, _turn_dir++ );
break;
case None:
derail ( );
break;
}
}
void Cart::derail ( ) const {
char* buf = new char[ 100 ];
sprintf ( buf, "Cart went off the rails at %d, %d with direction %d", _x, _y, _dir );
throw exception ( buf );
}
Track Cart::lookup_dest ( const pair<int, int> coords ) const {
return tracks[ coords.second ][ coords.first ];
}
int Cart::move ( ) {
auto dest = this->dest ( );
Track t = lookup_dest ( dest );
_x = dest.first; _y = dest.second;
this->turn ( t );
return ( _y * track_size ) + _x;
}
bool Cart::operator<( const Cart& rhs ) const {
if ( _y < rhs._y )
return true;
else if ( _y == rhs._y )
return _x < rhs._x;
else
return false;
}
bool Cart::operator==( const Cart& rhs ) const {
return ( _x == rhs._x ) && ( _y == rhs._y );
}
bool Cart::operator>( const Cart& rhs ) const {
return rhs < *this;
}
</code></pre>
<p>and the main function is:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "Day13CartClass.h"
using Day13::Cart;
using Day13::Track;
using Day13::Dir;
#include<cstdio>
#include<array>
using std::array;
#include<map>
using std::map;
void read_tracks ( FILE*,
array<array<Track, track_size>, track_size>&,
map<int, Cart*>& );
bool log_crash ( const int );
void day13 ( ) {
map<int, Cart*> carts = { };
FILE* input = fopen ( infile, "r" );
if ( input == nullptr ) {
printf ( "failed to open input file\n" );
return;
}
read_tracks ( input, Cart::tracks, carts );
bool crashed = false;
while ( carts.size ( ) > 1 ) {
map<int, Cart*> new_carts = { };
for ( auto it = carts.begin ( ); it != carts.end ( ); ) {
Cart* cart = it->second;
int pos = cart->move ( );
//If the new position is on an existing cart, erase it and don't save this cart, otherwise save new position
if ( carts.count ( pos ) ) {
//Check carts that haven't moved
carts.erase ( pos );
crashed = crashed || log_crash ( pos );
} else if ( new_carts.count ( pos ) ) {
//Check against carts that have already moved
new_carts.erase ( pos );
crashed = crashed || log_crash ( pos );
} else {
new_carts[ pos ] = cart;
}
//erase now that the cart has moved
it = carts.erase ( it );
}
carts = new_carts;
}
int x = ( carts.begin ( )->first ) % track_size;
int y = ( carts.begin ( )->first ) / track_size;
printf ( "last remaining cart at x=%d and y=%d\n", x, y );
}
//Some rather verbose IO follows
void read_tracks ( FILE* input,
array<array<Track, track_size>, track_size>& tracks,
map<int, Cart*>& carts ) {
for ( int y = 0; y < track_size; y++ ) {
for ( int x = 0; x < track_size; x++ ) {
char t;
int pos = ( ( track_size * y ) + x );
if ( fscanf ( input, "%c", &t ) != 1 ) {
printf ( "expected character but no match\n" );
return;
}
switch ( t ) {
case '<':
carts[ pos ] = new Cart ( x, y, Dir::Left );
t = '-';
break;
case '>':
carts[ pos ] = new Cart ( x, y, Dir::Right );
t = '-';
break;
case '^':
carts[ pos ] = new Cart ( x, y, Dir::Up );
t = '|';
break;
case 'v':
carts[ pos ] = new Cart ( x, y, Dir::Down );
t = '|';
break;
}
switch ( t ) {
case '-':
tracks[ y ][ x ] = Track::Flat;
break;
case '|':
tracks[ y ][ x ] = Track::Vert;
break;
case '\\':
tracks[ y ][ x ] = Track::Hack;
break;
case '/':
tracks[ y ][ x ] = Track::Slash;
break;
case '+':
tracks[ y ][ x ] = Track::Cross;
break;
default:
printf ( "weird input found\n" );
case ' ':
tracks[ y ][ x ] = Track::None;
}
}
char eol;
if ( fscanf ( input, "%c", &eol ) == EOF ) {
printf ( "unexpected EOF\n" );
return;
} else if ( eol != '\n' ) {
printf ( "expected newline not found\n" );
return;
}
}
}
bool log_crash ( const int pos ) {
int first_crash_x = pos % track_size;
int first_crash_y = pos / track_size;
printf ( "first crash at x=%d and y=%d\n", first_crash_x, first_crash_y );
return true;
}
</code></pre>
<p>The problem input I got (requires a newline at the end if you want it to run):</p>
<pre><code> /------------\ /----------------\ /---------------------\
| | | /----------\| | /-------------+--------------------------------------------------\
| | /-----+----+----------++------+-------+-------------+-----------------------------------\ |
| | | | | || | | | /---------+--------------+-\
| | | | | || | /----+-------------+-------------------------+---------+----\ | |
/+------------+-----+-----+----+----------++------+--+----+-------------+-------------------------+--------\| |/--------+-+\
|| /--------+-\ /+-----+----+----------++------+--+----+-------------+-----\ | || || | ||
|| | /------+-+--++--\ | | || | | | /-<---+-----+-------------------+--------++\ || | ||
/--------------++---+-+------+-+--++--+--+----+----------++------+--+----+-------+-----+-----+--------------\ | ||| || | ||
| || | | | | || | | | || /---+--+----+-------+-----+-----+------------\ | | ||| || | ||
| /----++---+-+------+-+--++--+--+----+----------++-\| | | | | | | | | | ||| || | ||
/--+---------+----++---+-+------+-+--++--+--+----+----------++-++---+--+----+-\ | | | | | | ||| || | ||
| | | || | | | | || | | | /-++-++---+--+----+-+-----+-----+-----+------------+-+----+--------+++---++-\ | ||
| | | || | | | | || | /+----+---\ | || || | | | | | | | | | | /-----+++---++\| | ||
| | | || | | | | || | || \---+----+-/|/++---+--+----+-+-----+---\ | |/-----------+-+----+\ | ||| |||| | ||
| | | || | | | | ||/-+-++--------+----+--++++---+--+>---+-+-----+---+-+-----++-----------+-+----++-+-----+++---++++----\ | ||
| | | || | | | | ||| | || | | |||| | | | | | /-+-+-----++-------\ | | || | ||| |||| | | ||
| | | /-++---+-+------+-+--+++-+-++<-------+----+--++++---+--+----+-+-----+-+-+-+-----++\ | | | || | ||| |||| | | ||
| | /+--+-++---+-+--\ | | ||| | || | | |||| | | | | | | | | /---+++------+---+-+----++-+-----+++---++++----+-+-++-\
| | || | || | | | | | /+++-+-++--------+----+--++++---+--+----+-+--\ | | | | | v|| | | | || | ||| |||| | | || |
| | ||/-+-++---+-+--+---+-+-++++-+-++-\ /----+----+\ |||| | | | | | | | | | | ||| | | | || | ||| |||| | | || |
| | |\+-+-++---+-+--+---+-+-++++-+-++-+-+----+----++-++/| | | | | | | | | | | ||| | | | || | ||| |||| | | || |
| | | | | || | | | | | |||| | || | | | || || | | | | | | | | | | | ||| | | | || | ||| |||| | | || |
/+--+--------+-+-+-++---+-+--+---+-+-++++-+-++-+-+----+\ || || | \--+----+-+--+--+-+-+-/ | ||| | | | || | ||| |||| | | || |
|| \--------+-+-+-++---+-+--+---+-+-++++-+-++-+-+----++---++-++-+------+----+-+--+--+-+-+---+---+++------+---+-/ || | ||| |||| | | || |
|| | | | || | | | /-+-+-++++-+-++-+-+----++---++-++-+------+--\ | | | | | | | ||| | | || | ||| |||| | | || |
|| /----+-+-+-++---+-+--+-+-+-+-++++-+-++-+-+----++---++-++-+----\ | | | | | | | | | ||| | | || | ||| |||| | | || |
|| | | | | || | \--+-+-+-+-++++-/ || | | || || || | | | | | | | | | | | ||| | | || | ||| |||| | | || |
|| | | | | || | | | | | |||| || | | || || || | | | | | | | | | | | ||| | | || | ||| |||| | | || |
|| /--+----+-+-+-++---+-\ | | | | |||| || | | || || || | | | | | | | | | | | ||| | | || | ||| |||| | | || |
|| /-+--+----+-+-+-++---+-+--+-+-+-+-++++---++-+-+\ || || || | /-+-+--+-+-+--+--+-+\| | ||| | | || | ||| |||| | | || |
|| | | | | \-+-++---+-+--+-+-+-+-++++---++-/ || ||/--++-++-+-\| | | | | | | | ||| | /+++------+---+\ || | ||| |||| | | || |
|| | | | | | || | | | | | | |||| || \+---+++--+/ || | || | | | | | | | ||| | |||| | || || | ||| |||| | | || |
|| | | | | | || /+-+--+-+-+-+-++++---++----+---+++--+--++-+-++-+-+--+-+\|/-+--+-+++---+--++++------+---++-----++-+-----+++--\|||| | | || |
|| | | | | | || || | | | | | ||\+---++----+---+++--+--++-+-++-+-+--+-++++-+--+-+++---+--++++------+---++-----++-+-----+/| ||||| | | || |
|| | | | | /+-++--++-+--+-+-+-+-++-+---++----+---+++--+--++-+-++-+-+--+-++++-+--+-+++---+--++++----\ | || || | | | ||||| | | || |
|| | | | | || || || | | | | | || | ||/---+---+++--+--++-+-++-+-+--+-++++-+--+-+++---+--++++----+-+---++-----++-+----\| | |||||/---+-+-++\|
|| | | | | || || || | | | | | |\-+---+++---+---+++--+--++-+-++-+-+--+-++++-+--+-+++---+--+/|| | | || /--++-+----++-+--++++++---+-+\||||
/-++-+-+--+----+--++-++--++-+--+-+-+-+\| | |||/--+---+++--+-\|| | || | | | |||| | | ||| | | || | | || | || | || | |||||| | ||||||
| || | | | | || || || |/-+-+-+-+++--+---++++\ | ||| \-+++-+-++-+-+--+-++++-+--+-+++---+--+-++----+-+---++--+--++-+----++-+--++++/| | ||||||
| || | | | | || || || || | | | |||/-+---+++++-+---+++----+++-+-++-+-+--+-++++-+--+-+++---+--+-++----+-+-\ || | || | || | ||\+-+---+-+++/||
| || | | | | || || || || | | | |||| | ||||| |/--+++----+++-+-++-+-+--+-++++-+--+-+++---+--+-++----+-+-+-++--+--++-+----++\| || | | | ||| ||
| || | | | | || || || || | | | |||| | /-+++++-++--+++----+++-+-++-+-+--+-++++-+--+-+++---+--+-++----+-+-+-++--+-\|| | |||| || | | | ||| ||
| || | | | | || || || || | | | |||| | | ||||| || ||| ||| | || | | | |||| | | ||| | \-++----+-+-+-+/ | ||| | |||| || | | | ||| ||
| || |/+--+----+--++-++--++-++-+-+-+-++++-+-+-+++++-++--+++----+++-+-++-+-+--+-++++-+--+\||| | || | | | | | ||| | |||| || | | | ||| ||
| || ||| | | || || || || | | | |||| | | ||||| || ||| ||| | || | | | |||| | \++++---+----++----+-+-+-+---+-+++-+-->-+++/ || | | | ||| ||
| || ||| | | || || || || |/+-+-++++-+-+-+++++-++--+++----+++-+-++-+-+-\| ||^| | |||| | || | | | | | ||| | ||| || | | | ||| ||
| || ||| | | || ||/-++-++-+++-+-++++-+-+-+++++-++--+++----+++-+-++-+-+-++-++++-+---++++---+----++----+-+-+-+---+-+++-+-\ ||| || | | | ||| ||
| ||/+++--+----+-\|| |||/++-++-+++-+-++++-+-+-+++++-++--+++----+++\| || | | || |||| | |||| | || | | | | | ||| | | ||| || | | | ||| ||
| |||||| | | ||| |||||| ||/+++-+-++++-+-+-+++++-++--+++----+++++-++-+-+-++-++++-+---++++---+----++\ | | | | | |\+-+-+--+++---++-+-+---+-++/ ||
| |||||| | | ||| |||||| |||||| | |||| | | ||||| || ||| ||||| || | | || |||| | |||| | ||| | | | | | | | | | ||| || | | | || ||
| |||||| | | ||| |||||| |||||\-+-++++-+-+-+++++-++--+++----+++++-++-+-+-+/ |||| | /-++++---+----+++---+-+-+-+---+-+-+-+-+--+++-\ || | | | || ||
| |||||| | | ||| |||||| ||||| | |||| | | ||||| || ||| ||||| || | | | |||| | | |||| | ||| | | | | | | | | | ||| | || | | | || ||
| |||||| | /+-+++-++++++-+++++--+-++++-+-+-+++++-++--+++----+++++\|| | | | |||| | | |||| | ||| | | | | | | | | |/-+++-+-++\| | | || ||
| |||||| | || ||| |||||\-+++++--+-/||| \-+-+++++-++--+++----++++++++-+-+-+--++++-+-+-++++---+----+++---+-+-+-+---+-+-+-+-++-+++-+-++++-+---/ || ||
| |||||| | || ||| ||||| ||||| |/-+++---+-+++++-++--+++----++++++++-+-+-+--++++-+-+-++++---+----+++--\| | | | | | | | || ||| | |||| | || ||
| |||||| | || ||| ||||| ||||| || ||| | ||||| || ||| ||||||||/+-+-+--++++-+-+-++++---+\ ||| || | | | | | | | || ||| | |||| | || ||
| |||||| | || ||| ||||| ||||| || ||| | ||||| || ||| /--++++++++++-+-+--++++-+-+-++++---++---+++--++-+-+-+--\| | | | || ||| | |||| | || ||
| |||||| /+---++-+++-+++++--+++++--++-+++---+-+++++-++\ ||| | |||||||||| | | |||| | | |||| || ||| || | | | || | | | || ||| | |||| | || ||
| |||||| || || ||| ||||| ||||| || ||| | |||||/+++-+++-+--++++++++++-+-+--++++-+-+-++++---++\ ||| || | | | || | | | || ||| | |||| | || ||
| |||||| || || ||| ||||| ||||| ||/+++---+-+++++++++-+++-+--++++++++++-+-+--++++-+-+-++++---+++--+++--++-+-+-+--++-+-+-+-++-+++\| |||| | || ||
| |||||| || || ||| ||||| ||||| |||||| | |\+++++++-+++-+--+/|||||||| | | |||| | | |||| ||| ||| || | | | || | | | || ||||| |||| | || ||
| |||||| || || ||| ||||| ||||| |||||| \-+-+++++++-+++-+--+-++++++++-+-+--++++-+-+-++++---+++--+++--++-+-+-+--++-/ | | ||/+++++-++++\| || ||
| |\++++-++---++-+++-+++++--+++++--++++++-----+-+++++++-+++-+--+-++++++++-+-+--++/| | | |||| ||| ||| || | | | || | | |||||||| |||||| || ||
| | ||||/++---++-+++-+++++--+++++--++++++-----+-+++++++-+++-+--+-++++++++-+-+--++-+-+-+-++++---+++--+++\ || | | | || | | |||||||| |||||| || ||
| | ||||||| || ||| ||||| ||||| |||||| /+-+++++++\||| | | |||||||| | | || | | | |||| ||| |||| || | | | || | | |||||||| |||||| || ||
| | ||\++++---++-+++-+++++--+++++--++++++----++-+++++++++++-+--+-++++++++-+-+--++-+-+-+-/||| ||| |||| || | | | || | | |||||||| |||||| || ||
| | || |||| /-++-+++-+++++--+++++--++++++----++-+++++++++++-+--+-++++++++-+-+--++-+-+-+--+++---+++--++++-++-+-+-+\ || | | |||||||| |||||| || ||
| \-++-++++-+-++-+++-+++++--+++++--++++++----++-+++++++++/| |/-+-++++++++-+-+--++-+-+-+--+++---+++--++++-++-+-+-++-++---+-+-++++++++\|||||| || ||
| || |||| | || ||| \++++--+++++--++++++----++-+++++++++-+-++-+-++++++++-+-+--++-+-+-+--+++---+++--++++-++-+-+-++-++---+-+-++++/|||||||||| || ||
| || \+++-+-++-+++--++++--/|||| |||||| /--++-+++++++++-+-++-+-++++++++-+-+--++-+-+-+--+++---+++--++++-++-+-+-++-++--\| | |||| |||||||||| || ||
| || ||| | || ||| |||| |||| |||||| | || ||||||||| | || | |||||||| | | || | | | |||/--+++--++++-++\| | || || || | |||| |||||||||| || ||
| || ||| | || ||| ||\+---++++--++++++-+--++-+++++++++-+-++-+-+/|||||| | | /++-+-+-+--++++--+++--++++-++++-+-++-++--++-+-++++-++++++++++-\ || ||
| || ||| | || ||| \+-+---++++--/||||| |/-++-+++++++++-+-++-+-+-++++++-+-+-+++-+-+-+--++++--+++\ |||| |||| |/++-++--++-+-++++-++++++++++-+\ || ||
| || ||| | || ||| | | |||| ||||| || || ||||||||| | || | | \+++++-+-+-+++-+-+-+--++++--++++-++++-++++-++/| || || | |||| |||||||||| || || ||
| || ||| | || ||| | | |||| ||||| || || ||||||||| | || | | ||||| | | ||| | | | |||| |||| |||| |||| || | || || | |||| |||||||||| || || ||
| || ||| | || ||| | | |||| |||\+-++-++-+++++++++-+-++-+-+--+++++-+-+-+++-+-/ | |||| |||| |||| |||| || | || || | |||| |||||||||| || || ||
| \+--+++-+-++-/|| \-+---++++---+++-+-++-++-+++++++++-+-++-+-+--+++++-+-+-+++-+---+--++++--++++-++++-++++-++-+-++--++-+-/||| |||||||||| || || ||
| | ||| | || || | |||| ||| | || ||/+++++++++-+-++-+-+--+++++-+-+-+++-+---+\ ||||/-++++-++++-++++-++-+-++--++-+-\||| |||||||||| || || ||
| | ||| | || || | ||||/--+++-+-++-++++++++++++-+-++-+\| ||||| | | ||| | || ||||| |||| |||| |||| || | || ||/+-++++-++++++++++-++--++-\||
| | ||| | || || | ||||| ||| | || |||||||||||| | || ||\--+++++-+-+-+++-+---++-++/|| |||| |||| |||| || | || |||\-++++-+++++++/|| || || |||
| | ||| | || || | ||||| /+++-+-++-++++++++++++-+-++-++---+++++-+-+-+++-+---++-++-++-++++-++++-++++\|| | || ||| |||| |||v||| || || || |||
| | ||| | || || | |||\+-++++-+-++-++++++++++++-+-++-++---+++++-+-/ ||| | || || || |||| |||| ||||||| | || ||| |||| ||||||| || || || |||
| | ||| | || || | ||| | |\++-+-++-++++++++++++-+-++-++---+++++-+---+++-+---++-++-++-++++-++++-/|||||| | || ||| |||| ||||||| || || || |||
| | ||| | || || | ||| | | || | || |||||||||||| | || || ||||| \---+++-+---++-++-++-++++-++++--++++++-+-++--+++--++++-+++++/| || || || |||
| | ||| | || || | ||| | | || | || |||||||||||| | || || ||||| ||| | || || || \+++-++++--++++++-+-++--+++--++++-+++++-+-++-++--++-++/
| | ||| | || || | ||| | | \+-+-++-++++++++++++-+-++-++---+++++-----+++-+---++-++-++--+++-++++--++++++-+-++--+++--++++-+/||| | || || || ||
| \--+++-+-++--++-----+---+++-+-+--+-+-++-+++++++/|||| | || || ||||| ||| | || || || ||| |||| |||||| | || ||| |||| | ||| | || || || ||
| ||| | || || | |\+-+-+--+-+-++-+++++++-++++-+-++-++---+++++-----+++-+---++-++-++--+++-++/| |||||| | || ||| |||| | ||| | || || || ||
| ||| | || || /-+---+-+-+-+--+-+-++-+++++++-++++-+-++-++---+++++-----+++-+---++-++-++--+++-++-+--++++++-+-++--+++--++++\| ||| | || || || ||
| ||| | || || |/+---+-+-+-+--+-+-++-+++++++-++++-+-++-++\ ||||| /+++-+---++-++-++--+++-++-+-\|||||| | || ||| |||||| |v| | || || || ||
| ||| |/++--++---+++---+-+-+-+--+-+\|| ||\++++-++++-+-++-+++--+++++----++++-+---+/ \+-++--+++-++-+-+++/||| | || ||| |||||| ||| | || || || ||
| ||| |||| || ||| | | | | | |||| || |||| |||| | || ||| ||||| |||| | | | || ||| || | ||| ||| | || ||| |||||| ||| | || || || ||
| ||| |||| ||/--+++---+-+-+-+\ | |||| || |||| |||| | || ||| ||||| |||| | | | || ||| || | ||| ||| | || ||| |||||| ||| | || || || ||
| ||| |||| ||| ||| | | | || | |||| || |||| \+++-+-++-+++--+++++----++++-+---+---+-++--+++-++-+-+++-+++-+-++--+++--+++++/ ||| | || || || ||
| /---+++-++++--+++\ ||| | | | || | |||| || |||| ||| | || ||| ||\++----++++-+---+---/ || |||/++-+-+++-+++-+-++>-+++--+++++-\||| | || || || ||
| | ||| |||| |||| ||\---+-+-+-++-+-++++-++-++++--+++-+-++-+++--++-++----+++/ | | || ||||||/+-+++-+++-+-++--+++-\||||| |||| | || || || ||
| | ||| |||\--++++-++----+-/ | || | |||\-++-++++--+++-+-++-+++--++-++----+++--+-->+-----++--++/||||| ||| ||| | || ||| |||||| |||| | || || || ||
| | ||| ||| |||| || | | || | ||| || |||| ||| | || ||| || || ||| | | || || ||||| ||| ||| | || ||| |||||| |||| | || || || ||
| | ||| ||| |||| |\----+---+-++-+-+++--++-++++--+++-+-++-++/ || || ||| | | || || ||||| ||| ||| | || ||| |||||| |||| | || || || ||
| | ||| ||| |||| | | | \+-+-+++--++-++++--+++-+-++-++---++-++----+++--+---+-----++--++-+++++-+++-/|| | || ||| |||||| |||| | || || || ||
| | ||| ||| |||| | /-+---+--+-+-+++--++-++++--+++-+-++-++---++-++----+++--+---+-----++--++\|||||/+++--++-+-++--+++-++++++-++++-+-++-++-\|| ||
| | ||| ||| /++++-+---+-+---+\ | | ||| || |||| ||| | || || || || ||| | | || |||||||||||| || | || ||| |||||| |||| | || || ||| ||
| | ||| ||| ||||| | | | || | | ||| || |||| ||| | || || || || |\+--+---+-----++--++++++++++++--++-+-++--+++-++++++-++++-+-++-/| ||| ||
| | \++-+++--+++++-+---+-+---++-+-+-+++--++-++++--+++-+-++-++---++-++----+-+--+---+-----++--+++++++/|||| || | || ||| |||||| |||| | || | ||| ||
| | || ||| ||||| | | | || | | |||/-++-++++--+++-+-++-++---++-++----+-+--+---+-----++--+++++++-++++--++-+-++--+++-++++++-++++-+-++--+-+++-++\
| | || ||| ||||| | |/+---++-+-+-++++-++-++++--+++-+-++-++---++-++----+-+--+---+-----++--+++++++-++++--++-+-++-\||| |||||| |||| | || | ||| |||
| | || ||| ||||| | ||| || | | |||| || |||| ||| \-++-++---+/ || | | | | || ||||||| |||| || | || |||| |||||| |||| | || | ||| |||
| | || ||| ||||| | ||| || | | |||| |\-++++--++/ || || | || | \--+---+-----++--+++++++-++++--++-+-++-++++-++++++-++++-+-++--+-+/| |||
| | || ||| ||||| | ||| || | | |||| | |||| || /--++-++---+--++\ | | | || ||||||| |||| || | |\-++++-++++++-++++-+-++--+-+-/ |||
| | || ||| ||||| | ||| || | | \+++-+--++++--++-+--++-++---+--+++---+----+---+-----++--+++++++-++++--/| | | |||| |||||| |||| | || | | |||
| | || ||| ||||| | ||| || | | ||| | |\++--++-+--++-/| | \++---+----+---+-----++--/|||||| |||| | | | |||| |||||| |||| | || | | |||
| | || ||| ||\++-+---+++---++-+-+--+++-+--+-++--++-+--++--+---+---++---+----+---+-----++---++++/| |||| | | | |||| |||||| |||| | || | | |||
| | || ||| || || | ||| || | | ||| | | || || | || | | || | | | || |||| | |||| | | | |||| |||||| |||| | || | | |||
| | || ||| || || | ||| || | | ||| | | |\--++-+--++--+---+---++---+----+---+-----++---/||| | |||| | | | |||| |||||| ||v| | || | | |||
| | || ||| || || | ||| || | | ||| | | | ||/+--++--+---+---++---+----+---+-----++----+++-+-++++\ | | | |||| |||||| |||| | || | | |||
\---+----++-+++--++-++-+---+++---++-+-/ ||| | | | |||| || | | || | | | || ||| | ||||| \-+-+--++++-++++++-++++-+-++--/ | |||
| || ||| || || | ||| \+-+----+++-+--+-+---++++--++--/ | || | | | || ||| | ||||| | | |||| |||||| |||| | || | |||
| || |\+--++-++-+---+++----+-+----/|| | | | |||| || | || | | \-----++----+++-+-+++++----+-+--++++-++++++-+/|| | || | |||
| || | | || || | ||| | | || | | | |||| || | || | | || ||| | ||||| | | |||| |||||| | || | |\----+---+/|
| || | | ||/++-+---+++-\ | | /-++-+--+-+---++++-\|| | || | | || ||| | ||||| | | |||\-++++++-+-++-+-+-----+---/ |
\----++-+-+--++++/ | ||| | | | | || | | | |||| ||| | || | | || ||\-+-+++++----+-+--++/ |||||| | || | | | |
|| | | |||| | ||| | | | | || | | | |||| |||/-----+--\|| | \---------++----++--+-+++++----+-+--++---++++++-+-+/ | | | |
|| | | |||| | ||| | | | | \+-+--+-+---++++-++++-----+--+++---+--------------++----++--+-+++++----+-+--+/ |||||| | | | | | |
|| | | |||| | ||| | | | | | | \-+---++++-++++-----+--+++---+--------------++----++--+-+++++----+-+--+----++++/| | | | | | |
|| | | |||| | ||| | | | | | | | ||\+-++++-----+--+++---+--------------++----++--+-++++/ | | | ||\+-+-+-+--/ | | |
|\-+-+--++++--+---+++-+--+-+---+--+-+----+---++-+-++++-----+--+/| | || |\--+-++++>----+-+--+----++-+-+-/ | | | |
/-----+--+-+\ |||| | ||| | | | | | | | || | |||| | | | | || | | |||| | | | || | | | | | |
| | | || |||| | ||| | |/+---+--+-+----+---++-+\|||| | | | | || | | \+++-----+-+--+----++-+-+---+----+-----/ |
| | | || ||v\--+---+++-+--++/ \--+-+----+---++-++/||| | | | | || | | ||| | | | || | | | | |
| | | || ||| | |\+-+--++-------+-+----+---++-++-+++-----+--+-+---+--------------++----+---+--+++-----+-+--/ || | | | | |
| | | || ||| | | | | || | | | || || ||| | | | | || | | ||| | | || | | | | |
| | | || ||| | | | | || | | | || || ||| | | | | || | ^ ||| | | || | | | | |
| | | || ||| | | | | || | \----+---+/ || \++-----+--+-+---+--------------++----+---+--+++-----+-/ || | | | | |
| | | || |\+---+---+-+-+--++-------+------+---+--++--++-----+--+-+---+--------------++----+---+--+/| | || | | | | |
| | | \+-+-+---+---+<+-+--++-------+------+---+--++--++-----/ | | | |\----+---+--+-+-----+---------+/ | | | | |
| | | | | | | | | | || | | | || |\--------/ | | | | | | | | | | | | | |
| | | | | | | | | | || \------+---+--++--+-----------+---+--------------+-----+---+--+-+-----+---------+--+-+---+----+-----------/
| | | | | | | | | | |\--------------+---+--+/ | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | \-+-+--+----->---------+---+--+---+-----------+---+--------------+-----/ | | | | | | | | |
| \--+--+-+-+---+-----+-+--+---------------+---/ | | | | | | | | | | | | | |
\--------+--/ | | | | | | | | | | | | | | | | | \-+---+----/
\----+-+---+-----+-+--+---------------+------+---+-----------+---+--------------+---------+--+-+-----/ | | |
\-+---+-----+-+--/ | | | | | | \--+-+---------------/ | |
| | | | | | | | \--------------+------------/ | | |
| | \-+------------------/ | | | | | | |
\---+-------/ | \-----------+------------------+--------------+--------------------+---/
\-----------------------<---------+---------------+------------------+--------------+--------------------/
\---------------/ \--------------/
</code></pre>
<p>I'm aware I use a bit more horizontal whitespace than normal. I find it easier to parse. Sorry if that's jarring.</p>
<p>I'm new to the language so suggestions on a more idiomatic style would be appreciated. I'm fairly sure there's something I should do differently around initialization of the track layout. I'm also a bit unsatisfied with the way it's continuously replacing the map. Fortunately, I don't have to manage the resources myself and I can see memory usage stays flat, but I can't help wonder if there isn't a better way.</p>
| [] | [
{
"body": "<p>Your code is quite good, but could be more concise.</p>\n\n<p>Specifically, I don't see why you would need all those <code>class</code>es and <code>enums</code>: a <code>track</code>, for instance, is adequately represented by the same <code>char</code> that is used for displaying it. Carts are only a bit more complicated, since you have to remember which direction it chose last, but a <code>std::pair<char, char></code> is quite enough. Besides, actual chars are more expressive than <code>enum</code>s, for instance:</p>\n\n<pre><code>char change_direction(char current) {\n switch (current) {\n case '<': return '^';\n case '^': return '>';\n case '>': return '<';\n default: throw bad_direction();\n }\n}\n</code></pre>\n\n<p>'x' can be used to represent a crash.</p>\n\n<p>It is also very simple to keep track of each track and cart position by maintaining two arrays representing the grid on which they are positioned.</p>\n\n<p>So two <code>std::array</code>s are enough to represent all your data. The <code>tick</code> function can have the signature <code>std::vector<int> tick(const std::array<char, N>& tracks, std::array<std::pair<char, char>, N>& carts)</code>: it lets all carts advance once and returns a vector of the crashes that occurred during the turn.</p>\n\n<p>You then have a really simple loop as your program:</p>\n\n<pre><code>constexpr std::array<char, N> tracks { /* input */ };\nstd::array<char, N> carts { /* input */ };\nconstexpr auto is_cart = [](char c) { c != ' '; };\nint nb_carts = std::count_if(carts.begin(), carts.end(), is_cart);\n\nint first_crash_location = -1;\nint last_cart_location = -1;\nwhile (true) {\n std::vector<int> crashes = tick(tracks, carts);\n if (first_crash_location == -1 && !crashes.empty())\n first_crash_location == *crashes.begin();\n nb_carts -= crashes.size();\n if (nb_carts == 1) {\n last_cart_location = std::distance(carts.begin(), \n std::find_if(carts.begin(), carts.end(), is_cart));\n break;\n}\n</code></pre>\n\n<p>That leaves only the <code>tick</code> function to be implemented. The only tedious thing is to iterate over the array of carts in the good order (row by row, beginning with the last row), but the general idea is:</p>\n\n<pre><code>for each cell of cart_array in the good order:\n if there is a cart:\n position = compute_next_position(cart)\n clear cell\n if occupied(position, cart_array): add crash to result, clear position\n else: cart_array[position] = new_direction_cart(cart, position, track_array)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T11:47:09.177",
"Id": "209665",
"ParentId": "209660",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:21:03.653",
"Id": "209660",
"Score": "3",
"Tags": [
"c++",
"beginner",
"programming-challenge",
"c++14"
],
"Title": "Advent of Code 2018 Day 13 - Detect mine cart collisions"
} | 209660 |
<p>I think Ruby is kinda interesting, so did this <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">Game of life</a> implement in Ruby. I am wonder is there is <em>some magic in Ruby</em> can let my code more elegant. </p>
<p>I am a python coder and I think my Ruby kinda smell like Python now xD(and with lots <code>end</code>)</p>
<pre><code>def lifegame(grid)
alive = 1
die = 0
while not lifeless(grid, alive)
print grid
print "\n"
next_round = update(grid, alive, die)
if next_round == grid
puts "In stable exiting..."
break
end
grid = next_round
end
end
def lifeless(grid, alive)
0.upto(grid.length-1) do |i|
0.upto(grid[0].length-1) do |j|
if(grid[i][j] == alive)
return false
end
end
end
return true
end
def update(grid, alive, die)
next_round = Array.new(grid.length){Array.new(grid[0].length, die)}
0.upto(grid.length-1) do |i|
0.upto(grid[0].length-1) do |j|
next_round[i][j] = evolve(grid, i, j, alive, die)
end
end
return next_round
end
def evolve(grid, i, j, alive, die)
directions = [[0,1],[0,-1],[1,0],[-1,0],[1,1],[1,-1],[-1,1],[-1,-1]]
t = 0
directions.each do |direction|
if (i+direction[0] >= 0 and i+direction[0] < grid.length and j+direction[1] >= 0 and j+direction[1] < grid[0].length)
if(grid[i+direction[0]][j+direction[1]] == alive)
t += 1
end
end
end
if((grid[i][j] == alive and (t < 2 or t > 3)) or (grid[i][j] == die and t != 3))
return die
else
return alive
end
end
grid = [[0,0,1,0,0],[1,0,1,0,0],[0,1,1,0,0],[0,0,0,0,0],[0,0,0,0,0]]
lifegame grid
</code></pre>
<h3><code>class</code> version</h3>
<p>Thanks for @Johan Wentholt's advice about <code>class</code></p>
<p>Here is my update code with custom class</p>
<p>Any advices all welcome!</p>
<pre><code>class Game
WIDTH = 5
HEIGHT = 5
SEEDS = [[0,2],[1,0],[1,2],[2,1],[2,2]]
def initialize
@grid = Grid.new(WIDTH, HEIGHT)
@grid.plant_seeds(SEEDS)
end
def start
while not @grid.lifeless?
puts @grid
next_grid = update()
if(@grid == next_grid)
break
end
@grid = next_grid
end
end
def update
next_round = Grid.new(WIDTH, HEIGHT)
0.upto(WIDTH-1) do |row|
0.upto(HEIGHT-1) do |column|
next_round.update(row, column, evolve(row, column))
end
end
return next_round
end
def evolve(row, column)
directions = [[0,1],[0,-1],[1,0],[-1,0],[1,1],[1,-1],[-1,1],[-1,-1]]
t = 0
directions.each do |i, j|
if (row+i >= 0 and row+i < WIDTH and column+j >= 0 and column+j < HEIGHT)
if(@grid.cell_alive(row+i,column+j))
t += 1
end
end
end
return ((@grid.cell_alive(row,column) and (t == 2 or t == 3)) or (not @grid.cell_alive(row,column) and t == 3))
end
end
class Grid
def initialize(width, height)
@width = width
@height = height
@grid = setup_grid
end
def setup_grid
grid = []
@width.times do |row|
cells = []
@height.times do |column|
cells << Cell.new(false)
end
grid << cells
end
return grid
end
def plant_seeds(seeds)
seeds.each do |x,y|
@grid[x][y].live!
end
end
def update(row, column, value)
@grid[row][column].change_state(value)
end
def cell_alive(row, column)
return @grid[row][column].alive?
end
def lifeless?
not @grid.any?{|row| row.any?{|cell| cell.alive?}}
end
def to_s
rows = []
0.upto(@width-1) do |row|
columns = []
0.upto(@height-1) do |column|
columns << @grid[row][column].to_s
end
rows << columns.join("")
end
return rows.join("\n") + "\n\n"
end
def ==(other)
0.upto(@width-1) do |row|
0.upto(@height-1) do |column|
if cell_alive(row, column) != other.cell_alive(row, column)
return false
end
end
end
return true
end
end
class Cell
def initialize(alive)
@alive = alive
end
def change_state(state)
@alive = state
end
def alive?
@alive
end
def live!
@alive = true
end
def to_s
if @alive
return "x"
else
return "."
end
end
end
game = Game.new()
game.start()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T12:33:11.320",
"Id": "405243",
"Score": "0",
"body": "My first question would be if you avoid custom classes for a reason? I would at least have the classes *Grid* and *Cell*, maybe the class *Game*. You're current solution seems inspired by a functional programming, however Ruby is an object oriented language which should be used to your advantage. I could provided you with an more object oriented example if you want. However if you're not interested in using classes there is no point in working out an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T14:20:45.657",
"Id": "405253",
"Score": "0",
"body": "@JohanWentholt Ah I am not **avoid** classes, just hmm not think of it, thanks for your advice, I will update my code with classes. I am curious for the reason why \"However if you're not interested in using classes there is no point in working out an answer\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:53:45.583",
"Id": "405283",
"Score": "0",
"body": "I'll add my answer below somewhere this weekend. The reason I asked if you avoided classes is because it would result in wasted effort to work out an example if you intentionally avoided that approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T21:44:15.073",
"Id": "405308",
"Score": "0",
"body": "yup, smells like Python with a scent of Pascal :D"
}
] | [
{
"body": "<p>Like <a href=\"https://codereview.stackexchange.com/questions/209661/game-of-life-in-ruby#comment405243_209661\">I said in the comments</a> Ruby is an object oriented language. However in your first attempt you don't make use of custom classes and object at all. In your second attempt you do use custom classes, but in my opinion the design can be done better.</p>\n\n<h3>Simple way to spot \"bad\" Ruby code</h3>\n\n<p>One of the simplest ways to spot \"bad\" Ruby code is by the use of manual iteration. Ruby provides plenty of iterators that could be used instead of manually iterating over an collection. Examples are <a href=\"https://ruby-doc.org/core-2.5.3/Array.html#method-i-each\" rel=\"nofollow noreferrer\"><code>each</code></a>, <a href=\"https://ruby-doc.org/core-2.5.3/Array.html#method-i-each_index\" rel=\"nofollow noreferrer\"><code>each_with_index</code></a>, <a href=\"https://ruby-doc.org/core-2.5.3/Array.html#method-i-map\" rel=\"nofollow noreferrer\"><code>map</code></a>, <a href=\"https://ruby-doc.org/core-2.5.3/Enumerable.html#method-i-none-3F\" rel=\"nofollow noreferrer\"><code>none?</code></a>, <a href=\"https://ruby-doc.org/core-2.5.3/Enumerable.html#method-i-all-3F\" rel=\"nofollow noreferrer\"><code>all?</code></a>, <a href=\"https://ruby-doc.org/core-2.5.3/Array.html#method-i-any-3F\" rel=\"nofollow noreferrer\"><code>any?</code></a> and many others.</p>\n\n<p>In some cases you may not be able to work around manual iteration, but most scenarios have a build-in solution.</p>\n\n<p>In case you need the index with <code>map</code> you can make use of the <a href=\"https://ruby-doc.org/core-2.5.3/Enumerator.html\" rel=\"nofollow noreferrer\">enumerator</a> returned if no block is provided.</p>\n\n<pre><code>array.map.with_index { |element, index| ... }\n</code></pre>\n\n<h3>Game rules</h3>\n\n<p>Let's first address the rules of the game:</p>\n\n<ol>\n<li>Any live cell with fewer than two live neighbours dies, as if by under-population.</li>\n<li>Any live cell with two or three live neighbours lives on to the next generation.</li>\n<li>Any live cell with more than three live neighbours dies, as if by overpopulation.</li>\n<li>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</li>\n</ol>\n\n<h3>Rule evaluation</h3>\n\n<p>The rules are all about the amount of neighbours that is alive. <strong>A cell could check this for himself if he knew who his neighbours are.</strong> For this reason I would leave the placement and neighbour assignment up to the <em>Grid</em>, but I would leave the state checking to the <em>Cell</em> itself. This would also eliminate a lot of the coordinate usage, since a cell doesn't care if a neighbour lives above, next or under him. The only thing that matters is the amount of neighbours alive. The only place where you still need the coordinates is when placing the cells and when assigning the neighbours of each cell.</p>\n\n<p>In my opinion the code becomes a lot more readable when it speaks for itself.</p>\n\n<h3>Advantages of working with classes</h3>\n\n<p>Working with classes comes most of the time with some overhead (which can be seen in my example below), but has several advantages.</p>\n\n<ul>\n<li>When working with classes the methods are namespaced in the class. Keeping the global namespace free from clutter.</li>\n<li>You can assign certain classes certain responsibilities. This makes it easier to maintain code since you know where you should look for certain problems.</li>\n</ul>\n\n<h3>Responsibilities</h3>\n\n<p>I've chosen the following responsibilities for the different classes: </p>\n\n<ul>\n<li><p><em>Cell</em></p>\n\n<p>A cell is responsible for its own state and the transition to the next state. It has references to its neighbours to check this.</p></li>\n<li><p><em>Grid</em></p>\n\n<p>The grid is responsible for creating the grid, creating initially activated cells and assigning each cell its neighbours.</p></li>\n<li><p><em>Game</em></p>\n\n<p>The game is responsible for grid instantiation and manages the game cycles to progress the grid further.</p></li>\n</ul>\n\n<h3>Code Example</h3>\n\n<pre><code>class Cell\n RELATIVE_NEIGHBOUR_COORDINATES = {\n north: [-1, 0].freeze, north_east: [-1, 1].freeze,\n east: [0, 1].freeze, south_east: [1, 1].freeze,\n south: [1, 0].freeze, south_west: [1, -1].freeze,\n west: [0, -1].freeze, north_west: [-1, -1].freeze,\n }.freeze\n\n NEIGHBOUR_DIRECTIONS = RELATIVE_NEIGHBOUR_COORDINATES.keys.freeze\n\n attr_accessor(*NEIGHBOUR_DIRECTIONS)\n\n def initialize(alive = false)\n @alive = !!alive # \"!!\" converts alive value to boolean\n end\n\n def alive?\n @alive\n end\n\n def live!\n @alive = true\n end\n\n def die! # currently unused\n @alive = false\n end\n\n ##\n # Queues the next state. Returns true if the state is going to change and \n # false if it stays the same.\n def queue_evolve\n @queued_alive = alive_next_cycle?\n\n @alive != @queued_alive\n end\n\n ##\n # Applies the queued state. Returns true if the state changed and false if the\n # state stayed the same.\n def apply_queued_evolve\n old_alive = @alive\n\n @alive = @queued_alive\n\n old_alive != @alive\n end\n\n def alive_next_cycle?\n alive_neighbours = neighbours.count(&:alive?)\n\n if alive?\n (2..3).cover?(alive_neighbours)\n else\n alive_neighbours == 3\n end\n end\n\n def going_to_change?\n alive? != alive_next_cycle?\n end\n\n ##\n # Used to get a neighbour in dynamic fashion. Returns the neighbouring cell or\n # nil if there is no neighbour on the provided direction.\n #\n # cell[:north]\n # #=> neighbouring_cell_or_nil\n #\n def [](direction)\n validate_direction(direction)\n send(direction)\n end\n\n ##\n # Used to set a neighbour in dynamic fashion. Returns the provided neighbour.\n #\n # cell[:south] = other_cell \n # #=> other_cell\n #\n def []=(direction, neighbour)\n validate_direction(direction)\n send(\"#{direction}=\", neighbour)\n end\n\n ##\n # Returns a list of all present neighbours.\n def neighbours\n NEIGHBOUR_DIRECTIONS.map(&method(:[])).compact\n end\n\n ##\n # Returns a hash of neighbours and their positions.\n #\n # cell.neighbours_hash\n # #=> {\n # north: nil,\n # north_east: nil,\n # east: some_cell,\n # south_east: some_other_cell,\n # # ...\n # }\n #\n def neighbours_hash # currently unused\n NEIGHBOUR_DIRECTIONS.map { |dir| [dir, self[dir]] }.to_h\n end\n\n ##\n # Returns \"x\" if the cell is alive and \".\" if the cell is not.\n def to_s\n alive? ? 'x' : '.'\n end\n\n ##\n # Since neighbours point to each other the default inspect results in an\n # endless loop. Therefore this is overwritten with a simpler representation.\n #\n # #<Cell dead> or #<Cell alive>\n #\n def inspect\n \"#<#{self.class} #{alive? ? 'alive' : 'dead'}>\"\n end\n\n private\n\n def validate_direction(direction)\n unless NEIGHBOUR_DIRECTIONS.map(&:to_s).include?(direction.to_s)\n raise \"unsupported direction #{direction}\"\n end\n end\nend\n\nclass Grid\n def initialize(width, height, seeds = [])\n @cells = Array.new(width * height).map { Cell.new }\n @grid = @cells.each_slice(width).to_a\n\n seeds.each { |coordinate| @grid.dig(*coordinate).live! }\n\n assign_cell_neighbours\n end\n\n ##\n # Returns true if the resulting grid changed after evolution.\n def evolve\n # Keep in mind that any? short circuits after the first truethy evaluation.\n # Therefore the following line would yield incorrect results.\n #\n # @cells.each(&:queue_evolve).any?(&:apply_queued_evolve)\n #\n\n @cells.each(&:queue_evolve).map(&:apply_queued_evolve).any?\n end\n\n ##\n # Returns true if the next evolutions doesn't change anything.\n def lifeless?\n @cells.none?(&:going_to_change?)\n end\n\n ##\n # Returns the grid in string format. Placing an \"x\" if a cell is alive and \".\"\n # if a cell is dead. Rows are separated with newline characters.\n def to_s\n @grid.map { |row| row.map(&:to_s).join }.join(\"\\n\")\n end\n\n private\n\n ##\n # Assigns every cell its neighbours. @grid must be initialized.\n def assign_cell_neighbours\n @grid.each_with_index do |row, row_index|\n row.each_with_index do |cell, column_index|\n Cell::RELATIVE_NEIGHBOUR_COORDINATES.each do |dir, rel_coord|\n (rel_row_index, rel_column_index) = rel_coord\n neighbour_row_index = row_index + rel_row_index\n neighbour_column_index = column_index + rel_column_index\n\n next if neighbour_row_index.negative? || \n neighbour_column_index.negative?\n\n cell[dir] = @grid.dig(neighbour_row_index, neighbour_column_index)\n end\n end\n end\n end\nend\n\nclass Game\n def initialize(width, height, seeds)\n @width = width\n @height = height\n @seeds = seeds\n end\n\n def reset\n @grid = Grid.new(@width, @height, @seeds)\n end\n\n def start\n reset\n\n puts @grid\n\n until @grid.lifeless?\n @grid.evolve\n\n puts\n puts @grid\n end\n end\nend\n\ngame = Game.new(5, 5, [[0,2], [1,0], [1,2], [2,1], [2,2]])\ngame.start\n</code></pre>\n\n<p>The reason cell needs to update its state in two steps is simple. It can't depend upon the new state of one of its neighbours. For this reason all cells prepare their new state first before applying the prepared state.</p>\n\n<h3>References</h3>\n\n<p>Most things speak for themselves, however I still think some references are needed for the not so obvious (Ruby specific) code.</p>\n\n<ul>\n<li><p>The <a href=\"https://ruby-doc.org/core-2.5.3/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion\" rel=\"nofollow noreferrer\">splat operator</a> (<code>*</code>) used to use the contents of an array as individual arguments. Used in the lines:</p>\n\n<pre><code>@grid.dig(*coordinate)\n# and\nattr_accessor(*NEIGHBOUR_DIRECTIONS)\n</code></pre></li>\n<li><p><a href=\"https://ruby-doc.org/core-2.5.3/Module.html#method-i-attr_accessor\" rel=\"nofollow noreferrer\"><code>attr_accessor</code></a> is used to create getters and setters for the different neighbour directions.</p>\n\n<pre><code>attr_accessor(:north) # or attr_accessor :north\n# is the same as\ndef north\n @north\nend\n\ndef north=(value)\n @north = value\nend\n</code></pre>\n\n<p>This allows <code>cell.north</code> to fetch the north neighbour and <code>cell.north = neighbour</code> to set the north neighbour.</p></li>\n<li><p>The use of <a href=\"https://ruby-doc.org/core-2.5.3/Object.html#method-i-send\" rel=\"nofollow noreferrer\"><code>send</code></a> to dynamically call methods inside the <em>Cell</em> class.</p></li>\n<li><p><a href=\"https://ruby-doc.org/core-2.5.3/doc/syntax/assignment_rdoc.html#label-Array+Decomposition\" rel=\"nofollow noreferrer\">Array decomposition assignment</a> done in the following line:</p>\n\n<pre><code>(rel_row_index, rel_column_index) = rel_coord\n</code></pre></li>\n<li><p>Block passing. I currently can't find a reference for this. But the following things yield the same result.</p>\n\n<pre><code>numbers = [1, 2, 3, 4]\n\nnumbers.map { |number| number.to_s }\n#=> [\"1\", \"2\", \"3\", \"4\"]\n# is the same as\nnumbers.map(&:to_s) \n#=> [\"1\", \"2\", \"3\", \"4\"]\n#===========================================\n\ndef some_method(number)\n number.to_s\nend\n\nnumbers.map { |number| some_method(number) }\n#=> [\"1\", \"2\", \"3\", \"4\"]\n# is the same as\nnumber.map(&method(:some_method))\n#=> [\"1\", \"2\", \"3\", \"4\"]\n</code></pre></li>\n</ul>\n\n<p>Most other methods I use (e.g. <code>none?</code>, <code>each_slice</code>) can be found in the <a href=\"https://ruby-doc.org/core-2.5.3/Enumerable.html\" rel=\"nofollow noreferrer\"><code>Enumerable</code></a> module.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:22:09.917",
"Id": "405492",
"Score": "0",
"body": "I've thrown my my on spin on your solution. If there is any code you don't understand just ask and I'll add some clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T07:03:37.533",
"Id": "405942",
"Score": "0",
"body": "Thanks again. hmm yup some of your improvments are overhead to me, but I think will try to practice more to well understand them ^^, splat operator and decomposition also exist in python, I used write swift, so attr_accessor and block are not so new to me, but the `send` is really new, and the `iteration` ! I am curious what you plan to do with `neighbours_hash`, as I am not used to do so in python(maybe because I am a bad coder ^^)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T19:15:31.717",
"Id": "406254",
"Score": "0",
"body": "@Aries_is_there I used *Cell#neighbours_hash* when coding to check if the neighbours where set correctly. But I left it because it might become in handy when you wan't to do more dynamic programming. When you call `cell[:with_a_key_that_does_not_exist]` it will raise a *RuntimeError*. While converting it to a hash and than calling `neighbours_hash[:with_a_key_that_does_not_exist]` will result in `#=> nil`. If you where to add the method `Cell#assign_neighbours` you might want to use an hash as parameter. This could be in the same format as the output of *Cell#neighbours_hash*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T15:59:55.757",
"Id": "209723",
"ParentId": "209661",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209723",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T08:36:00.590",
"Id": "209661",
"Score": "5",
"Tags": [
"ruby",
"game-of-life"
],
"Title": "Game of Life in Ruby"
} | 209661 |
<p>I am new to Java and had some difficulty creating this simple Publisher Subscriber class. It finally seems to be working and I wanted to check if I have been following best practices and see if there are any improvements I can make.</p>
<p>The following Java class accepts any topics as a string (e.g. "rand_int") and forwards any messages to that topic to any subscribers.</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
public class PubSub {
private Map<String, ArrayList<Consumer<?>>> topicsSubscribers =
new HashMap<String, ArrayList<Consumer<?>>>();
private static PubSub pubSubSingleton = null;
public static PubSub getInstance() {
if (pubSubSingleton == null)
pubSubSingleton = new PubSub();
return pubSubSingleton;
}
public <T> void publish(String topic, T message) {
ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topic);
if (subscribers == null)
return;
for (Consumer subscriberConsumer : subscribers) {
subscriberConsumer.accept(message);
}
}
public synchronized <T> void subscribe(String topicName, Consumer<T> subscriberCallback) {
ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topicName);
if (subscribers == null) {
subscribers = new ArrayList<Consumer<?>>();
subscribers.add(subscriberCallback);
this.topicsSubscribers.put(topicName, subscribers);
} else {
subscribers.add(subscriberCallback);
}
}
}
</code></pre>
<p>Example usage:</p>
<pre><code>public class SomeClass {
public SomeClass() {
PubSub.getInstance().subscribe("rand_int", this::randIntCallback);
PubSub.getInstance().publish("rand_int", 46);
}
public randIntCallback(int number) {
System.out.println(number);
}
}
</code></pre>
<p>The above code should output "46".</p>
<p>As I said, I am very new to Java and would like some feedback on my code to help improve. So any help on this is very appreciated. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:23:50.677",
"Id": "405281",
"Score": "1",
"body": "Your error message is off topic for this site. If you pared it down to an MCVE, it would be on-topic on Stack Overflow. But it would likely get closed as a duplicate of a question like [this](https://stackoverflow.com/q/14524751/6660678)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:36:24.653",
"Id": "405282",
"Score": "0",
"body": "Thanks mdfst13. Yes I only kept the error as the reason I wasn't able to improve my code a certain way. But I suppose you are right it's a bit off topic. Thanks for your answer as well. All very good points which I will look into and implement as much as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T22:12:44.127",
"Id": "405313",
"Score": "0",
"body": "You should give others some time to write an answer too before you accept the first answer you get."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T17:01:16.753",
"Id": "405352",
"Score": "0",
"body": "@EmilyL. I originally was going to wait but figured if a better answer comes along I can just change the accepted answer. Is that not possible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T17:04:35.820",
"Id": "405353",
"Score": "0",
"body": "Sure but it discourages others from answering."
}
] | [
{
"body": "<h3>Initializing object variables</h3>\n\n<blockquote>\n<pre><code> private Map<String, ArrayList<Consumer<?>>> topicsSubscribers =\n new HashMap<String, ArrayList<Consumer<?>>>();\n</code></pre>\n</blockquote>\n\n<p>The standard is to set the types as the interfaces, like <code>Map</code> and <code>List</code>. </p>\n\n<pre><code> private final Map<String, List<Consumer<?>>> topicSubscribers = new HashMap<>();\n</code></pre>\n\n<p>Also, you don't need to specify the contents of <code><></code> in the implementation instantiation. The compiler will work that out for you. </p>\n\n<h3>Initializing class variables</h3>\n\n<blockquote>\n<pre><code> private static PubSub pubSubSingleton = null;\n\n public static PubSub getInstance() {\n if (pubSubSingleton == null)\n pubSubSingleton = new PubSub();\n\n return pubSubSingleton;\n }\n</code></pre>\n</blockquote>\n\n<p>You don't have to do it this way. You can simply say </p>\n\n<pre><code> private static final PubSub pubSubSingleton = new PubSub();\n\n public static PubSub getInstance() {\n return pubSubSingleton;\n }\n\n private PubSub() {\n }\n</code></pre>\n\n<p>This saves the null check each time while still only initializing once. </p>\n\n<p>However, Singleton is generally considered an anti-pattern now. You may want to consider <a href=\"https://stackoverflow.com/q/1300655/6660678\">alternatives</a>. One possibility would be a separate instance for each message type. </p>\n\n<p>Your original code does not make the constructor private. </p>\n\n<p>The Java standard is four column indents rather than the two you are using. </p>\n\n<h3>Formatting</h3>\n\n<blockquote>\n<pre><code> if (subscribers == null)\n return;\n</code></pre>\n</blockquote>\n\n<p>If you are going to use the statement form, you should probably keep it one line: </p>\n\n<pre><code> if (subscribers == null) return;\n</code></pre>\n\n<p>If it's too complicated to fit into one line, you should probably use the block form instead. </p>\n\n<p>I actually use the block form consistently regardless. </p>\n\n<pre><code> if (subscribers == null) {\n return;\n }\n</code></pre>\n\n<h3>Factor out the common</h3>\n\n<blockquote>\n<pre><code> if (subscribers == null) {\n subscribers = new ArrayList<Consumer<?>>();\n subscribers.add(subscriberCallback);\n this.topicsSubscribers.put(topicName, subscribers);\n } else {\n subscribers.add(subscriberCallback);\n }\n</code></pre>\n</blockquote>\n\n<p>This could be </p>\n\n<pre><code> if (subscribers == null) {\n subscribers = new ArrayList<Consumer<?>>();\n topicsSubscribers.put(topicName, subscribers);\n }\n\n subscribers.add(subscriberCallback);\n</code></pre>\n\n<p>You don't have to do the <code>add</code> before the <code>put</code>. It's the same object either way. Otherwise, you'd have to do the <code>put</code> after the <code>add</code> in the non-null case. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:21:38.017",
"Id": "209685",
"ParentId": "209670",
"Score": "4"
}
},
{
"body": "<p>We consider singletons bad (i.e. your <code>getInstance</code> bit). There are numerous resources on why a short search away so I'm not going to list them here. </p>\n\n<p>That said your <code>getInstance</code> is not safe in a threaded context. You need to use <a href=\"https://en.wikipedia.org/wiki/Double-checked_locking\" rel=\"nofollow noreferrer\">Double-checked locking</a>. Note that I do think that initialising the object in the <em>static</em> constructor or inline with the declaration is safe as well.</p>\n\n<p>Your <code>subscribe</code> method is <code>synchronized</code> on the class object but the <code>publish</code> method is not meaning that you have a data race where the subscribers for a topic may change in the middle of iterating over it, typically this will throw a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html\" rel=\"nofollow noreferrer\">ConcurrentModificationException</a> when it happens. Either you do a thread safe design and add <code>synchronized</code> to <code>publish</code> as well or do a thread-un-safe design and remove the <code>synchronized</code> keyword everywhere.</p>\n\n<p>Your <code>publish</code> method swallows any errors. This is not good. Depending on your philosophy on error reporting you should either return a boolean signifying the success or failure of publishing the message to at least one receiver or throw an exception. In this case I would return an error, or maybe even the number of subscribers that the message was delivered too, yeah I think that makes more sense and is cheap to compute and rich in information.</p>\n\n<p>And finally, your class will forever hold a reference to the subscriber object and is likely to cause a memory leak as you cannot remove them, especially since this is a singleton which has the same lifetime as your application. A common pattern is to either allow removal through <code>unsubscribe</code> or use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html\" rel=\"nofollow noreferrer\">WeakReference</a> and let the life time be tied to an external object with cleanup of any weak references whose get returns null (object removed/gcd)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T22:11:56.207",
"Id": "209700",
"ParentId": "209670",
"Score": "2"
}
},
{
"body": "<p>One small addition to what the others said: </p>\n\n<pre><code>ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topicName);\nif (subscribers == null) {\n subscribers = new ArrayList<Consumer<?>>();\n subscribers.add(subscriberCallback);\n ...\n</code></pre>\n\n<p>is an outdated pattern. Since java 8 (i.e. 4.5 years now) we have <code>computeIfAbsent</code> in the Map. Therefore, use:</p>\n\n<pre><code>ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.computeIfAbsent(sub -> new ArrayList<>());\n</code></pre>\n\n<p>instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T14:59:48.847",
"Id": "405414",
"Score": "0",
"body": "Thanks for the tip. But wouldn't `putIfAbsent ()` be more appropriate here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T06:19:57.797",
"Id": "405478",
"Score": "1",
"body": "@KNejad No. For `putIfAbsent` you'd have to create a new list for every call which would be discarded in most cases. For `computeIfAbsent` you pass a supplier, which will only be called to create a new list if needed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T06:58:35.233",
"Id": "209754",
"ParentId": "209670",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209685",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T13:53:53.233",
"Id": "209670",
"Score": "4",
"Tags": [
"java",
"beginner",
"singleton",
"callback"
],
"Title": "Simple Publisher Subscriber in Java"
} | 209670 |
<p>This is my first attempt at React and I don't want to pick up any bad habits for the long term. The code is adopted from a example app, but I have added a fair amount of new features. I.e. </p>
<p>Clicking on the item allows it to be edited
Delete Option
Option to mark the items as Complete / Uncompleted</p>
<p>Any feedback would be appreciated. </p>
<pre><code> var data = [
{text: "Click me to edit!",
key: 43534534534534534,
show: false,
completed: false},
{text: "This is a long task that fits over multiple lines!",
key: 2453534566554353,
show: false,
completed: false
},
{ text: "This is a complted task",
key: 4353443534534534534,
show: false,
completed: true
}
]
class App extends React.Component {
inputElement = React.createRef()
constructor() {
super();
this.state = {
items: data,
currentItem: {
text: '',
key: '',
show: false,
completed: false
},
};
}
changeStatus = key =>{
const tempItems = this.state.items.slice()
tempItems.forEach((item) => {
if (item.key===key){
item.completed = !item.completed;
}
})
this.setState({
items: tempItems,
})
}
deleteItem = key => {
const filteredItems = this.state.items.filter(item => {
return item.key !== key
})
this.setState({
items: filteredItems,
})
}
showEditItemForm = (key) => {
const tempItems = this.state.items.slice()
tempItems.forEach((item) => {
if (item.key===key && !item.completed){
item.show = !item.show;
}
else
{
item.show = false
}
})
this.setState({
items: tempItems,
})
}
editItem = (key, NewText) => {
const tempItems = this.state.items.slice()
tempItems.forEach((item) => {
if (item.key===key){
item.text = NewText
item.show = false
item.completed = false
}
})
this.setState({
items: tempItems,
})
}
handleInput = e => {
const itemText = e.target.value
const currentItem = { text: itemText, key: Date.now() }
this.setState({
currentItem,
})
}
addItem = e => {
e.preventDefault()
const newItem = this.state.currentItem
if (newItem.text !== '') {
const items = [...this.state.items, newItem]
this.setState({
items: items,
currentItem: { text: '', key: '', show: false },
})
data = JSON.stringify(state.items)
}}
render() {
return (
<div className="App">
<TodoList
addItem={this.addItem}
inputElement={this.inputElement}
handleInput={this.handleInput}
currentItem={this.state.currentItem}
/>
<TodoItems entries={this.state.items} deleteItem={this.deleteItem} editItem={this.editItem} showEditItemForm={this.showEditItemForm} changeStatus = {this.changeStatus} />
</div>
);
}
}
class TodoList extends React.Component {
componentDidUpdate() {
this.props.inputElement.current.focus()
}
render() {
return (
<div className="todoListMain">
<div className="header">
<form onSubmit={this.props.addItem}>
<input
placeholder="Task"
ref={this.props.inputElement}
value={this.props.currentItem.text}
onChange={this.props.handleInput}
/>
<button type="submit"> Add Task </button>
</form>
</div>
</div>
)
}
}
class TodoItems extends React.Component {
constructor() {
super()
this.state = {
updatedText: '',
}
this.updateText = this.updateText.bind(this);
}
updateText(event){
this.setState({updatedText : event.target.value})
}
createTasks = item => {
var txtClass = item.completed ? 'completed' : 'uncompleted';
return (
<li key={item.key}>
{ !item.show &&
<div className="item-container">
<span className="control-containers checkbox-padding">
<input className="status-checkbox" type="checkbox" name="status" value="" checked={item.completed} onChange={() => this.props.changeStatus(item.key)}></input>
</span>
<span className={`item-text ${txtClass}`} onClick={() => this.props.showEditItemForm(item.key)}>{item.text}</span>
<span className="control-containers">
<button className="delete-button" onClick={() => this.props.deleteItem(item.key)}>Delete</button>
</span>
</div>
}
{item.show &&
<div>
<input className="edit-input" type="text" name="ItemText" title="Item Text" autoFocus={true} defaultValue={item.text} onFocus={this.updateText} onChange={this.updateText} />
<button className="save" onClick={() => this.props.editItem(item.key, this.state.updatedText)} >Save</button>
<button className="cancel" onClick={() => this.props.showEditItemForm(item.key)}>Close</button>
</div>
}
</li>
)
}
render() {
const todoEntries = this.props.entries
const listItems = todoEntries.map(this.createTasks)
return <ul className="theList">{listItems}</ul>
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</code></pre>
<p>Working demo can be found here: <a href="https://codepen.io/SA2018/pen/ebZzKV" rel="nofollow noreferrer">Codepen Demo</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T21:34:10.023",
"Id": "405306",
"Score": "0",
"body": "(Welcome to Code Review!) (The indentation of your code looks inconsistent, starting with `var data = […]`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T21:41:43.950",
"Id": "405307",
"Score": "0",
"body": "I had a right game getting the app working on a pen. It was coded in vs code in multiple files. The data in the var was originally a js file. While converting the code in a format so it works on a pen, all code formatting went out of the window."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T13:58:09.833",
"Id": "209671",
"Score": "3",
"Tags": [
"beginner",
"react.js",
"jsx",
"to-do-list"
],
"Title": "First React App: ToDo list"
} | 209671 |
<p>This question is a small subset of the problem I am trying to solve.
I am trying to learn to break problems into better abstractions.</p>
<p>The original problem I am trying to solve is:</p>
<blockquote>
<p>Write a JS library which allows an user to select an Image and then divide the image into square tiles. Calculate the average color of each tile and render the equivalent number of svg elements from top to bottom and left to right direction. The request for each svg element should be an XHR request.</p>
</blockquote>
<p>I decided to create two abstractions for now:</p>
<ol>
<li>Grid</li>
<li>Tile</li>
</ol>
<p>here is the code:</p>
<pre><code>class Tile {
constructor(shape='', width = Tile.Width, height = Tile.Height) {
this.shape = shape;
this.width = width;
this.height = height;
}
render() {
return this.shape;
}
}
Tile.Width = 50;
Tile.Height = 50;
class Grid {
constructor(rows, cols) {
this.cells = [];
this.R = rows;
this.C = cols;
for (let row = 0; row < rows; row++) {
const cells = [];
for (let col = 0; col < cols; col++) {
cells.push({
x: col * Tile.Width,
y: row * Tile.Height,
tile: new Tile()
});
}
this.cells.push(cells);
}
}
setTile(shape, {row, col}) {
if (row < 0 || row >= this.R || col < 0 || col >= this.C) {
throw new Error("Invalid tile position");
}
this.cells[row][col] = {
x: col * Tile.Width,
y: row * Tile.Height,
tile: new Tile(shape)
};
}
render() {
let output = [];
this.cells.forEach(row => {
output.push(this.renderRow(row));
});
console.log(output.join('\n'));
}
renderRow(cells) {
let output = [];
cells.forEach(cell => {
output.push(cell.tile.render());
});
return output.join(' ');
}
}
const grid = new Grid(2, 2);
grid.setTile('', {row: 0, col: 1});
grid.setTile('', {row: 1, col: 0});
grid.setTile('', {row: 0, col: 1});
grid.setTile('', {row: 1, col: 1});
console.log(grid.render());
</code></pre>
<p><a href="https://repl.it/@vivekimsit/PaleIdolizedHypotenuse" rel="nofollow noreferrer">Here</a> is the live example.</p>
<p><strong>Question</strong></p>
<p>Does the design of the grid system is compatible with the requirement so far? I want it to be used in the canvas or some other rendering platform so is this a good design?</p>
| [] | [
{
"body": "<h2>Your question</h2>\n\n<blockquote>\n <p>Does the design of the grid system is compatible with the requirement so far?</p>\n</blockquote>\n\n<p>Well, maybe I don't understand how setting characters (be them Unicode if necessary, as your example shows) on each tile relates to dividing an image into squares but it seems like you would want to allow the user to upload or choose an image (perhaps from a list), which might likely be a binary file. Then you would need to do some graphical analysis of the image and divide up the area of the image (perhaps using the dimensions).</p>\n\n<h2>Feedback on code</h2>\n\n<h3>Design</h3>\n\n<p>It appears that when a Grid object is created, it creates cells as plain objects that have an <code>x</code>, <code>y</code> and <code>tile</code> property. Then when the <code>setTile()</code> method is called, it re-assigns those cells, but the only thing that really changes is the tile, so the calculations of <code>x</code> and <code>y</code> seem unnecessary. Additionally, the tile object doesn't need to be recreated - the shape property could be simply re-assigned - perhaps via a setter method, but that property is public so it could be modified outside the class unless it is made <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations\" rel=\"nofollow noreferrer\">private</a> (though that is only experimental<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n\n<h3>forEach with <code>push</code></h3>\n\n<p>The <code>render()</code> method of the Grid uses <code>foreach</code> with <code>push</code>:</p>\n\n<blockquote>\n<pre><code>let output = [];\nthis.cells.forEach(row => {\n output.push(this.renderRow(row));\n});\n</code></pre>\n</blockquote>\n\n<p>That is essentially the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>map</code></a> method re-implemented... Why not use that method?</p>\n\n<pre><code>const output = this.cells.map(row => this.renderRow(row));\n</code></pre>\n\n<p>Notice that <code>const</code> is used because that value is never re-assigned. This can even be used with the <code>forEach</code>, since calling <code>push()</code> doesn't re-assign the value.</p>\n\n<p>The same principle applies for the <code>renderRow()</code> method.</p>\n\n<h3>render method</h3>\n\n<p>This method does not return any values, it merely logs output to the console. However, the method is called inside a call to <code>console.log()</code>, which results in <code>undefined</code> being output to the console. Maybe that is not a concern for you if you are the only one using the console (perhaps for debugging purposes) but be aware of this if you intend on primarily using the console for output.</p>\n\n<blockquote>\n<pre><code> \n \nundefined\n=> undefined\n</code></pre>\n</blockquote>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:18:09.790",
"Id": "209677",
"ParentId": "209673",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T14:34:58.953",
"Id": "209673",
"Score": "0",
"Tags": [
"javascript",
"object-oriented",
"html",
"design-patterns",
"ecmascript-6"
],
"Title": "Tile and grid abstraction"
} | 209673 |
<p>I wrote a program as an excercise, to check the <code>openpyxl</code> module, which inserts blank rows into an excel file. See the docstring in the code for more description.</p>
<p>I would like to know what you think about the code.
Is it easy / difficult to follow?<br>
Is it structured good / bad? <br>
What can be improved?</p>
<p><b> blank_row_inserter.py </b></p>
<pre><code>"""
Reads in an Excel document to add blank lines.
The user can run the program in command line with arguments or input
the information at runtime.
Things to input:
-Filename of excel file to manipulate
-Start row for blank lines
-Count of blank rows to insert
The changes made by the program get saved in a new excel file.
It is saved as updated_{filename}.xlsx
"""
import sys
from typing import Tuple
from copy import copy
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.utils import column_index_from_string
def is_positive_number(input_string: str) -> bool:
"""Checks if input is valid to use for the excel file"""
return input_string.isdigit() and int(input_string) >= 1
def enter_positive_number(user_message) -> int:
"""
Prompts the user until positive number was entered and returns then
the number
"""
while True:
input_string = input(user_message)
if is_positive_number(input_string):
return int(input_string)
def user_input() -> Tuple[int, int, str]:
"""
First looks for data on the command line. If command line input is
not valid the user is prompted to put in the values manually.
Returns start_row, count_of_blank_rows and filename
"""
if len(sys.argv) == 4:
start_blank_row_input: str = sys.argv[1]
blank_rows_input: str = sys.argv[2]
if (is_positive_number(start_blank_row_input) and
is_positive_number(blank_rows_input)):
return (int(start_blank_row_input),
int(blank_rows_input), sys.argv[3])
start_blank_row = enter_positive_number(
"Enter start of blank rows:\n")
blank_rows = enter_positive_number(
"Enter how many blank rows to insert:\n")
filename: str = input("Enter filename:\n")
return start_blank_row, blank_rows, filename
def save_workbook_excel_file(workbook, filename):
"""Tris to save created data to excel file"""
try:
workbook.save(filename)
except PermissionError:
print("Error: No permission to save file.")
def copy_cells(
source_sheet, target_sheet,
row_start: int, row_end: int, row_offset: int,
column_start: int, column_end: int, column_offset: int):
"""
Copies cells from one sheet to the other including its style.
It is possible to enter blank rows or columns into the new sheet.
"""
for row in range(row_start, row_end):
for column in range(column_start, column_end):
source = source_sheet.cell(row=row, column=column)
target = target_sheet.cell(
row=row + row_offset, column=column + column_offset)
target.value = copy(source.value)
if source.has_style:
target.font = copy(source.font)
target.border = copy(source.border)
target.fill = copy(source.fill)
target.number_format = copy(source.number_format)
target.protection = copy(source.protection)
target.alignment = copy(source.alignment)
def copy_row_dimensions(
source_sheet, target_sheet,
start_blank_row: int, blank_rows: int):
"""
Copies the dimension of rows from one sheet to the other.
It is possible to copy with an offset to "insert" new rows
into the new sheet
"""
for row_number, row_dim in source_sheet.row_dimensions.items():
if row_number >= start_blank_row:
row_number = row_number + blank_rows
target_sheet.row_dimensions[row_number] = copy(row_dim)
def copy_column_dimensions(
source_sheet, target_sheet,
start_blank_column: int, blank_columns: int):
"""
Copies the dimension of columns from one sheet to the other.
It is possible to copy with an offset to "insert" new columns
into the new sheet
"""
for column_letter, column_dim in source_sheet.column_dimensions.items():
column_index = column_index_from_string(column_letter)
if column_index >= start_blank_column:
column_index = column_index + blank_columns
column_letter = get_column_letter(column_index)
target_sheet.column_dimensions[column_letter] = copy(column_dim)
def blank_row_inserter():
"""Main logic to insert blank rows"""
start_blank_row: int
blank_rows: int
filename: str
start_blank_row, blank_rows, filename = user_input()
workbook = openpyxl.load_workbook(filename)
sheet_names = workbook.sheetnames
sheet = workbook[sheet_names[0]]
max_row = sheet.max_row
max_column = sheet.max_column
workbook.create_sheet(index=0, title='tmp_sheet')
new_sheet = workbook['tmp_sheet']
# Copy everything before blank area
copy_cells(
source_sheet=sheet, target_sheet=new_sheet,
row_start=1, row_end=start_blank_row, row_offset=0,
column_start=1, column_end=max_column, column_offset=0)
# Copy with row offset
copy_cells(
source_sheet=sheet, target_sheet=new_sheet,
row_start=start_blank_row, row_end=max_row, row_offset=blank_rows,
column_start=1, column_end=max_column, column_offset=0)
copy_row_dimensions(
source_sheet=sheet, target_sheet=new_sheet,
start_blank_row=start_blank_row, blank_rows=blank_rows)
copy_column_dimensions(
source_sheet=sheet, target_sheet=new_sheet,
start_blank_column=0, blank_columns=0)
sheet_name = sheet.title
del workbook[sheet_name]
new_sheet.title = sheet_name
save_workbook_excel_file(workbook, 'updated_' + filename)
if __name__ == "__main__":
blank_row_inserter()
</code></pre>
| [] | [
{
"body": "<pre><code>while True:\n input_string = input(user_message)\n if is_positive_number(input_string):\n return int(input_string)\n</code></pre>\n\n<p>Fine, but the user should be told if they have invalid input; so add an error message to the end of that loop.</p>\n\n<pre><code>if len(sys.argv) == 4:\n start_blank_row_input: str = sys.argv[1]\n blank_rows_input: str = sys.argv[2]\n\n if (is_positive_number(start_blank_row_input) and\n is_positive_number(blank_rows_input)):\n return (int(start_blank_row_input),\n int(blank_rows_input), sys.argv[3])\n</code></pre>\n\n<p>The problem with this approach is that if the user <em>tries</em> to enter command-line input but it's invalid (has the wrong number of args, for instance), their input is silently discarded. You should differentiate between \"no input\" and \"invalid input\", the latter showing an error message and the former continuing to your input prompts.</p>\n\n<pre><code>\"\"\"Tris to save created data to excel file\"\"\"\n</code></pre>\n\n<p>You probably meant \"tries\".</p>\n\n<p>For these two lines:</p>\n\n<pre><code>row_number = row_number + blank_rows\n\ncolumn_index = column_index + blank_columns\n</code></pre>\n\n<p>Use the <code>+=</code> operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:46:36.473",
"Id": "405270",
"Score": "0",
"body": "Im a bit surprised i was on the train that `+=` does not exist unlike for example `c++`. Was it added lately?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:49:28.883",
"Id": "405271",
"Score": "0",
"body": "It's been around for a very, very long time: https://docs.python.org/release/2.0/ref/delimiters.html"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:39:32.033",
"Id": "209681",
"ParentId": "209678",
"Score": "3"
}
},
{
"body": "<p>This is how I wrote it:</p>\n<pre><code>import openpyxl,sys\n\nif len(sys.argv)<1:\n sys.exit()\nelif len(sys.argv)>1:\n wb = openpyxl.load_workbook(sys.argv[3])\n sheet = wb.active\n from openpyxl.utils import get_column_letter,column_index_from_string\n\n N=int(sys.argv[1])\n M=int(sys.argv[2])\n \n newSpreadSheet1={}\n\n for column in range(1,sheet.max_column):\n newSpreadSheet1.setdefault(get_column_letter(column),[])\n for row in range(1,N):\n newSpreadSheet1[get_column_letter(column)].append(sheet[get_column_letter(column)+str(row)].value)\n for row in range(N,N+M):\n newSpreadSheet1[get_column_letter(column)].append(None)\n for row in range(N+M,sheet.max_row):\n newSpreadSheet1[get_column_letter(column)].append(sheet[get_column_letter(column)+str(row)].value)\n\n wb=openpyxl.Workbook()\n sheet=wb.active\n\n for k,v in newSpreadSheet1.items():\n for i,cellValue in enumerate(v,1):\n sheet.cell(row=i,column=(column_index_from_string(k))).value=cellValue\n\n wb.save(sys.argv[3])\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T21:46:36.770",
"Id": "483583",
"Score": "2",
"body": "Welcome to Code Review where we review the code posted in the question to help them improve their coding ability. Your answer is an alternate solution which is acceptable on stackoverflow.com but is not a good answer on Code Review. A good answer on Code Review makes one or more insightful observations about the code in the question. Your answer does not make any insightful observations about the code. Your answer may be down voted or deleted by the community. Please see our [guidelines on answering questions](https://codereview.stackexchange.com/help/how-to-answer)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T18:09:21.397",
"Id": "246138",
"ParentId": "209678",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209681",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:31:04.187",
"Id": "209678",
"Score": "3",
"Tags": [
"python",
"beginner",
"excel",
"file"
],
"Title": "Excel blank row inserter"
} | 209678 |
<p>I've implemented <a href="https://en.wikipedia.org/wiki/Luhn_algorithm" rel="noreferrer">Luhn's algorithm</a> for checking credit card numbers.
My code works, but I wanted to learn about a more efficient and more Pythonic way of doing this.</p>
<pre><code>def validate_credit_card_number(card_number):
#start writing your code here
#Step 1a - complete
temp_list=list(str(card_number))
my_list=[]
list1 = temp_list[-2::-2]
list2=temp_list[::-2]
list2 = [int (n) for n in list2]
#print(list2)
my_list=[int(n) for n in list1]
#print(my_list)
list1 = [int(n)*2 for n in list1]
t_list=list1
for el in list1:
sum_res=0
if el>9:
idx = list1.index(el)
t_list.pop(idx)
while el:
rem = el%10
sum_res+=rem
el = el//10
t_list.insert(idx, sum_res)
#print(t_list)
#step 1b
list1_sum=sum(t_list)
list2_sum = sum(list2)
#print(b_list)
final_sum = list1_sum+ list2_sum
#print(final_sum)
if final_sum%10==0:
return True
return False
card_number= 1456734512345698 #4539869650133101 #1456734512345698 # #5239512608615007
result=validate_credit_card_number(card_number)
if(result):
print("credit card number is valid")
else:
print("credit card number is invalid")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T21:17:29.533",
"Id": "405303",
"Score": "0",
"body": "(Welcome to Code Review!) (This question seems to be getting smoother by the edit…)"
}
] | [
{
"body": "<p>I assume that <code>card_number</code> is an integer. As such, you should not convert it to a <code>str</code>, nor convert it to a <code>list</code>. You should be doing integer operations only, not list operations.</p>\n\n<p>For your learning purposes, I won't rewrite the algorithm for you, but try to rewrite it such that it's represented as a loop over the credit card number, which successively gets divided by 10.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:06:38.647",
"Id": "405276",
"Score": "0",
"body": "How am I supposed to iterate over a number, even if I break the number to digits, I will have to store it in a list for further processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:07:05.113",
"Id": "405277",
"Score": "0",
"body": "Nope. Successively divide the number by 10 and work with the modulus."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:09:02.393",
"Id": "405278",
"Score": "0",
"body": "Ok, I will try that out. However, I was wondering what would be the cons of converting it to a list/str?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:09:31.410",
"Id": "405279",
"Score": "0",
"body": "It's slower and uses (slightly) more memory."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:55:41.170",
"Id": "209682",
"ParentId": "209680",
"Score": "3"
}
},
{
"body": "<p><strong>Style</strong></p>\n\n<p>Python has a style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. It is a good habit to try to follow it.</p>\n\n<p>In your case, that would mean fixing the missing whitespaces, removing parenthesis in <code>if(result)</code>.</p>\n\n<p>Also, you could get rid of old commented code and add a proper <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> if you want to describe the behavior of the function.</p>\n\n<p><strong>Tests</strong></p>\n\n<p>It could be a good idea to write tests before trying to improve your code.</p>\n\n<p>I wrote a very simple code but you could get this chance to dive into unit testing frameworks:</p>\n\n<pre><code>TESTS = [\n (1456734512345698, False),\n (4539869650133101, True),\n (1456734512345698, False),\n (5239512608615007, True),\n]\n\nfor (card_number, expected_valid) in TESTS:\n valid = validate_credit_card_number(card_number)\n assert valid == expected_valid\n</code></pre>\n\n<p><strong>Useless test</strong></p>\n\n<p>At the end of the function, you can return directly:</p>\n\n<pre><code>return final_sum % 10 == 0\n</code></pre>\n\n<p><strong>Useless variables</strong></p>\n\n<p>The <code>my_list</code> variable is not required.</p>\n\n<p>Also, we can take this chance to get rid of the variables at the end of the function:</p>\n\n<pre><code>return (sum(t_list) + sum(list2)) % 10 == 0\n</code></pre>\n\n<p><strong>Conversion of <code>card_number</code></strong></p>\n\n<p>At the beginning of the function, you could convert the parts of <code>card_number</code> directly to integer so that you do it in a single place.\nAlso, that removed the need to the call of <code>list</code>. We just have:</p>\n\n<pre><code>temp_list = [int(c) for c in str(card_number)]\n</code></pre>\n\n<p>And we can get rid of the line:</p>\n\n<pre><code>list2 = [int (n) for n in list2]\n</code></pre>\n\n<p>At this stage, the code looks like:</p>\n\n<pre><code>def validate_credit_card_number(card_number):\n temp_list = [int(c) for c in str(card_number)]\n\n list1 = temp_list[-2::-2]\n list1 = [2 * n for n in list1]\n\n list2 = temp_list[::-2]\n\n t_list = list1\n\n for el in list1:\n sum_res = 0\n\n if el > 9:\n idx = list1.index(el)\n t_list.pop(idx)\n\n while el:\n rem = el % 10\n sum_res += rem\n el = el // 10\n t_list.insert(idx, sum_res)\n\n return (sum(t_list) + sum(list2)) % 10 == 0\n</code></pre>\n\n<p><strong>Yet another useless variable</strong></p>\n\n<p><code>t_list</code> aliases <code>list1</code> (I am not sure if this is intended if if you were planning to have a copy of <code>list1</code>). Whenever you update the list through one variable, the other is affected as well. I highly recommend <a href=\"https://nedbatchelder.com/text/names1.html\" rel=\"nofollow noreferrer\">Ned Batchelder's talk about names and values</a>.</p>\n\n<p>In your case, we can get rid of <code>t_list</code> completely without changing the behavior of the function.</p>\n\n<p><strong>Simplify list logic</strong></p>\n\n<p>You go through multiple steps to modify <code>list1</code> (or <code>t_list</code>) : <code>index</code>, <code>pop</code>, <code>index</code>. These steps are more expensive/complicated than required. At the end of the day, you do not care about <code>list1</code>, you just want its final sum. You could keep track of the sum directly:</p>\n\n<pre><code>sum1 = 0\nfor el in list1:\n if el > 9:\n sum_res = 0\n while el:\n rem = el % 10\n sum_res += rem\n el = el // 10\n sum1 += sum_res\n else:\n sum1 += el\n\nreturn (sum1 + sum(list2)) % 10 == 0\n</code></pre>\n\n<p>We can take this chance to perform the multiplication in the loop to remove a list comprehension.</p>\n\n<p>Also, we can initialise the sum with <code>sum(list2)</code> so that we don't have to add them at the end:</p>\n\n<pre><code>def validate_credit_card_number(card_number):\n temp_list = [int(c) for c in str(card_number)]\n\n list1 = temp_list[-2::-2]\n list2 = temp_list[::-2]\n\n total_sum = sum(list2)\n for el in list1:\n el *= 2\n if el > 9:\n sum_res = 0\n while el:\n rem = el % 10\n sum_res += rem\n el = el // 10\n total_sum += sum_res\n else:\n total_sum += el\n\n return total_sum % 10 == 0\n</code></pre>\n\n<p><strong>Math logic</strong></p>\n\n<p>The code uses 10 (the base used for computations) everywhere except for one 9 which seems unexpected. You could write: <code>el >= 10</code> instead.</p>\n\n<p>Also, that check is not required because the logic applies exactly the same way for elements smaller than 10:</p>\n\n<pre><code>for el in list1:\n el *= 2\n sum_res = 0\n while el:\n rem = el % 10\n sum_res += rem\n el = el // 10\n total_sum += sum_res\n</code></pre>\n\n<p>Also, you could use <code>el //= 10</code> but you can get the best ouf of the Python builtins by using <a href=\"https://docs.python.org/3/library/functions.html#divmod\" rel=\"nofollow noreferrer\"><code>divmod</code></a> returning both the quotient and the remainder:</p>\n\n<pre><code> while el:\n el, rem = divmod(el, 10)\n sum_res += rem\n total_sum += sum_res\n</code></pre>\n\n<p>Then, it becomes clear that the variable <code>sum_res</code> is not really required as we could use <code>total_sum</code> instead:</p>\n\n<pre><code> while el:\n el, rem = divmod(el, 10)\n total_sum += rem\n</code></pre>\n\n<p><strong>\"Final\" code</strong></p>\n\n<pre><code>def validate_credit_card_number(card_number):\n temp_list = [int(c) for c in str(card_number)]\n\n list1 = temp_list[-2::-2]\n list2 = temp_list[::-2]\n\n total_sum = sum(list2)\n for el in list1:\n el *= 2\n while el:\n el, rem = divmod(el, 10)\n total_sum += rem\n\n return total_sum % 10 == 0\n\nTESTS = [\n (1456734512345698, False),\n (4539869650133101, True),\n (1456734512345698, False),\n (5239512608615007, True),\n]\n\nfor (card_number, expected_valid) in TESTS:\n valid = validate_credit_card_number(card_number)\n assert valid == expected_valid\n</code></pre>\n\n<p><strong>More simplification</strong></p>\n\n<p>Thinking about it, things can still be simplified a lot.\nWhat you are doing with the <code>while</code> loop can be performed using <code>str</code> conversion:</p>\n\n<pre><code>total_sum = sum(list2)\nfor el in list1:\n total_sum += sum(int(c) for c in str(2 * el))\n</code></pre>\n\n<p>Going further (too far?), this leads to:</p>\n\n<pre><code>def validate_credit_card_number(card_number):\n temp_list = [int(c) for c in str(card_number)]\n\n list1 = temp_list[-2::-2]\n list2 = temp_list[::-2]\n\n total_sum = sum(list2) + sum(sum(int(c) for c in str(2 * el)) for el in list1)\n return total_sum % 10 == 0\n</code></pre>\n\n<p>Edit:</p>\n\n<p><strong>More simplification</strong></p>\n\n<p>We are using <code>str</code> and <code>int</code> to get the digits of a number... which is known to be smaller than 18 (2 * 9).\nA trick could be, once again, to use <code>divmod</code> returning the quotient and remainder and use sum on it.</p>\n\n<pre><code>total_sum = sum(list2)\nfor el in list1:\n total_sum += sum(divmod(2 * el, 10))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>total_sum = sum(list2) + sum(sum(divmod(2 * el, 10)) for el in list1)\n</code></pre>\n\n<p><strong>Playing with indices</strong></p>\n\n<p>Instead of splitting the list into 2 lists, we could iterate over the (reversed) list once and handle differently elements at odd positions and elements at even positions.</p>\n\n<p>We'd get something like:</p>\n\n<pre><code>def validate_credit_card_number(card_number):\n temp_list = [int(c) for c in str(card_number)]\n\n total_sum = 0\n for i, e in enumerate(reversed(temp_list)):\n if i % 2 == 0:\n total_sum += e\n else:\n total_sum += sum(divmod(2 * e, 10))\n\n return total_sum % 10 == 0\n</code></pre>\n\n<p>Or the more concise solution taking advantage of the fact that the <code>divmod</code> trick works for both cases:</p>\n\n<pre><code>def validate_credit_card_number(card_number):\n total_sum = 0\n for i, c in enumerate(reversed(str(card_number))):\n e = int(c) * (2 if i % 2 else 1)\n total_sum += sum(divmod(e, 10))\n return total_sum % 10 == 0\n</code></pre>\n\n<p>or </p>\n\n<pre><code>def validate_credit_card_number(card_number):\n return sum(sum(divmod(int(c) * (2 if i % 2 else 1), 10))\n for i, c in enumerate(reversed(str(card_number)))) % 10 == 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T19:55:43.887",
"Id": "405296",
"Score": "0",
"body": "@HackersInside actually, I have other ideas that could somehow improve the solution. I'll try to update the answer when I am on a computer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T10:40:26.417",
"Id": "405335",
"Score": "0",
"body": "@HackerInside I've edited my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T10:56:23.260",
"Id": "405336",
"Score": "2",
"body": "`2 if i % 2 else 1` → `i % 2 + 1`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T18:31:08.753",
"Id": "209689",
"ParentId": "209680",
"Score": "13"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/209689/187192\">Josay's answer</a> is right on the money in terms of how to start optimizing one's Python code. </p>\n\n<p>Below I go further with the optimization that Josay started. I should warn that the code is at a stage where optimizations begin to really flirt with readability, and so for shared code that must be understood and maintained, we're home safe.</p>\n\n<p>If we desire to get a \"one-liner\" Python script, for what it's worth, let's look at the difference between <code>list1</code> and <code>list2</code>. As a side-note about style, more descriptive names of these lists might be <code>evens</code> and <code>odds</code>: hints that would really help the person who has to read your code. </p>\n\n<h2>Finding commonality in how the odds even digits are handled</h2>\n\n<p>Recall that for our sum, we will be adding up all the numbers in <code>odds</code>. We will, in fact, also be adding up all the digits in <code>evens</code>, except we will <em>also</em> add them up again (doubling). Then we also need to account for the cases when the doubling results in two-digit numbers, but more on that below.</p>\n\n<p>Since both <code>odds</code> and <code>evens</code> adds each digit, we could start off with just adding up all the digits:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): #incomplete code\n temp_list = [int(c) for c in str(card_number)]\n return ( sum(temp_list) + CORRECTIONS ) % 10 == 0\n</code></pre>\n\n<p>So what are the corrections we need to make? Well, every other digit needs to be added again. Instead of dividing the list up into <code>evens</code> and <code>odds</code> and separating the problems, what if we had some sort of <em>indicator</em> that we are processing an odd or an even digit? </p>\n\n<h2>Correcting for the even numbers</h2>\n\n<p>One possible answer is to somehow look up the <em>index</em> of the digit we are processing, and seeing if that one is odd or even. The check for whether <code>i</code> is odd is just <code>(i % 2) == 1</code>.</p>\n\n<p>But what's a good way of getting to know both the index of the digit and the digit itself? Python has a nice built-in iterator called <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\">enumerate</a>. Formally, <code>enumerate</code> gives you a generator that provides (index,element) pairs from a list. To illustrate, <code>enumerate ([\"foo\",\"bar\",7,\"zoo\"])</code> returns a generator for <code>[(0, 'foo'), (1, 'bar'), (2, 7), (3, 'zoo')]</code>. Great! Let's see if we can use that.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): #incomplete code\n temp_list = [int(c) for c in str(card_number)]\n return sum([ x + (x if (i % 2)==0 else 0) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<p>Here we use Python's <code>a if <test> else b</code> ternary notation to check if the number is the even number. </p>\n\n<h2>Thinking backwards</h2>\n\n<p>But wait ... the Luhn specification said we needed to start counting from the <em>right-most</em> digit. So what if that digit happens to have an even index? Our odds and evens would be exactly switched! Here, we would notice that it'd be so much more convenient to just count from the right. All we are doing is adding up numbers, so it wouldn't make any difference if we were to just reverse the list first! We just have to be careful that the rightmost digit in the reverse list (<code>temp_list</code>) is now at index 0, so we must now be correcting the <em>odd</em> numbers.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): #incomplete code\n temp_list = reversed([int(c) for c in str(card_number)])\n return sum([ x + (x if (i % 2)==1 else 0) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<h2>Fixing the double digit cases</h2>\n\n<p>Much better. But, alas, there is still an issue with the double digits. If the digit at the even index is 0, 1, 2, 3, or 4, we actually do the right thing: double the number. But if it's 5, 6, 7, 8, or 9, we are currently adding 10, 12, 14, 16, 18 instead of 1, 3, 5, 7, 9, respectively. But for those numbers, the difference between what we do now and what we should do is always 9! How about adding a check for whether the digit is 5 or more, in which case subtract 9?</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number):\n temp_list = reversed([int(c) for c in str(card_number)])\n return sum([ x + (x + (-9 if x>=5 else 0) if (i % 2)==1 else 0) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<p>This code actually works! </p>\n\n<h2>Simplifying with modulus tricks</h2>\n\n<p>Let's keep going! If we add -9 to a sum that we are reducing modulo 10, that's the same as adding 1 to the sum. Why? Because <span class=\"math-container\">\\$-9 \\pmod{10} \\equiv 10 + (-9) \\pmod{10} \\equiv 1 \\pmod{10}\\$</span> since the extra 10 doesn't change the modulus. It's a bit like saying that 9 hours ago, the clock hand pointed at the same number as it will do <span class=\"math-container\">\\$(12-9)=3\\$</span> hours from now -- except that clocks work modulo 12.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number):\n temp_list = reversed([int(c) for c in str(card_number)])\n return sum([ x + (x + (1 if x>=5 else 0) if (i % 2)==1 else 0) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<h2>Multiplication instead of ternary operator</h2>\n\n<p>Also, we can replace the ternary operators (the <code>if</code> business) with simple multiplication. Why? Because there is no difference between <code>8 + (42 if x%2==1 else 0)</code> and <code>8 + 42*(x%2)</code>. Further, something like <code>8 + (1 if x%2==1 else 0)</code> could just be simplified to <code>8 + (x%2)</code>.</p>\n\n<p>Using these ideas, we now have:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): \n temp_list = reversed([int(c) for c in str(card_number)])\n return sum([ x + (x+(x>=5))*(i%2) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<h2>Mapping to a one-liner</h2>\n\n<p>Nice. Now, can we squeeze this whole expression into a single line, just because? Here, we may notice that the list comprehension for <code>temp_list</code> is really just applying <code>int</code> to every character in <code>card_number</code>. There is another nice built-in function in Python called <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a>, a descendant from <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">functional programming</a> languages, that takes a function and a list, and applies the function to each element of a list. (From a Pythonic style perspective, bear in mind that <a href=\"https://stackoverflow.com/questions/40015439/why-does-map-return-a-map-object-instead-of-a-list-in-python-3\">generator expressions are usually favorable to map, which almost got removed in Python3</a>).</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): \n temp_list = reversed(list (map(int, [c for c in str(card_number)])))\n return sum([ x + (x+(x>=5))*(i%2) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<h2>One-liner ahoy!</h2>\n\n<p>Wait a minute. When we see <code>[c for c in str(card_number)]</code>, we should pause and think about what list we are really generating. When you think about it, <code>str(card_number)</code> return a string, and Python strings implement an <a href=\"http://zetcode.com/lang/python/itergener/\" rel=\"nofollow noreferrer\">iterator</a>. So for our purposes, we could just treat <code>str(card_number)</code> as a list of characters! This gives:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): \n temp_list = reversed(list (map(int, str(card_number))))\n return sum([ x + (x+(x>=5))*(i%2) for (i,x) in enumerate(temp_list)]) % 10 == 0\n</code></pre>\n\n<p>The <code>list</code> bit is ugly. So let's reverse the string earlier and conclude with:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_number): \n return sum([x + (x+(x>=5))*(i%2) for (i,x) in enumerate(map(int, reversed(str(card_number))))]) % 10 == 0\n</code></pre>\n\n<h2>Shorter still?</h2>\n\n<p>There are still opportunities to shorten the expression. For one, we could assume that the input is actually a string already. For another, we can remove the reversal business and just figure out if the doubling should happen for evens or odds by looking at the length of the input string. This gives:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def validate_credit_card_number(card_str): \n return sum([x + (x+(x>=5))*((len(card_str)-1+i)%2) for (i,x) in enumerate(map(int, card_str))]) % 10 == 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T05:57:20.650",
"Id": "405327",
"Score": "2",
"body": "I'm really taken back. Just one line. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T21:54:02.887",
"Id": "405377",
"Score": "1",
"body": "Welcome here! This is a very nice answer, I'm looking forward to reading more of your contributions in the near future!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T05:36:28.803",
"Id": "209709",
"ParentId": "209680",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209709",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T16:34:39.283",
"Id": "209680",
"Score": "12",
"Tags": [
"python",
"performance",
"checksum"
],
"Title": "Implementation of Luhn credit card algorithm"
} | 209680 |
<p>Has everyone moved over to <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout" rel="nofollow noreferrer">CSS Grid and/or Flexbox</a>? If not, I've maintained and evolved this system over a fair amount of time, the concept was derived originally, I believe, from <a href="https://tympanus.net/codrops/author/crnacura/" rel="nofollow noreferrer">Mary Lou</a>, although I don't recall where the article is.</p>
<p>I was never a proponent of floats, although the using <code>font-size:0</code> to clear whitespace isn't an ideal solution either, neither is a <em>DOM Cleaner</em> function in javascript. Probably minimized (non-formatted) HTML without whitespaces is ideal, just difficult to maintain... There's a lot of other "hacky" concepts, comments in HTML, bleh... but I landed on the <code>font-size:0</code>. This served me well and I still use it in a handful of projects, though I've mostly moved to a CSSGrid/Flexbox combination as of late.</p>
<p>It's a similar to:</p>
<pre><code>.table {display: table}
.table>div {display: table-cell}
</code></pre>
<p>With a higher degree of flexibility, if you need heights to match, the above or flexbox/css grid are probably a better solution. or <code>min-height</code> on columns if it's known content.</p>
<p>Any ideas to improve or flaws, let me know. </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-css lang-css prettyprint-override"><code>.autogrid {
padding: .5rem; /* 8px */
/** remove whitespace from container */
font-size: 0;
box-sizing: border-box}
.autogrid>* {
box-sizing: inherit; /* inherit border-box */
display: block;
font-size: inherit; /* inherit 0px */
margin: 0 auto .5rem; /* 0 auto 8px */
padding: 0 .5rem .5rem /* 0 8px 8px */}
/** create vertical space in columns & prevent margin-collapsing */
.autogrid>*:before {
content: '';
display: inline-block;
vertical-align: 0; /* baseline or 0% */
width: 0;
height: .5rem /* 8px */}
@media (min-width: 33.75em) { /* 540px */
.autogrid>* {
display: inline-block;
margin: .5rem; /* 8px */
/** align columns/cards to top, middle, etc. */
vertical-align: top}
.autogrid>*:first-child:nth-last-child(1),
.autogrid>*:first-child:nth-last-child(3),
.autogrid>*:first-child:nth-last-child(3)~* {width: calc(100% - 1rem) /* 100% - 16px */}
.autogrid>*:first-child:nth-last-child(4),
.autogrid>*:first-child:nth-last-child(4)~*,
.autogrid>*:first-child:nth-last-child(2),
.autogrid>*:first-child:nth-last-child(2)~* {width: calc(50% - 1rem) /* 50% - 16px */}
}
@media (min-width: 50em) { /* 800px */
.autogrid>*:first-child:nth-last-child(3),
.autogrid>*:first-child:nth-last-child(3)~* {width: calc(33.333% - 1rem) /* 33.333% - 16px */}
.autogrid>*:first-child:nth-last-child(4),
.autogrid>*:first-child:nth-last-child(4)~* {width: calc(25% - 1rem) /* 25% - 16px */}
}
/**
###############
# DEMO ONLY #
###############
html:
`
<div class="autogrid">
<div><p>col</p></div>
<div><p>col</p></div>
<div><p>col</p></div>
<div><p>col</p></div>
</div>
`
*/
html {
font: 400 100%/1 sans-serif;
color: #333}
body,
p {
font-size: 1rem; /* 16px */
line-height: 1.45; /* 145% or 23.2px */
margin: 0}
.autogrid>* {text-align: center}
.autogrid>*:first-child,
.autogrid>*:nth-child(2) {color: #fff}
.autogrid>*:nth-child(3),
.autogrid>*:last-child {color: inherit}
.autogrid>*:first-child {background-color: #4af}
.autogrid>*:nth-child(2) {background-color: #fa4}
.autogrid>*:nth-child(3) {background-color: #def}
.autogrid>*:last-child {background-color: #fed}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="autogrid">
<div><p>col</p></div>
<div><p>col</p></div>
<div><p>col</p></div>
<div><p>col</p></div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:39:44.773",
"Id": "413154",
"Score": "1",
"body": "*I was never a proponent of floats* whyyy? Float has it's uses, even in 2019, *even* in conjunction with a flex-driven project. I don't think they are synonymous, and I don't understand the hesitation to use it, it's not deprecated for a reason. The only thing I notice just by looking at it, is if one box has more content than the other there would be a lot of whitespace? But I really like this, looks great!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T22:07:41.077",
"Id": "413465",
"Score": "0",
"body": "I do use `float`'s for various purposes; however, seldom for grid. I suppose I should have worded that a little differently. As for whitespace, that's a problem with many grid systems (maybe even grids in general?), usually a different layout concept is better if there's too many cases of unbalanced content; or tailoring content slightly."
}
] | [
{
"body": "<p>This is not to take away at all from your system above, which is very smart.</p>\n\n<p>I'm still very much on the <strong>CSS Grid</strong> learning curve and I was genuinely curious to see how straightforward / difficult it might be to replicate your output above, using <strong>CSS Grid</strong>.</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-css lang-css prettyprint-override\"><code>.grid {\n display: grid;\n grid-template: repeat(4, 42px) / auto;\n grid-gap: 8px;\n}\n\ndiv p {\n margin: 0;\n padding: 0;\n line-height: 42px;\n text-align: center;\n font-family: sans-serif;\n}\n\n.box-1 {color: #fff; background-color: #4af;}\n.box-2 {color: #fff; background-color: #fa4;}\n.box-3 {color: #000; background-color: #def;}\n.box-4 {color: #000; background-color: #fed;}\n\n@media (min-width: 540px) {\n \n .grid {grid-template: repeat(2, 42px) / repeat(2, auto); grid-gap: 16px;}\n}\n\n@media (min-width: 800px) {\n \n .grid {grid-template: 42px / repeat(4, auto);}\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"grid\">\n <div class=\"box-1\"><p>col</p></div>\n <div class=\"box-2\"><p>col</p></div>\n <div class=\"box-3\"><p>col</p></div>\n <div class=\"box-4\"><p>col</p></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-02-05T10:46:39.183",
"Id": "236703",
"ParentId": "209684",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T17:19:10.970",
"Id": "209684",
"Score": "6",
"Tags": [
"css",
"layout"
],
"Title": "Ultra-simple, automatic, non-float, 1-4 column, grid system"
} | 209684 |
<p>We have been given a list of strings which are blacklisted. The goal is to identify if a given text contains any of these blacklisted strings. The restriction here is that the blacklisted string needs to match on the word boundary e.g. consider a blacklist string "abc" and text "abc pqr", the text in this case is unsafe (i.e. it contains a blacklisted string). On the other hand if the text is "abcoqr", then the text is safe since the string "abc" is not on the word boundary. Also the relative ordering of words in a blacklisted string needs to be checked e.g. if a blacklisted string is "abc pqr", then the text "pqr abc" is safe since the ordering of the words in the text does not match that of the blacklisted string.</p>
<p>Here is my solution using a modified Trie data structure. <a href="https://gist.github.com/hgadre/d4e9ec576932167f01fd33970002a882" rel="nofollow noreferrer">https://gist.github.com/hgadre/d4e9ec576932167f01fd33970002a882</a></p>
<pre><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SafeText {
static class Tuple {
int span = 0; // the length of previous words which should have been matched if end = true.
boolean end; // marks the identification of a blacklisted string.
Set<String> nextWords = new HashSet<>(); // next set of words to search for matching blacklisted strings.
public void setEnd(boolean end, int span) {
this.span = span;
this.end = end;
}
public boolean isEnd(int span) {
return end && span == this.span;
}
public void addNextWord (String word) {
this.nextWords.add(word);
}
public boolean containsWord(String word) {
return this.nextWords.contains(word);
}
}
private final Map<String, Tuple> m = new HashMap<>();
public SafeText(List<String> blackList) {
Collections.sort(blackList);
for (String str : blackList) {
String[] tokens = str.split("\\s");
int i = 0;
for (; i < tokens.length - 1; i++) {
m.computeIfAbsent(tokens[i], x -> new Tuple()).addNextWord(tokens[i+1]);
}
m.computeIfAbsent(tokens[i], x -> new Tuple()).setEnd(true, tokens.length-1);
}
}
public boolean isSafe(String text) {
String[] tokens = text.split("\\s");
for (int i = 0; i < tokens.length; i++) {
String key = tokens[i];
int j = i;
while (j < tokens.length && m.containsKey(key)) {
Tuple t = m.get(key);
if (t.isEnd(j-i)) {
return false;
} else if ((j+1) < tokens.length && t.containsWord(tokens[j+1])) {
key = tokens[j+1];
j++;
} else {
break;
}
}
}
return true;
}
}
</code></pre>
<p>Is this an optimal solution? Or is there any better approach to solve this problem?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T18:59:00.777",
"Id": "405290",
"Score": "0",
"body": "I don't see any kind of trie involved in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T19:44:50.340",
"Id": "405294",
"Score": "0",
"body": "@200_success its a modified trie. I am storing a mapping between a given word and the set of words which can occur in one or more blacklisted strings. e.g. if blacklisted string is \"a b\" then the mapping would be : a -> {false, 0, [b]} and b -> {true, 2, []}. make sense?"
}
] | [
{
"body": "<p>I may have missed something. But why don't you just use simple collections ?</p>\n\n<pre><code>// Naive implementation\nclass Text {\n public Text(String content, Set<String> blacklist) {\n this.words = new HashSet<>(Arrays.asList(content.split(\"\\\\s\")));\n this.blacklist = blacklist;\n }\n\n public boolean isSafe() {\n for (String forbidden: this.blacklist) {\n if (this.words.contains(forbidden) ) {\n return false;\n }\n }\n return true;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:22:54.970",
"Id": "405736",
"Score": "0",
"body": "I was about to post a very similar solution :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T18:45:49.583",
"Id": "405749",
"Score": "0",
"body": "No this will not work when the blacklisted string contains multiple words and we need to make sure that the all these words match in the text (in the correct order). In your solution, you have split the content string at the word boundary and inserted in the set. So I think you will loose the ordering amongst the individual words. For concrete examples please take a look at https://gist.github.com/hgadre/d4e9ec576932167f01fd33970002a882"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T08:54:51.007",
"Id": "405801",
"Score": "0",
"body": "Having only words in the `blacklist` entries must be an precondition. There was no oreding requirement in your question, that is why I said _\"I may have missed something\"_. But if you want to keep the ordering you can use a `List` instead of `Set`. Please update your requirements in this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:36:28.910",
"Id": "405903",
"Score": "0",
"body": "OK I updated the question now. BTW a trivial solution would be to use in-built substring match library function for every combination of (text, blacklisted_str). But this will not be very efficient when there are large number of blacklisted strings or if the size of the text is large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:28:43.443",
"Id": "405908",
"Score": "0",
"body": "Blacklisting and substrings also yields false positives. Blacklisting \"sex\" would claim that \"Middlesex, New Jersey\" is a bad phrase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:49:34.627",
"Id": "405940",
"Score": "0",
"body": "@RickDavin you are right. But if you use `String#startWith` then it would solve the issue. But I agree with @hsg, for large texts, this will not be the most efficient implementation (but premature optimisation is the root of all evil)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T23:38:30.400",
"Id": "426017",
"Score": "0",
"body": "@gervais.b I don't think your ass_umption about `startsWith` would work in practice."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T15:09:46.250",
"Id": "209912",
"ParentId": "209688",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T18:28:31.573",
"Id": "209688",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "Find out whether a given text contains any of the prohibited words"
} | 209688 |
<p>There is a Min-Heap implementation in Java. <strong>BubbleUp()</strong> and <strong>BubbleDown()</strong> could have been coded using recursion but I prefer without recursion. Would there be a major difference if had used recursion? </p>
<pre><code>package heap;
import interfaces.queue.PriorityQueue;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Heap<T extends Comparable<T>> implements
PriorityQueue<T>
{
private T[] elements;
private int size;
private int capacity;
public Heap()
{
this(500);
}
public Heap(int capacity)
{
this.capacity = capacity;
size = 0;
elements = (T[]) new Comparable[this.capacity];
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size() == 0;
}
@Override
public void add(T data) throws Exception
{
if(size() >= capacity) throw new Exception("Heap is full");
elements[size++] = data;
bubbleUp();
}
private void bubbleUp()
{
int child = size() - 1;
int parent = (child-1)/2;
while(parent >= 0 && elements[child].compareTo(elements[parent]) < 0)
{
swap(child, parent);
child = parent;
parent = (child-1)/2;
}
}
@Override
public T removeMin() throws Exception
{
if(isEmpty()) throw new Exception("Empty heap");
T root = elements[0];
swap(size()-1, 0);
elements[size()-1] = null;
size--;
bubbleDown();
return root;
}
private void bubbleDown()
{
int parent = 0;
int leftChild = 2*parent + 1;
int rightChild = 2*parent + 2;
int choice = compareAndPick(leftChild, rightChild);
while(choice != -1)
{
swap(choice, parent);
parent = choice;
choice = compareAndPick(2*choice+1, 2*choice+2);
}
}
private int compareAndPick(int leftChild, int rightChild)
{
if(leftChild >= capacity || elements[leftChild] == null) return -1;
if((elements[leftChild].compareTo(elements[rightChild]) <= 0)|| (elements[rightChild] == null))
return leftChild;
return rightChild;
}
private void swap(int child, int parent)
{
T t = elements[child];
elements[child] = elements[parent];
elements[parent] = t;
}
@Override
public String toString()
{
return Arrays.stream(elements)
.filter(element -> element != null)
.collect(Collectors.toList()).toString();
}
}
</code></pre>
| [] | [
{
"body": "<p>I do not endorse recursion when a clean and simple iterative iterative solution is readily available. You did the right thing.</p>\n\n<p>The only problem I have is with <code>compareAndPick</code> implementation. First, <code>rightChild</code> is not tested against <code>capacity</code>, and may cause an out-of-bounds access. Second, testing <code>elements[rightChild]</code> against <code>null</code> looks too late (how does <code>compareTo(null)</code> behave?). Finally, there is really no need to test both an index against <code>capacity</code> and an object against nullness: <code>index < size</code> guarantees both.</p>\n\n<p>You may consider renaming <code>compareAndPick</code> to <code>selectSmallestChild</code> (and <code>choice</code> to <code>child</code>).</p>\n\n<p>Also, I recommend to leave the children computation to <code>compareAndPick</code>, and have a terser version of <code>bubbleDown</code> loop:</p>\n\n<pre><code> while ((child = selectSmallestChild(parent)) != -1) {\n swap(child, parent);\n parent = child;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T01:01:32.577",
"Id": "209703",
"ParentId": "209701",
"Score": "1"
}
},
{
"body": "<h3>Exception handling</h3>\n\n<p>Throwing <code>Exception</code> is not recommended because it's too generic.\nIt doesn't give a clue to the caller as to what went wrong.\nIt's recommended to use specific exceptions.</p>\n\n<p>When implementing a collection abstract data type, it's good to take a look at a similar interface in the standard library, for example <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html#addFirst(E)\" rel=\"nofollow noreferrer\"><code>Deque</code></a>:</p>\n\n<ul>\n<li>How do they handle when an element cannot be added due to capacity restrictions? They throw <code>IllegalArgumentException</code>.</li>\n<li>How do they handle when an element is requested but the collection is empty? They throw <code>NoSuchElementException</code>.</li>\n</ul>\n\n<p>As you see, suitable specific exceptions already exist.\nAlso notice that these exceptions are <em>unchecked</em>.\nIt means that callers of these methods don't have to catch them.\nAnd that seems an appropriate decision,\nsince the situations in which these exceptions can be thrown are quite unexpected, and should not happen under normal circumstances.</p>\n\n<h3>Redundant <code>capacity</code> variable</h3>\n\n<p>The member variable <code>capacity</code> is redundant.\nThe same information already exists in <code>elements.length</code>.</p>\n\n<h3>Make members <code>final</code> when possible</h3>\n\n<p>Since <code>elements</code> is never reassigned, it would be good to make it <code>final</code>,\nso that you cannot reassign by mistake.</p>\n\n<h3>Overriding <code>toString</code></h3>\n\n<p>Keep in mind that <code>toString</code> is not intended for \"pretty-printing\".</p>\n\n<p>And for printing the content of the heap,\nthis implementation doesn't look useful to me.\nWith the <code>null</code> values removed,\nthe structure of the heap is not visible,\nand without the structure, the ordering of the elements is meaningless,\nwhich can be misleading.</p>\n\n<p>For printing the content of the heap I would suggest adding a dedicated method,\nkeep the <code>null</code>s, and print values of the first <code>size</code> elements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T09:57:34.350",
"Id": "209716",
"ParentId": "209701",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T00:02:33.503",
"Id": "209701",
"Score": "1",
"Tags": [
"java",
"heap",
"priority-queue"
],
"Title": "Generic Min Heap Implementation in Java"
} | 209701 |
<p>In <em>Algorithms</em> Fourth Edition by Robert Sedgewick and Kevin Wayne, the exercise 2.2.10 states that:</p>
<blockquote>
<p>Implement a version of merge() that copies the second half of a[] to
aux[] in decreasing order and then does the merge back to a[]. This
change al- lows you to remove the code to test that each of the halves
has been exhausted from the inner loop.</p>
</blockquote>
<p>This is my code in Python: </p>
<pre><code>def merge(a, lo, mi, hi):
aux_hi = deque(a[mi:hi])
for i in range(lo, hi)[::-1]:
if aux_hi:
last_a = i-len(aux_hi)
if last_a < lo:
a[i] = aux_hi.pop()
else:
a[i] = aux_hi.pop() if aux_hi[-1] > a[last_a] else a[last_a]
else:
break
</code></pre>
<p>Have I implemented it as required? Or can it be improved further?</p>
| [] | [
{
"body": "<p>I don't think you need <code>deque()</code> as you are popping from the end / right side which is a <span class=\"math-container\">\\$O(1)\\$</span> operation for regular lists:</p>\n\n<pre><code>aux_hi = a[mi:hi]\n</code></pre>\n\n<p>There are some minor concerns regarding:</p>\n\n<ul>\n<li>use of <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">whitespaces in the expressions and statements</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T12:58:05.813",
"Id": "405404",
"Score": "0",
"body": "Yes, you are right. deepcopy(precisely shallow copy) is not necessary here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T17:52:33.667",
"Id": "209727",
"ParentId": "209702",
"Score": "1"
}
},
{
"body": "<p>Disclaimer: I haven't tried to run your code nor the modifications I wrote.</p>\n\n<p><strong>Being explicit</strong></p>\n\n<p>Instead of using <code>[::-1]</code>, I'd recommend using <code>reversed</code> which is easier to read but more verbose.</p>\n\n<p>Also, as you are already using <code>if/else</code> you could get rid of the ternary operator to write the more explicit:</p>\n\n<pre><code> if last_a < lo:\n a[i] = aux_hi.pop()\n elif aux_hi[-1] > a[last_a]:\n a[i] = aux_hi.pop()\n else:\n a[i] = a[last_a]\n</code></pre>\n\n<p>which can be re-organised as:</p>\n\n<pre><code> if (last_a < lo or aux_hi[-1] > a[last_a]):\n a[i] = aux_hi.pop()\n else:\n a[i] = a[last_a]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:17:41.993",
"Id": "209741",
"ParentId": "209702",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T00:15:59.057",
"Id": "209702",
"Score": "2",
"Tags": [
"python",
"algorithm",
"sorting",
"mergesort"
],
"Title": "Python merge sort"
} | 209702 |
<p>I saw a question about prime factorization on Stack Overflow and realized I had never attempted it before. This was what I ended up with after some playing around and tweaking.</p>
<p>I'd like improvements on anything here.</p>
<ul>
<li><p>I know I could use a sieve instead of the naive method (I may switch later), but it was sufficient here. Is there a better way though to handle <code>2</code> in <code>prime?</code>? I feel like it being a special case is off.</p></li>
<li><p>Is there a better way than a full <code>loop</code> for the main function?</p></li>
<li><p>Whatever else</p></li>
</ul>
<hr>
<pre><code>(find-prime-factors 993061001)
=> [17 173 337661]
</code></pre>
<p>Verified against <a href="https://www.calculatorsoup.com/calculators/math/prime-factors.php" rel="nofollow noreferrer">CalculatorSoup</a>.</p>
<pre><code>(ns irrelevant.prime-factorization)
(defn is-factor-of? [n multiple]
(zero? (rem n multiple)))
(defn prime? [n]
(or (= n 2) ; TODO: Eww
(->> (range 2 (inc (Math/sqrt ^double n)))
(some #(is-factor-of? n %))
(not))))
(defn primes []
(->> (range)
(drop 2) ; Lower bound of 2 for the range
(filter prime?)))
(defn smallest-factor-of? [n possible-multiples]
(some #(when (is-factor-of? n %) %)
possible-multiples))
(defn find-prime-factors [n]
(loop [remaining n
remaining-primes (primes)
prime-factors []]
(if-let [small-prime (and (> remaining 1) (smallest-factor-of? remaining remaining-primes))]
(let [rest-primes (drop-while #(not= % small-prime) remaining-primes)]
(recur (long (/ remaining small-prime))
rest-primes
(conj prime-factors small-prime)))
prime-factors)))
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T02:23:32.290",
"Id": "209706",
"Score": "1",
"Tags": [
"primes",
"clojure"
],
"Title": "Naïve Prime Factorization in Clojure"
} | 209706 |
<p>I was asked this question and got no feedback, so I'd like to ask you for any feedback on my solution, Thanks!</p>
<p>Think of an audio sample as a rubber-band that you want to pin to a musical time ruler. The pins are called Warp Markers. A Warp Marker locks a specific point in the sample (in sample time) to a specific place in a measure (in beat time). You can use any number of Warp Markers to create an arbitrary mapping of the sample’s inherent rhythm to a musical meter. For the sake of this task, please assume the following behavior:</p>
<ol>
<li>An audio clip contains a reference to a sample and a collection of Warp Markers.</li>
<li>There is at least one Warp Marker in the clip.</li>
<li>Between two Warp Markers, the tempo is constant.</li>
<li>The tempo before the first Warp Marker is the same as the tempo after the first Warp
Marker.</li>
<li>The tempo after the last Warp Marker is specified separately in the input.</li>
<li>Beat time is measured in beats, sample time is measured in seconds, and tempo is
measured in beats per second.
Input description</li>
</ol>
<p>There are 4 kinds of lines in the input:</p>
<ol>
<li>Warp Marker definition</li>
<li>Definition of the tempo after the last marker</li>
<li>Sample time to beat time conversion</li>
<li>Beat time to sample time conversion</li>
</ol>
<p>At least one Warp Marker and the tempo after the last Warp Marker should be defined before the first conversion; otherwise, these can appear in any order.
Each line consists of a keyword followed by numeric arguments. All numeric values are entered as doubles without units. Warp Marker and tempo definitions affect only the conversions that come later in the input.</p>
<pre><code>marker <beat time> <sample time>
end_tempo <value>
s2b <sample time>
b2s <beat time>
</code></pre>
<p>Output description
For each of the s2b and b2s lines, the corresponding output time is printed without unit. Example</p>
<pre><code>Input
marker 0.0 0.0
marker 1.0 5.0
end_tempo 10.0
b2s 0.5
s2b 6.0
Output
2.5 11.0
</code></pre>
<p>Here's my solution:</p>
<pre><code>//one.h
#include <vector>
#include <string>
#include <map>
using namespace std;
#ifndef SAMPLER_H
#define SAMPLER_H
class Sampler {
public:
map<double, double> beats = {};
map<double, double> samples = {};
double endTempo;
void addMarker(double beat, double sample);
double b2s(double beat);
double s2b(double sample);
};
#endif
</code></pre>
<p>and</p>
<pre><code>// one.cc
#include "one.h"
using namespace std;
void Sampler::addMarker(double beat, double sample) {
beats[beat] = sample;
samples[sample] = beat;
}
double Sampler::b2s(double beat) {
auto marker2 = beats.upper_bound(beat);
if(marker2 == beats.begin()) marker2 = next(marker2);
auto marker1 = prev(marker2);
auto firstBeat = marker1->first;
auto firstSample = marker1->second;
double tempo;
if(marker2 == beats.end()) {
tempo = endTempo;
} else {
auto secondBeat = marker2->first;
auto secondSample = marker2->second;
tempo = (secondBeat - firstBeat) / (secondSample - firstSample);
}
return firstSample + ((beat - firstBeat) / tempo);
}
double Sampler::s2b(double sample) {
auto marker2 = samples.upper_bound(sample);
if(marker2 == samples.begin()) marker2 = next(marker2);
auto marker1 = prev(marker2);
auto firstBeat = marker1->second;
auto firstSample = marker1->first;
double tempo;
if(marker2 == samples.end()) {
tempo = endTempo;
} else {
auto secondBeat = marker2->second;
auto secondSample = marker2->first;
tempo = (secondBeat - firstBeat) / (secondSample - firstSample);
}
return firstBeat + ((sample - firstSample) * tempo);
}
</code></pre>
<p>and here's main</p>
<pre><code>#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include "one.h"
int main() {
Sampler sampler;
string str;
while(true) {
getline(cin, str);
istringstream ss(str);
string command;
getline(ss, command, ' ');
if(command == "marker") {
string strBeat;
string strSample;
getline(ss, strBeat, ' ');
getline(ss, strSample, ' ');
double beat = stod(strBeat);
double sample = stod(strSample);
sampler.addMarker(beat, sample);
} else if(command == "end_tempo") {
string strTempo;
getline(ss, strTempo, ' ');
sampler.endTempo = stod(strTempo);
} else if(command == "s2b") {
string s;
getline(ss, s, ' ');
cout << sampler.s2b(stod(s)) << endl;
} else if(command == "b2s") {
string b;
getline(ss, b, ' ');
cout << sampler.b2s(stod(b)) << endl;
} else {
break;
}
}
}
</code></pre>
<p>and heres my tests</p>
<pre><code>#include "one.h"
#include "gtest/gtest.h"
namespace {
class OneMarker : public ::testing::Test {
protected:
Sampler * sampler;
virtual void SetUp() {
sampler = new Sampler();
sampler->addMarker(3, 5);
sampler->endTempo = 10;
}
virtual void TearDown() {
delete sampler;
}
};
TEST_F(OneMarker, Before) {
EXPECT_EQ(4.6, sampler->b2s(-1));
EXPECT_EQ(-57, sampler->s2b(-1));
}
TEST_F(OneMarker, After) {
EXPECT_EQ(5.7, sampler->b2s(10));
EXPECT_EQ(53, sampler->s2b(10));
}
class TwoMarkers : public ::testing::Test {
protected:
Sampler * sampler;
virtual void SetUp() {
sampler = new Sampler();
sampler->addMarker(0, 0);
sampler->addMarker(1, 5);
sampler->endTempo = 10;
}
virtual void TearDown() {
delete sampler;
}
};
TEST_F(TwoMarkers, Before) {
EXPECT_EQ(-5.0, sampler->b2s(-1));
EXPECT_EQ(-0.2, sampler->s2b(-1));
}
TEST_F(TwoMarkers, Between) {
EXPECT_EQ(2.5, sampler->b2s(0.5));
EXPECT_EQ(11.0, sampler->s2b(6.0));
}
TEST_F(TwoMarkers, After) {
EXPECT_EQ(5.9, sampler->b2s(10));
EXPECT_EQ(51, sampler->s2b(10));
}
TEST_F(TwoMarkers, Mutation) {
EXPECT_EQ(5.9, sampler->b2s(10));
EXPECT_EQ(51, sampler->s2b(10));
sampler->addMarker(3,6);
EXPECT_EQ(6.7, sampler->b2s(10));
EXPECT_EQ(43, sampler->s2b(10));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T17:43:30.757",
"Id": "405426",
"Score": "1",
"body": "FYI, I considered reviewing your earlier question but could not understand what it was supposed to do. This explanation is much clearer to me."
}
] | [
{
"body": "<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. It's particularly bad to put that into a header file because it pollutes the global namespace.</p>\n\n<h2>Use appropriate <code>#include</code>s</h2>\n\n<p>The header file contains these two lines:</p>\n\n<pre><code>#include <vector>\n#include <string>\n</code></pre>\n\n<p>However, neither is actually required for the <em>interface</em>. Also <code>main</code> does not need <code><fstream></code> but needs <code><string></code> but that is not included.</p>\n\n<h2>Use better naming</h2>\n\n<p>The file named <code>one.h</code> is not well named. The include guard name suggests that it is actually named <code>sampler.h</code> which is indeed a better name.</p>\n\n<h2>Prefer <code>private</code> to <code>public</code> where practical</h2>\n\n<p>The <code>Sampler</code> class has data members <code>beats</code> and <code>samples</code> as public members. Rather than do it that way, it would be better to keep it private because the class relies on an <em>invariant</em> -- namely that each entry in <code>beats</code> has a corresponding entry in <code>samples</code>. Such invariants cannot easily be enforced if the data members are <code>public</code>.</p>\n\n<h2>Use include guards correctly</h2>\n\n<p>The <code>one.h</code> file does have an include guard, which is good, but doesn't have it as the first thing in the file. This can waste preprocessing time as contrasted with the usual (and recommended) method of putting the include guard as the very first non-comment line in the header.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>b2s</code> and <code>s2b</code> functions don't alter the underlying object and so should be declared <code>const</code>.</p>\n\n<h2>Reconsider the structures</h2>\n\n<p>It's unclear to me what, if anything, you intend to do with the beats and samples stored in the <code>Sampler</code> class, but the current method of having parallel <code>std::map</code> structures seems less than optimal. If, as I infer, the context is music, both the sample and beat are increasing functions. This suggests that they could easily be contained in a single <code>std::set<BeatTime></code> where <code>BeatTime</code> is a simple private <code>struct</code> containing both <code>double</code>s. </p>\n\n<p>With those changes, here's what the class declaration looks like:</p>\n\n<pre><code>class Sampler {\n struct BeatTime { \n double beat, sample; \n bool operator<(const BeatTime& rhs) const {\n return beat < rhs.beat;\n }\n };\n std::set<BeatTime> beats;\n std::set<BeatTime>::iterator sample_upper_bound(double sample) const;\n public:\n double endTempo;\n void addMarker(double beat, double sample);\n double b2s(double beat) const;\n double s2b(double sample) const;\n};\n</code></pre>\n\n<p>Now the <code>addMarker</code> function is very simple:</p>\n\n<pre><code>void Sampler::addMarker(double beat, double sample) {\n beats.emplace(BeatTime{beat, sample});\n}\n</code></pre>\n\n<p>And the <code>b2s</code> code is simplified:</p>\n\n<pre><code>double Sampler::b2s(double beat) const {\n auto marker2 = beats.upper_bound(BeatTime{beat, 0});\n double tempo{endTempo};\n if(marker2 == beats.begin()) {\n marker2 = next(marker2);\n }\n auto marker1 = prev(marker2);\n if(marker2 != beats.end()) {\n tempo = (marker2->beat - marker1->beat) / (marker2->sample - marker1->sample);\n }\n return marker1->sample + ((beat - marker1->beat) / tempo);\n}\n</code></pre>\n\n<p>The <code>s2b</code> code is almost identical except that, of course, we can't use <code>upper_bound</code> directly. Instead, it uses this:</p>\n\n<pre><code>std::set<Sampler::BeatTime>::iterator Sampler::sample_upper_bound(double sample) const {\n auto ret{beats.begin()};\n for ( ; ret != beats.end() && ret->sample <= sample; ++ret) \n {} \n return ret;\n}\n</code></pre>\n\n<p>This makes the search linear rather than logarithmic, but it's unlikely to make a huge practical difference until the set becomes very large.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T17:40:50.910",
"Id": "209776",
"ParentId": "209707",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209776",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T03:55:59.717",
"Id": "209707",
"Score": "7",
"Tags": [
"c++",
"algorithm",
"audio",
"music"
],
"Title": "Warped Audio Sample"
} | 209707 |
<p>I am self taught, so I'm consistently seeking ways to code better, and more efficiently. If anyone has the time, please advise me on what can be done better with explanations as to why the old method is considered inefficient, and why the new method proves to be better. Also, where I can implement more self explanatory code.</p>
<pre><code>using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
namespace Mans.Prototype.Lumberjack {
[System.Serializable]
public class GameManager : MonoBehaviour {
public static GameManager instance { get; private set; } //singleton
private static Timer _timer;
[SerializeField] private GameObject _logPrefab;
[SerializeField] private float _seconds;
public Timer timer {
get { return _timer; }
set { _timer = value; }
}
public static GameObject logPrefab {
get { return instance._logPrefab; }
}
private void Awake() {
instance = this;
timer = new Timer( _seconds );
InitializeScenes();
}
private void Start() {
ObjectManager.Initialize();
UIManager.ToggleUIElement( "InGame" );
SceneManager.SetActiveScene( SceneManager.GetSceneByName( "Level" ) );
}
private void Update() {
if ( Input.GetKey( KeyCode.Return ) ) {
Scene temp = SceneManager.GetSceneByName( "Level" );
SceneManager.UnloadSceneAsync( temp );
SceneManager.LoadScene( temp.buildIndex, LoadSceneMode.Additive );
}
}
private void FixedUpdate() {
if ( timer.seconds < 1f && ObjectManager.instance.treeCount > 0 ) {
PlayerManager.instance.player.GetComponent<Animator>().enabled = false;
UIManager.ToggleUIElement( "InGame", false );
UIManager.ToggleUIElement( "GameOver", true );
return;
} else if ( timer.seconds > 0f && ObjectManager.instance.treeCount <= 0 ) {
return;
}
InputManager.instance.HandleInput();
--_timer;
}
private void InitializeScenes() {
//Preload starting scenes
LoadScene( "Scenes/UI" );
LoadScene( "Scenes/Level 1/Level" );
LoadScene( "Scenes/Player" );
}
public static void LoadScene( string path ) {
//Loads a scene. Created so other scripts can manipulate the levels without having to include relevant namespaces each time.
SceneManager.LoadScene( path, LoadSceneMode.Additive );
}
public static void MoveObjectToScene( GameObject @object, string name ) {
//moves from current active scene to scene of choice, usually the level scene.
SceneManager.MoveGameObjectToScene( @object, SceneManager.GetSceneByName( name ) );
}
}
}
</code></pre>
<p>I'm unsure if I have elaborated enough, if not, say so and I will update with more explanations where necessary. No specific goal, other than to improve the readability and efficiency of the code.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T06:38:49.007",
"Id": "209711",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"game",
"design-patterns",
"unity3d"
],
"Title": "Prototype GameManager for game written in Unity"
} | 209711 |
<p>I'm doing a simple calc for my school. The code looks okay to me, but I'm not sure if there is something to improve, but probably there is always something to improve. Any ideas how to make it look and work better?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kalkulacka
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Daniel Nosek");
Console.WriteLine("Výpočet obvodu a obsahu - trojúhelník, pravidelný šestiúhelník");
Console.WriteLine("Zvolte si obrazec:");
Console.WriteLine("1 - trojúhelník");
Console.WriteLine("2 - pravidelný šestiúhelník");
int VolbaObrazce = int.Parse(Console.ReadLine());
double obvod = 0;
double obsah = 0;
bool prepocitat = false;
do
{
Console.Clear();
switch (VolbaObrazce)
{
case 1:
double a = PrectiPromennou("Zadejte délku strany a:");
double b = PrectiPromennou("Zadejte délku strany b:");
double c = PrectiPromennou("Zadejte délku strany c:");
obvod = ObvodTrojuhelniku(a, b, c);
obsah = ObsahTrojuhelniku(a, b, c);
break;
case 2:
double d = PrectiPromennou("Zadejte délku strany d:");
obvod = ObvodSestiuhelniku(d);
obsah = ObsahSestiuhelniku(d);
break;
default:
{
Console.WriteLine("Neplatná volba");
}
return;
}
// vysledky, zaokrouhleny na dve desetinna mista
Console.WriteLine("obvod: " + Math.Round(obvod, 2));
Console.WriteLine("obsah: " + Math.Round(obsah, 2));
/* loop pro pripad kdy uzivatel chce vypocet znova s jinymi hodnotami
promenna recalculate musi byt rovna 1, jinak se program vypne */
prepocitat = PrectiPromennou("Pro výpočet s jinými rozměry stiskněte 1:") == 1;
}
while (prepocitat);
}
/*Puvodne jsem pouzival pri cases
Console.WriteLine("Zadejte délku strany x:");
double x = double.Parse(Console.ReadLine());
nicmene resit to takhle mi prijde jednodussi.*/
static double PrectiPromennou(string text)
{
Console.Write(text);
return double.Parse(Console.ReadLine());
}
/// <summary>
/// Vypocet obvodu pomoci souctu stran
/// </summary>
/// <param name="a">delka strany a</param>
/// <param name="b">delka strany b</param>
/// <param name="c">delka strany c</param>
/// <returns>obvod trojuhelniku</returns>
static double ObvodTrojuhelniku(double a, double b, double c)
{
return a + b + c;
}
/// <summary>
/// Vypocet obsahu pomoci heronova vzorce
/// </summary>
/// <param name="a">delka strany a</param>
/// <param name="b">delka strany b</param>
/// <param name="c">delka strany c</param>
/// <returns>obsah trojuhelniku</returns>
static double ObsahTrojuhelniku(double a, double b, double c)
{
double s = (a + b + c) / 2;
return Math.Sqrt(s * (s - a) * (s - b) * (s - c));
}
/// <summary>
/// Vypocet obvodu pomoci soucinu stran
/// </summary>
/// <param name="d">delka strany d</param>
/// <returns>obvod sestiuhelniku</returns>
static double ObvodSestiuhelniku(double d)
{
return 6 * d;
}
/// <summary>
/// vypocet obsahu
/// </summary>
/// <param name="d">delka strany d</param>
/// <returns>obsah sestiuhelniku</returns>
static double ObsahSestiuhelniku(double d)
{
return ((3 * Math.Sqrt(3) * Math.Pow(d, 2))) / 2;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T10:02:25.757",
"Id": "405396",
"Score": "0",
"body": "what .net framework are you using? 4.6? 4.7? lower?"
}
] | [
{
"body": "<p>Depending on your style and .net version you can change some of your methods to <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6#expression-bodied-function-members\" rel=\"nofollow noreferrer\">Expression bodied function members</a>:</p>\n\n<pre><code>/// documentation\nstatic double ObvodTrojuhelniku(double a, double b, double c) => a + b + c\n\n/// documentation\nstatic double ObvodSestiuhelniku(double d) => 6 * d\n\n/// documentation\nstatic double ObsahSestiuhelniku(double d) => ((3 * Math.Sqrt(3) * Math.Pow(d, 2))) / 2;\n</code></pre>\n\n<p>I really like those small function you are using, they are easily testable and follow <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a> - they have only one function and one reasons to change - if at all.</p>\n\n<hr>\n\n<p>You should add input validation - if a user inputs <code>\"QWER\"</code> and you <code>int.Parse(..)</code> it <em>directly</em>, it will crash. Similarly for <code>double.Parse(...)</code> </p>\n\n<p>Consider using something along the lines of:</p>\n\n<pre><code>public static class InputHelper\n{\n /// <summary>\n /// Ask unser for input until a valid double is parsed\n /// </summary>\n /// <param name=\"text\">The text presented to the user before inputting.</param>\n /// <returns>double</returns>\n public static double GetDouble(string text)\n {\n string p = null;\n while (true)\n {\n Console.WriteLine(text);\n try\n {\n p = Console.ReadLine();\n return double.Parse(p);\n }\n catch (Exception ex)\n {\n if (ex is FormatException)\n {\n Console.WriteLine($\"Invalid input: '{p}' - only numbers and 1 decimal divider allowed!\");\n }\n else if (ex is OverflowException)\n {\n Console.WriteLine($\"Invalid input: '{p}' - is too big. Max: {double.MaxValue}\");\n }\n }\n }\n }\n\n /// <summary>\n /// Ask unser for input until a valid integer is parsed\n /// </summary>\n /// <param name=\"text\">The text presented to the user before inputting.</param>\n /// <returns>integer</returns>\n public static int GetInt(string text)\n {\n string p = null;\n while (true)\n {\n Console.WriteLine(text);\n try\n {\n p = Console.ReadLine();\n return int.Parse(p);\n }\n catch (Exception ex)\n {\n if (ex is FormatException)\n {\n Console.WriteLine($\"Invalid input: '{p}' - only numbers allowed!\");\n }\n else if (ex is OverflowException)\n {\n Console.WriteLine($\"Invalid input: '{p}' - is too big. Max: {int.MaxValue}\");\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>where you do <code>int VolbaObrazce = int.Parse(Console.ReadLine());</code> and inside <code>static double PrectiPromennou(string text)</code>.</p>\n\n<hr>\n\n<p>If you know about templating, you can reduce the duplicate code (DRY) in your static helpers. I put them into an extra class to be used in other projects as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T10:25:52.427",
"Id": "209757",
"ParentId": "209714",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>Handle possible exceptions across your code. <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch\" rel=\"nofollow noreferrer\">Handle Exceptions</a></p>\n<p>Handle parsing values directly to avoid exceptions (use <strong>TryParse</strong> instead of Parse).</p>\n</blockquote>\n<pre><code>int VolbaObrazce;\nbool validInput= int.TryParse(Console.ReadLine(),out VolbaObrazce);\n//here you shall have value in VolbaObrazce if you only provide valid int.\n</code></pre>\n<p>you have also multiple methods that handles only arithmetic operation which will be very hard to maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T14:03:31.770",
"Id": "405409",
"Score": "1",
"body": "`int.TryParse(...)` is generally used like this: `if (int.TryParse(Console.ReadLine(),out var VolbaObrazce)) { .... }` - you loose the _reason_ of the \"not parsable\" with it. Multiple methods that do one thing _very well_ are not hard to maintain - you can easily test them and they have very few reasons to change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T22:38:50.517",
"Id": "405459",
"Score": "0",
"body": "i second you in defining one responsibility per method but actually i see it so un useful to perform only one arithmetic operation per method, may be defining a property here will fit better for readability & maintainability."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T11:08:35.730",
"Id": "209758",
"ParentId": "209714",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T07:38:57.780",
"Id": "209714",
"Score": "3",
"Tags": [
"c#",
"homework",
"calculator"
],
"Title": "Simple C# calculator"
} | 209714 |
<p>I've been playing around with functional programming and testing with jest recently.</p>
<p>An issue I've run into, is that it's hard to mock ES6 module exports directly. <a href="https://stackoverflow.com/questions/53736766/what-is-the-state-of-the-art-for-testing-mocking-functions-within-a-module-in-20">See this Stack Overflow question for more details.</a></p>
<p>The solution I've come up with is to inject the dependency functions into the function that is calling it, via <code>.bind</code>.</p>
<p>Here's an example:</p>
<pre><code>import axios from "axios";
const BASE_URL = "https://jsonplaceholder.typicode.com/";
const URI_USERS = 'users/';
/**
* These are the implementation of our functions, which take functions as arguments.
*/
export const _fetchUsers = async function (_makeApiCall, _URI_USERS) {
return _makeApiCall(_URI_USERS);
}
export const _fetchUser = async function (_makeApiCall, _URI_USERS, id) {
return _makeApiCall(_URI_USERS + id);
}
export const _fetchUserStrings = async function (_fetchUser, _parseUser, ...ids) {
const users = await Promise.all(ids.map(id => _fetchUser(id)));
return users.map(user => _parseUser(user));
}
export const _makeApiCall = async function (uri) {
try {
const response = await axios(BASE_URL + uri);
return response.data;
} catch (err) {
throw new Error(err.message);
}
}
export function _parseUser(user) {
return `${user.name}:${user.username}`;
}
/**
* Real exports
*/
export const makeApiCall = _makeApiCall;
export const parseUser = _parseUser;
export const fetchUsers = _fetchUsers.bind(null, _makeApiCall, URI_USERS);
export const fetchUser = _fetchUser.bind(null, _makeApiCall, URI_USERS);
export const fetchUserStrings = _fetchUserStrings.bind(null, _fetchUser, _parseUser);
</code></pre>
<p>And a test:</p>
<pre><code>/**
* Our most complicated test
*
*/
describe("_fetchUserStrings", () => {
describe("happy flow", () => {
const fetchUserMock = jest.fn((i) => Promise.resolve({
username: "foo",
name: "bar"
}));
const parseUserMock = jest.fn(user => "string");
const fetchUserStrings = _fetchUserStrings.bind(null, fetchUserMock, parseUserMock);
it("returns an array of three strings", async () => {
expect.assertions(3);
const result = await fetchUserStrings(1, 2, 3);
// I'm being a bit lazy here, you could be checking that
// The strings are actually there etc, but whatevs.
expect(fetchUserMock).toHaveBeenCalledTimes(3);
expect(parseUserMock).toHaveBeenCalledTimes(3);
expect(result).toHaveLength(3);
})
});
});
</code></pre>
<p>My question is - is this a super clean way of writing functional JavaScript, or is this overkill that is easily solved another way?</p>
<p>If you're interested, there are more examples <a href="https://github.com/dwjohnston/testing_with_jest" rel="nofollow noreferrer">here</a>.</p>
| [] | [
{
"body": "<blockquote>\n <p>or is this overkill that is easily solved another way?</p>\n</blockquote>\n\n<p><code>_fetchUser</code> and <code>_fetchUsers</code> appear to be the same function; save for the <code>id</code> parameter.</p>\n\n<p>If interpret the question correctly, <code>_fetchUser</code> can be substituted for <code>_fetchUsers</code> (which can be removed entirely) by utilizing default parameters instead of <code>.bind()</code>.</p>\n\n<p>For example</p>\n\n<pre><code>async function _makeApiCall (uri) {\n try {\n const response = await Promise.resolve(uri);\n return response;\n } catch (err) {\n throw new Error(err.message);\n }\n}\n\nasync function _fetchUsers({makeApiCall = _makeApiCall, _URI_USERS = 'abc', id = ''} = {}) {\n return await makeApiCall(_URI_USERS + id);\n}\n\nexport default _fetchUsers;\n</code></pre>\n\n<hr>\n\n<pre><code><script type=\"module\">\n import _fetchUsers from './script.js'; \n (async() => {\n console.log(await _fetchUsers() // 'abc'\n , await _fetchUsers({id:'def'}) // 'abcdef'\n );\n })();\n</script>\n</code></pre>\n\n<p><a href=\"http://plnkr.co/edit/MM2wzPWdcfMbXIz4AVbm?p=preview\" rel=\"nofollow noreferrer\">plnkr</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:09:18.183",
"Id": "405379",
"Score": "0",
"body": "Re: deault parameters - this makes it difficult/impsible to use a rest operator (for passing in an array of arguments) - see this question: https://stackoverflow.com/questions/53752586/dependency-injection-rest-and-default-function-parameters-for-the-same-function, also - having the functions as parameters means they'll show up on the IDE and generally muddy it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:20:36.117",
"Id": "405380",
"Score": "0",
"body": "Rest element and rest parameter are not an operators [What is SpreadElement in ECMAScript documentation? Is it the same as Spread syntax at MDN?](https://stackoverflow.com/questions/37151966/) Concerning using both rest parameters and default parameters, are you trying to do something like [arrow functions: destructuring arguments and grabbing them as a whole at the same time](https://stackoverflow.com/q/47117312/2801559) or [Can we set persistent default parameters which remain set until explicitly changed?](https://stackoverflow.com/q/43466657/2801559)? How is an IDE related to the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:24:08.460",
"Id": "405381",
"Score": "0",
"body": "Alright - there's some fantastic resources there, thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T17:38:49.897",
"Id": "209726",
"ParentId": "209718",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T10:19:51.730",
"Id": "209718",
"Score": "2",
"Tags": [
"javascript",
"unit-testing",
"functional-programming"
],
"Title": "This technique for functional programming, and testing functional programming"
} | 209718 |
<blockquote>
<p>Given a Linked List of integers, write a function to modify the linked
list such that all <strong>even numbers appear before all the odd numbers in
the modified linked list.</strong> Also, keep the <strong>order</strong> of even and odd
numbers <strong>same.</strong> - (from geeksforgeeks: <a href="https://www.geeksforgeeks.org/segregate-even-and-odd-elements-in-a-linked-list/" rel="nofollow noreferrer">Segregate even and odd nodes in a Linked List</a>)</p>
<p>Example:</p>
<p>Input:</p>
<pre><code>3
7
17 15 8 9 2 4 6
4
1 3 5 7
7
8 12 10 5 4 1 6
</code></pre>
<p>Output:</p>
<pre><code>8 2 4 6 17 15 9
1 3 5 7
8 12 10 4 6 5 1
</code></pre>
</blockquote>
<p>My Approach: get pointer to the last node of list. And then traverse the list starting from the head node and move the odd valued nodes from their current position to end of the list.Also if all the node's data is even or odd then list remains unmodified so first I check if this is the case then I simply return(<strong>len</strong> is total number of nodes & <strong>count</strong> is total number of even data nodes).</p>
<p>I am getting right answer on an IDE, but on other IDE where the code needs to be submitted, it's showing <strong>time limit exceeded</strong>.</p>
<p>How do I optimize my code?</p>
<pre><code>#include <iostream>
using namespace std;
int flag=0;
struct Node{
int data;
Node* next;
};
void addkey(struct Node** head_ref,int key)
{struct Node* temp=(struct Node*)malloc(sizeof(Node));
temp->next=NULL;
temp->data=key;
if(*head_ref==NULL)
{
*head_ref=temp;
}
else
{
struct Node* ptr=*head_ref;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
}
}
void segregate(struct Node**head_ref)
{ int len=0,count=0;
struct Node* ptr1=*head_ref;
struct Node* ptr2=*head_ref;
struct Node* prev=NULL;
while(ptr2->next!=NULL)
{
if((ptr2->data)%2==0) count++;
ptr2=ptr2->next;
len++;
}
if(ptr2->data%2==0) count++;
if(count==len+1||count==0) return;
struct Node* ptr5=ptr2;
while(ptr1!=ptr5->next)
{
if((ptr1->data%2)==0)
{ if(flag==0) {
*head_ref=ptr1;
flag=1;}
prev=ptr1;
ptr1=ptr1->next;
}
else
{
if(prev!=NULL) prev->next=ptr1->next;
ptr2->next=ptr1;
ptr2=ptr2->next;
ptr1=ptr1->next;
ptr2->next=NULL;
}
}
}
void printlist(struct Node* head)
{
if(head==NULL) return;
else
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
}
}
int main() {
int T ;
cin>>T;
while(T--)
{
int n;
cin>>n;
struct Node* head=(struct Node*)malloc(sizeof(Node));
head=NULL;
for(int i=0;i<n;i++)
{int key;
cin>>key;
addkey(&head,key);
}
segregate(&head);
printlist(head);cout<<"\n";
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T14:29:49.233",
"Id": "405338",
"Score": "0",
"body": "Is this a homework question? What if you could do the task better without using linked lists?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T14:49:47.387",
"Id": "405339",
"Score": "0",
"body": "@200_success No not a homework question..you can suggest without using linked list too."
}
] | [
{
"body": "<p>The best way to accelerate your code is to defenestrate it (9.82 m/s2) and use the correct algorithm.</p>\n\n<p>You don't need to do anything fancy. Just go through the list once, print all the even numbers, go through once more and print the odd ones.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T15:49:44.570",
"Id": "405341",
"Score": "0",
"body": "Do you think that `std::stable_partition` will be slower? Though your solution is definitely the easiest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T15:54:38.753",
"Id": "405342",
"Score": "0",
"body": "In the general case I think two linear scans will be faster except when the input is already properly sorted. Of course I'd need to measure to be sure. The big time consumer would be branch mispredictions whenever determining if to print or not in the linear scans. But regardless it's not possible to do better than O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:03:15.043",
"Id": "405343",
"Score": "0",
"body": "It got me wondering if there are any practical usages for stable (or not) partition, may be when in-placeness is required? There are very few cases when a value is swappable and not movable. By the way, nice joke, though deletion of text or files do not abide gravity, if you didn't mean to throw away the computer too :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:20:22.313",
"Id": "405344",
"Score": "0",
"body": "`std::stable_sort` has provisions for dealing with large arrays and producing an output array, my solution only prints the answer without actually constructing it in memory. It's a metaphorical defenestration :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:37:57.043",
"Id": "405345",
"Score": "0",
"body": "@EmilyL. But actual question is to modify the linked list otherwise there's no meaning in question, I can solve it using array also then.I don't want to solve any question just for the sake of getting it submitted, want to learn also.So please suggest something else:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:41:18.673",
"Id": "405346",
"Score": "1",
"body": "@Hanoi Change \"print\" into append to output array :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:44:40.343",
"Id": "405347",
"Score": "0",
"body": "@EmilyL. Can you please suggest something using Linked list:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:46:52.243",
"Id": "405348",
"Score": "0",
"body": "@Hanoi, I posted my answer. It doesn't use linked list, but it gives some pointers about where to search for to improve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:50:24.847",
"Id": "405349",
"Score": "0",
"body": "@Hanoi to be honest the original problem isn't great for learning as it encourages coming up with an ad-hoc solution that probably isn't great instead of studying the typical stable partition algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:52:28.790",
"Id": "405350",
"Score": "1",
"body": "@Hanoi make a linked list of the input, iterate over it once, copy even numbers into a new linked list, iterate over the lined list once more and copy the odd numbers into the output linkde list, print. The solution doesn't change depending on which implementation of list you use in this case :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:53:08.970",
"Id": "405351",
"Score": "0",
"body": "@EmilyL. Yeah, you are right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T17:06:51.687",
"Id": "405354",
"Score": "2",
"body": "@Hanoi the question as formulated is basically \"I have this easy problem I want to solve but you must do it in the most convoluted manner possible and it won't matter for the result\" :)"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T15:48:36.830",
"Id": "209722",
"ParentId": "209720",
"Score": "4"
}
},
{
"body": "<h2>Code Review (or its absence)</h2>\n\n<p>There are way too many problems to talk about. This is definitely not idiomatic C++14, let alone C++98. Please grab a book from <a href=\"https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list\">this list</a>. The algorithm you are searching for though is called \"stable partition\".</p>\n\n<h2>Better solution</h2>\n\n<p><a href=\"https://codereview.stackexchange.com/users/36120/emily-l\">Emily's</a> <a href=\"https://codereview.stackexchange.com/posts/209722/revisions\">answer</a> is already great. Use it if you need to just solve the problem.</p>\n\n<h2>Alternative solution</h2>\n\n<p>Here is the C++14 solution with standard library:</p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n\nusing in_iterator = std::istream_iterator<int>;\nusing out_iterator = std::ostream_iterator<int>;\n\nvoid iteration(int count) {\n std::vector<int> values(count);\n std::copy_n(in_iterator{std::cin}, count, \n values.begin());\n\n std::stable_partition(values.begin(), values.end(), \n [](auto x) {return x % 2 == 0;});\n\n std::copy(values.begin(), values.end(), \n out_iterator{std::cout, \" \"});\n}\n\nint main() { \n int test_count = 0;\n std::cin >> test_count;\n for (; test_count >= 0; --test_count) {\n int value_count = 0;\n std::cin >> value_count;\n iteration(value_count);\n std::cout << '\\n';\n }\n}\n</code></pre>\n\n<p>I believe everything happening in <code>main()</code> is fairly obvious.</p>\n\n<pre><code>std::vector<int> values(count);\nstd::copy_n(in_iterator{std::cin}, count, \n values.begin());\n</code></pre>\n\n<p>Those two lines initialize the <code>values</code> vector, by first creating the vector to hold <code>count</code> elements, then copying <code>count</code> elements from <code>std::cin</code> into <code>values</code>.</p>\n\n<p>The next statement is just invocation of the algorithm from standard library.</p>\n\n<p>The last line of the <code>iteration</code> function just copies the whole of the <code>values</code> into the <code>std::cout</code> stream.</p>\n\n<p>Solution with linked list will be the same, just way more lengthier. One can also reimplement the stable partition too, if you feel like it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T18:06:47.650",
"Id": "405358",
"Score": "0",
"body": "Solution with linked lists: `sed -i 's/vector/list/g' solution.cpp` :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T18:24:23.783",
"Id": "405360",
"Score": "0",
"body": "@EmilyL., ikr, I would choose that solution any day of the week over reimplementing linked list"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T16:45:17.337",
"Id": "209724",
"ParentId": "209720",
"Score": "4"
}
},
{
"body": "<h3>Bug: Infinite loop</h3>\n\n<p>If your program runs on a list that ends in an odd number, it will run forever in an infinite loop. For example, try this input:</p>\n\n<pre><code>1\n3\n1 2 3\n</code></pre>\n\n<p>The problem is with the termination condition of your loop:</p>\n\n<pre><code>while(ptr1!=ptr5->next)\n</code></pre>\n\n<p><code>ptr5</code> is the last element of the original linked list (e.g. node <code>3</code>), and you are trying to terminate your loop when you have iterated through each element (get past node <code>3</code>). However, if the last element is an odd number, it will be moved to the end of the list, and <code>ptr1</code> will never actually \"get past ptr5\". Instead, it will only catch up to it, move it, and then keep iterating through the odd numbers of the list over and over.</p>\n\n<p>I made some minor edits to your program to fix the problem, although your algorithm is still overly complicated and you should think about simpler ways of solving the same problem:</p>\n\n<pre><code>void segregate(struct Node**head_ref)\n{ int len=0,count=0;\n struct Node* ptr1=*head_ref;\n struct Node* ptr2=*head_ref;\n struct Node* prev=NULL;\n while(ptr2->next!=NULL)\n {\n if((ptr2->data)%2==0) count++;\n ptr2=ptr2->next;\n len++;\n }\n if(ptr2->data%2==0) count++;\n if(count==len+1||count==0) return;\n struct Node* ptr5=ptr2;\n while(ptr1!=ptr5->next)\n {\n if((ptr1->data%2)==0)\n { if(flag==0) {\n *head_ref=ptr1;\n flag=1;}\n prev=ptr1;\n // I added this termination condition\n if (ptr1 == ptr5)\n break;\n ptr1=ptr1->next;\n }\n else\n {\n if(prev!=NULL) prev->next=ptr1->next;\n ptr2->next=ptr1;\n ptr2=ptr2->next;\n // I added this termination condition\n if (ptr1 == ptr5) {\n ptr2->next=NULL;\n break;\n }\n ptr1=ptr1->next;\n ptr2->next=NULL;\n }\n }\n}\n</code></pre>\n\n<h3>Example of a simpler solution</h3>\n\n<p>This solution assumes that you actually need to create a new sorted list instead of just printing out the answer. It iterates through the original list and places each element into one of two lists. Then it joins the two lists and returns the joined list.</p>\n\n<pre><code>void segregate(struct Node**head_ref)\n{\n struct Node *evenList = NULL;\n struct Node *evenTail = NULL;\n struct Node *oddList = NULL;\n struct Node *oddTail = NULL;\n\n // Separate nodes into two lists.\n for (struct Node *p = *head_ref; p != NULL; p = p->next) {\n if ((p->data) % 2 == 0) {\n if (evenTail != NULL)\n evenTail->next = p;\n else\n evenList = p;\n evenTail = p;\n } else {\n if (oddTail != NULL)\n oddTail->next = p;\n else\n oddList = p;\n oddTail = p;\n }\n }\n\n // Terminate odd list with NULL.\n if (oddList != NULL)\n oddTail->next = NULL;\n // Place odd list at the end of the even list.\n if (evenList != NULL)\n evenTail->next = oddList;\n else\n evenList = oddList;\n\n *head_ref = evenList;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T04:57:30.183",
"Id": "209797",
"ParentId": "209720",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T14:06:32.480",
"Id": "209720",
"Score": "4",
"Tags": [
"c++",
"programming-challenge",
"linked-list",
"time-limit-exceeded",
"c++14"
],
"Title": "Stable-sorting all even numbers before odd numbers in a linked list"
} | 209720 |
<p>Let's assume we have the following situation: </p>
<ul>
<li>Multiple project topics exist, each corresponding to a natural number <code>n</code>,</li>
<li>students can sign in and choose two projects and give them either <code>priority_1</code> or <code>priority_2</code>,</li>
<li>The name and the time when they sign in is tracked as well.</li>
</ul>
<p>With all of the information above assume you receive data in the from of a <code>txt</code>-file looking like this</p>
<pre><code>Martin 16:46:32 8 19
Alice 15:22:56 8 12
Alex 17:23:11 19 1
John 19:02:11 11 13
Phillip 19:03:11 11 13
Diego 15:23:57 14 5
Jack 16:46:45 8 3
</code></pre>
<p>where the columns represent the <code>name</code>, <code>time</code>, <code>priority 1</code> and <code>priority 2</code> in this order. You can assume that all of them signed in on the same day and students which signed in first have a higher priority in comparison to the others.</p>
<p>I wanted to write a program that takes this <code>txt</code>-file as input and returns a <code>txt</code>-file with output</p>
<pre><code>Name Assigned Project
Alice 8
Diego 14
Martin 19
Jack 3
Alex 1
John 11
Phillip 13
</code></pre>
<hr>
<p>The solution I came up with looks like this:</p>
<pre><code>import numpy as np
dat = np.genfromtxt("data.txt", dtype="str")
class person:
def __init__(self, name, time, prio1, prio2):
self.name = name
sp = time.split(":")
t = sp[0]*3600 + sp[1]*60 + sp[2]
self.time = t
self.prio1 = prio1
self.prio2 = prio2
names = dat[:, 0]
time = dat[:, 1]
prio1 = dat[:, 2]
prio2 = dat[:, 3]
people = []
for i,j,k,l in zip(names, time, prio1, prio2):
people.append(person(i,j,k,l))
people_sorted_time = sorted(people, key=lambda x: x.time)
for k in range(len(people_sorted_time)):
for j in range(k + 1, len(people_sorted_time)):
if people_sorted_time[k].prio1 == people_sorted_time[j].prio1:
people_sorted_time[j].prio1 = people_sorted_time[j].prio2
res = open("results","w")
res.write("Name"+"\t"+"Assigned Project"+"\n")
for k in range(len(people_sorted_time)):
res.write(people_sorted_time[k].name + "\t"
+ people_sorted_time[k].prio1 + "\n")
</code></pre>
<hr>
<p>The code seems to work fine, but I'm not sure if I actually was able to take care of all edge-cases. I'm also not sure if this is really a efficient way to solve the problem, I rarely code stuff like that (mostly computational physics stuff), and would appreciate any kind of suggestions on how one could improve the code in general. </p>
<p><strong>EDIT:</strong> What I realized after some thinking is that it would probably be quite hard do implement further <code>priority</code> variables (like <code>prio 3</code>, <code>prio 4</code>, etc.). If someone could suggest a better way of deciding how to assign the projects in terms of priority, I'd be glad to see it. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T00:48:05.753",
"Id": "405386",
"Score": "0",
"body": "Is there any reason to consider three students choosing the same pair? What about students in chronological order A(1,2), B(3,4), C(1,3) where a solution exists as long as you don’t choose greedily?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T00:50:24.363",
"Id": "405387",
"Score": "0",
"body": "Also, if a student waits until just after midnight, they are guaranteed first choice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T00:52:54.910",
"Id": "405388",
"Score": "0",
"body": "@IanMacDonald I‘m sorry, but I‘m having a hard time understandig what you mean by A(1,2), etc. To the forst question, well two students chosing the same pair was just a special case which I wanted to have for tests and since popular topics are often chosen multiple times this didn‘t seem to far fetched. Not sure if three and two times the same pair makes really any difference.. And what exactly do you mean by „choose greedily“?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T00:53:48.787",
"Id": "405389",
"Score": "0",
"body": "@IanMacDonald as written in the description you can assume that all students sign-in on the same day..."
}
] | [
{
"body": "<p>There are two issues I personally dislike very much.</p>\n\n<h1>Messing with date/time using homebrew algorithm and math</h1>\n\n<p>While looking easy to handle time/date are by far more complcated to handle than you ever can think of. Timezones, locals, leap years and so on. When doing time/date math and/or serialisation/deserialisation always(!) go for a library. For python this is <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\">datetime</a></p>\n\n<h1>When the code is lying to me when I'm reading it as natural language</h1>\n\n<p>With lying I mean your line</p>\n\n<pre><code>people_sorted_time[j].prio1 = people_sorted_time[j].prio2\n</code></pre>\n\n<p>This is not true. The person clearly stated a first priority project. When you change that value as an algorithmic side effect you immediatly break data integrity. Your person suddenly has both priorities on the same project. You even got yourself tricked. What happens, when a person got the first prio project taken away and later the second one as well?</p>\n\n<h1>Other issues</h1>\n\n<p>There is no need to have <code>people_sorted_time</code>, as you never refer to the read order again. Just do </p>\n\n<pre><code>people = sorted(people, key=lambda x: x.time) \n</code></pre>\n\n<p>Never loop over <code>range(len(something)</code>, always try to loop over the elements directly. Your output loop rewrites (still lying about prio1) to</p>\n\n<pre><code>for p in people:\n res.write(p.name + \"\\t\" + p.prio1 + \"\\n\")\n</code></pre>\n\n<p>You use numpy only for reading a file, then convert back to standard python. This is a fail. Read with python directly.</p>\n\n<pre><code>with open(\"data.txt\") as infile:\n lines = infile.readlines()\npeople = [Person(*line.split()) for line in lines]\n</code></pre>\n\n<p>You need time for comparison only. There is no need to mess with it, string comparison will do.</p>\n\n<pre><code>self.time = time\n</code></pre>\n\n<p>Do not modify the people data but maintain a set of available projects</p>\n\n<pre><code>prio1_projects = set(p.prio1 for p in people)\nprio2_projects = set(p.prio2 for p in people)\nprojects_available = prio1_projects | prio2_projects\n</code></pre>\n\n<p>When assigning projects we do it like </p>\n\n<pre><code>people = sorted(people, key = lambda p: p.time)\nassignments = []\nfor p in people:\n if p.prio1 in projects_available:\n proj = p.prio1\n elif p.prio2 in projects_available:\n proj = p.prio2\n else:\n proj = None\n assignments.append(proj)\n if proj is not None:\n projects_available.remove(proj)\n</code></pre>\n\n<p>Note the new <code>None</code> case.</p>\n\n<p>The output code</p>\n\n<pre><code>with open(\"results\",\"w\") as res:\n res.write(\"Name\"+\"\\t\"+\"Assigned Project\"+\"\\n\")\n for p, a in zip(people, assignments):\n res.write(p.name + \"\\t\" + str(a) + \"\\n\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T00:46:09.060",
"Id": "405385",
"Score": "0",
"body": "First of all, thank you very much for the comments! I think I understand most of them, or at least see why one should do it the way you suggest, but there when you say \"Never loop over `range(len(something)`\", could you maybe explain why? Is this just a convention, or are there downsides to doing this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T12:07:03.523",
"Id": "405399",
"Score": "2",
"body": "@Sito It is considered pythonic. (Convention) The talk, \"loop like a native\" covers this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T12:19:47.693",
"Id": "405400",
"Score": "1",
"body": "@Sito: It has the advantage that you can usually directly use your code whether or not what you iterate over is a `list` (which is indexable, so `range(len(x))` would work), a `set` (where you cannot use an index, but at least `len(x)` still works) and a generator (which might be infinite so you don't even know `len(x)`). Doing `for x in foo` works for any iterable (by definition)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T14:34:37.950",
"Id": "405411",
"Score": "1",
"body": "@Graipher Touché. I'll update my answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:03:32.597",
"Id": "209739",
"ParentId": "209729",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209739",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T18:24:16.923",
"Id": "209729",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Assigning projects in order of priority"
} | 209729 |
<p>The end result of this is to allow a user to log in and/or register themselves for a dice game. Please post some suggestions for improvement.</p>
<pre><code>import pickle
logged_in = False
with open('users.pickle', 'rb') as a_file:
users = pickle.load(a_file)
login_or_signup = input('do you want to login or signup? ')
# sign up (creating new account)
if login_or_signup.lower() == "signup":
create_username = input("enter a new username: ")
create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")
if create_password in users:
create_password = input("password taken re-enter: ")
users[create_username] = create_password
username = input('please enter username: ')
if username in users:
password = input("enter password: ")
if password == users[username]:
print("access granted")
logged_in = True
else:
print("access denied")
with open("users.pickle", 'wb') as f:
pickle.dump(users, f, pickle.HIGHEST_PROTOCOL)
</code></pre>
| [] | [
{
"body": "<p>You are introducing this requirement of not having a password being the same as a username, but the problem is the way you check for it:</p>\n\n<pre><code>create_password = input(\"enter a new password (Your password cannot be the same as your username !!!!!!!): \")\n\nif create_password in users:\n</code></pre>\n\n<p>The problem arises when my password matches someone else's username.</p>\n\n<p>I think you meant to just compare <code>create_username</code> with <code>create_password</code> values.</p>\n\n<hr>\n\n<p>In general, there is rarely a case when you should try writing your own login system except that for learning purposes. You may though improve your current setup by introducing hashing of the passwords, to avoid storing them in plain text: <a href=\"https://stackoverflow.com/questions/9594125/salt-and-hash-a-password-in-python\">Salt and hash a password in python</a>; as well as more password strength requirements: <a href=\"https://stackoverflow.com/q/16709638/771848\">Checking the strength of a password</a>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T20:37:10.690",
"Id": "209736",
"ParentId": "209733",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T20:03:58.547",
"Id": "209733",
"Score": "1",
"Tags": [
"python"
],
"Title": "Dice game login system"
} | 209733 |
<p>This isn't so much, HOW do I make it work, as this code works, rather how could I make it better. The way this code works is it guides a person to the correct answer by getting "Yes", "No" or "I don't know" (in some cases from the person).</p>
<p>It's intended to run in HTML5/JavaScript (kind of like an online interactive guide). This code actually works, but it uses the JavaScript "prompt" for the input, and frankly, it's pretty ugly. Any suggestions on how to make it either look or work better?</p>
<p>First the JavaScript, as it's the main engine:</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>function mc1() {
var n = prompt("Do you have Medicare benefits (Y=Yes, N=No, I=I don't know)", " ");
if( n == "Y"){
mcs2();
}
else if (n="N"){
mcs1a();
}
else if (n="I"){
mcs1b();
}
else {
alert("Enter a valid choice Y,N or I!");
mc1();
}
}
function mcs1a(){
var n1=prompt("Have you applied and been denied Medicare Coverage (Y= Yes, N= No, I = I don't know)", "");
if (n1=="Y"){
mc3a();
}
else if (n1=="N"){
mc2b();
}
else if (n1=="I"){
mc2b();
}
else {
alert("Enter a valid choice: Y, N or I!");
}
}
function mcs1b(){
alert("Refer to Social Security Administration to check status, (CODE E01M1)!");
}
function mcs2(){
var n2=prompt("Do you have Medicare Part A AND B ( Y=Yes, N=No, I=I don't know)","");
if (n2=="Y"){
mcs3();
}
if (n2=="N"){
alert("Refer to Social Security to apply for the other part (Code E01M1)!");
}
if (n2=="I"){
alert("Refer to Social Security Administration to check status (Code E01M1)!");
}
else {
alert("Enter a valid choice: Y, N, or I!");
}
}
function mcs3(){
var n3=prompt("Would you like to apply for HF MEdicare (Y=Yes, N=No)","");
if (n3=="Y"){
mcs4a();
}
if (n3=="N"){
mcs4();
}
else {
alert("Enter a valid choice: Y or N!");
}
}
function mcs4(){
var n4=prompt("Do you have a caretaker relative who claims you on their taxes (Y=Yes, N=No)","");
if (n4=="Y"){
alert("Follow standard prequalification with caretaker relative as the income");
}
if (n4=="N"){
alert("Refer to the HRA/LDSS/SLDSS to apply for benefits (CODE E01H)");
}
else {
alert("Enter a valid choice: Y or N!");
}
}
function mcs4a(){
alert("Warm transfer to Medicare Advertising to apply for HealthFirst Medicare (Code WTS)");}
mc1();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head />
<body>
<script src="testdrop.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:46:04.430",
"Id": "405382",
"Score": "3",
"body": "\"message\": \"Uncaught ReferenceError: mc2b is not defined\","
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:20:46.617",
"Id": "405501",
"Score": "0",
"body": "`mc3a` is also undefined."
}
] | [
{
"body": "<p>Indent your code and watch the newlines and spacing. <br>\nThere is a difference between == and =, you use both in mc1(). <br>\nThe names of your functions are not explaining what the functions do. <br>\nYou might want to allow lowercase letters as input, this is a design choice. Your prompt specifies capitals, so it should suffice. <br>\nAs an interactive guide, HTML/JS buttons might be better, but that is more a question for <a href=\"https://ux.stackexchange.com/\">https://ux.stackexchange.com/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:53:54.743",
"Id": "209744",
"ParentId": "209740",
"Score": "0"
}
},
{
"body": "<h1>Bad names!!</h1>\n\n<ul>\n<li>Very poor naming, so much so that your code is almost unreadable and definitely unusable.</li>\n<li>Use constants for variables that do not change. eg <code>var n1=</code> should be <code>const n =</code></li>\n<li>Always! indent your code.</li>\n<li>Spaces between operators <code>var n1=prompt(</code> should be <code>var n1 = prompt(</code> </li>\n<li><code>else</code> on same line as closing <code>}</code> eg <code>} else if (</code></li>\n<li>Use <code>===</code> rather than <code>==</code> and <code>!==</code> rather than <code>!=</code></li>\n<li>The code is broken and throws errors because you have missing function calls. Next time you post on code review please make sure that the code works, or clearly mark code stubs.</li>\n<li>A lot of repeated code could be put together as a function.</li>\n</ul>\n\n<p>eg Ask question function</p>\n\n<pre><code>function askQuestion(message, yesCall, noCall, unsureCall) {\n const result = prompt(message, \"\").toLowerCase();\n if ( result === \"y\") { yesCall() }\n else if (result === \"n\") { noCall() }\n else if (result === \"i\") { unsureCall() }\n else { askQuestion(message, yesCall, noCall, unsureCall) }\n}\n</code></pre>\n\n<p>Then you can ask the question </p>\n\n<pre><code>function mcs1() {\n askQuestion(\n \"Do you have Medicare benefits (Y=Yes, N=No, I=I don't know)\",\n mcs2, mcs1a, mcs1b\n );\n}\n</code></pre>\n\n<h2>User friendly</h2>\n\n<p>When creating interfaces you should never have ask the user to correct themselves due to improper use of the interface. </p>\n\n<p>If you ask for a Y or N and you can not control the keys, don't respond with <code>\"Enter a valid choice Y,N or I!\"</code> as it is a pointless and frustrating step for the user. Just ask the question again. <code>\"Try again... Do you have Medicare benefits? Y/N\"</code> </p>\n\n<p>Best is to ensure that the user can only make correct selections.</p>\n\n<p>Use <code>String.toLowerCase()</code> or <code>String.toUpperCase()</code> to eliminate the need to differentiate between upper and lower case input.</p>\n\n<p>Use a dialog with clickable options, or vet the key inputs with a keyboard event listener (not available on prompt) </p>\n\n<h2>Alert and Prompt are evil</h2>\n\n<p>Don't use prompts or alerts. Use the HTML5 element dialog (or use standard HTML) and create custom dialogs. </p>\n\n<p>Custom dialogs are non blocking and let you control the inputs, style, and much more. Giving a much better feel and flow to the interrogation.</p>\n\n<p>See example how to use <code><dialog></code> element. (Note: full support for <code><dialog></code> element is only on Chrome for the moment. A <a href=\"https://github.com/GoogleChrome/dialog-polyfill\" rel=\"nofollow noreferrer\">polyfill</a> can be found on <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\" rel=\"nofollow noreferrer\">MDN dialog reference</a> page.)</p>\n\n<h2>Separate questions from code.</h2>\n\n<p>You have coded the questions into the source such that if you make a change to the questions you will need to make changes to the source code. </p>\n\n<p>These types of apps (survey or interrogations) are generally a class of finite state machine. The state (a question or message) will always follow a previous known state, and the following state will depend on the current answer. </p>\n\n<p>Seperate the state flow from the logic in such a way that you do not need to code the questions. You should be able to present any list of questions as a dataset (eg JSON) without needing to change any of the source code.</p>\n\n<p>If the data structure is well defined, it also allows for non coders to create and change the interrogation.</p>\n\n<h2>An example.</h2>\n\n<p>The example may be a little advanced but have a look anyways, take what you can and feel free to ask questions in the comments.</p>\n\n<ul>\n<li>It uses the dialog element to create the dialogs.</li>\n<li>Async functions and promises to wait for user input.</li>\n<li>Event listeners to get user clicks.</li>\n<li>Defines a state machine via the object <code>interrogation</code> that uses named properties to connect states. The function <code>interrogate</code> takes a state name and use it to determine how to present and act on that state.</li>\n</ul>\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>setTimeout(()=>interrogate(\"start\"),0);\n\n/* Structure of interrogation All names are case sensitive [] means optional\n name: { // state name\n [action]: string, // one of two actions \"reset\" or \"showResult\"\n [question]: string, // The question if included the must have Y,N and/or [I]\n [Y]: string // name of state for yes result\n [N]: string // name of state for no result\n [I]: string // name of state for unsure result\n [message]: string, // Message to display. This is only optional if question is defined\n [next]: string // name of next state. If omitted then defaults to \"exit\"\n }\n*/\n\nconst interrogation = {\n results: \"\",\n start: {\n action: \"reset\",\n question: \"Do you have Medicare benefits?\",\n Y: \"partsAB\",\n N: \"deniedMedicare\",\n I: \"refSocialSecurityAdministration\"\n },\n partsAB: {\n question: \"Do you have Medicare Part A AND B\",\n Y: \"applyForHF\",\n N: \"unknown\",\n I: \"unknown\" \n },\n applyForHF: {\n question: \"Would you like to apply for HF MEdicare\",\n Y: \"applyForHFInfo\",\n N: \"haveCaretaker\"\n },\n haveCaretaker: {\n question: \"Do you have a caretaker relative who claims you on their taxes\",\n Y: \"haveCaretakerInfo\",\n N: \"dontHaveCaretakerInfo\", \n },\n deniedMedicare: {\n question: \"Have you applied and been denied Medicare Coverage\",\n Y: \"unknown\",\n N: \"unknown\", \n }, \n startAgain: {\n question: \"Would you like to restart?\",\n Y: \"start\",\n N: \"exit\", \n },\n unknown: {\n message: \"Arrrghhhh. computer meltdown.. the pain, the pain... :P\",\n next: \"startAgain\",\n },\n refSocialSecurity: {\n message: \"Refer to Social Security to apply for the other part (Code E01M1)!\"\n },\n refSocialSecurityAdministration: {\n message: \"Refer to Social Security Administration to check status (Code E01M1)!\" \n },\n haveCaretakerInfo: {\n message: \"Follow standard prequalification with caretaker relative as the income.\"\n },\n dontHaveCaretakerInfo: {\n message: \"Refer to the HRA/LDSS/SLDSS to apply for benefits (CODE E01H)\",\n },\n applyForHFInfo: {\n message: \"Transfer to Medicare Advertising to apply for HealthFirst Medicare\"\n },\n exit: {\n action: \"showResult\",\n message: \"Thank you for your participation.\",\n },\n}\n\nasync function askQuestion(message, includeNotSure) {\n return new Promise(selectionMade => {\n quesionMenuEl.addEventListener(\"click\", event => {\n selectionMade(event.target.value);\n event.preventDefault(); // stops the dialog from permanently closing\n questionDialog.close();\n }, {once: true});\n questiomMessageEl.textContent = message;\n notSureButton.style.display = includeNotSure ? null : \"none\"; //null is default \n questionDialog.showModal();\n });\n}\nasync function showMessage(message) {\n return new Promise(selectionMade => {\n messageMenuEl.addEventListener(\"click\", event => {\n messageDialog.close();\n event.preventDefault(); // stops the dialog from permanently closing\n selectionMade(\"OK\");\n }, {once: true});\n messageMessageEl.textContent = message;\n messageDialog.showModal();\n });\n}\nfunction interrogate(stateName = \"exit\") {\n const state = interrogation[stateName];\n if(state.action === \"reset\") { interrogation.results = \"\" }\n else if(state.action === \"showResult\") { console.log(\"Result: \" + interrogation.results) }\n if (state.question) { \n askQuestion(state.question, state.I !== undefined)\n .then(result => {\n if (result !== undefined) {\n interrogation.results += result;\n interrogate(state[result]);\n } else {\n interrogate(stateName); // clicked outside button\n }\n }); \n } else if (state.message) {\n showMessage(state.message)\n .then(() => {\n if (stateName !== \"exit\") { interrogate(state.next) } \n });\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><dialog id=\"questionDialog\">\n <form method=\"dialog\">\n <p id = \"questiomMessageEl\"></p>\n <menu id=\"quesionMenuEl\">\n <button value=\"Y\">Yes</button>\n <button value=\"N\">No</button>\n <button value=\"I\" id=\"notSureButton\">Not sure</button>\n </menu>\n </form>\n</dialog>\n<dialog id=\"messageDialog\">\n <form method=\"dialog\">\n <p id=\"messageMessageEl\"></p>\n <menu id=\"messageMenuEl\">\n <button value=\"ok\">OK</button>\n </menu>\n </form>\n</dialog></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:58:28.847",
"Id": "405604",
"Score": "0",
"body": "Blindman67 Thank you. That answers the question that I was asking. Thank you !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T15:09:05.450",
"Id": "209765",
"ParentId": "209740",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209765",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:10:24.520",
"Id": "209740",
"Score": "0",
"Tags": [
"javascript",
"html5"
],
"Title": "Interactive multiple choice code"
} | 209740 |
<p>Similar to <a href="https://codereview.stackexchange.com/questions/12979/powerset-in-clojure">this question</a>, here's another implementation. Assume the input is already a set.</p>
<pre><code> (defn powerset
[set]
(reduce
(fn [xs x] (concat xs (map #(cons x %) xs)))
[()]
set))
</code></pre>
| [] | [
{
"body": "<p>There isn't a <em>whole</em> lot here to comment on. I'll just mention a few things:</p>\n\n<ul>\n<li><p><em>Technically</em>, from my quick search of what a powerset is, this function should return sets. That seems petty, but unless it's documented to return a lazy list of lazy lists, users may try to treat the \"subsets\" as sets (like using them as functions). I'd finish this function off by <code>map</code>ping <code>set</code> over the list.</p></li>\n<li><p>But to do that, you should rename your parameter, as you're shadowing the build-in <code>set</code>.</p></li>\n<li><p>After doing the above two, it developed quite long lines and became nested. I'd add in some use of <code>->></code>, and put a few of the lines on the next line.</p></li>\n</ul>\n\n<p>After that, I ended up with:</p>\n\n<pre><code>(defn powerset [base-set]\n (->> base-set\n (reduce\n (fn [xs x] \n (concat xs\n (map #(cons x %) xs)))\n [()])\n\n (map set)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T15:40:36.197",
"Id": "412623",
"Score": "0",
"body": "You can construct the sets directly. Replace `#(cons x %)` with `#(conj % x)` and `[()]` with `[#{}]`. Then you don't need the final `(map set)`. This works whatever kind of collection `base-set` is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T17:09:09.020",
"Id": "412632",
"Score": "0",
"body": "@Thumbnail You're right. I wrote this answer quickly on my phone on a train on the way to get my hair cut. I could have dug further. I think your suggestion merits a new answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T17:57:50.300",
"Id": "412644",
"Score": "0",
"body": "No. You take it. It's a detail. But it's still not quite right. If you supply a sequence with repeats, you get some identical subsets. I think the cure is to replace `[()]` with `[(empty base-set)]`. What it produces from a sequence may not be the traditional idea of a powerset, but at least all the elements of the answer are different. Alternatively, you could start with `(set base-set)`, a trivial operation compared with what's to come."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T23:23:25.077",
"Id": "209746",
"ParentId": "209743",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:42:41.720",
"Id": "209743",
"Score": "2",
"Tags": [
"clojure",
"set"
],
"Title": "Powerset of collection in Clojure"
} | 209743 |
<p>I am attempting to, given two dimensions (width and height) which represent a quadrilateral, partition that quad in to <code>N</code> parts where each part is as proportionally similar to the other as possible.</p>
<p>For example, imagine a sheet of paper. It consists of 4 points <code>A</code>, <code>B</code>, <code>C</code>, <code>D</code>. Now consider that the sheet of paper has the dimensions 800 x 800 and the points:</p>
<pre><code>A: {0, 0}
B: {0, 800}
C: {800, 800}
D: {800, 0}
</code></pre>
<p>Plotting that will give you 4 points, or 3 lines with a line plot. Add an additional point <code>E: {0, 0}</code> to close the cell.</p>
<p>To my surprise, I've managed to do this programatically, for <code>N</code> number of cells.</p>
<p>How can I improve this code to make it more readable, pythonic, and as performant as possible?</p>
<pre><code>from math import floor, ceil
import matplotlib.pyplot as plt
class QuadPartitioner:
@staticmethod
def get_factors(number):
'''
Takes a number and returns a list of factors
:param number: The number for which to find the factors
:return: a list of factors for the given number
'''
facts = []
for i in range(1, number + 1):
if number % i == 0:
facts.append(i)
return facts
@staticmethod
def get_partitions(N, quad_width, quad_height):
'''
Given a width and height, partition the area into N parts
:param N: The number of partitions to generate
:param quad_width: The width of the quadrilateral
:param quad_height: The height of the quadrilateral
:return: a list of a list of cells where each cell is defined as a list of 5 verticies
'''
# We reverse only because my brain feels more comfortable looking at a grid in this way
factors = list(reversed(QuadPartitioner.get_factors(N)))
# We need to find the middle of the factors so that we get cells
# with as close to equal width and heights as possible
factor_count = len(factors)
# If even number of factors, we can partition both horizontally and vertically.
# If not even, we can only partition on the X axis
if factor_count % 2 == 0:
split = int(factor_count/2)
factors = factors[split-1:split+1]
else:
factors = []
split = ceil(factor_count/2)
factors.append(split)
factors.append(split)
# The width and height of an individual cell
cell_width = quad_width / factors[0]
cell_height = quad_height / factors[1]
number_of_cells_in_a_row = factors[0]
rows = factors[1]
row_of_cells = []
# We build just a single row of cells
# then for each additional row, we just duplicate this row and offset the cells
for n in range(0, number_of_cells_in_a_row):
cell_points = []
for i in range(0, 5):
cell_y = 0
cell_x = n * cell_width
if i == 2 or i == 3:
cell_x = n * cell_width + cell_width
if i == 1 or i == 2:
cell_y = cell_height
cell_points.append((cell_x, cell_y))
row_of_cells.append(cell_points)
rows_of_cells = [row_of_cells]
# With that 1 row of cells constructed, we can simply duplicate it and offset it
# by the height of a cell multiplied by the row number
for index in range(1, rows):
new_row_of_cells = [[ (point[0],point[1]+cell_height*index) for point in square] for square in row_of_cells]
rows_of_cells.append(new_row_of_cells)
return rows_of_cells
if __name__ == "__main__":
QP = QuadPartitioner()
partitions = QP.get_partitions(56, 1980,1080)
for row_of_cells in partitions:
for cell in row_of_cells:
x, y = zip(*cell)
plt.plot(x, y, marker='o')
plt.show()
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/sv6yD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sv6yD.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<p>First, there is no need for this to be a class at all. Your class has only two static methods, so they might as well be stand-alone functions. In this regard Python is different from e.g. Java, where everything is supposed to be a class.</p>\n\n<hr>\n\n<p>Your <code>get_factors</code> function can be sped-up significantly by recognizing that if <code>k</code> is a factor of <code>n</code>, then so is <code>l = n / k</code>. This also means you can stop looking for factors once you reach <span class=\"math-container\">\\$\\sqrt{n}\\$</span>, because if it is a square number, this will be the largest factor not yet checked (and otherwise it is an upper bound). I also used a <code>set</code> instead of a <code>list</code> here so adding a factor multiple times does not matter (only relevant for square numbers, again).</p>\n\n<pre><code>from math import sqrt\n\ndef get_factors(n):\n '''\n Takes a number and returns a list of factors\n :param number: The number for which to find the factors\n :return: a list of factors for the given number\n '''\n factors = set()\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n factors.add(i)\n factors.add(n // i)\n return list(sorted(factors)) # sorted might be unnecessary\n</code></pre>\n\n<p>As said, this is significantly faster than your implementation, although this only starts to be relevant for about <span class=\"math-container\">\\$n > 10\\$</span>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/yy9A1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yy9A1.png\" alt=\"enter image description here\"></a></p>\n\n<p>(Note the log scale on both axis.)</p>\n\n<hr>\n\n<p>As for your main function:</p>\n\n<p>First figure out how many rows and columns you will have. For this I would choose the factor that is closest to <span class=\"math-container\">\\$\\sqrt{n}\\$</span>:</p>\n\n<pre><code>k = min(factors, key=lambda x: abs(sqrt(n) - x))\nrows, cols = sorted([k, n //k]) # have more columns than rows\n</code></pre>\n\n<p>Then you can use <code>numpy.arange</code> to get the x- and y-coordinates of the grid:</p>\n\n<pre><code>x = np.arange(0, quad_width + 1, quad_width / cols)\ny = np.arange(0, quad_height + 1, quad_height / rows)\n</code></pre>\n\n<p>From this you now just have to construct the cells:</p>\n\n<pre><code>def get_cells(x, y):\n for x1, x2 in zip(x, x[1:]):\n for y1, y2 in zip(y, y[1:]):\n yield [x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1]\n</code></pre>\n\n<p>Putting all of this together:</p>\n\n<pre><code>import numpy as np\n\ndef get_partitions(n, width, height):\n factors = get_factors(n)\n k = min(factors, key=lambda x: abs(sqrt(n) - x))\n rows, cols = sorted([k, n //k]) # have more columns than rows\n\n x = np.arange(0, width + 1, width / cols)\n y = np.arange(0, height + 1, height / rows)\n\n yield from get_cells(x, y)\n\nif __name__ == \"__main__\":\n for cell in get_partitions(56, 1980, 1080):\n plt.plot(*cell, marker='o')\n plt.show()\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/xmGj4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xmGj4.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T12:44:49.917",
"Id": "209761",
"ParentId": "209745",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T22:55:18.140",
"Id": "209745",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Given 4 vertices representing a quadrilateral, divide it into N parts"
} | 209745 |
<p>This is my quicksort<br>
There are many like it but<br>
This quicksort is mine.</p>
<p>So, quicksort, in C, with a big framework to test it six ways from Sunday. Passed the tests nicely, but there may be warts, or subtle mistakes I didn’t think of, or code that’s hard to follow, or just better ways to do things. Have at it.</p>
<p>EDIT: Forgot another issue: I’m not handling memory allocation errors gracefully in this code. Suggestions on how professional-level production code might handle them are welcome. I’m thinking that functions using <code>malloc()</code> should return a value to be checked, and set <code>errno</code> to <code>ENOMEM</code>.</p>
<p>My quicksort implementation is somewhat slower than the library function; that’s only to be expected; library code is optimized and I don’t try to pick a good pivot with median-of-3 or such. No need to critique that, I wanted to keep it simple.</p>
<pre><code>/* Quicksort implementation and testing framework */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 0: use qsort correctly, to test the rest of the framework
* 1: mess up the sort sometimes, to test if sorting errors are caught
* 2: mess up the sentinels sometimes, to test if sentinel errors are
* caught
* 3: use my quicksort implementation, to test it */
#define TEST_TYPE 3
/* Stop testing after this many errors */
#define MAX_ERRORS 6
/* Set to 1 to print all pre-sort permutations */
#define VERBOSE 0
/* Max array length to test; more than 12 will take a long time */
#define MAXARRAY 10
/* Size of array for run_big_test() */
#define BIGTEST_SIZE 2000
/* Sentinels to detect buffer overruns */
#define SENTINEL_LEFT 111
#define SENTINEL_RIGHT -222
/* Used to count errors globally */
int err_ct = 0;
void run_tests(size_t N);
void run_big_test(void);
int error_check(size_t N, int *sorted);
void print_error(size_t N, int *to_sort, int *sorted);
void print_array(size_t len, int *arr);
int next_perm(int n, int *dest);
int cmp_int(const void *a, const void *b);
void quicksort(void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *));
void swap(void *a, void *b, size_t size);
void memquit(void);
int main(void)
{
size_t len;
srand(42);
for (len = 0; len <= MAXARRAY; ++len)
run_tests(len);
run_big_test();
return EXIT_SUCCESS;
}
void run_tests(size_t N)
{
/* Tests:
* 1. Sort all permutations of N distinct numbers.
* 2. Sort all permutations of N numbers with some repeated.
* 3. Sort an array of N numbers that are all the same (may catch
* infinite loops or recursion).
*/
int distinct[MAXARRAY];
int repeats[MAXARRAY] = {0, 0, 1, 2, 3, 3, 3, 4};
int perm[MAXARRAY];
int to_sort[MAXARRAY];
int sorted[MAXARRAY + 2];
int *dataset[2];
int i;
int test;
int retval;
if (N > MAXARRAY) {
fprintf(stderr, "run_tests(%lu) exceeds max array size.\n", N);
exit(EXIT_FAILURE);
}
for (i = 0; i < (int) N; ++i)
distinct[i] = i;
for (i = 2; i < (int) N; ++i)
if (repeats[i] == 0)
repeats[i] = 5;
dataset[0] = distinct;
dataset[1] = repeats;
for (test = 0; test < 2; ++test) {
while ((retval = next_perm((int) N, perm)) == 1) {
for (i = 0; i < (int) N; ++i)
to_sort[i] = dataset[test][perm[i]];
#if VERBOSE
print_array(N, to_sort);
putchar('\n');
#endif
sorted[0] = SENTINEL_LEFT;
memcpy(sorted + 1, to_sort, N * sizeof(int));
sorted[N + 1] = SENTINEL_RIGHT;
quicksort(sorted + 1, (size_t) N, sizeof(int), cmp_int);
if (error_check(N, sorted))
print_error(N, to_sort, sorted);
}
if (retval == -1)
memquit();
}
for (i = 0; i < (int) N; ++i)
to_sort[i] = 6;
#if VERBOSE
print_array(N, to_sort);
putchar('\n');
#endif
sorted[0] = SENTINEL_LEFT;
memcpy(sorted + 1, to_sort, N * sizeof(int));
sorted[N + 1] = SENTINEL_RIGHT;
quicksort(sorted + 1, (size_t) N, sizeof(int), cmp_int);
if (sorted[0] != SENTINEL_LEFT ||
sorted[N + 1] != SENTINEL_RIGHT ||
memcmp(sorted + 1, to_sort, N * sizeof(int)))
print_error(N, to_sort, sorted);
}
void run_big_test(void)
{
/* Create a long array of random numbers, sort it, check
* correctness. */
int *to_sort;
int *sorted;
int i;
to_sort = malloc(BIGTEST_SIZE * sizeof(int));
sorted = malloc((BIGTEST_SIZE + 2) * sizeof(int));
if (!to_sort || !sorted)
memquit();
for (i = 0; i < BIGTEST_SIZE; ++i)
to_sort[i] = rand() % (BIGTEST_SIZE * 4);
#if VERBOSE
print_array(BIGTEST_SIZE, to_sort);
putchar('\n');
#endif
sorted[0] = SENTINEL_LEFT;
memcpy(sorted + 1, to_sort, BIGTEST_SIZE * sizeof(int));
sorted[BIGTEST_SIZE + 1] = SENTINEL_RIGHT;
quicksort(sorted + 1, BIGTEST_SIZE, sizeof(int), cmp_int);
if (error_check(BIGTEST_SIZE, sorted))
print_error(BIGTEST_SIZE, to_sort, sorted);
}
int error_check(size_t N, int *sorted)
{
/* Check sentinels, check that sorted part is non-decreasing */
size_t i;
if (sorted[0] != SENTINEL_LEFT ||
sorted[N + 1] != SENTINEL_RIGHT)
return 1;
for (i = 2; i <= N; ++i)
if (sorted[i] < sorted[i - 1])
return 1;
return 0;
}
void print_error(size_t N, int *to_sort, int *sorted)
{
/* Print pre-sort and post-sort arrays to show where error occurred.
* Quit if MAX_ERRORS was reached. */
printf("Error: ");
print_array(N, to_sort);
printf(" -> ");
print_array(N + 2, sorted);
putchar('\n');
if (++err_ct >= MAX_ERRORS)
exit(EXIT_FAILURE);
}
void print_array(size_t len, int *arr)
{
/* Pretty-print array. No newline at end. */
char *sep = "";
size_t i;
putchar('(');
for (i = 0; i < len; ++i) {
printf("%s%d", sep, arr[i]);
sep = ", ";
}
putchar(')');
}
int next_perm(int passed_n, int *dest)
{
/* Generate permutations of [0, n) in lexicographic order.
*
* First call: Set up, generate first permutation, return 1.
*
* Subsequent calls: If possible, generate next permutation and
* return 1. If all permutations have been returned, clean up and
* return 0. "First call" status is reset and another series may be
* generated.
*
* Return -1 to indicate a memory allocation failure.
*
* Caller may alter the values in `dest` freely between calls, and
* may pass a different `dest` address each time. `n` is ignored
* after the first call.
*
* The function maintains static data; it can only keep track of one
* series of permutations at a time. */
static int *perm;
static int new_series = 1;
static int n;
int i, j;
if (new_series) {
/* Set up first permutation, return it. */
new_series = 0;
n = passed_n;
if ((perm = malloc((size_t) n * sizeof(int))) == NULL)
return -1;
for (i = 0; i < n; ++i)
perm[i] = dest[i] = i;
return 1;
}
/* Generate and return next permutation. First, find longest
* descending run on right. */
i = n - 2;
while (i >= 0 && perm[i] > perm[i+1])
--i;
/* If all of perm is descending, the previous call returned the last
* permutation. */
if (i < 0) {
free(perm);
new_series = 1;
return 0;
}
/* Find smallest value > perm[i] in descending run. */
j = n - 1;
while (perm[j] < perm[i])
--j;
/* Swap [i] and [j]; run will still be descending. */
perm[i] ^= perm[j];
perm[j] ^= perm[i];
perm[i] ^= perm[j];
/* Reverse the run, and we're done. */
for (++i, j = n - 1; i < j; ++i, --j) {
perm[i] ^= perm[j];
perm[j] ^= perm[i];
perm[i] ^= perm[j];
}
for (i = 0; i < n; ++i)
dest[i] = perm[i];
return 1;
}
int cmp_int(const void *a, const void *b)
{
/* Compatible with qsort. a and b are treated as pointers to int.
* Return value is:
* < 0 if *a < *b
* > 0 if *a > *b
* 0 if *a == *b
*/
const int *aa = a;
const int *bb = b;
return *aa - *bb;
}
#if TEST_TYPE == 0
/* Use qsort(3), correctly */
void quicksort(void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *))
{
qsort(base, nmemb, size, cmp);
}
#endif
#if TEST_TYPE == 1
/* Mess up the sort with probability 1/256 */
void quicksort(void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *))
{
int *ibase = base;
qsort(base, nmemb, size, cmp);
if (rand() % 256 == 0) {
ibase[0] ^= ibase[nmemb - 1];
ibase[nmemb - 1] ^= ibase[0];
ibase[0] ^= ibase[nmemb - 1];
}
}
#endif
#if TEST_TYPE == 2
/* Mess up one of the sentinels with probability 1/256 */
void quicksort(void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *))
{
int *ibase = base;
int i;
qsort(base, nmemb, size, cmp);
if (rand() % 256 == 0) {
i = (rand() % 2) ? -1 : (int) nmemb;
ibase[i] = 42;
}
}
#endif
#if TEST_TYPE == 3
/* Use my implementation */
void quicksort(void *base, size_t nmemb, size_t size,
int (*cmp)(const void *, const void *))
{
/* Sort array with quicksort algorithm. Pivot is always leftmost
* element. */
char *cbase = base;
char *p, *q;
if (nmemb < 2)
return;
/* p at element 1, just past pivot */
p = cbase + size;
/* q at last element */
q = cbase + (nmemb - 1) * size;
while (p <= q) {
/* Move p right until *p >= pivot */
while (p <= q && cmp(p, base) < 0)
p += size;
/* Move q left until *q < pivot */
while (p <= q && cmp(q, base) >= 0)
q -= size;
if (p < q)
swap(p, q, size);
}
/* After partitioning:
* Pivot is element 0
* p = q + 1 (in terms of elements)
* Case 1: some elements < pivot, some >= pivot
* =<<<<>>>> q is rightmost <, p is leftmost >
* Case 2: all elements < pivot
* =<<<<<<<< q is rightmost <, p is one past end
* Case 3: all elements >= pivot
* =>>>>>>>> q is =, p is leftmost >
*
* If not case 3:
* Swap pivot with q
* Recurse on 0 to q - 1
* Recurse on p to nmemb - 1
*
* Pivot is left out of both recursive calls, so size is always
* reduced by at least one and infinite recursion cannot occur.
*/
if (q != cbase) {
swap(base, q, size);
quicksort(base, (size_t) (q - cbase) / size, size, cmp);
}
quicksort(p, nmemb - (size_t) (p - cbase) / size, size, cmp);
}
#endif
void swap(void *a, void *b, size_t size)
{
static size_t bufsize = 0;
static char *buf = NULL;
if (size != bufsize) {
bufsize = size;
buf = realloc(buf, bufsize);
if (!buf)
memquit();
}
memcpy(buf, a, size);
memcpy(a, b, size);
memcpy(b, buf, size);
}
void memquit(void)
{
fprintf(stderr, "Memory allocation failure\n");
exit(EXIT_FAILURE);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T11:13:39.250",
"Id": "406409",
"Score": "0",
"body": "Oh yay, I won a Tumbleweed! :p"
}
] | [
{
"body": "<pre><code>#define TEST_TYPE 3\n</code></pre>\n\n<p>It would be more informative to represent this as an <code>enum</code>, with meaningfully named entries for your four test types.</p>\n\n<pre><code>/* Set to 1 to print all pre-sort permutations */\n#define VERBOSE 0\n</code></pre>\n\n<p>No reason not to represent this as an actual boolean using <code><stdbool.h></code>.</p>\n\n<p>Since it seems like this is the only translation unit in your project, you should set all of your functions to be <code>static</code>.</p>\n\n<p>Don't pre-declare your variables at the beginning of a function; this hasn't been needed for about 20 years. e.g. rewrite your <code>main</code> loop as:</p>\n\n<pre><code>for (size_t len = 0; len <= MAXARRAY; len++)\n</code></pre>\n\n<p>This <em>especially</em> applies to functions like <code>run_tests</code>, with a big pile of variables at the beginning.</p>\n\n<p>In <code>run_big_test</code>, you should be <code>free</code>ing <code>to_sort</code> and <code>sorted</code> after you're done with them.</p>\n\n<p>This:</p>\n\n<pre><code>i = n - 2;\nwhile (i >= 0 && perm[i] > perm[i+1])\n --i;\n</code></pre>\n\n<p>is better represented as a <code>for</code> loop:</p>\n\n<pre><code>for (int i = n-2; i >= 0; i--) \n if (perm[i] <= perm[i+1])\n break;\n</code></pre>\n\n<p>I suggest that you factor out your XOR swap into a function. The compiler will be smart enough to inline it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T23:22:27.457",
"Id": "406967",
"Score": "0",
"body": "Thanks for all of this. Regarding pre-declarations, I’ve been using `-ansi` with `gcc` to force me to write maximally-compatible C code. Is that not really an issue these days?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T23:23:26.230",
"Id": "406968",
"Score": "0",
"body": "You really should assume everyone has C99 or newer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T22:40:52.773",
"Id": "210527",
"ParentId": "209749",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210527",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T00:17:32.793",
"Id": "209749",
"Score": "1",
"Tags": [
"c",
"unit-testing",
"reinventing-the-wheel",
"error-handling",
"quick-sort"
],
"Title": "Quicksort in C with unit testing framework"
} | 209749 |
<h2>Goal of the program</h2>
<p>The goal of the program is to translate a nucleic acid sequence into its corresponding amino acid sequence. The nucleic sequences
have to be formatted in a specific format called <a href="https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp" rel="noreferrer"><code>fasta</code></a>. There is an existing implementation of this program in C here: <a href="http://emboss.sourceforge.net/apps/cvs/emboss/apps/transeq.html" rel="noreferrer">emboss transeq</a></p>
<h3>Fasta format</h3>
<p>A fasta file looks like this: </p>
<pre><code>>sequenceId comment
nucleic sequence
</code></pre>
<p>for example: </p>
<pre><code>>Seq1 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
CCTTTATCTAATCTTTGGAGCATGAGCTGGCATAGTTGGAACCGCCCTCAGCCTCCTCATCCGTGCAGAA
CCCAGTCCTGTACCAACACCTCTTCTGATTCTTCGGCCATCCAGAAGTCTATATCCTCATTTTAC
>Seq2 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
GGTAGGTACCGCCCTAAGNCTCCTAATCCGAGCAGAACTANGCCAACCCGGAGCCCTTCTGGGAGACGAC
AATCAACATAAAA
</code></pre>
<p>A nucleic sequence is a string composed of the letters <code>A</code>, <code>C</code>, <code>T</code>, <code>G</code>, <code>U</code>, <code>N</code></p>
<h3>Expected output</h3>
<p>A combinaison of <strong>3 nucleic acid</strong>, named codon, gives a specif amino acid, for exemple <code>GCT</code> is the code for <a href="https://en.wikipedia.org/wiki/Alanine" rel="noreferrer"><code>Alanine</code></a>, symbolised by the letter <code>A</code></p>
<p>With the Seq1 define above: </p>
<pre><code>codon CCT TTA TCT AAT CTT TGG AGC ATG ...
amino acid P L S N L W S M ...
</code></pre>
<p>The expected output is: </p>
<pre><code>>Seq1_1 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
PLSNLWSMSWHSWNRPQPPHPCRTQSCTNTSSDSSAIQKSISSFY
>Seq2_1 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
GRYRPKXPNPSRTXPTRSPSGRRQST*X
</code></pre>
<h3>Specific rules</h3>
<p>The program takes 4 parameters: </p>
<ul>
<li><code>clean</code> : if true, write STOP codon as <code>X</code> instead of <code>*</code></li>
<li><code>trim</code> : if true, remove all <code>X</code> and <code>*</code> chars from the right end of the amino - acid sequence</li>
<li><code>alternative</code>: different way to compute reverse frame </li>
<li><code>frame</code>: a string value in <code>["1", "2", "3", "F", "-1", "-2", "-3", "R", "6" ]</code></li>
</ul>
<p>The frame define the position in the nucleic sequence to start from: </p>
<pre><code>-frame 1
|-frame 2
||-frame 3
|||
CCTTTATCTAATCTTTGGAGCATGAGCTGGCATAGTTGGAACCGCCCTCAGCCTCCTCATCCGTGCAGAA
CCCAGTCCTGTACCAACACCTCTTCTGATTCTTCGGCCATCCAGAAGTCTATATCCTCATTTTAC
|||
||-frame -1
|-frame -2
-frame -3
frame "F" = "1", "2", "3"
frame "R" = "-1", "-2", "-3"
frame "6" = "1", "2", "3", "-1", "-2", "-3"
</code></pre>
<p>In the output file, we add the frame used to the sequenceId: <code>sequenceId = sequenceId_frame</code></p>
<p>For example if the program is used with <code>frame=6</code>, the expected output is</p>
<pre><code>>Seq1_1 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
PLSNLWSMSWHSWNRPQPPHPCRTQSCTNTSSDSSAIQKSISSFY
>Seq1_2 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
LYLIFGA*AGIVGTALSLLIRAEPSPVPTPLLILRPSRSLYPHFT
>Seq1_3 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
FI*SLEHELA*LEPPSASSSVQNPVLYQHLF*FFGHPEVYILILX
>Seq1_4 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
VK*GYRLLDGRRIRRGVGTGLGSARMRRLRAVPTMPAHAPKIR*R
>Seq1_5 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
KMRI*TSGWPKNQKRCWYRTGFCTDEEAEGGSNYASSCSKD*IKX
>Seq1_6 [organism=Carpodacus mexicanus] [clone=6b] actin (act) mRNA, partial cds
*NEDIDFWMAEESEEVLVQDWVLHG*GG*GRFQLCQLMLQRLDKG
>Seq2_1 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
GRYRPKXPNPSRTXPTRSPSGRRQST*X
>Seq2_2 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
VGTALXLLIRAELXQPGALLGDDNQHKX
>Seq2_3 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
*VPP*XS*SEQNXANPEPFWETTINIK
>Seq2_4 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
LC*LSSPRRAPGWXSSARIRXLRAVPT
>Seq2_5 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
FMLIVVSQKGSGLA*FCSD*EX*GGTYX
>Seq2_6 [organism=uncultured bacillus sp.] [isolate=A2] corticotropin (CT) gene
FYVDCRLPEGLRVGXVLLGLGXLGRYLP
</code></pre>
<h2>Improvements</h2>
<ul>
<li>Performance improvements </li>
<li>Is the code easy to read / understand ? </li>
<li>Is the code idiomatic ? </li>
</ul>
<p>( full project with tests + flags handling is avaible on github: <a href="https://github.com/feliixx/gotranseq" rel="noreferrer">gotranseq</a>)</p>
<p><strong>code :</strong></p>
<pre><code>package transeq
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"runtime"
"sync"
)
var (
letterCode = map[byte]uint8{
'A': aCode,
'C': cCode,
'T': tCode,
'G': gCode,
'N': nCode,
'U': uCode,
}
standard = map[string]byte{
"TTT": 'F',
"TCT": 'S',
"TAT": 'Y',
"TGT": 'C',
"TTC": 'F',
"TCC": 'S',
"TAC": 'Y',
"TGC": 'C',
"TTA": 'L',
"TCA": 'S',
"TAA": '*',
"TGA": '*',
"TTG": 'L',
"TCG": 'S',
"TAG": '*',
"TGG": 'W',
"CTT": 'L',
"CCT": 'P',
"CAT": 'H',
"CGT": 'R',
"CTC": 'L',
"CCC": 'P',
"CAC": 'H',
"CGC": 'R',
"CTA": 'L',
"CCA": 'P',
"CAA": 'Q',
"CGA": 'R',
"CTG": 'L',
"CCG": 'P',
"CAG": 'Q',
"CGG": 'R',
"ATT": 'I',
"ACT": 'T',
"AAT": 'N',
"AGT": 'S',
"ATC": 'I',
"ACC": 'T',
"AAC": 'N',
"AGC": 'S',
"ATA": 'I',
"ACA": 'T',
"AAA": 'K',
"AGA": 'R',
"ATG": 'M',
"ACG": 'T',
"AAG": 'K',
"AGG": 'R',
"GTT": 'V',
"GCT": 'A',
"GAT": 'D',
"GGT": 'G',
"GTC": 'V',
"GCC": 'A',
"GAC": 'D',
"GGC": 'G',
"GTA": 'V',
"GCA": 'A',
"GAA": 'E',
"GGA": 'G',
"GTG": 'V',
"GCG": 'A',
"GAG": 'E',
"GGG": 'G',
}
)
const (
nCode = uint8(0)
aCode = uint8(1)
cCode = uint8(2)
tCode = uint8(3)
uCode = uint8(3)
gCode = uint8(4)
stopByte = '*'
unknown = 'X'
// Length of the array to store code/bytes
// uses gCode because it's the biggest uint8 of all codes
arrayCodeSize = (uint32(gCode) | uint32(gCode)<<8 | uint32(gCode)<<16) + 1
)
func createCodeArray(clean bool) []byte {
resultMap := map[uint32]byte{}
twoLetterMap := map[string][]byte{}
tmpCode := make([]uint8, 4)
for codon, aaCode := range standard {
// generate 3 letter code
for i := 0; i < 3; i++ {
tmpCode[i] = letterCode[codon[i]]
}
// each codon is represented by an unique uint32:
// each possible nucleotide is represented by an uint8 (255 possibility)
// the three first bytes are the the code for each nucleotide
// last byte is unused ( eq to uint8(0) )
// example:
// codon 'ACG' ==> uint32(aCode) | uint32(cCode)<<8 | uint32(gCode)<<16
uint32Code := uint32(tmpCode[0]) | uint32(tmpCode[1])<<8 | uint32(tmpCode[2])<<16
resultMap[uint32Code] = aaCode
// generate 2 letter code
codes, ok := twoLetterMap[codon[0:2]]
if !ok {
twoLetterMap[codon[0:2]] = []byte{aaCode}
} else {
twoLetterMap[codon[0:2]] = append(codes, aaCode)
}
}
for twoLetterCodon, codes := range twoLetterMap {
uniqueAA := true
for i := 0; i < len(codes); i++ {
if codes[i] != codes[0] {
uniqueAA = false
}
}
if uniqueAA {
first := letterCode[twoLetterCodon[0]]
second := letterCode[twoLetterCodon[1]]
uint32Code := uint32(first) | uint32(second)<<8
resultMap[uint32Code] = codes[0]
}
}
// if clean is specified, we want to replace all '*' by 'X' in the output
// sequence, so replace all occurrences of '*' directly in the ref map
if clean {
for k, v := range resultMap {
if v == stopByte {
resultMap[k] = unknown
}
}
}
r := make([]byte, arrayCodeSize)
for k, v := range resultMap {
r[k] = v
}
return r
}
func computeFrames(frameName string) (frames []int, reverse bool, err error) {
frames = make([]int, 6)
reverse = false
switch frameName {
case "1":
frames[0] = 1
case "2":
frames[1] = 1
case "3":
frames[2] = 1
case "F":
for i := 0; i < 3; i++ {
frames[i] = 1
}
case "-1":
frames[3] = 1
reverse = true
case "-2":
frames[4] = 1
reverse = true
case "-3":
frames[5] = 1
reverse = true
case "R":
for i := 3; i < 6; i++ {
frames[i] = 1
}
reverse = true
case "6":
for i := range frames {
frames[i] = 1
}
reverse = true
default:
err = fmt.Errorf("wrong value for -f | --frame parameter: %s", frameName)
}
return frames, reverse, err
}
type writer struct {
buf *bytes.Buffer
currentLineLen int
bytesToTrim int
}
func (w *writer) addByte(b byte) {
w.buf.WriteByte(b)
w.currentLineLen++
if b == stopByte || b == unknown {
w.bytesToTrim++
} else {
w.bytesToTrim = 0
}
}
func (w *writer) addUnknown() {
w.buf.WriteByte(unknown)
w.currentLineLen++
w.bytesToTrim++
}
func (w *writer) newLine() {
w.buf.WriteByte('\n')
w.currentLineLen = 0
w.bytesToTrim++
}
const (
// size of the buffer for writing to file
maxBufferSize = 1024 * 1024 * 30
// max line size for sequence
maxLineSize = 60
// suffixes ta add to sequence id for each frame
suffixes = "123456"
)
// Translate read a fata file, translate each sequence to the corresponding prot sequence in the specified frame
func Translate(inputSequence io.Reader, out io.Writer, frame string, clean, trim, alternative bool) error {
arrayCode := createCodeArray(clean)
framesToGenerate, reverse, err := computeFrames(frame)
if err != nil {
return err
}
fnaSequences := make(chan encodedSequence, 10)
errs := make(chan error, 1)
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for nWorker := 0; nWorker < runtime.NumCPU(); nWorker++ {
wg.Add(1)
go func() {
defer wg.Done()
startPosition := make([]int, 3)
w := &writer{
buf: bytes.NewBuffer(nil),
bytesToTrim: 0,
currentLineLen: 0,
}
for sequence := range fnaSequences {
select {
case <-ctx.Done():
return
default:
}
frameIndex := 0
startPosition[0], startPosition[1], startPosition[2] = 0, 1, 2
idSize := int(binary.LittleEndian.Uint32(sequence[0:4]))
nuclSeqLength := len(sequence) - idSize
Translate:
for _, startPos := range startPosition {
if framesToGenerate[frameIndex] == 0 {
frameIndex++
continue
}
// sequence id should look like
// >sequenceID_<frame> comment
idEnd := bytes.IndexByte(sequence[4:idSize], ' ')
if idEnd != -1 {
w.buf.Write(sequence[4 : 4+idEnd])
w.buf.WriteByte('_')
w.buf.WriteByte(suffixes[frameIndex])
w.buf.Write(sequence[4+idEnd : idSize])
} else {
w.buf.Write(sequence[4:idSize])
w.buf.WriteByte('_')
w.buf.WriteByte(suffixes[frameIndex])
}
w.newLine()
// if in trim mode, nb of bytes to trim (nb of successive 'X', '*' and '\n'
// from right end of the sequence)
w.bytesToTrim = 0
w.currentLineLen = 0
// read the sequence 3 letters at a time, starting at a specific position
// corresponding to the frame
for pos := startPos + 2 + idSize; pos < len(sequence); pos += 3 {
if w.currentLineLen == maxLineSize {
w.newLine()
}
// create an uint32 from the codon, to retrieve the corresponding
// AA from the map
codonCode := uint32(sequence[pos-2]) | uint32(sequence[pos-1])<<8 | uint32(sequence[pos])<<16
b := arrayCode[codonCode]
if b != byte(0) {
w.addByte(b)
} else {
w.addUnknown()
}
}
// the last codon is only 2 nucleotid long, try to guess
// the corresponding AA
if (nuclSeqLength-startPos)%3 == 2 {
if w.currentLineLen == maxLineSize {
w.newLine()
}
codonCode := uint32(sequence[len(sequence)-2]) | uint32(sequence[len(sequence)-1])<<8
b := arrayCode[codonCode]
if b != byte(0) {
w.addByte(b)
} else {
w.addUnknown()
}
}
// the last codon is only 1 nucleotid long, no way to guess
// the corresponding AA
if (nuclSeqLength-startPos)%3 == 1 {
if w.currentLineLen == maxLineSize {
w.newLine()
}
w.addUnknown()
}
if trim && w.bytesToTrim > 0 {
// remove the last bytesToTrim bytes of the buffer
// as they are 'X', '*' or '\n'
w.buf.Truncate(w.buf.Len() - w.bytesToTrim)
w.currentLineLen -= w.bytesToTrim
}
if w.currentLineLen != 0 {
w.newLine()
}
frameIndex++
}
if reverse && frameIndex < 6 {
// get the complementary sequence.
// Basically, switch
// A <-> T
// C <-> G
// N is not modified
for i, n := range sequence[idSize:] {
switch n {
case aCode:
sequence[i+idSize] = tCode
case tCode:
// handle both tCode and uCode
sequence[i+idSize] = aCode
case cCode:
sequence[i+idSize] = gCode
case gCode:
sequence[i+idSize] = cCode
default:
//case N -> leave it
}
}
// reverse the sequence
for i, j := idSize, len(sequence)-1; i < j; i, j = i+1, j-1 {
sequence[i], sequence[j] = sequence[j], sequence[i]
}
if !alternative {
// Staden convention: Frame -1 is the reverse-complement of the sequence
// having the same codon phase as frame 1. Frame -2 is the same phase as
// frame 2. Frame -3 is the same phase as frame 3
//
// use the matrix to keep track of the forward frame as it depends on the
// length of the sequence
switch nuclSeqLength % 3 {
case 0:
startPosition[0], startPosition[1], startPosition[2] = 0, 2, 1
case 1:
startPosition[0], startPosition[1], startPosition[2] = 1, 0, 2
case 2:
startPosition[0], startPosition[1], startPosition[2] = 2, 1, 0
}
}
// run the same loop, but with the reverse-complemented sequence
goto Translate
}
if w.buf.Len() > maxBufferSize {
_, err := out.Write(w.buf.Bytes())
if err != nil {
select {
case errs <- fmt.Errorf("fail to write to output file: %v", err):
default:
}
cancel()
return
}
w.buf.Reset()
}
pool.Put(sequence)
}
if w.buf.Len() > 0 {
_, err := out.Write(w.buf.Bytes())
if err != nil {
select {
case errs <- fmt.Errorf("fail to write to output file: %v", err):
default:
}
cancel()
return
}
}
}()
}
readSequenceFromFasta(ctx, inputSequence, fnaSequences)
wg.Wait()
select {
case err, ok := <-errs:
if ok {
return err
}
default:
}
return nil
}
func readSequenceFromFasta(ctx context.Context, inputSequence io.Reader, fnaSequences chan encodedSequence) {
feeder := &fastaChannelFeeder{
idBuffer: bytes.NewBuffer(nil),
commentBuffer: bytes.NewBuffer(nil),
sequenceBuffer: bytes.NewBuffer(nil),
fastaChan: fnaSequences,
}
// fasta format is:
//
// >sequenceID some comments on sequence
// ACAGGCAGAGACACGACAGACGACGACACAGGAGCAGACAGCAGCAGACGACCACATATT
// TTTGCGGTCACATGACGACTTCGGCAGCGA
//
// see https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp
// section 1 for details
scanner := bufio.NewScanner(inputSequence)
Loop:
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
if line[0] == '>' {
if feeder.idBuffer.Len() > 0 {
select {
case <-ctx.Done():
break Loop
default:
}
feeder.sendFasta()
}
feeder.reset()
// parse the ID of the sequence. ID is formatted like this:
// >sequenceID comments
seqID := bytes.SplitN(line, []byte{' '}, 2)
feeder.idBuffer.Write(seqID[0])
if len(seqID) > 1 {
feeder.commentBuffer.WriteByte(' ')
feeder.commentBuffer.Write(seqID[1])
}
} else {
// if the line doesn't start with '>', then it's a part of the
// nucleotide sequence, so write it to the buffer
feeder.sequenceBuffer.Write(line)
}
}
// don't forget to push last sequence
select {
case <-ctx.Done():
default:
feeder.sendFasta()
}
close(fnaSequences)
}
// a type to hold an encoded fasta sequence
//
// s[0:4] stores the size of the sequence id + the size of the comment as an uint32 (little endian)
// s[4:idSize] stores the sequence id, and the comment id there is one
// s[idSize:] stores the nucl sequence
type encodedSequence []byte
var pool = sync.Pool{
New: func() interface{} {
return make(encodedSequence, 512)
},
}
func getSizedSlice(idSize, requiredSize int) encodedSequence {
s := pool.Get().(encodedSequence)
binary.LittleEndian.PutUint32(s[0:4], uint32(idSize))
for len(s) < requiredSize {
s = append(s, byte(0))
}
return s[0:requiredSize]
}
func (f *fastaChannelFeeder) sendFasta() {
idSize := 4 + f.idBuffer.Len() + f.commentBuffer.Len()
requiredSize := idSize + f.sequenceBuffer.Len()
s := getSizedSlice(idSize, requiredSize)
if f.commentBuffer.Len() > 0 {
copy(s[idSize-f.commentBuffer.Len():idSize], f.commentBuffer.Bytes())
}
copy(s[4:4+f.idBuffer.Len()], f.idBuffer.Bytes())
// convert the sequence of bytes to an array of uint8 codes,
// so a codon (3 nucleotides | 3 bytes ) can be represented
// as an uint32
for i, b := range f.sequenceBuffer.Bytes() {
switch b {
case 'A':
s[i+idSize] = aCode
case 'C':
s[i+idSize] = cCode
case 'G':
s[i+idSize] = gCode
case 'T', 'U':
s[i+idSize] = tCode
case 'N':
s[i+idSize] = nCode
default:
fmt.Printf("WARNING: invalid char in sequence %s: %s, ignoring", s[4:4+idSize], string(b))
}
}
f.fastaChan <- s
}
type fastaChannelFeeder struct {
idBuffer, commentBuffer, sequenceBuffer *bytes.Buffer
fastaChan chan encodedSequence
}
func (f *fastaChannelFeeder) reset() {
f.idBuffer.Reset()
f.sequenceBuffer.Reset()
f.commentBuffer.Reset()
}
</code></pre>
| [] | [
{
"body": "<p>This covers an interesting topic. Great work!</p>\n\n<p>Because I am unfamiliar with this area, I utilized your unit testing to ensure changes I make did not break functionality. If they do, I apologize and please let me know.</p>\n\n<h2>Utilize implicit repetition and <code>iota</code></h2>\n\n<p>Rather than manually defining the type and value of <code>nCode</code>, <code>aCode</code>, etc. we an implicitly get the value using <a href=\"https://golang.org/ref/spec#Iota\" rel=\"nofollow noreferrer\"><code>iota</code></a>. This also simplifies the assignment of <code>arrayCodeSize</code>.</p>\n\n<pre><code>const (\n nCode = uint8(0)\n aCode = uint8(1)\n cCode = uint8(2)\n tCode = uint8(3)\n uCode = uint8(3)\n gCode = uint8(4)\n\n stopByte = '*'\n unknown = 'X'\n // Length of the array to store code/bytes\n // uses gCode because it's the biggest uint8 of all codes\n arrayCodeSize = (uint32(gCode) | uint32(gCode)<<8 | uint32(gCode)<<16) + 1\n)\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>const (\n nCode = iota\n aCode\n cCode\n tCode\n uCode\n gCode\n\n stopByte = '*'\n unknown = 'X'\n\n // Length of the array to store code/bytes\n // uses gCode because it's the biggest of all codes\n arrayCodeSize = (gCode | gCode<<8 | gCode<<16) + 1\n)\n</code></pre>\n\n<h2>Check <code>error</code> return values</h2>\n\n<p>There are fourteen places in your code where the <code>error</code> return value is unchecked. If this is intentional, it's common practice to assign it to the <a href=\"https://golang.org/ref/spec#Blank_identifier\" rel=\"nofollow noreferrer\">blank identifier</a>: <code>_</code>.</p>\n\n<p>Here is a list of occurrences:</p>\n\n<ul>\n<li><s><code>w.buf.WriteByte()</code> in <code>addByte()</code></s></li>\n<li><s><code>w.buf.WriteByte()</code> in <code>addUnknown()</code></s></li>\n<li><s><code>w.buf.WriteByte()</code> in <code>newLine()</code></s></li>\n<li><s>Many <code>Write</code> and <code>WriteByte</code> calls in <code>Translate()</code></s></li>\n<li><s><code>feeder.idBuffer.Write()</code> and such, in <code>readSequenceFromFasta</code></s></li>\n</ul>\n\n<p><strong>Update:</strong> These always return <code>nil</code>.</p>\n\n<h2>Reduce complexity of <code>Translate()</code></h2>\n\n<p>The <code>Translate()</code> function is complex. It's current cyclomatic complexity is 45. (By the end of this, it's complexity is 27).</p>\n\n<p>I notice that you define a <code>go</code> statement, which acts as a worker. I will leave it up to you to choose a fitting name, but for now \"<code>worker()</code>\" is sufficient.</p>\n\n<pre><code>func worker(wg *sync.WaitGroup, fnaSequences chan encodedSequence,\n ctx context.Context, framesToGenerate []int, arrayCode []byte,\n options Options, reverse bool, out io.Writer, errs chan error,\n cancel context.CancelFunc) {\n defer wg.Done()\n\n startPosition := make([]int, 3)\n\n w := &writer{\n buf: bytes.NewBuffer(nil),\n bytesToTrim: 0,\n currentLineLen: 0,\n }\n\n for sequence := range fnaSequences {\n\n select {\n case <-ctx.Done():\n return\n default:\n }\n\n frameIndex := 0\n startPosition[0], startPosition[1], startPosition[2] = 0, 1, 2\n\n idSize := int(binary.LittleEndian.Uint32(sequence[0:4]))\n nuclSeqLength := len(sequence) - idSize\n\n Translate:\n for _, startPos := range startPosition {\n\n if framesToGenerate[frameIndex] == 0 {\n frameIndex++\n continue\n }\n\n // sequence id should look like\n // >sequenceID_<frame> comment\n idEnd := bytes.IndexByte(sequence[4:idSize], ' ')\n if idEnd != -1 {\n w.buf.Write(sequence[4 : 4+idEnd])\n w.buf.WriteByte('_')\n w.buf.WriteByte(suffixes[frameIndex])\n w.buf.Write(sequence[4+idEnd : idSize])\n } else {\n w.buf.Write(sequence[4:idSize])\n w.buf.WriteByte('_')\n w.buf.WriteByte(suffixes[frameIndex])\n }\n w.newLine()\n\n // if in trim mode, nb of bytes to trim (nb of successive 'X', '*' and '\\n'\n // from right end of the sequence)\n w.bytesToTrim = 0\n w.currentLineLen = 0\n\n // read the sequence 3 letters at a time, starting at a specific position\n // corresponding to the frame\n for pos := startPos + 2 + idSize; pos < len(sequence); pos += 3 {\n\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n // create an uint32 from the codon, to retrieve the corresponding\n // AA from the map\n codonCode := uint32(sequence[pos-2]) | uint32(sequence[pos-1])<<8 | uint32(sequence[pos])<<16\n\n b := arrayCode[codonCode]\n if b != byte(0) {\n w.addByte(b)\n } else {\n w.addUnknown()\n }\n }\n\n // the last codon is only 2 nucleotid long, try to guess\n // the corresponding AA\n if (nuclSeqLength-startPos)%3 == 2 {\n\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n codonCode := uint32(sequence[len(sequence)-2]) | uint32(sequence[len(sequence)-1])<<8\n\n b := arrayCode[codonCode]\n if b != byte(0) {\n w.addByte(b)\n } else {\n w.addUnknown()\n }\n }\n\n // the last codon is only 1 nucleotid long, no way to guess\n // the corresponding AA\n if (nuclSeqLength-startPos)%3 == 1 {\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n w.addUnknown()\n }\n\n if options.Trim && w.bytesToTrim > 0 {\n // remove the last bytesToTrim bytes of the buffer\n // as they are 'X', '*' or '\\n'\n w.buf.Truncate(w.buf.Len() - w.bytesToTrim)\n w.currentLineLen -= w.bytesToTrim\n }\n\n if w.currentLineLen != 0 {\n w.newLine()\n }\n frameIndex++\n }\n\n if reverse && frameIndex < 6 {\n\n // get the complementary sequence.\n // Basically, switch\n // A <-> T\n // C <-> G\n // N is not modified\n for i, n := range sequence[idSize:] {\n\n switch n {\n case aCode:\n sequence[i+idSize] = tCode\n case tCode:\n // handle both tCode and uCode\n sequence[i+idSize] = aCode\n case cCode:\n sequence[i+idSize] = gCode\n case gCode:\n sequence[i+idSize] = cCode\n default:\n //case N -> leave it\n }\n }\n // reverse the sequence\n for i, j := idSize, len(sequence)-1; i < j; i, j = i+1, j-1 {\n sequence[i], sequence[j] = sequence[j], sequence[i]\n }\n\n if !options.Alternative {\n // Staden convention: Frame -1 is the reverse-complement of the sequence\n // having the same codon phase as frame 1. Frame -2 is the same phase as\n // frame 2. Frame -3 is the same phase as frame 3\n //\n // use the matrix to keep track of the forward frame as it depends on the\n // length of the sequence\n switch nuclSeqLength % 3 {\n case 0:\n startPosition[0], startPosition[1], startPosition[2] = 0, 2, 1\n case 1:\n startPosition[0], startPosition[1], startPosition[2] = 1, 0, 2\n case 2:\n startPosition[0], startPosition[1], startPosition[2] = 2, 1, 0\n }\n }\n // run the same loop, but with the reverse-complemented sequence\n goto Translate\n }\n\n if w.buf.Len() > maxBufferSize {\n _, err := out.Write(w.buf.Bytes())\n if err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n }\n w.buf.Reset()\n }\n pool.Put(sequence)\n }\n\n if w.buf.Len() > 0 {\n _, err := out.Write(w.buf.Bytes())\n if err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n }\n }\n}\n</code></pre>\n\n<p>But that's a ton of arguments for the worker, can more be done? Sure! But first, let's get rid of <code>goto</code>.</p>\n\n<h2><code>goto</code></h2>\n\n<p>You use a <code>goto</code> statement to re-run a block of code again. That says to me: recursive function.</p>\n\n<p>So, let's move this to a separate function. Again, I have no idea the proper name, and will leave that to you. For now, I'll call it <code>getComplexityAndReverse()</code> -- a verbose name, but it should suffice.</p>\n\n<pre><code>func getComplexityAndAlternate(startPosition []int, framesToGenerate []int,\n frameIndex int, sequence encodedSequence, idSize int, w writer,\n arrayCode []byte, nuclSeqLength int, options Options, reverse bool) {\n for _, startPos := range startPosition {\n if framesToGenerate[frameIndex] == 0 {\n frameIndex++\n continue\n }\n\n // sequence id should look like\n // >sequenceID_<frame> comment\n idEnd := bytes.IndexByte(sequence[4:idSize], ' ')\n if idEnd != -1 {\n w.buf.Write(sequence[4 : 4+idEnd])\n w.buf.WriteByte('_')\n w.buf.WriteByte(suffixes[frameIndex])\n w.buf.Write(sequence[4+idEnd : idSize])\n } else {\n w.buf.Write(sequence[4:idSize])\n w.buf.WriteByte('_')\n w.buf.WriteByte(suffixes[frameIndex])\n }\n w.newLine()\n\n // if in trim mode, nb of bytes to trim (nb of successive 'X', '*' and '\\n'\n // from right end of the sequence)\n w.bytesToTrim = 0\n w.currentLineLen = 0\n\n // read the sequence 3 letters at a time, starting at a specific position\n // corresponding to the frame\n for pos := startPos + 2 + idSize; pos < len(sequence); pos += 3 {\n\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n // create an uint32 from the codon, to retrieve the corresponding\n // AA from the map\n codonCode := uint32(sequence[pos-2]) | uint32(sequence[pos-1])<<8 | uint32(sequence[pos])<<16\n\n b := arrayCode[codonCode]\n if b != byte(0) {\n w.addByte(b)\n } else {\n w.addUnknown()\n }\n }\n\n // the last codon is only 2 nucleotid long, try to guess\n // the corresponding AA\n if (nuclSeqLength-startPos)%3 == 2 {\n\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n codonCode := uint32(sequence[len(sequence)-2]) | uint32(sequence[len(sequence)-1])<<8\n\n b := arrayCode[codonCode]\n if b != byte(0) {\n w.addByte(b)\n } else {\n w.addUnknown()\n }\n }\n\n // the last codon is only 1 nucleotid long, no way to guess\n // the corresponding AA\n if (nuclSeqLength-startPos)%3 == 1 {\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n w.addUnknown()\n }\n\n if options.Trim && w.bytesToTrim > 0 {\n // remove the last bytesToTrim bytes of the buffer\n // as they are 'X', '*' or '\\n'\n w.buf.Truncate(w.buf.Len() - w.bytesToTrim)\n w.currentLineLen -= w.bytesToTrim\n }\n\n if w.currentLineLen != 0 {\n w.newLine()\n }\n frameIndex++\n }\n\n if reverse && frameIndex < 6 {\n\n // get the complementary sequence.\n // Basically, switch\n // A <-> T\n // C <-> G\n // N is not modified\n for i, n := range sequence[idSize:] {\n\n switch n {\n case aCode:\n sequence[i+idSize] = tCode\n case tCode:\n // handle both tCode and uCode\n sequence[i+idSize] = aCode\n case cCode:\n sequence[i+idSize] = gCode\n case gCode:\n sequence[i+idSize] = cCode\n default:\n //case N -> leave it\n }\n }\n // reverse the sequence\n for i, j := idSize, len(sequence)-1; i < j; i, j = i+1, j-1 {\n sequence[i], sequence[j] = sequence[j], sequence[i]\n }\n\n if !options.Alternative {\n // Staden convention: Frame -1 is the reverse-complement of the sequence\n // having the same codon phase as frame 1. Frame -2 is the same phase as\n // frame 2. Frame -3 is the same phase as frame 3\n //\n // use the matrix to keep track of the forward frame as it depends on the\n // length of the sequence\n switch nuclSeqLength % 3 {\n case 0:\n startPosition[0], startPosition[1], startPosition[2] = 0, 2, 1\n case 1:\n startPosition[0], startPosition[1], startPosition[2] = 1, 0, 2\n case 2:\n startPosition[0], startPosition[1], startPosition[2] = 2, 1, 0\n }\n }\n // run the same loop, but with the reverse-complemented sequence\n getComplexityAndAlternate(startPosition, framesToGenerate, frameIndex,\n sequence, idSize, w, arrayCode, nuclSeqLength, options, reverse)\n }\n}\n</code></pre>\n\n<p>And we can simplify <code>worker()</code> even more:</p>\n\n<pre><code>func worker(wg *sync.WaitGroup, fnaSequences chan encodedSequence,\n ctx context.Context, framesToGenerate []int, arrayCode []byte,\n options Options, reverse bool, out io.Writer, errs chan error,\n cancel context.CancelFunc) {\n defer wg.Done()\n\n startPosition := make([]int, 3)\n\n w := &writer{\n buf: bytes.NewBuffer(nil),\n bytesToTrim: 0,\n currentLineLen: 0,\n }\n\n for sequence := range fnaSequences {\n\n select {\n case <-ctx.Done():\n return\n default:\n }\n\n frameIndex := 0\n startPosition[0], startPosition[1], startPosition[2] = 0, 1, 2\n\n idSize := int(binary.LittleEndian.Uint32(sequence[0:4]))\n nuclSeqLength := len(sequence) - idSize\n\n getComplexityAndAlternate(startPosition, framesToGenerate, frameIndex,\n sequence, idSize, *w, arrayCode, nuclSeqLength, options, reverse)\n\n if w.buf.Len() > maxBufferSize {\n _, err := out.Write(w.buf.Bytes())\n if err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n }\n w.buf.Reset()\n }\n pool.Put(sequence)\n }\n\n if w.buf.Len() > 0 {\n _, err := out.Write(w.buf.Bytes())\n if err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n }\n }\n}\n</code></pre>\n\n<p>But, there's still loads of long arguments. However, now that things are broken into functions, I recommend shortening these variable names. These long names make the code very verbose.</p>\n\n<p>With my limited knowledge, I see the following:</p>\n\n<ul>\n<li><code>fnaSequences</code> → <code>fnaSeqs</code></li>\n<li><code>framesToGenerate</code> → <code>frames</code></li>\n<li><code>arrayCode</code> → <code>codes</code> (†)</li>\n<li><code>startPosition</code> → <code>starts</code> (or <code>sPos</code>)</li>\n<li><code>sequence</code> → <code>s</code> (changed in some places)</li>\n</ul>\n\n<p>† This may be incorrect jargon.</p>\n\n<h2>Move things to the lowest scope</h2>\n\n<p>For example, <code>startPosition</code> (now <code>starts</code>) can be declared in a lower scope.</p>\n\n<p>While we're at it, <code>starts</code> can be declared as such:</p>\n\n<pre><code>starts := []int{0, 1, 2}\n</code></pre>\n\n<p>Resulting in:</p>\n\n<p>(Within <code>worker()</code>)</p>\n\n<pre><code>for sequence := range fnaSequences {\n\n select {\n case <-ctx.Done():\n return\n default:\n }\n\n frameIndex := 0\n starts := []int{0, 1, 2}\n\n idSize := int(binary.LittleEndian.Uint32(sequence[0:4]))\n nuclSeqLength := len(sequence) - idSize\n\n getComplexityAndAlternate(starts, framesToGenerate, frameIndex,\n sequence, idSize, *w, arrayCode, nuclSeqLength, options, reverse)\n\n if w.buf.Len() > maxBufferSize {\n _, err := out.Write(w.buf.Bytes())\n if err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n }\n w.buf.Reset()\n }\n pool.Put(sequence)\n}\n</code></pre>\n\n<p>(Within <code>getComplexityAndAlternate()</code>)</p>\n\n<pre><code>if !options.Alternative {\n // Staden convention: Frame -1 is the reverse-complement of the sequence\n // having the same codon phase as frame 1. Frame -2 is the same phase as\n // frame 2. Frame -3 is the same phase as frame 3\n //\n // use the matrix to keep track of the forward frame as it depends on the\n // length of the sequence\n switch nuclSeqLength % 3 {\n case 0:\n starts = []int{0, 2, 1}\n case 1:\n starts = []int{1, 0, 2}\n case 2:\n starts = []int{2, 1, 0}\n }\n}\n</code></pre>\n\n<h2>Duplicate code</h2>\n\n<p>The following code is used twice and should instead be a function:</p>\n\n<pre><code>_, err := out.Write(w.buf.Bytes())\nif err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n}\n</code></pre>\n\n<p>Becomes a function (again, choose whatever name you want):</p>\n\n<pre><code>func writeOrCancel(w writer, out io.Writer, errs chan error,\n cancel context.CancelFunc) {\n if _, err := out.Write(w.buf.Bytes()); err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n return\n }\n}\n</code></pre>\n\n<h2>Unroll short loops</h2>\n\n<pre><code>case \"F\":\n for i := 0; i < 3; i++ {\n frames[i] = 1\n }\n</code></pre>\n\n<p>And</p>\n\n<pre><code>case \"R\":\n for i := 3; i < 6; i++ {\n frames[i] = 1\n }\n reverse = true\n</code></pre>\n\n<p>Shouldn't be loops. By using loops you use more magic numbers. Instead, unroll them:</p>\n\n<pre><code>case \"F\":\n frames[0] = 1\n frames[1] = 1\n frames[2] = 1\n// ...\ncase \"R\":\n frames[3] = 1\n frames[4] = 1\n frames[5] = 1\n reverse = true\n</code></pre>\n\n<p>There's probably an even easier way to clean up the switch statement in <code>computeFrames()</code>.</p>\n\n<h2>Don't name return arguments unless it simplifies code</h2>\n\n<p>In <code>computeFrames()</code> your return arguments are named, but they don't need to be.</p>\n\n<h2>Use straightforward conditions</h2>\n\n<pre><code>// generate 2 letter code\ncodes, ok := twoLetterMap[codon[0:2]]\n\nif !ok {\n twoLetterMap[codon[0:2]] = []byte{aaCode}\n} else {\n twoLetterMap[codon[0:2]] = append(codes, aaCode)\n}\n</code></pre>\n\n<p>Is more clearly:</p>\n\n<pre><code>// generate 2 letter code\nif codes, ok := twoLetterMap[codon[0:2]]; ok {\n twoLetterMap[codon[0:2]] = append(codes, aaCode)\n} else {\n twoLetterMap[codon[0:2]] = []byte{aaCode}\n}\n</code></pre>\n\n<h2>Exit loops early</h2>\n\n<p>You can break early upon the condition <code>codes[i] != codes[0]</code>.</p>\n\n<pre><code>for twoLetterCodon, codes := range twoLetterMap {\n uniqueAA := true\n for i := 0; i < len(codes); i++ {\n if codes[i] != codes[0] {\n uniqueAA = false\n }\n }\n if uniqueAA {\n first := letterCode[twoLetterCodon[0]]\n second := letterCode[twoLetterCodon[1]]\n\n uint32Code := uint32(first) | uint32(second)<<8\n resultMap[uint32Code] = codes[0]\n }\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>for twoLetterCodon, codes := range twoLetterMap {\n uniqueAA := true\n\n for _, c := range codes {\n if c != codes[0] {\n uniqueAA = false\n break\n }\n }\n\n if uniqueAA {\n first := letterCode[twoLetterCodon[0]]\n second := letterCode[twoLetterCodon[1]]\n\n uint32Code := uint32(first) | uint32(second)<<8\n resultMap[uint32Code] = codes[0]\n }\n}\n</code></pre>\n\n<h2>Combine global <code>const</code> declarations</h2>\n\n<p>It's common practice to combine them, so readers of your code don't need to search the entire document.</p>\n\n<h2>Move things to separate files</h2>\n\n<p>Your <code>writer</code> structure is relatively separate from everything else. I've moved it to a <code>writer.go</code> file -- moving the two constants it uses along with it.</p>\n\n<p>You can also simplify the field names. If you feel explanation is needed, that's the purpose of documentation, not the field names themselves.</p>\n\n<p>Rather than writing the following:</p>\n\n<pre><code>w := &writer{\n buf: bytes.NewBuffer(nil),\n toTrim: 0,\n clen: 0,\n}\n</code></pre>\n\n<p>We can use a <code>newWriter()</code> function, which follows Go APIs:</p>\n\n<pre><code>func newWriter(buf []byte) *writer {\n return &writer{buf: bytes.NewBuffer(buf)}\n}\n</code></pre>\n\n<p>Also note that specifying the default values (<code>0</code>) is not needed.</p>\n\n<h2>Conclusion: More to be done</h2>\n\n<p>I was not able to address all of the things I saw, but you should get the gist.</p>\n\n<p>I would urge you to continue to break concrete operations into functions. Even though you may end up with lots of function arguments, in my opinion that's better than hard-to-read deep nesting and long functions. Perhaps once seeing how things break up, you can simplify the whole architecture of the package.</p>\n\n<p><a href=\"https://gist.github.com/esote/24e6c0e641e1af9502f1c3a0caf03c11\" rel=\"nofollow noreferrer\">Here</a> is a GitHub Gist of the final code. It includes other formatting things I did not mention explicitly.</p>\n\n<p>Hope this helped. Your project looks promising, best of luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T20:27:42.203",
"Id": "408205",
"Score": "0",
"body": "Thanks for the answer, there is some interesting ideas ! However, I disagree with a few points:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T20:39:13.327",
"Id": "408208",
"Score": "0",
"body": "**(1)** can't use `iota` this way because `tCode` = `uCode` = `uint(3)` **(2)** `buf.Write()` and `buf.WriteByte()` always return a `nil` error, cf [godoc bytes](https://godoc.org/bytes#Buffer.Write), so no need to check for it **(3)** I agree that high cyclomatic complexity is bad, but methods with **10 (!!)** arguments is not a good solution **(4)** `starts = []int{0, 2, 1}` allocates a new array instead of reusing the same slice. Not really sure it's worth it as it's in the hot spot of the code ! And this answer doesn't talk at all about the performance of the modified code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T21:56:34.710",
"Id": "408212",
"Score": "0",
"body": "@felix **(1)** If you check, you will see that `tcode` is 3, and `ucode` is 4. That's how implicit repetition works in Go. **(2)** Fair point **(3)** In my opinion, it's better than code that's hard to read and understand, and definitely better than tons of nesting. If you split things into functions as I recommend, you may notice that functions (such as the one with 10 arguments) can be split up to do separate things. I left that work for you to implement. **(4)** If you do profiling, I highly doubt it will cause any noticeable performance difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T21:57:23.307",
"Id": "408213",
"Score": "0",
"body": "I don't talk about the performance of the modified code because it's likely the same as before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T22:31:45.787",
"Id": "408222",
"Score": "0",
"body": "**(1)** sorry it wasn't clear enough, I meant both `tCode` and `uCode` have to be equal to `uint(3)` (cf initial code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T22:57:17.847",
"Id": "408223",
"Score": "0",
"body": "@felix Ah, sorry I didn't notice that originally. In this case, you can move it to be lower than the rest, and declare it as 3 or equal to `tCode`/`uCode`. When I was using your tests, it still passed with having different values, maybe there could be a way to check this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-09T07:36:30.777",
"Id": "408271",
"Score": "1",
"body": "I was curious, so I did some benchmarking on a small file with ~85.000 sequences. Here are the results on 100 iterations: `Translate-4 1.23s ±54% 1.33s ±59% +8.57% (p=0.000 n=99+100)` ( ie new code is 8.57% slower) I guess it' the cost of extra function calls"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T07:41:02.373",
"Id": "211081",
"ParentId": "209750",
"Score": "9"
}
},
{
"body": "<p>After a large refactoring based on ideas from @esote answer, here is the result: </p>\n\n<p><strong>gotranseq.go</strong></p>\n\n<pre><code>package transeq\n\nimport (\n \"bufio\"\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n \"sync\"\n\n \"github.com/feliixx/gotranseq/ncbicode\"\n)\n\n// Options struct to store required command line args\ntype Options struct {\n Frame string `short:\"f\" long:\"frame\" value-name:\"<code>\" description:\"Frame to translate. Possible values:\\n [1, 2, 3, F, -1, -2, -3, R, 6]\\n F: forward three frames\\n R: reverse three frames\\n 6: all 6 frames\\n\" default:\"1\"`\n Table int `short:\"t\" long:\"table\" value-name:\"<code>\" description:\"NCBI code to use, see https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi?chapter=tgencodes#SG1 for details. Available codes: \\n 0: Standard code\\n 2: The Vertebrate Mitochondrial Code\\n 3: The Yeast Mitochondrial Code\\n 4: The Mold, Protozoan, and Coelenterate Mitochondrial Code and the Mycoplasma/Spiroplasma Code\\n 5: The Invertebrate Mitochondrial Code\\n 6: The Ciliate, Dasycladacean and Hexamita Nuclear Code\\n 9: The Echinoderm and Flatworm Mitochondrial Code\\n 10: The Euplotid Nuclear Code\\n 11: The Bacterial, Archaeal and Plant Plastid Code\\n 12: The Alternative Yeast Nuclear Code\\n 13: The Ascidian Mitochondrial Code\\n 14: The Alternative Flatworm Mitochondrial Code\\n16: Chlorophycean Mitochondrial Code\\n 21: Trematode Mitochondrial Code\\n22: Scenedesmus obliquus Mitochondrial Code\\n 23: Thraustochytrium Mitochondrial Code\\n 24: Pterobranchia Mitochondrial Code\\n 25: Candidate Division SR1 and Gracilibacteria Code\\n 26: Pachysolen tannophilus Nuclear Code\\n 29: Mesodinium Nuclear\\n 30: Peritrich Nuclear\\n\" default:\"0\"`\n Clean bool `short:\"c\" long:\"clean\" description:\"Replace stop codon '*' by 'X'\"`\n Alternative bool `short:\"a\" long:\"alternative\" description:\"Define frame '-1' as using the set of codons starting with the last codon of the sequence\"`\n Trim bool `short:\"T\" long:\"trim\" description:\"Removes all 'X' and '*' characters from the right end of the translation. The trimming process starts at the end and continues until the next character is not a 'X' or a '*'\"`\n NumWorker int `short:\"n\" long:\"numcpu\" value-name:\"<n>\" description:\"Number of threads to use, default is number of CPU\"`\n}\n\nconst (\n // nCode has to be 0 in order to compute two-letters code\n nCode uint8 = iota\n aCode\n cCode\n tCode\n gCode\n uCode = tCode\n\n // Length of the array to store codon <-> AA correspondance\n // uses gCode because it's the biggest uint8 of all codes\n arrayCodeSize = (uint32(gCode) | uint32(gCode)<<8 | uint32(gCode)<<16) + 1\n)\n\nvar letterCode = map[byte]uint8{\n 'A': aCode,\n 'C': cCode,\n 'T': tCode,\n 'G': gCode,\n 'N': nCode,\n 'U': uCode,\n}\n\nfunc createCodeArray(tableCode int, clean bool) ([arrayCodeSize]byte, error) {\n\n var codes [arrayCodeSize]byte\n for i := range codes {\n codes[i] = unknown\n }\n\n twoLetterMap := map[string][]byte{}\n codeMap, err := ncbicode.LoadTableCode(tableCode)\n if err != nil {\n return codes, err\n }\n\n for codon, aaCode := range codeMap {\n\n if !(clean && aaCode == stop) {\n // codon is always a 3 char string, for example 'ACG'\n // each nucleotide of the codon is represented by an uint8\n n1, n2, n3 := letterCode[codon[0]], letterCode[codon[1]], letterCode[codon[2]]\n index := uint32(n1) | uint32(n2)<<8 | uint32(n3)<<16\n codes[index] = aaCode\n }\n // in some case, all codon for an AA will start with the same\n // two nucleotid, for example:\n // GTC -> 'V'\n // GTG -> 'V'\n aaCodeArray, ok := twoLetterMap[codon[:2]]\n if !ok {\n twoLetterMap[codon[:2]] = []byte{aaCode}\n } else {\n if aaCode != aaCodeArray[0] {\n twoLetterMap[codon[:2]] = append(aaCodeArray, aaCode)\n }\n }\n }\n\n for twoLetterCodon, aaCodeArray := range twoLetterMap {\n\n aaCode := aaCodeArray[0]\n if len(aaCodeArray) == 1 && !(clean && aaCode == stop) {\n\n n1, n2 := letterCode[twoLetterCodon[0]], letterCode[twoLetterCodon[1]]\n index := uint32(n1) | uint32(n2)<<8\n codes[index] = aaCode\n }\n }\n return codes, nil\n}\n\nfunc computeFrames(frameName string) (frames [6]int, reverse bool, err error) {\n\n var frameMap = map[string]struct {\n frames [6]int\n reverse bool\n }{\n \"1\": {[6]int{1, 0, 0, 0, 0, 0}, false},\n \"2\": {[6]int{0, 1, 0, 0, 0, 0}, false},\n \"3\": {[6]int{0, 0, 1, 0, 0, 0}, false},\n \"F\": {[6]int{1, 1, 1, 0, 0, 0}, false},\n \"-1\": {[6]int{0, 0, 0, 1, 0, 0}, true},\n \"-2\": {[6]int{0, 0, 0, 0, 1, 0}, true},\n \"-3\": {[6]int{0, 0, 0, 0, 0, 1}, true},\n \"R\": {[6]int{0, 0, 0, 1, 1, 1}, true},\n \"6\": {[6]int{1, 1, 1, 1, 1, 1}, true},\n }\n\n f, ok := frameMap[frameName]\n if !ok {\n return frames, false, fmt.Errorf(\"wrong value for -f | --frame parameter: %s\", frameName)\n }\n return f.frames, f.reverse, nil\n}\n\n// Translate read a fata file and translate each sequence to the corresponding prot sequence\n// with the specified options\nfunc Translate(inputSequence io.Reader, out io.Writer, options Options) error {\n\n framesToGenerate, reverse, err := computeFrames(options.Frame)\n if err != nil {\n return err\n }\n\n codes, err := createCodeArray(options.Table, options.Clean)\n if err != nil {\n return err\n }\n\n fnaSequences := make(chan encodedSequence, 100)\n errs := make(chan error, 1)\n\n ctx, cancel := context.WithCancel(context.Background())\n defer cancel()\n\n var wg sync.WaitGroup\n wg.Add(options.NumWorker)\n\n for nWorker := 0; nWorker < options.NumWorker; nWorker++ {\n\n go func() {\n\n defer wg.Done()\n\n w := newWriter(codes, framesToGenerate, reverse, options.Alternative, options.Trim)\n\n for sequence := range fnaSequences {\n\n select {\n case <-ctx.Done():\n return\n default:\n }\n\n w.translate(sequence)\n\n if len(w.buf) > maxBufferSize {\n w.flush(out, cancel, errs)\n }\n pool.Put(sequence)\n }\n w.flush(out, cancel, errs)\n }()\n }\n readSequenceFromFasta(ctx, inputSequence, fnaSequences)\n\n wg.Wait()\n\n select {\n case err, ok := <-errs:\n if ok {\n return err\n }\n default:\n }\n return nil\n}\n\n// fasta format is:\n//\n// >sequenceID some comments on sequence\n// ACAGGCAGAGACACGACAGACGACGACACAGGAGCAGACAGCAGCAGACGACCACATATT\n// TTTGCGGTCACATGACGACTTCGGCAGCGA\n//\n// see https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp\n// section 1 for details\nfunc readSequenceFromFasta(ctx context.Context, inputSequence io.Reader, fnaSequences chan encodedSequence) {\n\n scanner := bufio.NewScanner(inputSequence)\n buf := bytes.NewBuffer(make([]byte, 0, 512))\n headerSize := 0\n\nLoop:\n for scanner.Scan() {\n\n line := scanner.Bytes()\n if len(line) == 0 {\n continue\n }\n if line[0] == '>' {\n if buf.Len() > 0 {\n select {\n case <-ctx.Done():\n break Loop\n default:\n }\n fnaSequences <- newEncodedSequence(buf, headerSize)\n }\n buf.Reset()\n headerSize = len(line)\n }\n buf.Write(line)\n }\n\n fnaSequences <- newEncodedSequence(buf, headerSize)\n\n close(fnaSequences)\n}\n</code></pre>\n\n<p><strong>writer.go</strong></p>\n\n<pre><code>package transeq\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n)\n\nconst (\n mb = 1 << (10 * 2)\n // size of the buffer for writing to file\n maxBufferSize = 5 * mb\n // suffixes to add to sequence id for each frame\n suffixes = \"123456\"\n maxLineSize = 60\n stop = '*'\n unknown = 'X'\n)\n\ntype writer struct {\n codes [arrayCodeSize]byte\n buf []byte\n currentLineLen int\n startPos [3]int\n frameIndex int\n framesToGenerate [6]int\n reverse bool\n alternative bool\n trim bool\n // if in trim mode, nb of bytes to trim (nb of successive 'X', '*' and '\\n'\n // from right end of the sequence)\n toTrim int\n}\n\nfunc newWriter(codes [arrayCodeSize]byte, framesToGenerate [6]int, reverse, alternative, trim bool) *writer {\n return &writer{\n codes: codes,\n buf: make([]byte, 0, maxBufferSize),\n startPos: [3]int{0, 1, 2},\n framesToGenerate: framesToGenerate,\n reverse: reverse,\n alternative: alternative,\n trim: trim,\n }\n}\n\nfunc (w *writer) reset() {\n w.frameIndex = 0\n if w.reverse && !w.alternative {\n w.startPos[0], w.startPos[1], w.startPos[2] = 0, 1, 2\n }\n}\n\nfunc (w *writer) translate(sequence encodedSequence) {\n\n w.reset()\n w.translate3Frames(sequence)\n\n if w.reverse {\n\n if !w.alternative {\n // Staden convention: Frame -1 is the reverse-complement of the sequence\n // having the same codon phase as frame 1. Frame -2 is the same phase as\n // frame 2. Frame -3 is the same phase as frame 3\n //\n // use the matrix to keep track of the forward frame as it depends on the\n // length of the sequence\n switch sequence.nuclSeqSize() % 3 {\n case 0:\n w.startPos[0], w.startPos[1], w.startPos[2] = 0, 2, 1\n case 1:\n w.startPos[0], w.startPos[1], w.startPos[2] = 1, 0, 2\n case 2:\n w.startPos[0], w.startPos[1], w.startPos[2] = 2, 1, 0\n }\n }\n sequence.reverseComplement()\n w.translate3Frames(sequence)\n }\n}\n\nfunc (w *writer) translate3Frames(sequence encodedSequence) {\n\n for _, startPos := range w.startPos {\n\n if w.framesToGenerate[w.frameIndex] == 0 {\n w.frameIndex++\n continue\n }\n w.writeHeader(sequence.header())\n\n // read the sequence 3 letters at a time, starting at a specific position\n // corresponding to the frame\n for pos := sequence.headerSize() + startPos; pos < len(sequence)-2; pos += 3 {\n index := uint32(sequence[pos]) | uint32(sequence[pos+1])<<8 | uint32(sequence[pos+2])<<16\n w.writeAA(w.codes[index])\n }\n\n switch (sequence.nuclSeqSize() - startPos) % 3 {\n case 2:\n // the last codon is only 2 nucleotid long, try to guess\n // the corresponding AA\n index := uint32(sequence[len(sequence)-2]) | uint32(sequence[len(sequence)-1])<<8\n w.writeAA(w.codes[index])\n case 1:\n // the last codon is only 1 nucleotid long, no way to guess\n // the corresponding AA\n w.writeAA(unknown)\n }\n w.trimAndReturn()\n w.frameIndex++\n }\n}\n\n// sequence id should look like\n// >sequenceID_<frame> comment\nfunc (w *writer) writeHeader(seqHeader []byte) {\n end := bytes.IndexByte(seqHeader, ' ')\n if end != -1 {\n w.buf = append(w.buf, seqHeader[:end]...)\n w.buf = append(w.buf, '_', suffixes[w.frameIndex])\n w.buf = append(w.buf, seqHeader[end:]...)\n } else {\n w.buf = append(w.buf, seqHeader...)\n w.buf = append(w.buf, '_', suffixes[w.frameIndex])\n }\n w.newLine()\n}\n\nfunc (w *writer) writeAA(aa byte) {\n\n if w.currentLineLen == maxLineSize {\n w.newLine()\n }\n w.buf = append(w.buf, aa)\n w.currentLineLen++\n\n if w.trim {\n if aa == stop || aa == unknown {\n w.toTrim++\n } else {\n w.toTrim = 0\n }\n }\n}\n\nfunc (w *writer) newLine() {\n w.buf = append(w.buf, '\\n')\n w.currentLineLen = 0\n\n if w.trim {\n w.toTrim++\n }\n}\n\nfunc (w *writer) trimAndReturn() {\n if w.toTrim > 0 {\n w.buf = w.buf[:len(w.buf)-w.toTrim]\n w.currentLineLen -= w.toTrim\n }\n\n if w.currentLineLen != 0 {\n w.newLine()\n }\n w.toTrim = 0\n}\n\nfunc (w *writer) flush(out io.Writer, cancel context.CancelFunc, errs chan error) {\n _, err := out.Write(w.buf)\n if err != nil {\n select {\n case errs <- fmt.Errorf(\"fail to write to output file: %v\", err):\n default:\n }\n cancel()\n }\n w.buf = w.buf[:0]\n}\n</code></pre>\n\n<p><strong>encodedSequence.go</strong></p>\n\n<pre><code>package transeq\n\nimport (\n \"bytes\"\n \"encoding/binary\"\n \"fmt\"\n \"sync\"\n)\n\n// a type to hold an encoded fasta sequence\n//\n// s[0:4] stores the size of the sequence header (sequence id + comment) as an uint32 (little endian)\n// s[4:headerSize] stores the sequence header\n// s[headerSize:] stores the nucl sequence\ntype encodedSequence []byte\n\nfunc newEncodedSequence(buf *bytes.Buffer, headerSize int) encodedSequence {\n\n s := getSizedSlice(4 + buf.Len())\n // reserve 4 bytes to store the header size as an uint32\n headerSize += 4\n binary.LittleEndian.PutUint32(s[0:4], uint32(headerSize))\n copy(s[4:], buf.Bytes())\n\n for i, n := range s[headerSize:] {\n switch n {\n case 'A':\n s[headerSize+i] = aCode\n case 'C':\n s[headerSize+i] = cCode\n case 'G':\n s[headerSize+i] = gCode\n case 'T', 'U':\n s[headerSize+i] = tCode\n case 'N':\n s[headerSize+i] = nCode\n default:\n fmt.Printf(\"WARNING: invalid char in sequence %s: %s, ignoring\", s[headerSize:], string(s[headerSize+i]))\n }\n }\n return s\n}\n\nvar pool = sync.Pool{\n New: func() interface{} {\n return make(encodedSequence, 512)\n },\n}\n\nfunc getSizedSlice(size int) encodedSequence {\n s := pool.Get().(encodedSequence)\n for len(s) < size {\n s = append(s, byte(0))\n }\n return s[:size]\n}\n\nfunc (s encodedSequence) header() []byte {\n return s[4:s.headerSize()]\n}\n\nfunc (s encodedSequence) headerSize() int {\n return int(binary.LittleEndian.Uint32(s[0:4]))\n}\n\nfunc (s encodedSequence) nuclSeqSize() int {\n return len(s) - s.headerSize()\n}\n\nfunc (s encodedSequence) reverseComplement() {\n\n headerSize := s.headerSize()\n // get the complementary sequence.\n // Basically, switch\n // A <-> T\n // C <-> G\n for i, n := range s[headerSize:] {\n switch n {\n case aCode:\n s[headerSize+i] = tCode\n case tCode:\n // handle both tCode and uCode\n s[headerSize+i] = aCode\n case cCode:\n s[headerSize+i] = gCode\n case gCode:\n s[headerSize+i] = cCode\n default:\n //case N -> leave it\n }\n }\n // reverse the sequence\n for i, j := headerSize, len(s)-1; i < j; i, j = i+1, j-1 {\n s[i], s[j] = s[j], s[i]\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-09T01:47:38.377",
"Id": "213123",
"ParentId": "209750",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T02:43:11.577",
"Id": "209750",
"Score": "14",
"Tags": [
"performance",
"algorithm",
"go",
"bioinformatics",
"multiprocessing"
],
"Title": "Translate nucleic acid sequence into its corresponding amino acid sequence"
} | 209750 |
<p>There is an implementation of <strong>Binary Search Tree</strong>. This is kind of based on <strong>Set Theory</strong> that duplicates are not allowed but an attempt to adding the same node twice will replace the older node.</p>
<p><strong>BSTNode Class:</strong></p>
<pre><code>package nodes.treeNodes.binaryTreesNode.bstNode;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class BSTNode<T>
{
private BSTNode<T> parent;
private BSTNode<T> leftChild;
private BSTNode<T> rightChild;
private T data;
public BSTNode(T data)
{
this(null, null, null, data);
}
public BSTNode(BSTNode<T> parent, BSTNode<T> leftChild, BSTNode<T> rightChild, T data)
{
this.parent = parent;
this.leftChild = leftChild;
this.rightChild = rightChild;
this.data = data;
}
public BSTNode <T> getParent()
{
return parent;
}
public void setParent(BSTNode <T> parent)
{
this.parent = parent;
}
public BSTNode <T> getLeftChild()
{
return leftChild;
}
public void setLeftChild(BSTNode <T> leftChild)
{
this.leftChild = leftChild;
}
public BSTNode <T> getRightChild()
{
return rightChild;
}
public void setRightChild(BSTNode <T> rightChild)
{
this.rightChild = rightChild;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
public void removeChild(BSTNode<T> child)
{
if(child == null) return;
if(this.getRightChild() == child)
{
this.setRightChild(null);
return;
}
if(this.getLeftChild() == child)
this.setLeftChild(null);
}
public Iterator<BSTNode> children()
{
List<BSTNode> childList = new LinkedList<>();
if(this.leftChild != null) childList.add(leftChild);
if(this.rightChild != null) childList.add(rightChild);
return childList.iterator();
}
}
</code></pre>
<p><strong>BST Class:</strong></p>
<pre><code>package trees.binaryTrees.bst;
import nodes.treeNodes.binaryTreesNode.bstNode.BSTNode;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BST<T extends Comparable<T>>
{
private BSTNode<T> root;
private int size;
public BST() {}
private BSTNode<T> root()
{
return root;
}
private void addRoot(T data) throws Exception
{
if(root != null) throw new Exception("Root exists is the tree.");
root = new BSTNode <>(data);
size++;
}
public void add(T data) throws Exception
{
BSTNode<T> node = find(data);
if (node == null)
addRoot(data);
else if (node.getData().compareTo(data) > 0)
addLeft(node, data);
else if (node.getData().compareTo(data) < 0)
addRight(node, data);
else node.setData(data);
}
private void addLeft(BSTNode<T> parent, T data)
{
BSTNode<T> left = new BSTNode <>(data);
parent.setLeftChild(left);
left.setParent(parent);
size++;
}
private void addRight(BSTNode<T> parent, T data)
{
BSTNode<T> right = new BSTNode <>(data);
parent.setRightChild(right);
right.setParent(parent);
size++;
}
public void remove(T data)
{
BSTNode<T> node = find(data);
if(node == null || !node.getData().equals(data)) return;
remove(node);
}
private BSTNode<T> remove(BSTNode<T> node)
{
if (isLeaf(node))
{
BSTNode<T> parent = node.getParent();
if (parent == null) root = null;
else parent.removeChild(node);
size--;
return parent;
}
BSTNode<T> descendant = descendant(node);
promoteDescendant(node, descendant);
return remove(descendant);
}
private void promoteDescendant(BSTNode<T> parent, BSTNode<T> descendant)
{
parent.setData(descendant.getData());
}
private BSTNode<T> descendant(BSTNode<T> parent)
{
BSTNode<T> child = parent.getLeftChild();
if (child != null)
{
while (child.getRightChild() != null) child = child.getRightChild();
return child;
}
child = parent.getRightChild();
if (child != null)
{
while (child.getLeftChild() != null) child = child.getLeftChild();
return child;
}
return child;
}
public T get(T data)
{
BSTNode<T> node = find(data);
if(node == null || !node.getData().equals(data)) return null;
return node.getData();
}
public boolean contains(T data)
{
BSTNode<T> node = find(data);
if(node == null || !node.getData().equals(data)) return false;
return true;
}
private BSTNode<T> find(T data)
{
if(root() == null) return null;
return findRecursively(root(), data);
}
private BSTNode<T> findRecursively(BSTNode<T> parent, T data)
{
int comparison = data.compareTo(parent.getData());
if(comparison == 0) return parent;
else if(comparison < 0 && parent.getLeftChild() != null) return findRecursively(parent.getLeftChild(), data);
else if(comparison > 0 && parent.getRightChild() != null) return findRecursively(parent.getRightChild(), data);
return parent;
}
public boolean isEmpty()
{
return size() == 0;
}
public int size()
{
return size;
}
private BSTNode<T> parent(BSTNode<T> child)
{
return child.getParent();
}
private boolean isInternal(BSTNode<T> node)
{
return node.children().hasNext();
}
private boolean isLeaf(BSTNode<T> node)
{
return !isInternal(node);
}
private int depth(BSTNode<T> node)
{
if(isLeaf(node)) return 0;
return depth(node.getParent()) + 1;
}
private int height(BSTNode<T> node)
{
if(isLeaf(node)) return 0;
int maxHeight = 0;
Iterator<BSTNode> children = node.children();
while (children.hasNext())
{
int height = height(children.next());
if(height > maxHeight) maxHeight = height;
}
return maxHeight + 1;
}
public int height()
{
if(root == null) return -1;
return height(root);
}
public List<T> preOrder()
{
List<T> list = new LinkedList<>();
preOrder(root, list);
return list;
}
private void preOrder(BSTNode<T> node, List<T> list)
{
if(node == null) return;
list.add(node.getData());
Iterator<BSTNode> children = node.children();
while (children.hasNext())
{
preOrder(children.next(), list);
}
}
public List<T> postOrder()
{
List<T> list = new LinkedList <>();
postOrder(root(), list);
return list;
}
private void postOrder(BSTNode<T> node, List<T> list)
{
if(node == null) return;
Iterator<BSTNode> children = node.children();
while (children.hasNext())
{
postOrder(children.next(), list);
}
list.add(node.getData());
}
public List<T> levelOrder()
{
List<T> nodeList = new LinkedList <>();
if(root() == null) return nodeList;
Queue<BSTNode> nodeQueue = new ConcurrentLinkedQueue <>();
try
{
nodeList.add(root().getData());
nodeQueue.add(root());
while (!nodeQueue.isEmpty())
{
BSTNode<T> node = nodeQueue.poll();
Iterator<BSTNode> nodeItr = node.children();
while (nodeItr.hasNext())
{
BSTNode<T> treeNode = nodeItr.next();
nodeQueue.add(treeNode);
nodeList.add(treeNode.getData());
}
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
return nodeList;
}
public List<T> inOrder()
{
List<T> answer = new LinkedList <>();
inOrder(root(), answer);
return answer;
}
private void inOrder(BSTNode<T> node, List<T> list)
{
if (node == null) return;
inOrder(node.getLeftChild(), list);
list.add(node.getData());
inOrder(node.getRightChild(), list);
}
@Override
public String toString()
{
return inOrder().toString();
}
}
</code></pre>
| [] | [
{
"body": "<h3>Don't throw <code>Exception</code></h3>\n\n<p>It's recommended to throw a specific type of exception, and avoid the overly general <code>Exception</code>.</p>\n\n<h3>Think twice before using checked exceptions</h3>\n\n<p>The <code>addRoot</code> method throws <code>Exception</code> when a root node already exists in the tree.\nThis is a checked exception, which means that callers must catch it and handle it.\nThis method is only called by <code>add</code>, and it doesn't handle it, instead it declares to <code>throw</code> as well.\nUsers of this class may wonder: \"why do I have to catch this exception\"?\nOr, \"what can go wrong while adding a node\"?\nIn fact, you won't be able to give a good answer to that question.\nUsing the public API of this class,\nan exception will never be thrown.\nThe only way the program might set <code>root</code> twice is if you have some mistake in the implementation.\nIn such case, a more appropriate exception type would be <code>IllegalStateException</code>.\nThat's a runtime exception, and users of the class won't have to handle it.</p>\n\n<h3>Hide implementation details</h3>\n\n<p>From the posted code, I don't see a reason for the <code>BSTNode</code> class to be publicly visible. If that's the case, then it would be better to make it a <code>private static</code> inner class of <code>BST</code>, to hide this implementation detail from users of <code>BST</code>.</p>\n\n<h3>Remove pointless <code>get</code> method</h3>\n\n<p>The <code>T get(T data)</code> method returns <code>null</code> if <code>data</code> is not found, or else <code>data</code>.\nThis is an unusual feature of a BST.\nWhatever this could be useful for, it could be implemented in terms of <code>contains</code>.</p>\n\n<h3>Use appropriate data types</h3>\n\n<p><code>levelOrder</code> uses a <code>ConcurrentLinkedQueue</code> for its queue.\nWhy not simply a <code>LinkedList</code> or <code>Deque</code>?</p>\n\n<p>Also, why does <code>children()</code> return an <code>Iterator</code> instead of a <code>List</code>?\nWith a <code>List</code>, iterating over the children would be more compact to implement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T00:03:34.357",
"Id": "209790",
"ParentId": "209751",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T02:47:17.633",
"Id": "209751",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"tree",
"generics",
"search"
],
"Title": "Generic Binary Search Tree Implementation in Java"
} | 209751 |
<p>A little bit about myself: I am 18 years old, a student living in Germany and currently working on an android app.</p>
<p>I would like if someone has the time to review my code. I am especially interested <strong>if this code has any vulnerabilities and if the efficiency could be improved</strong>. Thanks in advance :)</p>
<pre><code>import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
public class AES {
public static int iterations = 1000;
private static String seperator = ";";
private static int key_length = 256;
private static int salt_length = 64;
private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static void setSaltLength(int length) throws Exception {
if((length > 0) && ((length & (length - 1)) == 0))
salt_length = length;
else
throw new Exception("Invalid Salt Length");
}
public static void setKeyLength(int length) throws Exception {
if(length == 128 || length == 192 || length == 256)
key_length = length;
else
throw new Exception("Invalid Length");
}
public static void setSeperator(String s) throws Exception {
if(seperator.matches("[^+=/\\w]"))
seperator = s;
else
throw new Exception("Invalid Seperator");
}
public static void setDurationOnCurrentComputer(int milliseconds){
char[] password = {'t', 'e', 's', 't'};
int i = 1;
long duration = 0;
while(duration < milliseconds) {
i*=2;
long t = System.currentTimeMillis();
byte[] salt = new byte[64];
new SecureRandom().nextBytes(salt);
try {
createKey(password, salt, i);
} catch (Exception e) {
e.printStackTrace();
}
duration = System.currentTimeMillis() - t;
System.out.println("i: " + i + " duration: " + duration);
}
iterations = i;
}
private static SecretKey createKey(char[] password, byte[] salt, int iterations) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
KeySpec spec = new PBEKeySpec(password, salt, iterations, key_length);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM);
}
public static String encrypt(char[] password, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] salt = new byte[salt_length];
new SecureRandom().nextBytes(salt);
cipher.init(Cipher.ENCRYPT_MODE, createKey(password, salt, iterations));
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(data);
Base64.Encoder e = Base64.getEncoder();
return e.encodeToString((e.encodeToString(iv) + seperator + e.encodeToString(ciphertext) + seperator + e.encodeToString(salt)).getBytes());
}
public static String decrypt(char[] password, String ciphertext) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
Base64.Decoder d = Base64.getDecoder();
String[] data = new String(d.decode(ciphertext)).split(seperator);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, createKey(password, d.decode(data[2]), iterations), new IvParameterSpec(d.decode(data[0])));
return new String(cipher.doFinal(d.decode(data[1])));
}
}
</code></pre>
| [] | [
{
"body": "<p>I am far to be a crypto expert but I do not see anything wrong.</p>\n\n<p>However you should use the naming conventions for your fields. You can also consider to create an instance of your <code>AES</code> object or a via <em>factory</em> if you want to control the instance(s). This will remove all the <code>static</code> methods that can cause troubles in a concurrent environment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T14:34:50.053",
"Id": "209909",
"ParentId": "209763",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code> public static int iterations = 1000;\n</code></pre>\n</blockquote>\n\n<p>That seems quite low. See e.g. <a href=\"https://crypto.stackexchange.com/a/10335/1127\">1</a>, <a href=\"https://security.stackexchange.com/a/3993/20403\">2</a>. Or is the idea that you will use <code>setDurationOnCurrentComputer</code> always?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static String seperator = \";\";\n</code></pre>\n</blockquote>\n\n<p>Please correct the spelling to <em>separator</em> throughout the code.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static int key_length = 256;\n private static int salt_length = 64;\n</code></pre>\n</blockquote>\n\n<p><code>static</code>? I find that surprising.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static final String CIPHER_ALGORITHM = \"AES/CBC/PKCS5Padding\";\n</code></pre>\n</blockquote>\n\n<p>Is there any good reason to choose CBC over GCM? The latter is more parallelisable, and I'm using it on Android API 19, which could fairly be described as ancient.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static void setSaltLength(int length) throws Exception {\n if((length > 0) && ((length & (length - 1)) == 0))\n salt_length = length;\n else\n throw new Exception(\"Invalid Salt Length\");\n\n }\n</code></pre>\n</blockquote>\n\n<p>I think this method could use a few improvements:</p>\n\n<ol>\n<li>Why a checked exception? <code>IllegalArgumentException</code> looks like the natural fit here.</li>\n<li>Why must the salt length be a power of 2? That requirement is non-obvious, so it should be documented, and it wouldn't be a bad idea to also comment the test.</li>\n<li>The person who catches that exception will have rude words for the person who wrote the message. <code>\"Invalid Salt Length: \" + length</code> is <em>much</em> more useful for debugging.</li>\n</ol>\n\n<hr>\n\n<blockquote>\n<pre><code> public static String encrypt(char[] password, byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {\n</code></pre>\n</blockquote>\n\n<p>I think you could reasonably throw <code>GeneralSecurityException</code> and simplify that signature a bit.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> byte[] ciphertext = cipher.doFinal(data);\n</code></pre>\n</blockquote>\n\n<p>While this is tempting, I can tell you from personal experience that it may fail for large data blocks in some API levels. I can't remember offhand whether it was 64kB or 128kB which was the upper limit; to play it safe I suggest calling <code>update</code> with 16kB chunks.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Base64.Encoder e = Base64.getEncoder();\n return e.encodeToString((e.encodeToString(iv) + seperator + e.encodeToString(ciphertext) + seperator + e.encodeToString(salt)).getBytes());\n }\n</code></pre>\n</blockquote>\n\n<p>Ok, that's not efficient. Base64 encoding adds an overhead of 33%. Do it twice and you have an overhead of 78%. Ditch the outer <code>encodeToString</code>.</p>\n\n<p>Also, there are two problems with the contents. Putting <code>salt</code> at the end means that you can't start decrypting until you've read the entire string, which is a problem for stream-based operation. And failing to include the value of <code>iterations</code> in the string could mean that you aren't able to decrypt it later.</p>\n\n<hr>\n\n<p>The hardest part of cryptography is key management. There are some clues that you intend this to be used only locally: i.e. you won't be transmitting the ciphertext to another computer to decipher it remotely. So I would strongly suggest that you look at <a href=\"https://developer.android.com/training/articles/keystore.html\" rel=\"nofollow noreferrer\">KeyStore</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T15:53:31.387",
"Id": "209913",
"ParentId": "209763",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "209913",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T13:31:43.487",
"Id": "209763",
"Score": "2",
"Tags": [
"java",
"aes"
],
"Title": "Basic AES/CBC implementation in Java"
} | 209763 |
<p>I've created a script using Python in association with Scrapy to parse the movie names and its years spread across multiple pages from a torrent site. My goal here is to write the parsed data in a CSV file other than using the built-in command provided by Scrapy, because when I do this:</p>
<pre><code>scrapy crawl torrentdata -o outputfile.csv -t csv
</code></pre>
<p>I get a blank line in every alternate row in the CSV file.</p>
<p>However, I thought to go in a slightly different way to achieve the same thing. Now, I get a data-laden CSV file in the right format when I run the following script. Most importantly I made use of a <code>with statement</code> while creating a CSV file so that when the writing is done the file gets automatically closed. I used <code>crawlerprocess</code> to execute the script from within an IDE. </p>
<blockquote>
<p>My question: Isn't it a better idea for me to follow the way I tried below?</p>
</blockquote>
<p>This is the working script:</p>
<pre><code>import scrapy
from scrapy.crawler import CrawlerProcess
import csv
class TorrentSpider(scrapy.Spider):
name = "torrentdata"
start_urls = ["https://yts.am/browse-movies?page={}".format(page) for page in range(2,20)] #get something within list
itemlist = []
def parse(self, response):
for record in response.css('.browse-movie-bottom'):
items = {}
items["Name"] = record.css('.browse-movie-title::text').extract_first(default='')
items["Year"] = record.css('.browse-movie-year::text').extract_first(default='')
self.itemlist.append(items)
with open("outputfile.csv","w", newline="") as f:
writer = csv.DictWriter(f,['Name','Year'])
writer.writeheader()
for data in self.itemlist:
writer.writerow(data)
c = CrawlerProcess({
'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(TorrentSpider)
c.start()
</code></pre>
| [] | [
{
"body": "<p>By putting the CSV exporting logic into the spider itself, you are re-inventing the wheel and not using all the advantages of Scrapy and its components and, also, making the crawling slower as you are writing to disk in the crawling stage every time the callback is triggered. </p>\n\n<p>As you mentioned, the <em>CSV exporter is built-in</em>, you just need to yield/return items from the <code>parse()</code> callback:</p>\n\n<pre><code>import scrapy\n\n\nclass TorrentSpider(scrapy.Spider):\n name = \"torrentdata\"\n start_urls = [\"https://yts.am/browse-movies?page={}\".format(page) for page in range(2,20)] #get something within list\n\n def parse(self, response):\n for record in response.css('.browse-movie-bottom'):\n yield {\n \"Name\": record.css('.browse-movie-title::text').extract_first(default=''),\n \"Year\": record.css('.browse-movie-year::text').extract_first(default='')\n }\n</code></pre>\n\n<p>Then, by running:</p>\n\n<pre><code>scrapy runspider spider.py -o outputfile.csv -t csv\n</code></pre>\n\n<p>(or the <code>crawl</code> command)</p>\n\n<p>you would have the following in the <code>outputfile.csv</code>:</p>\n\n<pre><code>Name,Year\n\"Faith, Love & Chocolate\",2018\nBennett's Song,2018\n...\nTender Mercies,1983\nYou Might Be the Killer,2018\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T15:30:51.527",
"Id": "209767",
"ParentId": "209766",
"Score": "2"
}
},
{
"body": "<p>Although I'm not an expert on this, I thought to come up with a solution which I've been following quite some time.\nMaking use of <code>signals</code> might be a wise attempt here. When the scraping process is done, the <code>spider_closed()</code> method is invoked and thus the <code>DictWriter()</code> will be open once and when the writing is finished, it will be closed automatically because of the <code>with statement</code>. That said there is hardly any chance for your script to be slower, if you can get rid of <code>Disk I/O</code> issues.</p>\n\n<p>The following script represents what I told you so far:</p>\n\n<pre><code>import scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy import signals\nimport csv\n\nclass TorrentSpider(scrapy.Spider):\n name = \"torrentdata\"\n start_urls = [\"https://yts.am/browse-movies?page={}\".format(page) for page in range(2,10)] #get something within list\n itemlist = []\n\n @classmethod\n def from_crawler(cls, crawler):\n spider = super().from_crawler(crawler)\n crawler.signals.connect(spider.spider_closed, signals.spider_closed)\n return spider\n\n def spider_closed(self):\n with open(\"outputfile.csv\",\"w\", newline=\"\") as f:\n writer = csv.DictWriter(f,['Name','Year'])\n writer.writeheader()\n for data in self.itemlist:\n writer.writerow(data)\n\n def parse(self, response):\n for record in response.css('.browse-movie-bottom'):\n items = {}\n items[\"Name\"] = record.css('.browse-movie-title::text').extract_first(default='')\n items[\"Year\"] = record.css('.browse-movie-year::text').extract_first(default='')\n self.itemlist.append(items)\n\nc = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/5.0', \n})\nc.crawl(TorrentSpider)\nc.start()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T12:52:21.670",
"Id": "209829",
"ParentId": "209766",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T15:12:51.280",
"Id": "209766",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"scrapy"
],
"Title": "Creating a csv file using scrapy"
} | 209766 |
<p>The following script is part of a further education I'm currently enrolled into.</p>
<p>Not all of the code is written by myself. Function signatures for example. Therefore I have put the sections, written by myself, put into <code># -- Own ----</code> comment-lines.</p>
<p>Moreover you were given three CSV-files with business data from different cities. The imaginary business was a bikeshare-company.</p>
<pre><code>#!/usr/local/bin/python3
import time
import pandas as pd
import numpy as np
# --- Own Start ----------------------------------------------------------
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
feasible_cities = [ "new york city", "chicago", "washington" ]
feasible_months = [ "january", "february", "march", "april", "may", "june", "all" ]
feasible_days = [ "monday", "tuesday", "wednesday", "thursday",
"friday", "saturday", "sunday", "all" ]
def ask_user_selection(options, prompt_message):
answer = ""
while len(answer) == 0:
answer = input(prompt_message)
answer = answer.strip().lower()
if answer in options:
return answer
else:
answer = ""
print("Please enter one of the offered options.\n")
# -- Own END -----------------------------------------------------------------------------------
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('\n ---- Hello! Let\'s explore some US bikeshare data! ----\n')
# --- Own Start ----------------------------------------------------------
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = ask_user_selection(
feasible_cities,
"Please enter: 'new york city', 'chicago' or 'washington' > ")
# get user input for month (all, january, february, ... , june)
month = ask_user_selection(
feasible_months,
"Please enter month: 'january', 'february', 'march', 'april', 'may', 'june' or 'all' > ")
# get user input for day of week (all, monday, tuesday, ... sunday)
day = ask_user_selection(
feasible_days,
"Please enter day: 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' or 'all' > ")
print('-'*40)
return city, month, day
# --- Own End ----------------------------------------------------------
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# --- Own Start ----------------------------------------------------------
df = pd.read_csv(CITY_DATA[city], index_col = 0)
df['Start Time'] = pd.to_datetime(df['Start Time']) # Casting "Start Time" to datetime.
df["month"] = df['Start Time'].dt.month # Get the weekday out of the "Start Time" value.
df["week_day"] = df['Start Time'].dt.weekday_name # Month-part from "Start Time" value.
df["start_hour"] = df['Start Time'].dt.hour # Hour-part from "Start Time" value.
df["start_end"] = df['Start Station'].astype(str) + ' to ' + df['End Station']
if month != 'all':
month_index = feasible_months.index(month) + 1 # Get the list-index of the month.
df = df[df["month"] == month_index ] # Establish a filter for month.
if day != 'all':
df = df[df["week_day"] == day.title() ] # Establish a filter for week day.
return df
# --- Own End ----------------------------------------------------------
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
# --- Own Start ----------------------------------------------------------
print('\nCalculating The Most Frequent Times of Travel ... \n')
start_time = time.time()
# display the most common month
month_index = df["month"].mode()[0] - 1
most_common_month = feasible_months[month_index].title()
print("Most common month: ", most_common_month)
# display the most common day of week
most_common_day = df["week_day"].mode()[0]
print("Most common day: ", most_common_day)
# display the most common start hour
most_common_hour = df["start_hour"].mode()[0]
print("Most common hour: ", most_common_hour)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
# --- Own End ----------------------------------------------------------
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
# --- Own Start ----------------------------------------------------------
print('\nCalculating The Most Popular Stations and Trip ...\n')
start_time = time.time()
# display most commonly used start station
most_used_start = df['Start Station'].mode()[0]
print("Most used start: ", most_used_start)
# display most commonly used end station
most_used_end = df['End Station'].mode()[0]
print("Most used end: ", most_used_end)
# display most frequent combination of start station and end station trip
most_common_combination = df["start_end"].mode()[0]
print("Most common used combination concerning start- and end-station: ",
most_common_combination)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
# --- Own End ----------------------------------------------------------
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
# --- Own Start ----------------------------------------------------------
print("\nCalculating Trip Duration ...\n")
start_time = time.time()
# display total travel time
total_travel_time = df["Trip Duration"].sum()
print("Total time of travel: ", total_travel_time)
# display mean travel time
average_time = df["Trip Duration"].mean()
print("The average travel-time: ", average_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
# --- Own End ----------------------------------------------------------
def user_stats(df):
"""Displays statistics on bikeshare users."""
# --- Own Start ----------------------------------------------------------
print('\nCalculating User Stats ...\n')
start_time = time.time()
# Display counts of user types
print("Count of user types: ",
df["User Type"].value_counts())
# Display counts of gender
if "Gender" in df:
print("\nCounts concerning client`s gender")
print("Male persons: ", df.query("Gender == 'Male'").Gender.count())
print("Female persons: ", df.query("Gender == 'Female'").Gender.count())
# Display earliest, most recent, and most common year of birth
if "Birth Year" in df:
print("\nEarliest year of birth: ", df["Birth Year"].min())
print("Most recent year of birth: ", df["Birth Year"].max())
print("Most common year of birth: ", df["Birth Year"].value_counts().idxmax())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
# --- Own End ----------------------------------------------------------
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
# --- Own Start ----------------------------------------------------------
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
# --- Own End ----------------------------------------------------------
if __name__ == "__main__":
main()
</code></pre>
<p>Here's a screenshot how it looks on the command line:</p>
<p><a href="https://i.stack.imgur.com/FO5Sv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FO5Sv.png" alt="enter image description here"></a></p>
<p>The script has passed the review. But nevertheless I would appreciate other opinions.</p>
<p><strong>What have I done well and should keep it up? What could I have done better and why?</strong></p>
| [] | [
{
"body": "<p>The <code>ask_user_selection</code> function could be implemented a bit simpler,\nby using a <code>while True:</code> loop, and an early return:</p>\n\n<pre><code>def ask_user_selection(options, prompt_message):\n while True:\n answer = input(prompt_message).strip().lower()\n\n if answer in options:\n return answer\n\n print(\"Please enter one of the offered options.\\n\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T22:26:39.150",
"Id": "209787",
"ParentId": "209768",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209787",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T15:32:37.750",
"Id": "209768",
"Score": "4",
"Tags": [
"python",
"numpy",
"pandas"
],
"Title": "Python script for to evaluate business data"
} | 209768 |
<p>Here is MaxHeap implementation in pure JavaScript:</p>
<pre><code>/**
* We initialize index 0 because, calculations for finding
* children of a node and the parent of a node is easier
* parent = [ k/2 ], children: [ k*2, k*2+1 ]
*/
class Heap {
constructor() {
this.queue = [0];
};
/**
* Bottom-up reheapify (swim) : If the heap order is violated because a node's key
* becomes larger than that node's parents key, then we can make progress
* toward fixing the violation by exchanging the node with its parent
*
* @param {Number} k
*/
swim(k) {
while ( k>1 && this.less(k, Heap.flr(k/2)) ) {
this.exch(k, Heap.flr(k/2) ) ;
k = Heap.flr(k/2);
}
};
/**
* Top-down heapify (sink) : If the heap order is violated because a node's key becomes
* smaller than one or both of that node's children's keys, then we can make progress
* toward fixing the violation by exchanging the node with the larger of its two children.
*
* @param {Number} k
*/
sink(k) {
while ( 2*k <= this.n() ) {
const c1 = 2*k;
const c2 = 2*k + 1;
const j = this.more(c1,c2)?c2:c1;
if (this.more(k, j) ) {
this.exch(k, j);
} else {
break;
}
k = j;
}
};
/**
*
* @param {Number} i
* @param {Number} j
*/
less(i,j) {
return this.queue[i]>this.queue[j];
};
/**
*
* @param {Number} i
* @param {Number} j
*/
more(i,j) {
return this.queue[i]<this.queue[j];
};
/**
*
* @param {Number} i
* @param {Number} j
*/
exch(i, j) {
const tmp = this.queue[i];
this.queue[i] = this.queue[j];
this.queue[j] = tmp;
};
/**
* Inserts element into the internal queue
* @param {Number} k
*/
insert(k) {
this.queue.push(k);
this.swim(this.n());
};
/**
* Returns max element in the internal queue
*/
max() {
if (!this.isEmpty() ) {
return this.queue[1];
}
return false;
};
/**
* Deletes and returns max element from the internal queue
*/
delMax() {
if (!this.isEmpty()) {
const mx = this.queue[1];
this.queue[1] = this.queue.pop();
if (!this.isEmpty()) {
this.sink(1);
}
return mx;
};
return false;
};
/**
* Checks for emptyness (here we consider the queue empty if the length of the queue is 1)
*/
isEmpty() {
return this.queue.length === 1;
};
/**
* Returns last element index in the internal queue
*/
n() {
return this.queue.length-1;
};
/**
* in JS dividing odd number by even number gives fraction not integer,
* we need to get rid of this part
* @param {Number} i
*/
static flr(i) {
return Math.floor(i);
}
}
</code></pre>
<p>Is the implementation correct? What are the shortcomings that can be fixed?</p>
| [] | [
{
"body": "<h3>Bug</h3>\n\n<p>There's a bug in <code>delMax</code>:</p>\n\n<blockquote>\n<pre><code>const mx = this.queue[1];\nthis.queue[1] = this.queue.pop();\nif (!this.isEmpty()) { \n this.sink(1);\n}\nreturn mx;\n</code></pre>\n</blockquote>\n\n<p>What will happen when the heap has 1 element? The code will:</p>\n\n<ul>\n<li>Replace the first element with itself (the last element)</li>\n<li>It doesn't become empty</li>\n</ul>\n\n<p>In other words, the last element cannot be deleted.</p>\n\n<h3>Avoid hacky solutions</h3>\n\n<p>This code happens to work, but it's hacky:</p>\n\n<blockquote>\n<pre><code>while ( 2*k <= this.n() ) {\n const c1 = 2*k; \n const c2 = 2*k + 1;\n const j = this.more(c1,c2)?c2:c1;\n</code></pre>\n</blockquote>\n\n<p>What's wrong with it? When <code>2*k == this.n()</code>, then <code>c2</code> will point past the end of the queue, and <code>more</code> will compare <code>queue[c1]</code> with <code>undefined</code>, and always return <code>false</code>. The code works, but it would be better to not rely on numeric comparisons with <code>undefined</code>.</p>\n\n<h3>Look for generalization opportunities</h3>\n\n<p>It's a good idea to use a function to decide the ordering of elements, similar to what you did with <code>less</code> and <code>more</code>. This could open the opportunity to make the implementation work with arbitrary ordering.</p>\n\n<p>The current implementation doesn't make it easy to pass in these functions to customize the behavior. It would be good to make that possible. And it would be even better to make it work with a single function, let's say <code>less</code>.</p>\n\n<p>If you do that, then you should rename some methods, since <code>max</code> and <code>delMax</code> won't make sense for a min-heap ordering. You could rename these to <code>peek</code> and <code>pop</code>.</p>\n\n<h3>Hide implementation details</h3>\n\n<p>The class exposes many methods that are unnecessary for users:\n<code>swim</code>, <code>sink</code>, <code>less</code>, <code>more</code>, <code>exch</code>, <code>flr</code>.\nThese are implementation details, and it would be best to hide them.</p>\n\n<h3>Drop the unnecessary trick</h3>\n\n<p>This trick:</p>\n\n<blockquote>\n<pre><code>/**\n * We initialize index 0 because, calculations for finding \n * children of a node and the parent of a node is easier \n * parent = [ k/2 ], children: [ k*2, k*2+1 ]\n */\n</code></pre>\n</blockquote>\n\n<p>Looks completely unnecessary... I don't see a reason whatsoever why the dummy first element helps. You can eliminate it, and the implementation will be simpler and clearer.</p>\n\n<h3>Dividing by 2</h3>\n\n<p>I'm not sure if this is recommended in JavaScript world,\nbut instead of <code>Math.floor(x / 2)</code>,\n<code>x >> 1</code> feels cleaner.</p>\n\n<h3>Naming</h3>\n\n<p>Some method names could be improved:</p>\n\n<ul>\n<li><code>exch</code> -> <code>swap</code></li>\n<li><code>n</code> -> <code>size</code></li>\n<li><code>insert</code> -> <code>add</code></li>\n<li><code>flr</code> -> <code>floor</code>, or instead of always calling it with <code>flr(k / 2)</code> you could name it <code>childIndex</code> and call it with <code>k</code>, letting it do the necessary math</li>\n<li><code>flr</code> uses parameter <code>i</code>. The name <code>i</code> is best in simple counting loops.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T23:56:33.900",
"Id": "405467",
"Score": "1",
"body": "Thank you very much for allocating time to write an excellent review of my implementation, I will refactor it based on your suggestions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T22:03:05.910",
"Id": "209785",
"ParentId": "209769",
"Score": "4"
}
},
{
"body": "<h1>Protect state</h1>\n<p>There is a fundamental overriding principle in programing that if correctly followed ensures that your code will work. <strong>Encapsulate and protect the objects state so that you can trust its integrity</strong>.</p>\n<p>You have exposed the objects state yet provide no means to ensure that the state is maintained in such a way that your code will run as expected.</p>\n<p>The following actions are all possible and all make the whole object unusable. You have no systematic way to determine if the state of heap is safe to use. Yet you continue to try and perform actions on a broken state, and will eventually throw an unknown error</p>\n<pre><code>const heap = new Heap();\nheap.insert("ABC"); \nheap.queue.pop(); \nheap.queue.push(-100); \nheap.queue.length = 0; \nheap.queue = "monkey bread";\nheap.exch(0,1000);\n</code></pre>\n<p>A good object means that there is NO WAY to corrupt the state of the object. That if the state cannot be maintained a predefined known list of errors will be thrown.</p>\n<p>techniques to protect state</p>\n<ul>\n<li>Use closure to hide data that is not relevant to the user of the object.</li>\n<li>Use setters to ensure only valid values can be set.</li>\n<li>Use getters and setters to create read only and write only values.</li>\n<li>Avoid the <code>this</code> token as it can be hijacked and means any code that uses the token can corrupt state.</li>\n</ul>\n<h2>Performance</h2>\n<p>After making state trustable you must address performance. I am often down voted for putting too much emphasis on performance, yet when a new app or framework comes out the reviews always make a point off performance. Poor performance is an app killer.</p>\n<p>Performance starts at the very lowest level and is a mind set as much as a style. You should always be thinking, is there a faster way. You should also test and know what style are performant as in JavaScript it is not always evident.</p>\n<ul>\n<li><p>Inline is faster than function calls. It is a balancing act between readability and performance, but when readability is marginal always go for the inline option.</p>\n<p>You have <code>while(2*k <= this.n())</code> but could be <code>while(2 * k < queue.length)</code> Note queue should not be exposed.</p>\n</li>\n<li><p>Don't repeat calculations</p>\n<p>In swim you repeat the same calculation 3 times <code>Heap.flr(k/2)</code>. It should be calculated once and stored as a variable. You do the same in other functions.</p>\n</li>\n<li><p>Don't pass known values</p>\n<p>You call <code>sink</code> and <code>swim</code> with argument <code>k</code>, which are always the same value (either <code>1</code> or <code>queue.length - 1</code>). There is no need to pass a known value.</p>\n</li>\n<li><p>Integers are faster than doubles</p>\n<p>Javascript does not have a definable integer type, but internally to take advantage of hardware performance Javascript <code>Number</code> can be a variety of types from uint32 to double. All bitwise operators use uint32 and will coerce doubles to uint32. Integers can be up to 2 times faster than doubles (more depending on the platform)</p>\n<p>You have <code>Heap.flr(k/2)</code> that will convert odd values of <code>k</code> to a double, then floor it in <code>flr</code> which converts it back to integer. Also you require two allocations to the call stack just to complete the operation. <code>k >> 2</code> does the same thing, avoids the intermediate double and requires no use of the call stack.</p>\n<p>Learn binary math and how to use bitwise operators in javascript as they provide significant performance benefits when working with integers. Note that Javascript integers are signed 32 bit values.</p>\n</li>\n<li><p>Warning about destructuring</p>\n<p>Though you have not used destructuring, it is nowadays common to perform a swap using destructing. eg <code>[queue[a], queue[b]] = [queue[b], queue[a]]</code> and as a syntax it is very nice, but it is also currently extremely slow (About 10 times slower). You can get the same performance doing <code>{const swap = [queue[b], queue[a]]; const swapped = [swap[1], swap[0]]; queue[a] = swapped[0]; queue[b] = swap[1]}</code> to give a hint at how it's performed under the hood.</p>\n<p>I am sure this problem will be addressed soon and performance will follow standard styles, but for now be wary of destructuring in terms of performance.</p>\n</li>\n</ul>\n<h2>Consistency</h2>\n<p>Try to be consistent with JavaScript. If you access an array item outside the range you get <code>undefined</code>. However in your code you return <code>false</code> It makes more sense to return <code>undefined</code> when the queue is empty.</p>\n<h2>The rewrite</h2>\n<p>The rewrite addresses some more performance issues. The swim function can perform a lot of swaps, while in reality you are only looking for a place to put a new value. Rather than add the new value to the queue, locate the new position and use splice to insert it. This save a lot of data movements. Thus <code>swim</code> is passed the value to swim up and be inserted</p>\n<p><code>sink</code> can also be improved by starting at 0, same with the <code>queue</code>, there is no need to hold an unused item at the start.</p>\n<p>Removing the first item from <code>queue</code> means testing if there are items becomes <code>if(queue.length)</code></p>\n<p>If the <code>queue</code> is empty then undefined is returned. This eliminates the need to add conditional code to test for empty.</p>\n<p>As <code>sink</code> is only called to shift a value from the queue, it may as well shift that value as well simplifying the <code>delMax</code> function now called <code>shift</code></p>\n<p>The code is much safer this way as it can not be misused, and performs a lot faster. It also reduces the source code size by half thus making it much easier to understand.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Heap() {\n const queue = [];\n function sinkAndShift() {\n var k = 0, k2 = 1;\n while (k2 < queue.length) {\n if (queue[k] < queue[k2]) { \n const tmp = queue[k]; // don't use destructuring.\n queue[k] = queue[k2];\n queue[k2] = tmp;\n } else { break }\n k2 = (k = k2) * 2;\n }\n return queue.shift();\n }\n function swim(val) {\n var k = queue.length - 1; \n while (k > 0 && val > queue[k]) { k >>= 1 }\n queue.splice(k, 0, val);\n } \n return Object.freeze({\n set value(k) {\n if (isNaN(k)) { throw new RangeError(\"Must be a number '\" + k + \"'\") }\n swim(Number(k));\n }, \n shift() { return sinkAndShift() },\n get max() { return queue[0] }, \n get length() { return queue.length },\n });\n}\n\n// usage\n\nconst heap = new Heap();\n// or \n//const heap = new Heap;\n// or \n//const heap = Heap();\n\n\nheap.value = 100; // same as insert\nheap.value = 101; // adds second value\nheap.value = 102; \nheap.value = 103; \n\nconsole.log(heap.length); // outputs 4;\nconsole.log(heap.max); // outputs 103;\nconsole.log(heap.shift()); // outputs 103;\nconsole.log(heap.length); // outputs 3;\nconsole.log(heap.shift()); // outputs 102;\nconsole.log(heap.shift()); // outputs 101;\nconsole.log(heap.shift()); // outputs 100;\nconsole.log(heap.shift()); // outputs undefined;\n\nheap.value = \"Monkey bread\"; // will throw a range error</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:28:55.557",
"Id": "209814",
"ParentId": "209769",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209785",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T16:00:51.610",
"Id": "209769",
"Score": "4",
"Tags": [
"javascript",
"array",
"heap"
],
"Title": "MaxHeap implementation in JavaScript"
} | 209769 |
<p>Part of the program I wrote simulates a Chess game choosing random moves for each player until it's a draw or win for either player. It takes 3 seconds to complete 1 simulation and since it trains this way it will be much too slow to get real progress in chess because of the insane branching factor.</p>
<p>I tried dividing the most lengthy function in to multiple processes. This made it much slower because the function actually isn't that complicated and starting the processes takes longer than to just run it in one process. Is there any other way to speed this up?</p>
<p>For anyone who might be interested in seeing all the code and running it for themselves (it is fully functioning): <a href="https://github.com/basvdvelden/ChessAI/tree/master" rel="nofollow noreferrer">GitHub</a></p>
<p>This function belongs to class <code>Node</code>, which as the name suggests is a node on the game tree that this program explores and trains on.</p>
<p>Simulation function:</p>
<pre><code># Random simulation
def roll_out(self):
self.visits += 1
settings.path.append(int(self.index))
board = copy.deepcopy(self.state) # starting state of board
player = Player(self.state, self.color)
opponent = Player(board, self.opp)
if checkmate(board, self.color): # is the starting state already checkmate?
value, self.win = 20, True
settings.value[self.color] = value
return
if opponent.draw: # is the starting state already a draw?
value, self.draw = 5, True
settings.value[self.color] = value
return
for i in range(1000):
self.random_move(opponent, board) # moves a random piece
player.set_moves(board) # update our legal moves
if player.draw:
value = 5
settings.value[self.color] = value
return
if opponent.won:
value = 0
settings.value[self.color] = value
return
if len(opponent.pieces) == 1 and len(player.pieces) == 1:
value = 5
settings.value[self.color] = value
return
self.random_move(player, board) # moves a random piece
opponent.set_moves(board) # update opponents legal moves
if opponent.draw:
value = 5
settings.value[self.color] = value
return
if player.won:
value = 20
settings.value[self.color] = value
return
if len(player.pieces) == 1 and len(opponent.pieces) == 1:
value = 5
settings.value[self.color] = value
return
</code></pre>
<p>Move function located in <code>Player</code> class:</p>
<pre><code># Places chosen piece to chosen location on board
def move(self, c_pos, t_pos, board):
if self.side == 'black':
me, end_row = 'b', 7
else:
me, end_row = 'w', 0
c_row, c_column = c_pos[0], c_pos[1]
t_row, t_column = t_pos[0], t_pos[1]
piece = board[c_row][c_column]
board[c_row][c_column] = 1
if 'P' in piece and t_row == end_row:
self.pawn_queens += 1
piece = me + 'Q' + str(self.pawn_queens)
board[t_row][t_column] = piece
if 'bK' in piece:
self.bk_moved = True
if 'bR1' in piece:
self.br1_moved = True
if 'bR2' in piece:
self.br2_moved = True
if 'wK' in piece:
self.wk_moved = True
if 'wR1' in piece:
self.wr1_moved = True
if 'wR2' in piece:
self.wr2_moved = True
if 'K' in str(piece) and t_column == c_column - 3:
rook = board[c_row][0]
board[c_row][2], board[c_row][0] = rook, 1
if 'K' in str(piece) and t_column == c_column + 2:
rook = board[c_row][7]
board[c_row][5], board[c_row][7] = rook, 1
if self.checkmate(board):
self.won = True
self.available_moves_reset()
</code></pre>
<p>And then what I would think is the time consuming function, I left out the code for the queens moves since it's basically the code from the rook and bishop combined and would be I think too long to post here.</p>
<p>Pawn moves:</p>
<pre><code>def get_pawn_moves(board, color):
for row in board:
for square in row:
if color[0] + 'P' in str(square):
key = square.replace(color[0], '')
pawn_moves[key] = []
if color == 'b':
opp = 'w'
p_start, start_row = 1, 0
else:
opp = 'b'
p_start, start_row = 6, 7
row = 0
for i in board:
col = 0
for j in i:
if color[0] + 'P' in str(j):
key = j.replace(color[0], '')
if color[0] == 'b':
one_step = row + 1
two_steps = row + 2
else:
one_step = row - 1
two_steps = row - 2
p_capture_left = col - 1
p_capture_right = col + 1
if one_step in range(8):
if color[0] and opp not in str(board[one_step][col]):
pawn_moves[key].append([one_step, col])
if row == p_start:
if opp and color[0] not in str(board[two_steps][col]):
pawn_moves[key].append([two_steps, col])
if p_capture_left != -1 and opp in str(board[one_step][p_capture_left]):
pawn_moves[key].append([one_step, p_capture_left])
if p_capture_right != 8 and opp in str(board[one_step][p_capture_right]):
pawn_moves[key].append([one_step, p_capture_right])
col += 1
row += 1
</code></pre>
<p>Rook moves:</p>
<pre><code>def get_rook_moves(board, color):
for i in board:
for j in i:
if color[0] + 'R' in str(j):
key = j.replace(color[0], '')
rook_moves[key] = []
opp = 'w' if color[0] == 'b' else 'b'
row = 0
for i in board:
col = 0
for j in i:
if color[0] + 'R' in str(j):
key = j.replace(color[0], '')
for i in range(row, -1, -1):
if i != row:
if color[0] not in str(board[i][col]):
rook_moves[key].append([i, col])
if opp in str(board[i][col]):
break
else:
break
for i in range(row, 8):
if i != row:
if color[0] not in str(board[i][col]):
rook_moves[key].append([i, col])
if opp in str(board[i][col]):
break
else:
break
for i in range(col, -1, -1):
if i != col:
if color[0] not in str(board[row][i]):
rook_moves[key].append([row, i])
if opp in str(board[row][i]):
break
else:
break
for i in range(col, 8):
if i != col:
if color[0] not in str(board[row][i]):
rook_moves[key].append([row, i])
if opp in str(board[row][i]):
break
else:
break
col += 1
row += 1
</code></pre>
<p>Knight moves:</p>
<pre><code>def get_knight_moves(board, color):
for i in board:
for j in i:
if color[0] + 'N' in str(j):
key = j.replace(color[0], '')
knight_moves[key] = []
row = 0
for i in board:
col = 0
for j in i:
if color[0] + 'N' in str(j):
key = j.replace(color[0], '')
if row - 2 >= 0 and col + 1 <= 7:
if color[0] not in str(board[row - 2][col + 1]):
knight_moves[key].append([row - 2, col + 1])
if row - 2 >= 0 and col - 1 >= 0:
if color[0] not in str(board[row - 2][col - 1]):
knight_moves[key].append([row - 2, col - 1])
if row - 1 >= 0 and col + 2 <= 7:
if color[0] not in str(board[row - 1][col + 2]):
knight_moves[key].append([row - 1, col + 2])
if row - 1 >= 0 and col - 2 >= 0:
if color[0] not in str(board[row - 1][col - 2]):
knight_moves[key].append([row - 1, col - 2])
if row + 1 <= 7 and col + 2 <= 7:
if color[0] not in str(board[row + 1][col + 2]):
knight_moves[key].append([row + 1, col + 2])
if row + 1 <= 7 and col - 2 >= 0:
if color[0] not in str(board[row + 1][col - 2]):
knight_moves[key].append([row + 1, col - 2])
if row + 2 <= 7 and col + 1 <= 7:
if color[0] not in str(board[row + 2][col + 1]):
knight_moves[key].append([row + 2, col + 1])
if row + 2 <= 7 and col - 1 >= 0:
if color[0] not in str(board[row + 2][col - 1]):
knight_moves[key].append([row + 2, col - 1])
col += 1
row += 1
</code></pre>
<p>Bishop moves:</p>
<pre><code>def get_bishop_moves(board, color):
for n in board:
for j in n:
if color[0] + 'B' in str(j):
key = j.replace(color[0], '')
bishop_moves[key] = []
opp = 'w' if color[0] == 'b' else 'b'
row = 0
for i in board:
col = 0
for j in i:
if color[0] + 'B' in str(j):
no_color = j.replace(color[0], '')
ul_stop, dl_stop = False, False
ur_stop, dr_stop = False, False
count = 0
for n in range(col, 8):
if col != n:
count += 1
u_row, d_row = row - count, row + count
if u_row >= 0:
if not ur_stop and color[0] not in str(board[u_row][n]):
bishop_moves[no_color].append([u_row, n])
if opp in str(board[u_row][n]):
ur_stop = True
if color[0] in str(board[u_row][n]):
ur_stop = True
if d_row <= 7:
if not dr_stop and color[0] not in str(board[d_row][n]):
bishop_moves[no_color].append([d_row, n])
if opp in str(board[d_row][n]):
dr_stop = True
if color[0] in str(board[d_row][n]):
dr_stop = True
count = 0
for n in range(col, -1, -1):
if col != n:
count += 1
u_row, d_row = row - count, row + count
if u_row >= 0:
if not ul_stop and color[0] not in str(board[u_row][n]):
bishop_moves[no_color].append([u_row, n])
if opp in str(board[u_row][n]):
ul_stop = True
if color[0] in str(board[u_row][n]):
ul_stop = True
if d_row <= 7:
if not dl_stop and color[0] not in str(board[d_row][n]):
bishop_moves[no_color].append([d_row, n])
if opp in str(board[d_row][n]):
dl_stop = True
if color[0] in str(board[d_row][n]):
dl_stop = True
col += 1
row += 1
</code></pre>
<p>King moves:</p>
<pre><code>def get_king_moves(board, color, kmoved=False, r1moved=False, r2moved=False):
for n in board:
for j in n:
if color[0] + 'K' in str(j):
key = j.replace(color[0], '')
king_moves[key] = []
start_row = 0 if color[0] == 'b' else 7
row = 0
for i in board:
col = 0
for j in i:
if color[0] + 'K' in str(j):
key = j.replace(color[0], '')
k_moves = []
if row + 1 <= 7 and col + 1 <= 7:
if color[0] not in str(board[row + 1][col + 1]):
k_moves.append([row + 1, col + 1])
if color[0] not in str(board[row][col + 1]):
k_moves.append([row, col + 1])
if color[0] not in str(board[row + 1][col]):
k_moves.append([row + 1, col])
elif row + 1 <= 7:
if color[0] not in str(board[row + 1][col]):
k_moves.append([row + 1, col])
elif col + 1 <= 7:
if color[0] not in str(board[row][col + 1]):
k_moves.append([row, col + 1])
if not kmoved and not r1moved:
if str(board[start_row][1]) and str(board[start_row][2]) and str(board[start_row][3]) == '1':
k_moves.append([start_row, 1])
if not kmoved and not r2moved:
if str(board[start_row][5]) and str(board[start_row][6]) == '1':
k_moves.append([start_row, 6])
if row - 1 >= 0 and col - 1 >= 0:
if color[0] not in str(board[row - 1][col - 1]):
k_moves.append([row - 1, col - 1])
if color[0] not in str(board[row - 1][col]):
k_moves.append([row - 1, col])
if color[0] not in str(board[row][col - 1]):
k_moves.append([row, col - 1])
elif row - 1 >= 0:
if color[0] not in str(board[row - 1][col]):
k_moves.append([row - 1, col])
elif col - 1 >= 0:
if color[0] not in str(board[row][col - 1]):
k_moves.append([row, col - 1])
if row + 1 <= 7 and col - 1 >= 0 and color[0] not in str(board[row + 1][col - 1]):
k_moves.append([row + 1, col - 1])
if row - 1 >= 0 and col + 1 <= 7 and color[0] not in str(board[row - 1][col + 1]):
k_moves.append([row - 1, col + 1])
for i in k_moves:
king_moves[key].append(i)
col += 1
row += 1
</code></pre>
<p>Combine all moves in one dict:</p>
<pre><code>def pseudo_legal(board, color, kmoved=False, r1moved=False, r2moved=False):
all_moves = {}
get_pawn_moves(board, color)
get_rook_moves(board, color)
get_knight_moves(board, color)
get_bishop_moves(board, color)
get_queen_moves(board, color)
get_king_moves(board, color, kmoved=kmoved, r1moved=r1moved, r2moved=r2moved)
all_moves.update(pawn_moves)
all_moves.update(rook_moves)
all_moves.update(knight_moves)
all_moves.update(bishop_moves)
all_moves.update(queen_moves)
all_moves.update(king_moves)
return all_moves
</code></pre>
<p>Check if moves are legal:</p>
<pre><code>def get_moves(board, color, kmoved=False, r1moved=False, r2moved=False, opp_kmoved=False, opp_r1moved=False, opp_r2moved=False):
if color == 'w':
me, opp = 'w', 'b'
else:
me, opp = 'b', 'w'
if not kmoved and not r1moved and not r2moved:
moves, pieces = pseudo_legal(board, me), get_pieces(board, me)
elif kmoved:
moves, pieces = pseudo_legal(board, me, kmoved=True), get_pieces(board, me)
elif r1moved:
moves, pieces = pseudo_legal(board, me, r1moved=True), get_pieces(board, me)
elif r2moved:
moves, pieces = pseudo_legal(board, me, r2moved=True), get_pieces(board, me)
legal_moves = {}
for key in moves:
count = 0
piece = me + key
for move in moves[key]:
t_row, t_col = move[0], move[1]
c_row, c_col = pieces[key][0], pieces[key][1]
sim_board = copy.deepcopy(board)
sim_board[t_row][t_col] = piece
sim_board[c_row][c_col] = 1
king = [t_row, t_col] if key == 'K' else pieces['K']
if not opp_kmoved and not opp_r1moved and not opp_r2moved:
opp_moves = pseudo_legal(board, opp)
elif opp_kmoved:
opp_moves = pseudo_legal(board, color, kmoved=True)
elif opp_r1moved:
opp_moves = pseudo_legal(board, color, r1moved=True)
elif opp_r2moved:
opp_moves = pseudo_legal(board, color, r2moved=True)
legal = True
for opp_key in opp_moves:
for opp_move in opp_moves[opp_key]:
if king == opp_move:
legal = False
if legal:
if count == 0:
legal_moves[key] = []
count += 1
legal_moves[key].append(move)
if not legal_moves:
return False
return legal_moves
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T16:57:00.577",
"Id": "405422",
"Score": "0",
"body": "@Reinderien I was afraid I would get that answer... Should I code it from scratch? Also, is it possible to write the chess code in C, but leave the machine learning code in python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T17:36:25.677",
"Id": "405425",
"Score": "0",
"body": "You can do whatever you want :) You can invoke a C library through FFI, or you can run a C process and communicate with it via IPC, or you can find a pure C machine learning library... lots of options."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T17:59:04.927",
"Id": "405428",
"Score": "0",
"body": "@Reinderien Allright, i'll look into the options. Thanks for the response! cheers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:24:45.580",
"Id": "405430",
"Score": "1",
"body": "Welcome here! Would it be possible to provide more code. This seems to be part of a class but we're missing most of it? Also the other classes required such as Player could be useful if it is not too much code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:53:54.257",
"Id": "405442",
"Score": "0",
"body": "@Josay I have posted the code for getting the moves. The code might be too long though.. I'll remove them if this is the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T21:27:52.353",
"Id": "405454",
"Score": "0",
"body": "Hi, I have cloned your repo, but I am unsure how you are running it. What command are you using? There seems to be two mains (one in `player.py` and the other in `Origin.py`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T21:42:45.010",
"Id": "405455",
"Score": "0",
"body": "@Dair it's meant to run from Origin, the main in player is from a while ago. Thanks for pointing it out though, i'll edit it."
}
] | [
{
"body": "<p>If you are mainly looking for performance while sticking with python, you should check out <a href=\"https://python-chess.readthedocs.io/en/latest/core.html\" rel=\"nofollow noreferrer\"> python-chess</a>. It's board class has attributes like <code>board.legal_moves</code> and functions like <code>board.is_game_over()</code> which use bitboards for their low-level storage. It won't be as fast as C, but it will be a ton easier to use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T19:22:13.037",
"Id": "209780",
"ParentId": "209770",
"Score": "1"
}
},
{
"body": "<p>Looking over the github, one thing that's probably impacting your performance a good bit is memory thrash. Some of your big, complex functions spend a lot of time creating and assembling new data structures: for example your <code>pseudo_legal()</code> function (in <a href=\"https://github.com/basvdvelden/ChessAI/blob/master/chess_functions.py\" rel=\"nofollow noreferrer\">chess_functions.py</a>) is creating a new dictionary object every time its called. Along the way it calls <code>range()</code> quite a few times in order to loop over possibilities -- in Python 2, anyway, each of those <code>range()</code> calls is creating a new list. These short lived objects take time to create and also to destroy when they are no longer needed. That's a big part of your cost structure.</p>\n\n<p>On a related note, I think you're also paying extra for the way the board is represented. You're storing the board as an array-of-arrays, which means more objects to be updating and also two lookups for every access. Your method for scanning involves checking all of the board squares (including the empty squares) to find the string string identifiers for the pieces, and then you parse the display names like 'wN' or 'bBp' before you start collecting possible moves. \nTaken together all that means every time you want to update the board, you have to do this for a lot of squares:</p>\n\n<ol>\n<li>make a dictionary of possible moves</li>\n<li>get the row list from the board</li>\n<li>get the column entry from the row</li>\n<li>get the string name of the piece there</li>\n<li>parse the string to get the piece type (creating a new lookup string as part of the parsing -- another new object creation)</li>\n<li>(usually) create a list to hold possible moves</li>\n<li>do the logic to calculate possible moves add them to the list</li>\n<li>... which involves more double lookups...</li>\n<li>copy the moves from the list to the dictionary</li>\n</ol>\n\n<p>Between the lookups, the string creation, and the use of temporary lists you're moving a lot of memory around and also creating a lot of disposable objects which will need to be garbage collected.</p>\n\n<p>If you want to speed things up, it might be a good idea to tackle these in a couple of ways.</p>\n\n<h2>sparse board</h2>\n\n<p>There are 64 spaces on the board, but only 32 pieces at max (and fewer as the games goes on). So you can avoid checking a lot of empty air by representng the board sparsely. A dictionary whose keys are (x,y) tuples does a nice job of representing the placement of the pieces. Moving a piece just means doing</p>\n\n<pre><code> board[new_x, new_y] = board[old_x, old_y]\n del (board[old_x, old_y])\n</code></pre>\n\n<p>which would also automatically 'capture' any piece in <code>new_x, new_y</code> if there was already something there.</p>\n\n<h2>don't indirect the move functions</h2>\n\n<p>Related to using a dictionary is what you put into it. You can save a lot of string splitting and if-checking by just storing the functions which generate a move set in the board itself. Something like:</p>\n\n<pre><code>def knight(x, y):\n yield (x - 1, y + 2)\n yield (x - 2, y + 1)\n yield (x - 1, y - 2)\n yield (x - 2, y - 1)\n yield (x + 1, y + 2)\n yield (x + 2, y + 1)\n yield (x + 1, y - 2)\n yield (x + 2, y - 1)\n\n\nboard[0,1] = ('w', knight)\nboard[0,6] = ('w', knight)\nboard[7,1] = ('b', knight)\n#... etc\n</code></pre>\n\n<p>That way when you want to know what moves are available for the piece in a square you don't need an extra lookup:</p>\n\n<pre><code>get_moves_for(x, y):\n color, move_set = board[x,y]\n for move in move_set():\n # check legality here....\n</code></pre>\n\n<h2>split the logic for the moves</h2>\n\n<p>I used a generator here in my 'knight' function. That allows me to spit out all of the move combinations for a knight one at a time without having to assemble them into a list. For any given piece, many of the possible moves will be invalid so we don't want to create a list and then trim it down -- instead we can pass along one possible move at a time and then validate it in isolation, keeping or discarding it as conditions permit. </p>\n\n<p>A nice thing about splitting things up like this is that you can easily outsource pieces of the logic in bite-size pieces. For example all of our moves have to be limited to the range 0-7 in both x and y. Rather than copying that logic around, we can just add a filtering function that only passes along values that are in the right range:</p>\n\n<pre><code> def clip(addr):\n x, y = addr\n return -1 < x < 8 and -1 < y < 8\n</code></pre>\n\n<p>For example, you can take the move set for a given piece and location and clip it against the board like this:</p>\n\n<pre><code> color, moves = board[address]\n valid_moves = (m for m in moves() if clip(m))\n</code></pre>\n\n<p>which will filter out the impossible moves without any reference to what they are.</p>\n\n<p>One thing that's a bit hard to tackle with a pure generator setup like that is the fact that chess moves are -- as you show in your code -- sequential for many kinds of pieces. A rook, for example, can slide along until it hits a friendly piece or captures an enemy piece. But it's hard for a purely one-step-at-a-time generator to evaluate thing sequentially. I tried it by making each successive run of moves start with the original home address, so one can make a new generator that resets it's idea of 'blocked-ness' when it runs into that home value again. I'm sure there are more elegant ways that could be done, this was just a quick way to get it working:</p>\n\n<pre><code>def slide(addresses, our_color):\n clipped = (m for m in addresses if clip(m))\n stopped = False\n home = None\n for addr in clipped:\n if home is None:\n home = addr\n if addr == home:\n stopped = False\n continue\n if not stopped:\n next_square = board.get(addr)\n stopped = next_square is not None\n if not stopped or next_square[0] != our_color:\n yield addr\n</code></pre>\n\n<p>so now when you grab a piece and call slide() it will yield all the moves along its possible vectors, clipped to the limits of the board, and including possible captures (it does not however actually <em>care</em> those moves are captures -- it just says they're legal moves).</p>\n\n<h2>future work</h2>\n\n<p>I put a rough-and-ready approximation of a way it could be done into [this gist](<a href=\"https://gist.github.com/theodox/ea402db04aedcff607cd816843f3887d\" rel=\"nofollow noreferrer\">https://gist.github.com/theodox/ea402db04aedcff607cd816843f3887d</a>.</p>\n\n<p>It's not nearly as fully-featured as yours and I think it's probably got a hidden logic flaw -- white wins by a very lopsided 8:1 margin or so However it does generate about 2,000 games a minute, averaging around 65 turns each, which suggests that even with a lot more careful attention to detail it should be possible to generate a lot of data without going to C++ code or compiled extensions. </p>\n\n<p>There are several bits I didn't try to handle: the en-passant rule and castling, for example, and there's no algorithm for a draw. Those are all good places for tinkering. More importantly, I also brute-forced the calculations for checkmate by basically unioning all of the moves for each side after each turn. A more selective update of the different zones-of-death would probably double the throughput. The way I happened to try it is not really the point; it's mostly useful to show that you should be able to shave an order of magnitude or more off the times by paying close attention to limiting memory moves and object creation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:18:29.690",
"Id": "405743",
"Score": "0",
"body": "Thank you so much for taking the time to help out. imma get to work :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T07:09:32.957",
"Id": "209889",
"ParentId": "209770",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209889",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T16:28:36.780",
"Id": "209770",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"simulation",
"chess"
],
"Title": "Chess Simulation"
} | 209770 |
<p>I have written an implementation of the Strassen Vinograde Algorithm, but it's running slowly because of recursive creation of static arrays. I know that dynamic arrays would solve this problem, but I'm not allow to use them. So the main idea of this version of Strassen: We use corner elements of each square instead of copying every sub-square. I think something like this we should apply for the arrays that I create recursively.
In general, the main problem is that the algorithm is several times slower than usual even at larger values of n.</p>
<pre><code> #include "pch.h"
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<cstdlib>
#include<cmath>
#include<ctime>
#pragma comment(linker, "/STACK:5813242100")
using namespace std;
const int sizs = 256;
void vivod(int matrix[][256], int n);
void Matrix_Add(int a[][256], int b[][256], int c[][256], int n, int x1, int y1, int x2, int y2);
void Matrix_Sub(int a[][256], int b[][256], int c[][256], int n, int x1, int y1, int x2, int y2);
void Matrix_Multiply(int a[][256], int b[][256], int c[][256], int x1, int y1, int x2, int y2, int n);
void strassen(int a[][256], int b[][256], int c[][256], int m, int n, int x1, int y1, int x2, int y2);
void Naive_Multiply(int a[][256], int b[][256], int c[][256], int n);
int main()
{
setlocale(LC_ALL, "Russian");
int n;
cout << "Enter the N:";
cin >> n;
const int m = 256;
int A[m][m];
int B[m][m];
int C[m][m];
int k[m][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
A[i][j] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
B[i][j] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
A[i][j] = rand() % 10;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
B[i][j] = rand() % 10;
cout << "First Matrix:" << endl;
//vivod(A, n);
cout << "Second Matrix:" << endl;
//vivod(B, n);
int begin = clock();
//for (int i =0; i < 100; i++)
Naive_Multiply(A, B, k, n);
int end = clock();
cout << "Naive Multiply tacts: " << end - begin << endl;
//vivod(k, n);
int begin2 = clock();
//for (int i = 0; i < 100; i++)
strassen(A, B, C, n, n, 0, 0, 0, 0);
int end2 = clock();
cout << "Shtrassen tacts: " << end2 - begin2 << endl;
//vivod(C, n);
system("pause");
return 0;
}
void strassen(int a[][256], int b[][256], int c[][256], int m, int n, int x1, int y1, int x2, int y2) {
m = n / 2;
if (m != 1)
{
int s1[sizs][sizs];
int s2[sizs][sizs];
int s3[sizs][sizs];
int s4[sizs][sizs];
int s5[sizs][sizs];
int s6[sizs][sizs];
int s7[sizs][sizs];
int s8[sizs][sizs];
int m1[sizs][sizs];
int m2[sizs][sizs];
int m3[sizs][sizs];
int m4[sizs][sizs];
int m5[sizs][sizs];
int m6[sizs][sizs];
int m7[sizs][sizs];
int t1[sizs][sizs];
int t2[sizs][sizs];
int c11[sizs][sizs];
int c12[sizs][sizs];
int c21[sizs][sizs];
int c22[sizs][sizs];
Matrix_Add(a, a, s1, m, x1 + m, y1, x1 + m, y1 + m);
Matrix_Sub(s1, a, s2, m, 0, 0, x1, y1);
Matrix_Sub(a, a, s3, m, x1, y1, x1 + m, y1);
Matrix_Sub(a, s2, s4, m, x1, y1 + m, 0, 0);
Matrix_Sub(b, b, s5, m, x2, y2 + m, x2, y2);
Matrix_Sub(b, s5, s6, m, x2 + m, y2 + m, 0, 0);
Matrix_Sub(b, b, s7, m, x2 + m, y2 + m, x2, y2 + m);
Matrix_Sub(s6, b, s8, m, 0, 0, x2 + m, y2);
strassen(s2, s6, m1, m, m, 0, 0, 0, 0);
strassen(a, b, m2, m, m, x1, y1, x2, y2);
strassen(a, b, m3, m, m, x1, y1 + m, x2 + m, y2);
strassen(s3, s7, m4, m, m, 0, 0, 0, 0);
strassen(s1, s5, m5, m, m, 0, 0, 0, 0);
strassen(s4, b, m6, m, m, 0, 0, x2 + m, y2 + m);
strassen(a, s8, m7, m, m, x1 + m, y1 + m, 0, 0);
Matrix_Add(m1, m2, t1, m, 0, 0, 0, 0);
Matrix_Add(t1, m4, t2, m, 0, 0, 0, 0);
Matrix_Add(m2, m3, c11, m, 0, 0, 0, 0);
Matrix_Sub(t2, m7, c21, m, 0, 0, 0, 0);
Matrix_Add(t1, m5, c12, m, 0, 0, 0, 0);
Matrix_Add(c12, m6, c12, m, 0, 0, 0, 0);
Matrix_Add(t2, m5, c22, m, 0, 0, 0, 0);
for (int i = 0; i < n / 2; i++)
{
for (int j = 0; j < n / 2; j++)
{
c[i + n - 2 * m][j + n - 2 * m] = c11[i][j];
c[i + n - 2 * m][j + n - m] = c12[i][j];
c[i + n - m][j + n - 2 * m] = c21[i][j];
c[i + n - m][j + n - m] = c22[i][j];
}
}
}
else
{
Matrix_Multiply(a, b, c, x1, y1, x2, y2, n);
}
}
void vivod(int matrix[][256], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void Matrix_Add(int a[][256], int b[][256], int c[][256], int n, int x1, int y1, int x2, int y2)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = a[i + x1][j + y1] + b[i + x2][j + y2];
}
}
}
void Matrix_Sub(int a[][256], int b[][256], int c[][256], int n, int x1, int y1, int x2, int y2)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = a[i + x1][j + y1] - b[i + x2][j + y2];
}
}
}
void Matrix_Multiply(int a[][256], int b[][256], int c[][256], int x1, int y1, int x2, int y2, int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = 0;
for (int t = 0; t < n; t++) {
c[i][j] = c[i][j] + a[x1 + i][y1 + t] * b[x2 + t][y2 + j];
}
}
}
}
void Naive_Multiply(int a[][256], int b[][256], int c[][256], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = 0;
for (int t = 0; t < n; t++) {
c[i][j] = c[i][j] + a[i][t] * b[t][j];
}
}
}
}
</code></pre>
<p>It probably may not even start, because of large amount of arrays, but i have launched it and here is the tests:</p>
<p><a href="https://i.stack.imgur.com/kzwNG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kzwNG.jpg" alt="" /></a></p>
<p><a href="https://i.stack.imgur.com/L5Y28.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L5Y28.jpg" alt="enter image description here" /></a></p>
<p>With N = 128 and 256 naive multiplication takes nearly 10 seconds, when at the same time I'm waiting for Strassen for ~1-5 minutes.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:24:51.350",
"Id": "405431",
"Score": "1",
"body": "Brainstorming here, what do you mean no dynamic arrays? You're probably going to have to pre-declare storage for all the temporaries, using depth as well as row,col boundaries, so the recursive calls can share space in each NxN temporary. It might be ugly, but it will avoid declaring a bunch of extra MAX by MAX temporary arrays for tiny subproblems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:37:06.577",
"Id": "405436",
"Score": "0",
"body": "Maybe we need source storage, but their number for example for 256x256 matrices will be very large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:43:54.743",
"Id": "405440",
"Score": "0",
"body": "And I do not fully understand your idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T19:29:04.720",
"Id": "405450",
"Score": "0",
"body": "In addition, we can create dynamic arrays in main function, but it's not allowed to do it recursively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T10:15:42.140",
"Id": "406086",
"Score": "0",
"body": "For reference, original question: https://stackoverflow.com/questions/53802871/"
}
] | [
{
"body": "<p>I am not really sure if this question is correctly tagged, as what you wrote seems a lot like plain C-Code. If you really need static storage, you can always just fall back to <code>std::array</code>, which is more or less a wrapper around a plain C-style array.</p>\n\n<p>So you should be able to replace <code>int[256][256]</code> by <code>std::array<std::array<int, 256>, 256></code>. Note that in most times it is beneficial to have one array and use indexing to access the individual elements, but that is for another day.</p>\n\n<p>Note that <code>std::array</code> does not feature a constructor, so you would still have to manually fill it.</p>\n\n<p>Since recently you can declare variables as <code>constexpr</code>, which is a good replacement for your local variable <code>m</code>.</p>\n\n<p>Now regarding the actual code:</p>\n\n<ol>\n<li><p>You should not use <code>using namespace std;</code> This is bad practice that will pollute the entire namespace needlessly. It is quite beneficial to get into the habit of writing <code>std::</code> whenever necessary.</p></li>\n<li><p>Your original loops in main all run the same length so justfill the elements once and dont interate so often</p></li>\n<li><p>Regarding the respective functions you should be able to utilize quite a bit of functionality from the <code>algorithm</code> library.</p></li>\n</ol>\n\n<p>First lets have a look at Naive_Multiply:</p>\n\n<pre><code>void Naive_Multiply(int a[][256], int b[][256], int c[][256], int n)\n{\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n c[i][j] = 0;\n for (int t = 0; t < n; t++) {\n c[i][j] = c[i][j] + a[i][t] * b[t][j];\n }\n }\n }\n}\n</code></pre>\n\n<p>Here you can use <code>std::inner_product</code></p>\n\n<pre><code>constexpr int rowSize = 256;\nusing row = std::array<int, m>;\nusing mat = std::array<row , m>\n\nmat Naive_Multiply(const mat& a, const mat& b)\n{\n mat c;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n auto multiplyRowElement = [j](const int a, const row& b) {\n return a * b[j];\n };\n c[i][j] = std::inner_product(a[i].begin(), a[i].end(), \n b.begin(), b.end(), 0, \n std::plus<int>, multiplyRowElement);\n }\n }\n return c;\n}\n</code></pre>\n\n<p>Note that we also directly return the result of the operation rather than passing it as an inout parameter to the function, which is much cleaner. </p>\n\n<p>It seems your otehr functions create access violations if any of the additional parameters is not equal to 0. In that case you iterate over the border of the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T22:18:25.737",
"Id": "405771",
"Score": "0",
"body": "I am very grateful for your hints, but before using various functions, I must learn the principles of their work. So, that is why i'm not using it, i'm just learning the language. And what about the main problem? How to do the algorithm without recursive array creation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T10:14:09.607",
"Id": "406085",
"Score": "0",
"body": "@Emik The C++-standard-library is part of the language (not part of the core language, but part of the C++ standard)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:02:14.007",
"Id": "209927",
"ParentId": "209772",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T16:57:57.227",
"Id": "209772",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"matrix"
],
"Title": "Strassen Vinograde Algorithm"
} | 209772 |
<p>This is a <10 line Jenkins powershell build step triggered by a git commit which zips code and copies to lambda. Seems to work fine for javascript projects. I check for the zip file and then remove it if it's there. Any commentary? What am I missing?</p>
<pre><code>$sourceDir = $env:WORKSPACE;
$targetFile = $env:TEMP + "\" + $env:JOB_NAME + $env:BUILD_NUMBER+ ".zip";
if(Test-Path -Path $targetFile){
Write-Host exists;
Remove-Item $targetFile;
}
[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir , $targetfile);
aws lambda update-function-code --region us-east-1 --function-name $env:JOB_NAME --zip-file fileb://${targetFile};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:41:49.430",
"Id": "405576",
"Score": "1",
"body": "Welcome to Code Review. Apparently some users are voting to close this post as code not implemented or working properly. Do you believe it is working to the best of your knowledge?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T17:07:14.610",
"Id": "209774",
"Score": "1",
"Tags": [
"powershell",
"git",
"amazon-web-services"
],
"Title": "Jenkins Powershell script to copy code from Github to AWS Lambda"
} | 209774 |
<p>I needed some data structure for holding <em>Uri</em>s so I thought I try the <code>Uri</code> class. It quickly turned out that it's very impractical because:</p>
<ul>
<li>it's missing an implicit cast from/to string</li>
<li>it doesn't automatically recognize <em>uri</em>s as absolute or relative without specifying the <code>UriKind</code></li>
<li>it doesn't parse the query-string so it cannot compare <em>uri</em>s reliably when key-value pairs are in different order</li>
<li>it's not easy to combine an absolute <em>uri</em> with a relative one</li>
</ul>
<p>Working with it is just too inconvenient. As a solution I created my own <code>SimpleUri</code> that should solve these issues. It doesn't support everything yet because I don't need it right now but adding a couple of more regexes later should not be a problem.</p>
<pre><code>public class SimpleUri : IEquatable<SimpleUri>, IEquatable<string>
{
// https://regex101.com/r/sd288W/1
// using 'new[]' for _nicer_ syntax
private static readonly string UriPattern = string.Join(string.Empty, new[]
{
/* language=regexp */ @"^(?:(?<scheme>\w+):)?",
/* language=regexp */ @"(?:\/\/(?<authority>\w+))?",
/* language=regexp */ @"(?<path>[a-z0-9\/:]+)",
/* language=regexp */ @"(?:\?(?<query>[a-z0-9=&]+))?",
/* language=regexp */ @"(?:#(?<fragment>[a-z0-9]+))?"
});
public static readonly IEqualityComparer<SimpleUri> Comparer = EqualityComparerFactory<SimpleUri>.Create
(
equals: (x, y) => StringComparer.OrdinalIgnoreCase.Equals(x, y),
getHashCode: (obj) => StringComparer.OrdinalIgnoreCase.GetHashCode(obj)
);
public SimpleUri([NotNull] string uri)
{
if (uri == null) throw new ArgumentNullException(nameof(uri));
var uriMatch = Regex.Match
(
uri,
UriPattern,
RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture
);
if (!uriMatch.Success)
{
throw new ArgumentException(paramName: nameof(uri), message: $"'{uri}' is not a valid Uri.");
}
Scheme = uriMatch.Groups["scheme"];
Authority = uriMatch.Groups["authority"];
Path = uriMatch.Groups["path"];
Query =
uriMatch.Groups["query"].Success
? Regex
.Matches
(
uriMatch.Groups["query"].Value,
@"(?:^|&)(?<key>[a-z0-9]+)(?:=(?<value>[a-z0-9]+))?",
RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture
)
.Cast<Match>()
.ToImmutableDictionary
(
m => (ImplicitString)m.Groups["key"],
m => (ImplicitString)m.Groups["value"]
)
: ImmutableDictionary<ImplicitString, ImplicitString>.Empty;
Fragment = uriMatch.Groups["fragment"];
}
public SimpleUri(SimpleUri absoluteUri, SimpleUri relativeUri)
{
if (absoluteUri.IsRelative) throw new ArgumentException($"{nameof(absoluteUri)} must be an absolute Uri.");
if (!relativeUri.IsRelative) throw new ArgumentException($"{nameof(relativeUri)} must be a relative Uri.");
Scheme = absoluteUri.Scheme;
Authority = absoluteUri.Authority;
Path = absoluteUri.Path.Value.TrimEnd('/') + "/" + relativeUri.Path.Value.TrimStart('/');
Query = absoluteUri.Query;
Fragment = absoluteUri.Fragment;
}
public ImplicitString Scheme { get; }
public ImplicitString Authority { get; }
public ImplicitString Path { get; }
public IImmutableDictionary<ImplicitString, ImplicitString> Query { get; }
public ImplicitString Fragment { get; }
public bool IsRelative => !Scheme;
public override string ToString() => string.Join(string.Empty, GetComponents());
private IEnumerable<string> GetComponents()
{
if (Scheme)
{
yield return $"{Scheme}:";
}
if (Authority)
{
yield return $"//{Authority}";
}
yield return Path;
if (Query.Any())
{
var queryPairs =
Query
.OrderBy(x => (string)x.Key, StringComparer.OrdinalIgnoreCase)
.Select(x => $"{x.Key}{(x.Value ? "=" : string.Empty)}{x.Value}");
yield return $"?{string.Join("&", queryPairs)}";
}
if (Fragment)
{
yield return $"#{Fragment}";
}
}
#region IEquatable
public bool Equals(SimpleUri other) => Comparer.Equals(this, other);
public bool Equals(string other) => Comparer.Equals(this, other);
public override bool Equals(object obj) => obj is SimpleUri uri && Equals(uri);
public override int GetHashCode() => Comparer.GetHashCode(this);
#endregion
#region operators
public static implicit operator SimpleUri(string uri) => new SimpleUri(uri);
public static implicit operator string(SimpleUri uri) => uri.ToString();
public static SimpleUri operator +(SimpleUri absoluteUri, SimpleUri relativeUri) => new SimpleUri(absoluteUri, relativeUri);
#endregion
}
</code></pre>
<p>In this <em>experiment</em> I use a new helper for the first time which is the <code>ImplicitString</code>. Its purpose is to be able to use a <code>string</code> as a <em>conditional</em> without having to write any of the <code>string.IsX</code> all over the place.</p>
<pre><code>public class ImplicitString : IEquatable<ImplicitString>
{
public ImplicitString(string value) => Value = value;
[AutoEqualityProperty]
public string Value { get; }
public override string ToString() => Value;
public static implicit operator ImplicitString(string value) => new ImplicitString(value);
public static implicit operator ImplicitString(Group group) => group.Value;
public static implicit operator string(ImplicitString value) => value.ToString();
public static implicit operator bool(ImplicitString value) => !string.IsNullOrWhiteSpace(value);
#region IEquatable
public bool Equals(ImplicitString other) => AutoEquality<ImplicitString>.Comparer.Equals(this, other);
public override bool Equals(object obj) => obj is ImplicitString str && Equals(str);
public override int GetHashCode() => AutoEquality<ImplicitString>.Comparer.GetHashCode(this);
#endregion
}
</code></pre>
<h3>Example</h3>
<p>I tested it with use-cases I currently need it for and it works fine:</p>
<pre><code>new SimpleUri("scheme://authority/p/a/t/h?query#fragment").Dump();
new SimpleUri("scheme:p/a/t/h?q1=v1&q2=v2&q3#fragment").Dump();
new SimpleUri("p/a/t/h?q1=v1&q2=v2&q3#fragment").Dump();
new SimpleUri("p/a/t/h").Dump();
new SimpleUri("file:c:/p/a/t/h").Dump();
</code></pre>
<hr>
<p>What do you say? Is this an optimal implementation or can it be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:07:04.800",
"Id": "405429",
"Score": "0",
"body": "The `EqualityComparerFactory` can be found [here](https://github.com/he-dev/reusable/blob/47e58631fc37560176d172815ca525879da78e70/Reusable.Core/src/Collections/EqualityComparerFactory.cs)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T12:49:58.580",
"Id": "405521",
"Score": "0",
"body": "Downvoted... how so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:53:52.043",
"Id": "405922",
"Score": "0",
"body": "FWIW I’m mildly surprised you didn’t extend `URI` to create `SimpleUri`. Surely it would be easier and more robust."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T08:24:18.660",
"Id": "405948",
"Score": "0",
"body": "@RubberDuck I can still do this ;-] and I actually already was there but the `Uri` is not as great as one would think. It throws _unexplained_ exceptions all over the place. Values are spread over several _strange_ and _seemingly_ redundant properties. I might use it later for some edge cases that I'm to lazy to implement myself but generally it's terrible. On top of it it has a super-confusing system for registering new parsers which will break any dependency-injection. `Uri` is more trouble than help."
}
] | [
{
"body": "<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>$\"{x.Key}{(x.Value ? \"=\" : string.Empty)}{x.Value}\"\n</code></pre>\n</blockquote>\n\n<p>I would find it easier to understand this way:</p>\n\n<pre><code>$\"{x.Key}{(x.Value ? $\"={x.Value}\" : string.Empty)}\"\n</code></pre>\n\n<hr>\n\n<p>Instead of testing-by-printing, why not have proper unit tests for this?\n(So I don't have to read the output after every change and re-convince myself that it's still good.)</p>\n\n<hr>\n\n<p>I'm a bit surprised that the class doesn't handle URI with domain names containing a dot, for example <code>https://stackoverflow.com/somepath</code>.</p>\n\n<hr>\n\n<p>It might be an interesting feature to add,\nwhen <code>!uriMatch.Success</code>, to check if the URI could actually be parsed by the standard <code>Uri</code> class.\nThat is, give a more clear signal to users of the class,\nwhether the URI is invalid, or it's just using some pattern not-yet-supported by <code>SimpleUri</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T07:44:23.397",
"Id": "209802",
"ParentId": "209777",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:03:02.103",
"Id": "209777",
"Score": "5",
"Tags": [
"c#",
"parsing",
"regex",
"dto"
],
"Title": "Replacing Uri with a more convenient class"
} | 209777 |
<p>There is a Java program to check if a Heap (Min) is in the correct order. Heap Order means the parent is less than both left child and right child.</p>
<pre><code>package testers;
import heap.Heap;
import java.util.List;
public class HeapTester
{
public static void main(String[] args)
{
Heap<Integer> heap = new Heap <>();
heap.add(50);
heap.add(25);
heap.add(26);
heap.add(15);
heap.add(10);
heap.add(16);
heap.add(3);
heap.add(7);
heap.add(10);
heap.add(12);
heap.add(2);
System.out.println(heap);
System.out.println(hasHeapOrder(heap.copy()));
}
private static <T extends Comparable<T>> boolean hasHeapOrder(List<T> list)
{
if(list.size() < 2) return true;
boolean hasOrder = true;
int parent = 0;
int leftChild = 2 * parent + 1;
int rightChild = 2 * parent + 2;
while(leftChild < list.size())
{
if(list.get(parent).compareTo(list.get(leftChild)) > 0)
{
hasOrder = false;
break;
}
if(rightChild < list.size())
{
if(list.get(parent).compareTo(list.get(rightChild)) > 0)
{
hasOrder = false;
break;
}
}
parent++;
leftChild = 2 * parent + 1;
rightChild = 2 * parent + 2;
}
return hasOrder;
}
}
</code></pre>
| [] | [
{
"body": "<h3>Avoid flag variables if you don't need them</h3>\n\n<p>The <code>hasOrder</code> flag variable is unnecessary.\nWhen you set this variable to <code>false</code>,\nyou could <code>return false</code> instead.\nIf the end of the loop is reached, you can <code>return true</code>.</p>\n\n<h3>Avoid unnecessary special handling</h3>\n\n<p>The special treatment for the case <code>list.size() < 2</code> is unnecessary.\nThe rest of the implementation handles that case naturally.</p>\n\n<h3>Don't repeat yourself</h3>\n\n<p>The computation logic of the left and right child indexes is duplicated twice.\nYou could eliminate that by changing the loop to <code>while (true)</code>, and making this computation the first step of the loop instead of last:</p>\n\n<pre><code>while (true) {\n int leftChild = 2 * parent + 1;\n int rightChild = 2 * parent + 2;\n\n if (leftChild >= list.size()) {\n break;\n }\n\n // ...\n</code></pre>\n\n<h3>Test using a unit test framework</h3>\n\n<p>Testing by printing stuff is not very useful.\nYou have to read the output to verify it's correct,\nwhich takes mental effort, and error-prone.\nIt's better to use a proper unit testing framework,\nwhere test cases will give you simple yes-no answers per test case;\nno need to re-interpret passing results.</p>\n\n<h3>Test all corner cases</h3>\n\n<p>Only one case is \"tested\".\nYou need more tests to verify that <code>hasHeapOrder</code> correctly returns <code>true</code> or <code>false</code> depending on the input.\nI suppose you have an implementation of <code>Heap</code> such that <code>heap.copy()</code> returns a correctly heap-ordered list, and so <code>hasHeapOrder</code> returns <code>true</code>.\nAt the minimum,\nyou should verify that <code>hasHeapOrder</code> returns <code>false</code> for lists like 4, 1, 2 and 4, 5, 2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T20:50:12.703",
"Id": "209783",
"ParentId": "209778",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209783",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T18:18:53.340",
"Id": "209778",
"Score": "1",
"Tags": [
"java",
"generics",
"heap"
],
"Title": "Program to check if heap order is correct or not"
} | 209778 |
<p>I am trying to create an event system that would be quite easy to use. The idea is that a user would only need to create a custom function and tell which event should fire that function. It works as is, but I was wondering if there is a more efficient way to accomplish this of which I'm not aware.</p>
<p><strong>The main classes of the system</strong></p>
<pre><code>Event
EventListener
EventManager
EventType (size_t enum class)
</code></pre>
<p><strong>Event</strong></p>
<pre><code>class Event
{
friend class EventListener;
public:
virtual EventType GetEventType() const = 0;
virtual ~Event() { }
inline bool IsHandled() const
{
return m_Handled;
}
protected:
bool m_Handled = false;
};
</code></pre>
<p><strong>EventListener</strong></p>
<pre><code>using EventBehavior = std::function<bool(const Event& e)>;
class EventListener
{
public:
EventListener()
{
EventManager::AddListener(this);
}
template<class T>
void Listen(EventBehavior& behavior)
{
ASSERT(std::is_base_of<Event, T>, "Can't listen to non Event!");
m_ListeningTo[(size_t)T::GetStaticType()] = true;
m_RegisteredEvents[(size_t)T::GetStaticType()] = behavior;
}
template<class T>
void StopListening()
{
ASSERT(std::is_base_of<Event, T>, "Can't stop listening to non Event!");
m_ListeningTo[(size_t)T::GetStaticType()] = false;
}
void React(Event& event)
{
if (m_ListeningTo[(size_t)event.GetEventType()])
{
event.m_Handled = m_RegisteredEvents[(size_t)event.GetEventType()](event);
}
}
private:
std::bitset<MaxEvents> m_ListeningTo;
std::array<EventBehavior, MaxEvents> m_RegisteredEvents;
};
</code></pre>
<p><strong>EventManager</strong></p>
<pre><code> class EventManager
{
public:
static void Post(Event* event)
{
m_EventBuffer.push_back(event);
}
static void Dispatch()
{
for (unsigned int i = 0; i < m_EventBuffer.size(); i++)
{
for (EventListener* listener : m_Listeners)
{
if (!m_EventBuffer[i]->IsHandled())
{
listener->React(*m_EventBuffer[i]);
}
else if(m_EventBuffer[i]->IsHandled())
{
delete m_EventBuffer[i];
m_EventBuffer.erase(m_EventBuffer.begin() + i);
break;
}
}
}
}
static void AddListener(EventListener* listener)
{
m_Listeners.push_back(listener);
}
static void ClearBuffer()
{
for (unsigned int i = 0; i < m_EventBuffer.size(); i++)
{
delete m_EventBuffer[i];
}
m_EventBuffer.clear();
}
private:
static std::vector<Event*> m_EventBuffer;
static std::vector<EventListener*> m_Listeners;
};
</code></pre>
<p><strong>Example event</strong></p>
<pre><code>//Base class for all key events
class KeyEvent : public Event
{
public:
inline int GetKeyCode() const { return m_KeyCode; }
protected:
KeyEvent(int keycode)
: m_KeyCode(keycode), m_Mods(0) {}
KeyEvent(int keycode, int mods)
: m_KeyCode(keycode), m_Mods(mods) {}
int m_KeyCode;
int m_Mods;
};
class KeyPressedEvent : public KeyEvent
{
public:
KeyPressedEvent(int keycode, int repeatCount)
: KeyEvent(keycode, 0), m_RepeatCount(repeatCount) {}
KeyPressedEvent(int keycode, int repeatCount, int scancode, int mods)
: KeyEvent(keycode, mods), m_RepeatCount(repeatCount) {}
inline int GetRepeatCount() const { return m_RepeatCount; }
//EventType is a size_t enum class
static EventType GetStaticType() { return EventType::KeyPressed; }
virtual EventType GetEventType() const override { return GetStaticType(); }
private:
int m_RepeatCount;
};
</code></pre>
<p><strong>The way the user uses the system</strong></p>
<pre><code>bool keyPressed(const Event& event)
{
const KeyPressedEvent& kpe = static_cast<const KeyPressedEvent&>(event);
//Do something
return true;
}
class Sandbox : private EventListener
{
public:
Sandbox()
{
this->Listen<KeyPressedEvent>(EventBehavior(keyPressed));
}
~Sandbox()
{
}
};
</code></pre>
<p><strong>My main questions</strong></p>
<ol>
<li>Is there a way to pass the <code>Listen</code> method a function that would accept <code>KeyPressedEvent</code> and thus removing the need for <code>dynamic_cast</code> (I realize this will require a code change and I am glad to do that as long as the way the user would use the system would remain the same)</li>
<li>Is the current system efficient as it is or is it a complete mess?</li>
<li>What would be some similar alternatives (I tried making the <code>EventBehavior</code> a template, but then ran into problems trying to store it inside the array)?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T08:51:29.727",
"Id": "405482",
"Score": "0",
"body": "I'd take a look into some library like POCO. They do have callbacks/observers taking correct type, so you don't have to do dynamic cast inside of callback, but it'd be somewhere in the dispatcher anyways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T22:37:25.977",
"Id": "405647",
"Score": "0",
"body": "pretty sure you have a bug where you delete handled events. after you delete the ith item, you shouldn't increment your index or you will skip elements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T22:44:06.890",
"Id": "405649",
"Score": "0",
"body": "@sudorm-rfslash Oh yeah, I missed that part. Thanks :)"
}
] | [
{
"body": "<h3>General observations.</h3>\n<p>Personally (so you can ignore) I prefer to be able to easily distinguish between types and objects. To this end type names always have an initial uppercase letter while objects (and functions) always have an initial lowercase letter. It is a relatively common convention (but not absolute).</p>\n<p>Very Good. Nothing major. Think I found one minor bug. Some issues around the ownership of pointers that should be tightened up plus a few questions you should ask yourself.</p>\n<h3>Code Review</h3>\n<p>I don't add <code>inline</code> unless it is absolutely needed.</p>\n<pre><code>inline bool IsHandled() const\n</code></pre>\n<p>In the class it is not needed.</p>\n<p>Avoid <code>protected</code> on variables:</p>\n<pre><code>protected:\n bool m_Handled = false;\n</code></pre>\n<p>It does not really provide any protection from accidental abuse (which is what the public/protected/private is about. You are giving your user an entry point to abuse your class.</p>\n<p>If you add something in the constructor:</p>\n<pre><code> EventListener()\n {\n EventManager::AddListener(this);\n }\n</code></pre>\n<p>I would normally expect you to remove it in the destructor. Or have a very clear comment on why we don't need to remove it.</p>\n<p>I would pass by R-Value reference here:</p>\n<pre><code> template<class T>\n void Listen(EventBehavior& behavior)\n</code></pre>\n<p>I would wrtie like this:</p>\n<pre><code> template<class T>\n void Listen(EventBehavior&& behavior)\n {\n // STUFF\n\n // By using the && above and the std::move()\n // here we are doing a move assignment (rather than\n // copy assignment). This "can" be more effecient than\n // a copy (depending on the type of "EventBehavior").\n m_RegisteredEvents[(size_t)T::GetStaticType()] = std::move(behavior);\n }\n</code></pre>\n<p>Rather than force a copy you could potentially move it into the destination array.</p>\n<p>Why the old school assert?</p>\n<pre><code> ASSERT(std::is_base_of<Event, T>, "Can't listen to non Event!");\n</code></pre>\n<p>This assert is run time only. Also it is only enabled when the appropriate macro flags are set correctly. C++ has <code>static_assert()</code> a much better compiler time assert.</p>\n<p>So when you set a "Behavior" you override the existing one. What happens if there was already one set (could we not chain them)? Why do we need to set <code>m_ListeningTo</code> to true (could we not have a default null behavior that just always returns false; this would make a check against true unnecessary!). Just some thoughts.</p>\n<pre><code> m_ListeningTo[(size_t)T::GetStaticType()] = true;\n m_RegisteredEvents[(size_t)T::GetStaticType()] = behavior;\n</code></pre>\n<p>Prefer to use C++ casts:</p>\n<pre><code> (size_t)event.GetEventType()\n</code></pre>\n<p>These C casts are very dangerous; there is no compiler checking.</p>\n<pre><code> static_cast<std::size_t>(event.GetEventType())\n</code></pre>\n<p>Also I see the above cast everywhere. It would probably be best to give this its own function so it is done in exactly one place (that way if you change the behavior you only need to do it once).</p>\n<p>Passing by pointer.</p>\n<pre><code> static void Post(Event* event)\n</code></pre>\n<p>Please don't do that. Who is the owner? When I call this function am I supposed to pass a value created with new or the address of an object? I can't tell without reading the code in detail. If you want to force ownership transfer use <code>std::unique_ptr</code> if you want to pass objects use a reference. Pointers should be reserved for internal use where you can easily know the semantics and there is no questions.</p>\n<p>Think this is a bug!</p>\n<pre><code> for (unsigned int i = 0; i < m_EventBuffer.size(); i++)\n {\n for (EventListener* listener : m_Listeners)\n {\n // STUFF\n m_EventBuffer.erase(m_EventBuffer.begin() + i);\n break;\n\n // OK you just erased an item (and broke out the inner loop).\n // But the outer loop has now moved all elements down one\n // position and you are about to increment `i`.\n //\n // Does this not mean you are going to skip one of the events?\n }\n }\n</code></pre>\n<p>Seems like an un-needed test after the else?</p>\n<pre><code> if (!m_EventBuffer[i]->IsHandled()) {\n // ACTION 1\n }\n else if(m_EventBuffer[i]->IsHandled()) {\n // ACTION 2\n }\n</code></pre>\n<p>Ether it was handled or it was not handled previously.</p>\n<p>Again a pointer.</p>\n<pre><code> static void AddListener(EventListener* listener)\n</code></pre>\n<p>But this time (opposite from last time) you are not passing ownership. If you are not taking ownership pass by reference so we know ownership is not being passed. You can internally take a pointer from the reference. But the caller needs to know that ownership is not being taken.</p>\n<p>Why not just use the new range based for?</p>\n<pre><code> for (unsigned int i = 0; i < m_EventBuffer.size(); i++)\n {\n delete m_EventBuffer[i];\n }\n</code></pre>\n<p>Like this:</p>\n<pre><code> for (auto item: m_EventBuffer)\n {\n delete item;\n }\n</code></pre>\n<p>This looks like it should be a <code>dynamic_cast</code>.</p>\n<pre><code>bool keyPressed(const Event& event)\n{\n const KeyPressedEvent& kpe = static_cast<const KeyPressedEvent&>(event);\n //Do something\n return true;\n}\n</code></pre>\n<p>There is no guarantee that the <code>Event</code> is a <code>KeyPressedEvent</code>. You want to do a dynamic_cast to make sure the code checks at runtime that this is the correct type. This will help during testing as it will help you identify bugs. Also will static_cast work if there is multiple inheritance at play?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T03:47:56.433",
"Id": "405670",
"Score": "0",
"body": "I can't find anything on `std::assert`. Or do you mean `<cassert>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T11:21:17.000",
"Id": "405707",
"Score": "0",
"body": "Thanks for reviewing my code. I fixed the bug. And made the listener be passed as reference as well as remove the listener from the manager on destruction. But I have one question. What do you mean by passing an `R-Value reference`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:38:51.977",
"Id": "405737",
"Score": "1",
"body": "Ops. I meant [static_assert](https://en.cppreference.com/w/cpp/language/static_assert)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:40:51.023",
"Id": "405738",
"Score": "0",
"body": "You can catch an R-Value with: `void Listen(EventBehavior&& behavior)` notice the double `&&`. This allows you to `std::move()` the object to its destination which allows the move constructor to be used. This prevents a copy construction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:43:55.240",
"Id": "405739",
"Score": "0",
"body": "Added example of how to use R-Value reference and move semantics."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T00:14:26.070",
"Id": "209874",
"ParentId": "209784",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209874",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T21:27:17.697",
"Id": "209784",
"Score": "2",
"Tags": [
"c++",
"event-handling"
],
"Title": "Event system implementation with Listener and a static Manager"
} | 209784 |
<p>After my last <a href="https://codereview.stackexchange.com/questions/209706/na%C3%AFve-prime-factorization-in-clojure">review request</a>, I decided to try and make a "tree" visualization, and thought that I could benefit from making <code>find-prime-factors</code> lazily produce prime factors so the visualization can be updated in real time as factors are found.</p>
<p>This is what I ended up with. I was actually surprised how easy it was to adapt the <code>loop</code> to a recursive <code>lazy-seq</code> solution. The non-return accumulators were added as parameters to a recursive function, and the lazy return list was created via the typical <code>(lazy-seq (cons ... ...))</code>. It actually performs identically to the previous strict version too when evaluation is forced using <code>vec</code>.</p>
<p>If anyone sees anything here that can be commented on, I'd like to know.</p>
<hr>
<pre><code>(doseq [p (lazily-find-prime-factors 99930610001)]
(println p
(int (/ (System/currentTimeMillis) 1000))))
163 1544998649
191 1544998692
3209797 1544998692
</code></pre>
<hr>
<p>Same as in the last review:</p>
<pre><code>(ns irrelevant.prime-factorization.prime-factorization)
(defn is-factor-of? [n multiple]
(zero? (rem n multiple)))
(defn prime? [n]
(or (= n 2) ; TODO: Eww
(->> (range 2 (inc (Math/sqrt ^double n)))
(some #(is-factor-of? n %))
(not))))
(defn primes []
(->> (range)
(drop 2) ; Lower bound of 2 for the range
(filter prime?)))
(defn smallest-factor-of? [n possible-multiples]
(some #(when (is-factor-of? n %) %)
possible-multiples))
</code></pre>
<hr>
<p>Updated:</p>
<pre><code>(defn lazily-find-prime-factors [n]
(letfn [(rec [remaining remaining-primes]
(when-let [small-prime (and (> remaining 1)
(smallest-factor-of? remaining remaining-primes))]
(lazy-seq
(cons small-prime
(rec (long (/ remaining small-prime))
(drop-while #(not= % small-prime) remaining-primes))))))]
(rec n (primes))))
</code></pre>
| [] | [
{
"body": "<p>All that the <code>lazily-find-prime-factors</code> function needs is the <code>(primes)</code> sequence. You just keep trying each in turn. Your <code>smallest-factor-of</code> drops the failed factors, but forgets what it has done, so you have to do it again for the recursive call. </p>\n\n<p>And I'd rename your <code>is-factor-of?</code> function:</p>\n\n<pre><code>=> (is-factor-of? 4 2)\ntrue\n=> (is-factor-of? 2 4)\nfalse\n</code></pre>\n\n<p>... reads wrongly. I've called it <code>divides-by?</code>.</p>\n\n<p>I end up with ... </p>\n\n<pre><code>(defn lazily-find-prime-factors [n]\n (letfn [(rec [remaining remaining-primes]\n (when (> remaining 1)\n (let [rp (drop-while #(not (divides-by? remaining %)) remaining-primes)\n small-prime (first rp)]\n (lazy-seq (cons small-prime\n (rec (quot remaining small-prime) rp))))))]\n (rec n (primes))))\n</code></pre>\n\n<p>Factoring the problem this way, you can easily plug in an efficient way of generating primes. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:33:15.037",
"Id": "221850",
"ParentId": "209786",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221850",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T22:14:11.740",
"Id": "209786",
"Score": "0",
"Tags": [
"primes",
"clojure"
],
"Title": "Naïve Prime Factorization in Clojure Pt. 2"
} | 209786 |
<p>I'm attempting to create a function that will select the correct carton based on the qty of the carton content.</p>
<p>Here are my cartons that have the number of items they can hold:</p>
<blockquote>
<pre><code>SMALL_PASCAL = 300
BIG_PASCAL = 600
BABY_BOX = 1200
A485_1201 = 1800
A4140_1901 = 3000
A485 = 5000
</code></pre>
</blockquote>
<p>And here is the method that will return the <code>CartonType</code>:</p>
<pre><code>/// <summary>
/// Get Carton Type
/// </summary>
/// <param name="qty"></param>
/// <returns></returns>
[Test]
private static CartonType GetCartonType(int qty)
{
if (qty <= 300)
{
return CartonType.SMALL_PASCAL;
}
else if (qty > 300 && qty <= 600)
{
return CartonType.SMALL_PASCAL;
}
else if (qty > 600 && qty <= 1200)
{
return CartonType.BABY_BOX;
}
else if (qty > 1200 && qty <= 1800)
{
return CartonType.A485_1201;
}
else if (qty >1800 && qty <=3000)
{
return CartonType.A4140_1901;
}
else // 5000 or more.
{
return CartonType.A485;
}
}
</code></pre>
<p>Calling the method like so:</p>
<pre><code>int qty = 1540;
Console.WriteLine(GetCartonType(qty));
</code></pre>
<p>Output:</p>
<pre><code>A485_1201
</code></pre>
<p>Is there a better way to achieve this rather than an <code>if</code> statement? Also, I just had a thought that what if the qty is like 10,000? I would then require 2 A485.</p>
| [] | [
{
"body": "<blockquote>\n <p>Is there a better way to achieve this rather than an If statement?</p>\n</blockquote>\n\n<p>Yes. You could have an enumeration of the container types and their capacities, in increasing order by capacity,\nloop over in order,\nand as soon as you find one that's big enough, return it.</p>\n\n<p>It's perhaps easier to see after you simplify the if-else chain,\nby removing redundant conditions, for example:</p>\n\n<pre><code> if (qty <= 300)\n {\n return CartonType.SMALL_PASCAL;\n }\n if (qty <= 600)\n {\n return CartonType.SMALL_PASCAL;\n }\n if (qty <= 1200)\n {\n return CartonType.BABY_BOX;\n }\n // ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T23:21:00.957",
"Id": "405463",
"Score": "0",
"body": "do you have any suggestion if there is for anything over 5000? so eg the largest box and a small pascal could be required?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T23:23:43.820",
"Id": "405464",
"Score": "2",
"body": "@user1234433222 sure, but we don't implement feature requests here... You could subtract from the quantity the capacity of the selected container, and then call the method again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T23:24:35.837",
"Id": "405465",
"Score": "0",
"body": "Thanks for that, working backwards might be the key to this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T23:10:28.933",
"Id": "209789",
"ParentId": "209788",
"Score": "4"
}
},
{
"body": "<h3>Bug</h3>\n\n<p>There is a bug in your example where you are using <code>SMALL_PASCAL</code> twice:</p>\n\n<blockquote>\n<pre><code> if (qty <= 300)\n {\n return CartonType.SMALL_PASCAL;\n }\n else if (qty > 300 && qty <= 600)\n {\n return CartonType.SMALL_PASCAL;\n }\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h3>More flexibility with <em>free</em> mappings</h3>\n\n<p>I would take a different approach for the other answer. Quantities are something that might change in time or be different in different contexts so I wouldn't use them as <code>enum</code> or <code>const</code> values but instead created a <em>pure</em> <code>enum</code> first:</p>\n\n<pre><code>public enum CartonType\n{\n Undefined = 0,\n SMALL_PASCAL,\n BIG_PASCAL,\n BABY_BOX,\n A485_1201,\n A4140_1901,\n A485,\n Default = A485\n}\n</code></pre>\n\n<p>where there are two new items: <code>Undefined</code> and <code>Default</code> - that we can conveniently use in a new extension method. It would map <code>Quantity</code> to <code>CartonType</code> for any collection:</p>\n\n<pre><code>public static CartonType GetCartonType(this int quantity, IEnumerable<(int Quantity, CartonType Type)> mappings)\n{\n var mapping = mappings.FirstOrDefault(m => quantity <= m.Quantity);\n return \n mapping.Type == CartonType.Undefined \n ? CartonType.Default \n : mapping.Type;\n}\n</code></pre>\n\n<p>With this you can specify different quantities if necessary and use them as a parameter:</p>\n\n<pre><code>var quantityCartonTypeMappings = new(int Quantity, CartonType Type)[]\n{\n (300, CartonType.SMALL_PASCAL),\n (600, CartonType.BIG_PASCAL),\n};\n\nvar quantity = 700;\n\nvar cartonType = quantity.GetCartonType(quantityCartonTypeMappings);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:14:39.527",
"Id": "209812",
"ParentId": "209788",
"Score": "3"
}
},
{
"body": "<p>I am not a big fan of \"smart\" <code>enum</code> because they do not scale well (what if you will have a more complex logic?) and they force you to spread business logic all around in your code. Because of this - in most cases - I'd suggest to use the approach in <a href=\"https://codereview.stackexchange.com/a/209812/13424\">t3chb0t's answer</a> (\"mapping\" might be even moved to a separate configuration/rule file).</p>\n\n<p>For simple cases you have, however, an easier approach:</p>\n\n<pre><code>enum CartonType\n{\n SMALL_PASCAL = 300,\n BIG_PASCAL = 600,\n BABY_BOX = 1200,\n A485_1201 = 1800,\n A4140_1901 = 3000,\n A485 = 5000,\n}\n\nCartonType GetCartonType(int quantity)\n{\n return Enum.GetValues(typeof(CartonType))\n .Cast<CartonType?>()\n .OrderByDescending(x => x)\n .LastorDefault(x => quantity <= (int)x) ?? CartonType.A485;\n}\n</code></pre>\n\n<p>I don't like that <code>CartonType.A485</code> hard-coded default then you might need to make it slightly more complex:</p>\n\n<pre><code>CartonType GetCartonType(int quantity)\n{\n var types = Enum.GetValues(typeof(CartonType));\n var biggest = types.Cast<CartonType>().Max();\n\n return types\n .Cast<CartonType?>()\n .OrderByDescending(x => x)\n .LastOrDefault(x => quantity <= (int)x) ?? biggest;\n}\n</code></pre>\n\n<p>Simply used like this:</p>\n\n<pre><code>Debug.Assert(GetCartonQuantity(100) == CartonType.SMALL_PASCAL);\nDebug.Assert(GetCartonQuantity(1000) == CartonType.BABY_BOX);\nDebug.Assert(GetCartonQuantity(10000) == CartonType.A485);\n</code></pre>\n\n<p><strong>Note</strong>: if you put this \"business knowledge\" inside your <code>enum</code> then you must write proper tests not only for <code>GetCartonQuantity()</code> but also for <code>CartonType</code> itself (to be sure values are consistent).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:37:44.830",
"Id": "209815",
"ParentId": "209788",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-16T23:01:56.210",
"Id": "209788",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Selecting correct carton based on qty"
} | 209788 |
<p>I want to return all of the permutations of an integer in Swift. </p>
<pre><code>var outputArray = [[Int]]()
func perms ( _ input: [Int], _ output: [Int]) {
if input.count == 0 {
outputArray.append( [ Int( output.map{ String($0) }.joined() )! ] )
}
else {
for i in 0..<input.count {
let current = [input[i]]
let before = Array( input [0..<i] )
let after = Array( input [(i + 1) ..< input.count] )
perms(before + after, current + output)
}
}
}
func permsOfInteger(_ input: Int) -> [[Int]] {
var inp = input
var inpArray = [Int]()
while inp > 0 {
inpArray.append(inp % 10)
inp = inp / 10
}
perms(inpArray, [])
return (outputArray)
}
</code></pre>
<p>( permsOfInteger(5432) )</p>
<p>I don't want to switch the algorithm (I'm aware of Heap's algorithm) but rather improve my implementation here. Any advice?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T02:15:18.073",
"Id": "405473",
"Score": "1",
"body": "Just a quick clarification - can you elaborate on what it means to permute an integer? Do you mean generate all the permutations of the numerals that make up the number? Like the number 123 would generate \"123\", \"132\", \"213\", \"231\", \"312\", \"321\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T02:16:24.773",
"Id": "405474",
"Score": "0",
"body": "Exactly. That is correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T19:26:52.200",
"Id": "405623",
"Score": "0",
"body": "`Int.max`, `0`, and `-123` are also integers but would cause a crash. This code is slow for many reasons. Have a look [here](https://codereview.stackexchange.com/questions/158798/on-knuths-algorithm-l-to-generate-permutations-in-lexicographic-order) and [there](https://codereview.stackexchange.com/questions/158799/sequence-based-enumeration-of-permutations-in-lexicographic-order) for inspiration. This [one](https://codereview.stackexchange.com/questions/202994/sequence-based-enumeration-of-permutations-with-heaps-algorithm) is also good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T20:52:37.277",
"Id": "405639",
"Score": "0",
"body": "In addition, this code doesn't work for numbers with duplicate digits: There should be only one possible permutation for numbers like `1111`, ..."
}
] | [
{
"body": "<p><code>permsOfInteger</code> uses math operations divide and module to convert an <code>Int</code> to an array. By contrast, <code>perms</code> converts digits to strings and joins them to convert an array to <code>Int</code>. I think it's good to be consistent, I would use math operations for converting in both directions. And I would extract these operations to helper methods <code>intToDigits</code> and <code>digitsToInt</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T07:18:35.453",
"Id": "209800",
"ParentId": "209791",
"Score": "2"
}
},
{
"body": "<p>My main point of criticism is that the code uses a <em>global variable</em> to share data between the main function and the auxiliary function. That is problematic for various reasons:</p>\n\n<ul>\n<li>The variable must be reset before the function can be called again.</li>\n<li>The variable can be modified from outside of your function, causing\nwrong results.</li>\n<li>The function is not thread-safe.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>print(permsOfInteger(12)) // [[12], [21]]\nprint(permsOfInteger(12)) // [[12], [21], [12], [21]]\n</code></pre>\n\n<p>So</p>\n\n<pre><code>var outputArray = [[Int]]()\n</code></pre>\n\n<p>should be a local variable of <code>func permsOfInteger()</code>. You can then pass it as an “inout argument” to the helper function <code>func perms()</code>, or make that helper function a nested function of the main function:</p>\n\n<pre><code>func permsOfInteger(_ input: Int) -> [[Int]] {\n\n var outputArray = [[Int]]()\n\n func perms (_ input: [Int], _ output: [Int]) {\n // ... adds something to `outputArray` ...\n }\n\n // ...\n perms(inpArray, [])\n return (outputArray)\n}\n</code></pre>\n\n<p>Why is the return type a <em>nested</em> array where each “integer permutation” is wrapped into a single-element array? Returning a simple array of integers seems more natural to me, and would be more efficient:</p>\n\n<pre><code>func permsOfInteger(_ input: Int) -> [Int] {\n // ...\n}\n\nprint(permsOfInteger(12)) // [12, 21]\n</code></pre>\n\n<p>As @janos already said, combining the digits to an integer should be done in “pure maths” instead of using string operations. This can be done with <code>reduce()</code>, for example:</p>\n\n<pre><code>let digits = [1, 2, 3]\nlet number = digits.reduce(0, { $0 * 10 + $1 })\nprint(number) // 123\n</code></pre>\n\n<p>An <code>[UInt8]</code> array would be sufficient to store the decimal digits and save some memory. Here is a possible implementation as a computed property and custom initializer of the <code>Int</code> type:</p>\n\n<pre><code>extension Int {\n var decimalDigits: [UInt8] {\n precondition(self >= 0, \"Value must not be negative\")\n var digits = [UInt8]()\n var n = self\n while n > 0 {\n digits.append(UInt8(n % 10))\n n /= 10\n }\n return digits\n }\n\n init(decimalDigits: [UInt8]) {\n self = decimalDigits.reduce(0, { $0 * 10 + Int($1) })\n }\n}\n</code></pre>\n\n<p>The slicing</p>\n\n<blockquote>\n<pre><code>let before = Array(input[0..<i])\nlet after = Array(input[(i + 1) ..< input.count])\n</code></pre>\n</blockquote>\n\n<p>can be slightly shorted with <em>partial ranges:</em></p>\n\n<pre><code>let before = Array(input[..<i])\nlet after = Array(input[(i + 1)...])\n</code></pre>\n\n<p>An alternative would be to remove the current element from the input array:</p>\n\n<pre><code>var remaining = input\nlet current = [remaining.remove(at: i)]\nperms(remaining, current + output)\n</code></pre>\n\n<p>Instead of <code>if input.count == 0</code> you can test <code>if input.isEmpty</code> – it does not make a difference for arrays, but can be more efficient for arbitrary collections, where determining the <code>count</code> requires a traversal of the entire collection.</p>\n\n<p>For the same reason you might want to replace</p>\n\n<blockquote>\n<pre><code>for i in 0..<input.count { ... }\n</code></pre>\n</blockquote>\n\n<p>by </p>\n\n<pre><code>for i in input.indices { ... }\n</code></pre>\n\n<p>since collection indices are not always zero based.</p>\n\n<p>Finally, I would suggest some more descriptive variable names and argument names. Putting it all together, the function could look like this:</p>\n\n<pre><code>func permutations(of number: Int) -> [Int] {\n\n var permutations = [Int]()\n\n func addPermutations(of digits: [UInt8], withSuffix suffix: [UInt8]) {\n if digits.isEmpty {\n permutations.append( Int(decimalDigits: suffix) )\n } else {\n for i in digits.indices {\n var remainingDigits = digits\n let currentDigit = [remainingDigits.remove(at: i)]\n addPermutations(of: remainingDigits, withSuffix: currentDigit + suffix)\n }\n }\n }\n\n addPermutations(of: number.decimalDigits, withSuffix: [])\n return (permutations)\n}\n\nprint(permutations(of: 123))\n// [123, 213, 132, 312, 231, 321]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T20:33:43.903",
"Id": "213671",
"ParentId": "209791",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209800",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T00:20:46.523",
"Id": "209791",
"Score": "3",
"Tags": [
"swift"
],
"Title": "Swift permutations of the digits of an Integer"
} | 209791 |
<p>I wrote the Sierpinski’s Gasket Triangle in JavaScript, but I feel the code can be better, especially from <a href="https://github.com/zeyadetman/chaos/blob/949f1f8b414f0da382e4501807a2f675dd29684a/index.js#L32" rel="nofollow noreferrer">L32 to L47</a>. Could you make it more organized?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.getElementById('chaos');
var ctx = canvas.getContext('2d');
const GenerateRand = () => Math.floor(Math.random() * 7);
const updateDot = (x, y, point) => {
let X = Math.min(x,point.x)+(Math.max(x,point.x)-Math.min(x,point.x))/2;
let Y = Math.min(y,point.y)+(Math.max(y,point.y)-Math.min(y,point.y))/2;
return {x: X, y: Y};
}
const createDot = (obj) => {
ctx.beginPath();
ctx.arc(obj.x, obj.y, 1, 0, 2 * Math.PI, false);
ctx.lineWidth = 1;
ctx.strokeStyle = '#fc3';
ctx.stroke();
}
const pA = {x: canvas.width/2, y: 5};
const pB = {x: 5, y: canvas.height-5}
const pC = {x: canvas.width-5, y: canvas.height-5}
createDot(pA);
createDot(pB);
createDot(pC);
const begin = (iterations) => {
let x = canvas.width/4;
let y = canvas.height/2;
for(let i=0;i<iterations;i++) {
createDot({x, y});
let randN = GenerateRand();
if(randN == 1 || randN == 2) {
const currentDot = updateDot(x, y, pA);
x = currentDot.x;
y = currentDot.y;
}
else if(randN == 3 || randN == 4) {
const currentDot = updateDot(x, y, pB);
x = currentDot.x;
y = currentDot.y;
}
else if(randN == 5 || randN == 6){
const currentDot = updateDot(x, y, pC);
x = currentDot.x;
y = currentDot.y;
}
}
}
let time=0;
let timer = setInterval(() => {
if(time >= 500) return clearInterval(timer)
begin(500);
time++;
}, 200);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<canvas id="chaos" width="500" height="500"></canvas>
</div></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Performance</h2>\n<ul>\n<li>For positive numbers < 2 ^ 31 use <code>num | 0</code> (bitwise or zero) to floor</li>\n<li>You are drawing an arc that is 1 pixel in radius, with the stroke width of 1 the diameter is 3 pixels. This covers an area much greater than the point you sample. Use <code>fillRect</code> to draw a single pixel as its much quicker. Better yet as they are all the same color create a single path and use <code>ctx.rect</code> to add to it. Render all rect in one pass at the end of <code>begin</code> function.</li>\n<li>Avoid creating objects needlessly. Create a working object and use that to hold intermediate values. This can greatly reduce memory allocation and GC overheads. Eg the object you return in <code>updateDot</code> is a waste of memory and time.</li>\n<li>If you test two numbers to find the max or min, knowing either means you also know the other and thus do not need to test for it. The long lines <code>Math.min(p.y, p1.y) + (Math.max(p.y, p1.y) - Math.min(p.y, p1.y)) / 2</code> can be reduced by a single test and give significant performance improvement.</li>\n</ul>\n<h2>Style</h2>\n<ul>\n<li>Use <code>const</code> for constants. Eg <code>canvas</code> and <code>ctx</code> should be <code>const</code>.</li>\n<li>Capitals only for names of objects that are instantiated with the <code>new</code> token. Eg <code>GenerateRand</code> should be <code>generateRand</code></li>\n<li>Avoid repeated code by using functions. Eg you create many instances of an object {x,y}, would be better as a function.</li>\n<li>Spaces between operators, commas, etc.</li>\n<li>Use <code>===</code> rather than <code>==</code></li>\n<li><code>else</code> on the same line as the closing <code>}</code></li>\n<li>The final statement in function <code>begin</code> does not need the test <code>(randN == 5 || randN == 6)</code> (assuming you want a new point each iteration)</li>\n</ul>\n<h2>Code</h2>\n<p>The random number generated is from 0 to 6 and you ignore 0, redrawing the same point 1 in 7 times. You can reduce the random to give 3 values 0,1,2 and perform the correct calculation on that or use a counter and cycle the points.</p>\n<p>You could also put the points <code>pA</code>, <code>pB</code>, <code>pC</code> in an array and index them directly via the random number.</p>\n<p>Rather than use <code>setInterval</code>, use <code>setTimeout</code>. That way you don't need to clear the timer each time.</p>\n<p>Put magic numbers in one place and name them as constants.</p>\n<p>You reset the start point each time <code>delay</code> is called (first two lines). Better to just let it keep going. It may also pay to stop the rendering after a fixed amount of points have been rendered.</p>\n<h2>The rewrite.</h2>\n<p>This is just an example of the various points outlined above.</p>\n<p>Also a few modifications</p>\n<ul>\n<li>Automatically adjust number of points rendered to keep the GPU load steady.</li>\n<li>Stop rendering after a fixed number of points rendered.</li>\n<li>The starting points <code>pA,pB,pC</code> are in an array.</li>\n<li>Magic numbers as constants.</li>\n<li>Using a single render path to draw all points per render cycle.</li>\n<li>Using a working point <code>wPoint</code> to hold coordinates rather than create a new point for each point rendered.</li>\n</ul>\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 ctx = canvas.getContext('2d');\n\n\nconst padding = 5;\nconst renderDelay = 200;\nconst maxTime = 2; // time in ms allowed to render points.\nconst maxPointsToDraw = canvas.width * canvas.height * (1 / 3); \n\nvar pointsPerRender = 500; // points to render per render pass\nvar totalPoints = 0; // count of total points drawn\nctx.fillStyle = '#fc3';\n\nconst generateRand = () => Math.random() * 3 | 0;\nconst point = (x, y) => ({x, y});\nconst drawDot = p => ctx.rect(p.x, p.y, 1, 1);\n\nconst updateDot = (p, p1) => {\n p.x = p.x < p1.x ? p.x + (p1.x - p.x) / 2 : p1.x + (p.x - p1.x) / 2;\n p.y = p.y < p1.y ? p.y + (p1.y - p.y) / 2 : p1.y + (p.y - p1.y) / 2;\n return p;\n}\n\nconst points = [\n point(canvas.width / 2, padding),\n point(padding, canvas.height - padding),\n point(canvas.width - padding, canvas.height - padding)\n];\nconst wPoint = point(canvas.width / 4, canvas.height / 2); // working point\n\n\nconst renderPoints = iterations => {\n totalPoints += iterations;\n \n const now = performance.now(); \n ctx.beginPath();\n while (iterations --) { drawDot(updateDot(wPoint, points[generateRand()])) }\n ctx.fill();\n const time = performance.now() - now;\n\n // use render time to tune number points to draw \n // Calculates approx time per point and then calcs number of points\n // to render next time based on that speed.\n // Note that security issues mean time is rounded to much higher\n // value than 0.001 ms so must test for 0 incase time is zero\n pointsPerRender = maxTime / ((time ? time : 0.1)/ pointsPerRender);\n\n if (totalPoints < maxPointsToDraw) {\n setTimeout(renderPoints, renderDelay, pointsPerRender | 0);\n }\n}\nrenderPoints(pointsPerRender);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\" width=\"500\" height=\"500\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T12:17:27.843",
"Id": "405715",
"Score": "0",
"body": "Thank you so much, I'll consider them from now on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:28:11.117",
"Id": "209824",
"ParentId": "209792",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209824",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T02:28:23.997",
"Id": "209792",
"Score": "4",
"Tags": [
"javascript",
"animation",
"canvas",
"fractals"
],
"Title": "Sierpinski’s Gasket Triangle in JavaScript"
} | 209792 |
<p>It was suggested I place this code here. I had posted it on StackOverflow for a kind of review.</p>
<p>I have tried to generate Hamming numbers using primes but the speed of the generation slows the higher the number generated and the prime list grew proportionately. I then started to find if a number could be factored down to 2,3 or 5. This was faster but still far away from linear.</p>
<p>Then I found in Excel that a candidate number when evenly divided by one of 2,3 or 5 can be found in previously generated hamming numbers if it is itself a Hamming number. </p>
<p>I thought this approach would result in faster Hammond number generation.</p>
<p>I have played with generating the last of a large set of Hamming numbers using my standard methods. Once the final set is generated all previous Hammings can selectively be extracted from it. The last set just takes to long to generate even though once it is, the speed becomes linear. I just need a faster way to generate any Hamming list.</p>
<p>I do not know if anyone has ever tried to exploit the fact that each successive candidate number can be tested for Hamming status by dividing it by one of 2,3 or 5 and testing if the quotient is a member of the Hamming list generated to that point. </p>
<p>The function takes two parameters, a seed list of (reversed) Hamming numbers less than 10 and a candidate list of any size. I prefer to us a list of [2,3,5] multiples I call <code>base</code></p>
<pre><code>base = scanl (\b a -> a+b) 2 $ cycle [1,1,1,1,2,1,1,2,2,1,1,2,2,1,1,2,1,1,1,1,2,2]
hamx ls (x:xs)
| even x && elem (div x 2) ls = hamx (x:ls) xs
| mod x 3 == 0 && elem (div x 3) ls = hamx (x:ls) xs
| mod x 5 == 0 && elem (div x 5) ls = hamx (x:ls) xs
| null xs = ls
| otherwise = hamx ls xs
</code></pre>
<p>I tried <code>filter</code> and <code>any</code> and others in place of <code>elem</code>. The list generates in reverse. The <code>elem</code> finds Hamming matches faster from the bottom and new Hamming numbers appear also at the bottom. So, the bottom is the top.</p>
<p>I am now working on the 2,3,5 Hamming multiples used in other algorithms. I know how not to generate duplicates. I might be able to integrate these select multiples into the above code. For example, the select list will only use 15 multiples of 5 in 6,103,515,625. All of the 10s are already in the 2 multiples and many 5 multiples are found in 3 multiples. The only 3 multiples needed are from odd Hamming numbers. All 2 multiples are needed.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:24:24.713",
"Id": "405566",
"Score": "0",
"body": "Welcome to Code Review. Unfortunately, this question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226). A short description of the Hamming sequence will ease the life of reviewers and make it more likely that your code gets properly reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T13:30:27.133",
"Id": "406314",
"Score": "0",
"body": "see [this](https://codereview.stackexchange.com/a/110681/9064) for a related discussion, of the code based on the idea not unlike the one in your question."
}
] | [
{
"body": "<p>The main problem is that <code>elem</code> traverses list and that is slow. It is better to use <a href=\"http://hackage.haskell.org/package/containers-0.6.0.1/docs/Data-Set.html\" rel=\"nofollow noreferrer\"><code>Data.Set</code></a> or <a href=\"http://hackage.haskell.org/package/unordered-containers-0.2.9.0/docs/Data-HashMap-Strict.html\" rel=\"nofollow noreferrer\"><code>HashMap</code></a> as this data structures allow sub-linear membership checking.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import qualified Data.Set as Set\n\nhamx :: [Integer] -> [Integer] -> [Integer]\nhamx ls = reverse . Set.toList . loop (Set.fromList ls)\n where\n loop res [] = res\n loop res (x:xs)\n | even x && Set.member (div x 2) res = loop (Set.insert x res) xs\n | mod x 3 == 0 && Set.member (div x 3) res = loop (Set.insert x res) xs\n | mod x 5 == 0 && Set.member (div x 5) res = loop (Set.insert x res) xs\n | otherwise = loop res xs\n</code></pre>\n\n<p>Or a bit shorter (but less readable) version:</p>\n\n<pre><code>import Data.List (foldl')\nimport qualified Data.Set as Set\n\nhamx :: [Integer] -> [Integer] -> [Integer]\nhamx ls = reverse . Set.toList . loop (Set.fromList ls)\n where\n loop = foldl' (\\res x -> if predicate res x then Set.insert x res else res)\n predicate res x = any (\\y -> mod x y == 0 && Set.member (div x y) res) [2, 3, 5]\n</code></pre>\n\n<hr>\n\n<p>Using <a href=\"http://hackage.haskell.org/package/containers-0.6.0.1/docs/Data-IntSet.html\" rel=\"nofollow noreferrer\"><code>IntSet</code></a> instead of <code>Set</code> is several times faster, but <a href=\"https://stackoverflow.com/a/12482407/147057\">Daniel Fischer's solution</a> is still several orders of magnitude faster.</p>\n\n<p>I put a project with <a href=\"http://hackage.haskell.org/package/criterion\" rel=\"nofollow noreferrer\">criterion</a> benchmark <a href=\"https://github.com/jorpic/playground/tree/master/hamming-numbers\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T22:30:58.323",
"Id": "405645",
"Score": "0",
"body": "Ha, I had my logic in a `foldl'`, too but with `elem` also but also with a function to divide the candidate numbers by a select factor of one of [2,3,5]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T03:00:28.617",
"Id": "405666",
"Score": "0",
"body": "The top rendition is faster. Neither require `reverse` because `res` is not constructed in reverse. My result `ls` was constructed in reverse for speed of `':'` vs. ``++`` and for search from the end of the list which was closer to a match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T07:50:17.807",
"Id": "405800",
"Score": "0",
"body": "I copy-pasted your code from Github to my GHCi and ran `hamx n` with `n` in `[200,300,400,500]` and each time the run time increased three-fold. This means *the algorithm* is exponential in `n`. The other, classic, algo is of course linear, so there is no one speedup factor to give between the two (re \"several orders of magnitude\"). It simply does not exist. Saying that one code is X times faster than the other implies that both are in the same Theta complexity class. --- (a side note: I'd use a descriptive name for `predicate`, like `keep`.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T21:25:41.137",
"Id": "209864",
"ParentId": "209794",
"Score": "2"
}
},
{
"body": "<p>A review of a computational code starts with reviewing the <em>algorithm</em> it uses.</p>\n\n<p>Here's a kicker. Your algorithm in exponential, or worse, whereas the well-known \"classic\" algorithm is linear.</p>\n\n<p>This means your code is <em>spectacularly</em> slower, <strong><em>incomparably</em></strong> slower. </p>\n\n<p>Why are your algorithm exponential <em>(at least)</em>? It is because in order to produce <em>n</em> first Hamming numbers you are testing <em>all</em> the natural numbers below the <i>n</i>th Hamming number. But the <i>n</i>th Hamming number is on the order of <i>~ exp (n<sup>1/3</sup>)</i> in magnitude, <a href=\"https://en.wikipedia.org/wiki/Regular_number#Number_theory\" rel=\"nofollow noreferrer\">according to Wikipedia</a>.</p>\n\n<p>The \"classic\" algorithm is <strong><em>linear</em></strong> in <em>n</em>. So is the <strong><em>improved</em></strong> algorithm (used in the two older answers on \n<a href=\"https://stackoverflow.com/questions/12480291/new-state-of-the-art-in-unlimited-generation-of-hamming-sequence\">the SO entry</a> where you've <a href=\"https://stackoverflow.com/questions/12480291/new-state-of-the-art-in-unlimited-generation-of-hamming-sequence/53842595#53842595\">posted</a> your code), which is faster than the \"classic\" one by about a constant factor of <em>2</em>. I think anyone will agree that exponential algorithm is <em>no improvement</em> to the linear, <em>quite the contrary</em>.</p>\n\n<p>Since the algorithm in your question is so abominably slow, any other considerations about your code will pale in comparison.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:06:45.377",
"Id": "406114",
"Score": "0",
"body": "Math is a tautology. That in no way detracts from it as the highest endeavor. The converse of “exponential algorithm is no improvement” is a tautology but benefits likewise. My motivation for writing code is at odds with yours and CR. Subsets of Hamming numbers can be calculated. There is a relationship to primes and algebras. All numbers in the 10^n set are contained in 10^n+1 set by taking the 0 (mod 10)s and dividing by 10. This is part of my interest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:18:37.157",
"Id": "406120",
"Score": "0",
"body": "To late editing, *all numbers in 10^(0-n) are contained in 10^n+1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T07:38:47.007",
"Id": "406524",
"Score": "1",
"body": "yes, you're right, math doesn't care for speed, only correctness. Fibonaccis are Fibonaccis whether defined with a linear, logarithmic, or exponential code. but in programming we also have speed and memory space considerations, and we generally prefer the faster solution, and search for it diligently. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T21:46:43.727",
"Id": "210077",
"ParentId": "209794",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T03:59:04.623",
"Id": "209794",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Haskell Hamming Sequence Logic"
} | 209794 |
<p>Here is code implementing <a href="http://www.passportjs.org/" rel="nofollow noreferrer">Passport</a> authentication with a Google Strategy. It uses <a href="http://mongoosejs.com/" rel="nofollow noreferrer">Mongoose</a> to store and retrieve user data.</p>
<p>You might need to be familiar with both of these technologies to review this code if not check out the two links I provided.</p>
<p>I have included only the Passport file. I was told I am not using promises correctly and would like to rectify this if it is in fact true.</p>
<p>The code is full of comments below. Please let me know if more clarification or context is needed.</p>
<p>Thanks for any feedback.</p>
<p><strong>Passport</strong></p>
<pre><code>const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const DBM = require('../../database/mongoose');
const helper = require('../../config/helper');
// review this post
// https://stackoverflow.com/questions/50339887/can-i-reduce-this-passport-code
// configure Passport to use Google Auth
passport.use('google', new GoogleStrategy(helper.getPassport(), getOrCreateUser));
// passed to passport, this is the starting point for Google Auth
function getOrCreateUser (accessToken, refreshToken, profile, done) {
// abstracts out relevant information from what Google returns
const user_props = obtainProps(profile);
DBM.getUser(user_props.id_google).then( (res) => {
// res[0] will be "true" if the user exists
return res[0] ? done(null, user_props) : createUser(done, user_props);
}).catch( error => {
return done(error, null);
});
}
// the user was not found, create the user
function createUser (done, user_props) {
DBM.createUser(user_props).then(() => {
return done(null, user_props);
}).catch( error => {
return done(error, null);
});
}
// serializeUser required by passport to identify the user uniquely on the client
passport.serializeUser( (profile, done) => {
done(null, profile.id_google);
});
// deserializeUser required by passport to retrieve data on the server using unique
// identifier created by serializeUser
passport.deserializeUser( (id_google, done) => {
DBM.getUser(id_google).then((res) => {
done(null, res[0]);
}).catch( (error) => {
console.error('DBM.getUser() Error: ', error);
});
});
// takes a profile from Google and extracts parameters to save
function obtainProps (profile) {
let props = {};
props.id_google = profile.id;
props.email = profile.emails[0].value;
props.name = profile.displayName;
props.pic_url = profile.photos[0].value;
props.type = profile._json.objectType;
return props;
}
module.exports = passport;
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>When writing your custom functions that operate on promises, a good habit is to return resulting promises in order to have ability to chain them. For instance:</p>\n\n<p><code>return DBM.getUser(user_props.id_google).then( (res) => {</code> (from <code>getOrCreateUser</code>)<br/>\nor:<br/>\n<code>return DBM.createUser(user_props).then(() => {</code></p></li>\n</ol>\n\n<p>It will ensure that <code>getOrCreateUser</code> and <code>createUser</code> operations will be chained together properly.</p>\n\n<ol start=\"2\">\n<li><p>The <code>passportjs</code> uses different API. It does not use promises but callbacks. \nAs I see, you mixed them together by mistake! For instance in <code>DBM.createUser</code> from inside your promise you returned an object returned just by <code>done</code> callback when resulting value/other promise is expected. Same in <code>DBM.getUser</code> from <code>passport.deserializeUser</code></p></li>\n<li><p>It might be only mine (a little bit nerdy) custom, but I have a habit to wrap 3rd party non promise APIs into promise adapters.</p></li>\n</ol>\n\n<p>For instance (an easy one):</p>\n\n<pre><code>function serializeUser(idProviderPromise) {\n let resultDeffered = Promise.defer();\n passport.serializeUser((profile, done) => {\n idProviderPromise(profile).then(function (profileId) {\n done(null, profileId);\n resultDeffered.resolve();\n });\n });\n return resultDeffered;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>passportPromiseApi.serializeUser(new Promise(profile => profile.id_google));\n</code></pre>\n\n<p>It can help make us sure not to mix different APIs together.</p>\n\n<p>At the first glance it can look a little bit over complicated, but please take a look how it simplifies more complex cases:</p>\n\n<pre><code>function configure(getOrCreateUserPromise) {\n let resultDeffered = Promise.defer();\n function getOrCreateUser(accessToken, refreshToken, profile, done) {\n getOrCreateUserPromise(accessToken, refreshToken, profile).then(function (userProps) {\n done(null, userProps);\n resultDeffered.resolve(userProps);\n }).catch(function (error) {\n done(error, null);\n resultDeffered.fail(error);\n });\n }\n passport.use('google', new GoogleStrategy(helper.getPassport(), getOrCreateUser));\n return resultDeffered;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>passportPromiseApi.configure(new Promise(function (accessToken, refreshToken, profile) {\n const userProps = obtainProps(profile);\n return DBM.getUser(userProps.id_google).then(res => {\n return res[0] ? Promise.resolve(userProps) : createUser(userProps);\n //Instead Promise.resolve(userProps) simply userProps should work as well\n //But it is also a good practice for return type in any JS function to be consistent.\n });\n}));\n\nfunction createUser (userProps) {\n return DBM.createUser(userProps).then(() => userProps); \n //Error handling is already done by our adapter.\n //We can focus only on business logic here!\n}\n</code></pre>\n\n<ol start=\"4\">\n<li>Last less important thing: let assume some consistent naming convention for function parameters and local variables respectively. You have to decide whether to use <code>xxx_yyy</code> or <code>xxxYyy</code> (camel case). 3-rd party usages doesn't count as it must be used exactly.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T18:46:54.653",
"Id": "209855",
"ParentId": "209795",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T04:16:32.777",
"Id": "209795",
"Score": "4",
"Tags": [
"javascript",
"promise",
"passport"
],
"Title": "Implementing Passport authentication with promises"
} | 209795 |
<p><strong>Program:</strong>
I have designed a program in python that does the following (in order):</p>
<ol>
<li>Webscrapes google trends for the most popular searches</li>
<li>Stores the searches and traffic of the searches in an in-memory database along with a timestamp </li>
<li>Finds the trends that no longer exist (I.E the trends that are no longer in googles top 20 most popular) and then searches the database for the rows in which the trend first appeared and when it disappeared in order to find how long it has been popular (I.E the duration the trend spent in googles top 20 most popular searches) </li>
</ol>
<p><strong>Context:</strong>
I have only been programming for a month now and my experience is entirely limited to python. As a result, I'm 100% certain that I'm using atrocious practices and my code is super inefficient. Hence, these are my two big concerns: 1) My program is extremely slow. 2) It's clunky and looks unpleasant to a professional. </p>
<p><strong>Issues:</strong>
Here I will try to be as comprehensive as possible as to what I think is wrong with my program:</p>
<p><em>It is slow</em>. Particularly in my third script (which corresponds to the third step) there is a giant block of code in the function inst_range. I used two while loops to search from either end of the table. If the program finds the search while counting up the rows it treats the search as the first instance of the search that exists. Likewise, if it finds the search going backwards through the table it treats it as the last instance of the search that exists. Then it computes the time between these two rows to find how long the search has been popular. <em>What is the most efficient, clear way I could express this in my code while maintaining speed?</em> </p>
<p><em>I use bad practices / it looks unappealing</em> My third script is the main culprit again. It looks very clunky to me. When I look at really good github projects they are all so readable and nice. How do I apply that to my project? Another thing I worry about is alot of the complex stuff I don't yet understand. I.E caching, threading, and different types of sorting which I should probably be using but I don't know about. Sorry to tack this bit on as well, but should I be using more OOP in my program? <em>Is it messed up?</em></p>
<p><strong>The code:</strong></p>
<p><strong>trend_parser.py</strong> (corresponds to step 1) </p>
<pre><code>import re
import requests
from bs4 import BeautifulSoup
def fetch_xml(country_code):
"""Initialises a request to the Google Trends RSS feed
Returns:
string: Unparsed html stored as a string for use by BeautifulSoup
"""
try:
url = f"https://trends.google.com/trends/trendingsearches/daily/rss?geo={country_code}"
response = requests.get(url)
return response.content
except requests.exceptions.ConnectionError:
print("failed to connect")
def trends_retriever(country_code):
"""Parses the Google Trends RSS feed using BeautifulSoup.
Returns:
dict: Trend title for key, trend approximate traffic for value.
"""
xml_document = fetch_xml(country_code)
soup = BeautifulSoup(xml_document, "lxml")
titles = soup.find_all("title")
approximate_traffic = soup.find_all("ht:approx_traffic")
return {title.text: re.sub("[+,]", "", traffic.text)
for title, traffic in zip(titles[1:], approximate_traffic)}
</code></pre>
<p><strong>models.py</strong> (corresponds to step 2)</p>
<pre><code>from trend_parser import trends_retriever
from flask import Flask
from datetime import datetime
import os
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///trends.sqlite3"
app.config["SECRET_KEY"] = os.urandom(16)
db = SQLAlchemy(app)
class trends(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String, nullable = False)
traffic = db.Column(db.Integer, nullable = False)
time = db.Column(db.DateTime, nullable = False)
def __init__(self):
"""These are the parameters that are passed on to the database"""
self.title = f"{list(trends_retriever('US').keys())}"
self.traffic = f"{list(trends_retriever('US').values())}"
self.time = datetime.now()
</code></pre>
<p><strong>database_crawler.py</strong> (corresponds to step 3)</p>
<pre><code>from models import trends
import ast
import itertools
queried_titles = [ast.literal_eval(item.title) for item in trends.query.all()]
queried_time = [item.time for item in trends.query.all()]
def title_query():
for index, item in enumerate(itertools.count()):
try:
first_row = set(queried_titles[index])
second_row = set(queried_titles[index + 1])
removed_trend = first_row - second_row
yield removed_trend
except IndexError:
break
def inst_range():
removed_trends = list(itertools.chain(*title_query()))
row_count, row_count2 = 0, -1
for item in removed_trends:
while item not in queried_titles[row_count]:
row_count += 1
if item in queried_titles[row_count]:
first_instance = row_count
row_count = 0
while item not in queried_titles[row_count2]:
row_count2 -= 1
if item in queried_titles[row_count2]:
last_instance = len(queried_titles) - abs(row_count2)
row_count2 = -1
first_time = queried_time[first_instance]
last_time = queried_time[last_instance]
time_difference = (last_time - first_time).total_seconds() / 3600
yield item, round(time_difference, 2)
print(dict(inst_range()))
</code></pre>
<p><strong>Outputs:</strong></p>
<p><a href="https://i.stack.imgur.com/NgLBS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NgLBS.png" alt="Visualisation of database"></a></p>
<p><strong>Output of the third script</strong> (value corresponds to duration of staying in the top 20 searches, key corresponds to title of search) </p>
<pre><code>{'Chiefs': 0.24, 'The Mule': 4.28, 'KFC Firelog': 0.62, 'Yeezy': 1.46,
'Chiko Juan': 0.96, 'Dragon Ball Super: Broly full movie': 0.0, 'Roma':
4.28, 'Imagine Ariana Grande': 4.28, 'Canelo vs Rocky': 4.28, 'Chiefs
schedule': 4.28, 'Nfl playoff picture 2019': 0.0, 'Mick Mulvaney': 4.28,
'Nancy Wilson': 4.28, 'Johnson and Johnson': 4.28, 'JWoww': 4.28,
'Jabari Parker': 4.28, 'Chick-fil-A': 4.28, 'Fuller House': 2.82, 'Artie
Lange': 4.28, 'Al Roker': 4.28, 'Obamacare': 0.0, 'Bill Fralic': 4.28,
'Sandy Hook': 4.28, 'Aus vs Ind': 4.28, "Shareef O'Neal": 4.28,
'Jennifer Lawrence': 0.0, 'Alcorn State': 0.0, 'Spider-Man Spider-
Verse': 0.0, 'NFL scores': 0.0, 'Pete Davidson': 0.0, 'Chivas': 0.0,
'Juventus': 0.0, 'NFL games': 0.0, 'Fresno State football': 0.0,
'Browns': 0.0, 'Lakers vs Hornets': 0.0, 'Matt Damon': 0.0, 'DAZN': 0.0,
'Stoney Westmoreland': 0.0, 'Canelo fight December 15, 2018': 0.0, 'UNC
basketball': 0.0, 'NFL': 0.0, 'Texans': 0.0, 'Nebraska volleyball': 0.0,
'NFL schedule': 0.0, 'Chicago Bears': 0.09, 'Offset Cardi B': 0.09,
'Appalachian State football': 0.09, '76ers vs Cavaliers': 0.09}
[Finished in 0.4s]
</code></pre>
| [] | [
{
"body": "<p>First of all, to me this code looks clean, easy to read, so overall, nicely done!</p>\n\n<h3>Avoid repeated queries</h3>\n\n<p>This piece of code runs the exact same query twice:</p>\n\n<blockquote>\n<pre><code>queried_titles = [ast.literal_eval(item.title) for item in trends.query.all()]\nqueried_time = [item.time for item in trends.query.all()]\n</code></pre>\n</blockquote>\n\n<p>It would be better to run the query once and iterate over its result twice.\nOptionally, if not too inconvenient for the rest of code,\na further, less important optimization would be to iterate over the results only once, and extract pairs of title and time in one pass.</p>\n\n<p>There is another form of double-querying in the constructor of <code>trends</code>:</p>\n\n<blockquote>\n<pre><code>self.title = f\"{list(trends_retriever('US').keys())}\"\nself.traffic = f\"{list(trends_retriever('US').values())}\"\n</code></pre>\n</blockquote>\n\n<p><code>trends_retriever('US')</code> will fetch and parse an HTML document,\nso it will be good to only do it once.</p>\n\n<h3>Are some trends removed twice?</h3>\n\n<p><code>inst_range</code> chains into a <code>list</code> the sets of trends returned by <code>title_query</code>.\nI didn't analyze deeply to fully understand,\nbut isn't it possible that there can be duplicates in the resulting list?\nIf so, it would better to chain into a <code>set</code> instead of a <code>list</code>.</p>\n\n<h3>Do not use exception handling for flow control</h3>\n\n<p>This code catches <code>IndexError</code>:</p>\n\n<blockquote>\n<pre><code>for index, item in enumerate(itertools.count()):\n try:\n first_row = set(queried_titles[index])\n second_row = set(queried_titles[index + 1])\n removed_trend = first_row - second_row\n yield removed_trend\n except IndexError:\n break\n</code></pre>\n</blockquote>\n\n<p>But there is nothing unexpected about <code>IndexError</code>,\n<em>we know for certain</em> it will be raised for the last entry of <code>queried_title</code>.</p>\n\n<p>Also note that <code>item</code> is not used in the loop.\nFor unused loop variables the convention is to name them <code>_</code>.</p>\n\n<p>It seems to me that you can replace this loop with <code>for index in range(len(queried_titles) - 1)</code>.</p>\n\n<h3>Simplify logic</h3>\n\n<p>I find it hard to understand the logic in <code>inst_range</code>.\nFor example, <code>row_count</code> is incremented in a loop,\nuntil some condition is reached.\nDuring this loop, <code>row_count</code> is used as an index into a list,\nbut it's never verified if this index is valid.\nIn other words, it's not obvious that the loop is guaranteed to terminate before <code>row_count</code> goes out of range.\nAlso it's not a \"count\", it's really an <em>index</em>.\nTo add to the confusion, the variable is initialized before the outer for-loop,\nand conditionally reset to 0.</p>\n\n<p>Consider this alternative implementation, using more helper functions:</p>\n\n<pre><code>for item in removed_trends:\n first_instance = find_first_instance(queried_titles, item)\n last_instance = find_last_instance(queried_titles, item)\n first_time = queried_time[first_instance]\n last_time = queried_time[last_instance]\n time_difference = (last_time - first_time).total_seconds() / 3600\n yield item, round(time_difference, 2)\n</code></pre>\n\n<p>With the introduction of the helper methods <code>find_first_instance</code> and <code>find_last_instance</code>, the earlier doubts are simply eliminated.\nOf course, those functions need to be correctly implemented,\nbut their complexity is now hidden from this higher level code,\nand better isolated, so that it will be probably easier to read.</p>\n\n<h3>Beware of <code>x in ...</code> conditions on list</h3>\n\n<p>The implementation of <code>inst_range</code> uses many <code>x in ...</code> conditions in lists.\nKeep in mind that searching in a list is an <span class=\"math-container\">\\$O(n)\\$</span> operation:\nin the worst case, all elements will be checked.\nThe performance penalty can become even worse when this is part of a nested loop.</p>\n\n<p>I haven't looked deeply into your code,\nbut probably you can optimize this part by building two dictionaries:</p>\n\n<ol>\n<li>the first time a trend was seen</li>\n<li>the last time a trend was seen</li>\n</ol>\n\n<p>You could build these dictionaries by looping over trends and their times in one pass:</p>\n\n<ul>\n<li>if <code>trend not in first</code>, then <code>first[trend] = time</code></li>\n<li><code>last[trend] = time</code></li>\n</ul>\n\n<p>This will be more efficient, because <code>key in ...</code> conditions on dictionaries is an <span class=\"math-container\">\\$O(1)\\$</span> operation, and so is <code>d[key] = ...</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T08:50:18.200",
"Id": "209808",
"ParentId": "209798",
"Score": "5"
}
},
{
"body": "<p>In addition to @janos’s point about exception handling:</p>\n\n<p>Don’t handle exceptions if there is nothing you can do about them. <code>fetch_xml()</code> catches the <code>ConnectionError</code>, prints a message, and then ...? Does nothing! The end of the function is reached without returning anything, so <code>None</code> is returned to the caller. </p>\n\n<p><code>trends_retriever()</code> gets the <code>None</code> value, and doesn’t do anything special, so probably causes other exceptions by passing <code>None</code> to <code>BeautifulSoup()</code>!</p>\n\n<p>If you didn’t catch the exception, the exception would have percolated right through <code>trends_retriever()</code> to its caller, without it having to do anything special or causing further issues. If you want to print (or log) the exception, but can’t really handle it, consider re-raising it, or raising a different one, perhaps with the current one as a “cause”. </p>\n\n<p>The main program is an exception. It is allowed to catch and print a message for expected exceptions, to present a more professional looking output, instead of looking like an unexpected crash. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T20:10:08.153",
"Id": "209861",
"ParentId": "209798",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T05:08:07.077",
"Id": "209798",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"database",
"sqlalchemy"
],
"Title": "Finding the duration of how long a search has been popular"
} | 209798 |
<p>The idea is that I have a subset of the movements of material of a factory (over 700k rows), and I want to separate these movements by the reference of each product to plot the stock of each product over time.</p>
<p>But the dataframe has repeated days, and the stock at the end of every month (<code>STOCK FINAL</code>) is in another dataframe (<code>inventario_df</code>). I get the <code>final_stock</code> from the other dataframe because I wanted to see if the data from the two dataframes are the same (in the 1st output it is not the same, in the 2nd it is, so now I know that the company has some kind of problem with the reference of the 1st output).</p>
<p><strong>example data</strong>:</p>
<p>MvtosMaterial.xlsx:</p>
<pre><code>Referencia Fecha Stock
13017094 20170507 23857.00
13037094 20170507 10733.00
13127094 20170101 10.00
13127094 20170101 20.00
13127094 20170101 0.00
14017094 20170507 9395.00
14047094 20170507 88847.00
15017094 20170507 10157.00
</code></pre>
<p>Inventario.xlsx:</p>
<pre><code>AÑO_INVENTARIO MES_INVENTARIO REFERENCIA STOCK FINAL
2017 1 13017094 17644
2017 1 13037094 5948
2017 1 13127094 10558
2017 1 14017094 15502
2017 1 14047094 44453
2017 1 15017094 10214
2017 5 13017094 17962
2017 5 13037094 3588
2017 5 14017094 13970
2017 5 14047094 88066
2017 5 15017094 8830
</code></pre>
<p>And the <strong>intended output</strong> is the groups separate by the reference, summing the quantities of stock by day, and the last day of each month with a final stock. This value is taken from the other dataframe (<code>inventory_df</code>), so one of the output groups would be:</p>
<pre><code> Referencia Fecha Stock Stock_final
101673 1304790 2015-01-05 135746.0 0.0
101745 1304790 2015-01-07 129353.0 0.0
101834 1304790 2015-01-08 182706.0 0.0
...
103123 1304790 2015-01-29 140634.0 0.0
103213 1304790 2015-01-30 194103.0 0.0
103226 1304790 2015-01-31 193383.0 253039.0
103306 1304790 2015-02-02 187932.0 0.0
103382 1304790 2015-02-03 182183.0 0.0
...
</code></pre>
<p>and another group:</p>
<pre><code> Referencia Fecha Stock Stock_final
51804 13017287 2016-05-26 2000.0 2000.0
51805 13017287 2016-06-23 1764.0 1764.0
51806 13017287 2016-10-19 1586.0 0.0
51807 13017287 2016-10-24 1200.0 1200.0
51808 13017287 2017-01-19 1079.0 0.0
51809 13017287 2017-01-20 938.0 0.0
...
</code></pre>
<p><strong>code</strong>:</p>
<pre><code>import pandas as pd
path = '../Data/'
mvtos_material_df = pd.read_excel(path + 'MvtosMaterial.xlsx')
inventario_df = pd.read_excel(path + 'Inventario.xlsx')
mvtos_material_df['Fecha'] = pd.to_datetime(mvtos_material_df['Fecha'], format='%Y%m%d')
inventario_df = inventario_df.rename(index = str, columns = {'MES_INVENTARIO': 'Month', 'AÑO_INVENTARIO': 'Year'})
inventario_df['Fecha'] = pd.to_datetime(inventario_df[['Year', 'Month']].assign(Day=1), format='%Y%m%d')
inventario_df.drop(['Month', 'Year'], axis = 1, inplace = True)
mvtos_dict = {}
stock_finales = {}
mvtos_material_df['Stock_final'] = 0.0
for name, group in mvtos_material_df.groupby('Referencia'):
mvtos_dict[str(name)] = pd.DataFrame()
# for loop to fill moves_dict with the orders per day
for k, v in group.groupby(pd.Grouper(key='Fecha', freq='M')):
if not v.empty:
# Comparing dates in inventory and movements to get the final stock
a = (inventario_df[inventario_df['REFERENCIA'].values == v.tail(1)['Referencia'].values])
a = (a[a['Fecha'].dt.month.values == v.tail(1)['Fecha'].dt.month.values])
a = (a[a['Fecha'].dt.year.values == v.tail(1)['Fecha'].dt.year.values])
# sum all days together and create the ones which are missing
for i, j in v.groupby(pd.Grouper(key='Fecha', freq='D')):
temp = j.tail(1).copy() # We need to get the last row
mvtos_dict[str(name)] = mvtos_dict[str(name)].append(j.tail(1))
if not a.empty:
# Drop last row (last day of the month) and add the one with the final stock
mvtos_dict[str(name)].drop(mvtos_dict[str(name)].index[len(mvtos_dict[str(name)])-1], inplace = True)
temp['Stock_final'] = float(a['STOCK FINAL'])
mvtos_dict[str(name)] = mvtos_dict[str(name)].append(temp)
</code></pre>
<p>In the code I have now, I have separated the groups in a dictionary so that I can access them later. Although I mainly used the dictionary because I didn't know how to do all this in the same dataframe.</p>
<p>On the second group, the first 2 rows are the last days of each month because they didn't have any other move between on <code>mvtos_material_df</code>.</p>
<p>Also, for <strong>plotting</strong> the graphs I use this code:</p>
<pre><code>for ke, v in mvtos_dict.items():
x = v['Fecha']
y1 = v['Stock']
y2 = v['Stock_final'].replace(0, np.nan)
# I had to use this to fix a problem with the axis
# but now seems is not needed
#pd.plotting.deregister_matplotlib_converters()
fig, ax = plt.subplots(figsize=(18, 8))
ax.plot(x, y1, c='red',alpha=0.6, label='Movimientos de material')
ax.scatter(x = x, y = y2, alpha=1, marker='x', label='Stock Final')
ax.xaxis.grid(True)
myFmt = mdates.DateFormatter("%Y-%m-%d")
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 30))
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.legend(loc='best')
ax.set_title(f'Gráfica del componente {ke}')
plt.show()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:37:36.787",
"Id": "405592",
"Score": "1",
"body": "Please provide a better explanation of what this code accomplishes, including example inputs and the intended output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T08:01:59.013",
"Id": "405685",
"Score": "0",
"body": "@200_success done, ty for taking the time to check it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:01:17.923",
"Id": "405701",
"Score": "0",
"body": "I think what would help your question greatly is a better title. You should change your title to state what the code achieves (group references by something) and just state your current code with example data. In addition, asking about whether or not code is correct or for specific changes to the code are off-topic here. However, asking for general improvements is on-topic. Any reviewer will most likely give you a more vectorized version anyways (but they might also comment on other things)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:59:20.607",
"Id": "405705",
"Score": "0",
"body": "@Graipher ty for the input, I'll try to rework the post to include all the code, the example data is better to put it here or with a link to a gist? Because I was thinking that I could share a big chunk of data instead of only 10 rows but here I think it will be too much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T11:08:42.697",
"Id": "405706",
"Score": "0",
"body": "@set92 A few rows is usually enough (as long as all relevant parts are there, e.g. at least two groups and two entries per group/enough for the function to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T11:56:37.443",
"Id": "405713",
"Score": "0",
"body": "I think is good now, the only thing may be the intended output, which I've put as two separate groups, and I don't really mind if there are separate or I have them all together in a dataframe and then I can filter by reference to plot them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:25:48.293",
"Id": "405809",
"Score": "0",
"body": "@Graipher why offtopic? I didn't put all the code, the input and intended output? Or is a problem of my english and the ability to state what I want to do?\nI rewrite to a mostly vectorized code, going from 43s to 12s, but now I have a multi-index dataframe which seems harder to work with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T13:57:29.570",
"Id": "405833",
"Score": "0",
"body": "@set92: Sorry, I had cast my close vote some time ago, long before your edit. I think the current version is much better than the previous (and I have therefore voted to reopen the question). One thing left to change could be the title. Maybe something like `\"Plot stock movements per product and day and cross-check with end-of-month inventory\"` better describes what your code achieves (and not what you want out of a review)?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T07:41:45.027",
"Id": "209801",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner",
"pandas",
"matplotlib"
],
"Title": "Sum, validate, and plot monthly inventory levels"
} | 209801 |
<p>To quantify Buffet's #1 rule of investing, "Don't lose money", I take the assumption that % returns of an investment follow a Normal distribution. </p>
<p>Now a high return high risk investment might follow N(mu=50%, sigma=70%) while low return low risk investment follow N(mu=20%, sigma=10%). </p>
<pre><code>from operator import mul
from functools import reduce
from random import gauss
from statistics import median
from typing import List
def avg_cagr(percents: List[int]) -> float:
'''Given (successive) % annual growth rates, returns average Compound Annual Growth Rate'''
amount = reduce(mul, [1+p/100 for p in percents])
amount = amount if amount > 0 else 0 # at worst, complete amount can be lost but can't go negative
return (amount**(1/len(percents)) - 1)*100
def normal_returns(mu: float, sigma: float, years: int = 20, simulations: int = 1000) -> float:
'''Returns net CAGR assuming annual percentage returns follow a Normal distribution'''
return median(avg_cagr([gauss(mu=mu, sigma=sigma) for _ in range(years)]) for _ in range(simulations))
</code></pre>
<p>I have simulated <code>normal_returns</code> for various values of <code>mu</code> & <code>sigma</code> (for 20 consecutive years) and plotted a contour plot. We can see here that N(25, 20) handily beats N(60, 80). <a href="https://pastebin.com/7Ybhpbdq" rel="nofollow noreferrer">Plotting code</a></p>
<p><a href="https://i.stack.imgur.com/7y8qp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7y8qp.png" alt="Contour plot of CAGR"></a> </p>
<p>My query is does this formulation of problem (beyond just the code) seem alright? Could I model/design it better? What are other approaches?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T18:36:35.487",
"Id": "406034",
"Score": "0",
"body": "Since you're asking about the formulation of the problem beyond the code, this question may be better suited for the folks at [Quant Stack Exchange](https://quant.stackexchange.com/)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T07:47:21.417",
"Id": "209803",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"random",
"simulation",
"data-visualization"
],
"Title": "Moderate return-low risk vs high returns-high risk investments"
} | 209803 |
<p>After some research I found the following information: In <a href="https://stackoverflow.com/questions/19064987/html-css-popup-div-on-text-click">this</a> closed question I found a solution which does not work well when pop-up has height bigger than screen (and some jquery solution). <a href="https://stackoverflow.com/questions/6787258/most-elegant-way-to-create-a-javascript-popup">Here</a> is a question about showing outside page in popup. And <a href="https://stackoverflow.com/questions/15812203/show-pop-ups-the-most-elegant-way">here</a> are some theoretical and angularJS solutions. However, those answers do not satisfy me.</p>
<p>I want to show a pop-up to user which contains my content (not loaded from URL) e.g. an editor. I am interested in only pure JS/HTML/CSS solutions (no jQuery or other libs). This is the code which I regularly use, and which was tested on Chrome, Safari, Firefox and Edge:</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>toggle = q => document.querySelector(q).classList.toggle('hide');</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; padding: 0; }
.btn { padding: 10px; background: #BADA55; border-radius: 5px; cursor: pointer}
.popupBg {
position: absolute;
top: 0;
left: 0;
display: flex;
min-height: 100vh;
width: 100vw;
justify-content: center;
align-items:center;
background: rgba(255,0,0,0.5)
}
.popup {
width: 100px;
min-height: 200px;
border: 1px solid black;
background: #88f;
margin: 40px;
}
.hide {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="example">Some content</div>
<div class="btn" onclick="toggle('.popupBg')">PopUP</div>
<div class="popupBg hide" onclick="toggle('.popupBg')" >
<div class="popup" onclick="event.stopPropagation()" >
My popup
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Here is <a href="https://jsfiddle.net/ng6eo7y4/1/" rel="nofollow noreferrer">a JSfiddle version</a><a href="https://codepen.io/peiche/pen/vhqym" rel="nofollow noreferrer">.</a></p>
<p><strong>Question1</strong>: Is there simpler way to show popup (similar to this in snipped and easy to modify) to user?</p>
<p><strong>Question2</strong>: Does approach have any drawbacks?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T08:06:32.710",
"Id": "405481",
"Score": "1",
"body": "I read [this article](https://hackernoon.com/the-ultimate-guide-for-creating-a-simple-modal-component-in-vanilla-javascript-react-angular-8733e2859b42) not long ago - it might be useful to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:19:19.687",
"Id": "405554",
"Score": "2",
"body": "Your script is better that I can make, but I think some people would suggest you seperate the html and the script. Something like\n\n document.getElementById(\"myBtn\").addEventListener(\"click\", function(){\n document.getElementById(\"demo\").innerHTML = \"Hello World\";\n});"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T22:41:49.487",
"Id": "405648",
"Score": "0",
"body": "@guest271314 - can you provide some code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:15:22.397",
"Id": "405653",
"Score": "0",
"body": "@KamilKiełczewski One approach, though not yet rendered exactly the same as at the question is the use `<input type=\"checkbox\">`, CSS `:checked` and adjacent sibling selector `+` https://jsfiddle.net/ng6eo7y4/2/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:21:20.363",
"Id": "405655",
"Score": "0",
"body": "@guest271314 I think your proposition is not yet production ready"
}
] | [
{
"body": "<h3>General notes:</h3>\n\n<p>I will focus mainly on your second question as I cannot imagine simpler solution. I would even suggest to do it a little bit more complex in order to make CSS more scalable (in the terms of resolution and content size).</p>\n\n<p>For instance you can consider using <code>width: auto;</code> for your <code>.popup</code> class in order to make it scale itself depending on internal content.</p>\n\n<p>Another approach would be to set width and height fixed and use <code>overflow:auto;</code> in order to use some scrollbars as internal content grows bigger.</p>\n\n<p>If you would like to make it simpler for the user (if you mean an user of your code) you can wrap it inside some API like:</p>\n\n<pre><code>function showPopup(message) {\n const popupContainerClass = '.popupBg';\n document.querySelector(popupContainerClass).classList.toggle('hide');\n const popupContentClass = '.popup';\n const popupElement = document.querySelector(popupContentClass);\n popupElement.innerHTML = message;\n //... but please be aware of potential Cross Site Request Forgery vulnerability here!\n popupElement.focus();\n}\n</code></pre>\n\n<h3>Question2:</h3>\n\n<p>Your approach is about hiding an element that in fact is always present in DOM. It usually has advantages because displaying popup will not consume any processing power.</p>\n\n<p>But in some cases (for instance when your popup presence would solely cause complex computations, or require lot of memory -like some videos or animations) it would be considerable to completely remove it from DOM instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:01:25.600",
"Id": "209850",
"ParentId": "209804",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209850",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T07:57:48.287",
"Id": "209804",
"Score": "5",
"Tags": [
"javascript",
"css",
"html5"
],
"Title": "Simple way to show popup"
} | 209804 |
<p>I am playing with 3 Main Classes Please have a look </p>
<p>I have integrated <a href="https://github.com/jonkykong/SideMenu" rel="nofollow noreferrer">https://github.com/jonkykong/SideMenu</a> </p>
<p>I have one tableview which act as leftViewController</p>
<p>This class is show the list of menu user has</p>
<pre><code>import UIKit
struct SideMenuListItem {
var name:String
var isSelected: Bool
var notificationCount:Int
var viewController:UIViewController
}
protocol SideMenuItemTappedDelegate:class {
func itemTapped(item:SideMenuListItem,index:Int)
}
class SideMenuListVC: UIViewController {
//MARK:- Outlets
@IBOutlet weak var tableView: UITableView!
//MARK:- Var
weak var delegate : SideMenuItemTappedDelegate?
//Please ignore repetition `viewController` this is just for testing
private let menuItems = [SideMenuListItem(name: "Inbox", isSelected: false, notificationCount: 25,viewController:MapVC.viewController()),
SideMenuListItem(name: "Stats", isSelected: false, notificationCount: 0,viewController:PageContentViewController.viewController(pageData:PageData(title: "How to do", desc: "TEST STATS", image: UIImage(named: "Rectangle 2 copy")!))),
SideMenuListItem(name: "Calendar", isSelected: false, notificationCount: 12,viewController:MapVC.viewController()),
SideMenuListItem(name: "Map", isSelected: true, notificationCount: 0,viewController:MapVC.viewController()),
SideMenuListItem(name: "Settings", isSelected: false, notificationCount: 0,viewController:PageContentViewController.viewController(pageData:PageData(title: "How to do", desc: "TEST SETTINGS", image: UIImage(named: "Rectangle 2 copy")!)))]
var getCurrentSelectedItem:SideMenuListItem? {
return menuItems.first{$0.isSelected}
}
...
</code></pre>
<p>When User Login I call following class (root view controller) embedded in navigation controller </p>
<pre><code>import UIKit
import SideMenu
class SideMenuVC: UIViewController {
//--------------------------------------------------------------------------------
//MARK:- Memory Managment Methods
//--------------------------------------------------------------------------------
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//--------------------------------------------------------------------------------
//MARK:- Custom Methdos
//--------------------------------------------------------------------------------
private func configureSideMenu() {
AppGlobalManager.sharedManager.setupSideMenu()
AppGlobalManager.sharedManager.leftMenuViewController.delegate = self
if let vc = AppGlobalManager.sharedManager.leftMenuViewController.getCurrentSelectedItem?.viewController {
self.addChildVC(vc)
}
}
private func addChildVC (_ vc:UIViewController) {
self.addChild(vc)
self.view.addSubview(vc.view)
vc.view.frame = self.view.bounds
vc.didMove(toParent: self)
}
//--------------------------------------------------------------------------------
//MARK:- ViewLifeCycle Methods
//--------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
self.configureSideMenu()
}
//--------------------------------------------------------------------------------
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
//--------------------------------------------------------------------------------
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
}
</code></pre>
<p>And This is <code>AppGlobalManager</code> Which is Shared class</p>
<pre><code>import UIKit
import SideMenu
import Foundation
class AppGlobalManager: NSObject {
static let sharedManager = AppGlobalManager()
lazy var leftMenuViewController = SideMenuListVC.viewController()
public func setupSideMenu () {
let sideMenu = UISideMenuNavigationController(rootViewController: leftMenuViewController)
SideMenuManager.default.menuLeftNavigationController = sideMenu
SideMenuManager.default.menuLeftNavigationController?.isNavigationBarHidden = true
SideMenuManager.default.menuWidth = UIScreen.main.bounds.width
SideMenuManager.default.menuPresentMode = .menuDissolveIn
SideMenuManager.default.menuFadeStatusBar = false
}
}
</code></pre>
<p>What I am doing : </p>
<ol>
<li>On Login set <code>SideMenuVC</code> to root View controller</li>
<li>Setup Side menu controller from AppGlobalManager (shared instance )class <br> </li>
<li>Keep leftMenu Controller as global property <br></li>
<li>Get Current Selected ViewController and add to Child VC <br></li>
<li>Setup delegate of Menu list so when user tap on cell call <code>addChildVC</code></li>
</ol>
<p>Please suggest </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T08:22:46.857",
"Id": "209805",
"Score": "1",
"Tags": [
"swift",
"ios"
],
"Title": "Side menu handling ios"
} | 209805 |
<p>I have a class which represents some translations of a keyword. </p>
<pre><code>public abstract class Name {
private String name;
private String name_de;
private String name_it;
private String name_fr;
private String name_hu;
private String name_cs;
public Name(String name_key, String name_de, String name_it, String name_fr, String name_hu, String name_cs) {
super();
this.name = name_key;
this.name_de = name_de;
this.name_it = name_it;
this.name_fr = name_fr;
this.name_hu = name_hu;
this.name_cs = name_cs;
}
</code></pre>
<p>Each translation has to be an own field because of saving purpose. The problem here is that I cant make sure that for instance the german translation is really the second parameter. </p>
<p>I was thinking about to create an own Object for each translation, but seems a litte bit of overhead. Are there any other options to represent a translation class?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T13:06:06.877",
"Id": "405525",
"Score": "1",
"body": "In internationalisation, the number of languages should ideally be open-ended, with a fallback, as the `name` here. So just name, and such. Resource bundles, **.properties** or **ListResourceBundle** (java arrays) allow such a more generic approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:01:18.643",
"Id": "405532",
"Score": "0",
"body": "A fluent builder can make your code more readable and safe. But nothing will prevent someone to pass a wrong value. `new Name.Builder(key).deutch(\"..\").italian(\"..\").build()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:00:18.370",
"Id": "405547",
"Score": "0",
"body": "@gervais.b A builder is a good approach. Its more important to make clear which value belongs to which language. If a wrong value will be passed, its not the fault of the code. If you would like to create an answer, I will accept it."
}
] | [
{
"body": "<p>A fluent builder can make your code more readable and safe:</p>\n\n<pre><code>new Name.Builder(key)\n .deutch(\"..\")\n .italian(\"..\")\n .build();\n</code></pre>\n\n<p>However nothing will prevent someone to pass wrong value. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:01:59.447",
"Id": "209836",
"ParentId": "209807",
"Score": "2"
}
},
{
"body": "<p>In addition to @gervais.b's great answer, you can for instance use some kind of <code>Map</code> to store translations for different languages. Of course instead of using strings for keys like <code>\"de\", \"it\", \"fr\"</code> it will be safer to use enum for indication of different languages.</p>\n\n<blockquote>\n <p>However nothing will prevent someone to pass wrong value.</p>\n</blockquote>\n\n<p>It is possible to implement some mechanism in <code>build()</code> method to check if all enum values are covered and are correct. <a href=\"https://www.geeksforgeeks.org/iterating-over-enum-values-in-java/\" rel=\"nofollow noreferrer\">Here is some reference how to iterate over enum</a></p>\n\n<p>You can also simplify the builder a little bit:</p>\n\n<pre><code>new Name.Builder(key)\n .translatedAs(Languages.DEUTCH, \"..\")\n .translatedAs(Languages.ITALIAN, \"..\")\n .build();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T19:49:22.657",
"Id": "405626",
"Score": "1",
"body": "My remark about the fact that nothing can prevent someone to pass wrong value was not about ensuring that all translations are filled in. But more that you cannot prevent someone to pass \"Bonjour\" in English."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T20:24:59.173",
"Id": "405630",
"Score": "0",
"body": "@gervais.b You are right. But in that case it is at least possible to minimize the probability of human error by providing clean API."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:11:22.893",
"Id": "209843",
"ParentId": "209807",
"Score": "1"
}
},
{
"body": "<p>You haven't given much context about how you intend to <em>use</em> this class, which is always important. In my experience (echoed in comments), there's not much use case for needing all translations of a string at one time. The use case is more typically that you need to render the UI in a particular language, so you need a bunch of German strings but none of the other languages. Also, you want to be able to easily add support for additional languages, ideally without any code changes. That's what resource bundles are for, it seems like you are trying to reinvent the wheel here. If you think that resource bundles don't solve your problem, you should give more context.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:46:00.337",
"Id": "405597",
"Score": "0",
"body": "I do not have much experience using resource boundles, but I already say that I need every attribute because of saving purpuse. I am not able to change the structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:55:58.953",
"Id": "405603",
"Score": "1",
"body": "\"Saving purpose\" is pretty vague. How would this class be used? What does the save function look like? Where does this class get its data? Why does it need every translation in a different field, rather than a map langId -> translation?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:39:18.997",
"Id": "209848",
"ParentId": "209807",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209836",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T08:50:15.583",
"Id": "209807",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"constructor"
],
"Title": "Represent a Class which holds translation Strings"
} | 209807 |
<p>I'm trying to read a text file formatted as in this example:</p>
<pre><code>5 3
3 1 5
6 6
6 1 3 2 5 4
</code></pre>
<p>Where the lines are coupled, with the line above always being of length equal to 2 and the line below having length equal to the the last digit in the line above.</p>
<p><em>(Unfortunately this is from an old note I took and I don't remember what those numbers are actually supposed to mean, so I'm limiting myself to store them in a multidimensional vector form where they can be easily recovered).</em></p>
<p>In the beginning I was tring to read the digit which represents the length below to execute a loop of finite length, but in the end this is the code I wrote:</p>
<pre><code>#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string filname="data/file01.txt";
std::ifstream file01(filname);
std::vector<std::vector<int>> v;
std::string line;
while(getline(file01,line))
{
std::stringstream ls;
ls<<line;
int c;
std::vector<int> t;
while(!ls.eof())
{
ls>>c;
t.push_back(c);
}
v.push_back(t);
}
return 0;
}
</code></pre>
<p>This gives me a 2-dimensional vector that can be easily accessed, but I don't like having to convert both the file and each string to a stream and I don't like using nested vectors.</p>
<p>Is there a way to achieve this goal with more simple and elegant code (even if it means to make the code more specific)?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:22:37.647",
"Id": "405535",
"Score": "1",
"body": "What would be the use case of your 2-dimensional vector? Because you can't just ask for `nested_vector[x][y]` unless you know `nested_vector[x]` has at least `y` elements -and this information is contained in line `y-1`. That means you could as well store lines by pair and elide the first line's last number since it is `pair_of_lines.size() - 1`. Actually, if the numbers are all one-digit long, you don't need to convert the `char`s to integers, and you can store the pairs of lines directly as strings. You could even simply store the whole file as a long string ... (1/2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:26:18.110",
"Id": "405536",
"Score": "0",
"body": "... and a vector of iterators / positions denoting the end of a pair of lines. It might allow you to perform faster I/O (reading the file in bulk rather than line by line), and only then parsing your lines from the copy in memory. (2/2)"
}
] | [
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Decompose your program into functions</h2>\n\n<p>All of the logic here is in <code>main</code> in one chunk of code. It would be better to decompose this into separate functions.</p>\n\n<h2>Don't loop on <code>eof()</code></h2>\n\n<p>It's almost always incorrect to loop on <code>eof()</code> while reading a file. The reason is that the <code>eof</code> indication is only set when an attempt is made to read something from the file when we're already at the end. In this case, it means we have already executed the line <code>ls >> c;</code> and then called <code>t.push_back(c);</code>. The problem is that if we're at the end of the file and we attempt to read one more <code>c</code> value, it will append an unwanted value to the end of the vector. See <a href=\"https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong\">this question</a> for more details on why using <code>eof</code> is usually wrong.</p>\n\n<h2>Omit <code>return 0</code></h2>\n\n<p>When a C or C++ program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so there is no need to put <code>return 0;</code> explicitly at the end of <code>main</code>. </p>\n\n<h2>Allow the user to specify input file name</h2>\n\n<p>The file name is currently hardcoded which certainly greatly restricts the usefulness of the program. Consider using <code>argc</code> and <code>argv</code> to allow the user to specify file names on the command line. </p>\n\n<h2>Use standard algorithms</h2>\n\n<p>An alternative is to use <code>std::copy</code> to read in a line of integers. Here's one way to do that:</p>\n\n<pre><code>while(getline(in, line))\n{\n std::stringstream ls{line};\n std::vector<int> vec;\n std::copy(std::istream_iterator<int>(ls), \n std::istream_iterator<int>(), \n std::back_inserter(vec)\n );\n v.push_back(vec);\n}\n</code></pre>\n\n<h2>Use a custom object</h2>\n\n<p>An alternative would be to use your own class, <code>LinePair</code> and create a single-dimensional vector of those. Here's how the <code>LinePair</code> object might be defined:</p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <vector>\n\nclass LinePair {\npublic:\n friend std::ostream& operator<<(std::ostream& out, const LinePair& lp) {\n constexpr char sep[]{\" \"};\n auto it{lp.data.begin()};\n out << *it++ << sep << lp.data.size() - 1 << '\\n';\n std::copy(it, lp.data.end(), \n std::ostream_iterator<int>(out, sep));\n return out << '\\n';\n }\n friend std::istream& operator>>(std::istream& in, LinePair& lp) {\n int a, len;\n in >> a >> len;\n if (in && len) {\n lp.data.clear();\n lp.data.reserve(len+1);\n lp.data.push_back(a);\n for ( ; len && in >> a; --len) {\n lp.data.push_back(a);\n }\n }\n return in;\n }\nprivate:\n std::vector<int> data;\n};\n</code></pre>\n\n<p>Now <code>main</code> is quite simple:</p>\n\n<pre><code>int main(int argc, char *argv[])\n{\n if (argc != 2) {\n std::cerr << \"Usage: readlines filename\\n\";\n return 1;\n }\n std::ifstream in{argv[1]};\n std::vector<LinePair> v;\n std::copy(std::istream_iterator<LinePair>(in), \n std::istream_iterator<LinePair>(),\n std::back_inserter(v)\n );\n\n // now echo it back out\n std::copy(v.begin(), v.end(), \n std::ostream_iterator<LinePair>(std::cout));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:02:44.670",
"Id": "209837",
"ParentId": "209809",
"Score": "4"
}
},
{
"body": "<p>You're turning the whole input file into a vector of vectors. That's fine, but you state yourself that your input has structure. It would be nice to have that structure reflected in your program:</p>\n\n<ol>\n<li>since the lines are couple in pairs I'd like to see a code block that clearly processes a pair of lines</li>\n<li>you should then eliminate the redundancy that the second number of the 1 st line equals the number of items on the second.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T18:47:47.620",
"Id": "405612",
"Score": "1",
"body": "Good point! I've added such an alternative to my answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T18:24:07.097",
"Id": "209854",
"ParentId": "209809",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "209837",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T08:58:07.667",
"Id": "209809",
"Score": "1",
"Tags": [
"c++",
"io",
"stream"
],
"Title": "Read integers from coupled lines in a text file"
} | 209809 |
<p>I have the following script to find files containing a certain string and then report on the location of the file along with the size in bytes. </p>
<p>It works, but I seem to have made heavy weather of finding the string which involves a fair bit of tidying up afterwards to produce some clean output.</p>
<p>Any idea how I could make this more concise?</p>
<pre><code># Ignore errors
$ErrorActionPreference= 'silentlycontinue'
# Grab user options
$ext = Read-Host -Prompt "Enter extension "
$huntString = Read-Host -Prompt "Enter hunt string "
# Find text files (.log, .txt etc) containing the hunt string
$entries = gci -recurse -include *.$ext -ErrorAction SilentlyContinue | select fullname, length | sort -property length
echo ''
foreach ($e in $entries)
{
# Find files containing the hunt string
$foundFile = (gci $e.fullname | select-string $huntString | measure-object | findstr Count)
# Output hit count along with size and name
$rawOutput = $foundFile.ToString() + $e.Length.ToString().PadRight(10,[char]32) + "`t" + $e.fullname
# Only output entries with a hit count
$cleanOutput = echo $rawOutput | select-string ": 1"
# Remove hit count
$finalOutput = $cleanOutput -replace "Count","" -replace ": ",""
# Trim and output
echo $finalOutput.TrimStart()
}
</code></pre>
| [] | [
{
"body": "<p>Using findstr in PowerShell is superfluous and<br>\nnot very <strong><em>powershell'ish</em></strong> which is about objects and pipes.</p>\n\n<p>You can directly pipe the raw output of <code>Get-ChildItem</code> to <code>Select-String</code> and parse the resulting object for the information you require.</p>\n\n<p>As the size of the file isn't contained in the properties <code>sls</code> returns:</p>\n\n<pre><code>Context Property\nFilename Property\nIgnoreCase Property\nLine Property\nLineNumber Property\nMatches Property\nPath Property\nPattern Property\n</code></pre>\n\n<p>You've to append it, either with a <code>calculated property</code> </p>\n\n<pre><code># Grab user options\n$ext = Read-Host -Prompt \"Enter extension \"\n$huntString = Read-Host -Prompt \"Enter hunt string \"\n\nGet-ChildItem *.$ext -Recurse | Select-String $huntString -List | \n Select-Object @{Label='Size';Expression={(Get-Item $_.Path).Length}},Path\n</code></pre>\n\n<p>or iterate the output and build a <code>[PSCustomObject]</code>:</p>\n\n<pre><code>Get-ChildItem *.$ext -Recurse | Select-String $huntString -List | \n ForEach-Object {\n [PSCustomObject]@{\n Path = $_.Path\n Size = (Get-Item $_.path).Length\n }\n }\n</code></pre>\n\n<p>The <code>objects</code>output will be the very same:</p>\n\n<pre><code>> Q:\\Test\\2018\\12\\17\\CR_209811.ps1\nEnter extension : ps1\nEnter hunt string : ::Now\nSize Path\n---- ----\n 878 Q:\\Test\\2018\\09\\18\\SO_52381514.ps1\n 677 Q:\\Test\\2018\\11\\16\\SO_53336923.ps1\n 770 Q:\\Test\\2018\\11\\19\\SO_53381881.ps1\n1141 Q:\\Test\\2018\\12\\17\\CR_209811.ps1\n1259 Q:\\Test\\2018\\12\\17\\SU_1385185.ps1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T13:12:34.003",
"Id": "405721",
"Score": "1",
"body": "@RobbieDee Sorry for the missing closing brackets, Label or Name are both valid for calculated properties"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:30:21.683",
"Id": "209847",
"ParentId": "209811",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209847",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:10:28.513",
"Id": "209811",
"Score": "2",
"Tags": [
"powershell"
],
"Title": "Finding a string in a text file and reporting full file name and size"
} | 209811 |
<p>This function's goal is to reduce the length of a <code>sentence</code> to exactly <code>max_length</code> characters by cutting each word in the sentence to a length of minimum 4 characters, if cutting each word to 4 characters isn't enough the the sentence is returned anyway.<br>
All sentences are free of special characters and words are separated by spaces.<br>
Here is the function:</p>
<pre><code>def cut_everything(sentence, max_length):
"""
reduces each word in sentence to a length of 4
:type sentence: string
:param sentence: the sentence to cut
:type max_length: int
:param max_length: the length to which the sentence will be reduced
"""
words = sentence.split()
for index, word in enumerate(words):
word_length = len(word)
if word_length > 4:
to_cut = len(sentence) - max_length
to_keep = word_length - to_cut
if to_keep < 4:
to_keep = 4
words[index] = word[:to_keep]
sentence = ' '.join(words)
if len(sentence) <= max_length:
break
return sentence
</code></pre>
<p>My main concern for this review is performance, but any readability comment is appreciated</p>
| [] | [
{
"body": "<h1>Review</h1>\n\n<ul>\n<li><p>Magic numbers</p>\n\n<p><code>4</code> is a magic number, it is best to assign these to a variable name, that way it is more clear what this number means</p>\n\n<p><em>numbers don't have names, variables do</em></p>\n\n<pre><code>MAX_WORD_LENGHT = 4\n</code></pre></li>\n<li><p>Use built-ins when possible</p>\n\n<blockquote>\n<pre><code>to_keep = word_length - to_cut\nif to_keep < 4:\nto_keep = 4\n</code></pre>\n</blockquote>\n\n<p>Can be replaced with the <code>max</code> builtin</p>\n\n<pre><code> to_keep = max(word_length - to_cut, 4)\n</code></pre></li>\n<li><p>Add tests</p>\n\n<p>That way it becomes easy to check after a change if the function still works</p></li>\n</ul>\n\n<h1>Alternative</h1>\n\n<p>I went a slightly different route, </p>\n\n<p>Instead of joining after each word, I calculate the chars we need to cut beforehand</p>\n\n<p>So we can keep a variable that will hold the amount of chars we still need to cut to reach our target</p>\n\n<p>And only at the return join the words</p>\n\n<pre><code>import doctest\n\nMAX_WORD_LENGHT = 4\n\ndef cut_everything(sentence, max_length):\n \"\"\"\n reduces each word in sentence to a length of 4\n\n :type sentence: string\n :param sentence: the sentence to cut\n :type max_length: int\n :param max_length: the length to which the sentence will be reduced\n\n >>> cut_everything('foo bar foooobar', 16)\n 'foo bar foooobar'\n\n >>> cut_everything('foo bar foooobar', 8)\n 'foo bar fooo'\n\n >>> cut_everything('foo bar foooobar baaarfoo', 20)\n 'foo bar fooo baaarfo'\n\n >>> cut_everything('fooooooo baaaaaaar foooobar baaarfoo', 2)\n 'fooo baaa fooo baaa'\n \"\"\"\n words = sentence.split()\n chars_to_cut = len(sentence) - max_length\n for index, word in enumerate(words):\n if chars_to_cut < 0:\n break\n word_length = len(word)\n if word_length > MAX_WORD_LENGHT:\n to_keep = max(word_length - chars_to_cut, MAX_WORD_LENGHT)\n words[index] = word[:to_keep]\n chars_to_cut -= word_length - to_keep\n return ' '.join(words)\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:59:03.613",
"Id": "405494",
"Score": "0",
"body": "do you think it is useful to put use cases in the docstring or is it just for the answer to be clearer ? Also would using a parameter with a default value be more efficient than a global variable for the \"magic number situation\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:01:25.387",
"Id": "405495",
"Score": "0",
"body": "I have used the docstrings to add a test-suite with the [doctest module](https://docs.python.org/3/library/doctest.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:04:41.647",
"Id": "405497",
"Score": "0",
"body": "Both could work, but depending on the situation. If the max_word_length can be changed you could add it as a parameter. But if the max_word_length is static ie cannot be changed add it as a constant."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:51:27.940",
"Id": "209820",
"ParentId": "209813",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:21:44.150",
"Id": "209813",
"Score": "3",
"Tags": [
"python",
"strings",
"natural-language-processing"
],
"Title": "Reduce the length of words in a sentence"
} | 209813 |
<p>I'm generating a URL (in string) that depends on 3 optional parameters, <code>file</code>, <code>user</code> and <code>active</code>.</p>
<p>From a base url: <code>/hey</code> I want to generate the endpoint, this means:</p>
<ul>
<li>If <code>file</code> is specificied, my desired output would is: <code>/hey?file=example</code></li>
<li>If <code>file</code> and <code>user</code> is specified, my desired output is: <code>/hey?file=example&user=boo</code></li>
<li>If <code>user</code> and <code>active</code> are specified, my desired output is: <code>/hey?user=boo&active=1</code> </li>
<li>If no optional parameters are specified, my desired output is: <code>/hey</code></li>
<li>and so on with all the combinations...</li>
</ul>
<p>My code, which is working correctly, is as follows (change the <code>None</code>'s at the top if you want to test it):</p>
<pre><code>file = None
user = None
active = 1
ep = "/hey"
isFirst = True
if file:
if isFirst:
ep+= "?file=" + file;
isFirst = False;
else: ep += "&file=" + file;
if user:
if isFirst:
ep+= "?user=" + user;
isFirst = False;
else: ep += "&user=" + user;
if active:
if isFirst:
ep+= "?active=" + str(active);
isFirst = False;
else: ep += "&active=" + str(active);
print ep
</code></pre>
<p>Can someone give me <em>a more python implementation</em> for this? I can't use modules as <code>requests</code>.</p>
<p>Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:00:28.810",
"Id": "405531",
"Score": "8",
"body": "Lose the `;`. makes python look ugly"
}
] | [
{
"body": "<p>The most Pythonic version of this depends a bit on what you do with that URL afterwards. If you are using the <code>requests</code> module (which you probably should), this is already built-in by <a href=\"http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls\" rel=\"nofollow noreferrer\">specifying the <code>params</code> keyword</a>:</p>\n\n<pre><code>import requests\n\nURL = \"https://example.com/hey\"\n\nr1 = requests.get(URL, params={\"file\": \"example\"})\nprint(r1.url)\n# https://example.com/hey?file=example\n\nr2 = requests.get(URL, params={\"file\": \"example\", \"user\": \"boo\"})\nprint(r2.url)\n# https://example.com/hey?file=example&user=boo\n\nr3 = requests.get(URL, params={\"user\": \"boo\", \"active\": 1})\nprint(r3.url)\n# https://example.com/hey?user=boo&active=1\n\nr4 = requests.get(URL, params={})\nprint(r4.url)\n# https://example.com/hey\n</code></pre>\n\n<hr>\n\n<p>If you do need a pure Python solution without any imports, this is what I would do:</p>\n\n<pre><code>def get_url(base_url, **kwargs):\n if not kwargs:\n return base_url\n params = \"&\".join(f\"{key}={value}\" for key, value in kwargs.items())\n return base_url + \"?\" + params\n</code></pre>\n\n<p>Of course this does not urlencode the keys and values and may therefore be a security risk or fail unexpectedly, but neither does your code.</p>\n\n<p>Example usage:</p>\n\n<pre><code>print(get_url(\"/hey\", file=\"example\"))\n# /hey?file=example\n\nprint(get_url(\"/hey\", file=\"example\", user=\"boo\"))\n# /hey?file=example&user=boo\n\nprint(get_url(\"/hey\", user=\"boo\", active=1))\n# /hey?user=boo&active=1\n\nprint(get_url(\"/hey\"))\n# /hey\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:09:18.670",
"Id": "405486",
"Score": "0",
"body": "Due to the implementation of the rest of the code, I need to do it everything without any _requests_ module, just improving the code I posted using strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:12:12.740",
"Id": "405487",
"Score": "0",
"body": "Can you please give me a simple example of how to use the `get_url` function please? The `**kwargs` part is a bit hard for me to understand. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:13:13.100",
"Id": "405488",
"Score": "2",
"body": "@Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:35:32.643",
"Id": "405538",
"Score": "4",
"body": "Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:37:38.170",
"Id": "405540",
"Score": "0",
"body": "@KonradRudolph True, which is why I would recommend using the already existing stuff that is in `requests` (first part of my answer) or in `urllib` (like in Matthias answer) for production."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:38:32.140",
"Id": "405541",
"Score": "1",
"body": "@KonradRudolph Added a short disclaimer regarding that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T08:33:18.787",
"Id": "405688",
"Score": "1",
"body": "It's not just that it's a security risk, it's also that if you have `&` in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another `=` in the values)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T08:51:45.817",
"Id": "405692",
"Score": "0",
"body": "@ChatterOne True, but I still stand by my answer. In any real context you can use modules like `request` (it is in the standard library after all) and you should. If however you need to do it yourself, this is a shortened and IMO more pythonic version of the OPs code. It sounds like it is an assignment where things like sanitized/only simple input is often guaranteed. If it is not, then the OPs code does not work as intended either, which would make the question off topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T08:53:45.807",
"Id": "405693",
"Score": "0",
"body": "@ChatterOne Amended the disclaimer to say that it also may fail unexpectedly because of the lack of urlencoding."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:07:03.463",
"Id": "209817",
"ParentId": "209816",
"Score": "12"
}
},
{
"body": "<p>You're pretty much reinventing <a href=\"https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode\" rel=\"noreferrer\"><code>urllib.parse.urlencode</code></a>:</p>\n\n<pre><code>from urllib.parse import urlencode\n\n\ndef prepare_query_string(**kwargs):\n return urlencode([(key, value) for key, value in kwargs.items() if value is not None])\n</code></pre>\n\n<p>Usage being:</p>\n\n<pre><code>>>> prepare_query_string(active=1)\n'active=1'\n>>> prepare_query_string(active=1, user=None)\n'active=1'\n>>> prepare_query_string(active=1, user='bob')\n'active=1&user=bob'\n>>> prepare_query_string(file='foo.tar.gz', user='bob')\n'file=foo.tar.gz&user=bob'\n>>> prepare_query_string(file='foo.tar.gz', user='bob', active=None)\n'file=foo.tar.gz&user=bob'\n>>> prepare_query_string(file='foo.tar.gz', user='bob', active=1)\n'file=foo.tar.gz&user=bob&active=1'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T10:12:13.590",
"Id": "209818",
"ParentId": "209816",
"Score": "18"
}
}
] | {
"AcceptedAnswerId": "209817",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:53:30.137",
"Id": "209816",
"Score": "7",
"Tags": [
"python",
"strings"
],
"Title": "Generating strings dynamically in Python"
} | 209816 |
<p>I am trying to solve <a href="https://projecteuler.net/problem=224" rel="nofollow noreferrer">Project Euler Problem 224</a>:</p>
<blockquote>
<p>Let us call an integer sided triangle with sides <em>a</em> ≤ <em>b</em> ≤ <em>c</em> <em>barely obtuse</em> if the sides satisfy <em>a</em><sup>2</sup> + <em>b</em><sup>2</sup> = <em>c</em><sup>2</sup> - 1.</p>
<p>How many barely obtuse triangles are there with perimeter ≤ 75,000,000?</p>
</blockquote>
<p>For large <code>v_max</code> and <code>v_max_n</code>, the generator below yields very slow when I have 750000000 and 500000000, respectively. Having tried for days, I am still looking for an algorithm that can do this in under a minute.</p>
<pre><code>from itertools import product
import math
n = 15 * 10 ** 8
v_max = math.floor(n / 2 - 1 / (2 * n))
v_max_n = n // 3
(i for i in product(range(2, v_max_n + 1, 2),
range(2, v_max + 1, 2),
range(3, v_max + 1))
if i[0] <= i[1] and i[1] <= i[2] and sum(i) <= n and
i[0] ** 2 + i[1] ** 2 == i[2] ** 2 - 1)
</code></pre>
<p>I have tried using it as <code>map(lambda x: x, gen)</code>, nested for loops, and have generally been racking my brain to no avail.</p>
<p>I tried re-writing b, c as expressions. This tends to be quick but misses some of the triples.</p>
<pre><code>n = 12
v_max = math.floor(n / 2 - 1 / (2 * n))
v_max_n = n // 3
j = 0 # tested this with low n and compared: 12, 150 to see
for a in range(1, v_max_n + 1, 1):
b = (n ** 2 - 2 * n * a - 1) / (2 * (n - a))
c = (a ** 2 + b ** 2 + 1) ** 0.5
if c % 1 == 0 and b % 1 == 0 and a + int(b) + int(c) <= n:
# print(a, int(b), int(c))
j += 1
print(j)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:28:45.097",
"Id": "405503",
"Score": "0",
"body": "For me this does not even fit into memory (16 GB). Which is weird, since `product` should not make any intermediate lists and neither should `range`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:31:33.027",
"Id": "405506",
"Score": "0",
"body": "@Graipher you should just get a generator object when you initialize the generator which shouldn't use any memory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:32:32.803",
"Id": "405508",
"Score": "0",
"body": "I agree. Yet it does consume memory on my machine (even with Python 3.6.3)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:34:47.863",
"Id": "405511",
"Score": "0",
"body": "@Graipher I am on 3.6.6 Anaconda on Mac. Only 8 GBs of RAM, I checked my memory when creating the object but didn't have that problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:36:10.497",
"Id": "405512",
"Score": "0",
"body": "Very weird, will investigate that later. That shouldn't matter for your question, though. Anyways, can you actually define `v_max_n` and `v_max` in your code? Also, `n` does not seem to have anything to do with the rest of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:36:51.737",
"Id": "405513",
"Score": "1",
"body": "@Graipher sum(i) <= n. Added the variable definitions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:26:59.527",
"Id": "405537",
"Score": "0",
"body": "`... and i[0] ** 2 + i[1] ** 2 == i[2] ** 2 - 1` Can't you calculate `i[2]` directly instead of testing all possible values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:40:56.520",
"Id": "405543",
"Score": "0",
"body": "@tobias_k of course but then our product is larger. Not sure if that would be faster or slower though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:46:30.480",
"Id": "405544",
"Score": "0",
"body": "@tobias_k Improvement is very small for small n and yields the same results for large n."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:24:55.580",
"Id": "405567",
"Score": "1",
"body": "It would probably help to tell what problem you are actually trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:27:47.780",
"Id": "405569",
"Score": "0",
"body": "@Josay See comment below my answer: [Project Euler #224](https://projecteuler.net/problem=224)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:43:53.627",
"Id": "405577",
"Score": "0",
"body": "@Josay I'm not sure I agree with that edit of the title. The original question asked for \"optimizing this generator\", which is technically not the same as \"solve this problem\". E.g. my answer certainly makes the generator faster (and those general hints are applicable to similar problems, too), but it's still far from solving the Project Euler problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:45:08.567",
"Id": "405579",
"Score": "0",
"body": "@tobias_k Fair enough, I'm happy to see a more precise name but the original name clearly conveys no intent about what the code is trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:47:30.977",
"Id": "405582",
"Score": "0",
"body": "@Josay Agreed. Maybe \"Optimizing generator for solving Project Euler #224\" or something like that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:49:58.953",
"Id": "405583",
"Score": "0",
"body": "@tobias_k This is fine for me. Also, if your optimised solutions is still far from solving the PE problem, I reckon the question should be closed as \"code not working\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T18:54:45.980",
"Id": "405613",
"Score": "0",
"body": "\"Looking to run it under a minute\" might be impossible depending on the specs of the computer you're using."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T19:24:10.457",
"Id": "405622",
"Score": "0",
"body": "@IEatBagels according to the website, a modestly powered computer can accomplish this task.\nhttps://projecteuler.net/about"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T21:13:39.907",
"Id": "405641",
"Score": "1",
"body": "A running time \"under a minute\" (or in a few minutes, but somewhere in that ballpark) is certainly possible, but _not_ using a brute-force-search over (10^6)^3 possibilities."
}
] | [
{
"body": "<p>It seems like you want to find a solution for <code>a²+b²=c²-1</code> with some added constraints, like <code>a<=b<=c</code>, <code>a+b+c<=n</code>, etc. by trying <em>all</em> possible combinations of <code>a</code>, <code>b</code>, and <code>c</code> and testing whether they satisfy all your conditions at once. This is pretty wasteful.</p>\n\n<p>Instead of <code>itertools.product</code>, you can use a generator expression with three regular <code>for</code> loops. This has several advantages:</p>\n\n<ul>\n<li><p>you could move some of the <code>if</code> clauses up after the first or second loop, i.e. you don't have to run the other loops if those conditions already fail at this point, e.g.</p>\n\n<pre><code> for x in ... if test(x) for y in ... if test(y) ...\n</code></pre></li>\n<li><p>you can use the values of your previous variables in the lower and upper bounds for the later variables (in your case this replaces most of your <code>if</code> conditions)</p></li>\n<li>you can basically <em>calculate</em> the value for <code>c</code> from <code>a</code> and <code>b</code> without testing all possible values</li>\n</ul>\n\n<p>This is how I'd do it:</p>\n\n<pre><code>gen = ((a, b, int(c))\n for a in range(2, v_max_n + 1, 2)\n for b in range(a, min(v_max + 1, n - a - a), 2) # use a for lower and upper bounds\n for c in [(a ** 2 + b ** 2 + 1)**0.5] # just a single candidate for c\n if c % 1 == 0) # whole-numbered c found?\n</code></pre>\n\n<p>Note that the calculation of <code>c</code> using <code>very_large_number**0.5</code> might be imprecise with <code>float</code>; using <code>decimal</code> might work, though. However, even with those optimizations, testing much fewer values than your original loop (on the order of O(n²) instead of O(n³)), it might not be feasible to find solution for large values of <code>a</code>, <code>b</code> and <code>c</code>.</p>\n\n<p>Also note that I did not thoroughly test this for off-by-one errors, since performance was the main concern.</p>\n\n<p>Another thing that you might try: Invert the loops for <code>a</code> and for <code>b</code>, i.e. instead of testing all <code>b</code> for each <code>a</code>, no matter how large the difference, test all <code>a</code> up to <code>b</code> first. This does not decrease the number of combinations to test, but it seems to yield much more valid combinations in the \"smaller\" number much faster. Like this (upper bound for <code>b</code> can probably be reduced):</p>\n\n<pre><code> for b in range(2, v_max + 1, 2)\n for a in range(2, b+1, 2)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:53:57.210",
"Id": "405546",
"Score": "0",
"body": "It is feasible to find solutions for large N people have solved it with many languages just not an easy task.\nhttps://projecteuler.net/problem=224"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:03:33.603",
"Id": "405548",
"Score": "0",
"body": "@dustin Surely it is possible, but certainly not using three nested loops with ~10**18 combinations. I don't know what those folks were using, but probably some high-level fancy math."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:05:09.183",
"Id": "405551",
"Score": "0",
"body": "I tried all kinds of equation re-written and have like 10 code snippets. This generator one was over 1000x better at lower n but just couldn't hang as n increased."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:26:41.293",
"Id": "405556",
"Score": "0",
"body": "I think you need to look at the math more. One thing that will help is that you can put upper bounds on how high to search for one of the numbers based on the gaps between consecutive squares."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:33:43.517",
"Id": "405557",
"Score": "0",
"body": "@OscarSmith That sounds like a great idea, but IMHO that's beyond the scope of my answer. My main point was \"using individual loops with adaptive bounds and if checks in between is faster than product with lots of checks for each combination\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:35:18.997",
"Id": "405558",
"Score": "1",
"body": "yeah I don't disagree. I'm seeing if I can get an answer up that uses this now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T21:36:19.877",
"Id": "405643",
"Score": "0",
"body": "Re \"*probably some high-level fancy math*\": not really. A lot of people solved it using an algebraic identity which I was taught at age 12 or 13."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:51:20.773",
"Id": "209833",
"ParentId": "209821",
"Score": "3"
}
},
{
"body": "<p>One improvement over @tobias_k s answer is to add the extra upper bound on b of <code>b<1 + a*a//2</code>. This is valid because after that, the distance between <code>b^2</code> and <code>(b+1)^2</code> will be bigger than <code>a^2</code>, so <code>c^2</code> does not exist. This provides a massive speedup at least a first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:17:27.033",
"Id": "405562",
"Score": "0",
"body": "Did you actually test this? Try 10 ** 3. On my machine, it has poorer performance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:23:12.793",
"Id": "405565",
"Score": "0",
"body": "Nice. That's a _massive_ speedup, but it still takes ages until `a` gets anywhere close to it's upper bound. (Did not thorougly check whether this actually does not skip any values, though)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:26:26.307",
"Id": "405568",
"Score": "0",
"body": "@dustin How did you add that \"extra check\"? I added it to the `min`; did you do something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:35:17.710",
"Id": "405571",
"Score": "0",
"body": "@tobias_k I am using timeit for this edit. I added to the min as you say and your solution is still faster without it by 2.3ns and a smaller std. Also, beyond 10 ** 3, it is still going over a minute and I end up stoping the interrupt since it is running very long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:39:05.633",
"Id": "405573",
"Score": "0",
"body": "@dustin \"faster by 2.3 ns\" is nothing. I did not test it, but maybe the condition is not triggered very often for small n so the additioal check adds a tiny amount of computational overhead without much use. How are you printing your results? Are you getting all the valid results first, or printing them as they come? As I said, waiting for all results still takes ages (after some time, `a` barely climbed into the lower 1000s) , but the individual results come in much faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:41:10.427",
"Id": "405574",
"Score": "0",
"body": "@tobias_k incrementing a counter but not printing, displaying, or storing the results"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:41:35.773",
"Id": "405575",
"Score": "0",
"body": "this will mainly help when n is massive. Since the other cutoffs in the min are based around n-something, what this does is it prevents you from needing to search almost all b values for smallish a. Specificially with `n=1.5*10**9`, it cuts off `b>5000`, for `a=100` instead of `b=10**9`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:45:26.043",
"Id": "405580",
"Score": "0",
"body": "@dustin Try printing the counter (or the actual element) when you increase the counter, not just when you finished the generator, then you should see a speedup."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:08:23.283",
"Id": "209842",
"ParentId": "209821",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>v_max_n = n // 3\n</code></pre>\n</blockquote>\n\n<p>The name of this variable is a mystery to me, but you seem to be using it as an upper bound on <span class=\"math-container\">\\$a\\$</span>. You can get a notably better upper bound on <span class=\"math-container\">\\$a\\$</span> very easily: since <span class=\"math-container\">\\$a \\le b\\$</span> and <span class=\"math-container\">\\$c^2 = a^2 + b^2 + 1\\$</span>, <span class=\"math-container\">\\$a + b + c \\ge 2a + \\sqrt{2a^2 + 1} > 2a + \\sqrt{2a^2} = (2 + \\sqrt 2)a\\$</span>. Then your upper bound on <span class=\"math-container\">\\$a\\$</span> can be reduced by 12.13%.</p>\n\n<hr>\n\n<p>Given a value of <span class=\"math-container\">\\$a\\$</span>, the constraints on <span class=\"math-container\">\\$b\\$</span> are <span class=\"math-container\">\\$a \\le b\\$</span> and <span class=\"math-container\">\\$a + b + \\sqrt{a^2+b^2+1} \\le n\\$</span>. Rearrange and square: <span class=\"math-container\">\\$a^2 + b^2 + 1 \\le n^2 + a^2 + b^2 - 2an +2ab -2bn\\$</span> or <span class=\"math-container\">\\$b \\le \\frac{n^2 - 2an - 1}{2n - 2a}\\$</span>. I'm not sure why you appear to be using this <em>bound</em> as a <em>forced value</em> in the code you added to the question.</p>\n\n<hr>\n\n<p><span class=\"math-container\">$$\\sum_{a=1}^{\\frac{n}{2 + \\sqrt 2}} \\left(\\frac{n^2 - 2an - 1}{2n - 2a} - a\\right)\n= \\left(\\sum_{a=1}^{\\frac{n}{2 + \\sqrt 2}} \\frac{n^2 - 2an - 1}{2n - 2a}\\right) - \\frac{n(n + 2 + \\sqrt 2)}{2(2 + \\sqrt 2)^2} \\\\\n= \\frac{n^2 + 1}2 \\left(\\psi\\left(\\frac{n}{2 + \\sqrt 2}-n+1\\right) - \\psi(1-n)\\right) + \\frac{n^2}{2 + \\sqrt 2} - \\frac{n(n + 2 + \\sqrt 2)}{2(2 + \\sqrt 2)^2} \\\\\n= \\frac{n^2 + 1}2 \\left(\\psi\\left(1-\\frac{1+\\sqrt2}{2 + \\sqrt 2}n\\right) - \\psi(1-n)\\right) + \\frac{(3 + 2\\sqrt 2)n^2 + (2 + \\sqrt 2)n}{2(2 + \\sqrt 2)^2} \\\\\n> 0.9n^2\n$$</span>\nThe step from the sum to an expression in terms of the digamma function is courtesy of Wolfram Alpha.</p>\n\n<p>As a rule of thumb, you don't want to be repeating a loop body <span class=\"math-container\">\\$10^{12}\\$</span> times, so looping over all values of <span class=\"math-container\">\\$a\\$</span> and all values of <span class=\"math-container\">\\$b\\$</span> is a non-starter.</p>\n\n<hr>\n\n<p>Hint: try rearranging <span class=\"math-container\">\\$a^2 + b^2 = c^2 - 1\\$</span>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:15:17.213",
"Id": "209894",
"ParentId": "209821",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:20:02.950",
"Id": "209821",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"iterator",
"generator"
],
"Title": "Python generator for \"barely obtuse\" triangles (Project Euler 224)"
} | 209821 |
<p>Follow-up question: <a href="https://codereview.stackexchange.com/questions/210041/display-all-files-in-a-folder-object-along-with-nested-subdirectories-part-2">Display all files in a folder (object) along with nested subdirectories part 2</a></p>
<p><strong>Task:</strong> Given a main directory/folder, list all the files from it and if this directory have other nested sub-directories, list files from them also.</p>
<p><strong>Background history:</strong> short story long - I got an internship, no past experience with asp.net-mcv-5, a nuisance of an assignment (Yet fulfilling), and now I want to optimize my code, giving the content is to be used for our intern job portal.</p>
<p><strong>Path to a functional solution:</strong> In my quest for finding a solution have I looked at various recursive programs writing in other languages. However, they all made use of methods and after further research, I found out about @funtions in razor. It came to my conclusion, that people have different opinions on when, and if ever they should be used. That lead me to choose a different route, to finding a solution. I decided to go with Stacks inorder to store a collection of previous sub-directories, as I worked my way down each individual folder to display their content.</p>
<p>I would greatly appreciate feedback. And should there be any problems with my post regarding community rules, let me know.</p>
<p><strong>Ps. </strong>My english dictionary isn't quite developed, so should you have any recommendations with how I should describe things. Please be specific, and concrete.</p>
<pre><code>@foreach (var parentFolder in Model)
{
Stack<Folder> folderStack = new Stack<Folder>();
folderStack.Push(parentFolder);
var currentFolder = folderStack.Pop();
int dummyCounter = 1;
//Parent folder
<div class="row">
<div class="col-sm-2">
<a class="btn"
role="button"
data-toggle="collapse"
href="#@currentFolder.Id"
aria-expanded="false"
aria-controls="@currentFolder.Id">
<span class="@GlyphionCategoryIcon"></span>
</a>
</div>
<div class="col-sm-5">@currentFolder.Id</div>
<div class="col-sm-5">@currentFolder.Name</div>
</div>
<div class="collapse" id="@currentFolder.Id">
@if (currentFolder.FoldersContained != 0)
{
do
{
//Prevents a copy of the parent folder, otherwise this display nested folders
if (dummyCounter != 1)
{
<div class="row">
<div class="col-sm-2">
<a class="btn"
role="button"
data-toggle="collapse"
href="#@currentFolder.Id"
aria-expanded="false"
aria-controls="@currentFolder.Id">
<span class="@GlyphionCategoryIcon"></span>
</a>
</div>
<div class="col-sm-5">@currentFolder.Id</div>
<div class="col-sm-5">@currentFolder.Name</div>
</div>
}
// Create a collapse div using bootstrap 3.3.7
<div class="collapse" id="@currentFolder.Id">
@if (currentFolder.FoldersContained > 0)
{
for (int i = currentFolder.FoldersContained; i > 0; i--)
{
//Pushes all nested directories into my stack
//in reverse inorder to display the top directory
folderStack.Push(currentFolder.Folders[i - 1]);
dummyCounter++;
}
}
@if (currentFolder.FilesContained != 0)
{
// Should they contain any files, display them
foreach (var file in currentFolder.Files)
{
<div class="row">
<div class="col-sm-2">
<a class="btn"
role="button"
href="@webUrl@file.Url"
target="_blank">
<span class="@GlyphionPaperIcon"></span>
</a>
</div>
<div class="col-sm-5">@file.Id</div>
<div class="col-sm-5">@file.Name</div>
</div>
}
}
</div>
//Ends the while loop
if (folderStack.Count == 0)
{
dummyCounter = 0;
}
//Prepares the next nested folder object
if (folderStack.Count != 0)
{
currentFolder = folderStack.Pop();
}
// I make use of a dummy counter inorder to break the loop
// should there no longer be any nested directories and files
// left to display
} while (dummyCounter != 0);
}
//Finally, display all files in the parent folder, should there be any
@if (parentFolder.FilesContained != 0)
{
foreach (var file in parentFolder.Files)
{
<div class="row">
<div class="col-sm-2">
<a class="btn"
role="button"
href="@webUrl@parentFolder.Url"
target="_blank">
<span class="@GlyphionPaperIcon"></span>
</a>
</div>
<div class="col-sm-5">@parentFolder.Id</div>
<div class="col-sm-5">@parentFolder.Name</div>
</div>
}
}
</div>
}
</code></pre>
<p>Output: (dummy data, folders expanded)
<a href="https://i.stack.imgur.com/bsKv5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bsKv5.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T12:59:30.423",
"Id": "405523",
"Score": "1",
"body": "**The site standard 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/a/2438/41243) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T13:40:52.263",
"Id": "405528",
"Score": "0",
"body": "@BCdotWEB Could you give an example? My code simply takes an object<Folder> and iterates through its content and display it in html. I'm using asp.net-mcv and the code is writing in razor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:04:13.053",
"Id": "405549",
"Score": "1",
"body": "For one, no need for \"ASP.NET MVC Razor\", that's what the tags are for. But \"dynamic folder iteration HTML display\" is less of a sentence, and more a bunch of words. \"Displays it in HTML\" is needlessly technical. Why not something like \"Navigating the contents of folders on a website\"? However, I don't know what your code is supposed to do, so that's something you need to describe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:46:41.910",
"Id": "405599",
"Score": "2",
"body": "This is what I call a fix! Great job ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T21:11:42.660",
"Id": "405640",
"Score": "0",
"body": "@t3chb0t Thanks for your kind message, greatly appriciated :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:57:32.180",
"Id": "405962",
"Score": "0",
"body": "Please do not modify the code in question after receiving answers. You can post a self-answer or a new question if you wish another review.... this needs to be rolledback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:17:00.420",
"Id": "405965",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>I have just two comments:</p>\n\n<ul>\n<li>The name <code>dummyCounter</code> is really terrible, you should find something more appropriate like <code>currentDepth</code> or something but you actually don't need this at all, you can use the <code>folderStack</code> and just <em>ask</em> it whether it's not empty with <code>folderStack.Any()</code></li>\n<li><p>You use the same <em>html</em> snippet four times (!)</p>\n\n<blockquote>\n<pre><code><div class=\"row\">\n <div class=\"col-sm-2\">\n <a class=\"btn\"\n role=\"button\"\n data-toggle=\"collapse\"\n href=\"#@currentFolder.Id\"\n aria-expanded=\"false\"\n aria-controls=\"@currentFolder.Id\">\n <span class=\"@GlyphionCategoryIcon\"></span>\n </a>\n </div>\n <div class=\"col-sm-5\">@currentFolder.Id</div>\n <div class=\"col-sm-5\">@currentFolder.Name</div>\n</div>\n</code></pre>\n</blockquote>\n\n<p>This should be a partial view that you can reuse instead of copy-pasting it everywhere. The values that are chaniging can be passed via its own new model.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T21:56:54.927",
"Id": "405914",
"Score": "0",
"body": "Thanks for your insight, I will differently look into how partial view works and it's implementation. However considering your first suggestment, I have already tired using my stack as a way to end my while loop. But it lead to missing out on the last folder, as the while loop would end after I pop the last element to prepare my the \"final\" loop. I also haven't firgured out a way to print my parent folder without using an if statement to skip my second folder \"creating\" in order to prevent duplicating my parent folder."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:28:59.137",
"Id": "209991",
"ParentId": "209823",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209991",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:26:41.863",
"Id": "209823",
"Score": "4",
"Tags": [
"c#",
"performance",
"asp.net-mvc-5",
"razor"
],
"Title": "Display all files in a folder (object) along with nested subdirectories"
} | 209823 |
<p>I've got a .csv file with ZIP codes containing the city and its sub-districts</p>
<pre>
67401,City 1,district_a
67401,City 2,district_b
67401,City 3,district_c
67401,City 3,district_d
67401,City 3,district_e
67401,City 3,district_f
67401,City 3,district_g
67401,City 3,district_h
67401,City 3,district_i
67401,City 3,district_j
67401,City 3,district_k
67401,City 3,district_l
67401,City 3,district_m
67401,City 3,district_n
67401,City 3,district_o
67401,City 3,district_p
67401,City 3,district_q
67401,City 3,district_r
67401,City 3,district_s
67401,City 4,district_t
67401,City 5,district_u
67501,City 6,district_v
67501,City 7,district_w
67501,City 8,district_x
67501,City 8,district_y
67501,City 8,district_z</pre>
<p>And I need to put it in an array, where I can select/search by the zip code (67401, 67501, etc.) and return these results as an associative array in this format, so I can populate a select control.</p>
<p>For example I want to look-up all the Cities and its districts with zip code 67401 I need this result:</p>
<pre><code>"City 1" => [
district_a => district_a
],
"City 2" => [
district_b => district_b
],
"City 3" => [
district_c => district_c
district_d => district_d
district_e => district_e
district_f => district_f
district_g => district_g
district_h => district_h
district_i => district_i
district_j => district_j
district_k => district_k
district_l => district_l
district_m => district_m
district_n => district_n
district_o => district_o
district_p => district_p
district_q => district_q
district_r => district_r
district_s => district_s
],
"City 4" => [
district_t => district_t
],
"City 5" = [
district_u => district_u
]
</code></pre>
<p>Right now I've got this working code, but I'm sure there has to be a simpler way to achieve it.</p>
<pre><code><?php
$zipcode = '67401';
$a = file("zip.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$a = array_map(function ($i) {return explode(',', $i); }, $a);
$a = array_filter($a, function ($i) use ($zipcode) { return $i[0] == $zipcode; });
$b = [];
$i = 0;
foreach ($a as $key => $value) {
$b[$i++] = [
'city' => $value[1],
'district' => $value[2],
];
}
$c = [];
foreach($b as $key => $item) {
$c[$item['city']][$key] = $item;
}
ksort($c, SORT_REGULAR);
$d = [];
foreach($c as $key => $value) {
$subarray = [];
foreach($value as $s_key => $s_val) {
foreach($s_val as $ss_key => $ss_val) {
$subarray[$ss_val] = $ss_val;
}
}
$d[$key] = $subarray;
}
$myresult = $d;
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:33:08.280",
"Id": "405509",
"Score": "2",
"body": "Any chance to store this data in a database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:37:07.677",
"Id": "405514",
"Score": "0",
"body": "Yes, that would be possible. But still I would get the same results from database as are stored in variable $a, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T12:09:35.317",
"Id": "405518",
"Score": "3",
"body": "You would never get the same results from a database as it can filter out and sort the data for you. And a database API can format the resulting array"
}
] | [
{
"body": "<p>Well, first of all this data must be stored in a database, not a file. <a href=\"https://phpdelusions.net/pdo/fetch_modes#FETCH_GROUP\" rel=\"nofollow noreferrer\">Using PDO</a> you'll get your array in a few lines (assuming a database connection is already established):</p>\n\n<pre><code>$sql = \"SELECT city, district FROM zip WHERE zipcode=? ORDER BY city, district\";\n$stmt = $pdo->prepare($sql);\n$stmt->execute([$zipcode]);\n$data = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN); \n</code></pre>\n\n<p>As of the code present, there are way too much loops to my taste. I believe everything could be done in one loop, like</p>\n\n<pre><code>$zipcode = '67401';\n$data = [];\nforeach (file(\"zip.csv\", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $row) {\n list($zip, $city, $district) = explode(\",\",$row);\n if ($zip == $zipcode) {\n if (!isset($data[$city])) {\n $data[$city] = [];\n }\n $data[$city][] = $district;\n }\n}\n</code></pre>\n\n<p>well if you need to sort your arrays, a couple extra loops are still needed</p>\n\n<pre><code>ksort($data);\nforeach ($data as $city => $array) {\n sort($data[$city]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:49:51.950",
"Id": "209826",
"ParentId": "209825",
"Score": "2"
}
},
{
"body": "<p>Some extra inspirational stuff ;)</p>\n\n<pre><code>// Load your CSV into array\n$zipcode = '67401';\n$options = [];\n$fh = fopen('zip.csv', 'r');\nwhile (($data = fgetcsv($fh)) !== false) {\n if ($zipcode == $data[0]) {\n list($zip, $city, $district) = $data;\n $options[$city][$district] = $district;\n }\n}\nfclose($fh);\n\n// Sort cities\nksort($options);\n\n// Sort districts\narray_walk($options, function(&$districts) {\n ksort($districts);\n});\n\n// Enjoy!\nprint_r($options);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T12:53:07.043",
"Id": "405522",
"Score": "0",
"body": "This code is more memory efficient than mine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T13:30:34.643",
"Id": "405527",
"Score": "0",
"body": "@YourCommonSense I think it will be noticeable only for large files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T12:20:12.393",
"Id": "209828",
"ParentId": "209825",
"Score": "1"
}
},
{
"body": "<p>If this were my project, I'd certainly entertain the idea of using regex. Now, it is common knowledge that regular expressions typically offer flexibility with a cost of drag on efficiency. However, because it avoids reading line by line and so many iterated explosions, there may be a chance that it performs well on your large data size. (no guarantees, just a suggestion to benchmark)</p>\n\n<p>Code:</p>\n\n<pre><code>$zip = '67401';\nif (preg_match_all(\"~^{$zip},([^,]+),([^,]+)$~m\", file_get_contents('zip.csv'), $matches)) {\n foreach ($matches[1] as $index => $city) {\n $result[$city][$matches[2][$index]] = $matches[2][$index];\n }\n}\nvar_export($result); // see the correct/desired result\n</code></pre>\n\n<p>The simple above pattern, matches one whole line at a time by using anchors <code>^</code> and <code>$</code>. The <code>$zip</code> variable is wrapped in curly braces as a matter of personal preference / readability, but it is not captured, because the value is known and it is not used in the output. By using negated characters classes containing commas, the regex engine can move with maximum efficiency (in a greedy fashion).</p>\n\n<hr>\n\n<p>Alternatively, it seems a good idea to <code>break</code> early (assuming your csv file is already sorted by zipcode). Of course, a function like <code>fgetcsv()</code> is a very sensible/reliable tool for processing rows of csv data. The following snippet largely resembles @Victor's answer.</p>\n\n<pre><code>$zipcode = '67401';\n$result = [];\n$handle = fopen('zip.csv', 'r');\nwhile (($row = fgetcsv($handle)) !== false) {\n if ($zipcode == $row[0]) {\n $result[$row[1]][$row[2]] = $row[2];\n } elseif ($result) { // the current row doesn't match $zipcode; and $result is not empty\n break;\n }\n}\nfclose($handle);\nvar_export($result);\n</code></pre>\n\n<p>and of course, if you prefer to write meaningful variables names, you can make iterated declarations of <code>$zip</code>, <code>$city</code>, and <code>$district</code> if you like, by way of <a href=\"https://webdevetc.com/blog/php-7-array-destructuring-explained\" rel=\"nofollow noreferrer\">array destructuring</a>.</p>\n\n<p>p.s. If your csv data is not already pre-sorted and you require the output to be sorted in a particular way, please express these facts in your question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T06:57:46.627",
"Id": "210464",
"ParentId": "209825",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:31:47.043",
"Id": "209825",
"Score": "3",
"Tags": [
"php",
"array",
"csv"
],
"Title": "Select data from csv and make associative array"
} | 209825 |
<p>This is refactored and much more expanded version of the script reviewed <a href="https://codereview.stackexchange.com/questions/209423/spotify-api-data-to-vk-com-users-status">here</a>. The whole authorization process is added.</p>
<pre><code>import os
import secrets
import string
import time
import webbrowser
import furl
import requests
import simplejson as json
import config
URL_CODE_BASE_VK = 'https://oauth.vk.com/authorize'
URL_CODE_BASE_SP = 'https://accounts.spotify.com/authorize'
URL_TOKEN_VK = 'https://oauth.vk.com/access_token'
URL_TOKEN_SP = 'https://accounts.spotify.com/api/token'
URL_TRACK = 'https://api.spotify.com/v1/me/player/currently-playing'
URL_STATUS = 'https://api.vk.com/method/status.set'
EXP_IN_TOKEN_SP = 3400
EXP_IN_TOKEN_VK = 86400
FILE_TOKEN_VK = 'vk_token.json'
FILE_TOKEN_SP = 'sp_token.json'
INP_MSG = '''Enter the full URL, that you have been redirected on after giving
the permissions: '''
def get_auth_code_vk():
url_code_params = {
'client_id': config.CLIENT_ID_VK,
'response_type': 'code',
'redirect_uri': 'https://oauth.vk.com/blank.html',
'v': 5.92,
'scope': 'status',
'state': gen_state(),
'display': 'page'
}
code = url_open(URL_CODE_BASE_VK, url_code_params)
return parse_code(code)
def get_auth_code_sp():
url_code_params = {
'client_id': config.CLIENT_ID_SP,
'response_type': 'code',
'redirect_uri': 'https://www.spotify.com/',
'scope': 'user-read-currently-playing',
'state': gen_state()
}
code = url_open(URL_CODE_BASE_SP, url_code_params)
return parse_code(code)
def gen_state():
symbols = string.ascii_lowercase + string.digits
return ''.join(secrets.choice(symbols) for _ in range(12))
def url_open(url_base, url_params):
url_code_full = furl.furl(url_base).add(url_params).url
webbrowser.open_new_tab(url_code_full)
input_url = input(INP_MSG)
return input_url
def parse_code(url):
return (url.split("code=")[1]).split("&state=")[0]
def get_token_vk():
data = {
'grant_type': 'authorization_code',
'code': get_auth_code_vk(),
'redirect_uri': 'https://oauth.vk.com/blank.html',
'client_id': 6782333,
'client_secret': config.CLIENT_SECRET_VK
}
response = requests.post(url=URL_TOKEN_VK, data=data).json()
write_file(FILE_TOKEN_VK, response)
def get_token_sp():
data = {
'grant_type': 'authorization_code',
'code': get_auth_code_sp(),
'redirect_uri': 'https://www.spotify.com/',
'client_id': config.CLIENT_ID_SP,
'client_secret': config.CLIENT_SECRET_SP
}
response = requests.post(url=URL_TOKEN_SP, data=data).json()
write_file(FILE_TOKEN_SP, response)
def write_file(tkn_file, response):
token = {}
token['token'] = response["access_token"]
token['time'] = time.time()
with open(tkn_file, 'w') as file:
file.write(json.dumps(token))
def load_file(tkn_file):
with open(tkn_file) as file:
data = json.load(file)
return data
def set_status():
params = {
'user_id': 8573490,
'v': 5.92,
'access_token': load_file(FILE_TOKEN_VK)['token'],
'text': current_track()
}
response = requests.get(url=URL_STATUS, params=params)
error = http_error(response)
if error:
return error
return response
def track_data():
tkn_file = load_file(FILE_TOKEN_SP)['token']
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {tkn_file}'
}
return requests.get(url=URL_TRACK, headers=headers)
def current_track():
response = track_data()
error = http_error(response)
if error:
return error
data = response.json()
artist = data['item']['artists'][0]['name']
track = data['item']['name']
return f'{artist} - {track}'
def http_error(response):
try:
response.raise_for_status()
return None
except requests.exceptions.HTTPError as error:
return error
def check_playback():
if track_data().status_code == 204:
print("Not playing")
else:
set_status()
print(current_track())
def token_missing(file):
return not os.path.isfile(file)
def token_expired(file, exp_in):
return time.time() - load_file(file)['time'] > exp_in
def token_not_valid(file, exp_in):
return token_missing(file) or token_expired(file, exp_in)
def run_script():
if token_not_valid(FILE_TOKEN_VK, EXP_IN_TOKEN_VK):
get_token_vk()
if token_not_valid(FILE_TOKEN_SP, EXP_IN_TOKEN_SP):
get_token_sp()
check_playback()
if __name__ == "__main__":
run_script()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:33:06.187",
"Id": "405850",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
}
] | [
{
"body": "<h3>Parse URLs with <code>furl</code></h3>\n\n<p>This method looks like a hacky way to get the value of the <code>code</code> parameter from a query string:</p>\n\n<blockquote>\n<pre><code>def parse_code(url):\n return (url.split(\"code=\")[1]).split(\"&state=\")[0]\n</code></pre>\n</blockquote>\n\n<p>Since the script already imports <code>furl</code>, why not use it for this job:</p>\n\n<pre><code>def parse_code(url):\n return furl(url).args.get('code', '')\n</code></pre>\n\n<p>As you mentioned in a comment, the parameters in the URL are not proper query parameters following <code>?</code>, but encoded in the URL fragment after <code>#</code>.\nIn this case, I suggest to replace the beginning of the string until <code>#</code> with <code>?</code>, and then apply <code>furl</code>:</p>\n\n<pre><code>def parse_code(url):\n # urls contain the parameters encoded in the fragment after #\n url = '?' + url[url.find('#')+1:]\n return furl(url).args.get('code', '')\n</code></pre>\n\n<h3>Avoid magic values</h3>\n\n<p>It's good that you have defined some constants at the top of the file.\nIt would be good to go a bit further and define some more,\nbecause there are still quite many magic values scattered around in the code,\nfor example these definitely deserve some explanation (by a good name),\nor to come from configuration:</p>\n\n<blockquote>\n<pre><code>'redirect_uri': 'https://oauth.vk.com/blank.html',\n'v': 5.92,\n# ...\n\n'client_id': 6782333,\n'user_id': 8573490,\n# ...\n\nreturn ''.join(secrets.choice(symbols) for _ in range(12))\n# ^^ why 12?\n</code></pre>\n</blockquote>\n\n<h3>Avoid redundant local variables</h3>\n\n<p>There are some local variables that are set once and then immediately returned. I don't see much value brought by these variables, I would return the values directly, for example here:</p>\n\n<blockquote>\n<pre><code>input_url = input(INP_MSG)\nreturn input_url\n# ...\n\nwith open(tkn_file) as file:\n data = json.load(file)\nreturn data\n# ...\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T06:43:29.250",
"Id": "405677",
"Score": "0",
"body": "`return furl(URL).args.get('code')` this does not work in vk.com case because the code is returned like this `https://oauth.vk.com/blank.html#code=`. Initially, I've had different parsing lines for two services. Had something similar to your proposal for the Spotify auth code. The way in my code is really hacky, yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T07:16:01.117",
"Id": "405679",
"Score": "0",
"body": "@Flynn84 in that case, I guess you want to get empty string instead of `None`, you can pass a default value to `get`: `furl(URL).args.get('code', '')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T07:18:58.417",
"Id": "405680",
"Score": "0",
"body": "`return ''.join(secrets.choice(symbols) for _ in range(12))` it is really a random number, what should be better in this case, define a constant with that number? Or put another generator for this number? For example, generate a random length of `state` parameter between 8 and 20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T07:20:55.450",
"Id": "405681",
"Score": "0",
"body": "@Flynn84 I meant that perhaps you could define a constant for 12, for example `SECRET_LENGTH = 12`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T07:47:34.090",
"Id": "405683",
"Score": "0",
"body": "I meant that there is an actual code being passed but furl and other URL functions couldn't parse it because there is `#` instead of `?`. If I understood it correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T07:52:44.770",
"Id": "405684",
"Score": "0",
"body": "@Flynn84 I see. In that case, I would recommend to replace the beginning of the url until `#` with `?`, for example with `furl('?' + u[u.find('#')+1:]).args.get('code')`. Although this is a bit hacky, it's still better than the original. I updated my answer accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T06:50:13.540",
"Id": "405795",
"Score": "0",
"body": "This change is forcing us to use an `if` condition in the function. Is that ok? Take a look, I've added the new implementation to the initial post. I've read that the `inspect` is not the best thing to put into production code, mostly used for a debugging"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T07:00:51.553",
"Id": "405796",
"Score": "0",
"body": "@Flynn84 no, don't use `inspect`. Using `inspect` makes this overall worse than your original. I didn't realize that you need to support two kinds of patterns. In this case, it would be better to split `parse_code` to two functions, `parse_code_vk` and `parse_code_sp`, like you did for other steps."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:27:43.377",
"Id": "209845",
"ParentId": "209827",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "209845",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T11:57:20.903",
"Id": "209827",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Spotify current track to vk.com user's status"
} | 209827 |
<p>I am working on a math library for an online game. I want to prevent as many errors as possible and I want to catch all errors as early as possible to simplify debugging in the long run. However, I feel like I drown in details. This is quite different from "let it crash" motto.</p>
<p><code>point</code> has <code>{number(), number()}</code> type or better say <code>{0, 0}</code> is a point. I started with <code>Dialyzer</code> specs and guard statements which work as a poor man's assertions. </p>
<p>Here is my <code>point</code> class. </p>
<pre><code>-module(point).
-author("nt").
-export([is_point/1, distance/2, translate/2, pointToMap/1]).
-type point() :: {number(), number()}.
-export_type([point/0]).
is_point({X, Y}) when is_number(X), is_number(Y) -> true;
is_point(_) -> false.
distance({X1, Y1} = A, {X2, Y2} = B) ->
case is_point(A) of false -> error(badarg); _ -> ok end,
case is_point(B) of false -> error(badarg); _ -> ok end,
math:sqrt(math:pow((X2 - X1), 2) + math:pow(Y2 - Y1, 2)).
translate({X1, Y1} = A, {X2, Y2} = B) ->
case is_point(A) of false -> error(badarg); _ -> ok end,
case is_point(B) of false -> error(badarg); _ -> ok end,
{X1 + X2, Y1 + Y2}.
pointToMap({X, Y} = A) ->
case is_point(A) of false -> error(badarg); _ -> ok end,
#{
x => X,
y => Y
}.
%% Spec
-spec is_point(P :: point()) -> boolean().
-spec distance(A :: point(), B :: point()) -> float().
-spec translate(A :: point(), B :: point()) -> point().
-spec pointToMap(A :: point()) -> #{x:= number(), y := number()}.
</code></pre>
<p><code>{{0, 0}, {0, 0}}</code> is a <code>rect</code>.
<code>rect</code> "class" relies on <code>point</code>.</p>
<pre><code>-module(rect).
-author("nt").
%% API
-export([is_rect/1, contains/2]).
-type rect() :: {point:point(), point:point()}.
-export_type([rect/0]).
is_rect({{OriginX, OriginY}, {W, H}}) when is_number(OriginX), is_number(OriginY), is_number(W), is_number(H) -> true;
is_rect(_) -> false.
-spec contains(Rect, Point) -> boolean() when Rect :: rect(), Point :: point:point().
contains({{OriginX, OriginY}, {W, H}} = R, {X, Y} = P) ->
case is_rect(R) of false -> error(badarg); _ -> ok end,
case point:is_point(P) of false -> error(badarg); _ -> ok end,
((OriginX < X) and (X < (OriginX + W))) and ((OriginY < Y) and (Y < (OriginY + H))).
</code></pre>
<p>Things are getting really massive and daunting. Given the fact there is almost no business logic I wonder how fast codebase will become a complete mess if I continue to check all the required preconditions in all functions.</p>
<p><strong>Update</strong>:</p>
<p>I think about removing all the specs and "assertions" from the code. Functions like <code>pointToMap</code> will be also removed as I don't need to rely on concrete types anymore. Something like <code>tupleToMap</code> should be used instead.</p>
<p><code>point.erl</code>:</p>
<pre><code>-module(point).
-author("nt").
-export([distance/2, translate/2]).
distance({X1, Y1}, {X2, Y2}) ->
math:sqrt(math:pow((X2 - X1), 2) + math:pow(Y2 - Y1, 2)).
translate({X1, Y1}, {X2, Y2}) ->
{X1 + X2, Y1 + Y2}.
</code></pre>
<p><code>rect.erl</code></p>
<pre><code>-module(rect).
-author("nt").
-export([contains/2]).
contains({{OriginX, OriginY}, {W, H}}, {X, Y}) ->
((OriginX < X) and (X < (OriginX + W))) and ((OriginY < Y) and (Y < (OriginY + H))).
</code></pre>
| [] | [
{
"body": "<p>I think the concerns about redundancy and verbosity are probably well placed.</p>\n<h2><code>andalso</code></h2>\n<p>The short circuiting logical AND is <code>andalso</code>. It can be used to simplify the code:</p>\n<pre><code>is_point({X, Y}) -> is_number(X) andalso is_number(Y).\n</code></pre>\n<p>Generally, the pattern:</p>\n<pre><code>// pseudo code\nif f(x)\n return true\nelse\n return false\n</code></pre>\n<p>can be replaced with <code>return f(x)</code>. Or in languages like Erlang where everything is an expression, <code>f(x)</code> alone is sufficient.</p>\n<h2>Atoms</h2>\n<p>In Erlang, it is idiomatic to use atoms as the first level of data validation:</p>\n<pre><code>is_point({point, X, Y}) -> is_number(X) andalso is_number(Y).\n</code></pre>\n<p>More importantly, it aids in readability and debugging. Atoms let points be distinguished from football scores:</p>\n<pre><code>1> point:is_point({point, 3, 2}).\ntrue\n2> point:is_point({football_score, 3, 2}).\n** exception error: no function clause matching \npoint:is_point({football_score,3,2})\n(/erlang/point.erl line 4) \n</code></pre>\n<p>Note that using atoms and good function names provides most of what we want to start debugging this type of problem. Football scores are not points and "letting it crash" provides better information than <code>badarg</code>.</p>\n<h2>Message passing</h2>\n<p>Labeling data with atoms lets us distinguish <code>{rhombus, P1, P2}</code> from <code>{rectangle, P1, P2}</code> and <code>{circle, P1, P2}</code>.</p>\n<h2>Try-catch</h2>\n<p>Taking error handling code out of <code>point:is_point</code> is consistent with the "unwritten code is bug free" heuristic. If crashes are problematic, the <em>caller</em> should wrap the call to <code>point:is_point/1</code> in a <code>try-catch-finally</code> block. The <em>caller</em> can handle the exception at whatever granularity it needs. And we can avoid the close coupling that coordinated error handling requires whenever the defaults are good enough.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T23:30:59.497",
"Id": "225103",
"ParentId": "209832",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:32:00.220",
"Id": "209832",
"Score": "4",
"Tags": [
"error-handling",
"coordinate-system",
"erlang"
],
"Title": "Error handling for an Erlang 2D point class"
} | 209832 |
<p>I'm coding for fun with the secret ambition of making a fun little game for mobile. So I started out building this little jumping game with Javascript and jQuery. </p>
<p>The game relies heavy on css transformations to do the animations. This way it is not nessecary to do the hard animations work by javascript. I suspect it is also more efficient, but I dont know for sure. </p>
<p>I think it is going ok, but I would love feedback on what should/ could be better/ smarter coded. Also I have this nagging feeling that I should ditch this approach and start over with html5 canvas instead. What are your thoughts? </p>
<p>(The jsfiddle works better: <a href="https://jsfiddle.net/hpvl/z7vw03ud/36/" rel="nofollow noreferrer">https://jsfiddle.net/hpvl/z7vw03ud/36/</a> )</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
function makeObstacleRND(){
if (Math.random()>0.7){makeObstacle()}
}
function makeObstacle(){
var el = document.getElementById('world');
var st = window.getComputedStyle(el, null);
var tr = st.getPropertyValue("transform");
var values = tr.split('(')[1];
values = values.split(')')[0];
values = values.split(',');
var a = values[0]*1;
var b = values[1]*-1;
var c = values[2]*-1;
var d = values[3]*1;
//var mymatrix='matrix('+a+','+b+','+c+','+d+', 0, 0)'
//var mymatrix='matrix(1,0,0,1, 0, 0)'
var mymatrix='matrix('+a+','+b+','+c+','+d+',0,0)'
console.log(mymatrix)
$clone = $('#stock .base').clone( true ).css('transform',mymatrix).appendTo("#world") .delay(6000).queue(function() {$(this).remove()})
}
function checkObstacle(element) {
return element.className=='obstacle';
}
function checkCollision(){
$el=$('#player');
var myX=400;
var myY=235;
var myY=$el.position().top + $el.offset().top -50 //this is not working ok yet
$('#sensor').css('top',myY+'px').css('left',myX+'px')
console.log(myY);
myelements=document.elementsFromPoint(myX, myY)
isobstacle=(typeof myelements.find(checkObstacle)!="undefined")
if(isobstacle){
$('#player').css('background-color','red')
}
else{
$('#player').css('background-color','green')
}
}
var checkCollisionInterval=setInterval(checkCollision, 100);
var makeObstacleRNDInterval=setInterval(makeObstacleRND, 600);
$( "body" ).keydown(function(e){
e.stopPropagation();
e.preventDefault();
var $el=$('#player');
if (!$el.hasClass( "jump" )){
$('#player').addClass('jump')
$('#gaia').addClass('bump')
var timeoutforremoveclass=setTimeout(ready2jump, 280);
}
})
function ready2jump(){
$('#player').removeClass('jump')
$('#gaia').removeClass('bump')
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#world{
background-image: url('https://hyperalbum.com/jump/earth-3228308_19202.png');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: absolute;
width: 1000px;
height: 1000px;
animation:spin 10s linear infinite;
}
#gaia{
position: absolute;
top: 240px;
left: -100px;
}
@keyframes spin { 100% { transform:rotate(-360deg); } }
.base{
position: absolute;
top: 0px;
left: 0px;
height: 40px;
margin-top: 480px;
margin-bottom: 480px;
width: 1000px;
display: block;
}
.obstacle {
position: absolute;
top: 0px;
left: 1000px;
display: block;
height: 40px;
width: 40px;
background: blue;
}
#stock {display: none}
#player {
position: absolute;
left: 360px;
top: 140px;
height: 100px;
width: 40px;
background: green;
}
.jump{ animation: jump 0.3s linear 0s normal ;}
.bump{ animation: bump 0.3s linear 0s normal ;}
@keyframes jump {
0%{
transform: translateY(0);
}
10%{
transform: translateY(-140px);
}
100%{
transform: translateY(0px);
}
}
@keyframes bump {
0%{
transform: translateY(0);
}
10%{
transform: translateY(12px);
}
40%{
transform: translateY(0px);
}
80%{
transform: translateY(6px);
}
100%{
transform: translateY(0px);
}
}
#sensor{height: 2px; width:2px; display: block; position: absolute; background-color: orange}</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>
<div id="gaia">
<div id="world">
</div>
</div>
<div id="player" href="#">
</div>
<!--<div id="sensor"></div>-->
<div id="stock">
<div class="base">
<div class="obstacle"></div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:06:00.497",
"Id": "405552",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:53:01.377",
"Id": "209834",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html5",
"canvas",
"cordova"
],
"Title": "Simple jumping game: continue with jquery or switch to html5 canvas?"
} | 209834 |
<p>I tried to make a MVC in PHP with OOP approach. Code Review this so I can understand whether am I using the best practices and can I legally call it a MVC framework or not. Also, I am going with 1 controller for each action.</p>
<blockquote>
<p><em>This blockquote might help you review my code better.</em></p>
<p>The default thing is actually works like this:</p>
<p><a href="http://localhost/coolcodes/something/test/" rel="nofollow noreferrer">http://localhost/coolcodes/something/test/</a> (This is bring up the TestController)</p>
<p><a href="http://localhost/coolcodes/something/" rel="nofollow noreferrer">http://localhost/coolcodes/something/</a> (This will bring up the default controller for something).</p>
<p>There is a function called getDefaultRouteName. </p>
<p><em>getDefaultRouteName</em> => Returns the key for which the default controller is located in the $routesTree variable.</p>
</blockquote>
<p>My code:</p>
<p>index.php (The page the client will go to):</p>
<pre><code><?php
include_once("App.php");
$app = new App();
$app->init();
$app->execute();
?>
</code></pre>
<p>App.php (The main application starter):</p>
<pre><code><?php
include_once("RoutesTree.php");
include_once("Config.php");
class App {
private $controller;
public function init() {
$routesTree = new RoutesTree;
if (Config::isUnderDevelopment()) {
$this->controller = $routesTree->getUnderDevelopmentController();
} else {
$pageURL = str_replace("/coolcodes/api/", "", $_SERVER['REQUEST_URI']);
$path = explode("/", $pageURL);
if ($_SERVER['REQUEST_URI']{strlen($_SERVER['REQUEST_URI']) - 1} == "/") {
$path = array_slice($path, 0, count($path) - 1);
}
$this->controller = $routesTree->getController($path);
}
}
public function execute() {
$this->controller->execute();
}
}
?>
</code></pre>
<p>Routes.php (The routes for MVC):</p>
<pre><code><?php
include_once("Config.php");
class RoutesTree {
private $routesTree;
private $notFoundController;
function __construct() {
$this->initRoutesTree();
}
public function initRoutesTree() {
$this->routesTree = Config::getPreparedRoutesTree();
$this->notFoundController = Config::getNotFoundController();
}
public function getRoutesTree() {
return $this->routesTree;
}
public function getUnderDevelopmentController() {
return Config::getUnderDevelopmentController();
}
public function getController($path) {
$route = $this->routesTree;
foreach ($path as $pathSegments) {
if (array_key_exists($pathSegments, $route)) {
$route = $route[$pathSegments];
} else {
return $this->notFoundController;
}
}
if (is_array($route)) {
return $route[Config::getDefaultRouteName()];
}
return $route;
}
}
?>
</code></pre>
<p>Controller.php (MVC Controller base class):</p>
<pre><code><?php
abstract class Controller {
abstract public function execute();
}
?>
</code></pre>
<p><em>Some Controllers:</em></p>
<p>TestController.php:</p>
<pre><code><?php
include_once("Controller.php");
class TestController extends Controller {
public function execute() {
echo json_encode(["value" => "Hello, World!!!!"]);
}
}
?>
</code></pre>
<p>SomethingController.php:</p>
<pre><code><?php
include_once("Controller.php");
class SomethingController extends Controller {
public function execute() {
echo json_encode(["value" => "From something controller."]);
}
}
?>
</code></pre>
<p><em>Controllers that are required</em>:</p>
<p>NotFoundController.php (The Error 404 Controller)</p>
<pre><code><?php
include_once("Controller.php");
class NotFoundController extends Controller {
public function execute() {
echo "<h1>Sorry, Page not found.</h1>";
}
}
?>
</code></pre>
<p>UnderDevelopementController (Controller shown if the website is under construction):</p>
<pre><code><?php
include_once("Controller.php");
class UnderDevelopmentController extends Controller {
public function execute() {
echo json_encode(["value" => "This website is under construction. See you soon."]);
}
}
?>
</code></pre>
<p>Config.php (Settings for MVC (inspired by settings.py in Django))</p>
<blockquote>
<p>I made functions instead of variables because I thought that it will be more OOP oriented in PHP (Because I do not want to make variables outside of any classes).</p>
</blockquote>
<pre><code><?php
include_once("allclasses.php");
class Config {
public static function isUnderDevelopment() {
return false;
}
public static function getUnderDevelopmentController() {
return new UnderDevelopmentController;
}
public static function getNotFoundController() {
return new NotFoundController;
}
public static function getDefaultRouteName() {
return "default";
}
public static function getPreparedRoutesTree() {
return [
"something" => [
"default" => new SomethingController,
"test" => new TestController
]
];
}
}
?>
</code></pre>
<p>addclasses.php (To Group all the controllers)</p>
<pre><code><?php
include_once("controllers/TestController.php");
include_once("controllers/SomethingController.php");
include_once("controllers/NotFoundController.php");
include_once("controllers/UnderDevelopmentController.php");
?>
</code></pre>
<p>The .htaccess file:</p>
<pre><code>Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./index.php
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:04:33.177",
"Id": "405550",
"Score": "1",
"body": "Apparently the biggest improvement would be implementation of autoload"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:44:11.153",
"Id": "405596",
"Score": "3",
"body": "@YourCommonSense Please do not answer in comments. All suggestions for improvements should be posted as answers."
}
] | [
{
"body": "<p>As Your Common Sense noted in the comments, leveraging <a href=\"http://php.net/manual/en/language.oop5.autoload.php\" rel=\"nofollow noreferrer\">auto loading classes in PHP</a> can help clean up your includes for the controller files (and model classes too).</p>\n\n<p>Some additional improvements:</p>\n\n<ul>\n<li><p><strong>Tight Coupling to Config class:</strong> Create an instance of your Config class, and pass it to the constructor of your App class, instead of using static methods.</p>\n\n<pre><code>$app = new App(new Config());\n</code></pre>\n\n<p>Then pass this the instance of <code>Config</code> into your <code>RoutesTree</code> class:</p>\n\n<pre><code>$routesTree = new RoutesTree($this->config);\n</code></pre>\n\n<p>This gives you loose coupling between the App, RoutesTree and Config classes by way of <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a>.</p></li>\n<li><p><strong>Separate controllers from ouput:</strong> I think this is the area where you are violating the \"V\" in MVC. Your example controller <code>echo</code>'s directly to the standard output. A controller should produce a result, but something else should be responsible for sending this back to the client. Most frameworks opt for an object that encompasses the data to be rendered, and the name of a view used to render it.</p></li>\n<li><p><strong>Convention based URL mappings:</strong> Instead of keeping an array of controller names to controllers, use the controller name from the URL to return the right controller:</p>\n\n<pre><code>// http://localhost/app/test maps to TestController\n$controller = ucfirst('test') . 'Controller';\n\nreturn new $controller();\n</code></pre>\n\n<p>You can still build in a way to do custom routing, but you'll find a pattern to your URLs and the controllers that respond to them</p></li>\n<li><p><strong>No restriction on HTTP methods:</strong> Your controller actions appear to respond to both GET and POST requests. This can be a security flaw when you allow a GET request to modify data. Consider this request:</p>\n\n<pre><code>HTTP/1.1 POST http://localhost/app/createComment\n\ncomment=Hacked&post_id=3\n</code></pre>\n\n<p>That's all fine and dandy until someone puts this HTML on a random page on the internet, and tricks your users into visiting it:</p>\n\n<pre><code><script src=\"http://localhost/app/comments?comment=Hacked&post_id=3\"></script>\n</code></pre>\n\n<p>Upon visiting the page, if you are logged in to your site the browser will issue a GET request to <code>http://localhost/app/comments?comment=Hacked&post_id=3</code>. Since your application does not check if the client has issued a GET or POST request, blog post #3 gets a new comment each time you visit the page.</p>\n\n<p>Sure the browser can't understand the result of this HTTP request as JavaScript, but that doesn't stop the browser from sending the request, along with your session cookies.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:39:31.803",
"Id": "405814",
"Score": "0",
"body": "I guess that I will make two different execute functions, one for GET request and another for POST request. So, will it be fine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:54:04.140",
"Id": "405824",
"Score": "0",
"body": "@SiddharthBose: Since you have one controller per request, the controller itself could define a method called something like `canExecuteRequest('GET')`. If it returns `false` then the `App` object would throw an exception, or return a `400 bad request` response back to the client."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T14:31:21.097",
"Id": "209908",
"ParentId": "209835",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209908",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:58:57.017",
"Id": "209835",
"Score": "2",
"Tags": [
"php",
"mvc",
"url-routing"
],
"Title": "Simple MVC built in PHP"
} | 209835 |
<p>Can anyone check my solution to the first part of exercise 3.47 in SICP? Thanks.</p>
<blockquote>
<p>Exercise 3.47: A semaphore (of size n) is a generalization of a mutex.
Like a mutex, a semaphore supports acquire and release operations, but
it is more general in that up to n processes can acquire it
concurrently. Additional processes that attempt to acquire the
semaphore must wait for release operations. Give implementations of
semaphores</p>
<ol>
<li>in terms of mutexes<br />
...</li>
</ol>
</blockquote>
<p>I have a local state called number-of-processes which tracks the processes that acquired the semaphore. Since it is mutated when acquire and release operations occur, I used a mutex to prevent concurrent writes.</p>
<p>Here is my code: I displayed the outputs of some variable for testing.</p>
<pre><code>> (define (make-serializer n)
(let ((semaphore (make-semaphore n)))
(lambda (p)
(define (serialized-p . args)
(semaphore 'acquire)
(let ((val (apply p args)))
(newline)
(display val)
(semaphore 'release)
val))
serialized-p)))
(define (make-semaphore n)
(let ((mutex (make-mutex))
(number-of-processes 0))
(define (acquire)
(mutex 'acquire)
(if (< number-of-processes n)
(begin (set! number-of-processes (+ number-of-processes 1))
(display 'acquired)
(mutex 'release))
(begin (mutex 'release)
(acquire))))
(define (release)
(mutex 'acquire)
(if (> number-of-processes 0)
(begin (set! number-of-processes (- number-of-processes 1))
(newline)
(display 'released)
(newline))
(error "error!"))
(mutex 'release))
(define (the-semaphore m)
(cond ((eq? m 'acquire) (acquire))
((eq? m 'release) (release))))
the-semaphore))
</code></pre>
<p>I tested it like this:</p>
<pre><code>(define s (make-serializer 2))
(define p1 (s (lambda () 1)))
(define p2 (s (lambda () 2)))
(define p3 (s (lambda () 3)))
(define p4 (s (lambda () 4)))
(define p5 (s (lambda () 5)))
</code></pre>
<p>The outputs are:</p>
<pre><code>> (parallel-execute p1)
acquired
1
released
(1)
> (parallel-execute p1 p2)
acquired
1
acquired
2
released
released
(1 2)
> (parallel-execute p1 p2 p3)
acquired
1
acquired
2
released
acquired
3
released
released
(1 2 3)
> (parallel-execute p1 p2 p3 p4)
acquired
1
acquired
2
released
acquired
4
released
acquired
3
released
released
(1 2 4 3)
> (parallel-execute p1 p2 p3 p4 p5)
acquired
4
acquired
1
released
acquired
2
released
released
acquired
5
acquired
3
released
released
(4 1 2 5 3)
</code></pre>
<p>I believe my procedure is working correctly. All my tests passed. How can I improve this code? Thanks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T16:46:04.373",
"Id": "405581",
"Score": "1",
"body": "Please use Emacs to format your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:16:27.440",
"Id": "405587",
"Score": "1",
"body": "@sds I'm afraid emacs is inaccessible with my screen reader."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T14:46:40.050",
"Id": "405730",
"Score": "0",
"body": "@sds I used the indenting feature of racket. Can you check it out? Is it readable now? Thanks."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T15:34:39.597",
"Id": "209840",
"Score": "1",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "SICP exercise 3.47 - implementing a semaphore in terms of mutexes"
} | 209840 |
<p>I am using Python threads to download images. I have a JSON file that contains URLs to the images in the following structure: </p>
<pre><code>images = {'images: [{'url': 'https://contestimg.wish.com/api/webimage/5468f1c0d96b290ff8e5c805-large',
'imageId': '1'},....]}
</code></pre>
<p>There are over 1,000,000 images. After using 20 threads, I only collected ~80,000 of these images, along with ~1000 exceptions due to 500 status codes from the URL. I have a feeling that my code is incorrect. Can someone please check my code?</p>
<pre><code>import requests
import threading
import json
import pickle
train_data = json.load(open("train.json", "rb"))
images = train_data["images"]
threads = []
def save_image(images_part):
errors = []
for i in images_part:
Picture_request = requests.get(i['url'])
if Picture_request.status_code == 200:
with open(f"train/{i['imageId']}.jpeg", "wb") as f:
f.write(Picture_request.content)
else:
errors.append((i, Picture_request.status_code))
print(f"error in {i['imageId']} with {Picture_request.status_code}")
return errors
for i in range(0, 20):
start = i*50727
end = (i+1)*50727
if i == 19:
end = None
t = threading.Thread(target=save_image, args=(images[start:end],))
threads.append(t)
t.start()
print(f"initiating {i}th thread")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T20:26:31.160",
"Id": "405631",
"Score": "2",
"body": "CodeReview SE is for improving style and performance of working code. If your code is broken, it's probably better to ask on Stackoverflow. However, is there any particular reason why you're using python for this task. You can achieve parallelized URL downloads with something like `cat urls.txt | parallel wget` assuming urls.txt is a file with each URL on a separate line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:18:01.090",
"Id": "405654",
"Score": "0",
"body": "Exactly. This is my first practical usage of threads and I was wondering if anyone could see places of potential improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T09:25:21.227",
"Id": "405696",
"Score": "0",
"body": "What do the magical numbers `20` and `50727` mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T09:47:26.797",
"Id": "405700",
"Score": "1",
"body": "Have you checked what happens if you manually visit one of the urls which threw a 500 error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T18:58:55.363",
"Id": "405751",
"Score": "0",
"body": "@Graipher the 20 and 50727 numbers represent how I want to partition the data. There are 1,014,544 images, and I want to have 20 threads running. Therefore, each thread will handle 1, 014,544/20 images which is approximately 50,727. Note that on the last iteration in the for loop when i =19, the last thread will take remainders.\nWhen I put the url in the browser, the image doesn't show up and the web inspector throws a message saying - \"Fail to load resource: the server responded with a status of 500 ()\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T21:01:00.587",
"Id": "405764",
"Score": "0",
"body": "@ElizabethKeleshian The first part should probably be part of an answer (don't have magical numbers), but regarding also getting a 500 error, then it is apparently not a problem with your script, but with the webserver/url."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T17:53:26.867",
"Id": "209853",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"multithreading",
"json",
"network-file-transfer"
],
"Title": "Using Python threads to download images"
} | 209853 |
<p>Annother little excercise with openpyxl:</p>
<p>Say you have a Excel file like this:</p>
<p><a href="https://i.stack.imgur.com/BvAzG.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/BvAzG.jpg" alt="enter image description here"></a></p>
<p>The Goal is to make make it look like this:</p>
<p><a href="https://i.stack.imgur.com/fmRbF.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/fmRbF.jpg" alt="enter image description here"></a></p>
<p>My code to acomplish this:</p>
<p><b> inversion.py </b></p>
<pre><code>"""
Inverts the content of table row and columns
"""
from copy import copy
import openpyxl
from openpyxl.utils import get_column_letter
def save_workbook_excel_file(workbook, filename: str):
"""Tries to save created data to excel file"""
try:
workbook.save(filename)
except PermissionError:
print("Error: No permission to save file.")
def invert_row_column(filename: str):
"""
Main loop to invert rows and column
"""
workbook = openpyxl.load_workbook(filename)
sheet_names = workbook.sheetnames
sheet = workbook[sheet_names[0]]
workbook.create_sheet(index=0, title='tmp_sheet')
tmp_sheet = workbook['tmp_sheet']
data = []
for row in sheet:
cells = []
for cell in row:
cells.append(cell)
data.append(cells)
for x in range(0, len(data)):
for y in range(0, len(data[x])):
column = get_column_letter(x + 1)
row = str(y + 1)
tmp_sheet[column + row] = copy(data[x][y].value)
sheet_name = sheet.title
del workbook[sheet_name]
tmp_sheet.title = sheet_name
save_workbook_excel_file(workbook, 'updated_' + filename)
invert_row_column("test.xlsx")
</code></pre>
<p>I wonder how this can be improved?
Can the naming be better?
Is there a better / or shorter solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:51:01.923",
"Id": "405740",
"Score": "1",
"body": "a small tip: don't overwrite the original file, but write it to a different filename, or rename the original file"
}
] | [
{
"body": "<p>Disclaimer: I'm not familiar with <code>openpyxl</code>. I hope this review won't be nonsense. Do tell me!</p>\n\n<p>The posted code copies the content of the first sheet into <code>data</code>,\nwrites inverted (transposed?) content into a new sheet <code>tmp_sheet</code>,\ncopies attributes of the original sheet to <code>tmp_sheet</code>\nand finally deletes the original sheet.</p>\n\n<p>What I don't get is why not update the original sheet directly?\nYou could loop over coordinates of the cells below the diagonal of the sheet,\ncompute the coordinates of the cell to swap with,\nuse a suitable temporary storage for swapping single values.\nThe diagonal can be left alone, they don't need to be swapped with anything.</p>\n\n<p>This approach would have the advantages that if there are multiple sheets in the file,\nthe content of the first sheet stays on the first sheet,\nand you don't need to worry about copying properties of the sheet such as the title.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T19:08:41.320",
"Id": "209858",
"ParentId": "209857",
"Score": "3"
}
},
{
"body": "<p>Another way to solve this, without using <code>openpyxl</code> and thereby slightly defeating the purpose of learning more about that, would be to use <code>pandas</code>, where this is quite short:</p>\n\n<pre><code>import pandas as pd\n\n# This would load the first sheet by default, but we need the name to save it again\n# df = pd.read_excel(filename) \n\nsheets = pd.read_excel(file_name, sheet_name=None) # all sheets\nsheet_name, df = next(iter(sheets.items())) # first sheet\ndf = df.T # transpose\ndf.to_excel(file_name, sheet_name) # write back\n</code></pre>\n\n<p>This uses <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html\" rel=\"nofollow noreferrer\"><code>pandas.read_excel</code></a> to read the file and <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html\" rel=\"nofollow noreferrer\"><code>pandas.DataFrame.to_excel</code></a> to write it back. You need to have the <a href=\"https://pypi.org/project/xlrd/\" rel=\"nofollow noreferrer\"><code>xlrd</code></a> module installed for this to work.</p>\n\n<p>Feel free to wrap it in functions again if needed.</p>\n\n<p>This should be faster than the manual iteration in Python, since the transpose should happen at C speed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T09:41:23.187",
"Id": "209892",
"ParentId": "209857",
"Score": "8"
}
},
{
"body": "<p>Simple approach, with <code>openpyxl</code></p>\n\n<pre><code>import openpyxl\n\ncurrent_wb = openpyxl.load_workbook('./data/items.xlsx')\ncurrent_sheet = current_wb.get_active_sheet()\n\nnew_wb = openpyxl.Workbook()\nnew_sheet = new_wb.get_active_sheet()\n\nfor row in range(1, current_sheet.max_row + 1):\n for col in range(1, current_sheet.max_column + 1):\n new_sheet.cell(col, row).value = current_sheet.cell(row, col).value\n\nnew_wb.save('./dist/items.xlsx')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T08:59:27.133",
"Id": "435950",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T17:10:48.870",
"Id": "436192",
"Score": "0",
"body": "this is a nice approach since it uses openpyxl like my original question. It is so much shorter than it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T19:48:47.463",
"Id": "224699",
"ParentId": "209857",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209858",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T18:52:45.557",
"Id": "209857",
"Score": "8",
"Tags": [
"python",
"excel",
"file"
],
"Title": "Invert rows and columns in an Excel file"
} | 209857 |
<p>Here is how I'm detecting a field separator and line break in a CSV file for which I do not already know the format. Does this look sufficient, or are there other things I should be adding here?</p>
<pre><code>SEPARATORS=['\x00', '\x01', '^', ':', ',', '\t', ':', ';', '|', '~', ' ']
LINE_TERMINATORS_IN_ORDER = ['\x02\n', '\r\n', '\n', '\r']
def get_csv_info(f):
with open(f, 'r') as csvfile:
line = next(csvfile)
dialect = csv.Sniffer().sniff(line, SEPARATORS)
for _terminator in LINE_TERMINATORS_IN_ORDER:
if line.endswith(_terminator):
terminator = _terminator
break
return (dialect.delimiter, terminator)
get_csv_info('/Users/david/Desktop/validate_headers/artist')
('\x01', '\x02\n')
</code></pre>
<p>Note: using the normal <code>csv.Sniffer</code> without params fails most of the time I use it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T06:48:35.413",
"Id": "405678",
"Score": "0",
"body": "`SEPARATORS=['\\x00', ..., ':', ..., ':',...]` - why two **:**?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T08:43:36.013",
"Id": "405690",
"Score": "0",
"body": "There is only one case where you need a single byte, which is the line ending with `\\r`. If it doesn't end with it then you need two bytes, no need to go through a list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:18:29.773",
"Id": "405735",
"Score": "0",
"body": "@ChatterOne could you please clarify what you mean with that? For example, what should the `LINE_TERMINATORS` be instead?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:25:12.243",
"Id": "209869",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"csv"
],
"Title": "Detecting line separators and line breaks in Python CSV"
} | 209869 |
<p>I've been reading around how golang writes to a file, and this <a href="https://stackoverflow.com/questions/29981050/concurrent-writing-to-a-file">stack overflow question</a> and this <a href="https://www.reddit.com/r/golang/comments/6bpmtj/writing_to_a_file_on_multiple_threads/" rel="nofollow noreferrer">reddit question</a> highlights the fact Go doesn't gurantee atomicity when writing to a file system. Although I didn't see any interleaved writes (which I guess could be due to writev(2)), I didn't want to risk it so I built a a simple Go interface to do that.</p>
<p>I'm not super proficient with Go, but I'd like to understand how this code can be improved with best practices and on potential issues that may arise when using it.</p>
<pre><code>package main
import (
"fmt"
"io"
"os"
)
// FileLogger defines the methods to log to file
type FileLogger interface {
Write(s string)
}
type fileLogger struct {
stream chan string
writer io.Writer
}
func (l *fileLogger) run() {
for {
select {
case s := <-l.stream:
_, err := l.writer.Write([]byte(s))
if err != nil {
fmt.Println("Error writing to file: ", err.Error())
}
}
}
}
func (l *fileLogger) Write(s string) {
l.stream <- s
}
// NewFileLogger returns a new FileLogger
func NewFileLogger() FileLogger {
file, err := os.OpenFile(
"logs/logs.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666,
)
if err != nil {
panic(err)
}
f := &fileLogger{make(chan string), file}
go f.run()
return f
}
</code></pre>
<p>I could for instance make it conform to the io.Writer interface, but I'm not sure what benefits there are of that?</p>
<p>Would there be an advantage to mutex locks here using the sync package?</p>
| [] | [
{
"body": "<blockquote>\n <p>Go doesn't guarantee atomicity ... so I built a simple Go interface to do that</p>\n</blockquote>\n\n<p>Okay, but is your implementation atomic? The only atomic operations guaranteed to be atomic in Go are through the <code>sync/atomic</code> package (or things like <code>func (*Cond) Wait</code> under <code>sync</code>).</p>\n\n<p>If you need true atomic write, use the atomic package. However, using <code>log</code> is usually sufficient.</p>\n\n<hr>\n\n<p>Your implementation looks like it's trying to be concurrent, not atomic. Rather than rolling your own concurrent writer interface, use the standard API.</p>\n\n<p>You're right, <code>fmt</code> (& <code>os</code> write functions, etc.) do not provide concurrency. However, the <code>log</code> package <a href=\"https://stackoverflow.com/a/18362952\">does</a>.</p>\n\n<p>You <a href=\"https://golang.org/src/log/log.go?s=5252:5306#L139\" rel=\"noreferrer\">can see</a> that they use mutex locks for the <code>Output</code> function, which is used by almost everything else.</p>\n\n<p>This should perform nearly identical to your use case, because you open the file with <code>O_APPEND</code>, and <code>log</code> appends.</p>\n\n<p>So open a file, and pass it to <code>log.New()</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>package main\n\nimport (\n \"log\"\n \"os\"\n)\n\nfunc main() {\n f, err := os.OpenFile(\"testfile\", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\n if err != nil {\n log.Fatal(err)\n }\n\n logger := log.New(f, \"\", 0)\n logger.Output(2, \"wow\")\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T00:55:33.863",
"Id": "405659",
"Score": "1",
"body": "thanks for the response! Is it not atomic if I have a single go routine that handles the writes using the for select?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T00:55:52.627",
"Id": "405660",
"Score": "2",
"body": "I see, it's concurrent..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T00:56:12.543",
"Id": "405661",
"Score": "2",
"body": "I think I have some more reading to do..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:58:10.643",
"Id": "209872",
"ParentId": "209870",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "209872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:25:12.340",
"Id": "209870",
"Score": "4",
"Tags": [
"file-system",
"go",
"interface"
],
"Title": "Writing to a file in Golang across concurrent go routines"
} | 209870 |
<p>I implemented an algorithm that takes only sublinear extra space as required in the exercise description: </p>
<blockquote>
<p>Develop a merge implementation that reduces the extra space
requirement to max(M, N/M). (dividing the array into N/M blocks of
size M).</p>
</blockquote>
<pre><code>def insert_sort(a, lo, hi):
for i in range(lo+1, hi):
j = i
while(j>lo and a[j]<a[j-1]):
a[j], a[j-1] = a[j-1], a[j]
j -= 1
def in_place_merge(a, lo, mi, hi):
aux_hi = a[mi:hi]
for i in reversed(range(lo, hi)):
if aux_hi:
last_a = i - len(aux_hi)
if (last_a < lo or aux_hi[-1] > a[last_a]):
a[i] = aux_hi.pop()
else:
a[i] = a[last_a]
else:
break
def block_insertion_sort(a):
M = 5
for i in range(0, len(a), M):
insert_sort(a, i, min(i+M, len(a)))
if i > 0:
in_place_merge(a, 0, i, min(i+M, len(a)))
</code></pre>
<p>In addition, I don't understand the max(M, N/M) part, then I don't know if I have made it. Any suggestions are highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T04:47:38.830",
"Id": "405671",
"Score": "0",
"body": "Could you provide the tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T12:07:56.770",
"Id": "405714",
"Score": "0",
"body": "@vnp What do you mean by tests? The test code for every function?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T23:51:49.723",
"Id": "209871",
"Score": "3",
"Tags": [
"python",
"algorithm",
"mergesort",
"genetic-algorithm"
],
"Title": "Implementation of merge sort that takes sublinear extra space"
} | 209871 |
<p>I have been doing OOP and imperative programming my whole career but I wanted to dabble in Scala along with functional programming. Rather than writing Java like code in Scala I wanted to try a more functional approach. I decided to try a simple Kata with Scala, Game of Life. The following is what I came up with. I admit I am very much stuck in OOP/imperative mindset. I am not sure if this is the best approach for Scala, or functional programming. I avoided functions that mutate objects, and favor returning a new copy. I was unsure what the best approach is with functional programming to ensure objects can't be created in an invalid state. Is there a way I can make my code more aligned with idiomatic Scala and functional programming. </p>
<pre><code>package io.jkratz.katas.gameoflife
import scala.util.Random
case class Board(grid: Array[Array[Int]]) {
require(grid != null, "grid cannot be null")
require(!isJagged(grid), "grid cannot be jagged")
require(isValid(grid), "grid contains invalid values, 0 and 1 are the only valid values")
val rows: Int = {
grid.length
}
val columns: Int = {
grid(0).length
}
def evolve(): Board = {
val newGrid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
newGrid(i)(j) = getNextCellState(i,j)
}
}
Board(newGrid)
}
private def getNextCellState(i:Int, j: Int): Int = {
var liveCount = 0
val cellValue = grid(i)(j)
for (x <- -1 to 1; y <- -1 to 1) {
if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
// do nothing, out of bounds
} else {
liveCount += grid(i + x)(j + y)
}
}
liveCount -= cellValue
if (cellValue.equals(Board.CELL_ALIVE) && (liveCount < 2 || liveCount > 3)) {
Board.CELL_DEAD
} else if (cellValue.equals(Board.CELL_DEAD) && liveCount == 3) {
Board.CELL_ALIVE
} else {
cellValue
}
}
private def isJagged(grid: Array[Array[Int]]): Boolean = {
var valid = true
val size = grid(0).length
grid.foreach(row => if (row.length.equals(size)) valid = false)
valid
}
private def isValid(grid: Array[Array[Int]]): Boolean = {
var valid = true
for (i <- grid.indices; j <- grid(0).indices) {
val x = grid(i)(j)
if (x != 0 && x != 1) {
valid = false
}
}
valid
}
}
object Board {
val CELL_DEAD = 0
val CELL_ALIVE = 1
val DEFAULT_ROWS = 10
val DEFAULT_COLUMNS = 10
def random(rows: Int = DEFAULT_ROWS, columns: Int = DEFAULT_COLUMNS): Board = {
val grid = Array.ofDim[Int](rows, columns)
for (i <- grid.indices) {
for (j <- grid(0).indices) {
grid(i)(j) = Random.nextInt(2)
}
}
Board(grid=grid)
}
def prettyPrint(board: Board): Unit = {
val grid = board.grid
for (i <- grid.indices) {
for (j <- grid(0).indices) {
if (grid(i)(j) == 0) print(" - ") else print(" * ")
}
println()
}
}
}
</code></pre>
<p>And my main entry point.</p>
<pre><code>package io.jkratz.katas.gameoflife
object Life {
def main(args: Array[String]): Unit = {
val state0 = Board.random(5,5)
println("State 0")
Board.prettyPrint(state0)
val state1 = state0.evolve()
println("State 1")
Board.prettyPrint(state1)
}
}
</code></pre>
| [] | [
{
"body": "<p>You're doing a lot of indexing, which is efficient in an <code>Array</code>, but indicates that you're thinking in small steps. As you get to know the Scala Standard Library you start thinking in larger chunks because it offers many ways to process data collections all at once.</p>\n\n<p>I'll start at the bottom and work my way up.</p>\n\n<p><strong>*<code>prettyPrint()</code></strong> - Testing for value <code>0</code> means that the <code>prettyPrint()</code> method knows about the underlying representation. If you test for <code>CELL_DEAD</code> and/or <code>CELL_ALIVE</code> then <code>prettyPrint()</code> should still work even if the grid implementation changes.</p>\n\n<p>Here I chose to turn each row into a <code>String</code> and then <code>println()</code> it.</p>\n\n<pre><code>def prettyPrint(board: Board): Unit =\n board.grid\n .map(_.map(c => if (c == CELL_DEAD) \" - \" else \" * \").mkString)\n .foreach(println)\n</code></pre>\n\n<p><strong>*<code>random()</code></strong> - Most Scala collections offer many different \"builder\" methods on the companion object. Here I use <code>fill()</code> to populate a 2-dimensional <code>Array</code>.</p>\n\n<pre><code>def random(rows:Int = DEFAULT_ROWS, columns:Int = DEFAULT_COLUMNS): Board =\n Board(Array.fill(rows,columns)(Random.nextInt(2)))\n</code></pre>\n\n<p><strong>*<code>isValid()</code></strong> - The Standard Library doesn't offer many collection methods with early termination, but <code>forall()</code> is one of them. It stops after the first <code>false</code> encountered.</p>\n\n<p>Here I use <code>-2</code> as a bit-mask to test the value of all bits except for the lowest.</p>\n\n<pre><code>private def isValid(grid: Array[Array[Int]]): Boolean =\n grid.forall(_.forall(n => (n & -2)==0))\n</code></pre>\n\n<p><strong>*<code>isJagged()</code></strong> - The <code>exists()</code> method is the compliment of <code>forall()</code>. It stops after the first <code>true</code> encountered.</p>\n\n<pre><code>private def isJagged(grid: Array[Array[Int]]): Boolean =\n grid.exists(_.length != grid.head.length)\n</code></pre>\n\n<p><strong>*<code>liveCount</code></strong> - Idiomatic Scala avoids mutable variables. In order to calculate the value of <code>liveCount</code> once, without any post-evaluation adjustments, we'll want a way to get all valid neighbor-cell indexes, also without any post-evaluation adjustments.</p>\n\n<pre><code>val liveCount = (for {\n x <- (0 max i-1) to (i+1 min rows-1)\n y <- (0 max j-1) to (j+1 min columns-1)\n} yield grid(x)(y)).sum - cellValue\n</code></pre>\n\n<p><strong>*<code>evolve()</code></strong> - <code>tabulate()</code> is another one of those \"builder\" methods that appears to do everything you need, in this situation, all at once. In this case, because we're building a 2-D <code>Array</code>, <code>tabulate()</code> passes two arguments, the row index and the column index, to its lambda argument. And because the <code>getNextCellState()</code> method takes those same two arguments in the same order, they don't need to be explicitly specified.</p>\n\n<pre><code>def evolve(): Board = Board(Array.tabulate(rows,columns)(getNextCellState))\n</code></pre>\n\n<p>It's worth noting that you test if <code>grid</code> is <code>null</code> but you don't test to see if it's empty. <code>Board.random(0,0)</code> will throw a run-time error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T13:31:46.683",
"Id": "405724",
"Score": "0",
"body": "Wow this is a great answer and well explained! Thanks for taking the time to provide a very detailed answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T06:43:43.913",
"Id": "209888",
"ParentId": "209873",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209888",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T00:03:08.343",
"Id": "209873",
"Score": "2",
"Tags": [
"functional-programming",
"scala",
"game-of-life"
],
"Title": "Game of Life with Scala and Functional Programming"
} | 209873 |
<p>The <a href="http://en.wikipedia.org/wiki/Complex_number" rel="nofollow noreferrer">complex numbers</a> extend the <a href="http://en.wikipedia.org/wiki/Real_number" rel="nofollow noreferrer">real numbers</a> to allow <a href="http://en.wikipedia.org/wiki/Negative_number" rel="nofollow noreferrer">negative numbers</a> to have a square root. Every complex number can be expressed in the form <em>x</em> + <em>y</em> * <em>i</em> where <em>x</em> and <em>y</em> are real numbers and <em>i</em>² = -1; this is called the rectangular form of the number. The rectangular form leads to an interpretation of complex numbers as points on a <a href="http://en.wikipedia.org/wiki/Complex_plane" rel="nofollow noreferrer">plane</a>, the same way real numbers are akin to points on a line. If <em>y</em> = 0, the number is a real number; if <em>x</em> = 0, the number is called an <a href="http://en.wikipedia.org/wiki/Imaginary_number" rel="nofollow noreferrer">imaginary number</a>.</p>
<p>A nonzero complex number has a family of representations in the form <em>r</em> exp(<em>i</em> φ) with <em>r</em> > 0, called the <a href="http://en.wikipedia.org/wiki/Polar_coordinate_system" rel="nofollow noreferrer">polar representation</a>.</p>
<h2>Representation and manipulation in programming languages</h2>
<h3>Floating point complex numbers</h3>
<ul>
<li><strong>C</strong>: C99 supports <code>complex</code> as a type. To use complex numbers, <code>#include <complex.h></code>. Many C89 compilers have a similar extension. See also <a href="http://c-faq.com/fp/complex.html" rel="nofollow noreferrer">clc FAQ 14.11</a>.</li>
<li><strong>Haskell</strong>: <a href="http://www.haskell.org/onlinereport/complex.html" rel="nofollow noreferrer"><code>Complex</code> library</a> in Haskell 98.</li>
<li><strong>Java</strong> <a href="http://www.cs.virginia.edu/~evans/cs655/readings/steele.pdf" rel="nofollow noreferrer">has no standard complex type</a>; <a href="http://en.literateprograms.org/Complex_numbers_%28Java%29" rel="nofollow noreferrer">many implementations exist</a>.</li>
<li><strong>Matlab</strong>: Native <a href="http://www.mathworks.com/help/matlab/matlab_prog/complex-numbers.html" rel="nofollow noreferrer">complex single- and double-precision arrays</a> as well as <a href="http://www.mathworks.com/help/symbolic/assumptions-for-symbolic-objects.html" rel="nofollow noreferrer">complex variable precision and symbolic variables</a> via the <a href="http://www.mathworks.com/help/symbolic/index.html" rel="nofollow noreferrer">Symbolic Math Toolbox</a>.</li>
<li><strong>OCaml</strong>: <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Complex.html" rel="nofollow noreferrer"><code>Complex</code> module</a> in the standard library.</li>
<li><strong>Python</strong>: <a href="http://docs.python.org/library/functions.html#complex" rel="nofollow noreferrer"><code>complex</code></a> is a <a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow noreferrer">built-in type</a>.</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T01:48:23.730",
"Id": "209878",
"Score": "0",
"Tags": null,
"Title": null
} | 209878 |
Questions about complex numbers (numbers in the form of x + y∙i where i² = -1), types to represent them in programming languages, and libraries to manipulate them | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T01:48:23.730",
"Id": "209879",
"Score": "0",
"Tags": null,
"Title": null
} | 209879 |
Given a set or multiset of integers, is there a non-empty subset whose sum is zero? The subset sum problem can be extended to find the sum to any given integer. The subset sum problem is a special case of the knapsack problem. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T01:55:31.720",
"Id": "209881",
"Score": "0",
"Tags": null,
"Title": null
} | 209881 |
<p>I am refactoring my existing product's webapi part of the solution. Current Repo pattern does not allow me to add custom functions to a specific repository. In result, most of the functions directly use the Db context in the controller.</p>
<p>I read various articles and come up a good way of implementation to achieve my targets and also best practice. Here I am posting my sample implementation to review and some more guidelines. I don't know if you can help me to review from git repository as I am new to this forum. </p>
<h2><strong>Aim/Targets:</strong></h2>
<ol>
<li>Need a generic way of repository and Unit of work pattern so that code can be reused with the advantage of the Repository pattern.</li>
<li>I also have custom functions to each repository and the pattern should accept this extension.</li>
</ol>
<h2><strong>Current Limitations/Future Plans:</strong></h2>
<ol>
<li><p>The current implementation does not have dependency injection so I am not making complex now. Will check in near future due to the impact.</p></li>
<li><p>The current implementation does not use the business layer. So repository class directly calling from API controller. Here I can't check deep into the business functions now so will look into future.</p></li>
</ol>
<h2><strong>Code:</strong></h2>
<p>Now please look into my implementation</p>
<p><strong>Project Structure</strong></p>
<p><a href="https://i.stack.imgur.com/jzuPm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jzuPm.png" alt="Project structure"></a></p>
<p><strong>Data Project Code:</strong></p>
<pre><code>public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public PaginatedList(IEnumerable<T> source, int pageNumber, int pageSize, int totalCount)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (pageSize <= 0)
{
throw new ArgumentException("pageSize");
}
AddRange(source);
PageNumber = pageNumber < 1 ? 1 : pageNumber;
PageSize = pageSize;
TotalCount = totalCount;
TotalPageCount = (int)Math.Ceiling(totalCount / (double)pageSize);
}
public int PageNumber { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }
public int TotalPageCount { get; private set; }
public bool HasPreviousPage
{
get
{
return (PageNumber > 1);
}
}
public bool HasNextPage
{
get
{
return (PageNumber < TotalPageCount);
}
}
}
public SampleContext() : base("Name=SampleContext")
{
}
public IDbSet<User> Users { get; set; }
public IDbSet<Item> Items { get; set; }
}
</code></pre>
<p><strong>Repository Project Code:</strong></p>
<p><em>Interfaces</em></p>
<pre><code> public interface IRepository<T> where T : class
{
Task<IEnumerable<T>> GetAll();
Task<PaginatedList<T>> GetPaged(Func<IQueryable<T>, IOrderedQueryable<T>> orderBy, int pageIndex, int pageSize, Expression<Func<T, bool>> filter = null, IList<Expression<Func<T, object>>> includedProperties = null);
Task<IEnumerable<T>> FindByAsync(Expression<Func<T, bool>> expression);
Task<T> Get(object id);
void Create(T entity);
void Update(T entity);
}
public interface IUnitOfWork
{
IUserRepository Users { get; }
IItemRepository Items { get; }
void SaveAsync();
}
public interface IUserRepository : IRepository<User>
{
User GetByName(string name);
}
public interface IItemRepository : IRepository<Item>
{
}
</code></pre>
<p><em>Repositories</em></p>
<pre><code>public abstract class Repository<T> : IRepository<T>
where T : class
{
private readonly DbSet<T> _dbSet;
protected SampleContext Context { get; set; }
protected Repository(SampleContext context)
{
Context = context;
_dbSet = Context.Set<T>();
}
public virtual async Task<IEnumerable<T>> GetAll()
{
return await _dbSet.ToListAsync();
}
public virtual async Task<PaginatedList<T>> GetPaged(Func<IQueryable<T>, IOrderedQueryable<T>> orderBy, int pageIndex, int pageSize, Expression<Func<T, bool>> filter = null, IList<Expression<Func<T, object>>> includedProperties = null)
{
var query = orderBy(_dbSet);
int totalCount = query.Count();
var collection = await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync();
return new PaginatedList<T>(collection, pageIndex, pageSize, totalCount);
}
public virtual async Task<IEnumerable<T>> FindByAsync(Expression<Func<T, bool>> expression)
{
return await _dbSet.Where(expression).ToListAsync();
}
public virtual async Task<T> Get(object id)
{
return await _dbSet.FindAsync(id);
}
public virtual void Create(T entity)
{
_dbSet.Add(entity);
}
public virtual void Update(T entity)
{
_dbSet.Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
}
}
public class UserRepository : Repository<User>, IUserRepository
{
public UserRepository(SampleContext context) : base(context)
{
}
public User GetByName(string name)
{
return Context.Users.FirstOrDefault(x => x.Name == name);
}
}
public ItemRepository(SampleContext context) : base(context)
{
}
</code></pre>
<p><strong>API ProjectCode:</strong></p>
<pre><code> public class BaseController : ApiController
{
protected IUnitOfWork UnitOfWork { get; set; }
public BaseController()
{
UnitOfWork = new UnitOfWork();
}
}
public class UserController : BaseController
{
public UserController()
{
}
[Route("api/users/all", Name = "UsersCollection")]
public async Task<IHttpActionResult> GetAll([FromUri]int page = 1, int pageSize = 20)
{
var items = await UnitOfWork.Users.GetPaged(x => x.OrderBy(y => y.Id), page, pageSize);
//Add mapping to DTO
return Ok(items);
}
[Route("api/users/{name}", Name = "UserByName")]
public IHttpActionResult GetByName(string name)
{
var item = UnitOfWork.Users.GetByName(name);
if(item == null)
{
return StatusCode(HttpStatusCode.NoContent);
}
//Add mapping to DTO
return Ok(item);
}
}
</code></pre>
<h2>My Questions:</h2>
<ol>
<li><p>Please review my project structure, namings, and implementation for any code smell?</p></li>
<li><p>I didn't create an interface for Paginated List because of the private set. Please suggest any good approach for this if any? Also, this class is not part of the database but I keep it in the Model folder itself.</p></li>
<li><p>Any code smell in the use of UnitOfWork class initialization in the base controller? If so, while initializing all repositories in the UnitOFWork class is initialized unnecessarily?</p></li>
<li><p>UnitOfWork class is implemented IDisposable so can I implement dispose in the base controller to dispose UniOfWork class? As I implement IDisposable in the class itself, I can't use dispose method from IUnitOfWork interface object</p></li>
</ol>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T04:11:44.493",
"Id": "209884",
"Score": "2",
"Tags": [
"c#",
"repository",
"asp.net-web-api"
],
"Title": "Repository + Unit Of Work Pattern in WebAPI"
} | 209884 |
<p>This is the simple game of hangman. Guess letters and six wrong letters means you're dead.</p>
<p>This took me about 20 hours. And I learned enough to be certain I could make something better now in half the time. Still, give me your honest (and brutal) opinion, since that will help me improve the most.</p>
<pre><code><?php
//init
$woordenlijst = array(
"knie",
"rug",
"nek",
"elleboog",
);
$gekozen = '';
$woordstatus = array('*',);
$aantalfouten = 0;
//function
function tekengalg($arg1)
//tekent de juiste galg
{
if ($arg1 == 0) {
//blanco galg
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
if ($arg1 == 1) {
// galg1
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" o |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
if ($arg1 == 2) {
//galg2
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" o |") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
if ($arg1 == 3){
//galg3
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" o |") . PHP_EOL;
echo ("/| |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
if ($arg1 == 4){
//galg4
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" o |") . PHP_EOL;
echo ("/|\ |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
if ($arg1 == 5){
//galg5
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" o |") . PHP_EOL;
echo ("/|\ |") . PHP_EOL;
echo ("/ |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
if ($arg1 == 6){
//galg6
echo (" +---+") . PHP_EOL;
echo (" | |") . PHP_EOL;
echo (" o |") . PHP_EOL;
echo ("/|\ |") . PHP_EOL;
echo ("/ \ |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo (" |") . PHP_EOL;
echo ("=======") . PHP_EOL;
}
}
function toonwoord($letter)
//print de bekende letters in het woord, met verder sterretjes
{
global $galgwoord, $woordstatus;
$galgarray = str_split($galgwoord);
for ($i=0; $i < strlen($galgwoord); $i++) {
if ($galgarray[$i] == $letter) {
$woordstatus[$i] = $letter;
}
}
for ($i=0; $i < strlen($galgwoord); $i++) {
echo $woordstatus[$i] . " ";
}
echo PHP_EOL;
}
function doorgaan($int){
//true is doorgaan
//zes fouten dan return false
//woord is af dan return false,
global $length, $woordstatus;
$boolret = false;
if ($int == 6) {
} else {
# stop als geen asterisk
for ($i=0; $i < $length; $i++) {
if ($woordstatus[$i] == '*') {
$boolret = true;
}
}
}
return $boolret;
}
//kies een woord
$galgwoord = $woordenlijst[rand(1, sizeof($woordenlijst)) - 1];
$length = strlen($galgwoord);
for ($i=0; $i < $length; $i++) {
$woordstatus[$i] = '*';
}
echo "het woord heeft $length letters" . PHP_EOL;
//blanco statusscherm
tekengalg($aantalfouten);
//gekozen letters, woordstatus, foute letters, stand van de galg
echo "U heeft de volgende letters al gekozen: " . $gekozen . PHP_EOL;
echo "U weet dit van het woord: " . $woordstatus[0] . PHP_EOL;
echo "De volgende letters staan niet in het woord: " . PHP_EOL;
//deel 3, computer vraagt een letter,
while (doorgaan($aantalfouten)) {
echo "Geef uw keuze voor een letter." . PHP_EOL;
echo "> ";
$input = trim(fgets(STDIN));
//is het een letter? is die letter eerder gebruikt?
if (ctype_alpha($input)) {
if (strlen($input) == 1) {
echo "De door u gekozen letter is: $input" . PHP_EOL;
if (is_numeric(strpos($gekozen, $input))) {
echo "deze letter heeft u al eerder geprobeerd" . PHP_EOL;
}
else {
echo "U heeft deze letter niet eerder gekozen" . PHP_EOL;
$gekozen .= $input;
if (is_numeric(strpos($galgwoord, $input))) {
echo "goedzo, deze letter komt voor in het woord." . PHP_EOL;
// toon woord met alle bekende letters
toonwoord($input);
} else {
echo "jammer, deze letter komt niet voor in het woord." . PHP_EOL;
$aantalfouten += 1;
tekengalg($aantalfouten);
// nieuw plaatje
}
}
$gekozen .= $input;
} else {
echo "U heeft meer dan één letter gekozen." . PHP_EOL;
}
} else {
echo "dit is geen geldige letter voor galgje." . PHP_EOL;
}
}
if ($aantalfouten == 6) {
echo "sorry, u heeft verloren" . PHP_EOL;
}else{
echo "gefeliciteerd, u heeft gewonnen" . PHP_EOL;
}
?>
</code></pre>
| [] | [
{
"body": "<h3>Use <code>elseif</code> for mutually exclusive conditions</h3>\n\n<p>In <code>tekengalg</code> there are multiple <code>if</code> statements that cannot be <code>true</code> at the same time:</p>\n\n<blockquote>\n<pre><code>if ($arg1 == 0) {\n // ...\n}\nif ($arg1 == 1) {\n // ...\n}\nif ($arg1 == 2) {\n // ...\n}\n// ...\n</code></pre>\n</blockquote>\n\n<p>That is, after <code>$arg1</code> is known to be 0, then there's no need to evaluate <code>$arg == 1</code>, and so on. Replace the second and later <code>if</code> with <code>elseif</code>.</p>\n\n<h3>Avoid flag variables when possible</h3>\n\n<p>In <code>doorgaan</code>, <code>$boolret</code> is set to <code>true</code> when an <code>'*'</code> is found.\nIts value never changes again.\nInstead of setting <code>$boolret = true</code>, you could <code>return true</code> at this point.\nThis will have two nice effects:</p>\n\n<ul>\n<li>Stop looping as soon as possible. It's pointless to continue in the loop, it won't change the outcome of the function.</li>\n<li>Eliminate a variable. If the end of the loop is reached, that means we never returned because we haven't found <code>'*'</code>, so you can <code>return false</code>. No need for the variable <code>$boolret</code>.</li>\n</ul>\n\n<h3>Avoid deeply nested statements</h3>\n\n<p>Deeply nested statements like this can be hard to read:</p>\n\n<blockquote>\n<pre><code>if (ctype_alpha($input)) {\n if (strlen($input) == 1) {\n // ...\n } else {\n echo \"U heeft meer dan één letter gekozen.\" . PHP_EOL;\n }\n} else {\n echo \"dit is geen geldige letter voor galgje.\" . PHP_EOL;\n}\n</code></pre>\n</blockquote>\n\n<p>In particular, when the main branch of an <code>if</code> is a long piece of code, then by the time you read the <code>else</code>, you might not remember well what it was about.\nIn such cases it can be interesting to invert the conditions, making the code flatter, and perhaps easier to understand:</p>\n\n<pre><code>if (!ctype_alpha($input)) {\n echo \"dit is geen geldige letter voor galgje.\" . PHP_EOL;\n continue;\n}\n\nif (strlen($input) != 1) {\n echo \"U heeft meer dan één letter gekozen.\" . PHP_EOL;\n continue;\n}\n\n// ...\n</code></pre>\n\n<h3>Use more helper functions</h3>\n\n<p>I find the <code>echo \"...\" . PHP_EOL</code> boilerplate tedious... I would create a helper function that appends <code>PHP_EOL</code>, so I don't have to repeatedly type that.</p>\n\n<h3>Use better names</h3>\n\n<p>It's important to use names that describe the values they represent,\nand help readers understand the code.\nFor example <code>$arg1</code> doesn't describe that it's the number of failed guesses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:09:30.077",
"Id": "405742",
"Score": "1",
"body": "To improve on \"use better names\": don't program in Dutch. Stick to English. That's what most of the rest of the world does too and makes it a lot more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T12:27:35.983",
"Id": "209902",
"ParentId": "209893",
"Score": "1"
}
},
{
"body": "<h3>Avoid global variables</h3>\n\n<p>This may be difficult to explain but there are many reasons to avoid global variables, many of which are explained in <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">this article</a>. The reasons that stand out the most to me are <strong>Implicit coupling</strong> and <strong>Testing and Confinement</strong> (testing becomes a lot more difficult when global variables are used). </p>\n\n<h3>Empty <code>if</code> statement</h3>\n\n<p>I see the following in <code>doorgaan()</code>:</p>\n\n<blockquote>\n<pre><code>if ($int == 6) {\n } else {\n</code></pre>\n</blockquote>\n\n<p>It would be simpler to just use a negated condition from the <code>if</code> condition:</p>\n\n<pre><code>if ($int !== 6) {\n //statements currently in the else block\n}\n</code></pre>\n\n<h3>Use <a href=\"http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc\" rel=\"nofollow noreferrer\">Nowdoc syntax</a> for multi-line text that is static</h3>\n\n<p>Each of the gallows representations could be stored in a constant - e.g. with <a href=\"https://php.net/define\" rel=\"nofollow noreferrer\"><code>define()</code></a> or <a href=\"http://php.net/manual/en/language.oop5.constants.php\" rel=\"nofollow noreferrer\"><code>const</code></a></p>\n\n<pre><code>const GALLOWS_0 = <<<'GALLOWS'\n +---+\n | |\n |\n |\n |\n |\n |\n=======\nGALLOWS;\n</code></pre>\n\n<p>Then <code>GALLOWS_0</code> could be used instead of the 8 <code>echo()</code> statements with <code>PHP_EOL</code> appended. Another option would be to construct the gallows dynamically based the number in <code>$arg1</code>. Of the six variations with the eight lines, there are only three lines that really change - i.e. the third, fourth and fifth lines. </p>\n\n<h3>Utilize more string functions</h3>\n\n<p>Code like </p>\n\n<blockquote>\n<pre><code>$length = strlen($galgwoord);\nfor ($i=0; $i < $length; $i++) { \n $woordstatus[$i] = '*';\n}\n</code></pre>\n</blockquote>\n\n<p>Could be simplified with <a href=\"https://php.net/str_repeat\" rel=\"nofollow noreferrer\"><code>str_repeat()</code></a>:</p>\n\n<pre><code>$woordstatus = str_repeat('*', strlen($galgwoord));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:20:54.503",
"Id": "209919",
"ParentId": "209893",
"Score": "1"
}
},
{
"body": "<p>I didn't test any of my snippets below, so they may contain typos. I am only including them to give context to my advice.</p>\n\n<p>I translated the Dutch to English so that I could follow your processes.</p>\n\n<ul>\n<li><p>By storing the gallows data as a semi-matrix, you can swiftly update the image by adding a single character in its desired position. I could have condensed the <code>$victim</code> array further, but I felt that that would negatively impact readability / maintainability.</p></li>\n<li><p>My custom <code>update</code> functions modify variables by reference, so there is no return value -- this makes the code slightly more succinct.</p></li>\n<li><p>Iterating the letters in a string can be done without splitting the word into an array of letters because php allows access to each letter by its offset. If your hangman game may include multibyte characters, <code>mb_</code> functions will need to be implemented.</p></li>\n<li><p>In your loop I recommend writing all of your negative/invalid/erred processes first and saving the successful outcome for last -- I find this more readable.</p></li>\n</ul>\n\n<p>The custom functions:</p>\n\n<pre><code>function game_not_finished($secret_word, $word_status, $wrong_count) {\n return $wrong_count < 6 && $secret_word != $word_status;\n}\n\nfunction update_gallows(&$gallows, $part) {\n $gallows[$part[\"row\"]][$part[\"offset\"]] = $part[\"symbol\"];\n}\n\nfunction update_word_status($secret_word, &$word_status, $letter) {\n for ($offset = 0, $length = strlen($secret_word); $offset < $length; ++$offset) {\n if ($secret_word[$offset] == $letter) {\n $word_status[$offset] == $letter;\n }\n }\n}\n</code></pre>\n\n<p>The gallows storage:</p>\n\n<pre><code>$gallows = [\n \" +---+\",\n \" | |\",\n \" |\",\n \" |\",\n \" |\",\n \" |\",\n \"=======\",\n];\n\n$victim = [\n [\"row\" => 2, \"offset\" => 1, \"symbol\" => \"o\"], // head\n [\"row\" => 3, \"offset\" => 1, \"symbol\" => \"|\"], // torso\n [\"row\" => 3, \"offset\" => 0, \"symbol\" => \"/\"], // right arm\n [\"row\" => 3, \"offset\" => 2, \"symbol\" => \"\\\\\"], // left arm\n [\"row\" => 4, \"offset\" => 0, \"symbol\" => \"/\"], // right leg\n [\"row\" => 4, \"offset\" => 2, \"symbol\" => \"\\\\\"], // left leg\n];\n</code></pre>\n\n<p>Initializing required variables:</p>\n\n<pre><code>$secret_word = $wordpool[rand(0, sizeof($wordpool) -1)];\n$word_length = strlen($secret_word);\n$word_status = str_repeat('*', $word_length);\n$chosen_letters = '';\n$wrong_letters = '';\n$wrong_count = 0;\n\necho \"The word has $word_length letters.\" , PHP_EOL; \n</code></pre>\n\n<p>The loop:</p>\n\n<pre><code>while (game_not_finished($secret_word, $word_status, $wrong_count)) {\n echo \"You have already chosen the following letters: \" , $chosen_letters , PHP_EOL;\n echo \"The letters revealed so far are: \" , $word_status , PHP_EOL;\n echo \"The following guessed letters are not in the word: \" , $wrong_letters , PHP_EOL;\n echo implode(PHP_EOL, $gallows);\n\n echo \"Give your choice for a letter.\" . PHP_EOL;\n echo \">\";\n $input = trim(strtolower(fgets(STDIN))); // or uppercase if fitting for your word list\n echo \"The letter you have chosen is: $input\" , PHP_EOL;\n // validate input\n if (strlen($input) != 1) {\n echo \"You have chosen more than one letter.\" , PHP_EOL;\n continue;\n }\n if (!ctype_alpha($input)) {\n echo \"This is not a valid letter for hangman.\" , PHP_EOL;\n continue;\n }\n if (strpos($chosen_letters, $input) === false) {\n echo \"You have tried this letter before.\" , PHP_EOL;\n continue;\n }\n if (strpos($secret_word, $input) === false) {\n echo \"Too bad, this letter does not appear in the word.\" , PHP_EOL;\n $wrong_letters .= $input;\n update_gallows($gallows, $victim[$wrong_count]); // add another body part to gallows\n ++$wrong_count;\n } else {\n echo \"Well done, this letter occurs in the word.\" , PHP_EOL;\n update_word_status($secret_word, &$word_status, $input); // no return value, overwrites $word_status in function\n }\n $chosen_letters .= $input;\n}\n</code></pre>\n\n<p>The conclusion:</p>\n\n<pre><code>if ($wrong_count == 6) {\n echo \"Sorry, you lost\" , PHP_EOL;\n // show full hangman . echo implode(PHP_EOL, $gallows);\n} else {\n echo \"Congratulations, you won\" , PHP_EOL;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T22:01:24.127",
"Id": "210330",
"ParentId": "209893",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T09:51:07.247",
"Id": "209893",
"Score": "2",
"Tags": [
"beginner",
"php",
"game",
"console",
"hangman"
],
"Title": "Simple Hangman in PHP"
} | 209893 |
<p>I want to create a function that unpacks nested <code>dataclass</code>es and <code>namedtuple</code>s (or a combination of both)</p>
<hr>
<p><strong>my attempt</strong></p>
<p>I found <a href="https://stackoverflow.com/a/39235373/9253013">this</a> answer about how to unpack a named tuple, and i am simply extending it:</p>
<p>the unpack function</p>
<pre><code>def unpack(obj):
if isinstance(obj, dict):
return {key: unpack(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [unpack(value) for value in obj]
elif is_named_tuple_instance(obj):
return {key: unpack(value) for key, value in obj._asdict().items()}
elif is_data_class_instance(obj):
return {key: unpack(getattr(obj, key)) for key in obj.__dataclass_fields__.keys()}
elif isinstance(obj, tuple):
return tuple(unpack(value) for value in obj)
else:
return obj
</code></pre>
<p>the <code>is_data_class_instance</code> function:</p>
<pre><code>def is_data_class_instance(obj):
data_class_attrs = {'__dataclass_fields__', '__dataclass_params__'}
return set(dir(obj)).intersection(data_class_attrs) == data_class_attrs
</code></pre>
<hr>
<p>side note, would this be acceptable type hints ?</p>
<pre><code>from typing import NamedTuple, Any, NewType, Union
DataClass = NewType('DataClass', Any)
def unpack(obj: Union[DataClass, NamedTuple, Any]) -> Union[tuple, list, dict, Any]:
...
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T10:48:54.730",
"Id": "503743",
"Score": "0",
"body": "This is interesting, if you solved it a solution would be appreciated. I wonder why you didn't use dataclasses.astuple, that seems a simple way to unpack, although I am not sure about recursively as your function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T12:04:12.293",
"Id": "504357",
"Score": "0",
"body": "@Davos what do you mean by \"solve\"? The code runs as expected"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T14:08:29.343",
"Id": "504370",
"Score": "0",
"body": "Oh I see now this site is Code Review, I thought this was a question, my mistake. Regarding the type hints, I think if you are going to put `Any` in a `Union` type then it makes other types in the `Union` redundant."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T11:05:21.430",
"Id": "209898",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "unpack a nested dataclass and named tuple"
} | 209898 |
<p>I am creating a test class for the following code. splay_test.py which is the unit test code for <a href="https://en.wikipedia.org/wiki/Splay_tree" rel="nofollow noreferrer">splay tree</a>. I needed help with writing unit tests for python to get %100 coverage. I am very bad at unit testing but have started off ok. just need someone to help me finish it off and maybe find any more bugs. My coverage for some reason isn't connecting the two files together so I can't see what my overall coverage is.</p>
<pre><code>class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
def equals(self, node):
return self.key == node.key
class SplayTree:
def __init__(self):
self.root = None
self.header = Node(None) # For splay()
def insert(self, key):
if (self.root == None):
self.root = Node(key)
return #test
self.splay(key)
if self.root.key == key:
# If the key is already there in the tree, don't do anything.
return
n = Node(key)
if key < self.root.key:
n.left = self.root.left
n.right = self.root
self.root.left = None
else:
n.right = self.root.right
n.left = self.root
self.root.right = None
self.root = n
def remove(self, key):
self.splay(key)
if key != self.root.key:
raise 'key not found in tree' # do
# Now delete the root.
if self.root.left == None:
self.root = self.root.right
else:
x = self.root.right
self.root = self.root.left
self.splay(key)
self.root.right = x
def findMin(self):
if self.root == None:
return None
x = self.root
while x.left != None:
x = x.left
self.splay(x.key)
return x.key
def findMax(self):
if self.root == None:
return None
x = self.root
while (x.right != None):
x = x.right
self.splay(x.key)
return x.key
def find(self, key): # test
if self.root == None:
return None
self.splay(key)
if self.root.key != key:
return None
return self.root.key
def isEmpty(self):
return self.root == None
def splay(self, key): # test
l = r = self.header
t = self.root
self.header.left = self.header.right = None
while True:
if key < t.key:
if t.left == None:
break
if key < t.left.key:
y = t.left
t.left = y.right
y.right = t
t = y
if t.left == None:
break
r.left = t
r = t
t = t.left
elif key > t.key:
if t.right == None:
break
if key > t.right.key:
y = t.right
t.right = y.left
y.left = t
t = y
if t.right == None:
break
l.right = t
l = t
t = t.right
else:
break
l.right = t.left
r.left = t.right
t.left = self.header.right
t.right = self.header.left
self.root = t
</code></pre>
<p>What I have so far</p>
<pre><code>import unittest
from splay import SplayTree
class TestCase(unittest.TestCase):
def setUp(self):
self.keys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
self.t = SplayTree()
for key in self.keys:
self.t.insert(key)
def testInsert(self):
for key in self.keys:
self.assertEquals(key, self.t.find(key))
def testRemove(self):
for key in self.keys:
self.t.remove(key)
self.assertEquals(self.t.find(key), None)
def testLargeInserts(self):
t = SplayTree()
nums = 40000
gap = 307
i = gap
while i != 0:
t.insert(i)
i = (i + gap) % nums
def testIsEmpty(self):
self.assertFalse(self.t.isEmpty())
t = SplayTree()
self.assertTrue(t.isEmpty())
def testMinMax(self):
self.assertEquals(self.t.findMin(), 0)
self.assertEquals(self.t.findMax(), 9)
</code></pre>
<p>Tests I have done so far </p>
<pre><code>import unittest
from splay import SplayTree
class TestCase(unittest.TestCase):
def setUp(self):
self.keys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
self.t = SplayTree()
for key in self.keys:
self.t.insert(key)
def testInsert(self):
for key in self.keys:
self.assertEquals(key, self.t.find(key))
def testRemove(self):
for key in self.keys:
self.t.remove(key)
self.assertEquals(self.t.find(key), None)
def testLargeInserts(self):
t = SplayTree()
nums = 40000
gap = 307
i = gap
while i != 0:
t.insert(i)
i = (i + gap) % nums
def testIsEmpty(self):
self.assertFalse(self.t.isEmpty())
t = SplayTree()
self.assertTrue(t.isEmpty())
def testMinMax(self):
self.assertEquals(self.t.findMin(), 0)
self.assertEquals(self.t.findMax(), 9)
if __name__ == "__main__":
unittest.main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T15:25:06.977",
"Id": "405733",
"Score": "1",
"body": "Rather than writing an `equals` method, consider using `__eq__`; do some reading here: https://docs.python.org/3/reference/datamodel.html#object.__eq__"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T17:54:35.977",
"Id": "406921",
"Score": "0",
"body": "@Reinderien You have a point about that, but as far as i can see, he hasn't make any `equals` method, he's rather using an [assertion](https://www.programiz.com/python-programming/assert-statement)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T21:11:15.507",
"Id": "406949",
"Score": "0",
"body": "@SebasSBM Look harder :) There's an `equals` under the `Node` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-29T02:32:31.540",
"Id": "406977",
"Score": "0",
"body": "@Reinderien in that case, `__eq__` usage would fit better, as you said."
}
] | [
{
"body": "<p>You've already done a pretty good job adding these tests and covering a big chunk of the code under test.</p>\n\n<p>The problem is, if we look at the <a href=\"https://coverage.readthedocs.io/en/coverage-4.3.4/branch.html\" rel=\"nofollow noreferrer\"><em>branch coverage</em></a>, we'll see that quite a few of the branches are not reached as the implementation is relatively <a href=\"https://github.com/PyCQA/mccabe\" rel=\"nofollow noreferrer\">\"complex\"</a> - by <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">code complexity standards</a>:</p>\n\n<pre><code>python -m pytest test_tree.py --cov-branch --cov=tree --cov-report html\n</code></pre>\n\n<p>Using <code>pytest</code> and <code>pytest-cov</code> plugin, <code>tree</code> here is the module/package name for which to measure coverage. </p>\n\n<p>Other observations:</p>\n\n<ul>\n<li><code>self.assertEquals()</code> is deprecated in favor of <code>self.assertEqual()</code></li>\n<li>even though <code>setUp</code> and <code>tearDown</code> are the legacy camel-case Junit-inspired names, consider following PEP8 and naming your methods in an <a href=\"https://www.python.org/dev/peps/pep-0008/#id36\" rel=\"nofollow noreferrer\">lower_case_with_underscores style</a></li>\n<li>look into defining your tree as a <a href=\"https://docs.pytest.org/en/latest/fixture.html\" rel=\"nofollow noreferrer\"><code>pytest</code> fixture</a></li>\n<li>look into <em>property-based-testing</em> with <a href=\"https://hypothesis.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">Hypothesis</a> as a means to generate possible input nodes for your tree</li>\n<li>focus on the more complex parts first as this is where the possibility of having a problem is higher - the <code>splay()</code> method should probably be tested separately and directly checking all the major variations of re-balancing the tree when a new node is added</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T16:15:44.133",
"Id": "209914",
"ParentId": "209904",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T13:05:25.503",
"Id": "209904",
"Score": "6",
"Tags": [
"python",
"unit-testing",
"tree"
],
"Title": "Unit testing for Splay Tree in Python"
} | 209904 |
<p>I have project on Django wich use Django Channels. I use Django Channel for sending notifications to users who are subscribed to articles changes (adding/editing/deleting comments on article).</p>
<p>So I've chosen this way of realization: every group of channels is an article and when changes happen, script sends notification to relevant groups. My code works correctly but I have some doubts if my choice of way of realization is most appropriate for this task. I need advice what is the best practice in my case?</p>
<p>Solution:</p>
<p>consumers.py</p>
<pre><code>from channels.generic.websocket import AsyncJsonWebsocketConsumer
from channels.db import database_sync_to_async
from project.apps.account.models import UserStatus
from .models import CommentSubscribe
class CommentNotificationConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
if not self.scope['user'].is_anonymous:
groups = await database_sync_to_async(self.get_users_subscription)()
await database_sync_to_async(self.change_user_status)(True)
await self.add_subscriptions(groups)
async def add_subscriptions(self, groups):
for group in groups:
await self.channel_layer.group_add(
'article_{0}'.format(group.article_id),
self.channel_name
)
async def receive_json(self, content, **kwargs):
command = content.get('command', None)
article_id = content.get('article_id', None)
if command == 'subscribe':
await self.subscribe(article_id)
elif command == 'unsubscribe':
await self.unsubscribe(article_id)
else:
await self.send_json({
'error': 'unknown command'
})
async def disconnect(self, code):
await database_sync_to_async(self.change_user_status)(False)
async def send_notification(self, action):
await self.send_json(action)
async def subscribe(self, article_id):
await self.channel_layer.group_add(
'article_{0}'.format(article_id),
self.channel_name
)
async def unsubscribe(self, article_id):
await self.channel_layer.group_discard(
'article_{0}'.format(article_id),
self.channel_name
)
def get_users_subscription(self):
return CommentSubscribe.objects.filter(
user=self.scope['user']
)
def change_user_status(self, online):
return UserStatus.objects.filter(
user=self.scope['user']
).update(online=online)
</code></pre>
<p>views.py</p>
<pre><code>from .notify import send_comment_notification
class CreateComment(CreateView):
...
def form_valid(self, form):
...
super().form_valid(form)
send_comment_notification('create', article_id)
class UpdateComment(UpdateView):
...
def form_valid(self, form):
...
super().form_valid(form)
send_comment_notification('update', article_id)
class DeleteComment(DeleteView):
...
def delete(self, request, *args, **kwargs):
...
send_comment_notification('delete', article_id)
</code></pre>
<p>notify.py</p>
<pre><code>...
def send_comment_notification(action, article_id):
channel_layer = get_channel_layer()
group_name = 'article_{0}'.format(article_id)
async_to_sync(channel_layer.group_send)(
group_name,
{
'type': 'send.notification',
'data': {
'action': action
}
}
)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T13:43:47.963",
"Id": "209907",
"Score": "11",
"Tags": [
"python",
"django",
"async-await",
"websocket"
],
"Title": "Sending notifications with Django channels"
} | 209907 |
<p>Today I tried Bonobo + SQLAlchemy (for the first time), so it's bound to be full of bad practices. However, this is working code. I'm hoping for some feedback to for doing it correctly.</p>
<p>I started out using the SQLAlchemy extension for Bonobo, but I ran into limitations, so I wrote my own loader. My DB is SQLite3, so it doesn't support multiple connections.</p>
<p>What this does is read from one table, do a simple transformation and load into a target table with a different table structure.</p>
<p>SQLite database:</p>
<pre><code>CREATE TABLE sys_batch (
batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_name VARCHAR2 ( 100 ) );
CREATE TABLE sys_batch_tgt (
batch_id INTEGER PRIMARY KEY,
name_of_batch VARCHAR2 ( 100 ) );
</code></pre>
<p>Python code:</p>
<pre><code>import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.sql import select
from sqlalchemy.orm import Session
import bonobo
#import bonobo_sqlalchemy
engine = sqlalchemy.create_engine('sqlite:///C:/Py/bonobo/coolstuff.db')
Base = automap_base()
Base.prepare(engine, reflect=True)
# Tables
sys_batch = Base.classes.sys_batch
sys_batch_tgt = Base.classes.sys_batch_tgt
#def get_services():
# return {'sqlalchemy.pgengine': sqlalchemy.create_engine('sqlite:///C:/Py/bonobo/coolstuff.db')}
def extract_sys_batch():
conn = engine.connect()
s = select([sys_batch])
result = conn.execute(s)
#conn.close()
row = result.fetchone()
yield row
# convert incoming SQLAlchemy "ProxyRow" to a dict, so we can manipulate it.
def tfm_0(row):
tgt_row = {}
tgt_row['batch_id'] = row['batch_id']
tgt_row['name_of_batch'] = row['batch_name']
return tgt_row
def tfm_1(row):
row['batch_id'] = row['batch_id'] + 100
return row
def ldr_1(row):
# write to target
session = Session(engine)
thing = sys_batch_tgt(**row)
session.add(thing)
session.commit()
def get_graph(**options):
return bonobo.Graph(
extract_sys_batch,
tfm_0,
tfm_1,
ldr_1,
bonobo.PrettyPrinter(),
)
# The __main__ block actually execute the graph.
if __name__ == '__main__':
parser = bonobo.get_argument_parser()
#each transformation is its own thread, so we have to open/close in there.
#conn = engine.connect()
with bonobo.parse_args(parser) as options:
bonobo.run(get_graph(**options)) #, services=get_services(**options)
#conn.close()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:59:31.800",
"Id": "405836",
"Score": "0",
"body": "So `get_graph` ignores all options?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:25:32.380",
"Id": "209920",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"sqlalchemy"
],
"Title": "Loading into a target table"
} | 209920 |
<p>I was trying my hand at learning Elixir via ancient adventofcode puzzles and was trying to write a function to satisfy this requirement:</p>
<blockquote>
<p>It contains a pair of any two letters that appears at least twice in
the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but
not like aaa (aa, but it overlaps).</p>
</blockquote>
<p>Here is what I came up with, but it feels like it might be unwieldy. Is there a way to make it more elegant?</p>
<pre><code> def has_non_overlapping_pair(string) do
0..String.length(string)-2
|> Enum.map(fn n ->
String.slice(string, n, 2)
end)
|> Enum.reduce(["_"], fn pair, acc ->
if pair == hd(acc) do ["_"|acc]
else [pair|acc] end
end)
|> count_occurrences
|> Map.delete("_")
|> Map.values
|> Enum.any?(fn val -> val > 1 end)
end
</code></pre>
| [] | [
{
"body": "<p>You could use a map to store the pairs with their first occurrence while iterating over the pairs. Break if the current pair was already found at a position less than the current position minus 1.</p>\n\n<pre><code>def has_non_overlapping_pair(string) do\n 0..String.length(string) - 2\n |> Enum.reduce_while(%{}, fn n, m ->\n pair = String.slice(string, n, 2)\n pos = Map.get(m, pair, n)\n cond do\n pos == n -> {:cont, Map.put(m, pair, n)}\n pos == n - 1 -> {:cont, m}\n true -> {:halt, true}\n end\n end) == true\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T01:58:35.477",
"Id": "210197",
"ParentId": "209921",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:30:31.110",
"Id": "209921",
"Score": "6",
"Tags": [
"strings",
"elixir"
],
"Title": "String contains non-overlapping letter pairs"
} | 209921 |
<p>I recently started coding and after learning a bit about functions and basics I tried to make a simple text escape room game. My code is working and the game functions as intended but I now there are probably neat ways to reduce the long amount of code using techniques I haven't yet heard about. I would really appreciate it if anyone could offer some improvements I could make.</p>
<pre><code>room1 ="""There's a small, silent creature huddled in the corner chained to a
pipe. It faces the wall and trembles vigorously. Around the room there are many
sharp objects smeared in a thick, inky liquid. It stings to the touch. You want
to leave as soon as possible. In the corner of the room there is a switch on the
wall.\n
The doors are in front of you and to the right.\n"""
room2 ="""There is a body upon a table in the middle of the room, but it doesn't
look like a human. It has huge black eyes and a strangely misshapen head. The
skin is an ugly greyish colour and it's blood smells like perfume.
The doors are behind you, right, and forwards.\n"""
room3 ="""You open the door and the room is completely filled with water, or some
kind of watery substance that somehow doesn't gush out when you open the door,
seemingly encased by an invisible membrane. The only way to get to the other
doors is to swim through the block of water. The liquid has a yellow-green tinge
to it.
The doors are behind you and to the right.\n\n"""
room4 ="""The rancid smell of rotting flesh fills your nose as you glance around
the concrete room. You see...nothing. Until you look up and notice the 7 corpses
dangling from the roof. Instantly repulsed, you think nothing can be worse than
this.
The doors are left, right, and forward.\n"""
room5 ="""The same room you woke up in. You wonder how you ended up in this
nightmarish hell-house.
The doors are on all sides.\n"""
room6 ="""As you open the door there is an ominous choral humming. Apprehensively,
you enter into a room circled by cloaked figures, rehearsing a bone chilling
chant. The longer you listen, the more you want to leave.
The doors behind you, to your left, and to your right.\n"""
room7 ="""All this room is, is yellow hazard writing on the wall reading 'Room 7'
You get the sense this one hasn't been finished yet.
The doors are to your left and forwards.\n"""
room8 ="""Pleasantly, you are surprised by a room seemingly out of a museum, with
beautiful pieces of art lining each of the four walls, and classical music
playing. Only, the art seems to be... bleeding.
The doors are behind you, left, and forward.\n"""
room9 ="""A large, levitating, purple ball sits in the center of the room. All
light seemes to be swallowed up by it and it produces a low frequency sound
that makes your bones shake within you. You try and approach it but it repels
you like a magnet and leaves you skirting around it to get to the other doors.
The doors are behind you and to your left.\n"""
r1 ="""\n
|[ ][ ][ ]|
|[ ][ ][ ]|
|[^][ ][ ]|
"""
r2 ="""\n
|[ ][ ][ ]|
|[^][ ][ ]|
|[ ][ ][ ]|
"""
r3 ="""\n
|[^][ ][ ]|
|[ ][ ][ ]|
|[ ][ ][ ]|
"""
r4 ="""\n
|[ ][ ][ ]|
|[ ][ ][ ]|
|[ ][^][ ]|
"""
r5 ="""\n
|[ ][ ][ ]|
|[ ][^][ ]|
|[ ][ ][ ]|
"""
r6 ="""\n
|[ ][^][ ]|
|[ ][ ][ ]|
|[ ][ ][ ]|
"""
r7 ="""\n
|[ ][ ][ ]|
|[ ][ ][ ]|
|[ ][ ][^]|
"""
r8 ="""\n
|[ ][ ][ ]|
|[ ][ ][^]|
|[ ][ ][ ]|
"""
r9 ="""\n
|[ ][ ][^]|
|[ ][ ][ ]|
|[ ][ ][ ]|
"""
#!/usr/bin/python3
import time
import sys
import random
import pygame
pygame.init()
start_time=time.time()
def stutter(text):
for c in text:
print(c, end="")
sys.stdout.flush()
time.sleep(.02)
def end():
stutter("\n>>>>><<<<<\nYOU DIED\n>>>>><<<<<\n")
sound.load("/home/leo/Documents/Python/Sounds/lose.mp3")
sound.play()
time.sleep(6)
start()
def win():
global start_time
end_time=time.time()-start_time
m = end_time / 60
minutes = round(m,2)
stutter("\n---------------------------------------------------\n")
stutter("Well done! You escaped in only {} minutes!\n".format(minutes))
stutter("\nThank you for playing!")
def direction():
global x
global y
global key
global gloves
global intestines
global battery
global switch
global potion
global chance
prompt = input("\n\nChoose a direction using AWSD:\n")
if prompt == "a" or prompt == "A":
if (x-1) > 0 and (x-1) <= 3:
x -= 1
else:
stutter("You hit a wall")
sound.load("/home/leo/Documents/Python/Sounds/thud.mp3")
sound.play()
direction()
elif prompt == "w" or prompt == "W":
if (y+1) > 0 and (y+1) <= 3:
y += 1
else:
stutter("You hit a wall")
sound.load("/home/leo/Documents/Python/Sounds/thud.mp3")
sound.play()
direction()
elif prompt == "s" or prompt == "S":
if (y-1) > 0 and (y-1) <= 3:
y -= 1
else:
stutter("You hit a wall")
sound.load("/home/leo/Documents/Python/Sounds/thud.mp3")
sound.play()
direction()
elif prompt == "d" or prompt == "D":
if (x+1) > 0 and (x+1) <= 3:
x += 1
else:
stutter("You hit a wall")
sound.load("/home/leo/Documents/Python/Sounds/thud.mp3")
sound.play()
direction()
else:
print("That's not a valid input")
direction()
if x==1 and y==1:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
print(r1)
stutter(room1)
if switch == False:
stutter("The switch on the wall seems to be missing a battery.\n")
flick_switch = input("Flick the switch?(y or n):\n")
if flick_switch == "y" or flick_switch == "Y":
if battery == True:
stutter("""Hastily, not wanting to spend any more time with the
unnerving creature in the corner, you insert the
battery into the socket and flick the switch. A
series of mechanical whirrings come from one of
the other rooms.""")
sound.load("/home/leo/Documents/Python/Sounds/metal_scrape.mp3")
sound.play()
time.sleep(2)
switch = True
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
direction()
elif battery == False:
stutter("""
The cowering creature in the corner, seeminly
suddenly agitated, turns to see you flicking the
switch that doesn't have a battery in. Its depressing
face morphs in a flash into a terrify expression of
anger, and, with sudden strength and a terrifying
snarl, it rips it's restraints off and bounds towards
you.""")
sound.load("/home/leo/Documents/Python/Sounds/scream2.mp3")
sound.play()
stutter("""
It pounces on top of you, overpowering
you, and digs its knife-like nails into your eyes.""")
sound.play()
stutter("""
At once, you are filled with instant regret knowing
that the last thing you see will be the creatures
disgusting face.""")
end()
elif flick_switch == "n" or flick_switch == "N":
stutter("You leave the switch for the time being.")
direction()
elif switch == True:
direction()
elif x==1 and y==2:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
print(r2)
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
stutter(room2)
if intestines == False:
stutter("""\nIt's strange, rope-like intestines lay on another table
bordering the room.""")
take_intestines = input("\nTake the intestines?(y or n):\n")
if take_intestines == "y" or take_intestines == "Y":
if gloves == True:
stutter("Using the gloves, you pick up the intestines.\n")
stutter("Intestines equipped.")
sound.load("/home/leo/Documents/Python/Sounds/ding.mp3")
sound.play()
time.sleep(2)
intestines = True
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
direction()
elif gloves == False:
sound.load("/home/leo/Documents/Python/Sounds/scream1.mp3")
sound.play()
stutter("""
You try to take the intestines but as soon as you touch
them, spasms run up and down your arm, then through
your entire body.""")
sound.play()
stutter("""You begin frothing at the mouth as
you feel the last dregs of life force swiftly exiting
your body.""")
end()
elif take_intestines == "n" or take_intestines == "N":
stutter("""You decide to leave the intestines for now""")
direction()
elif intestines == True:
direction()
elif x==1 and y==3:
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
stutter(room3)
stutter("""You notice one of the doors has the bright sign saying 'EXIT'
above it.\n""")
swim = input("Swim through the liquid to the door?(y or n):\n")
if swim == "y" or swim == "Y":
if potion == True:
sound.load("/home/leo/Documents/Python/Sounds/escape.mp3")
sound.play()
stutter("""The potion protecting you from the deadly toxicity, you
swim through the thick, cold substance, inching
closer to the door every stroke, hope fills your heart
as you stand in front of the exit door and grasp the
possibility of escape. One shove of the door, sees
it swing open and reveal a wide expanse of forest.
\nYou made it! You escaped! At least for now...""")
win()
elif potion == False:
sound.load("/home/leo/Documents/Python/Sounds/scream3.mp3")
sound.play()
stutter("""As soon as you make contact with the liquid your
body begins to slowly disintegrate. Piece by
piece, you break apart. You look down and see
your insides tumbling out your stomach.""")
sound.load("/home/leo/Documents/Python/Sounds/scream3.mp3")
sound.play()
stutter("""Your
eyes bulge and your limps are ripped of by an
invisible force and the bleak world slowly fades away..""")
end()
elif swim == "n" or swim == "N":
stutter("You decide to avoid touching the substance for now.")
direction()
elif x==2 and y==1:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
print(r4)
stutter(room4)
if key == False:
stutter("\nThere is a key tucked inside one of the body's trouser pocket.\n")
take_key = input("Take the key?(y or n):\n")
if take_key == "y" or take_key == "Y":
stutter("Key equipped.")
sound.load("/home/leo/Documents/Python/Sounds/ding.mp3")
sound.play()
time.sleep(2)
key = True
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
direction()
elif take_key =="n" or take_key =="N":
stutter("You didn't take the key.")
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
direction()
elif key == True:
direction()
elif x==2 and y==2:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
print(r5)
stutter(room5)
direction()
elif x==2 and y==3:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
print(r6)
sound.load("/home/leo/Documents/Python/Sounds/scary_chant.mp3")
sound.play()
stutter(room6)
if gloves == False:
stutter("""\nThere is a small locked glass case in the middle of the room with
a pair of silk gloves inside.\n""")
take_gloves = input("Take the gloves?(y or n):\n")
if take_gloves == "y" or take_gloves == "Y":
if key == True:
stutter("Using the key, you open the case and take the gloves.\n")
sound.load("/home/leo/Documents/Python/Sounds/unlock.mp3")
sound.play()
time.sleep(3)
stutter("Gloves equipped.")
sound.load("/home/leo/Documents/Python/Sounds/ding.mp3")
sound.play()
time.sleep(2)
gloves = True
sound.load("/home/leo/Documents/Python/Sounds/scary_chant.mp3")
sound.play()
direction()
elif key == False:
stutter("The case is locked and you can't get the gloves.")
direction()
elif take_gloves =="n" or take_gloves =="N":
stutter("You didn't take the gloves.")
direction()
elif gloves == True:
direction()
elif x==3 and y==1:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
sound.load("/home/leo/Documents/Python/Sounds/ambient.mp3")
sound.play()
if switch == False or potion == True:
print(r7)
stutter(room7)
direction()
elif switch == True:
print(r7)
stutter(room7)
time.sleep(2)
stutter("\nBut wait...\n")
time.sleep(2)
stutter("""Now a small hatch has opened up in the wall. You peek inside
and a small volume of liquid sits in a glass flask. This
must be what the switch opened. You read the label.
'The odds are even. Will you take the chance?'
You ponder what this means as you sense an important
decision approaching...""")
drink = input("\nWill you drink the potion?(y or n):\n")
if drink == "n" or drink == "N":
stutter("You might come back to the potion later.")
elif drink == "y" or drink == "Y":
sound.load("/home/leo/Documents/Python/Sounds/glug.mp3")
sound.play()
time.sleep(0.6)
sound.play()
time.sleep(0.6)
sound.play()
time.sleep(0.6)
sound.play()
time.sleep(0.6)
sound.play()
time.sleep(1)
if chance == 0 or chance == 1:
stutter("""You tip the potion back into your mouth. Nothing goes
wrong so you assume it worked.""")
stutter("\nPotion activated.")
sound.load("/home/leo/Documents/Python/Sounds/item_consumption.mp3")
sound.play()
potion = True
direction()
elif chance == 2:
sound.load("/home/leo/Documents/Python/Sounds/scream2.mp3")
stutter("You gulp the liquid down. Oh no.")
sound.play()
stutter("""
You bones feel like they're being hammerred at from the inside. You run
your hands through your hair and every strand is
stripped of and falls on the floor.""")
sound.play()
stutter("""
It feels like all of your nails and toenails are ripped off one
by one. You try and move, but full body paralysis
seems to have overcome your body. 'Fuck'.""")
sound.load("/home/leo/Documents/Python/Sounds/scream1.mp3")
sound.play()
stutter("""
You suffer one last wave of astronomical pain
before swiftly leaving this plane of existance.""")
end()
elif x==3 and y==2:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
print(r8)
sound.load("/home/leo/Documents/Python/Sounds/classical_music.mp3")
sound.play()
stutter(room8)
if battery == False:
stutter("""\nYou notice a faint light behind one of the paintings and
so take the hanging art of the wall. It reveals a thin
cylindrical hole in the wall too thin to fit through.
You can see that there is something at the end but
don't know what it is.\n""")
take_battery = input("Reach for the object?(y or n):\n")
if take_battery == "y" or take_battery == "Y":
if intestines == True:
stutter("""Using the ropey intesines, you form them into somewhat
of a lasso shape and manage to fish out the the
object. It is a battery.\n""")
stutter("Battery equipped.")
sound.load("/home/leo/Documents/Python/Sounds/ding.mp3")
sound.play()
battery = True
time.sleep(2)
sound.load("/home/leo/Documents/Python/Sounds/classical_music.mp3")
sound.play()
direction()
elif intestines == False:
stutter("The hole is to small to reach the object through.")
direction()
elif take_battery == "n" or take_battery == "N":
stutter("You didn't get the object.")
direction()
elif battery == True:
direction()
elif x==3 and y==3:
sound.load("/home/leo/Documents/Python/Sounds/walking.mp3")
sound.play()
time.sleep(2)
sound.stop()
print(r9)
sound.load("/home/leo/Documents/Python/Sounds/low_hum.mp3")
sound.play()
stutter(room9)
touch = input("\nTouch the levitating ball?(y or n):\n")
if touch == "y" or touch == "Y":
sound.load("/home/leo/Documents/Python/Sounds/scream1.mp3")
sound.play()
time.sleep(2)
end()
elif touch =="n" or touch =="N":
print("Makes sense")
direction()
def start():
global x
global y
global key
global gloves
global intestines
global battery
global switch
global potion
global chance
global sound
x=2
y=2
key = False
gloves = False
intestines = False
battery = False
switch = False
potion = False
chance = random.randint(0,2)
sound = pygame.mixer.music
sound.load("/home/leo/Documents/Python/Sounds/slow_music.mp3")
sound.play()
stutter("\n\n<<<<<<<<<<<<<<<<<<<<<<<<<< Escape Room >>>>>>>>>>>>>>>>>>>>>>>>>>\n")
time.sleep(3)
stutter("A game by Leo Gortzak\n")
time.sleep(5)
stutter("""\n\nYou awake in a dark room with a rusty iron door. There is a small
circular window casting a dim light across the room.
There are four doors leading out. One on each wall.\n""")
print(r5)
direction()
start()
</code></pre>
| [] | [
{
"body": "<p>You could possibly store the rooms in a text file to reduce the code,\nlike this:</p>\n\n<pre><code>if rooms == 1:\n N=10\n f=open(\"test.txt\")\n for i in range(5):\n line=f.read().strip()\n print(line)\n f.close()\n</code></pre>\n\n<p>This will print what is inside the file and for the range you put the number of lines that are in the file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:17:56.317",
"Id": "405754",
"Score": "0",
"body": "Not just the rooms either, the texts, stutters and everything else could be in there too. Or in different files, if you're so inclined. To keep things neat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:19:08.597",
"Id": "405755",
"Score": "1",
"body": "Of-course, once you go this route, you can simply read the entire file and parse it in a loader. This loader can put all the texts in lists or dictionaries."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T18:39:44.043",
"Id": "209926",
"ParentId": "209922",
"Score": "2"
}
},
{
"body": "<p>Organizationally, something that might help in this type of game is classes:\n<a href=\"https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/\" rel=\"nofollow noreferrer\">https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/</a></p>\n\n<p>For example, you could store all the relevant data for a single room together in a Room class, and you could store the state of various flags like gloves/battery/switch in a GameState class.</p>\n\n<p>In addition to that, try to reduce global variables and instead just pass each function the data it needs. This will make it much easier to grow your game further - at nine rooms, you already have ten global variables, and that number will keep going up until it becomes unmanageable. </p>\n\n<p>For example:</p>\n\n<pre><code> def promptMovement(gameState):\n prompt = input(\"\\n\\nChoose a direction using AWSD:\\n\")\n if prompt.lower() == \"a\":\n attemptMovement(gameState, -1, 0)\n else if prompt.lower() == \"w\":\n attemptMovement(gameState, 0, 1)\n else if prompt.lower() == \"s\":\n attemptMovement(gameState, 0, -1)\n else if prompt.lower() == \"d\":\n attemptMovement(gameState, 1, 0)\n else\n print(\"That's not a valid input\")\n\ndef attemptMovement(gameState, dx, dy):\n tx = gameState.x + dx\n ty = gameState.y + dy\n if tx < 1 or tx > 3 or ty < 1 or ty > 3:\n stutter(\"You hit a wall\")\n sound.load(\"/home/leo/Documents/Python/Sounds/thud.mp3\")\n sound.play()\n else:\n gameState.x = tx\n gameState.y = ty\n</code></pre>\n\n<p>By splitting the logic into multiple functions, you can avoid repetition and also make the code clearer to read. This is just a starting point; you could also:</p>\n\n<ul>\n<li>Use a dynamic size for the play area rather than hard-coded 3.</li>\n<li>Put some of this logic inside GameState as a member function.</li>\n</ul>\n\n<p>There are other parts of the code that can be made into functions as well. For example:</p>\n\n<pre><code>def playSoundFor(sfx, seconds):\n sound.load(sfx)\n sound.play()\n time.sleep(seconds)\n sound.stop()\n</code></pre>\n\n<p>In terms of the data itself, there's only so far you can compress that, but the map images (r1-r9) could all be generated by a single function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:38:51.113",
"Id": "209930",
"ParentId": "209922",
"Score": "4"
}
},
{
"body": "<p>To add to @Errorsatz's comment at the bottom of his answer</p>\n\n<blockquote>\n <p>In terms of the data itself, there's only so far you can compress that, but the map images (r1-r9) could all be generated by a single function.</p>\n</blockquote>\n\n<p>Any time you find yourself hard coding repetitious, complicated things like with the variables <code>r1</code>-<code>r9</code>, you should take a step back and consider writing code to automate it for you. What if you want to change the size later, or add some other detail? Do you really want to have to edit every room?</p>\n\n<p>Here's some code that does just that. I chose to break it down quite far and opt for a verbose version, but I feel that will help readability and understanding. Don't worry, we'll walk through the code in detail after. </p>\n\n<pre><code>room_wall = \"|\"\nspot_template = \"[ ]\"\nposition_indicator = \"^\"\n\ndef room_template(width, height):\n row = [room_wall + spot_template * width + room_wall]\n\n return \"\\n\".join(row * height)\n\ndef generate_room(width, height, pos_x, pos_y):\n template = room_template(width, height)\n\n spot_width = len(spot_template)\n wall_width = len(room_wall)\n row_width = spot_width * width + wall_width * 2 + 1 # + 1 to account for newline\n replace_index = 1 + wall_width + pos_y * row_width + pos_x * spot_width\n\n return template[:replace_index] \\\n + position_indicator \\\n + template[replace_index + 1:] \n\ndef generate_rooms(room_width, room_height):\n return [generate_room(room_width, room_height, x, y)\n for x in range(room_width)\n for y in range(room_height - 1, -1, -1)]\n</code></pre>\n\n<p>And an example of its use:</p>\n\n<pre><code>>>> for r in generate_rooms(3, 3):\n print(r + \"\\n\")\n\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n|[^][ ][ ]|\n\n|[ ][ ][ ]|\n|[^][ ][ ]|\n|[ ][ ][ ]|\n\n|[^][ ][ ]|\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n|[ ][^][ ]|\n\n|[ ][ ][ ]|\n|[ ][^][ ]|\n|[ ][ ][ ]|\n\n|[ ][^][ ]|\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n|[ ][ ][^]|\n\n|[ ][ ][ ]|\n|[ ][ ][^]|\n|[ ][ ][ ]|\n\n|[ ][ ][^]|\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n</code></pre>\n\n<hr>\n\n<h1>So, how does it work?</h1>\n\n<pre><code>room_wall = \"|\"\nspot_template = \"[ ]\"\nposition_indicator = \"^\"\n</code></pre>\n\n<p>First, at the top I defined several variables holding the bare-bones of what's going to be generated. This makes it easier to change things later, and makes it clearer what the characters actually represent. <code>spot_template</code> represents the basic structure of an empty \"cell\" in a room. The <code>^</code> will be plugged in later when necessary.</p>\n\n<hr>\n\n<pre><code>def room_template(width, height):\n row = [room_wall + spot_template * width + room_wall]\n\n return \"\\n\".join(row * height)\n</code></pre>\n\n<p><code>room_template</code> returns a simple, empty-celled room. <code>row</code> ends up being, with dimensions of 3x3, <code>[\"|[ ][ ][ ]|\"]</code>; a string representing a row enclosed in a list. I put a list around it because later on I need <code>row * height</code> to multiply lists, not strings directly. I need each row separate so I can join them with a newline before it's all returned:</p>\n\n<pre><code>>>> room_template(3, 3)\n'|[ ][ ][ ]|\\n|[ ][ ][ ]|\\n|[ ][ ][ ]|'\n\n>>> print(room_template(3, 3))\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n</code></pre>\n\n<hr>\n\n<p><code>generate_room</code>'s math got a little messy unfortunately. There's a few nit-picky details that need to be taken into consideration though.</p>\n\n<p>Here's the idea of how it works: take the returned template room, figure out the index of the empty space character in the selected <code>\"[ ]\"</code> that needs to be replaced, then replace it with a <code>\"^\"</code>.</p>\n\n<pre><code>spot_width = len(spot_template)\nwall_width = len(room_wall)\nrow_width = spot_width * width + wall_width * 2 + 1 # + 1 to account for newline\nreplace_index = 1 + wall_width + pos_y * row_width + pos_x * spot_width\n</code></pre>\n\n<p>This whole chunk is figuring out the exact index in the template string that needs to be replaced. Basically, I just sat down with a pen and paper and figured the math out by manually finding the indices for a 3x3 room, and thinking out what math would lead to that. Then I expanded it to other dimensions, and fixed a couple bugs. I originally figured it out without the <code>\"|\"</code> walls for simplicity, then accounted for them after.</p>\n\n<p>Here are the major parts:</p>\n\n<pre><code>row_width = spot_width * width + wall_width * 2 + 1 # + 1 to account for newline\n</code></pre>\n\n<p>This is how many characters long each \"row\" of the string is. Each <code>\"[ ]\"</code> cell is 3 characters long, so the whole row is the length of <code>\"[ ]\"</code> * the width of the room + the length of <code>\"|\"</code> * 2. Then + 1 to account for the newline at the end of each row.</p>\n\n<pre><code>replace_index = 1 + wall_width + pos_y * row_width + pos_x * spot_width\n</code></pre>\n\n<p>This is based on an old equation that's useful in many scenarios. If you have a 2D list/matrix being represented by a normal, 1D list (like <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code> representing a 2D array of <code>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code>), and you wanted to figure out the index of the cell at position (1, 2), what's the equation? It's simply</p>\n\n<pre><code>i = row_width * y + x\ni = 3 * 2 + 1\ni = 7\n</code></pre>\n\n<p>The element at index 7 is <code>8</code>, which if this were a 2D array, would be the element at (1, 2).</p>\n\n<p>This is the basic idea here. If you squint a bit, you can see <code>row_width * y + x</code> in there. The + 1 is to account for the first <code>\"[\"</code>, and I have to + <code>wall_width</code> to account for the walls on each end.</p>\n\n<pre><code>return template[:replace_index] \\\n + position_indicator \\\n + template[replace_index + 1:]\n</code></pre>\n\n<p>This is just \"replacing\" the character at index <code>replace_index</code> of the <code>template</code> string. See <a href=\"https://stackoverflow.com/a/41752999/3000206\">@Willem's answer here</a> for an in-depth explanation of what's going on. It basically just cuts the string in two pieces at the calculated index, puts the <code>\"^\"</code> in there, then glues it all back together.</p>\n\n<pre><code>>>> generate_room(3, 3, 1, 2)\n'|[ ][ ][ ]|\\n|[ ][ ][ ]|\\n|[ ][^][ ]|'\n\n>>> print(generate_room(3, 3, 1, 2))\n|[ ][ ][ ]|\n|[ ][ ][ ]|\n|[ ][^][ ]|\n</code></pre>\n\n<hr>\n\n<p>Finally, <code>generate_rooms</code> goes through each x,y position, in the order you had before, and creates a room with an indicator at the given position.</p>\n\n<p>The whole thing is just a list comprehension split over a few lines.</p>\n\n<pre><code>for x in range(room_width)\nfor y in range(room_height - 1, -1, -1)\n</code></pre>\n\n<p>This generates each x,y position starting from the bottom left. It then passes the generated <code>x</code>,<code>y</code> values to <code>generate_room</code>, generates a room, and adds it to the list. The list is then returned. This function is basically a more succinct version of:</p>\n\n<pre><code>def generate_rooms_verbose(room_width, room_height):\n rooms = []\n\n for x in range(room_width):\n for y in range(room_height - 1, -1, -1):\n rooms.append(generate_room(room_width, room_height, x, y))\n\n return rooms\n</code></pre>\n\n<p>Which may make more sense.</p>\n\n<hr>\n\n<p>Hopefully this helps. This code certainly isn't very short, but it shows how this problem can be approached, and that it can be automated.</p>\n\n<p>Now, you can create rooms of any dimensions:</p>\n\n<pre><code>>>> print(generate_room(4, 10, 2, 7))\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][^][ ]|\n|[ ][ ][ ][ ]|\n|[ ][ ][ ][ ]|\n</code></pre>\n\n<p>Without ever needing to manually write each of the possible 40 rooms of that size.</p>\n\n<hr>\n\n<hr>\n\n<p>Looking back, I could/should have broken <code>generate_room</code> down further. The math calculating the index could go in its own function, and I could have also created a function to return a string with the character at a given <code>i</code> replaced with a <code>replacement</code> character. Something like:</p>\n\n<pre><code>def spot_index_in_template(template_width, x, y):\n spot_width = len(spot_template)\n wall_width = len(room_wall)\n row_width = spot_width * template_width + wall_width * 2 + 1\n\n return 1 + wall_width + y * row_width + x * spot_width\n\ndef replace_at_index(s, i, replacement):\n return s[:i] + replacement + s[i + 1:]\n\ndef generate_room(width, height, pos_x, pos_y):\n template = room_template(width, height)\n i = spot_index_in_template(width, pos_x, pos_y)\n\n return replace_at_index(template, i, position_indicator)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-28T13:22:30.287",
"Id": "414721",
"Score": "0",
"body": "This is very clever thank you for taking the time. May I ask how long you've been coding for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-28T14:59:31.560",
"Id": "414749",
"Score": "0",
"body": "@LeoGortz You're welcome. And about 5 - 10 years depending on what you consider \"coding\". I've been writing code daily for about 5 years now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T22:59:08.993",
"Id": "209941",
"ParentId": "209922",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:47:33.703",
"Id": "209922",
"Score": "5",
"Tags": [
"python",
"beginner",
"pygame",
"adventure-game"
],
"Title": "Simple text escape room game"
} | 209922 |
<p>I have a function that's doing this correctly, but I feel as though this can be done (possibly) with minimal code, with recursion, but I'm just wracking my brain. Basically I have JSON that gets decoded to an array. What I want to do is turn this:</p>
<blockquote>
<pre><code>{
"parentView": {
"childViews": [
{
"type": "container-fluid",
"childViews": [
{
"type": "row",
"childViews": [
{
"type": "slider"
},
{
"type": "slider"
}
]
}
]
}
]
}
}
</code></pre>
</blockquote>
<p>Into this:</p>
<blockquote>
<pre><code>{
"parentView": {
"childViews": [
{
"type": "controller",
"childViews": [
{
"type": "container-fluid",
"childViews": [
{
"type": "controller",
"childViews": [
{
"type": "row",
"childViews": [
{
"type": "controller",
"childViews": [
{
"type": "slider"
}
]
},
{
"type": "controller",
"childViews": [
{
"type": "slider"
}
]
}
]
}
]
}
]
}
]
}
]
}
}
</code></pre>
</blockquote>
<p>Here is the code I am using to make it work how I need. I am just looking for a cleaner method:</p>
<pre><code>function createControls($parentView)
{
$newArr = $parentView;
foreach ($parentView as $k => $v) {
$newArr[$k] = [
'type' => 'control',
'childViews' => $v
];
if ($v['childViews']) {
foreach ($v['childViews'] as $kk => $vv) {
$newArr[$k]['childViews']['childViews'] = [
'type' => 'control',
'childViews' => $vv
];
if ($vv['childViews']) {
foreach ($vv['childViews'] as $_k => $_v) {
$newArr[$k]['childViews']['childViews']['childViews']['childViews'][$_k] = [
'type' => 'control',
'childViews' => $_v
];
}
}
}
}
}
return $newArr;
}
$newArr = createControls($arr['parentView']['childViews']);
$arr['parentView']['childViews'] = $newArr;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T23:29:51.997",
"Id": "405781",
"Score": "0",
"body": "Welcome to Code Review. It seems that the question may greatly benefit from a more precise problem statement."
}
] | [
{
"body": "<p>You can try something like this, note that it is untested:</p>\n\n<pre><code><?php\nfunction createControls($parentView) {\n $newArr = $parentView;\n foreach ($parentView as $k => $v) {\n $newArr[$k] = ['type' => 'control'];\n if (isset($v['childViews'])) {\n $v = createControls($v['childViews']);\n }\n $newArr[$k]['childViews'] = $v;\n }\n return $newArr;\n}\n?>\n</code></pre>\n\n<p>This function uses reccursion to do the same as your code above. It takes one array of Key Value pairs and reassigns the values to wrap the old values into an array with the following format:</p>\n\n<pre><code>array ( 'type' => 'control', 'childViews' => $oldValue );\n</code></pre>\n\n<p>Basically, instead of nesting a new loop each time the depth of your input array changes like in your function above this function will just pass the old childValues back into itself and assign the result as the new childValues array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:07:20.040",
"Id": "405752",
"Score": "0",
"body": "Thanks for the reply. While I believe I tried something like this before just adding a bunch of foreach statements, everything that should have `control` gets wrapped with `control` but the contents get lost (`container-fluid`, `row`), and so the last items are the ones that still retain data (childViews type > control, subviews > slider). This is definitely close. I'll try to rework this, or find out why the data is not retaining in the parent items. (example output from the code above) https://codeshare.io/GbYNYA"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:22:03.543",
"Id": "405756",
"Score": "0",
"body": "Ha! I just added an answer, and yours was based on the same thing. Thanks again for your help Kevin! Much appreciated"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T18:37:03.000",
"Id": "209925",
"ParentId": "209924",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T18:31:36.207",
"Id": "209924",
"Score": "1",
"Tags": [
"php",
"array",
"recursion",
"json",
"wrapper"
],
"Title": "Wrapping certain elements in an array with an array with PHP"
} | 209924 |
<p>I'm working in a Tableau driven system, with large numbers of charts, I needed a way to reduce the strain of the initial load of our app. It's fairly simple, but wanted to ensure I accounted for every scenario, I don't generally utilize lazy loading.</p>
<p>Print isn't a priority.</p>
<p>jsfiddle: <a href="https://jsfiddle.net/darcher/nkeryf4w/" rel="nofollow noreferrer">Demo</a> (Tableau doesn't work within SO's <a href="https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/">snippets</a> because of the iframes)</p>
<p><strong>Relevant Javascript</strong></p>
<pre><code>const throttle = (fn, delay) => {
let canCall = true;
return (...args) => {
if (canCall) {
fn.apply(null, args);
canCall = false;
setTimeout(() => {
canCall = true;
}, delay);
}
};
};
const setAttributes = (el, options) =>
Object.keys(options).forEach(attr => el.setAttribute(attr, options[attr]));
const w = window;
const d = document;
const b = d.body;
const x = w.innerWidth || e.clientWidth || b.clientWidth;
const y = w.innerHeight || e.clientHeight || b.clientHeight;
/* unecessary, but to have same object format, e.g. readability */
const win = Object.create(null);
win.y = y;
const frame = d.querySelectorAll("iframe");
/** may be over doing it here... test results */
const preloadPath = () =>
frame.forEach(item => {
const source = item.getAttribute("data-src");
const preloadLink = d.createElement("link");
const head = d.getElementsByTagName("head")[0];
setAttributes(preloadLink, {
rel: "preload",
as: "document",
type: "text/html",
crossorigin: "anonymous",
href: source
});
head.insertBefore(preloadLink, head.firstChild);
});
const loadFrame = () =>
frame.forEach(item => {
/* only run if not src is present */
if (!item.src) {
const source = item.getAttribute("data-src"); // path
const parent = item.parentElement; // wrapper
const frameRect = parent.getBoundingClientRect(); // wrapper dimensions
if (
w.pageYOffset + win.y >= frameRect.y && // if frame top exceeds page bottom
frameRect.y + frameRect.height >= w.pageYOffset // if frame bottom exceeds page top
) {
item.src = source; // set path
item.removeAttribute("data-src"); // remove placeholder attr
}
}
});
/** load on docReady */
d.addEventListener("DOMContentLoaded", [preloadPath, loadFrame]);
/** throttle on scroll */
const t = throttle(loadFrame, 64);
w.addEventListener("scroll", t);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:30:48.990",
"Id": "406025",
"Score": "0",
"body": "What is the purpose of `preloadPath`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T15:05:03.747",
"Id": "407298",
"Score": "0",
"body": "I was attempting to leverage [preloading](https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content) although I don't believe it is of any benefit here, using javascript to inject into the DOM isn't early enough in the lifecycle of the page load... If it is beneficial, it's negligible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T15:55:03.980",
"Id": "407306",
"Score": "0",
"body": "If the purpose is to use `<link>` element is used to preload a resource, then `load` event of `<link>` should be used before `loadFrame()` is called. Presently `preloadPath` does not have direct relevance to the `<iframe>` elements, though can be utilized if `import` is used; see [Is there a way to know if a link/script is still pending or has it failed](https://stackoverflow.com/questions/39824927/); [How to querySelector an element in an html import from a document that imports it?](https://stackoverflow.com/a/46388003/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T16:28:50.870",
"Id": "407312",
"Score": "0",
"body": "That's actually a great point. I hadn't thought of that. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T20:05:08.330",
"Id": "407335",
"Score": "0",
"body": "I think there's a bug in `throttle`. If `t` is called twice in quick succession, `loadFrame` will only be called in response to the first call to `t`. What you probably wanted in this case was to call `loadFrame` again 64 milliseconds after the first time it was called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T21:36:25.367",
"Id": "407337",
"Score": "0",
"body": "Intention is to execute _at most_ once every _n_ milliseconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-01T22:33:34.407",
"Id": "407340",
"Score": "0",
"body": "@darcher I realise that, but you can still make sure it runs after every scroll event. On the first scroll event it should run the handler immediately. If the next scroll is within `n` milliseconds it should wait until the `n` milliseconds are up and then run the handler. If there are any more scroll events before it has run then they can be ignored, because the handler is going to run anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-02T05:12:08.227",
"Id": "407353",
"Score": "1",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-02T14:23:05.500",
"Id": "407384",
"Score": "0",
"body": "@DavidKnipe I see your point, isn't that more of a debounce?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-02T17:47:59.190",
"Id": "407412",
"Score": "0",
"body": "@darcher I don't know what the best name for it is. But the point is that if there are two scroll events less than 64 milliseconds apart (and no other scrolls), `loadFrame` will not be called after the second scroll, and the UI will remain in an inconsistent state. If you want to rename it as well then I'm not going to object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-03T15:37:17.020",
"Id": "407527",
"Score": "0",
"body": "I think `requestAnimationFrame()` may be a good option here, thoughts?"
}
] | [
{
"body": "<h2>General Feedback</h2>\n\n<p>The code in the jsFiddle Demo appears to function well (although it isn't the same as the code above- see the next section for an explanation). There is good usage of <code>const</code> for values that are not re-assigned and functional programming with arrow functions.</p>\n\n<h2>Flaw with event listener setup</h2>\n\n<p>It appears that the fiddle has different code than appears here, but nonetheless, the code above contains the following line:</p>\n\n<blockquote>\n<pre><code>d.addEventListener(\"DOMContentLoaded\", [preloadPath, loadFrame]);\n</code></pre>\n</blockquote>\n\n<p>The second argument appears to be an array. I haven't seen an array there used before and it doesn't appear to work. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters\" rel=\"nofollow noreferrer\">Parameters section of the MDN documentation for addEventListener</a> reads:</p>\n\n<blockquote>\n <p><strong><code>listener</code></strong><br>\n The object which receives a notification (an object that implements the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event\" rel=\"nofollow noreferrer\"><code>Event</code></a> interface) when an event of the specified type occurs. <strong>This must be an object implementing the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventListener\" rel=\"nofollow noreferrer\"><code>EventListener</code></a> interface, or a JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions\" rel=\"nofollow noreferrer\"><code>function</code></a></strong>. See <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback\" rel=\"nofollow noreferrer\">The event listener callback</a> for details on the callback itself.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>If you did need to have both functions run when that event occurs, you would either need to have a single callback function that calls both or call <code>addEventListener</code> once for each function. It appears that in the fiddle <code>preloadPath</code> has been removed...</p>\n\n<h2>Suggestions</h2>\n\n<h3>Variable naming</h3>\n\n<p>The variable name <code>frame</code> sounds singular, yet it returns a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NodeList\" rel=\"nofollow noreferrer\"><code>NodeList</code></a> which would typically contain multiple DOM elements. </p>\n\n<blockquote>\n<pre><code>const frame = d.querySelectorAll(\"iframe\");\n</code></pre>\n</blockquote>\n\n<p>Thus a more appropriate name would be <code>frames</code>. That way when statements like <code>frames.forEach()</code> is read, it implies that a function is invoked for each of the frames.</p>\n\n<h3>The <code>setAttributes()</code> function</h3>\n\n<p>Correct me if I am wrong but this function appears to do the same thing that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\"><code>Object.assign()</code></a>. I was able to replace calls to that function with calls to <code>Object.assign()</code> and still saw the attributes set as expected in Opera and Chrome.</p>\n\n<h3>Arrow functions with empty argument lists</h3>\n\n<p>You don't have to do this, but <code>_</code> could be used instead of empty parentheses for arrow functions with no named arguments. Refer to <a href=\"https://stackoverflow.com/q/41085189/1575353\">this SO post</a> and its answers for more context.</p>\n\n<h3>timeout in function returned by <code>throttle()</code></h3>\n\n<p>While it would only save a couple lines, the arrow function passed to <code>setTimeout()</code> in the function returned by <code>throttle()</code> could be simplified to remove the curly braces. While this would mean that <code>true</code> would be returned, it doesn't affect anything.</p>\n\n<pre><code>const throttle = (fn, delay) => {\n let canCall = true;\n return (...args) => {\n if (canCall) {\n fn.apply(null, args);\n canCall = false;\n setTimeout(_ => canCall = true, delay);\n }\n };\n};\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters</a>)</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T17:12:17.737",
"Id": "406131",
"Score": "0",
"body": "yeah actually in the version I'm using it has a `const readyInit = (() => {preloadPath();loadFrame();});` function I call on DOMReady. This was actually due to me showing a collage \"I wish we could\" and must have overlooked it when posting a copy+paste; good eye. I was not aware of the Lambda expression for empty ()! All valid and good points, thanks for your input! I'll update the OP to reflect changes when I get a moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:55:28.610",
"Id": "406152",
"Score": "0",
"body": "Cool; 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_](https://codereview.meta.stackexchange.com/a/1765/120114). You could post a follow up question with update code..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:13:04.640",
"Id": "210064",
"ParentId": "209929",
"Score": "1"
}
},
{
"body": "<p>I've updated the code based on the suggestions in comments and answers.</p>\n\n<p>shout out to <a href=\"https://codereview.stackexchange.com/users/120114/s%E1%B4%80%E1%B4%8D-on%E1%B4%87%E1%B4%8C%E1%B4%80\">Sᴀᴍ Onᴇᴌᴀ</a> for his suggestions in the accepted answer and <a href=\"https://codereview.stackexchange.com/users/34881/david-knipe\">David Knipe</a> for suggestions on the <code>throttle</code> function.</p>\n\n<pre><code>const w = window;\nconst d = document;\n\nlet timeout;\nconst throttle = (fn, ...args) => (\n timeout && w.cancelAnimationFrame(timeout),\n timeout = w.requestAnimationFrame(_ => fn(...args)));\n\nconst loadFrame = _ => \n d.querySelectorAll(\"iframe\").forEach(frame => {\n if (frame.src) return\n const frameRect = frame.parentElement.getBoundingClientRect();\n (w.pageYOffset + d.documentElement.clientHeight >= frameRect.y\n && frameRect.y + frameRect.height >= w.pageYOffset)\n && frame.setAttribute('src', frame.getAttribute(\"data-src\"))\n .removeAttribute(\"data-src\")});\n\nd.addEventListener(\"DOMContentLoaded\", loadFrame, false);\nw.addEventListener(\"scroll\", _ => throttle(loadFrame), false);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-03T19:34:55.180",
"Id": "210837",
"ParentId": "209929",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "210064",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T19:21:02.410",
"Id": "209929",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"event-handling",
"dom",
"lazy"
],
"Title": "Lazy-loading iframes as they scroll into view"
} | 209929 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.