body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have a fairly complex query which insert multiple rows into a table from multiple tables. Its works fine but I really don't want to use cursor as some blog says cursor took long time for execution (of course it depends). I hope I could find alternative way for minimize my execution time or cursor complexity. Here is my query: </p>
<pre><code>DECLARE @employeeid int;
DECLARE @joiningdate date;
DECLARE @quitdate date;
DECLARE @eodrefs int,@amounts decimal;
select @employeeid=HRMS_Employee.ID,@joiningdate=HRMS_Employee.Joining_Date,@quitdate=HRMS_Employee.QuitDate
from HRMS_Employee where HRMS_Employee.Present_Status=1 and ID=4
DECLARE @tabEodRecord table(eodref int,amount decimal)
insert INTO @tabEodRecord (eodref,amount)
select HRMS_EodRecord.Eod_RefFk,HRMS_EodRecord.ActualAmount from HRMS_EodRecord join HRMS_Employee on HRMS_EodRecord.EmployeeId=HRMS_Employee.ID
where HRMS_EodRecord.Status=1 and HRMS_EodRecord.EmployeeId=@employeeid
IF CURSOR_STATUS('global','PayrollInfoCursor')>=-1
BEGIN
DEALLOCATE PayrollInfoCursor
END
DECLARE PayrollInfoCursor CURSOR
FOR (select eodref,amount from @tabEodRecord)
OPEN PayrollInfoCursor;
FETCH NEXT FROM PayrollInfoCursor INTO @eodrefs,@amounts
WHILE @@FETCH_STATUS = 0
BEGIN
insert HRMS_PayrollInfo (PayrollFK,EmployeeIdFk,Eod_ReferenceFk,Amount,PaymentDate,[Status],AlertActive,Entry_By,Entry_Date,Update_By,Update_Date)
select 26,@employeeid,@eodrefs,@amounts,getdate(),1,1,1,getdate(),1,getdate()
FETCH NEXT FROM PayrollInfoCursor INTO @eodrefs,@amounts
END
CLOSE PayrollInfoCursor
DEALLOCATE PayrollInfoCursor
</code></pre>
<p>I hope there is something like this (however this won't work) because <strong>subquery returns multiple rows</strong> </p>
<pre><code>insert HRMS_PayrollInfo (PayrollFK,EmployeeIdFk,Eod_ReferenceFk,Amount,PaymentDate,[Status],AlertActive,Entry_By,Entry_Date,Update_By,Update_Date)
select 26,@employeeid,(select eodref from tabEodRecord),(select amountfrom tabEodRecord),getdate(),1,1,1,getdate(),1,getdate()
</code></pre>
| [] | [
{
"body": "<p>From what I can tell based on the code you've presented, you can reduce it down to the following...</p>\n\n<pre><code>DECLARE @employeeid INT;\n\nINSERT dbo.HRMS_PayrollInfo (PayrollFK, EmployeeIdFk, Eod_ReferenceFk, Amount, PaymentDate, Status, AlertActive, Entry_By, Entry_Date, Update_By, Update_Date)\nSELECT\n 26,\n @employeeid,\n er.Eod_RefFk,\n er.ActualAmount,\n GETDATE(),\n 1,\n 1,\n 1,\n GETDATE(),\n 1,\n GETDATE() \nFROM\n dbo.HRMS_EodRecord er\n --JOIN dbo.HRMS_Employee e\n -- ON er.EmployeeId = e.ID\nWHERE\n er.Status = 1\n AND er.EmployeeId = @employeeid;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T03:17:43.290",
"Id": "424841",
"Score": "1",
"body": "thanks. That's amazing. I didn't see actually how simple it is. thanks once again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:22:46.697",
"Id": "424922",
"Score": "0",
"body": "@Parvez - Not a problem. Sometimes it just takes a second set of eyes to see the problem from a different perspective."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T13:36:06.460",
"Id": "219869",
"ParentId": "219850",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219869",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T07:32:49.973",
"Id": "219850",
"Score": "1",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Insert multiple rows without using CURSOR SQL Server 2014"
} | 219850 |
<p>For lack of better things to do I went on coderbyte and did one of the simple challenges since I have not written code for a little while.</p>
<p>The problem was stated as following:</p>
<p><em>Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.</em> </p>
<p>Few notes to TL;DR the comments:</p>
<ul>
<li>I would have used const std::string& but function definition was given by CoderByte</li>
<li>string[string.length()] is guaranteed to return '\0' since C++11.</li>
<li>My code does not look for any terminating zeroes.</li>
</ul>
<p>I'm looking for more discussion regarding the structure, the approach to the problem and general look & feel.</p>
<p>This is my solution:</p>
<pre><code>// The function definition was given by CoderByte, I would have used
// const std::string& if it was up to me
string LongestWord(string sen) {
// code goes here
int start = -1;
int bstart = -1;
int blen = 0;
// lequal since std string is compatible with c strings, it will have \0 at
// the end, saving a special case after the loop.
for (int i = 0; i <= sen.length(); ++i)
{
if (start == -1 && isalpha(sen[i]))
{
start = i;
}
else if (!isalpha(sen[i]))
{
if (start >= 0 && i - start > blen)
{
blen = i - start;
bstart = start;
start = -1;
}
}
}
return sen.substr(bstart, blen);
}
</code></pre>
<p>I ran the test cases and all was well, so I figured I'd check the top solution on the website:</p>
<pre><code>string LongestWord(string sen) {
// code goes here
string sen2 = "";
for(int i=0;i<sen.length();i++)
{
if(isalpha(sen[i])||sen[i]==' '||'0'<=sen[i]&&sen[i]<='9')
{
sen2.append(sen.substr(i,1));
}
}
char* sench = (char*)sen2.c_str();
string longest = "";
int longestLen = 0;
for(const char* pch=strtok(sench," ");pch;pch=strtok(NULL," "))
{
if(strlen(pch)>longestLen)
{
longest = pch;
longestLen=strlen(pch);
}
}
return longest;
}
</code></pre>
<p>From my point of view my solution is less complicated, has fewer moving parts, is easier to digest and at first glance I expect it to perform better due to less looping(although I have not tested this).</p>
<p>I feel like I am missing something, this happens with some frequency where I notice people use more complex solutions and I wonder if I'm basically writing tutorial code or something. Is this just me doubting myself or have I missed something?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T09:53:02.917",
"Id": "424703",
"Score": "0",
"body": "`std::string` isn't compatible with c strings the way you seem to think it is. `std::string` can contain several null characters. See: https://akrzemi1.wordpress.com/2014/03/20/strings-length/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T10:44:54.483",
"Id": "424713",
"Score": "0",
"body": "Thanks for the comment, I seem to have made some assumptions. It seems assuming that std::string stores a '\\0' at the end of the string is the only one that impacts the solution though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T11:01:35.180",
"Id": "424723",
"Score": "0",
"body": "While I did not read the standard, some research points towards std::string now being guaranteed to be null terminated and contiguous in memory since C++11."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T11:21:36.523",
"Id": "424738",
"Score": "0",
"body": "Some research was referring to browsing a bunch of stack overflow questions since I could not come up with anything more definite, see the comment on your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T12:38:52.667",
"Id": "424749",
"Score": "0",
"body": "@Peter: `std::string` is probably always null terminated under the hood but the ending null character doesn't have the same meaning as in a C string: it's more convenient with the `c_str()` interface, but doesn't prevent a `std::string` to contain intermediary null characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T12:41:12.780",
"Id": "424750",
"Score": "0",
"body": "My code never checks for '\\0'. It just relies on the character in memory just after the length of the string not being a letter.\n\nI noticed you edited away the part about that causing my code to end prematurely, which in turn causes my comment to make no sense :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T18:10:34.917",
"Id": "424951",
"Score": "0",
"body": "Well the two solutions have slightly different behavior. Your version will split words on punctuation while the top one does not. Your version does not consider numbers to be words (bit strange in computer science terms as words are usually referred to as white space separated tokens) the top solution does. Neither solution handles white space (just space). In terms of speed both are going to be about the same until you start judging on huge amounts of text. But your has a slight advantage by only doing a single pass. In terms of readability. I prefer the top solution (more correct)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T07:25:34.857",
"Id": "425007",
"Score": "0",
"body": "Examples and test cases on CoderByte were literally like this:\n\"!!fun& time\" should return time, it did not talk about tokens but words in the literal sense, although that information was not clear from my question so I can understand your comment, it would be trivial to modify my code to accept anything else separated by whitespace. Not sure I understand what you mean when you say that my version does not handle whitespace, it will literally discard anything except a series of letters as a word, I don't check specifically for ' ', '\\n' or '\\t' works just fine."
}
] | [
{
"body": "<p>The presented solution is quite C-like with <code>strtok</code> and such. For your solution:</p>\n\n<ul>\n<li><p>Your function takes the input by-value, but this seems unnecessary and wasteful. Prefer to take it by const-reference. </p></li>\n<li><p>The idea behind your solution looks OK, but you should notice that <code>std::string</code> can contain multiple null characters and is not null-terminated. In general, I would prefer to solve the problem by leveraging the standard library more. For example, we could write:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <algorithm>\n#include <cctype>\n\nstd::string LongestWord(const std::string& str)\n{\n std::string longest;\n\n for (auto first = str.cbegin(); first != str.cend(); )\n {\n auto w_end = std::adjacent_find(first, str.cend(),\n [](char a, char b)\n {\n return std::isalpha(static_cast<unsigned char>(a)) !=\n std::isalpha(static_cast<unsigned char>(b));\n });\n\n if (w_end != str.cend())\n {\n ++w_end;\n }\n\n if(std::isalpha(static_cast<unsigned char>(*first)) && \n std::distance(first, w_end) > longest.size())\n {\n longest = std::string(first, w_end);\n }\n\n first = w_end;\n }\n\n return longest;\n}\n\nint main()\n{\n std::string sen = \"Some ,long sentence!!!!! with punctuation \\t, and. all that!\";\n\n const std::string w = LongestWord(sen);\n std::cout << w << \"\\n\";\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T12:37:47.043",
"Id": "424748",
"Score": "0",
"body": "@papagaga are you refering to this:\nFor the first (non-const) version, the behavior is undefined if this character is modified to any value other than CharT() .\n\nfrom the cppreference? as far as I can tell that would only be UB if I tried to modify it but maybe I am reading it wrong? \n\nEdit: I see what you mean now, it's split up in two, one for pre C++11 where non const is undefined, and one for post C++11 where it is defined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T12:43:23.387",
"Id": "424751",
"Score": "1",
"body": "@Peter: I believe you're right, it's defined after C++11 provided you don't modify the last + 1 character... C++ in all its glory ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T12:44:14.937",
"Id": "424752",
"Score": "0",
"body": "Yep. It's nearly impossible to be 100% sure with this god forsaken language."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T09:55:52.793",
"Id": "219859",
"ParentId": "219852",
"Score": "3"
}
},
{
"body": "<p>Your solution is certainly neater than the other one. Programming challenge websites often contain horrible code.</p>\n\n<p>There's a few things to improve though:</p>\n\n<hr>\n\n<p>Use the container index type for indexing into a container. This ensures the index values cover the necessary range.</p>\n\n<p>In this case, we should use <code>std::size_t</code> instead of <code>int</code> for indexing the <code>std::string</code> (or <code>std::string::size_type</code> if we're being paranoid). This would mean rethinking the algorithm slightly (perhaps we need a <code>std::optional<std::size_t></code>).</p>\n\n<p>Note that for storing the difference between indices (i.e. word length) we should use <code>std::ptrdiff_t</code> (or <code>std::string::difference_type</code>).</p>\n\n<hr>\n\n<p>In C++ it's more idiomatic to use iterators, instead of indices. This makes it easier to genericize functions (e.g. finding the longest run satisfying an arbitrary precondition on an arbitrary sequence).</p>\n\n<hr>\n\n<p>I'd be inclined to implement this with an outer loop to iterate each word, and an inner loop to find the start and end points.</p>\n\n<p>It's more verbose, but perhaps a bit easier to follow:</p>\n\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <string>\n\nstd::string get_longest_word(std::string const& input)\n{\n auto const is_in_word = [] (unsigned char c) { return std::isalpha(c); };\n\n auto max_word_length = std::string::difference_type{ 0 };\n auto max_word_start = input.end();\n auto max_word_end = input.end();\n\n for (auto i = input.begin(); i != input.end(); )\n {\n auto word_start = std::find_if(i, input.end(), is_in_word);\n\n if (word_start == input.end())\n break;\n\n auto word_end = std::find_if_not(word_start, input.end(), is_in_word);\n\n auto const word_length = std::distance(word_start, word_end);\n\n if (word_length > max_word_length)\n {\n max_word_length = word_length;\n max_word_start = word_start;\n max_word_end = word_end;\n }\n\n i = word_end;\n }\n\n return std::string(max_word_start, max_word_end);\n}\n</code></pre>\n\n<p>Which is on the way to becoming:</p>\n\n<pre><code>template<InputItT, PredicateT>\nstd::pair<InputItT, InputItT> find_longest_run(InputItT begin, InputItT end, PredicateT predicate);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T20:19:38.867",
"Id": "424822",
"Score": "0",
"body": "Thanks for your answer. The points about using size_t and ptrdiff_t would be be more robust, instead of setting start to -1 you could simply have a bool to track if we are current inside a word or not.\nI'm still not quite sold on making the solution more generic though. If I wanted to allow customization of what constitues a word I could add a parameter for a function pointer/functor/interface etc that could optionally replace isalpha. (Should add that the problem is quite specific with no requirements about being approach in a generic way)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T20:25:55.497",
"Id": "424823",
"Score": "0",
"body": "I see the point about iterators being more idiomatic for modern C++, though I'm not sold on having a for loop that increments the iterator by variable amount based on the word size, it definitely seems more complex to me.\n\nthe std::find_if and friends mean that I mentally need to parse and understand that each of those will iterate over some part of the string and provide me with new iterators, as opposed to just keeping track of one iterator variable(i). Sorry for being argumentative, it's the only way for me to really take in feedback without being a yes-man. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T17:38:37.910",
"Id": "219882",
"ParentId": "219852",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T08:26:43.550",
"Id": "219852",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Longest word simple online challenge"
} | 219852 |
<p>I have created a binary to decimal calculator that needs to follow this spec:</p>
<ul>
<li>Arrays may not be used contain the binary digits entered by the user</li>
<li>Determining the decimal equivalent of a particular binary digit in the sequence must be calculated using a single mathematical function, for example the natural logarithm. It's up to you to figure out which function to use.</li>
<li>User can enter up to 8 binary digits in one input field</li>
<li>User must be notified if anything other than a 0 or 1 was entered</li>
<li>User views the results in a single output field containing the decimal (base 10) equivalent of the binary number that was entered</li>
<li>User can enter a variable number of binary digits</li>
</ul>
<p>My code is:</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>binaryForm = document.getElementById('formComplete');
numberInput = document.getElementById('numberInput');
numberInputButton = document.getElementById('updateNumberBtn');
binaryInput = document.getElementById('binaryInput');
decimalValue = document.getElementById('decimalOutput');
numberInputButton.addEventListener('click', function () {
var numberInputValue = numberInput.value;
binaryInput.setAttribute('maxLength', numberInputValue);
});
binaryInput.addEventListener('keydown', function (e) {
if (e.keyCode !== 48 && e.keyCode !== 49 && e.keyCode !== 13 && e.keyCode !== 8) {
e.preventDefault();
alert('Only 0 and 1 is allowed');
}
});
binaryForm.addEventListener('submit', function (e) {
e.preventDefault();
if (binaryInput.value == 0) {
alert('Empty');
} else {
var userInput = binaryInput.value;
var total = 0;
for (var i = 0; i < userInput.length; i++) {
var binaryDigit = parseInt(userInput[i]);
var calcInput = (total * 2) + binaryDigit;
total = calcInput;
}
decimalValue.innerHTML = total;
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background: #2e2e2e;
color: #fff;
font-family: Heebo, sans-serif;
}
h1,
h2,
h3,
h4 {
font-weight: 900;
}
input {
display: block;
margin: 0 auto;
width: 100%;
max-width: 300px;
height: 60px;
}
.form-body {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
#numberInput,
#binaryInput {
margin-bottom: 1rem;
border: 0.125rem solid rgba(255,255,255,0.25);
background: rgba(255,255,255,0.05);
color: #fff;
font-size: 2rem;
text-align: center;
font-family: Heebo, sans-serif;
font-weight: 300;
}
#updateNumberBtn,
#convertBtn {
margin-bottom: 1rem;
border: 0.125rem solid rgba(0,128,0,0.75);
color: #fff;
background: rgba(0,128,0,0.75);
text-transform: uppercase;
}
#updateNumberBtn:hover,
#convertBtn:hover {
background: rgba(0,128,0,0.25);
cursor: pointer;
}
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-body">
<h1>Binary to Decimal Calculator</h1>
<label for="numberInput">Set max number of bits (Max 12 - Default 8)</label>
<input id="numberInput" type="number" value="8" min="1" max="12">
<input id="updateNumberBtn" type="button" value="Set Number of Bits">
<form action="" id="formComplete">
<label for="binaryInput">Enter a binary value</label>
<input id="binaryInput" type="text" size="12" maxlength="8">
<input id="convertBtn" type="submit" value="Convert to Decimal">
</form>
<h2>Decimal Value: <span id="decimalOutput"></span></h2>
</div></code></pre>
</div>
</div>
</p>
<p>Are there areas that I could improve performance-wise or by making the app easier to operate, such as the part where I am targeting the keys that the user can input.</p>
| [] | [
{
"body": "<ul>\n<li><p>You should use the directive <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\"><code>"use strict"</code></a> that will place the JavaScript context into strict mode. This will throw errors for some common bad practices.</p>\n</li>\n<li><p>Always declare variables as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\"><code>var</code></a>, or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a>. If you are in strict mode you will get an error if you don't.</p>\n</li>\n<li><p>Don't use alerts or prompts as there is no way to know if they are actually displayed (clients can turn them off) and they are very annoying.</p>\n</li>\n<li><p>The key event properties <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode\" rel=\"nofollow noreferrer\"><code>KeyboardEvent.keyCode</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/charCode\" rel=\"nofollow noreferrer\"><code>KeyboardEvent.charCode</code></a> have been depreciated and you should not use them. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\" rel=\"nofollow noreferrer\"><code>KeyboardEvent.code</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\" rel=\"nofollow noreferrer\"><code>KeyboardEvent.key</code></a> instead</p>\n</li>\n<li><p>Rather than filter the input via the keybpoard events, listen to the input's <code>keyup</code> and <code>change</code> events, removing bad characters automatically. Use a CSS rule to unhide a warning and a JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\" rel=\"nofollow noreferrer\">setTimeout</a> to hide it again</p>\n<p>Filtering keyboard events means you need to check many keys that are valid (left, right, backspace, delete, etc...) which is just unneeded complexity.</p>\n</li>\n<li><p>Don't wait for the user to click "Convert to Decimal", display the output automatically. This makes it a lot friendlier to use.</p>\n</li>\n<li><p>JavaScript can convert binary strings to decimal for you using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\"><code>parseInt</code></a>. The second argument is the radix (AKA base) of the number that is being parsed.</p>\n</li>\n<li><p>If you are just setting text (no HTML) use the elements <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent\" rel=\"nofollow noreferrer\">textContent</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML\" rel=\"nofollow noreferrer\">innerHTML</a></p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite is following the points you have set-out in your question. I have not implemented how your code differs from these points.</p>\n<p>The rewrite uses</p>\n<ul>\n<li>a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\">RegExp</a> to test and filter the input.</li>\n<li>a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">ternary</a> expression to create the decimal value as <code>parseInt</code> will return <code>NaN</code> for empty strings. The ternary checks if the string is empty evaluating to <code>""</code> or if there is a number the ternary evaluates to the decimal value.</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus\" rel=\"nofollow noreferrer\">HTMLInputElement.focus</a> (inherited from <code>HTMLElement</code>) to focus the input element when loaded.</li>\n</ul>\n<p>I have modified the HTML and CSS to fit the snippet window a little better.</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\";\nconst binaryInput = document.getElementById(\"binaryInput\");\nconst decimalOutput = document.getElementById(\"decimalOutput\");\nconst inputWarning = document.getElementById(\"inputWarning\");\nbinaryInput.addEventListener('change', update);\nbinaryInput.addEventListener('keyup', update);\nbinaryInput.focus();\n\nconst WARNING_TIME = 2000; // in ms\nvar warningTimer;\nfunction hidWarning() {\n inputWarning.classList.add(\"hideWarning\");\n}\nfunction showWarning() {\n clearTimeout(warningTimer);\n warningTimer = setTimeout(hidWarning, WARNING_TIME);\n inputWarning.classList.remove(\"hideWarning\");\n}\nfunction update() {\n var value = binaryInput.value;\n if (/[^01]/g.test(value)){\n binaryInput.value = value = value.replace(/[^01]/g, \"\");\n showWarning();\n }\n decimalOutput.textContent = value === \"\" ? \"\" : parseInt(value, 2);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n background: #2e2e2e;\n color: #fff;\n font-family: Heebo, sans-serif;\n}\n.form-body {\n display: flex;\n flex-direction: column;\n text-align: center;\n}\ninput {\n margin: 0 auto;\n width: 100%;\n max-width: 300px;\n border: 0.125rem solid rgba(255,255,255,0.25);\n background: rgba(255,255,255,0.05);\n color: #fff;\n font-size: 2rem;\n text-align: center;\n font-weight: 300; \n}\n\n.inputWarning { color: #F88 }\n.hideWarning { display: none }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"form-body\">\n <h2>Binary to Decimal Calculator</h2>\n <label for=\"binaryInput\">Enter a binary value<span id=\"inputWarning\" class=\"inputWarning hideWarning\"> [Only valid digits 0 and 1 permitted]</span></label>\n <input id=\"binaryInput\" type=\"text\" size=\"8\" maxlength=\"8\">\n <h3>Decimal Value: <span id=\"decimalOutput\"></span></h3>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T22:37:52.790",
"Id": "424830",
"Score": "0",
"body": "Thank you, that was the type of in-depth feedback I was hoping for. It's a much smoother operation. I think the only area I am not too familiar with is the RegExp but this will come with time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T08:13:54.067",
"Id": "424853",
"Score": "0",
"body": "When you give an element an id, it already exists as a property on the window object. You don't need to use getElementById. Since you are using the same name you can just remove those 3 lines entirely. By the way, your opening and closing tag doesn't match for the headings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:28:33.990",
"Id": "424910",
"Score": "0",
"body": "@Kruga If I don't add a detailed explanation regarding direct referencing I get down-voted for using them eg https://codereview.stackexchange.com/a/184295/120556 I volunteer answers and time is not always available to provide a defense of direct referencing as in the following https://codereview.stackexchange.com/a/217497/120556"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T13:54:16.330",
"Id": "219870",
"ParentId": "219853",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219870",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T08:32:11.403",
"Id": "219853",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Binary to Decimal Conversion App"
} | 219853 |
<p>I have created a program that lets you play the fifteen puzzle game. You have to get the blocks into ascending order by moving them into the one open space. I would like some feedback on the code and how I made it. This works best in full screen mode.</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>"use strict";
class Block {
constructor(x, y, w, h, value) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.value = value;
}
draw() {
if (this.value) {
let padding = 5;
ctx.strokeStyle = "#000";
ctx.font = (this.w / 4).toString() + "px Georgia";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#7d4b1488";
ctx.fillRect(this.x + padding, this.y + padding, this.w - padding, this.h - padding);
ctx.strokeRect(this.x + padding, this.y + padding, this.w - padding, this.h - padding);
ctx.fillStyle = "#000";
ctx.fillText(this.value.toString(), this.x + this.w / 2, this.y + this.h / 2, width * 0.75);
}
}
collidePoint(x, y) {
return (
x > this.x &&
x < this.x + this.w &&
y > this.y &&
y < this.y + this.h
);
}
sendTo(position) {
moving++;
let pos = {
x: position.x,
y: position.y,
}
let vel = {
x: (this.x - pos.x) / 10,
y: (this.y - pos.y) / 10,
}
let self = this;
let n = 0;
let movement = () => {
drawAll();
self.x -= vel.x;
self.y -= vel.y;
if (n >= 10) {
self.x = pos.x;
self.y = pos.y;
moving--;
}
else {
setTimeout(movement, 15);
n++;
}
};
setTimeout(movement, 15);
}
}
function shuffle(array) {
for (let i = 0; i < array.length; ++i) {
let newI = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[newI];
array[newI] = temp;
}
}
function isValidNeighbor(ind1, ind2) {
let pos1 = toNested(ind1);
let pos2 = toNested(ind2);
let dist1 = Math.abs(pos1[0] - pos2[0]);
let dist2 = Math.abs(pos1[1] - pos2[1]);
if (!dist1 || !dist2) {
if (dist1 === 1 || dist2 === 1) {
return dist1 !== dist2;
}
}
return false;
}
function toNested(index) {
return [ index % boardSize, Math.floor(index / boardSize) ];
}
function findZero() {
for (let i = 0; i < board.length; ++i) {
if (board[i].value === 0) {
return i;
}
}
}
function win() {
if (!moving) {
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "#000";
ctx.font = "50px Georgia";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(`You won in ${moves} ${moves === 1 ? "move" : "moves"}!`, width / 2, height / 2);
setTimeout(() => {
location.reload();
}, 2500);
}
else {
setTimeout(win, 150);
}
}
function drawAll() {
ctx.clearRect(0, 0, width, height);
board.forEach(block => {
block.draw();
});
}
function update() {
drawAll();
if (checkWin()) {
setTimeout(() => {
canvas.removeEventListener("click", handleClick);
setTimeout(win, 1000);
}, 200);
}
document.getElementById("moves").innerHTML = "Moves: " + moves.toString();
}
function checkWin() {
let noZ = board.slice(0);
noZ.splice(findZero(), 1);
for (let i = 1; i < noZ.length; ++i) {
if (noZ[i].value < noZ[i - 1].value) {
return false;
}
}
return true;
}
const canvas = document.getElementById("display");
const ctx = canvas.getContext("2d");
const width = canvas.width;
const height = canvas.height;
let boardSize;
let board;
let moves;
let moving;
function init() {
moving = 0;
boardSize = parseInt(document.getElementById("size").value);
if (boardSize < 2 || boardSize > 5 || isNaN(boardSize)) {
boardSize = 4;
}
board = Array.from(Array(boardSize ** 2).keys());
moves = 0;
shuffle(board);
for (let i = 0; i < board.length; ++i) {
let pos = toNested(i);
let w = width / boardSize;
let h = height / boardSize;
board[i] = new Block(pos[0] * w, pos[1] * h, w, h, board[i]);
}
update();
}
function handleClick(e) {
if (!moving) {
let rect = canvas.getBoundingClientRect();
for (let i = 0; i < board.length; ++i) {
if (board[i].collidePoint(e.clientX - rect.x, e.clientY - rect.y)) {
let zIndex = findZero();
if (isValidNeighbor(i, zIndex)) {
moves++;
let tempPos = {
x: board[i].x,
y: board[i].y,
};
board[i].sendTo(board[zIndex]);
board[zIndex].sendTo(tempPos);
let temp = board[i];
board[i] = board[zIndex];
board[zIndex] = temp;
}
break;
}
}
update();
}
}
canvas.addEventListener("click", handleClick);
document.getElementById("reset").onclick = init;
init();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
height: 100%;
display: grid;
}
body {
margin: auto;
background-color: #fac4af;
font-family: Georgia;
}
#board {
display: inline-block;
background-image: url("https://15-puzzle-game--joyalmathew.repl.co/board.jpeg");
padding: 10px;
box-shadow: 10px 20px #9b857a;
border: 1px solid black;
border-radius: 15px;
}
#display {
margin-left: 0px;
float: right;
}
#menu {
display: grid;
font-size: 15pt;
float: left;
width: 500px;
height: 500px;
margin-right: 0px;
box-sizing: border-box;
}
#menu p {
margin-top: 1px;
margin-bottom: 1px;
}
#menu input, #menu button {
font-family: Georgia;
}
#content {
margin: auto;
width: 450px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>15 Puzzle Game</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="board">
<canvas id="display" width="500" height="500"></canvas>
<div id="menu">
<div id="content">
<p id="moves">Moves: </p><br><br>
<p>Try getting the blocks into ascending order: left to right, top to bottom.</p>
<p>Click any block next to the space to swap them.</p>
<br>
Size: <input id="size" type="number" min="2" max="5" value="4">
<button id="reset">Reset</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T11:16:35.960",
"Id": "513334",
"Score": "0",
"body": "Amazing job! Very fun game to play! Thank you for sharing!"
}
] | [
{
"body": "<h1>Foreword</h1>\n<p>Your code is quite decent. However, I did make a general outline of how I would probably implement a <code>Board</code> to improve readability. Don't feel the need to take my suggestion. The major changes I made to the code is CSS and HTML restructuring. Additionally, I made modifications to accommodate different window sizes better. The updated code is at the bottom. I know that the topic of resizing can be difficult, so I wrote up the example.</p>\n<p>Major JavaScript changes are not implemented (although some minor are) but are outlined inside the <strong>JavaScript Structure Changes</strong> section.</p>\n<h1>Scaling problem</h1>\n<p>Your code seems to scale oddly at different dimensions. I fixed that by assigning <code>canvas.width</code> to <code>Math.min(window.innerWidth - 40, 500)</code> to accomodate for smaller windows. I also changed where you set the width/height of the <code>#menu</code> to <code>#board</code> becuase it looked better. I also changed it to <code>max-width</code> to accommodate smaller game boards better. It didn't make much sense to set a <code>max-height</code> as that is relative (depending on the size of <code>#menu</code>).</p>\n<h1>CSS Structure changes</h1>\n<p>I removed <code>#content</code> it seemed erroneous and just completely removed <code>margin:auto</code> except for in <code>body</code>.</p>\n<p>To increase DRYness I moved all <code>font-family: Georgia</code> to one selector.</p>\n<pre><code>#menu input, #menu button, body {\n font-family: Georgia;\n}\n</code></pre>\n<p>I added a spacer between menu and the game because it looked better (<code>maring-top</code>) I removed <code>display:grid</code> for <code>#menu</code> because when I removed <code>#content</code> it did not perform properly.</p>\n<h1>JavaScript Structure Changes</h1>\n<p>I liked most of your JavaScript; however, I find that allowing on-the-fly dimension changes to be important when programming a 2d game like this. So, I added a <code>window.addEventListener</code> to your code and had to make some minor changes to your class.</p>\n<p>This is more of a band-aid solution, however. Optimally, the <code>Block</code> class's x and y should have very little to do with drawing. <code>Block.draw</code> would simply store how it should be drawn based on some values given (like x, y, w, h). Then <code>Board.draw</code> would loop through <code>Block</code>s and invoke <code>Block.draw</code>. <code>Board</code> would manage location information.</p>\n<p>More of a style thing, but I prefer:</p>\n<pre><code>let pos = toNested(i),\n w = width / boardSize,\n h = height / boardSize;\n</code></pre>\n<p>over having lots of let's pile up in my code:</p>\n<pre><code>let pos = toNested(i);\nlet w = width / boardSize;\nlet h = height / boardSize;\n</code></pre>\n<p>Some people prefer to use <code>let</code>, that's fine. <code>var</code> can be used where it does not matter when changes occur after the control block is over. <code>let</code> saves the head ache so I understand the choice.</p>\n<p>Board is implemented as an array. You could probably benefit a little from turning it into a class. From there, instead of:</p>\n<pre><code>let temp = board[i];\nboard[i] = board[zIndex];\nboard[zIndex] = temp;\n</code></pre>\n<p>You could invoke something like <code>board.swap</code>. This change would improve readability in <code>handleClick</code> and <code>shuffle</code>, as you are creating clearly defined functions: one for each purpose. You could also add easy functions like <code>moveUp</code> or <code>moveDown</code>... etc.</p>\n<p>It would be preferred to have a <code>Board.collision</code> that returns first collision with a block (there should only be one...). It would prevent <code>handleClick</code> from having to perform both collision detection and board swapping and movement checks.</p>\n<p>I would prefer to use a 2D array within the <code>Board</code> class instead of <code>toNested</code>, it would make code more readable. I liked that you decided to just make that a function. However, it isn't as great as a simple 2d array.</p>\n<p>It would probably also be easier to store the location of the empty square. I liked your decision to have be a <code>0</code> tile. Very clever way to work with an array. But it may be simpler to leave it as a <code>null</code> inside a 2d array in <code>Board</code>.</p>\n<p>When swapping, it would be simpler to use <code>Board.draw</code> and then swapping them inside of the 2d array, just my opinion. Then having <code>Board.draw</code> set up how where to draw each tile.</p>\n<p>Having a <code>Board</code> class would also help you encapsulate a lot of the erroneous draw functions scattered in global namespace. I typically make a <code>Game</code> class which is responsible for invoking appropriate draw functions, but in a game this small, I think you could incorporate it inside of <code>Board</code>.</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\nclass Block {\n constructor(value) {\n this.value = value;\n }\n \n setDrawSettings(x, y , w, h) {\n this.x = x;\n this.y = y;\n this.w = w;\n this.h = h;\n }\n\n draw() {\n if (this.value) {\n let padding = 5;\n ctx.strokeStyle = \"#000\";\n ctx.font = (this.w / 4).toString() + \"px Georgia\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\";\n ctx.fillStyle = \"#7d4b1488\";\n ctx.fillRect(this.x + padding, this.y + padding, this.w - padding, this.h - padding);\n ctx.strokeRect(this.x + padding, this.y + padding, this.w - padding, this.h - padding);\n ctx.fillStyle = \"#000\";\n ctx.fillText(this.value.toString(), this.x + this.w / 2, this.y + this.h / 2, width * 0.75);\n }\n }\n\n collidePoint(x, y) {\n return (\n x > this.x &&\n x < this.x + this.w &&\n y > this.y &&\n y < this.y + this.h\n );\n }\n\n sendTo(position) {\n moving++;\n let pos = {\n x: position.x,\n y: position.y,\n }\n let vel = {\n x: (this.x - pos.x) / 10,\n y: (this.y - pos.y) / 10,\n }\n let self = this;\n let n = 0;\n let movement = () => {\n drawAll();\n self.x -= vel.x;\n self.y -= vel.y;\n if (n >= 10) {\n self.x = pos.x;\n self.y = pos.y;\n moving--;\n }\n else {\n setTimeout(movement, 15);\n n++;\n }\n };\n setTimeout(movement, 15);\n }\n}\n\nfunction shuffle(array) {\n for (let i = 0; i < array.length; ++i) {\n let newI = Math.floor(Math.random() * (i + 1));\n let temp = array[i];\n array[i] = array[newI];\n array[newI] = temp;\n }\n}\n\nfunction isValidNeighbor(ind1, ind2) {\n let pos1 = toNested(ind1);\n let pos2 = toNested(ind2);\n let dist1 = Math.abs(pos1[0] - pos2[0]);\n let dist2 = Math.abs(pos1[1] - pos2[1]);\n if (!dist1 || !dist2) {\n if (dist1 === 1 || dist2 === 1) {\n return dist1 !== dist2;\n }\n }\n return false;\n}\n\nfunction toNested(index) {\n return [ index % boardSize, Math.floor(index / boardSize) ];\n}\n\nfunction findZero() {\n for (let i = 0; i < board.length; ++i) {\n if (board[i].value === 0) {\n return i;\n }\n }\n}\n\nfunction win() {\n if (!moving) {\n ctx.clearRect(0, 0, width, height);\n ctx.fillStyle = \"#000\";\n ctx.font = \"50px Georgia\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\";\n ctx.fillText(`You won in ${moves} ${moves === 1 ? \"move\" : \"moves\"}!`, width / 2, height / 2);\n setTimeout(() => {\n location.reload();\n }, 2500);\n }\n else {\n setTimeout(win, 150);\n }\n}\n\nfunction drawAll() {\n ctx.clearRect(0, 0, width, height);\n board.forEach(block => {\n block.draw();\n });\n}\n\nfunction update() {\n drawAll();\n if (checkWin()) {\n setTimeout(() => {\n canvas.removeEventListener(\"click\", handleClick);\n setTimeout(win, 1000);\n }, 200);\n }\n document.getElementById(\"moves\").innerHTML = \"Moves: \" + moves.toString();\n}\n\nfunction checkWin() {\n let noZ = board.slice(0);\n noZ.splice(findZero(), 1);\n for (let i = 1; i < noZ.length; ++i) {\n if (noZ[i].value < noZ[i - 1].value) {\n return false;\n }\n }\n return true;\n}\n\nconst canvas = document.getElementById(\"display\");\nconst ctx = canvas.getContext(\"2d\");\nlet width,\n height,\n boardSize,\n board,\n moves,\n moving;\n\n//new\nfunction setDimensions() {\n canvas.width = Math.min(window.innerWidth - 40, 500);\n canvas.height = Math.min(window.innerHeight - 20, 500);\n width = canvas.width;\n height = canvas.height;\n}\nsetDimensions();\n\nwindow.addEventListener(\"resize\", function () {\n setDimensions();\n let w = width / boardSize,\n h = height / boardSize;\n setUpBoard(board);\n update();\n});\n\nfunction setUpBoard(board) {\n for (let i = 0; i < board.length; ++i) {\n let pos = toNested(i),\n w = width / boardSize,\n h = height / boardSize;\n board[i].setDrawSettings(pos[0] * w, pos[1] * h, w, h);\n }\n}\n\nfunction init() {\n moving = 0;\n boardSize = parseInt(document.getElementById(\"size\").value);\n if (boardSize < 2 || boardSize > 5 || isNaN(boardSize)) {\n boardSize = 4;\n }\n board = Array.from(Array(boardSize ** 2).keys());\n moves = 0;\n shuffle(board);\n for (let i = 0; i < board.length; i++) {\n board[i] = new Block(board[i]);\n }\n setUpBoard(board);\n update();\n}\n\nfunction handleClick(e) {\n if (!moving) {\n let rect = canvas.getBoundingClientRect();\n for (let i = 0; i < board.length; ++i) {\n if (board[i].collidePoint(e.clientX - rect.x, e.clientY - rect.y)) {\n let zIndex = findZero();\n if (isValidNeighbor(i, zIndex)) {\n moves++;\n let tempPos = {\n x: board[i].x,\n y: board[i].y,\n };\n board[i].sendTo(board[zIndex]);\n board[zIndex].sendTo(tempPos);\n \n let temp = board[i];\n board[i] = board[zIndex];\n board[zIndex] = temp;\n }\n break;\n }\n }\n update();\n }\n}\n\ncanvas.addEventListener(\"click\", handleClick);\n\ndocument.getElementById(\"reset\").onclick = init;\ninit();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n height: 100%;\n display: grid;\n}\n\nbody {\n background-color: #fac4af;\n margin: auto;\n}\n\n#menu input, #menu button, body {\n font-family: Georgia;\n}\n\n#board {\n display: inline-block;\n background-image: url(\"https://15-puzzle-game--joyalmathew.repl.co/board.jpeg\");\n padding: 10px;\n box-shadow: 10px 20px #9b857a;\n border: 1px solid black;\n border-radius: 15px;\n max-width: 500px;\n}\n\n#display {\n margin-left: 0px;\n float: right;\n}\n\n#menu {\n font-size: 15pt;\n float: left;\n margin-right: 0px;\n box-sizing: border-box;\n margin-top:10px;\n}\n\n#menu p {\n margin-top: 1px;\n margin-bottom: 1px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>15 Puzzle Game</title>\n <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" />\n </head>\n <body>\n <div id=\"board\">\n <canvas id=\"display\" width=\"500\" height=\"500\"></canvas>\n <div id=\"menu\">\n <p id=\"moves\">Moves: </p><br><br>\n <p>Try getting the blocks into ascending order: left to right, top to bottom.</p>\n <p>Click any block next to the space to swap them.</p>\n <br>\n Size: <input id=\"size\" type=\"number\" min=\"2\" max=\"5\" value=\"4\">\n <button id=\"reset\">Reset</button>\n </div>\n </div>\n <script src=\"script.js\"></script>\n </body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T18:27:19.783",
"Id": "219884",
"ParentId": "219866",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219884",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T13:10:53.837",
"Id": "219866",
"Score": "7",
"Tags": [
"javascript",
"game",
"canvas",
"sliding-tile-puzzle"
],
"Title": "15 Puzzle Game JavaScript"
} | 219866 |
<p>I've just published a small library implementing the <a href="https://en.wikipedia.org/wiki/Blind_signature" rel="nofollow noreferrer">RSA Blind Signature</a> process. </p>
<h2><a href="https://github.com/ShapeOfMatter/RSA-Blind-Signature" rel="nofollow noreferrer">Here's the GitHub repo!</a></h2>
<p>I needed something portable, and easy enough to use that I could ask <em>other people</em> to incorporate it into their work. Nothing like that seemed to be available, so I put it together using the Crypto++ library, some example code on their wiki, and some advice from other websites. </p>
<p>The whole thing is ~1000 lines of code, half of which is the parser for PEM-formatted keys (which is lifted from a pre-existing Crypto++ extension).</p>
<p>I've already had someone go over it (briefly) for style, and I'm certainly open to feedback about usability, but the important question at this point is </p>
<h3><strong>Would using this library as directed provide the guarantees expected of a blind signature protocol?</strong></h3>
<p>In short, we need the same behavior/guarantees we'd need form a normal hash-and-sign protocol, <em>plus</em> "unlinkability". This <a href="https://security.stackexchange.com/a/109840/191509">prior question/answer</a> explains the idea well, and there's some discussion of the math we're relying on <a href="https://crypto.stackexchange.com/a/42249/63950">here</a>.</p>
<p>I'm really hoping that people will like the library and use it, but if there are problems with it then the sooner we can identify them the better!</p>
<h2>Code Files:</h2>
<p><a href="https://github.com/ShapeOfMatter/RSA-Blind-Signature/tree/e94a504fbb5afcf2dc689dc43e59a24b095432b8" rel="nofollow noreferrer">Here's the head commit when I posted this question</a>, and from which the below is copied.</p>
<h3>makefile</h3>
<pre><code>CXX=g++
CXXFLAGS=-I. -Lcryptopp810 -lcryptopp -static
OUTDIR=bin/
PREFIX=$(OUTDIR)blsig_
INCLUDES=includes.h common_functions.h inner_functions.h pem-rd.h
all: $(PREFIX)get_client_secret
all: $(PREFIX)get_blinded_hash
all: $(PREFIX)get_blind_signature
all: $(PREFIX)get_unblinded_signature
all: $(PREFIX)verify_unblinded_signature
all: $(OUTDIR)test
$(PREFIX)%: %.cxx $(INCLUDES)
$(CXX) $< $(CXXFLAGS) -o $@
$(OUTDIR)test: test.cxx $(INCLUDES)
$(CXX) $< $(CXXFLAGS) -g -o $@
clean:
rm -f $(PREFIX)*
rm $(OUTDIR)test
.PHONY: clean all
</code></pre>
<h3>includes.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef BLSIG_INCLUDES_INCLUDED
# define BLSIG_INCLUDES_INCLUDED
# ifndef DEBUG
# define DEBUG 0
# endif
# include <iostream>
# include <fstream>
# include <regex>
# include <stdexcept>
// Use "" based includes for the cryptopp library because it's perfectly
// legitimate to install it to the local directory.
# include "cryptopp810/base64.h"
# include "cryptopp810/cryptlib.h"
# include "cryptopp810/files.h"
# include "cryptopp810/integer.h"
# include "cryptopp810/nbtheory.h"
# include "cryptopp810/osrng.h"
# include "cryptopp810/rsa.h"
# include "cryptopp810/sha.h"
# include "pem-rd.h"
# include "common_functions.h"
# include "inner_functions.h"
#endif
</code></pre>
<h3>common_functions.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef BLSIG_COMMON_H_INCLUDED
# define BLSIG_COMMON_H_INCLUDED
# include "includes.h"
using namespace CryptoPP;
static const std::regex PEM_Key_Regex_Public(
"-----BEGIN (?:RSA )?PUBLIC KEY-----[\\r\\n]+([^-]*)[\\r\\n]+-----END (?:RSA )?PUBLIC KEY-----");
static const std::regex PEM_Key_Regex_Private(
"-----BEGIN (?:RSA )?PRIVATE KEY-----[\\r\\n]+([^-]*)[\\r\\n]+-----END (?:RSA )?PRIVATE KEY-----");
/* Generates the SHA512 hash of an arbitrary string.
*/
Integer GenerateHash(const std::string &message)
{
SHA512 hash;
SecByteBlock buff;
SecByteBlock orig((const byte*)message.c_str(), message.size());
buff.resize(SHA512::DIGESTSIZE);
hash.CalculateTruncatedDigest(buff, buff.size(), orig, orig.size());
Integer hashed_message(buff.data(), buff.size());
#if DEBUG
std::cout << "Message: " << message << std::endl;
std::cout << "Hash: " << std::hex << hashed_message << std::dec << std::endl;
#endif
return hashed_message;
}
/* Loads an RSA Public Key from the specified file.
*/
RSA::PublicKey ReadPEMPublicKey(std::string file_name)
{
RSA::PublicKey public_key;
FileSource public_key_file(file_name.c_str(), true);
PEM_Load(public_key_file, public_key);
return public_key;
}
/* Loads an RSA Private Key from the specified file.
* The key must not be password protected.
*/
RSA::PrivateKey ReadPEMPrivateKey(std::string file_name)
{
RSA::PrivateKey private_key;
FileSource private_key_file(file_name.c_str(), true);
PEM_Load(private_key_file, private_key);
return private_key;
}
#endif
</code></pre>
<h3>inner_functions.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef BLSIG_INNER_H_INCLUDED
# define BLSIG_INNER_H_INCLUDED
# include "includes.h"
using namespace CryptoPP;
/* Generates a single-use secret value for blinding a message before it is sent
* to the signer.
* The public key is needed as a parameter because the space of valid secrets
* depends on the details of the key.
*/
Integer GenerateClientSecret(const RSA::PublicKey &public_key, AutoSeededRandomPool &rng_source)
{
const Integer &n = public_key.GetModulus();
Integer client_secret;
do
{
client_secret.Randomize(rng_source, Integer::One(), n - Integer::One());
} while (!RelativelyPrime(client_secret, n));
#if DEBUG
std::cout << "Random Client Secret: " << std::hex << client_secret << std::dec << std::endl;
#endif
return client_secret;
}
/* Generates a blinded version of the message value, to be sent to the signer.
*/
Integer MessageBlinding(const Integer &hashed_message, const RSA::PublicKey &public_key, const Integer &client_secret)
{
const Integer &n = public_key.GetModulus();
const Integer &e = public_key.GetPublicExponent();
Integer b = a_exp_b_mod_c(client_secret, e, n);
Integer hidden_message = a_times_b_mod_c(hashed_message, b, n);
#if DEBUG
std::cout << "Blinding factor: " << std::hex << b << std::dec << std::endl;
std::cout << "Blinded hashed message: " << std::hex << hidden_message << std::dec << std::endl;
#endif
return hidden_message;
}
/* Retrieves the completed signature from a blinded signature.
*/
Integer SignatureUnblinding(const Integer &blinded_signature, const RSA::PublicKey &public_key, const Integer &client_secret)
{
const Integer &n = public_key.GetModulus();
const Integer &inverse_secret = client_secret.InverseMod(n);
Integer signed_unblinded = a_times_b_mod_c(blinded_signature, inverse_secret, n);
#if DEBUG
std::cout << "Signed Unblinded: " << std::hex << signed_unblinded << std::dec << std::endl;
#endif
return signed_unblinded;
}
/* Blindly signs the provided hash.
* The returned value is not quite a complete signature; it must be unblinded
* by the original requestor using the one-time client secret.
*/
Integer SignBlindedMessage(const Integer &blinded_hash, const RSA::PrivateKey &private_key, AutoSeededRandomPool &rng_source)
{
Integer signed_message = private_key.CalculateInverse(rng_source, blinded_hash);
#if DEBUG
std::cout << "Signed Message: " << std::hex << signed_message << std::dec << std::endl;
#endif
return signed_message;
}
/* Prior to unblinding a signature, checks if the signature will be valid.
* **It's unclear if this contributes anything of value to the algorithm or
* this library. We include it for now for completeness.**
*/
bool PreverifySignature(const Integer &signed_blinded_hash, const Integer &blinded_hash, const RSA::PublicKey &public_key)
{
bool valid = public_key.ApplyFunction(signed_blinded_hash) == blinded_hash;
#if DEBUG
std::cout << "The blind message was" << (valid ? " " : " NOT ") << "properly signed." << std::endl;
#endif
return valid;
}
/* Checks that a completed signature is a valid signature of the message hash.
*/
bool VerifySignature(const Integer &unblinded_signature, const Integer &hashed_message, const RSA::PublicKey &public_key)
{
Integer signature_payload = public_key.ApplyFunction(unblinded_signature);
bool valid = hashed_message == signature_payload;
#if DEBUG
std::cout << "The signature contained message hash: " << std::hex << signature_payload << std::dec << std::endl;
std::cout << "The signature is " << (valid ? "valid" : "INVALID") << "." << std::endl;
#endif
return valid;
}
#endif
</code></pre>
<h3>get_client_secret.cxx</h3>
<pre class="lang-cpp prettyprint-override"><code>#include "includes.h"
using namespace CryptoPP;
static AutoSeededRandomPool rng_source;
#define DOCUMENTATION "Generates a single-use secret for blinding a message."
#define USEAGE "blsig_get_client_secret public_key.pem"
#define ARGUMENT_COUNT 1
static RSA::PublicKey public_key;
int main(int argc, char *argv[])
{
if(ARGUMENT_COUNT != --argc){
std::cerr << "Incorrect useage of " << argv[0]
<< ". Expected " << ARGUMENT_COUNT << " arguments; given " << argc << "." << std::endl
<< "Useage: \n\t" << USEAGE << std::endl
<< DOCUMENTATION << std::endl;
return EXIT_FAILURE;
}
try{
public_key = ReadPEMPublicKey(argv[1]);
}
catch(std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
Integer client_secret = GenerateClientSecret(public_key, rng_source);
std::cout << std::hex << client_secret << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
<h3>get_blinded_hash.cxx</h3>
<pre class="lang-cpp prettyprint-override"><code>#include "includes.h"
using namespace CryptoPP;
#define DOCUMENTATION "Hashes the message and then blinds the hash so it can be sent to the signer."
#define USEAGE "blsig_get_blinded_hash message client_secret public_key.pem"
#define ARGUMENT_COUNT 3
static std::string message;
static Integer client_secret;
static RSA::PublicKey public_key;
int main(int argc, char *argv[])
{
if(ARGUMENT_COUNT != --argc){
std::cerr << "Incorrect useage of " << argv[0]
<< ". Expected " << ARGUMENT_COUNT << " arguments; given " << argc << "." << std::endl
<< "Useage: \n\t" << USEAGE << std::endl
<< DOCUMENTATION << std::endl;
return EXIT_FAILURE;
}
try{
message = argv[1];
client_secret = Integer(argv[2]);
public_key = ReadPEMPublicKey(argv[3]);
}
catch(std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
Integer hashed_message = GenerateHash(message);
Integer hidden_message = MessageBlinding(hashed_message, public_key, client_secret);
std::cout << std::hex << hidden_message << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
<h3>get_blind_signature.cxx</h3>
<pre class="lang-cpp prettyprint-override"><code>#include "includes.h"
using namespace CryptoPP;
static AutoSeededRandomPool rng_source;
#define DOCUMENTATION "Generates a "pre-signature" (or hashed signature or whatever you want to call it) without any knowledge of the message, the message-hash, or the client secret."
#define USEAGE "blsig_get_blind_signature blinded_hash private_key.pem"
#define ARGUMENT_COUNT 2
static Integer blinded_hash;
static RSA::PrivateKey private_key;
int main(int argc, char *argv[])
{
if(ARGUMENT_COUNT != --argc){
std::cerr << "Incorrect useage of " << argv[0]
<< ". Expected " << ARGUMENT_COUNT << " arguments; given " << argc << "." << std::endl
<< "Useage: \n\t" << USEAGE << std::endl
<< DOCUMENTATION << std::endl;
return EXIT_FAILURE;
}
try{
blinded_hash = Integer(argv[1]);
private_key = ReadPEMPrivateKey(argv[2]);
}
catch(std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
Integer signed_message = SignBlindedMessage(blinded_hash, private_key, rng_source);
std::cout << std::hex << signed_message << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
<h3>get_unblinded_signature.cxx</h3>
<pre class="lang-cpp prettyprint-override"><code>#include "includes.h"
using namespace CryptoPP;
#define DOCUMENTATION "Un-blinds the pre-signature using the same client_secret used to generate the blinded-hash. Also verifies the signature. The client secret should not be stored once it has served its purpose once."
#define USEAGE "blsig_get_unblinded_signature blind_signature blinded_hash client_secret public_key.pem"
#define ARGUMENT_COUNT 4
static Integer blinded_signature;
static Integer blinded_hash;
static Integer client_secret;
static RSA::PublicKey public_key;
int main(int argc, char *argv[])
{
if(ARGUMENT_COUNT != --argc){
std::cerr << "Incorrect useage of " << argv[0]
<< ". Expected " << ARGUMENT_COUNT << " arguments; given " << argc << "." << std::endl
<< "Useage: \n\t" << USEAGE << std::endl
<< DOCUMENTATION << std::endl;
return EXIT_FAILURE;
}
try{
blinded_signature = Integer(argv[1]);
blinded_hash = Integer(argv[2]);
client_secret = Integer(argv[3]);
public_key = ReadPEMPublicKey(argv[4]);
}
catch(std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
if(PreverifySignature(blinded_signature, blinded_hash, public_key))
{
Integer unblinded_signature = SignatureUnblinding(blinded_signature, public_key, client_secret);
std::cout << std::hex << unblinded_signature << std::endl;
return EXIT_SUCCESS;
}
else
{
std::cerr << "There is a problem with the provided signature: it does not match the blinded hash." << std::endl;
return EXIT_FAILURE;
}
}
</code></pre>
<h3>verify_unblinded_signature.cxx</h3>
<pre class="lang-cpp prettyprint-override"><code>#include "includes.h"
using namespace CryptoPP;
#define DOCUMENTATION "Confirms that a provided signature is a valid signature, by the corresponding private-key, of the provided message. Prints true for success."
#define USEAGE "blsig_verify_unlinded_signature unblinded_signature message public_key.pem"
#define ARGUMENT_COUNT 3
static Integer unblinded_signature;
static std::string message;
static RSA::PublicKey public_key;
int main(int argc, char *argv[])
{
if(ARGUMENT_COUNT != --argc){
std::cerr << "Incorrect useage of " << argv[0]
<< ". Expected " << ARGUMENT_COUNT << " arguments; given " << argc << "." << std::endl
<< "Useage: \n\t" << USEAGE << std::endl
<< DOCUMENTATION << std::endl;
return EXIT_FAILURE;
}
try{
unblinded_signature = Integer(argv[1]);
message = argv[2];
public_key = ReadPEMPublicKey(argv[3]);
}
catch(std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
Integer hashed_message = GenerateHash(message);
if(VerifySignature(unblinded_signature, hashed_message, public_key))
{
std::cout << "true" << std::endl;
return EXIT_SUCCESS;
}
else
{
std::cerr << "That is not a valid signature for the provided message." << std::endl;
return EXIT_FAILURE;
}
}
</code></pre>
<h3>test.cxx</h3>
<pre class="lang-cpp prettyprint-override"><code>#define DEBUG 1
#include "includes.h"
using namespace CryptoPP;
static AutoSeededRandomPool rng_source;
/* Generates a key pair using system calls to openssl.
* Then loads the keys and uses them to walk through the steps of hashing, blind-signing, and verifying the signature.
*/
int main(int argc, char *argv[])
{
if(0 == std::system(NULL)
|| 0 != std::system("which openssl")
|| 0 != std::system("which rm")){
std::cerr << "The test script will not work on this system." << std::endl;
exit(EXIT_FAILURE);
}
std::system("openssl genrsa -out scratch/._blsig_test_rsa_key_priv.pem 2048");
std::system("openssl rsa -in scratch/._blsig_test_rsa_key_priv.pem -out scratch/._blsig_test_rsa_key_pub.pem -pubout");
RSA::PublicKey public_key = ReadPEMPublicKey("scratch/._blsig_test_rsa_key_pub.pem");
RSA::PrivateKey private_key = ReadPEMPrivateKey("scratch/._blsig_test_rsa_key_priv.pem");
// Alice create a blind message
Integer client_secret = GenerateClientSecret(public_key, rng_source);
std::string message = "Hello world! How are you doing to day? It's a pretty nice day if i do say so myself1.";
Integer original_hash = GenerateHash(message);
Integer blinded = MessageBlinding(original_hash, public_key, client_secret);
// Send blinded message for signing
Integer signed_blinded = SignBlindedMessage(blinded, private_key, rng_source);
// Alice will remove blinding factor
Integer signed_unblinded = SignatureUnblinding(signed_blinded, public_key, client_secret);
// Eve verification stage
Integer message_hash = GenerateHash(message);
Integer received_hash = public_key.ApplyFunction(signed_unblinded);
std::cout << "Signature payload: " << received_hash << std::endl;
if (!VerifySignature(signed_unblinded, message_hash, public_key))
{
std::cout << "Verification failed" << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "Signature Verified" << std::endl;
// return success
return EXIT_SUCCESS;
}
</code></pre>
<h3>pem-rd.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef BLSIG_PEM_H_INCLUDED
# define BLSIG_PEM_H_INCLUDED
# include "includes.h"
// pem-rd.cpp - PEM read routines. Written and placed in the public domain by Jeffrey Walton
// Copyright assigned to the Crypto++ project.
//
// Modified for selective standalone use by Mako Bates
//
// Crypto++ Library is copyrighted as a compilation and (as of version 5.6.2) licensed
// under the Boost Software License 1.0, while the individual files in the compilation
// are all public domain.
///////////////////////////////////////////////////////////////////////////
// For documentation on the PEM read and write routines, see
// http://www.cryptopp.com/wiki/PEM_Pack
///////////////////////////////////////////////////////////////////////////
#include <string>
#include <algorithm>
#include <cctype>
#include "cryptopp810/secblock.h"
#include "cryptopp810/gfpcrypt.h"
#include "cryptopp810/camellia.h"
#include "cryptopp810/smartptr.h"
#include "cryptopp810/filters.h"
#include "cryptopp810/queue.h"
#include "cryptopp810/modes.h"
#include "cryptopp810/asn.h"
#include "cryptopp810/aes.h"
#include "cryptopp810/idea.h"
#include "cryptopp810/des.h"
#include "cryptopp810/hex.h"
NAMESPACE_BEGIN(CryptoPP)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//I want this to be just one file, so I'm pulling some stuff in from the original headers.
enum PEM_Type { PEM_PUBLIC_KEY = 1, PEM_PRIVATE_KEY,
PEM_RSA_PUBLIC_KEY, PEM_RSA_PRIVATE_KEY, PEM_RSA_ENC_PRIVATE_KEY,
PEM_DSA_PUBLIC_KEY, PEM_DSA_PRIVATE_KEY, PEM_DSA_ENC_PRIVATE_KEY,
PEM_EC_PUBLIC_KEY, PEM_ECDSA_PUBLIC_KEY, PEM_EC_PRIVATE_KEY, PEM_EC_ENC_PRIVATE_KEY,
PEM_EC_PARAMETERS, PEM_DH_PARAMETERS, PEM_DSA_PARAMETERS,
PEM_X509_CERTIFICATE, PEM_REQ_CERTIFICATE, PEM_CERTIFICATE,
PEM_UNSUPPORTED = 0xFFFFFFFF };
static inline SecByteBlock StringToSecByteBlock(const std::string& str)
{
return SecByteBlock(reinterpret_cast<const byte*>(str.data()), str.size());
}
static inline SecByteBlock StringToSecByteBlock(const char* str)
{
return SecByteBlock(reinterpret_cast<const byte*>(str), strlen(str));
}
static inline const byte* BYTE_PTR(const char* cstr)
{
return reinterpret_cast<const byte*>(cstr);
}
static inline byte* BYTE_PTR(char* cstr)
{
return reinterpret_cast<byte*>(cstr);
}
static const SecByteBlock CR(BYTE_PTR("\r"), 1);
static const SecByteBlock LF(BYTE_PTR("\n"), 1);
static const SecByteBlock CRLF(BYTE_PTR("\r\n"), 2);
static const unsigned int RFC1421_LINE_BREAK = 64;
static const std::string RFC1421_EOL = "\r\n";
static const SecByteBlock SBB_PEM_BEGIN(BYTE_PTR("-----BEGIN"), 10);
static const SecByteBlock SBB_PEM_TAIL(BYTE_PTR("-----"), 5);
static const SecByteBlock SBB_PEM_END(BYTE_PTR("-----END"), 8);
static const size_t PEM_INVALID = static_cast<size_t>(-1);
static const std::string LBL_PUBLIC_BEGIN("-----BEGIN PUBLIC KEY-----");
static const std::string LBL_PUBLIC_END("-----END PUBLIC KEY-----");
static const std::string LBL_PRIVATE_BEGIN("-----BEGIN PRIVATE KEY-----");
static const std::string LBL_PRIVATE_END("-----END PRIVATE KEY-----");
static const std::string LBL_RSA_PUBLIC_BEGIN("-----BEGIN RSA PUBLIC KEY-----");
static const std::string LBL_RSA_PUBLIC_END("-----END RSA PUBLIC KEY-----");
static const std::string LBL_RSA_PRIVATE_BEGIN("-----BEGIN RSA PRIVATE KEY-----");
static const std::string LBL_RSA_PRIVATE_END("-----END RSA PRIVATE KEY-----");
static const std::string LBL_PROC_TYPE_ENC("Proc-Type: 4,ENCRYPTED");
static const SecByteBlock SBB_PUBLIC_BEGIN(StringToSecByteBlock(LBL_PUBLIC_BEGIN));
static const SecByteBlock SBB_PUBLIC_END(StringToSecByteBlock(LBL_PUBLIC_END));
static const SecByteBlock SBB_PRIVATE_BEGIN(StringToSecByteBlock(LBL_PRIVATE_BEGIN));
static const SecByteBlock SBB_PRIVATE_END(StringToSecByteBlock(LBL_PRIVATE_END));
static const SecByteBlock SBB_RSA_PUBLIC_BEGIN(StringToSecByteBlock(LBL_RSA_PUBLIC_BEGIN));
static const SecByteBlock SBB_RSA_PUBLIC_END(StringToSecByteBlock(LBL_RSA_PUBLIC_END));
static const SecByteBlock SBB_RSA_PRIVATE_BEGIN(StringToSecByteBlock(LBL_RSA_PRIVATE_BEGIN));
static const SecByteBlock SBB_RSA_PRIVATE_END(StringToSecByteBlock(LBL_RSA_PRIVATE_END));
static const SecByteBlock SBB_PROC_TYPE_ENC(StringToSecByteBlock(LBL_PROC_TYPE_ENC));
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
static size_t PEM_ReadLine(BufferedTransformation& source, SecByteBlock& line, SecByteBlock& ending);
static PEM_Type PEM_GetType(const BufferedTransformation& bt);
static PEM_Type PEM_GetType(const SecByteBlock& sb);
static void PEM_StripEncapsulatedBoundary(BufferedTransformation& bt, const SecByteBlock& pre, const SecByteBlock& post);
static void PEM_StripEncapsulatedBoundary(SecByteBlock& sb, const SecByteBlock& pre, const SecByteBlock& post);
static inline SecByteBlock::const_iterator Search(const SecByteBlock& source, const SecByteBlock& target);
static void PEM_LoadPublicKey(BufferedTransformation& bt, X509PublicKey& key, bool subjectInfo = false);
static void PEM_LoadPrivateKey(BufferedTransformation& src, PKCS8PrivateKey& key, bool subjectInfo);
static void PEM_NextObject(BufferedTransformation& src, BufferedTransformation& dest);
static void PEM_Base64Decode(BufferedTransformation& source, BufferedTransformation& dest);
static void PEM_WriteLine(BufferedTransformation& bt, const std::string& line);
static void PEM_WriteLine(BufferedTransformation& bt, const SecByteBlock& line);
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void PEM_Load(BufferedTransformation& bt, RSA::PublicKey& rsa)
{
ByteQueue obj;
PEM_NextObject(bt, obj);
PEM_Type type = PEM_GetType(obj);
if (type == PEM_PUBLIC_KEY)
PEM_StripEncapsulatedBoundary(obj, SBB_PUBLIC_BEGIN, SBB_PUBLIC_END);
else if(type == PEM_RSA_PUBLIC_KEY)
PEM_StripEncapsulatedBoundary(obj, SBB_RSA_PUBLIC_BEGIN, SBB_RSA_PUBLIC_END);
else
throw InvalidDataFormat("PEM_Load: not a RSA public key");
ByteQueue temp;
PEM_Base64Decode(obj, temp);
PEM_LoadPublicKey(temp, rsa, type == PEM_PUBLIC_KEY);
}
void PEM_Load(BufferedTransformation& bt, RSA::PrivateKey& rsa)
{
ByteQueue obj;
PEM_NextObject(bt, obj);
PEM_Type type = PEM_GetType(obj);
if(type == PEM_PRIVATE_KEY)
PEM_StripEncapsulatedBoundary(obj, SBB_PRIVATE_BEGIN, SBB_PRIVATE_END);
else if(type == PEM_RSA_PRIVATE_KEY)
PEM_StripEncapsulatedBoundary(obj, SBB_RSA_PRIVATE_BEGIN, SBB_RSA_PRIVATE_END);
else if(type == PEM_RSA_ENC_PRIVATE_KEY)
throw InvalidArgument("PEM_Load: RSA private key is encrypted");
else
throw InvalidDataFormat("PEM_Load: not a RSA private key");
ByteQueue temp;
PEM_Base64Decode(obj, temp);
PEM_LoadPrivateKey(temp, rsa, type == PEM_PRIVATE_KEY);
}
void PEM_LoadPublicKey(BufferedTransformation& src, X509PublicKey& key, bool subjectInfo)
{
X509PublicKey& pk = dynamic_cast<X509PublicKey&>(key);
if (subjectInfo)
pk.Load(src);
else
pk.BERDecode(src);
#if !defined(NO_OS_DEPENDENCE)
AutoSeededRandomPool prng;
if(!pk.Validate(prng, 2))
throw Exception(Exception::OTHER_ERROR, "PEM_LoadPublicKey: key validation failed");
#endif
}
void PEM_LoadPrivateKey(BufferedTransformation& src, PKCS8PrivateKey& key, bool subjectInfo)
{
if (subjectInfo)
key.Load(src);
else
key.BERDecodePrivateKey(src, 0, src.MaxRetrievable());
#if !defined(NO_OS_DEPENDENCE)
AutoSeededRandomPool prng;
if(!key.Validate(prng, 2))
throw Exception(Exception::OTHER_ERROR, "PEM_LoadPrivateKey: key validation failed");
#endif
}
PEM_Type PEM_GetType(const BufferedTransformation& bt)
{
const size_t size = bt.MaxRetrievable();
SecByteBlock sb(size);
bt.Peek(sb.data(), sb.size());
return PEM_GetType(sb);
}
PEM_Type PEM_GetType(const SecByteBlock& sb)
{
SecByteBlock::const_iterator it;
// Uses an OID to identify the public key type
it = Search(sb, SBB_PUBLIC_BEGIN);
if (it != sb.end())
return PEM_PUBLIC_KEY;
// Uses an OID to identify the private key type
it = Search(sb, SBB_PRIVATE_BEGIN);
if (it != sb.end())
return PEM_PRIVATE_KEY;
// RSA key types
it = Search(sb, SBB_RSA_PUBLIC_BEGIN);
if(it != sb.end())
return PEM_RSA_PUBLIC_KEY;
it = Search(sb, SBB_RSA_PRIVATE_BEGIN);
if(it != sb.end())
{
it = Search(sb, SBB_PROC_TYPE_ENC);
if(it != sb.end())
return PEM_RSA_ENC_PRIVATE_KEY;
return PEM_RSA_PRIVATE_KEY;
}
return PEM_UNSUPPORTED;
}
void PEM_StripEncapsulatedBoundary(BufferedTransformation& bt, const SecByteBlock& pre, const SecByteBlock& post)
{
ByteQueue temp;
SecByteBlock::const_iterator it;
int n = 1, prePos = -1, postPos = -1;
while(bt.AnyRetrievable() && n++)
{
SecByteBlock line, unused;
PEM_ReadLine(bt, line, unused);
// The write associated with an empty line must to occur. Otherwise, we loose the CR or LF
// in an ecrypted private key between the control fields and the encapsulated text.
//if(line.empty())
// continue;
it = Search(line, pre);
if(it != line.end())
{
prePos = n;
continue;
}
it = Search(line, post);
if(it != line.end())
{
postPos = n;
continue;
}
PEM_WriteLine(temp, line);
}
if(prePos == -1)
{
std::string msg = "PEM_StripEncapsulatedBoundary: '";
msg += std::string((char*)pre.data(), pre.size()) + "' not found";
throw InvalidDataFormat(msg);
}
if(postPos == -1)
{
std::string msg = "PEM_StripEncapsulatedBoundary: '";
msg += std::string((char*)post.data(), post.size()) + "' not found";
throw InvalidDataFormat(msg);
}
if(prePos > postPos)
throw InvalidDataFormat("PEM_StripEncapsulatedBoundary: header boundary follows footer boundary");
temp.TransferTo(bt);
}
void PEM_NextObject(BufferedTransformation& src, BufferedTransformation& dest)
{
if(!src.AnyRetrievable())
return;
// We have four things to find:
// 1. -----BEGIN (the leading begin)
// 2. ----- (the trailing dashes)
// 3. -----END (the leading end)
// 4. ----- (the trailing dashes)
// Once we parse something that purports to be PEM encoded, another routine
// will have to look for something particular, like a RSA key. We *will*
// inadvertently parse garbage, like -----BEGIN FOO BAR-----. It will
// be caught later when a PEM_Load routine is called.
static const size_t BAD_IDX = PEM_INVALID;
// We use iterators for the search. However, an interator is invalidated
// after each insert that grows the container. So we save indexes
// from begin() to speed up searching. On each iteration, we simply
// reinitialize them.
SecByteBlock::const_iterator it;
size_t idx1 = BAD_IDX, idx2 = BAD_IDX, idx3 = BAD_IDX, idx4 = BAD_IDX;
// The idea is to read chunks in case there are multiple keys or
// paramters in a BufferedTransformation. So we use CopyTo to
// extract what we are interested in. We don't take anything
// out of the BufferedTransformation (yet).
// We also use indexes because the iterator will be invalidated
// when we append to the ByteQueue. Even though the iterator
// is invalid, `accum.begin() + index` will be valid.
// Reading 8 or 10 lines at a time is an optimization from testing
// against cacerts.pem. The file has 153 certs, so its a good test.
// +2 to allow for CR + LF line endings. There's no guarantee a line
// will be present, or it will be RFC1421_LINE_BREAK in size.
static const size_t READ_SIZE = (RFC1421_LINE_BREAK + 1) * 10;
static const size_t REWIND = std::max(SBB_PEM_BEGIN.size(), SBB_PEM_END.size()) + 2;
SecByteBlock accum;
size_t idx = 0, next = 0;
size_t available = src.MaxRetrievable();
while(available)
{
// How much can we read?
const size_t size = (std::min)(available, READ_SIZE);
// Ideally, we would only scan the line we are reading. However,
// we need to rewind a bit in case a token spans the previous
// block and the block we are reading. But we can't rewind
// into a previous index. Once we find an index, the variable
// next is set to it. Hence the reason for the max()
if(idx > REWIND)
{
const size_t x = idx - REWIND;
next = std::max(next, x);
}
// We need a temp queue to use CopyRangeTo. We have to use it
// because there's no Peek that allows us to peek a range.
ByteQueue tq;
src.CopyRangeTo(tq, static_cast<lword>(idx), static_cast<lword>(size));
const size_t offset = accum.size();
accum.Grow(offset + size);
tq.Get(accum.data() + offset, size);
// Adjust sizes
idx += size;
available -= size;
// Locate '-----BEGIN'
if(idx1 == BAD_IDX)
{
it = std::search(accum.begin() + next, accum.end(), SBB_PEM_BEGIN.begin(), SBB_PEM_BEGIN.end());
if(it == accum.end())
continue;
idx1 = it - accum.begin();
next = idx1 + SBB_PEM_BEGIN.size();
}
// Locate '-----'
if(idx2 == BAD_IDX && idx1 != BAD_IDX)
{
it = std::search(accum.begin() + next, accum.end(), SBB_PEM_TAIL.begin(), SBB_PEM_TAIL.end());
if(it == accum.end())
continue;
idx2 = it - accum.begin();
next = idx2 + SBB_PEM_TAIL.size();
}
// Locate '-----END'
if(idx3 == BAD_IDX && idx2 != BAD_IDX)
{
it = std::search(accum.begin() + next, accum.end(), SBB_PEM_END.begin(), SBB_PEM_END.end());
if(it == accum.end())
continue;
idx3 = it - accum.begin();
next = idx3 + SBB_PEM_END.size();
}
// Locate '-----'
if(idx4 == BAD_IDX && idx3 != BAD_IDX)
{
it = std::search(accum.begin() + next, accum.end(), SBB_PEM_TAIL.begin(), SBB_PEM_TAIL.end());
if(it == accum.end())
continue;
idx4 = it - accum.begin();
next = idx4 + SBB_PEM_TAIL.size();
}
}
// Did we find `-----BEGIN XXX-----` (RFC 1421 calls this pre-encapsulated boundary)?
if(idx1 == BAD_IDX || idx2 == BAD_IDX)
throw InvalidDataFormat("PEM_NextObject: could not locate boundary header");
// Did we find `-----END XXX-----` (RFC 1421 calls this post-encapsulated boundary)?
if(idx3 == BAD_IDX || idx4 == BAD_IDX)
throw InvalidDataFormat("PEM_NextObject: could not locate boundary footer");
// *IF* the trailing '-----' occurred in the last 5 bytes in accum, then we might miss the
// End of Line. We need to peek 2 more bytes if available and append them to accum.
if(available >= 2)
{
ByteQueue tq;
src.CopyRangeTo(tq, static_cast<lword>(idx), static_cast<lword>(2));
const size_t offset = accum.size();
accum.Grow(offset + 2);
tq.Get(accum.data() + offset, 2);
}
else if(available == 1)
{
ByteQueue tq;
src.CopyRangeTo(tq, static_cast<lword>(idx), static_cast<lword>(1));
const size_t offset = accum.size();
accum.Grow(offset + 1);
tq.Get(accum.data() + offset, 1);
}
// Final book keeping
const byte* ptr = accum.begin() + idx1;
const size_t used = idx4 + SBB_PEM_TAIL.size();
const size_t len = used - idx1;
// Include one CR/LF if its available in the accumulator
next = idx1 + len;
size_t adjust = 0;
if(next < accum.size())
{
byte c1 = accum[next];
byte c2 = 0;
if(next + 1 < accum.size())
c2 = accum[next + 1];
// Longest match first
if(c1 == '\r' && c2 == '\n')
adjust = 2;
else if(c1 == '\r' || c1 == '\n')
adjust = 1;
}
dest.Put(ptr, len + adjust);
dest.MessageEnd();
src.Skip(used + adjust);
}
size_t PEM_ReadLine(BufferedTransformation& source, SecByteBlock& line, SecByteBlock& ending)
{
if(!source.AnyRetrievable())
{
line.New(0);
ending.New(0);
return 0;
}
ByteQueue temp;
while(source.AnyRetrievable())
{
byte b;
if(!source.Get(b))
throw Exception(Exception::OTHER_ERROR, "PEM_ReadLine: failed to read byte");
// LF ?
if(b == '\n')
{
ending = LF;
break;
}
// CR ?
if(b == '\r')
{
// CRLF ?
if(source.AnyRetrievable() && source.Peek(b))
{
if(b == '\n')
{
source.Skip(1);
ending = CRLF;
break;
}
}
ending = CR;
break;
}
// Not End-of-Line, accumulate it.
temp.Put(b);
}
if(temp.AnyRetrievable())
{
line.Grow(temp.MaxRetrievable());
temp.Get(line.data(), line.size());
}
else
{
line.New(0);
ending.New(0);
}
// We return a line stripped of CRs and LFs. However, we return the actual number of
// of bytes processed, including the CR and LF. A return of 0 means nothing was read.
// A return of 1 means an empty line was read (CR or LF). A return of 2 could
// mean an empty line was read (CRLF), or could mean 1 character was read. In
// any case, line will hold whatever was parsed.
return line.size() + ending.size();
}
SecByteBlock::const_iterator Search(const SecByteBlock& source, const SecByteBlock& target)
{
return std::search(source.begin(), source.end(), target.begin(), target.end());
}
void PEM_Base64Decode(BufferedTransformation& source, BufferedTransformation& dest)
{
Base64Decoder decoder(new Redirector(dest));
source.TransferTo(decoder);
decoder.MessageEnd();
}
void PEM_WriteLine(BufferedTransformation& bt, const SecByteBlock& line)
{
bt.Put(line.data(), line.size());
bt.Put(reinterpret_cast<const byte*>(RFC1421_EOL.data()), RFC1421_EOL.size());
}
void PEM_WriteLine(BufferedTransformation& bt, const std::string& line)
{
bt.Put(reinterpret_cast<const byte*>(line.data()), line.size());
bt.Put(reinterpret_cast<const byte*>(RFC1421_EOL.data()), RFC1421_EOL.size());
}
NAMESPACE_END
#endif
</code></pre>
<blockquote>
<p><sub><strong>Licence</strong><br>
Boost Software License - Version 1.0 - August 17th, 2003<br>
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:<br>
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.<br>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</sub></p>
</blockquote>
<h2>Bounty</h2>
<p>I'm going to let the bounty run for the maximum time.</p>
<p>Useability feedback, or even style or efficiency feedback, is welcome, but the pricipal concern is if there is <em>any concrete reason for the library not to be used in a production environment</em>.</p>
<p>I'm not going to accept a <em>"don't roll your own crypto"</em> answer unless it provides a suitable alternative.<br>
I'm not going to accept a "this all looks fine" answer unless it includes some analysis of <em>why other people should trust the library</em>.<br>
That said, toward the end I'll upvote all answers that contribute to the collective assesment. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T15:07:13.263",
"Id": "424772",
"Score": "0",
"body": "It is possible to post the entire solution here, I've posted question with over 3000 lines of code. Do you only want the code posted to be reviewed or do you want the entire solution reviewed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T15:12:40.167",
"Id": "424774",
"Score": "0",
"body": "I'm hoping people will look at the whole repository. I could certainly copy paste it here if you think that's a good idea, but it seems like reading the code sequentially like that would be harder, and it would clutter this page. Do you think I should?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T15:16:32.820",
"Id": "424775",
"Score": "0",
"body": "You break it up by file, make the file names bold. FYI, I've already downloaded the zip."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:51:15.357",
"Id": "424820",
"Score": "2",
"body": "@pacmaninbw: done. You're right that it's not awful; I forget that SE has scroll boxes for very large code blocks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:41:17.630",
"Id": "424939",
"Score": "0",
"body": "I'm going to start a bounty on this. If the question get's four more upvotes it'll pay for itself!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:43:47.560",
"Id": "424940",
"Score": "0",
"body": "I think you should wait until tomorrow, but yes it could definitely help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:50:31.203",
"Id": "424943",
"Score": "0",
"body": "yeah, the window doesn't even open until tomorrow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T01:32:24.450",
"Id": "425144",
"Score": "0",
"body": "Have you tried clicking on the shared link to promote the question on facebook and twitter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T17:52:07.677",
"Id": "425294",
"Score": "2",
"body": "I've asked a [question on meta](https://codereview.meta.stackexchange.com/questions/9162/should-a-question-poster-include-the-boost-software-license) about the necessity of including the Boost Software License in a question."
}
] | [
{
"body": "<p>It is good to see cstdlib, EXIT_SUCCESS and EXIT_FAILURE in use. This is a very interesting concept with some good ideas. I admire your tenacity because it really must have been difficult to debug with all the functions in the headers.</p>\n\n<p>It might be good to have a Installshield setup or some other mechanism to install the source code as well as the <code>cryptopp810</code> header files.</p>\n\n<blockquote>\n <p>Would using this library as directed provide the guarantees expected of a blind signature protocol?</p>\n</blockquote>\n\n<p>I may not be able to provide a security audit, this review is based primarily on the code itself.</p>\n\n<p>This is a set of binaries, where is the library? I would expect to see a shared library generated by the make file. I would also expect to see the header files contain only function prototypes or classes and not the functions themselves. Including the function bodies in the header file makes the project more difficult to maintain. It means that any time a bug is fixed or code changes then everything that includes the header file needs to recompile. Creating a shared library would be better because the library interfaces would stay constant and the user code would not have to rebuild, only re-link. The current implementation could lead to multiple definitions of functions at link time.</p>\n\n<p>It might also be possible to eliminate the inclusion and use of the <code>cryptopp810</code> header files and the <code>using namespace CryptoPP;</code> from the end users code if the library is implemented as a shared library rather than a header file. This would decrease compile/build times for the end user. </p>\n\n<p>Embedding the <code>cryptopp810</code> header files in the user space prevents the user from upgrading to newer libraries.</p>\n\n<p>If the code continues to be in the header file it might be better to adopt the <code>Boost Library filename.hpp</code> extensions instead of <code>.h</code>. </p>\n\n<p>I'm curious as to why the library wasn't implemented in a class for encapsulate and data hiding reasons.</p>\n\n<p><strong>The use of Macros as Constants in C++</strong><br>\nC++ provides the <code>const</code> or <code>constexpr</code> to create symbolic constants, the use of <code>#define</code> is really the C programming language and is generally avoided because it is not type safe. The <code>const</code> symbolic constants have a type and can be checked at compile time. This <a href=\"https://stackoverflow.com/questions/1637332/static-const-vs-define\">stackoverflow question</a> may provide more background.\nUsing #ifdef and #define within header files to prevent repeated includes is still an accepted practice.</p>\n\n<p><strong>The try/catch Blocks</strong><br>\nIt might be better to include all of the successful code in the <code>try</code> block. The code is a little confusing the way it is implemented now.</p>\n\n<p>Instead of</p>\n\n<pre><code> try{\n message = argv[1];\n client_secret = Integer(argv[2]);\n public_key = ReadPEMPublicKey(argv[3]);\n }\n catch(std::runtime_error& e)\n {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n Integer hashed_message = GenerateHash(message);\n Integer hidden_message = MessageBlinding(hashed_message, public_key, client_secret);\n\n std::cout << std::hex << hidden_message << std::endl;\n return EXIT_SUCCESS;\n</code></pre>\n\n<p>This might be better, as it provides a continuos flow of the code.</p>\n\n<pre><code> try{\n message = argv[1];\n client_secret = Integer(argv[2]);\n public_key = ReadPEMPublicKey(argv[3]);\n Integer hashed_message = GenerateHash(message);\n Integer hidden_message = MessageBlinding(hashed_message, public_key, client_secret);\n\n std::cout << std::hex << hidden_message << std::endl;\n return EXIT_SUCCESS;\n }\n catch(std::runtime_error& e)\n {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n</code></pre>\n\n<p>If this alternate method is used then the declarations for current global variables could be moved into the try block. Even in the current implementation the global variables should be declared as local variables in <code>main()</code>.</p>\n\n<p><strong>Complexity</strong><br>\nWhile the Single Responsibility Principle is primarily an object oriented it can and should be applied to functional programs as well. <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">The Single Responsibility Principle states</a>:</p>\n\n<blockquote>\n <p>every module, class, or function should have responsibility over a single part of the functionality provided by the software...</p>\n</blockquote>\n\n<p>The function <code>void PEM_NextObject(BufferedTransformation& src, BufferedTransformation& dest)</code> is overly complex and could be broken up into multiple functions. </p>\n\n<p>The <code>PEM</code> code is also a good candidate for being turned into an object. Most of the <code>PEM</code> functions could be private functions in the class. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T00:52:41.727",
"Id": "425678",
"Score": "1",
"body": "Thank you for the above, Pacmanintw. Some of it is immediately actionable (although I probably won't get around to it this week!). As for giving a more traditional C++ style \"library\", I'm not sure of my way forward. The ideal solution would be to get the protocol added to the next version of Crypto++ itself, but I don't know if I'll have time in any sense of the word."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T00:19:48.897",
"Id": "220022",
"ParentId": "219867",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T13:19:19.053",
"Id": "219867",
"Score": "15",
"Tags": [
"c++",
"security",
"cryptography"
],
"Title": "Security audit of open-source, RSA Blind Signature library"
} | 219867 |
<p>I have written an answer to <a href="https://stackoverflow.com/questions/55970704/keyboard-interrupt-program-does-not-return-values">this question</a> on Stack Overflow. To make it easier for you, I have copy-pasted the main question below.</p>
<blockquote>
<p>Write a program that generates 100 random integers that are either <code>0</code>
or <code>1</code>.</p>
<p>Then find the:</p>
<ul>
<li>longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in <code>[1,0,1,1,0,0,0,0,1,0,0]</code> is
<code>4</code>.</li>
</ul>
</blockquote>
<p>Here is my answer to this:</p>
<pre><code>import random
l = []
def my_list():
for j in range(0,100):
x = random.randint(0,1)
l.append(x)
print (l)
return l
def largest_row_of_zeros(l):
c = 0
max_count = 0
for j in l:
if j == 0:
c += 1
else:
if c > max_count:
max_count = c
c = 0
return max_count
l = my_list()
print(largest_row_of_zeros(l))
</code></pre>
<p>NOTE: I have changed <code>zero_count</code> to <code>max_count</code> as it sounds more sensible. It keeps track of the <code>max_count</code> (or the largest number of zeros in a row) seen so far, and if a number is not <code>0</code>, it resets the value of <code>c</code> (count) to <code>0</code> after updating the value of <code>max_count</code> with a new value. </p>
<p>So, I would like to know whether I could make this code shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T17:17:43.520",
"Id": "424799",
"Score": "8",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). 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": "2019-05-08T00:15:49.757",
"Id": "424836",
"Score": "1",
"body": "What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:56:19.090",
"Id": "424931",
"Score": "1",
"body": "What version of Python are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:04:08.567",
"Id": "424933",
"Score": "1",
"body": "@jpmc26 - Python 3.7"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:30:52.430",
"Id": "425020",
"Score": "0",
"body": "For people viewing this question, please take a look at [user200345 's answer](https://codereview.stackexchange.com/questions/219872/program-for-finding-longest-run-of-zeros-from-a-list-of-100-random-integers-whic/219942#219942) below. It provides a good solution to my question too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:56:11.360",
"Id": "425026",
"Score": "0",
"body": "Also, please take a look at [Viktor Mellgren's answer](https://codereview.stackexchange.com/questions/219872/program-for-finding-longest-run-of-zeros-from-a-list-of-100-random-integers-whic/219976#219976), which provides a short solution to my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T12:58:56.977",
"Id": "425046",
"Score": "1",
"body": "what's wrong with the various `rle` codes? It's 2 or 3 lines, at least in `R`; then add a line to find `max(runlength(val==0))` Here's the base package code: `y <- x[-1L] != x[-n]` ; \n `i <- c(which(y | is.na(y)), n)` ;\n `structure(list(lengths = diff(c(0L, i)), values = x[i]), \n class = \"rle\")`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:58:54.940",
"Id": "425068",
"Score": "0",
"body": "@CarlWitthoft - You should write this as an answer. It seems interesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:03:43.293",
"Id": "425077",
"Score": "0",
"body": "@Justin OK, will do."
}
] | [
{
"body": "<p>To simplify the code you can:</p>\n\n<ol>\n<li>You can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a> to group the runs of 1s and 0s.</li>\n<li>Filter if these groups to ones just containing zero.</li>\n<li>Find the length of each group.</li>\n<li>Return the maximum.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\n\ndef largest_row_of_zeros(l):\n return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)\n</code></pre>\n\n<hr>\n\n<p>In your code I would move the <code>max</code> aspect of the code out of the function and make the original a generator function. This allows you to use <code>max</code> to simplify the handling of the data.</p>\n\n<pre><code>def zero_groups(l):\n c = 0\n for j in l:\n if j == 0:\n c += 1\n else:\n yield c\n c = 0\n\n\ndef largest_row_of_zeros(l):\n return max(zero_groups(l))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T14:50:30.643",
"Id": "219874",
"ParentId": "219872",
"Score": "9"
}
},
{
"body": "<h1>Generating a random list</h1>\n\n<p>Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and <code>return</code> it. This way, you will be able to call <code>my_list</code> a second time without having <code>l</code> being 200 items long. It will make the code easier to test.</p>\n\n<p>Also note that <code>l</code> as a variable name is a poor choice as certain fonts make it hard to distinguish from <code>1</code>.</p>\n\n<p>You also use the \"empty list + for loop + append\" pattern which can be converted to a more efficient list-comprehension:</p>\n\n<pre><code>def random_list(length=100):\n return [random.randint(0, 1) for _ in range(length)]\n</code></pre>\n\n<p>Note that, as suggested by <a href=\"https://codereview.stackexchange.com/users/25167/jpmc26\">@jpmc26</a> in the comments, and starting with Python 3.6, you can simplify further using <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"noreferrer\"><code>random.choices</code></a>:</p>\n\n<pre><code>def random_list(length=100):\n return random.choices((0, 1), k=length)\n</code></pre>\n\n<h1>Finding the longest sequence</h1>\n\n<p>Your manual counting is not that bad, but usually counting a number of element can be done using either <code>sum</code> or <code>len</code> depending on the iterable at play. And finding the longest count can be delegated to <code>max</code>. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.</p>\n\n<p><a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a> will happily do the grouping for you. But you won't be able to use <code>len</code> on the resulting groups, so you can add <code>1</code> for each element in said group.</p>\n\n<p>Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct <code>max</code> that the longest count is <code>0</code> in such cases:</p>\n\n<pre><code>def largest_row_of_zero(iterable):\n return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)\n</code></pre>\n\n<h1>Testing code</h1>\n\n<p>Instead of putting the testing code at the top-level of the file, you should take the habit of using an <a href=\"https://stackoverflow.com/q/419163/5069029\"><code>if __name__ == '__main__':</code></a> guard:</p>\n\n<pre><code>if __name__ == '__main__':\n l = random_list()\n print(l, largest_row_of_zero(l))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T01:28:32.797",
"Id": "424838",
"Score": "2",
"body": "Looping over `random.randint` is 5 times slower (on my machine) than `random.choices(POPULATION, k=100)`, with a global list `POPULATION = [0, 1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T12:38:24.253",
"Id": "424884",
"Score": "3",
"body": "Pretty sure `numpy.random.randint(0, 1, size=100)` would make a good job here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:25:54.080",
"Id": "424899",
"Score": "2",
"body": "@jpmc26 right, but `choices` is only available in latest versions and not yet an automatism"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:17:39.770",
"Id": "424934",
"Score": "1",
"body": "OP is [using 3.7](https://codereview.stackexchange.com/questions/219872/program-for-finding-longest-run-of-zeros-from-a-list-of-100-random-integers-whic?noredirect=1#comment424933_219872)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T07:34:29.087",
"Id": "425010",
"Score": "1",
"body": "@Rightleg And then using `np.max` on a variation of [this answer](https://stackoverflow.com/a/24343375/5069029). But I fear that, for such a small problem, you spend more time importing `numpy` than you'd be able to get as speedup from it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T15:04:45.283",
"Id": "219876",
"ParentId": "219872",
"Score": "21"
}
},
{
"body": "<p>First the good: your code provides a testable function. So let's add some test code</p>\n\n<pre><code>def largest_row_of_zeros(l):\n '''\n >>> largest_row_of_zeros([])\n 0\n >>> largest_row_of_zeros([0])\n 1\n >>> largest_row_of_zeros([1])\n 0\n >>> largest_row_of_zeros([0, 0])\n 2\n >>> largest_row_of_zeros([0, 1])\n 1\n >>> largest_row_of_zeros([1, 0])\n 1\n >>> largest_row_of_zeros([1, 1])\n 0\n '''\n\n c = 0\n max_count = 0\n for j in l:\n if j==0:\n c+=1\n else:\n if c > max_count:\n max_count = c\n c = 0\n return max_count\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n</code></pre>\n\n<p>which gives</p>\n\n<pre><code>Python 3.6.1 (default, Dec 2015, 13:05:11)\n[GCC 4.8.2] on linux\n**********************************************************************\nFile \"main.py\", line 5, in __main__.largest_row_of_zeros\nFailed example:\n largest_row_of_zeros([0])\nExpected:\n 1\nGot:\n 0\n**********************************************************************\nFile \"main.py\", line 9, in __main__.largest_row_of_zeros\nFailed example:\n largest_row_of_zeros([0, 0])\nExpected:\n 2\nGot:\n 0\n**********************************************************************\nFile \"main.py\", line 13, in __main__.largest_row_of_zeros\nFailed example:\n largest_row_of_zeros([1, 0])\nExpected:\n 1\nGot:\n 0\n**********************************************************************\n1 items had failures:\n 3 of 7 in __main__.largest_row_of_zeros\n***Test Failed*** 3 failures.\n</code></pre>\n\n<p>Here I use <a href=\"https://docs.python.org/3.6/library/doctest.html#module-doctest\" rel=\"nofollow noreferrer\">doctest</a>. Another very common module is <a href=\"https://docs.python.org/3.6/library/unittest.html#module-unittest\" rel=\"nofollow noreferrer\">unittest</a>. But you could also use simple assertions</p>\n\n<pre><code>if __name__ == \"__main__\":\n assert largest_row_of_zeros([0]) == 1\n</code></pre>\n\n<p>Have fun with testing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T09:56:36.493",
"Id": "425185",
"Score": "1",
"body": "For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see [this question on meta](https://codereview.meta.stackexchange.com/q/9156/31562)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T12:24:34.103",
"Id": "425193",
"Score": "0",
"body": "@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T16:40:51.823",
"Id": "219880",
"ParentId": "219872",
"Score": "11"
}
},
{
"body": "<p><strong>Bug</strong> in the posted code. If you try it with the input <code>[1,0,1,0,0]</code> you will get the answer <code>1</code>. The first two lines in the <code>else</code> won't get executed if the sequence ends with the longest run of zeros. Correct code is</p>\n\n<pre><code> for j in l:\n if j==0:\n c+=1\n else:\n c = 0\n if c > max_count:\n max_count = c\n\n return max_count\n</code></pre>\n\n<p>This can be considerably shortened and, I think, clarified:</p>\n\n<pre><code> for j in l:\n c = c + 1 if j==0 else 0 # in other languages there is a ternary ?: op\n max_count = max( max_count, c) \n\n return max_count\n</code></pre>\n\n<p>Two stylistic issues:</p>\n\n<p>never use <code>l</code> as a variable name, it reads like <code>1</code>. Lowercase <code>l</code> is best avoided altogether unless it's part of a word in a natural language. Similar arguments against <code>O</code> and <code>Z</code> which read like <code>0</code> and <code>2</code>, but class-names starting with capital <code>O</code> or <code>Z</code> aren't so confusing.</p>\n\n<p>The Pythonic form of initialization is <code>c, max_count = 0, 0</code> (one line) provided the right-hand side, in particular, needs no real thought. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T17:43:42.737",
"Id": "219883",
"ParentId": "219872",
"Score": "16"
}
},
{
"body": "<p>Why check all the elements? You can jump ahead k+1 elements at a time once you find k in a row. After a while you're jumping huge amounts each iteration</p>\n\n<pre><code>def longest_run(arr, element):\n longest = 0\n start = 0\n non_match = -1\n while start < len(arr):\n if arr[start] == element:\n current_run = 1\n while current_run <= longest and arr[start - current_run] == element:\n current_run += 1\n if current_run > longest:\n while non_match + current_run + 1 < len(arr) and arr[non_match + current_run + 1] == element:\n current_run += 1\n longest = current_run\n non_match = non_match + current_run\n else:\n non_match = start - current_run\n else:\n non_match = start\n start = non_match + longest + 1\n return longest\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T01:13:08.403",
"Id": "219899",
"ParentId": "219872",
"Score": "4"
}
},
{
"body": "<p>Just curious, but if the values list appears as a delimited collection, could you not just strip out the commas and split on the 1's to make an array and then reduce that? I haven't worked in python in 15 years (edit: updated to python) but this code seems to work:</p>\n\n<pre><code># importing functools for reduce() \nimport functools \n\n# initializing list \ninputString = \"1,0,1,1,0,0,0,0,1,0,0\"\n\n#remove commas and split result into an array using 1 as the delimiter\ninputString = inputString.replace(\",\", \"\")\nresultArr = inputString.split(\"1\");\n\n# using reduce to compute maximum element from resulting array list \nlongestString = (functools.reduce(lambda a,b : a if a >= b else b,resultArr)) \n\n#output the result\nprint (\"The maximum element of the list is : \",end=\"\") \nprint (len(longestString)) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:58:30.953",
"Id": "424948",
"Score": "1",
"body": "Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page https://codereview.stackexchange.com/help/how-to-answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:59:11.110",
"Id": "424949",
"Score": "0",
"body": "@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T20:53:01.333",
"Id": "424965",
"Score": "0",
"body": "Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:55:24.147",
"Id": "219942",
"ParentId": "219872",
"Score": "1"
}
},
{
"body": "<p>Wanted to provide an alternate solution to the <code>largest_row_of_zeros</code> method. Easier to understand, but might not be as efficient.</p>\n\n<pre><code>def largest_row_of_zeros():\n asStr = reduce((lambda x, y: str(x) + str(y)), random_list())\n splitted = asStr.split(\"1\")\n return len(max(splitted))\n</code></pre>\n\n<ul>\n<li>Basically create a string <code>\"1010010101010\"</code></li>\n<li>Split at 1s. <code>\"\",\"0\",\"00\",\"0\"</code> ...</li>\n<li>Get length of longest string</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:53:22.287",
"Id": "425025",
"Score": "0",
"body": "Yes, this also a very good solution to my question. Thanks for the answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T13:12:59.337",
"Id": "425050",
"Score": "4",
"body": "Instead of using reduce, `''.join(map(str, random_list()))` is more idiomatic and understandable at a glance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T13:46:21.247",
"Id": "425055",
"Score": "1",
"body": "@MathiasEttinger much nicer"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:45:51.427",
"Id": "219976",
"ParentId": "219872",
"Score": "0"
}
},
{
"body": "<p>Another alternative: use <code>RLE</code> (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name. </p>\n\n<p>Here's the code, albeit in the <code>R</code> language. (For non-users, <code>1L</code> just forces integer-class, <code>x[-k]</code> means all of vector <code>x</code> <em>except</em> index 'k' ) </p>\n\n<p>Here's the base package code for the function <code>rle(x)</code> :<br>\nFirst line: generate logical vector of \"is x[j] == x[j-1] ? \" </p>\n\n<pre><code> y <- x[-1L] != x[-n] ;\n</code></pre>\n\n<p><code>which</code> returns index values when argument is TRUE, and <code>c</code> concatenates vectors (is.na just catches N/A values in case the input was skeevy) </p>\n\n<pre><code> i <- c(which(y | is.na(y)), n) ; \n</code></pre>\n\n<p>finally, create a structure. First element calculates run lengths by comparing sequential index values in <code>i</code> ; second element returns the value of the input vector every time that run terminates </p>\n\n<pre><code> structure(list(lengths = diff(c(0L, i)), values = x[i]), class = \"rle\")\n</code></pre>\n\n<p>then add a line to find <code>max(lengths[values==0])</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:09:38.713",
"Id": "425078",
"Score": "0",
"body": "Is the `R` language related to Python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:35:31.690",
"Id": "425085",
"Score": "3",
"body": "Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:53:10.020",
"Id": "425089",
"Score": "0",
"body": "@AlexV Done -- I hope :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T10:33:04.680",
"Id": "425269",
"Score": "3",
"body": "RLE stands for Run Length Encoding, AFAIK. There is no estimation involved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:46:57.750",
"Id": "425417",
"Score": "0",
"body": "@graipher - thanks - corrected that."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:07:49.863",
"Id": "219999",
"ParentId": "219872",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219876",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T14:30:17.003",
"Id": "219872",
"Score": "16",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Program for finding longest run of zeros from a list of 100 random integers which are either 0 or 1"
} | 219872 |
<p><strong>I have my movie folders formatted:</strong></p>
<ol>
<li><p><strong>~:</strong> no sub included</p></li>
<li><p><strong>{}:</strong> already watched</p></li>
<li><p><strong><em>nothing:</em></strong> sub included, ready to watch</p></li>
</ol>
<p>the program asks for the movie directory; extracts the name and searches IMDb for the name; renames the given directory to the first IMDb search result.</p>
<p>finally saves what you'd see when the first result is clicked as a .html file in the given directory.
<a href="https://i.stack.imgur.com/tNJly.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tNJly.png" alt="Example"></a></p>
<pre><code>import urllib
import requests
import os
import re
from bs4 import BeautifulSoup
# write response page in tmp.html
def movNameSearch(path, movie):
print('Fetching...\n')
url = "https://www.imdb.com/find?ref_=nv_sr_fn&q=" + movie + "&s=tt"
response = requests.get(url) #get response
resTxt = response.text
soup = BeautifulSoup(resTxt, 'html.parser') #parsed response
findList = soup.find_all('td', class_ = 'result_text') #all founded movies
someList = []
for i in range(10):
theRes = findList[i].contents[1].contents[0] + findList[i].contents[2]
someList.append(theRes)
for j in range(len(someList)):
print(str(j+1) + '. ' + someList[j])
selection = int(input('\nWhich is the desired result? '))
rec = findList[selection-1].contents #first found result - recommended
recText = rec[1].contents[0] #movie name
fullName = recText + rec[2] #movie year
suggestion = 'Confirm ' + fullName + '? (y/n) '
accept = input(suggestion)
if accept == 'y':
print('Renaming the folder...')
#rename folder
pathArray = path.split(sep='/')
if pathArray[-1] == '': # / at the end
pathArray.pop()
pathArray.pop()
else: #no / at the end
pathArray.pop()
pathArray.append(fullName)
src = path
dst = '/'.join(pathArray)
os.rename(src, dst)
print('Renamed to ' + fullName)
#generate info into info.txt
imdbUrl = 'https://www.imdb.com'
toAdd = list(rec[1].parent.contents[1].attrs.values())[0]
imdbUrl = imdbUrl + toAdd
result = [imdbUrl, dst]
return result
else:
print('K bye')
def getInfo(url, path):
print('Fetching extra info...')
response = requests.get(url)
resTxt = response.text
soup = BeautifulSoup(resTxt, 'html.parser')
print('Generating extra info...')
f = open(path + '/info.html', 'w+')
f.write(resTxt)
print('Complete.')
return True
#/home/name/some/~{}folder
# open directory =>
# get path
mainPath = str(input("Enter movie directory: "))
movName = re.split("/", mainPath)
if movName[-1] == '':
movName = movName[-2]
else:
movName = movName[-1]
# remove extra chars
movName = re.sub("[~{}]", "", movName).capitalize()
# check
accept = input("Confirm " + movName + " ? (y/n) ")
if accept == "y":
result = movNameSearch(mainPath, movName)
if len(result) == 2:
stat = getInfo(result[0], result[1])
if stat == True:
print('Success! Quitting now.')
else:
print('K Bye')
else:
print("K bye")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T17:00:54.840",
"Id": "474997",
"Score": "1",
"body": "Wouldn't it be easier to have an imdb.txt and a watched.txt in each folder?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T15:23:23.930",
"Id": "219877",
"Score": "7",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Get a movie directory, rename it and save imdb info as a webpage"
} | 219877 |
<p>Follow-up of <a href="https://stackoverflow.com/questions/55835457/main-function-not-waiting-for-channel-read-before-exiting">this question</a>.</p>
<p><strong>Questions:</strong></p>
<ul>
<li>is this code a correct implementation of the <a href="https://en.wikipedia.org/wiki/Dining_philosophers_problem" rel="nofollow noreferrer">Dining Philosophers problem</a>?</li>
<li>what is there to improve regarding Go Best Practices?</li>
</ul>
<pre><code>package main
import (
"fmt"
"sync"
)
func philos(id int, left, right chan bool, wg *sync.WaitGroup) {
fmt.Printf("Philosopher # %d wants to eat\n", id)
<-left
<-right
left <- true
right <- true
fmt.Printf("Philosopher # %d finished eating\n", id)
wg.Done()
}
func main() {
const numPhilos = 5
var forks [numPhilos]chan bool
for i := 0; i < numPhilos; i++ {
forks[i] = make(chan bool, 1)
forks[i] <- true
}
var wg sync.WaitGroup
for i := 0; i < numPhilos; i++ {
wg.Add(1)
go philos(i, forks[(i-1+numPhilos)%numPhilos], forks[(i+numPhilos)%numPhilos], &wg)
}
wg.Wait()
fmt.Println("Everybody finished eating")
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T09:16:57.133",
"Id": "424855",
"Score": "1",
"body": "Just an observation, but the second argument to your routine in `go philos()` is `forks[(i+numPhilos)%numPhilos]`, which is the exact same thing as writing `forks[i]` anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T12:41:52.657",
"Id": "424885",
"Score": "0",
"body": "@EliasVanOotegem: good point!"
}
] | [
{
"body": "<p>All in all, it's not a bad implementation at all. The bulk of my comments will focus on idiomatic golang stuff, and some small tweaks you can make to the <code>main</code> function. As I usually do here, I'll go through it line by line</p>\n\n<pre><code>func main() {\n const numPhilos = 5\n</code></pre>\n\n<p>OK, so you're starting out defining an untyped constant in your <code>main</code>. That's perfectly valid, and it doesn't make much of a difference, but generally speaking, I'd define my constants outside of functions. This makes it easier to centralise your constants, see what constants are used in the file/package (if you're exporting them), and makes it easier to break up your code into smaller functions further down the line. Moving on:</p>\n\n<pre><code>var forks [numPhilos]chan bool\n</code></pre>\n\n<p>OK, so arrays can be used in go, but it's generally recommended you don't. The rule of thumb is: use slices if you can. Next:</p>\n\n<pre><code>for i := 0; i < numPhilos; i++ {\n forks[i] = make(chan bool, 1)\n forks[i] <- true\n}\n</code></pre>\n\n<p>Again, no real issues here, only, you're assigning a channel to an index in an array, and then writing to it, accessing the array again. I'd use a scoped variable instead. Next:</p>\n\n<pre><code>var wg sync.WaitGroup\nfor i := 0; i < numPhilos; i++ {\n wg.Add(1)\n go philos(i, forks[(i-1+numPhilos)%numPhilos], forks[(i+numPhilos)%numPhilos], &wg)\n} \nwg.Wait()\n</code></pre>\n\n<p>Right, short of what I pointed out in the comment about <code>forks[(i+numPhilos)%numPhilos]</code> being the same as <code>forks[i]</code>, this all works, but there's quite a few things we can improve:</p>\n\n<ul>\n<li>you're creating a <code>var wg sync.WaitGroup</code>, and passing pointers to it. Good, but why not create a pointer literal. It's safer (less likely to pass by value accidentally), and code is easier to read IMO</li>\n<li>You're incrementing <code>i</code>, and accessing <code>forks</code>, knowing full well that the <code>len(forks)</code> won't be exceeded. After all, your loop is the same as the one you used to initialise <code>forks</code>. So why not loop over <code>forks</code> to begin with?</li>\n<li><code>wg.Add(1)</code> is incrementing the waitgroup for each routine, but you clearly know beforehand how many routines you're going to spin up. You can add that total number of routines to your waitgroup outside of the loop.</li>\n<li>I don't like the names <code>numPhilos</code> and <code>philos</code> for a func.</li>\n<li>You're passing the waitgroup as a last argument. It's more common to see <code>context.Context</code> as the first argument, and things like a waitgroup (controlling the runtime and routines) as first arguments, rather than last</li>\n</ul>\n\n<p>Last line:</p>\n\n<pre><code>fmt.Println(\"Everybody finished eating\")\n</code></pre>\n\n<p>This should not be the end of your program. You should close the channels!</p>\n\n<p>Now, let's put all of this together:</p>\n\n<pre><code>const numPhilos = 5\n\nfunc main() {\n // create slice, not an array - set capacity to numPhilos\n forks := make([]chan bool, 0, numPhilos)\n for i := 0; i < numPhilos; i++ {\n // create channel in local scope\n ch := make(chan bool, 1)\n ch <- true // write to channel directly\n forks = append(forks, ch) // append to forks slice\n }\n // I prefer literals, because I can create a pointer type directly\n wg := &sync.WaitGroup{}\n // add 1 for each channel in forks\n wg.Add(len(forks))\n for i, ch := range forks {\n // forks[i] is now ch, get the left one using the method you are using already\n go philos(wg, i, forks[(i+numPhilos-1)%numPhilos], ch)\n }\n wg.Wait()\n // close channels\n for _, ch := range forks {\n close(ch)\n }\n // done\n fmt.Println(\"Everybody finished eating\")\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T20:25:56.663",
"Id": "219953",
"ParentId": "219881",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T17:21:55.727",
"Id": "219881",
"Score": "4",
"Tags": [
"go",
"dining-philosophers"
],
"Title": "Go implementation of dining philosophers"
} | 219881 |
<p>I reviewed this question to a snake game console implementation:
<a href="https://codereview.stackexchange.com/questions/219645/my-first-c-game-snake-console-game/219658#219658">My first C++ game (snake console game)</a></p>
<p>I enjoyed refactoring this code and presenting a solution using more C++ features/classes. I ended up rewriting this project from scratch.</p>
<p>My aim was to make the code easy and maintainable to read. Also, I tried to seperate the IO with the console from the logic because maybe I want to use the logic to port the game from console to QT-GUI as another excercise later.</p>
<p>I wonder what can be still be improved in the code?</p>
<p>Is the code easy to read for you/easy to follow?</p>
<p>Are there any bad practices?</p>
<p>Things which can possible be improved:</p>
<ul>
<li>Currently, we are not portable. <code>ConsoleOperations.cpp</code> uses Windows specified header. Is there an easy way to enable Linux/Mac aswell?</li>
</ul>
<p><strong>main.cpp</strong></p>
<pre><code>#include "Game.h"
#include <iostream>
int main()
try {
snakeGame::runGame();
return 0;
}
catch (...) {
std::wcerr << "unknown error " << "\n";
std::wcin.get();
}
</code></pre>
<p><strong>Game.h</strong></p>
<pre><code>#pragma once
namespace snakeGame {
void runGame();
}
namespace snakeGame::impl {
class Board; // fwd delaration
bool askUserToEndGame();
void pauseUntilPauseKeyPressedAgain();
void printBoardWithStats(const Board& board, long long score, int delay);
void waitFor(int milliseconds);
void printGameOverWithScore(int score);
}
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>#include "Game.h"
#include "Snake.h"
#include "Board.h"
#include "ConsoleOperations.h"
#include "SnakeDirection.h"
#include <chrono>
#include <iostream>
#include <thread>
namespace snakeGame {
using namespace impl;
void runGame()
{
for (;;) {
if (askUserToEndGame()) {
return;
}
constexpr auto fieldWidth = 40;
constexpr auto fieldHeight = 15;
Board board{ fieldWidth, fieldHeight };
board.updateSnakePosition();
board.placeFood();
SnakeDirection snakeDirection = SnakeDirection::right;
long long score{ 0 };
long long points{ 100 };
auto delay(300);
bool wasPausedInLastLoop{ false };
for (;;) {
putCursorToStartOfConsole();
printBoardWithStats(board, score, delay);
if (wasPausedInLastLoop) {
// If we don't do this and print pause to the console by
// pressing p during the game the pause statement will
// still be printed because during the game the pause
// statement will still be printed because during the game
// the pause statement will still be printed because
// during the game the pause statement will still be
// printed because we start printing from the beginning of
// the console and now the total string printed to the
// console would be one row lower.
std::wcout << L" \n";
wasPausedInLastLoop = false;
}
if (keyWasPressed()) {
auto key = getKey();
if (key == 'p') {
wasPausedInLastLoop = true;
std::wcout << L"#####PAUSED#####\n";
pauseUntilPauseKeyPressedAgain();
}
else {
snakeDirection = updateDirection(key, snakeDirection);
}
}
board.moveSnake(snakeDirection);
if (board.snakeHitFood()) {
board.eatFood();
board.growSnake();
board.placeFood();
score += points;
points *= 2;
delay -= 5;
}
else if (board.snakeHitWall() || board.snakeHitSnake()) {
break;
}
board.updateSnakePosition();
std::this_thread::sleep_for(std::chrono::milliseconds{ delay });
}
printGameOverWithScore(score);
}
}
}
namespace snakeGame::impl {
bool askUserToEndGame()
{
clearScreen();
while (true) {
auto choice{ 0 };
std::wcout << L"1. Play\n";
std::wcout << L"2. Quit\n";
std::wcin >> choice;
if (choice == 1) {
return false;
}
else if (choice == 2) {
return true;
}
else {
std::wcout << L"Invalid input!";
std::wcin.get();
clearScreen();
}
}
}
void pauseUntilPauseKeyPressedAgain()
{
for (;;) {
if (keyWasPressed) {
auto key = getKey();
if (key == 'p') {
return;
}
}
}
}
void printBoardWithStats(const Board& board, long long score, int delay)
{
std::wcout << L"Score:" << score << '\n';
std::wcout << L"Delay:" << delay << "ms \n";
std::wcout << board;
std::wcout << L"Use 'w, a, s, d' to change directions\n";
}
void waitFor(int milliseconds)
{
std::this_thread::sleep_for(std::chrono::milliseconds{ milliseconds });
}
void printGameOverWithScore(int score)
{
clearScreen();
std::wcout << L"Game over!\n";
std::wcout << L"Score: " << score << '\n';
std::wcin.clear();
std::wcin.ignore(120, '\n');
std::wcin.get();
}
}
</code></pre>
<p><strong>Board.h</strong></p>
<pre><code>#pragma once
#include "Snake.h"
#include <vector>
#include <random>
#include <iosfwd>
namespace snakeGame::impl {
enum class SnakeDirection;
struct Element {
bool hasSnakeSegment{ false };
bool hasSnakeHead{ false };
bool hasWall{ false };
bool hasFood{ false };
};
class Board
{
public:
Board(int width, int height);
void placeFood();
void updateSnakePosition();
bool snakeHitFood() const;
void eatFood();
void growSnake();
bool snakeHitWall() const;
bool snakeHitSnake() const;
void moveSnake(SnakeDirection snakeDirection);
void debugPrintSnakeCoordinates();
private:
std::vector<std::vector<Element>> initFieldWithWalls(int width, int height);
void removeOldSnakePosition(const std::vector<SnakeSegment>& body);
void addNewSnakePosition(const std::vector<SnakeSegment>& body);
Snake mSnake;
std::vector<std::vector<Element>> mField;
std::random_device mRandomDevice;
std::default_random_engine mGenerator;
std::uniform_int_distribution<int> mWidthDistribution;
std::uniform_int_distribution<int> mHeightDistribution;
friend std::wostream& operator<<(std::wostream& os, const Board& obj);
};
std::wostream& operator<<(std::wostream& os, const Board& obj);
}
</code></pre>
<p><strong>Board.cpp</strong></p>
<pre><code>#include "Board.h"
#include "SnakeDirection.h"
#include <algorithm>
#include <iostream>;
namespace snakeGame::impl {
Board::Board(int width, int height)
: mSnake{ width, height },
mField{ initFieldWithWalls(width, height) },
mRandomDevice{},
mGenerator{ mRandomDevice() },
mWidthDistribution{ 1, width - 2 },
mHeightDistribution{ 1, height - 2 }
{
}
void Board::updateSnakePosition()
{
auto snakeBody = mSnake.getBody();
removeOldSnakePosition(snakeBody);
addNewSnakePosition(snakeBody);
}
bool Board::snakeHitFood() const
{
auto pos = mSnake.getBody()[0].pos;
return mField[pos.y][pos.x].hasFood;
}
void Board::eatFood()
{
auto pos = mSnake.getBody()[0].pos;
mField[pos.y][pos.x].hasFood = false;
}
void Board::growSnake()
{
mSnake.grow();
}
bool Board::snakeHitWall() const
{
auto pos = mSnake.getBody()[0].pos;
return mField[pos.y][pos.x].hasWall;
}
bool Board::snakeHitSnake() const
{
auto pos = mSnake.getBody()[0].pos;
return mField[pos.y][pos.x].hasSnakeSegment;
}
void Board::moveSnake(SnakeDirection snakeDirection)
{
switch (snakeDirection) {
case SnakeDirection::right:
mSnake.moveRight();
break;
case SnakeDirection::down:
mSnake.moveDown();
break;
case SnakeDirection::left:
mSnake.moveLeft();
break;
case SnakeDirection::up:
mSnake.moveUp();
break;
}
}
void Board::debugPrintSnakeCoordinates()
{
auto body = mSnake.getBody();
for (auto i = 0; i < body.size(); ++i) {
auto pos = body[i].pos;
std::wcout << "nr:" << i << "x:" << pos.x << "\t" << "y:" << pos.y << "\t";
auto field = mField[pos.y][pos.x];
if (field.hasSnakeHead) {
std::wcout << L"Head\t";
}
else {
std::wcout << L" \t";
}
if (field.hasSnakeSegment) {
std::wcout << L"Body\n";
}
else {
std::wcout << L" \n";
}
}
}
void Board::placeFood()
{
for (;;) {
auto x = mWidthDistribution(mGenerator);
auto y = mHeightDistribution(mGenerator);
if (!mField[y][x].hasSnakeHead &&
!mField[y][x].hasSnakeSegment) {
mField[y][x].hasFood = true;
break;
}
}
}
std::vector<std::vector<Element>> Board::initFieldWithWalls(int width, int height)
{
std::vector<Element> row(width, Element{});
std::vector<std::vector<Element>> field(height, row);
Element wall{ false, false, true, false };
std::fill(field[0].begin(), field[0].end(), wall);
std::fill(field[field.size() - 1].begin(), field[field.size() - 1].end(), wall);
for (auto it_row = field.begin() + 1; it_row < field.end() - 1; ++it_row) {
(*it_row)[0] = wall;
(*it_row)[it_row->size() - 1] = wall;
}
return field;
}
void Board::removeOldSnakePosition(const std::vector<SnakeSegment>& body)
{
auto first{ true };
for (const auto& snakeSegment : body) {
auto prev = snakeSegment.prev;
if (first) {
mField[prev.y][prev.x].hasSnakeHead = false;
first = false;
}
else {
mField[prev.y][prev.x].hasSnakeSegment = false;
}
}
}
void Board::addNewSnakePosition(const std::vector<SnakeSegment>& body)
{
auto first{ true };
for (const auto& snakeSegment : body) {
auto pos = snakeSegment.pos;
if (first) {
mField[pos.y][pos.x].hasSnakeHead = true;
first = false;
}
else {
mField[pos.y][pos.x].hasSnakeSegment = true;
}
}
}
std::wostream& operator<<(std::wostream& os, const Board& obj)
{
for (const auto& row : obj.mField) {
for (const auto& element : row) {
if (element.hasSnakeSegment) {
os << L'o';
}
else if (element.hasSnakeHead) {
os << L'@';
}
else if (element.hasWall) {
os << L'#';
}
else if (element.hasFood) {
os << L'*';
}
else {
os << L' ';
}
}
os << '\n';
}
return os;
}
}
</code></pre>
<p><strong>Snake.h</strong></p>
<pre><code>#pragma once
#include "Point.h"
#include <vector>
namespace snakeGame::impl {
struct SnakeSegment
{
Point pos{ 0 , 0 };
Point prev{ pos };
};
class Snake
{
public:
Snake(int boardWidth, int boardHeight);
std::vector<SnakeSegment> getBody() const;
void moveRight();
void moveDown();
void moveLeft();
void moveUp();
void grow();
private:
void safeCurrentPosToLastOfFirstElement();
void moveRemainingElements();
std::vector<SnakeSegment> mBody;
};
std::vector<SnakeSegment> initSnake(int fieldWidth, int fieldHeight);
}
</code></pre>
<p><strong>Snake.cpp</strong></p>
<pre><code>#include "Snake.h"
namespace snakeGame::impl {
Snake::Snake(int fieldWidth, int fieldHeight)
:mBody{ initSnake(fieldWidth, fieldHeight) }
{
}
std::vector<SnakeSegment> Snake::getBody() const
{
return mBody;
}
void Snake::moveRight()
{
safeCurrentPosToLastOfFirstElement();
++mBody[0].pos.x;
moveRemainingElements();
}
void Snake::moveDown()
{
safeCurrentPosToLastOfFirstElement();
++mBody[0].pos.y;
moveRemainingElements();
}
void Snake::moveLeft()
{
safeCurrentPosToLastOfFirstElement();
--mBody[0].pos.x;
moveRemainingElements();
}
void Snake::moveUp()
{
safeCurrentPosToLastOfFirstElement();
--mBody[0].pos.y;
moveRemainingElements();
}
void Snake::grow()
{
SnakeSegment newTail;
newTail.pos.x = mBody[mBody.size() - 1].prev.x;
newTail.pos.y = mBody[mBody.size() - 1].prev.y;
mBody.push_back(newTail);
}
void Snake::safeCurrentPosToLastOfFirstElement()
{
mBody[0].prev.x = mBody[0].pos.x;
mBody[0].prev.y = mBody[0].pos.y;
}
void Snake::moveRemainingElements()
{
for (int i = 1; i < mBody.size(); ++i) {
mBody[i].prev.x = mBody[i].pos.x;
mBody[i].prev.y = mBody[i].pos.y;
mBody[i].pos.x = mBody[i - 1].prev.x;
mBody[i].pos.y = mBody[i - 1].prev.y;
}
}
std::vector<SnakeSegment> initSnake(int boardWidth, int boardHeight)
{
auto x = boardWidth / 2;
auto y = boardHeight / 2;
std::vector<SnakeSegment> body{
SnakeSegment{ x, y },
SnakeSegment{ x - 1, y },
};
return body;
}
}
</code></pre>
<p><strong>Point.h</strong></p>
<pre><code>#pragma once
namespace snakeGame::impl {
struct Point {
int x;
int y;
};
}
</code></pre>
<p><strong>SnakeDirection.h</strong></p>
<pre><code>#pragma once
namespace snakeGame::impl {
enum class SnakeDirection {
up, right, down, left
};
}
</code></pre>
<p><strong>ConsoleOperations.h</strong></p>
<pre><code>#pragma once
// Non portable. At the moment only windows works
namespace snakeGame::impl {
enum class SnakeDirection;
void putCursorToStartOfConsole();
void clearScreen();
bool keyWasPressed();
char getKey();
SnakeDirection updateDirection(char c, SnakeDirection direction);
}
</code></pre>
<p><strong>ConsoleOperations.cpp</strong></p>
<pre><code>#include "ConsoleOperations.h"
#include "SnakeDirection.h"
#include <cstdlib>
//#ifdef _WIN32
#include <conio.h>
#include <Windows.h>
//#else
// //Assume POSIX
//#endif
namespace snakeGame::impl {
void putCursorToStartOfConsole()
{
//#ifdef _WIN32
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
//#else
// //Assume POSIX
//#endif
}
void clearScreen()
{
//#ifdef _WIN32
std::system("cls");
//#else
// // Assume POSIX
// std::system("clear");
//#endif
}
bool keyWasPressed()
{
//#ifdef _WIN32
return static_cast<bool>(_kbhit());
//#else
// Assume POSIX
//#endif
}
char getKey()
{
//#ifdef _WIN32
return _getch();
//#else
// Assume POSIX
//#endif
}
SnakeDirection updateDirection(char c, SnakeDirection direction)
{
switch (c) {
case 'a':
if (direction != SnakeDirection::right) {
direction = SnakeDirection::left;
}
break;
case 'w':
if (direction != SnakeDirection::down) {
direction = SnakeDirection::up;
}
break;
case 'd':
if (direction != SnakeDirection::left) {
direction = SnakeDirection::right;
}
break;
case 's':
if (direction != SnakeDirection::up) {
direction = SnakeDirection::down;
}
break;
}
return direction;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:31:01.507",
"Id": "424902",
"Score": "0",
"body": "I assume snakedirection is a header file, but you might want to make that clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:05:04.097",
"Id": "424907",
"Score": "0",
"body": "What version of Visual Studio are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:12:17.353",
"Id": "424921",
"Score": "0",
"body": "Fixed. Its a header file. I used MSVC2017."
}
] | [
{
"body": "<p>Overall a good job, and much better than the version you answered.</p>\n\n<p><strong>Better Not to Ignore Warning Messages</strong><br>\nBoard.cpp generates 2 warning messages, the first is for a typo on the semicolon on this line:</p>\n\n<pre><code>#include <iostream>;\n</code></pre>\n\n<p>The second is for a type mismatch on this line</p>\n\n<pre><code> for (auto i = 0; i < body.size(); ++i) {\n</code></pre>\n\n<p>Auto comes in very handy for some things, but it is best not to abuse it. C++ is not a scripting language and type checking in C++ is a good thing. Use auto to define iterators when looping through a container but use the proper type in other instances. It's generally a good idea for someone who has to maintain the code to know what type an objects is. Unlike C# and some other languages C++ does not have Reflection.</p>\n\n<p><strong>Inlcude Header Files Within Headers</strong><br>\nThe code might be more maintainable if header files such as <code>Board.h</code> and <code>ConsoleOperations.h</code> included header files for objects they consume such as <code>SnakeDirection.h</code> and <code>Point.h</code>. As it is now someone using <code>Board.h</code> in a new file will run into compiler issues if they haven't already included the proper files. </p>\n\n<p><strong>Check User Input</strong><br>\nNeither the function <code>getKey()</code> nor <code>updateDirection(key, snakeDirection)</code> performs adequate error checking, if the user enters an illegal value, the behavior is unknown. It is always good to check user input.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:50:15.007",
"Id": "219946",
"ParentId": "219886",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:15:09.187",
"Id": "219886",
"Score": "6",
"Tags": [
"c++",
"console",
"windows",
"c++17",
"snake-game"
],
"Title": "Snake console game in C++"
} | 219886 |
<p>I tried to implement a cyclic Queue using an array, as a task from a coding interview.</p>
<p>Please comment about style, as well as any edge cases I may have missed.</p>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CirucularArray
{
[TestClass]
public class CyclicQueueUsingArray
{
[TestMethod]
public void QueueTest()
{
CyclicQueue Q = new CyclicQueue(5);
Q.Enqueue(1);
Assert.AreEqual(1, Q.Front);
Q.Enqueue(2);
Assert.AreEqual(1, Q.Front);
Assert.AreEqual(2, Q.Rear);
Q.Enqueue(3);
Assert.AreEqual(1, Q.Front);
Assert.AreEqual(3, Q.Rear);
Assert.AreEqual(1, Q.Dequeue());
Assert.AreEqual(2, Q.Front);
Assert.AreEqual(3, Q.Rear);
Assert.AreEqual(2, Q.Dequeue());
Assert.AreEqual(3, Q.Front);
Assert.AreEqual(3, Q.Rear);
Assert.AreEqual(3, Q.Dequeue());
}
[TestMethod]
public void QueueOverflowTest()
{
CyclicQueue Q = new CyclicQueue(5);
Q.Enqueue(1);
Q.Enqueue(2);
Q.Enqueue(3);
Q.Enqueue(4);
Q.Enqueue(5);
Assert.AreEqual(1, Q.Dequeue());
Q.Enqueue(6);
Assert.AreEqual(2, Q.Front);
Assert.AreEqual(6, Q.Rear);
}
}
public class CyclicQueue
{
public int[] _buffer;
private int _start;
private int _end;
private int _size;
private int _maxSize;
public CyclicQueue(int maxSize)
{
_maxSize = maxSize;
_buffer = new int[_maxSize];
_start = 0;
_end = 0;
}
public void Enqueue(int newValue)
{
if (_size == _maxSize)
{
throw new OutOfMemoryException("Queue at full capacity");
}
if (_size > 0)
{
_end = (_end + 1) % _maxSize;
}
_buffer[_end] = newValue;
_size++;
}
public int Dequeue()
{
if (_size == 0)
{
throw new IndexOutOfRangeException("Queue is empty");
}
int result = _buffer[_start];
_size--;
_start = (_start + 1) % _maxSize;
return result;
}
public int Front
{
get { return _buffer[_start]; }
}
public int Rear
{
get { return _buffer[_end]; }
}
}
}
</code></pre>
| [] | [
{
"body": "<h2>Yay exceptions!</h2>\n\n<p>Though it isn't reservered for execution-ending errors, I would avoid throwing an <code>OutOfMemoryException</code>, because usually it signals something very inconvient indeed. <code>IndexOutOfRangeException</code> also seems inappropriate: I would probably use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.invalidoperationexception?view=netframework-4.8\" rel=\"noreferrer\"><code>InvalidOperationException</code></a> in both <code>Enqueue</code> and <code>Dequeue</code>.</p>\n\n<p>The constructor could do with a check to ensure <code>maxSize</code> is positive, so that it doesn't throw with a cryptic error.</p>\n\n<p><code>Front</code> and <code>End</code> don't throw on an empty buffer, and probably should.</p>\n\n<h2>API and Encapsulation</h2>\n\n<p>There is no reason this class couldn't be generic: I would make it so. Indeed, because it stores <code>int</code>s at the moment, it would not be clear to a consumer looking at the members that <code>Front</code> and <code>Rear</code> return elements rather than indexes.</p>\n\n<p>I'd expect a <code>Count => _size</code> property, so that the Queue can be used for the sort of things Queues tend to be used (e.g. in your previous questions).</p>\n\n<p>Do you have a particular use-case in mind for exposing <code>_buffer</code>? What good can come of this? There is no information made available as to the content of the buffer, so it can't be used for anything because nothing except the <code>CyclicQueue</code> knows how to use it. I would strongly suggest making this private (also, if it is public, it should ideally following the <code>ProperCamelCase</code> naming conventions like your other public members).</p>\n\n<p>Since this is a non-resizing queue, the <code>MaxSize</code> probably ought to be public information. I'd also consider making it <code>MaxSize => _buffer.Length</code> to reduce redundancy. You could also make <code>_buffer</code> readonly to signal it's not meant to be changed to the maintainers.</p>\n\n<h2>Correctness</h2>\n\n<p>I'm not sure the <code>_size > 0</code> check in <code>Enqueue</code> works. Consider a sequence of <code>Enqueue</code>, (<code>Dequeue</code>, <code>Enqueue</code>)<code>*n</code> on a newly created <code>CyclicQueue</code>: this will leave <code>_end = 0</code> while <code>_start</code> is incremented. I think this can be resolved by setting <code>_end = _maxSize - 1</code> in the constructor and removing the check.</p>\n\n<h2>Misc/Boring Stuff</h2>\n\n<ul>\n<li><p>You could do with a little more white-space between things... at the very least, be consistent with your between-member spacing.</p></li>\n<li><p>You could do with tests which test the exceptions (i.e. checking it throws if you try to enqueue/dequeue too many things.</p></li>\n<li><p>As always, inline-documentation would be appreciated. This should describe the non-resizing nature of the queue, when it throws exceptions, and resolve the confusion concerning whether <code>Front</code> is an index or element.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T21:18:22.913",
"Id": "424826",
"Score": "1",
"body": "I always like and appreciate your reviews! Thanks again"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T20:48:43.937",
"Id": "219891",
"ParentId": "219887",
"Score": "9"
}
},
{
"body": "<p>Wouldn't it be possible to calculate the <code>_end</code> as </p>\n\n<pre><code> private int End => (_start + _size) % _maxSize;\n</code></pre>\n\n<p>so you only have to update <code>_start</code> and <code>_size</code> and then omit <code>_end</code>?</p>\n\n<p><code>Enqueue</code> will then look as:</p>\n\n<pre><code> public void Enqueue(T newValue)\n {\n\n if (_size == _maxSize)\n {\n throw new InvalidOperationException(\"Queue at full capacity\");\n }\n\n _buffer[End] = newValue;\n _size++;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T07:21:48.100",
"Id": "219911",
"ParentId": "219887",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219891",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:34:58.590",
"Id": "219887",
"Score": "7",
"Tags": [
"c#",
"programming-challenge",
"queue",
"circular-list"
],
"Title": "Cyclic queue using an array"
} | 219887 |
<p>I've got this simple ring/circular buffer class:</p>
<pre><code>template<class T, size_t sz>
class CircularBuffer {
std::array<T, sz> buffer;
size_t head;
size_t tail;
bool isFull;
public:
CircularBuffer() :
head{0},
tail{0},
isFull{false} {
}
void put(T item) {
buffer[head] = item;
head = (head + 1) % sz;
if (isFull) {
tail = (tail + 1) % sz;
}
isFull = head == tail;
}
T get() {
auto result = buffer[tail];
tail = (tail + 1) % sz;
isFull = false;
return result;
}
bool empty() const {
return tail == head;
}
size_t capacity() const {
return sz;
}
size_t size() const {
if (isFull)
return sz;
if (head >= tail)
return head - tail;
return sz + head - tail;
}
};
</code></pre>
<p>And I was looking for clarification on a few things, to take advantage of C++ features.</p>
<p>First, the new <code>constexpr</code> keyword, what here, if anything should I apply it to? (I'm assuming the <code>size_t size() const</code> member function could use it? Anything else?)</p>
<p>Second, all of these member functions are quite small, should they be <code>inlined</code>?</p>
<p>Third, in the <code>T get()</code> member function, I do <code>auto result = buffer[tail];</code>, should I use <code>auto&</code> instead, or any other versions? (or even just <code>T</code>/<code>T&</code>?) Should that be a const as it's not modified within the function, and only potentially modified once a copy is returned via the functions return parameter.</p>
<p>Any other feedback is welcome!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:48:19.990",
"Id": "424817",
"Score": "1",
"body": "Relevant: [*Titling your question*](https://codereview.stackexchange.com/help/how-to-ask) in the Help Center."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:48:26.520",
"Id": "424818",
"Score": "0",
"body": "@yuri I don't really care about this specific classes implementation, rather I'm trying to understand why/when to use keywords etc. The class itself is irrelevant and instead just being used as an example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:50:43.037",
"Id": "424819",
"Score": "0",
"body": "@AlexV What would you title it if the question isn't about the class code, and instead about the c++ features I'm asking about? Because I could put any class code in the example, the questions would remain the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:55:18.130",
"Id": "424821",
"Score": "3",
"body": "\"General purpose questions\" are IMHO not suited for Code Review. As the Help Center puts it: \"In order to give good advice, we need to see real, concrete code, and understand the context in which the code is used. Generic code [...] leaves too much to the imagination.\" ([source](https://codereview.stackexchange.com/help/on-topic))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T21:10:40.137",
"Id": "424825",
"Score": "8",
"body": "Since you are asking to take advantage of language features, please specify what version of C++ you are targeting."
}
] | [
{
"body": "<h1>Interface</h1>\n<h2>Naming</h2>\n<p>Functions returning a <code>bool</code> should be phrased as a question. <code>empty</code> should be <code>is_empty</code> instead. Yes, the standard library does it wrong too, leading to confusion like "I used <code>vector.empty();</code>, but it didn't empty my vector. Why?"<br />\n<code>get</code> should be <code>pop</code> or <code>pop_get</code>. Getters are not supposed to change the object.<br />\nNote that it is impossible to write <code>get</code> with the <a href=\"https://en.cppreference.com/w/cpp/language/exceptions\" rel=\"nofollow noreferrer\">strong exception guarantee</a>, which is the reason why <code>std::vector::pop_back</code> returns <code>void</code> instead of the element.</p>\n<h2><code>constexpr</code></h2>\n<p>Currently you can mark all your functions <code>constexpr</code>. Sometimes it is possible to evaluate the result of your <code>CircularBuffer</code> at compile time. That probably rarely comes up, but there is no good reason not to do it (yet).</p>\n<h2>Generality</h2>\n<h3>Type restrictions</h3>\n<p>There are limits for what <code>T</code>s I can use your <code>CircularBuffer</code> with. <code>T</code> must be copyable and default constructible. That means I cannot use a <code>struct Foo{ Foo(int); };</code> or a <code>std::unique_ptr<int></code>. Arguably those should be allowed.</p>\nMove-Only\n<p>Supporting move-only types is possible by using <code>std::move</code> in the appropriate spots, mainly <code>buffer[head] = std::move(item);</code> and <code>auto result = std::move(buffer[tail]);</code>. Just try to use a <code>CircularBuffer<std::unique_ptr<int>></code> and the compiler will tell you about each spot.</p>\nNon-Default-Constructible\n<p>To be able to use <code>CircularBuffer<Foo></code> you would need to delay constructing objects until the user uses <code>put</code>. You can achieve that by changing <code>std::array<T, sz> buffer;</code> to <code>alignas(alignof(T)) std::array<char, sz * sizeof(T)> buffer;</code>. That way no <code>T</code>s are default constructed. When you add an element in <code>put</code> you have to placement <code>new</code> the element: <code>new (&buffer[head * sizeof(T)]) T(std::move(item));</code>. <code>get</code> then has to call <code>std::destroy_at(reinterpret_cast<T*>(&buffer[tail * sizeof(T)]));</code> (or just call the destructor). This makes things more complicated and also <code>reinterpret_cast</code> and <code>new</code> are not <code>constexpr</code>.</p>\nBrick Types\n<p>Some types like <code>std::mutex</code> cannot be copied or moved, but you could still support them. To do that, offer an <code>emplace</code> function similar to <code>std::vector::emplace_back</code> that constructs the <code>T</code> in place from a given list of arguments.</p>\n<h2><code>get</code> Return Type</h2>\n<p>Returning a <code>T</code> by value seems reasonable. You are taking out the element. Returning a <code>T &</code> instead seems dangerous, because usage of the buffer will eventually change the value you got. Maybe add 2 <code>peek</code> functions instead that return a reference to the current object without removing it. One of the functions would be <code>T &peek()</code> and the other <code>const T &peek() const</code>.</p>\n<h1>Bugs</h1>\n<h2><code>empty</code> When Full</h2>\n<pre><code>CircularBuffer<int, 3> b;\nb.put(1);\nb.put(2);\nb.put(3);\nstd::cout << std::boolalpha << b.empty();\n</code></pre>\n<p>That should really not print <code>true</code>.</p>\n<h2>Over- and Underflow</h2>\n<p>If I <code>put</code> more items into the buffer than it has space it silently overwrites objects. If I try to <code>get</code> items without putting items in, it simply returns uninitialized objects which is undefined behavior for builtins. This is my fault for using your container incorrectly, but you could be nice and add an <code>assert</code> so that I can find my bug easier.</p>\n<h2><code>inline</code></h2>\n<p>Your functions are already implicitly marked <code>inline</code> which changes the linkage and has nothing to do with inlining. Whether inlining is the right choice is a complicated case-by-case question that you should leave to your compiler. Only use <a href=\"https://en.cppreference.com/w/c/language/inline\" rel=\"nofollow noreferrer\"><code>inline</code></a> to mean "I want internal linkage", which you can also do for variables since C++17.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:27:44.857",
"Id": "424937",
"Score": "3",
"body": "It is highly questionable to suggest naming conventions that arecontradictory to standard practices demonstrated by the standard (e.g `empty` vs `is_empty`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T19:20:45.573",
"Id": "424958",
"Score": "0",
"body": "Thanks for taking the time to go in depth on everything, I guess I should clarify why I hadn't put anything in place to support different types of T, currently the code was only being used by another data-structure that only uses unsigned ints with it, as far as the get and put, those are also both only called by the data structure so i hadn't really bothered to make it very client facing friendly. That said, thanks for catching the empty bug. Out of curiosity, would adding all the extra stuff to support all the other types, add much overhead? I'm trying to keep this as fast as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T19:39:20.203",
"Id": "424959",
"Score": "0",
"body": "also what do you mean with \"When you add an element in put you have to placement new the element: `new &buffer[head * sizeof(T)] T(std::move(item));`.\" I'm not sure how that code is supposed to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T07:30:27.607",
"Id": "425008",
"Score": "0",
"body": "When you use `new` it normally allocates dynamic memory, constructs an object of given type with given arguments there and returns a pointer to that object. But you can optionally provide memory instead. (I messed up the syntax and forgot the parenthesis around the address). That way it constructs an object in the given memory without needing dynamic memory allocation. It's only needed if you have need a memory buffer that sometimes contains objects and sometimes doesn't, which is the case here if you decide to support creating and destroying objects as needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T07:31:20.630",
"Id": "425009",
"Score": "0",
"body": "As for the performance of [placement new](https://en.cppreference.com/w/cpp/language/new#Placement_new), the constructor and destructor for `unsigned int` don't do anything at runtime, so there should be no difference. Technically you are not allowed to access objects that don't exist, so you can't just cast the address of `buffer` to a `T *` and access the `T` that isn't there. That also applies to `unsigned int`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:05:59.240",
"Id": "425017",
"Score": "0",
"body": "@miscco \"standard practice\" is to use question phrasing (`is_empty`). Just because part of the C++ standard library does something is no reason to recommend doing the same (c.f. the naming in the iostreams part of the library)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:30:10.737",
"Id": "425062",
"Score": "0",
"body": "@user673679 I believe that this is a problem with programmers blaming others for their own mistakes. There is no qualitative difference between `empty` and `size` both describe the state of the object in question. If you go down the \"boolean return value should be a verb\" then you would also need to go for `getSize` and `getCapacity`. Btw the phrasing `empty` for removing elements from the container would be semantically much worse than `clear`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:35:10.553",
"Id": "425064",
"Score": "0",
"body": "@miscco There is a difference. `empty` is ambiguous. It could ask if the container is empty or empty it. `size` is not ambiguous. It tells you the size. The command would be `resize` or at least require a parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:47:15.737",
"Id": "425066",
"Score": "0",
"body": "@miscco Yeah, I'd say `getSize()` and `getCapacity()` are also better names. Using a verb can help to distinguish other things too, e.g. returning something that's instantly accessible (`getFoo()`) and performing an operation that might have a significant performance impact (`calculateFoo()`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T04:11:14.937",
"Id": "426110",
"Score": "0",
"body": "@nwp So I've been adding the functionality you mentioned above, and one thing i'm unsure of, what's the proper order for the cleanup in the \"get\" function, would it be something along the lines of `auto location = reinterpret_cast<T*>(&buffer[tail * sizeof(T)]); auto result = std::move(*location); std::destroy_at(location);`? The I know that the destroy would only be called on the copy that is at the memory location in the buffer, but would the use of \"move\" here cause problems? Thanks in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T09:12:23.740",
"Id": "426143",
"Score": "0",
"body": "@HexCrown Seems reasonable. First you move the object out and then you destroy the old object. What C++ calls \"moving\" is just a copy that steals resources from the original. But the original still exists in a valid state, so you can destruct it without problems."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:47:44.923",
"Id": "219926",
"ParentId": "219888",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "219926",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:42:45.537",
"Id": "219888",
"Score": "1",
"Tags": [
"c++",
"circular-list"
],
"Title": "Simple ring/circular buffer C++ class"
} | 219888 |
<blockquote>
<p>You are given a data structure of employee information, which includes
the employee's unique id, his importance value and his direct
subordinates' id.</p>
<p>For example, employee 1 is the leader of employee 2, and employee 2 is
the leader of employee 3. They have importance value 15, 10 and 5,
respectively. Then employee 1 has a data structure like [1, 15, [2]],
and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note
that although employee 3 is also a subordinate of employee 1, the
relationship is not direct.</p>
<p>Now given the employee information of a company, and an employee id,
you need to return the total importance value of this employee and all
his subordinates.</p>
<p>Example 1:</p>
<p>Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 Output: 11
Explanation: Employee 1 has importance value 5, and he has two direct
subordinates: employee 2 and employee 3. They both have importance
value 3. So the total importance value of employee 1 is 5 + 3 + 3 =
11. </p>
<p>Note:</p>
<p>One employee has at most one direct leader and may have several
subordinates. The maximum number of employees won't exceed 2000.</p>
</blockquote>
<p>Please comment about performance.</p>
<pre><code>using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
/// <summary>
/// https://leetcode.com/problems/employee-importance/
/// </summary>
[TestClass]
public class EmployeeImportanceBFS
{
[TestMethod]
public void ChildrenSumTo30Test()
{
List<Employee> employees = new List<Employee>();
Employee one = new Employee { Id = 1, Importance = 15 };
Employee two = new Employee { Id = 2, Importance = 10 };
one.Subordinates.Add(two.Id);
Employee three = new Employee { Id = 3, Importance = 5 };
two.Subordinates.Add(three.Id);
employees.Add(one);
employees.Add(two);
employees.Add(three);
Assert.AreEqual(30, GetImportance(employees, 1));
}
[TestMethod]
public void ChildrenSumTo11Test()
{
List<Employee> employees = new List<Employee>();
Employee one = new Employee { Id = 1, Importance = 5 };
Employee two = new Employee { Id = 2, Importance = 3 };
Employee three = new Employee { Id = 3, Importance = 3 };
one.Subordinates.Add(three.Id);
one.Subordinates.Add(two.Id);
employees.Add(one);
employees.Add(two);
employees.Add(three);
Assert.AreEqual(11, GetImportance(employees, 1));
}
int GetImportance(IList<Employee> employees, int id)
{
Dictionary<int, Employee> idToEmployee = new Dictionary<int, Employee>();
foreach (var employee in employees)
{
idToEmployee.Add(employee.Id, employee);
}
int result = 0;
if (employees == null || employees.Count == 0)
{
return result;
}
Queue<Employee> Q = new Queue<Employee>();
Q.Enqueue(idToEmployee[id]);
while (Q.Count > 0)
{
var current = Q.Dequeue();
result += current.Importance;
foreach (var childIdSubordinate in current.Subordinates)
{
if (idToEmployee.ContainsKey(childIdSubordinate))
{
Q.Enqueue(idToEmployee[childIdSubordinate]);
}
}
}
return result;
}
}
// Employee info
class Employee
{
public Employee()
{
Subordinates = new List<int>();
}
// It's the unique ID of each node.
// unique id of this employee
public int Id { get; set; }
// the importance value of this employee
public int Importance { get; set; }
// the id of direct subordinates
public List<int> Subordinates { get; set; }
}
}
</code></pre>
| [] | [
{
"body": "<p>You'll have to have this check before the initialization of the dictionary:</p>\n\n<blockquote>\n<pre><code> if (employees == null || employees.Count == 0)\n {\n return 0;\n }\n</code></pre>\n</blockquote>\n\n<p>or else the initialization of the dictionary may throw if <code>employees == null</code></p>\n\n<hr>\n\n<p>You can initialize the dictionary this way:</p>\n\n<pre><code>Dictionary<int, Employee> idToEmployee = employees.ToDictionary(e => e.Id);\n</code></pre>\n\n<hr>\n\n<p>Instead of:</p>\n\n<blockquote>\n<pre><code>if (idToEmployee.ContainsKey(childIdSubordinate))\n {\n Q.Enqueue(idToEmployee[childIdSubordinate]);\n }\n</code></pre>\n</blockquote>\n\n<p>You can do:</p>\n\n<pre><code> if (idToEmployee.TryGetValue(childIdSubordinate, out Employee subordinate))\n {\n Q.Enqueue(subordinate);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T12:45:58.697",
"Id": "424886",
"Score": "0",
"body": "I think the `TryGetValue` needs explanation that it's not just an alternative technique but is more efficient since it queries the dictionary once instead of twice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:07:45.667",
"Id": "424888",
"Score": "0",
"body": "@RickDavin: One should think so, but according to the [reference](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,2e5bc6d8c0f21e67,references) it actually does the same as when using `ContainsKey etc.` - it just combines them into one method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:40:39.150",
"Id": "424926",
"Score": "1",
"body": "@HenrikHansen it only calls `FindEntry` once, which is the expensive bit. (As opposed to calling `ContainsKey` and `this[TKey]` which both call it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:46:23.250",
"Id": "424928",
"Score": "1",
"body": "@RickDavin: You're right - I didn't check `this[]`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T08:19:34.607",
"Id": "219914",
"ParentId": "219890",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "219914",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T20:46:30.093",
"Id": "219890",
"Score": "2",
"Tags": [
"c#",
"programming-challenge",
"breadth-first-search"
],
"Title": "LeetCode: Employee-importance BFS"
} | 219890 |
<p>I have a task connected with reinforcement learning. The state of my environment is described with the class below:</p>
<pre><code>from dataclasses import dataclass
from typing import Tuple
@dataclass
class LearningState:
pre_cross_densities: Tuple[int]
global_aggregated_densities: Tuple[int]
phase_no: int
phase_duration: int
</code></pre>
<p>I need the following behaviour (*):</p>
<pre><code>state_1 = LearningState(pre_cross_densities=(0, 4, 5), global_aggregated_densities=(2, 4, 5), phase_no=2, phase_duration=1)
different_state = LearningState(pre_cross_densities=(0, 4, 5), global_aggregated_densities=(2, 4, 8), phase_no=2, phase_duration=1)
state_1_also = LearningState(pre_cross_densities=(0, 4, 5), global_aggregated_densities=(2, 4, 5), phase_no=2, phase_duration=1)
myDic = {state_1: [2], different_state: [7]}
myDic[state_1_also].append(6)
print(myDic[state_1]) # prints [2, 6]
</code></pre>
<p>So the dictionary needs to see <code>state_1</code> and <code>state_1_also</code> as the same key. Also objects cannot be keys without a __hashable_ method implementation. To overcome these two problems I have created the following decorator.</p>
<pre><code>def hashable(*args):
def wrapper(cls):
setattr(cls, '__hash__', eval('__hash__'))
setattr(cls, '__eq__', eval('__eq__'))
return cls
return wrapper
def __hash__(self):
all_properties = [prop for prop in self.hash_keys if not prop.startswith('__')]
values = tuple([getattr(self, prop) for prop in all_properties])
return hash(values)
def __eq__(self, other):
return self.__hash__() == other.__hash__()
</code></pre>
<p>Now I can write my class with the decorator and hash_keys properties as follows:</p>
<pre><code>from dataclasses import dataclass
from typing import Tuple
from services.hashable_decorator import hashable
@hashable()
@dataclass
class LearningState:
pre_cross_densities: Tuple[int]
global_aggregated_densities: Tuple[int]
phase_no: int
phase_duration: int
hash_keys = ['pre_cross_densities', 'global_aggregated_densities', 'phase_no', 'phase_duration']
</code></pre>
<p>Code provides a (*) behaviour, but I feel like this is a sculpture. There will be a lot of data and I am also afraid about the performance couse there is a lot of immutable data.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:01:53.880",
"Id": "424891",
"Score": "2",
"body": "If your state is immutable, you can use `@dataclass(eq=True, Frozen=True)`, then Python makes a hash function for you. If your class is mutable, you shouldn't use it as the key in a dict"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T21:46:58.877",
"Id": "219892",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Pythonic way to store rewards of states"
} | 219892 |
<p>just a little script, or a bit of a template of one that I used to submit an assignment.<br />
I believe it all works fine, I just wanted to give it to other people, and get some feedback on it; maybe make some improvements. I have several variations of the main <code>check_hash</code> function. I've included two of them here today and it's the main element that I'd like some feedback on. Not necessarily just for the sake of this one script, but more to help me design/write better scripts in the future.</p>
<p>I couldn't really decide if I ought to hardcode the variables in place (like variation #1), or make them more modular and have the take arguments (like variation #2). You can have static values like I have here, or you could <code>read</code> values in to the script or accept positional parameters or adapt it however you like.</p>
<p>Some bits have been commented out. I just used them while testing bits and pieces, and thought i'd leave them there for quick debugging in the future. You probably want to know about <code>md5</code> vs <code>md5sum</code>: I was taking a class on on Unix & C Programming, where we use a bunch of different UNIX-based systems. Some (macOS, most notably), don't have a native <code>md5sum</code> utility, but they have a similar utility just called <code>md5</code>. So that's all that is.</p>
<p>It's not really supposed to be some kind of security / protection mechanism, It's more just to verify file integrity and ensure it's not corrupt.</p>
<h1>preamble</h1>
<pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash
directory='2CvAwTx'
tarball="$directory.tar.gz"
md5='135c72bc1e201819941072fcea882d6f'
sha='318e96fd35806cd008fe79732edba00908fcbeff'
</code></pre>
<hr />
<h1>check_hash function</h1>
<h3>variant #1</h3>
<pre class="lang-bsh prettyprint-override"><code>################################################################################
check_hash ()
{
############################################################################
check_md5 ()
{
if [[ "$(command -v md5)" ]];
then [[ "$(md5 ./"$tarball" | awk '{print $4}')" == "$md5" ]] ;
elif [[ "$(command -v md5sum)" ]];
then [[ "$(md5sum ./"$tarball" | awk '{print $1}')" == "$md5" ]] ;
fi
}
############################################################################
check_sha ()
{
[[ "$(shasum ./"$tarball" | awk '{print $1}')" == "$sha" ]] ;
}
############################################################################
check_md5 "$@" ||
check_sha "$@" ;
}
################################################################################
# check_hash &&
# printf '%s\n' 'true' ||
# printf '%s\n' 'false' ;
</code></pre>
<h3>variant #2</h3>
<pre class="lang-bsh prettyprint-override"><code>################################################################################
check_hash ()
{
############################################################################
check_md5 ()
{
if [[ "$(command -v md5)" ]] ;
then read -r hash _ < <(md5 -q "$1") ;
[[ $hash == "$2" ]] ;
elif [[ "$(command -v md5sum)" ]] ;
then read -r hash _ < <(md5sum "$1") ;
[[ $hash == "$2" ]] ;
fi
}
############################################################################
check_sha ()
{
read -r hash _ < <(shasum "$1") ;
[[ $hash == "$2" ]] ;
}
############################################################################
check_md5 "$@" ||
check_sha "$@" ;
}
################################################################################
# check_hash ./"$tarball" "$md5" ||
# check_hash ./"$tarball" "$sha" &&
# printf '%s\n' 'true' ||
# printf '%s\n' 'false' ;
</code></pre>
<hr />
<h1>the part where the things do the stuff</h1>
<pre class="lang-bsh prettyprint-override"><code>wget "http://www.example.com/$tarball" &&
check_hash "$tarball" "$md5" &&
tar -xzf "$tarball" &&
cd "$directory" &&
make && make clean &&
./a.out
</code></pre>
| [] | [
{
"body": "<p>Functions inside of functions have global scope unless you declare the outer one with parens, like <code>func() ( ... )</code>. </p>\n\n<p>You can avoid filenames in the output with <code><</code> input redirection. md5sum and sha1sum will print <code>-</code> for the filename; testing with a regex allows us to ignore that.</p>\n\n<p>The encompassing logic is \"try these things until one works,\" so just do that.</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>check_hash() { \n for sum in md5 md5sum shasum\n do \n [[ $( $sum <\"$1\" ) =~ ^$2\" \"*-?$ ]] && return 0 \n done 2>/dev/null\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-25T23:05:27.967",
"Id": "427176",
"Score": "0",
"body": "I didn't know `=` is different from `==`! Do you have a reference for that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-26T06:43:19.743",
"Id": "427219",
"Score": "0",
"body": "turns out that it isn't! I probably got the idea from an [old version of the manual](http://bashdb.sourceforge.net/bashref.html#IDX42) where it was worded like they are different: _When the '==' and '!=' operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below / ... / [== means] True if the strings are equal. '=' may be used in place of '==' for strict POSIX compliance._ Current manuals make clear that `=` and `==` are the same thing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T23:36:10.300",
"Id": "219895",
"ParentId": "219893",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T22:19:47.027",
"Id": "219893",
"Score": "3",
"Tags": [
"validation",
"bash",
"unix",
"sh",
"checksum"
],
"Title": "checksum hash verification functions for bash scripts"
} | 219893 |
<p>I have implemented a sample program that converts vector of characters to its integer representation depending on the bit size specified. I was hoping to get some input on how to simplify the sequence. I think my approach is convoluted.</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <vector>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <iterator>
int OctalToBinary(int octalNum) {
int decimalNum = 0, binaryNum = 0, count = 0;
while (octalNum != 0) {
decimalNum += (octalNum % 10) * pow(8, count);
++count;
octalNum /= 10;
}
count = 1;
while (decimalNum != 0) {
binaryNum += (decimalNum % 2) * count;
decimalNum /= 2;
count *= 10;
}
return binaryNum;
}
int main()
{
std::vector<char> buffer = { '3','7','4','3','0'};
std::vector<int> bitsize = { 3,3,8 };
std::vector<char> collection;
std::vector<std::string> output;
// convert characters to octal and
for each ( char c in buffer)
{
int x = c - '0';
std::stringstream opt;
opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << "\n";
std::string val = opt.str();
std::copy(val.begin(), val.end()-1, std::back_inserter(collection));
}
int start_index = 0;
int end_index = 0;
// convert binary values to integer
for (int i = 0; i < bitsize.size(); i++)
{
start_index = end_index;
end_index += bitsize[i];
std::string temporary_string(collection.begin() + start_index, collection.begin() + end_index);
int converted_integer = std::stoi(temporary_string.c_str(), nullptr, 2);
std::cout << temporary_string << " " << converted_integer << "\n";
}
// output should be 3, 7 , 140
int x;
std::cin >> x;
return 0;
}
</code></pre>
| [] | [
{
"body": "<p><strong>Unnecessary Headers</strong><br>\nThe #includes for iterator and bitset are not needed, the code compiles fine without them, iterator may be included indirectly through vector.</p>\n\n<p>Adding unnecessary headers can increase compile/build times and may cause other problems in larger more complex programs.</p>\n\n<p><strong>Portability</strong><br>\nThis program is currently not portable for 2 reasons, the use of the Visual Studio generated <code>#include \"stdafx.h\"</code> and the use of the non-standard for each loop. It might be better to embed <code>#include \"stdafx.h\"</code> within ifdef/endif.</p>\n\n<pre><code>#ifdef windows\n#include \"stdafx.h\"\n#endif\n</code></pre>\n\n<p>I compiled this in Visual Studio 2017 on Windows 10 and it actually reported a compile error on the for each loop. The suggested fix was to use a range based for loop.</p>\n\n<pre><code>1>------ Build started: Project: octbinintconv0, Configuration: Debug Win32 ------\n1>octbinintconv0.cpp\n1>d:\\projectsnfwsi\\codereview\\octbinintconv0\\octbinintconv0\\octbinintconv0.cpp(18): warning C4244: '+=': conversion from 'double' to 'int', possible loss of data\n1>d:\\projectsnfwsi\\codereview\\octbinintconv0\\octbinintconv0\\octbinintconv0.cpp(40): error C4496: nonstandard extension 'for each' used: replace with ranged-for statement\n1>d:\\projectsnfwsi\\codereview\\octbinintconv0\\octbinintconv0\\octbinintconv0.cpp(55): warning C4018: '<': signed/unsigned mismatch\n1>Done building project \"octbinintconv0.vcxproj\" -- FAILED.\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========\n</code></pre>\n\n<p>You might want to replace the <code>for each</code> loop with the following code, which uses an iterator and is part of standard C++.</p>\n\n<pre><code> for (auto c : buffer)\n {\n int x = c - '0';\n std::stringstream opt;\n opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << \"\\n\";\n\n std::string val = opt.str();\n\n std::copy(val.begin(), val.end() - 1, std::back_inserter(collection));\n }\n</code></pre>\n\n<p><strong>Type Mismatches</strong><br>\nA good practice is treating warning messages as errors, since they point to potential logic errors. The <code>pow()</code> function returns double and the result is being truncated, it might be better to use a static cast in the code to show that this is intentional.</p>\n\n<pre><code> decimalNum += (octalNum % 10) * static_cast<int>(pow(8, count));\n</code></pre>\n\n<p>In this for loop it would be better to define the local variable <code>i</code> as <code>size_t</code> rather than int, in any of the STL container classes the function <code>size()</code> returns size_t.</p>\n\n<pre><code> for (size_t i = 0; i < bitsize.size(); i++)\n</code></pre>\n\n<p><strong>Complexity</strong><br>\nCreating the function <code>OctalToBinary(int octalNum)</code> was good but there are two more functions that <code>main()</code> can be broken up into, they have even been identified by comments, both of the for loop are good candidates for functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:17:58.027",
"Id": "219927",
"ParentId": "219894",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T22:39:12.510",
"Id": "219894",
"Score": "3",
"Tags": [
"c++",
"serialization",
"number-systems"
],
"Title": "Convert characters to octal, binary, and integer"
} | 219894 |
<p>How can I pass data from database to my HTML template without putting PHP code in my HTML file.</p>
<p>Thanks.</p>
<p>This is my controller</p>
<pre><code>public function index($aRequest)
{
$oModel = new todoModel();
$aTodoList = $oModel->getTodoList();
return array('type' => 'view', 'view' => 'view/index.tpl', 'data' =>
array('aTodoList' => $aTodoList));
}
</code></pre>
<p>my Model</p>
<pre><code>public function getTodoList()
{
$aTodoList = [];
$this->oConnection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sQuery = 'SELECT * FROM t_todolist';
foreach ($this->oConnection->query($sQuery) as $aTodo) {
array_push($aTodoList, array(
'sequence' => $aTodo['sequence'],
'todo' => $aTodo['todo']
));
}
print_r($aTodoList);
return $aTodoList;
}
</code></pre>
<p>my tpl -(this is working but it has php code inside)</p>
<pre><code><div id="todo_list">
<ul id="todo_list_ul">
<?php
foreach ($aTodoList as $aTodo) {
?>
<!-- list here -->
<li><?php echo $aTodo['todo'];?> <a href=""
class="todo_update">update</a> <a class="todo_delete" href="">delete</a></li>
<?php
}
?>
</ul>
<button id="todo_create">create</button>
</div>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T07:49:10.557",
"Id": "424849",
"Score": "0",
"body": "What is the *acrual* problem with PHP code inside?"
}
] | [
{
"body": "<p>First, let me review some of of the code you have</p>\n\n<pre><code>public function getTodoList()\n{\n return $this->oConnection->query('SELECT * FROM t_todolist')->fetchAll();\n}\n</code></pre>\n\n<p>This is actually all the code you need for this task. Just one line. Thanks PDO being not an ordinary database driver like mysqli. You can check other PDO wonders in my <a href=\"https://phpdelusions.net/pdo\" rel=\"nofollow noreferrer\">article</a></p>\n\n<p>There is also one important issue that should be fixed in the controller</p>\n\n<pre><code>public function index($aRequest)\n{\n $connection = new Database; // whatever you have to supply a database connection\n $oModel = new todoModel($connection);\n $aTodoList = $oModel->getTodoList();\n return ['type' => 'view', 'view' => 'view/index.tpl', 'data' => \n ['aTodoList' => $aTodoList]];\n}\n</code></pre>\n\n<p>You may check the above article in order to learn why it is very important to create a database connection only once instead of making each model to create its own.</p>\n\n<p>Now, to the template.</p>\n\n<p>First off, there is <strong>absolutely nothing wrong</strong> with having some PHP code in a template. PHP is a template language after all, and a good one. All you need is to keep an eye on your template and make sure that all PHP code does in it is actually related to the output only. You can only make it a bit prettier and safer</p>\n\n<pre><code><ul id=\"todo_list_ul\">\n<?php foreach ($aTodoList as $aTodo): ?>\n <!-- list here -->\n <li>\n <?= htmlspecialchars($aTodo['todo']) ?>\n <a href=\"\" class=\"todo_update\">update</a> <a class=\"todo_delete\">\n delete\n </a>\n </li>\n<?php endforeach ?>\n</ul>\n</code></pre>\n\n<p>However, to answer your question literally, you will need a <strong>dedicated template engine</strong>, like <a href=\"https://twig.symfony.com/doc/2.x/intro.html#installation\" rel=\"nofollow noreferrer\">Twig</a>. Twig has many good features compared to raw PHP. One of them is <strong>autoescaping</strong>. There is one critical flaw in your current template, namely </p>\n\n<pre><code><li><?php echo $aTodo['todo'];?>\n</code></pre>\n\n<p>The moment a malicious user will put some bad Javascript in the todo description, your site will be hacked. So you have to escape HTML when echoing a variable. </p>\n\n<p>Unlike PHP, Twig escapes your values automatically, so a code </p>\n\n<pre><code><ul id=\"todo_list_ul\">\n{% for aTodo in aTodoList %}\n <li>\n {{ aTodo.todo }}\n <a href=\"\" class=\"todo_update\">update</a> <a class=\"todo_delete\">\n delete\n </a>\n </li>\n{% endfor %}\n</ul>\n</code></pre>\n\n<p>will be automatically protected from XSS</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T08:05:41.223",
"Id": "219913",
"ParentId": "219898",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219913",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T00:35:44.740",
"Id": "219898",
"Score": "2",
"Tags": [
"php",
"jquery",
"ajax",
"pdo"
],
"Title": "Passing data to HTML template"
} | 219898 |
<p>I need to get some information about the <strong>Pascal Triangle</strong>.</p>
<p>What is a pascal triangle ?</p>
<blockquote>
<p><strong>It is a triangle of integers with 1 at the top and at the sides. Any number inside is equal to the sum of the two numbers above his. For
example, here are the first 5 lines of the triangle</strong>:</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/GMBb5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GMBb5.png" alt="Pascal Triangle"></a></p>
<p>So I need to figure out the number of numbers
pairs that exist in the <strong>first thousand lines</strong> of the triangle.</p>
<p>I would like to know how I can improve the performance of my code or rewrite some part that is poorly structured</p>
<pre class="lang-java prettyprint-override"><code>import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;
public class PascalTriangle {
private static int [][] matrix;
private static int i, j, n;
public static void main(String[] args)
{
long start_time = System.currentTimeMillis();
n = 0; // Number of even numbers;
matrix = new int[1000][1000];
for (i = 0; i < 1000; i++) {
for (j = 0; j < 1000; j++) {
matrix[i][j] = 0;
}
}
matrix[0][0] = 1;
matrix[1][0] = 1;
matrix[1][1] = 1;
for (i = 2; i < 1000; i++) {
matrix[i][0] = 1;
matrix[i][i] = 1;
for (j = 1; j < i; j++) {
matrix[i][j] = matrix[i-1][j-1]+matrix[i-1][j];
if ( matrix[i][j] % 2 == 0 ) {
n++;
}
}
}
System.out.println( "Amount of even numbers = " + n );
long end_time = System.currentTimeMillis();
System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end_time - start_time)));
}
}
</code></pre>
<p><strong>Expected result:</strong></p>
<pre><code>Amount of even numbers = 448363
</code></pre>
<p>Currently taking a time of <strong>00.011 seconds</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:18:41.613",
"Id": "425060",
"Score": "0",
"body": "Are you really calculating what you're asked to calculate? I understand \"number of number pairs\" to mean how many numbers in one line are duplicated. So, for example, line 2 has 1 pair (1 and 1 are a pair). Line 3 has 1 pair (1 and 1 are paired but the 2 isn't), while line 4 has 2 pairs (a pair of 1s and a pair of 3s). You seem to be looking for even numbers instead."
}
] | [
{
"body": "<h1>One array solution</h1>\n<p>The following algorithm is an improvement on the two array system stated bellow it. Basically, we only need the context of the old previous value (as well as the next value, which goes unmodified), so we copy this value. From there we can set the new end to <code>1</code> then start over. This cuts down on the memory overhead. I think you'll see minimal computational improvements as yours was already pretty efficient, but this one takes less memory. I suspect there will be a performance increase where you are dealing with pretty large arrays.</p>\n<pre><code>import java.util.Arrays;\n\nclass Pascal{\n\n public static void main(String []args) {\n int toNthLine = 1000;\n int[] row = new int[toNthLine+1];\n int counter = 0;\n int previous;\n row[0] = 1;\n for (int i = 0; i < toNthLine; i++) {\n previous = 1;\n for (int j = 0; row[j+1] != 0; j++) {\n int temp = row[j+1];\n row[j+1] = previous + row[j+1];\n previous = temp;\n if (row[j+1] % 2 == 0)counter++;\n }\n row[i] = 1;\n }\n System.out.println(counter);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T02:49:15.110",
"Id": "219906",
"ParentId": "219900",
"Score": "3"
}
},
{
"body": "<p>There is one fairly obvious optimization that should cut your time in roughly half. Pascal's Triangle is symmetric. Take advantage of that with whatever algorithm you are using. Roughly speaking (without checking my end-conditions so do that):</p>\n\n<pre><code>for (j=1;j<i/2;j++)\n{\n value = matrix[i-1][j-1] + matrix[i-1][j];\n matrix[i][j] = matrix[i][i-j] = value;\n if (value % 2 == 0) \n n+=2;\n}\nif ((2*j==i) && (value%2 == 0))\n n--;\n</code></pre>\n\n<p>This also shows some minor optimizations that may gain you time. Saving the new value in a separate variable so that you aren't dereferencing the array subscripts repeatedly, especially the check I added outside the loop, should save a little time. The check outside is because most of the way through the half row you want to count two for every even number, but on the specific end condition in the rows with an odd number of values you will double count it and have to subtract it out again. Do that outside the loop to avoid an if statement inside the loop.</p>\n\n<p>@Neil suggested using two arrays instead of a two dimensional array. That may gain you savings by allowing you to set a variable to row1[i] outside the while loop to avoid double subscripting throughout the j loop. However a good compiler may do that optimization for you. Try it with and without.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:56:43.537",
"Id": "424919",
"Score": "0",
"body": "It should also be possible to optimize the space of a row in half, but it makes the calculation in the middle a little trickier. If memory isn't an issue it may not be worth it to bother. It may also slow the solution by making the middle less general since it is different for even sized rows than odd sized rows."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:26:22.843",
"Id": "219928",
"ParentId": "219900",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219906",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T01:15:24.833",
"Id": "219900",
"Score": "5",
"Tags": [
"java",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "Pascal's Triangle Java (performance)"
} | 219900 |
<p>This is part of my research project with the main objective to select patients from various characteristics that are modeled as filters. The main filters include <code>VALID_INDEX_STATUS</code>, <code>VALID_DX_STATUS</code>, <code>VALID_REG_STATUS</code>, and <code>VALID_RX_STATUS</code>, where <code>VALID_RX_STATUS</code> describes if patient has certain treatment drug pattern (i.e., number of particular drugs before and after index date), which is handled by the <code>RxStatus</code>. </p>
<p>I created other python scripts that take care of data preparation as in <code>sec1_data_preparation</code> and data import as in <code>sec2_prepped_data_import</code>.</p>
<pre><code>import sys
from abc import ABC, abstractmethod
import pandas as pd
import datetime
import ctypes
import numpy as np
import random
import pysnooper
import var_creator.var_creator as vc
import feature_tagger.feature_tagger as ft
import data_descriptor.data_descriptor as dd
import data_transformer.data_transformer as dt
import helper_functions.helper_functions as hf
import sec1_data_preparation as data_prep
import sec2_prepped_data_import as prepped_data_import
# Main class
class SubjectGrouping(ABC):
def subject_selection_steps(self):
self._pandas_output_setting()
self.run_data_preparation()
self.import_processed_main_data()
self.initial_subject_pool()
self.create_index_date()
self.create_filter_tags()
self.create_master_df()
self._done_alert()
def _pandas_output_setting(self):
'''Set pandas output display setting'''
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 180)
@abstractmethod
def run_data_preparation(self):
'''Run data_preparation_steps from base class'''
pass
@abstractmethod
def import_processed_main_data(self):
'''Import processed main data'''
pass
@abstractmethod
def initial_subject_pool(self):
'''Import processed main data'''
pass
@abstractmethod
def create_index_date(self):
'''Create index date'''
pass
@abstractmethod
def create_filter_tags(self):
'''Create tags to be used as filters'''
pass
@abstractmethod
def create_master_df(self):
'''Prepare dfs before filtering'''
pass
def _done_alert(self):
'''Alert when data processing is complete'''
if self.control_panel['done_switch']:
ctypes.windll.user32.MessageBoxA(0, b'Hello there', b'Program done.', 0x1000)
class SubjectGrouping_Project1(SubjectGrouping, data_prep.DataPreparation_Project1):
def __init__(self):
# Original df; never overwrite
self.df_dad_origin = None
self.df_pc_origin = None
self.df_nacrs_origin = None
self.df_pin_origin = None
self.df_reg_origin = None
# Working/processed df; can overwrite
self.df_dad = None
self.df_pc = None
self.df_nacrs = None
self.df_pin = None
self.df_reg = None
# Subject group holder
self.df_validIndexDate = None
self.df_initialPool = None
self.df_master = None
self.df_master_filtered = None
self.control_panel = {
'save_file_switch': False, # WARNING: Will overwrite existing files
'df_subsampling_switch': False, # WARNING: Only switch to True when testing
'df_subsampling_n': 50000,
'random_seed': 888,
'df_remove_dup_switch': True,
'parse_date_switch': True,
'result_printout_switch': True,
'comp_loc': 'office',
'show_df_n_switch': False, # To be implemented. Show df length before and after record removal
'done_switch': False,
}
def run_data_preparation(self):
self.data_preparation_steps()
def import_processed_main_data(self):
t_obj = prepped_data_import.PreppedDataImport_Project1()
t_obj.prepped_data_import_steps()
df_dict = t_obj.return_all_dfs()
self.df_dad_origin, self.df_pc_origin, self.df_nacrs_origin, self.df_pin_origin, self.df_reg_origin = (
df_dict['DF_DAD'], df_dict['DF_PC'], df_dict['DF_NACRS'], df_dict['DF_PIN'], df_dict['DF_REG'])
self.df_dad, self.df_pc, self.df_nacrs, self.df_pin, self.df_reg = (
df_dict['DF_DAD'], df_dict['DF_PC'], df_dict['DF_NACRS'], df_dict['DF_PIN'], df_dict['DF_REG'])
del t_obj, df_dict
def initial_subject_pool(self, id_var='PATIENT_ID'):
self.df_initialPool = total_subject_pool(self.df_dad_origin, self.df_pc_origin,
self.df_nacrs_origin, self.df_pin_origin, self.df_reg_origin, id_var=id_var)
self.df_initialPool = self.df_initialPool[[id_var]]
def create_index_date(self):
# Age criteria
self.df_pin = age_addOn_tag(df=self.df_pin)
# Date range criteria
self.df_pin = inDateRange_addOn_tag(
df=self.df_pin,
start_date=self.inclusion_start_date,
end_date=self.inclusion_end_date
)
# Sp. Rx critiera
self.df_pin = spRx_addOn_tag(
df=self.df_pin,
new_var='VALID_DRUG_A',
rx_var='DRUG_DIN',
rx_list=self.drug_a_fg_dinCode_list+self.drug_a_sg_dinCode_list
)
self.df_pin = spRx_addOn_tag(
df=self.df_pin,
new_var='VALID_FG_DRUG_A',
rx_var='DRUG_DIN',
rx_list=self.drug_a_fg_dinCode_list
)
self.df_pin = spRx_addOn_tag(
df=self.df_pin,
new_var='VALID_SG_DRUG_A',
rx_var='DRUG_DIN',
rx_list=self.drug_a_sg_dinCode_list
)
# Create INDEX_DATE
self.df_validIndexDate = index_date(df=self.df_pin, rx_tag='VALID_SG_DRUG_A')
def create_filter_tags(self):
# Create df with only subjects with VALID_REG_STATUS==1
self.df_validResidence_is1only = residence_is1only_tag(df=self.df_reg)
# Create pre and post marks around index date
surround_dates = {
'PREINDEX_9YR':[9*365, 'subtract'],
'PREINDEX_2YR':[2*365, 'subtract'],
'PREINDEX_1YR':[1*365, 'subtract'],
'PREINDEX_6MO':[0.5*365, 'subtract'],
'POSTINDEX_6MO':[0.5*365, 'add'],
'POSTINDEX_1YR':[1*365, 'add'],
'POSTINDEX_2YR':[2*365, 'add'],
}
self.df_validIndexDate = add_surround_dates(df=self.df_validIndexDate, index_date='INDEX_DATE',
date_dict=surround_dates)
# Create INDEX_AGE, INDEX_SEX, INDEX_RURAL
self.df_validIndexDate = add_index_vars(df_index=self.df_validIndexDate, df_origin=self.df_pin_origin)
# For DAD, create df with only subjects with VALID_DX status
dx_obj1 = DxStatus(
df=self.df_dad_origin,
df_id='DAD',
df_ref=self.df_validIndexDate)
dx_obj1.dx_identification_steps()
df_agg_dad_withDxTag = dx_obj1.return_agg_df()
# For PC, create df with only subjects with VALID_DX status
dx_obj2 = DxStatus(
df=self.df_pc_origin,
df_id='PC',
df_ref=self.df_validIndexDate)
dx_obj2.dx_identification_steps()
df_agg_pc_withDxTag = dx_obj2.return_agg_df()
# Merge the aggregated DAD and PC data with VALID_DX
self.df_validDx = merge_dx_status_from_dfs(
df_agg_dad_withDxTag,
df_agg_pc_withDxTag,
id_var='PATIENT_ID')
# Obtain valid medication status with VALID_RX
rx_obj1 = RxStatus(df=self.df_pin_origin, df_ref=self.df_validIndexDate)
rx_obj1.rx_identification_steps()
rx_filterCommand1 = [
# Drug A-related
['&', 'PREINDEX2YR_N_DRUG_A_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_DRUG_A_FG_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_FG_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_DRUG_A_SG_TAG', '==', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_SG_TAG', '>=', 2],
# Control drug-related
['&', 'PREINDEX2YR_N_CONTROL_DRUG_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', '>=', 0],
]
rx_filterCommand2 = [
# Drug A-related
['&', 'PREINDEX2YR_N_DRUG_A_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_DRUG_A_FG_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_FG_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_DRUG_A_SG_TAG', '==', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_SG_TAG', '==', 0],
# Control drug-related
['&', 'PREINDEX2YR_N_CONTROL_DRUG_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', '==', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', '>=', 2],
]
rx_filterCommand3 = [
# Drug A-related
['&', 'PREINDEX2YR_N_DRUG_A_TAG', '==', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_TAG', '>=', 2],
['&', 'PREINDEX2YR_N_DRUG_A_FG_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_FG_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_DRUG_A_SG_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_DRUG_A_SG_TAG', '>=', 0],
# Control drug-related
['&', 'PREINDEX2YR_N_CONTROL_DRUG_TAG', '>=', 2],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', '>=', 0],
['&', 'PREINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', '>=', 0],
['&', 'POSTINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', '>=', 0],
]
rx_obj1.add_rxTag_to_agg_df(new_var='VALID_RX_STATUS_DRUG_A_SG', filter_command_list=rx_filterCommand1)
rx_obj1.add_rxTag_to_agg_df(new_var='VALID_RX_STATUS_CONTROL_DRUG_ATYPICAL', filter_command_list=rx_filterCommand2)
rx_obj1.add_rxTag_to_agg_df(new_var='VALID_RX_STATUS_DRUG_A', filter_command_list=rx_filterCommand3)
self.df_validRx = rx_obj1.return_agg_df()
def create_master_df(self):
self.df_master = self.df_initialPool
df_dict = {
'df_validIndexDate':self.df_validIndexDate,
'df_validDx':self.df_validDx,
'df_validRx':self.df_validRx,
'df_validResidence_is1only':self.df_validResidence_is1only,
}
for df in df_dict.values():
self.df_master = self.df_master.merge(df, on='PATIENT_ID', how='left')
# Convert missing into '0'
var_list = ['VALID_INDEX_STATUS', 'VALID_DX_STATUS', 'VALID_REG_STATUS', 'VALID_RX_STATUS_DRUG_A',
'VALID_RX_STATUS_CONTROL_DRUG_ATYPICAL', 'VALID_RX_STATUS_DRUG_A_SG']
self.df_master[var_list] = self.df_master[var_list].fillna(0)
def filter_master_df(self, new_var, filter_command_list):
self.df_master_filtered = self.df_master.query((''.join([''.join(map(str, x)) for x in
filter_command_list])).strip('&'))
self.df_master_filtered[new_var] = 1
if len(self.df_master_filtered)==0:
print('Warning: filter_master_df() resulted no "1" signal.')
def return_master_df(self) -> object:
return self.df_master
def return_filtered_master_df(self) -> object:
return self.df_master_filtered
# Helper class
######################################################################
class DxStatus():
def __init__(self, df, df_id, df_ref, id_var='PATIENT_ID'):
# Assert df_id input is 'DAD', 'NACRS', or 'PC' only
assert df_id.lower() in ['dad', 'pc'], 'Assertion error: df_id needs to be DAD or PC.'
# Composition, borrow from another class
dataPrep_obj = data_prep.DataPreparation_Project1()
dataPrep_obj.dir_name()
dataPrep_obj.file_name()
dataPrep_obj.import_ref_data()
# Declare class vars
self.df = df
self.df_id = df_id
self.df_ref = df_ref
self.id_var = id_var
self.ft_obj = ft.Tagger()
self._dx_start_date_range = 'PREINDEX_9YR'
self._dx_end_date_range = 'INDEX_DATE'
if (self.df_id.lower() == 'dad'):
self._var_base = 'DXCODE'
self._repeat_var_start = 1
self._repeat_var_end = 25
self._cond_list = dataPrep_obj.dxIcd10Code_list
elif (self.df_id.lower() == 'pc'):
self._var_base = 'HLTH_DX_ICD9X_CODE_'
self._repeat_var_start = 1
self._repeat_var_end = 3
self._cond_list = dataPrep_obj.dxIcd9Code_list
if (self.df_id.lower() == 'dad'):
self._dx_event_date = 'ADMIT_DATE'
elif (self.df_id.lower() == 'pc'):
self._dx_event_date = 'SE_END_DATE'
def dx_identification_steps(self):
self.merge_data()
self.dx_tag()
self.date_tag()
self.merge_tag()
def merge_data(self):
'''Remove rows if their id's are not in ref data; merge vars across dfs'''
self.df = self.df_ref.merge(self.df, on=self.id_var, how='left')
def dx_tag(self):
self.df['ICD_TAG'] = self.ft_obj.multi_var_cond_tagger(
self.df,
repeat_var_base_name=self._var_base,
repeat_var_start=self._repeat_var_start,
repeat_var_end=self._repeat_var_end,
cond_list=self._cond_list
)
def date_tag(self):
self.df['DATE_TAG'] = np.where(
(self.df[self._dx_event_date]>=self.df[self._dx_start_date_range])
& (self.df[self._dx_event_date]<=self.df[self._dx_end_date_range]), 1, 0)
def merge_tag(self):
self.df['ICD_N_DATE_TAG'] = self.ft_obj.summing_all_tagger(
self.df, tag_var_list=['ICD_TAG', 'DATE_TAG'])
def return_df(self) -> object:
return self.df
def return_agg_df(self) -> object:
if (self.df_id.lower() == 'dad'):
return return_agg_df_dad_withDxTag(
df=self.df,
id_var=self.id_var,
event_date='ADMIT_DATE',
tag_var='ICD_N_DATE_TAG'
)
elif (self.df_id.lower() == 'pc'):
return return_agg_df_pc_withDxTag(
df=self.df,
id_var=self.id_var,
event_date='SE_END_DATE',
tag_var='ICD_N_DATE_TAG'
)
class RxStatus():
def __init__(self, df, df_ref, id_var='PATIENT_ID'):
self.df = df
self.df_ref = df_ref
self.id_var = id_var
self.ft_obj = ft.Tagger()
# Composition, borrow from another class
self.dataPrep_obj = data_prep.DataPreparation_Project1()
self.dataPrep_obj.dir_name()
self.dataPrep_obj.file_name()
self.dataPrep_obj.import_ref_data()
def rx_identification_steps(self):
self.filter_data()
self.rx_tag()
self.date_tag()
self.merge_tag()
self.agg_df()
def filter_data(self, index_status='VALID_INDEX_STATUS'):
self.df = self.df.merge(self.df_ref, on=self.id_var, how='left')
self.df = self.df[self.df[index_status]==1]
def rx_tag(self, din_var='DRUG_DIN', atc_var='SUPP_DRUG_ATC_CODE'):
self.df['RX_DRUG_A_TAG'] = self.ft_obj.isin_tagger(self.df, din_var, self.dataPrep_obj.drug_a_dinCode_list)
self.df['RX_DRUG_A_FG_TAG'] = self.ft_obj.isin_tagger(self.df, din_var, self.dataPrep_obj.drug_a_fg_dinCode_list)
self.df['RX_DRUG_A_SG_TAG'] = self.ft_obj.isin_tagger(self.df, din_var, self.dataPrep_obj.drug_a_sg_dinCode_list)
self.df['RX_CONTROL_DRUG_EXCLUDE_TAG'] = self.ft_obj.isin_tagger(self.df, din_var, self.dataPrep_obj.controlDrug_dinExclusion_list)
self.df['RX_CONTROL_DRUG_PRETAG'] = self.ft_obj.isin_tagger(self.df, atc_var, self.dataPrep_obj.controlDrug_atcCode_list)
self.df['RX_CONTROL_DRUG_TYPICAL_PRETAG'] = self.ft_obj.isin_tagger(self.df, atc_var, self.dataPrep_obj.controlDrug_typical_atcCode_list)
self.df['RX_CONTROL_DRUG_ATYPICAL_PRETAG'] = self.ft_obj.isin_tagger(self.df, atc_var, self.dataPrep_obj.controlDrug_atypical_atcCode_list)
self.df['RX_CONTROL_DRUG_TAG'] = np.where((self.df['RX_CONTROL_DRUG_PRETAG']==1)&(self.df['RX_CONTROL_DRUG_EXCLUDE_TAG']!=1), 1, 0)
self.df['RX_CONTROL_DRUG_TYPICAL_TAG'] = np.where((self.df['RX_CONTROL_DRUG_TYPICAL_PRETAG']==1)
&(self.df['RX_CONTROL_DRUG_EXCLUDE_TAG']!=1), 1, 0)
self.df['RX_CONTROL_DRUG_ATYPICAL_TAG'] = np.where((self.df['RX_CONTROL_DRUG_ATYPICAL_PRETAG']==1)
&(self.df['RX_CONTROL_DRUG_EXCLUDE_TAG']!=1), 1, 0)
def date_tag(self, index_date='INDEX_DATE', event_date='DSPN_DATE'):
self.df['IN_PREINDEX_2YR_TAG'] = self.ft_obj.date_range_tagger(self.df, event_date,
start_date_range=self.df['PREINDEX_2YR'], end_date_range=self.df[index_date],
include_start_date=True, include_end_date=False) # index date not included as pre-index period
self.df['IN_POSTINDEX_2YR_TAG'] = self.ft_obj.date_range_tagger(self.df, event_date,
start_date_range=self.df[index_date], end_date_range=self.df['POSTINDEX_2YR'],
include_start_date=True, include_end_date=True) # index date included as post-index period
def merge_tag(self):
merge_dict = {
'PREINDEX2YR_N_DRUG_A_TAG':['IN_PREINDEX_2YR_TAG', 'RX_DRUG_A_TAG'],
'POSTINDEX2YR_N_DRUG_A_TAG':['IN_POSTINDEX_2YR_TAG', 'RX_DRUG_A_TAG'],
'PREINDEX2YR_N_DRUG_A_FG_TAG':['IN_PREINDEX_2YR_TAG', 'RX_DRUG_A_FG_TAG'],
'POSTINDEX2YR_N_DRUG_A_FG_TAG':['IN_POSTINDEX_2YR_TAG', 'RX_DRUG_A_FG_TAG'],
'PREINDEX2YR_N_DRUG_A_SG_TAG':['IN_PREINDEX_2YR_TAG', 'RX_DRUG_A_SG_TAG'],
'POSTINDEX2YR_N_DRUG_A_SG_TAG':['IN_POSTINDEX_2YR_TAG', 'RX_DRUG_A_SG_TAG'],
'PREINDEX2YR_N_CONTROL_DRUG_TAG':['IN_PREINDEX_2YR_TAG', 'RX_CONTROL_DRUG_TAG'],
'POSTINDEX2YR_N_CONTROL_DRUG_TAG':['IN_POSTINDEX_2YR_TAG', 'RX_CONTROL_DRUG_TAG'],
'PREINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG':['IN_PREINDEX_2YR_TAG', 'RX_CONTROL_DRUG_TYPICAL_TAG'],
'POSTINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG':['IN_POSTINDEX_2YR_TAG', 'RX_CONTROL_DRUG_TYPICAL_TAG'],
'PREINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG':['IN_PREINDEX_2YR_TAG', 'RX_CONTROL_DRUG_ATYPICAL_TAG'],
'POSTINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG':['IN_POSTINDEX_2YR_TAG', 'RX_CONTROL_DRUG_ATYPICAL_TAG'],
}
for key, val in merge_dict.items():
self.df[key] = self.ft_obj.summing_all_tagger(self.df, tag_var_list=val)
def agg_df(self, id_var='PATIENT_ID'):
self.df_agg = pd.pivot_table(self.df, index=[id_var], values=[
'INDEX_DATE', 'PREINDEX_2YR', 'POSTINDEX_2YR',
'PREINDEX2YR_N_DRUG_A_TAG', 'POSTINDEX2YR_N_DRUG_A_TAG',
'PREINDEX2YR_N_DRUG_A_FG_TAG', 'POSTINDEX2YR_N_DRUG_A_FG_TAG',
'PREINDEX2YR_N_DRUG_A_SG_TAG', 'POSTINDEX2YR_N_DRUG_A_SG_TAG',
'PREINDEX2YR_N_CONTROL_DRUG_TAG', 'POSTINDEX2YR_N_CONTROL_DRUG_TAG',
'PREINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG', 'POSTINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG',
'PREINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG', 'POSTINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG'], aggfunc={
'INDEX_DATE': 'first',
'PREINDEX_2YR': 'first',
'POSTINDEX_2YR': 'first',
'PREINDEX2YR_N_DRUG_A_TAG':np.sum,
'POSTINDEX2YR_N_DRUG_A_TAG':np.sum,
'PREINDEX2YR_N_DRUG_A_FG_TAG':np.sum,
'POSTINDEX2YR_N_DRUG_A_FG_TAG':np.sum,
'PREINDEX2YR_N_DRUG_A_SG_TAG':np.sum,
'POSTINDEX2YR_N_DRUG_A_SG_TAG':np.sum,
'PREINDEX2YR_N_CONTROL_DRUG_TAG':np.sum,
'POSTINDEX2YR_N_CONTROL_DRUG_TAG':np.sum,
'PREINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG':np.sum,
'POSTINDEX2YR_N_CONTROL_DRUG_TYPICAL_TAG':np.sum,
'PREINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG':np.sum,
'POSTINDEX2YR_N_CONTROL_DRUG_ATYPICAL_TAG':np.sum
}
)
self.df_agg = pd.DataFrame(self.df_agg.to_records())
def add_rxTag_to_agg_df(self, new_var, filter_command_list):
self.df_agg_filtered = self.df_agg.query((''.join([''.join(map(str, x)) for x in
filter_command_list])).strip('&'))
self.df_agg_filtered[new_var] = 1
if len(self.df_agg_filtered)==0:
print('Warning: add_rxTag_to_agg_df() resulted no RxTag=1 signal.')
self.df_agg_filtered = self.df_agg_filtered[[new_var, self.id_var]]
self.df_agg = self.df_agg.merge(self.df_agg_filtered, on=self.id_var, how='left')
def return_agg_df(self) -> object:
return self.df_agg
# Helper functions
######################################################################
def total_subject_pool(*dfs, id_var='PATIENT_ID') -> object:
'''Return a new df by collecting all the unique values in id_var
from input df's'''
t_list = []
for df in dfs:
t_list += df[id_var].to_list()
t_list = list(set(t_list))
return pd.DataFrame(t_list, columns=[id_var])
def index_date(df, rx_tag, id_var='PATIENT_ID', event_date='DSPN_DATE') -> object:
'''Return a new df with only subjects that have an existing index date'''
# Remove if row not having valid age
df = df[df['VALID_AGE']==1]
# Sort
df = df.sort_values([id_var, rx_tag, event_date], ascending=[True, False, True])
# Aggregrate
df_agg = aggregate_for_index_date(df, tag_filter_var=rx_tag,
pre_index_var=event_date, index=[id_var], values=[event_date, 'DRUG_DIN','SUPP_DRUG_ATC_CODE',
'SEX', 'RURAL'], aggfunc={event_date:np.min, 'DRUG_DIN':'first', 'SUPP_DRUG_ATC_CODE':'first',
'SEX':'first', 'RURAL':'first'})
# Assert df_pin_patients_agg is not empty
assert len(df_agg)>0, 'Assertion error: empty dataframe.'
# Rename columns
df_agg = df_agg.rename(columns={'DRUG_DIN':'INDEX_DIN', 'SUPP_DRUG_ATC_CODE':'INDEX_ATC'})
# Add VALID_INDEX_STATUS==1 to later show these are the satisfied patients
df_agg['VALID_INDEX_STATUS'] = 1
# Normalize date (aka: removing hour/min/sec)
df_agg['INDEX_DATE'] = pd.DatetimeIndex(df_agg['INDEX_DATE']).normalize()
return df_agg
def add_surround_dates(df, date_dict, index_date='INDEX_DATE') -> object:
for var, values in date_dict.items():
df[var] = vc.date_adder(df, index_date, values[0], values[1])
df[var] = pd.DatetimeIndex(df[var]).normalize()
return df
def add_index_vars(df_index, df_origin, id_var='PATIENT_ID', index_var='INDEX_DATE', age_var='AGE',
sex_var='SEX', rural_var='RURAL') -> object:
# Adding INDEX_AGE corresponding to INDEX_DATE
df_temp = df_origin.merge(df_index, on=id_var, how='left')
df_temp['MATCHED_DATES'] = np.where((df_temp['DSPN_DATE']==df_temp[index_var]), 1, 0)
df_temp = df_temp[df_temp['MATCHED_DATES']==1]
df_temp_agg = pd.pivot_table(df_temp, index=[id_var], values=[age_var], aggfunc='first')
df_temp_agg = df_temp_agg.rename(columns={age_var:'INDEX_AGE'})
df_temp_agg = pd.DataFrame(df_temp_agg.to_records())
# Actually adding that to the original df
df_index = df_index.merge(df_temp_agg, on=id_var, how='left')
df_index = df_index.rename(columns={sex_var:'INDEX_SEX', rural_var:'INDEX_RURAL'})
return df_index
def residence_is1only_tag(df, id_var='PATIENT_ID', criteria_year=[2015, 2016]) -> object:
'''Return a new df tagged with 1 (who fulfilled the valid AB registry criterion).
Valid AB residence period - had a valid record in the provincial registry within
the inclusion period (Apr 2014 and Mar 2016).'''
df['FYE_ACTIVE'] = np.where(df['ACTIVE_COVERAGE']==1, df['FYE'], np.nan)
df_agg = df.groupby(by=id_var).agg({'FYE_ACTIVE':lambda x: list(x)})
df_agg = df_agg.reset_index()
df_agg['FYE_ACTIVE'] = df_agg['FYE_ACTIVE'].apply(lambda x: [i for i in x if ~np.isnan(i)]) # remove float nan
df_agg['FYE_ACTIVE'] = df_agg['FYE_ACTIVE'].apply(lambda x: [int(i) for i in x]) # convert float to int
df_agg['FYE_NEEDED'] = df_agg.apply(lambda x: criteria_year, axis=1)
df_agg['VALID_REG_STATUS'] = df_agg.apply(compare_list_elements_btw_vars, axis=1)
df_agg = df_agg[df_agg['VALID_REG_STATUS']==1]
return df_agg[[id_var, 'VALID_REG_STATUS']]
def age_addOn_tag(df, age_var='AGE', new_var='VALID_AGE', criteria_age_min=18, criteria_age_max=999) -> object:
'''Return an updated df tagged with 1 for correct age, 0 otherwise'''
df[new_var] = np.where((df[age_var]>=criteria_age_min)&(df[age_var]<=criteria_age_max), 1, 0)
return df
def inDateRange_addOn_tag(df, start_date, end_date, event_date='DSPN_DATE', new_var='VALID_DATE',
include_start_date=True, include_end_date=True) -> object:
'''Return an updated df tagged with 1 for date within data range, 0 otherwise'''
ft_obj = ft.Tagger()
df[new_var] = ft_obj.date_range_tagger(df, event_date, start_date_range=start_date,
end_date_range=end_date, include_start_date=include_start_date, include_end_date=include_end_date)
return df
def spRx_addOn_tag(df, rx_var, new_var, rx_list) -> object:
'''Return an updated df tagged with 1 who had a match with a sp Rx, 0 otherwise'''
ft_obj = ft.Tagger()
df[new_var] = ft_obj.isin_tagger(df, rx_var, rx_list)
return df
def aggregate_for_index_date(df, tag_filter_var, pre_index_var, index, values, aggfunc,
index_var='INDEX_DATE') -> object:
'''tag_filter_col_name refers to the column to retain patients>=1
pre_index_col_name refers to the date column index date will be derived from
index_col_name refers to the column name of the index date'''
df_filtered = df[df[tag_filter_var]>=1]
df_agg = pd.pivot_table(df_filtered, index=index, values=values,
aggfunc=aggfunc)
df_agg = pd.DataFrame(df_agg.to_records())
df_agg = df_agg.rename(columns={pre_index_var:index_var})
return df_agg
def compare_list_elements_btw_vars(row):
if set(row['FYE_NEEDED']).issubset(row['FYE_ACTIVE']): return 1
else: return 0
def return_agg_df_dad_withDxTag(df, id_var, event_date, tag_var) -> object:
'''Aggregate by PATIENT_ID; return a df'''
# Shorter df
df = df.sort_values([id_var, tag_var, event_date], ascending=[True,
False, True])
# Assign new column
df_agg = (df.assign(ADMIT_DATE=df[event_date].where(
df[tag_var].astype(bool)))
.groupby(id_var)
.agg({tag_var:'max', event_date:'first'})
)
df_agg = df_agg.rename(columns={event_date:'DAD_DX_DATE',
tag_var:'DAD_DX_TAG'})
df_agg = pd.DataFrame(df_agg.to_records())
return df_agg
def return_agg_df_pc_withDxTag(df, id_var, event_date, tag_var) -> object:
df = df.sort_values([id_var, tag_var, event_date], ascending=[True,
False, True])
# Aggregate by PATIENT_ID; tag_var will take the maximum value; SE_END_DATE will store the dates into
# .. a list of dates if tag_var==1
# Complex code below
# Assign new column
df_agg = (df.assign(SE_END_DATE=df[event_date].where(
df[tag_var].astype(bool)))
.groupby(id_var)
.agg({tag_var:'max', event_date:lambda x: x.dropna().tolist()})
)
df_agg = pd.DataFrame(df_agg.to_records())
# The dates in the PC_VISIT_DATE_LIST are date of visits that fulfill 1) dx icd and 2) within 9 years pre-index
df_agg = df_agg.rename(columns={event_date:'PC_VISIT_DATE_LIST'})
# Execute the function and reassign to new columns
df_agg['temp'] = df_agg['PC_VISIT_DATE_LIST'].apply(date_scan_by_year_range)
new_col_list = ['TOTAL_PC_DX_SIGNAL', 'PC_DX_TAG', 'PC_DX_DATE'] # WARNING: 'TOTAL_PC_DX_SIGNAL' gives strange figure, need to check later on
for n, col in enumerate(new_col_list):
df_agg[col] = df_agg['temp'].apply(lambda temp: temp[n])
# Remove unused col and obj instance
df_agg = df_agg.drop([tag_var, 'PC_VISIT_DATE_LIST', 'temp'], axis=1)
return df_agg
def date_scan_by_year_range(date_list, num_of_events=3, num_of_years=3) -> tuple:
'''return (signal_total, signal_binary, first_signal_date); i.e., if a signal is
3 events over 3 years, then num_of_events=3 and num_of_years=3, if it is
2 events over 4 years, then num_of_events=2 and num_of_years=4'''
date_list.sort()
signal_total = 0
signal_binary = 0
first_signal_date = None
signal_date_list = []
for i in range(0, len(date_list)):
try:
current_date = date_list[i]
next_xx_date = date_list[i+(num_of_events-1)]
days_diff = next_xx_date - current_date
if days_diff <= datetime.timedelta(days=365*num_of_years):
signal_total+=1
signal_date_list.append(current_date)
except Exception: pass
# Get a binary signal summary
if signal_total>=1:
signal_binary=1
# Sort signal_date_list and extract the first date
signal_date_list.sort()
try:
first_signal_date = signal_date_list[0]
except:
first_signal_date = np.NaN
return signal_total, signal_binary, first_signal_date
def merge_dx_status_from_dfs(*dfs, id_var) -> object:
'''Param: *dfs as many dfs as user specified. id_var is the common identifier across dfs.
Function: 1) Outer merge of all the dfs based on id_var; 2) assian 1 to VALID_DX_STATUS if at least one
{VAR}_DX_TAG variables is 1, otherwise 0; 3) assign earliest date from {VAR}_DX_DATE to DX_DATE;
4) return processed df'''
df_merged = pd.DataFrame(columns=[id_var])
for df in dfs:
df_merged = df_merged.merge(df, on=id_var, how='outer')
dx_tag_cols = [col for col in df_merged.columns if '_DX_TAG' in col]
df_merged['DX_TAG_SUM'] = df_merged[dx_tag_cols].sum(axis=1)
df_merged['VALID_DX_STATUS'] = np.where((df_merged['DX_TAG_SUM']>=1), 1, 0)
df_date_cols = [col for col in df_merged.columns if '_DX_DATE' in col]
df_merged['DX_DATE'] = df_merged[df_date_cols].min(axis=1)
return df_merged
# Execution
######################################################################
if __name__=='__main__':
subjectGrp_filter_DRUG_A_sg = [
['&', 'VALID_INDEX_STATUS', '==', 1],
['&', 'VALID_DX_STATUS', '==', 1],
['&', 'VALID_REG_STATUS', '==', 1],
['&', 'VALID_RX_STATUS_DRUG_A_SG', '==', 1],
]
subjectGrp_filter_CONTROL_DRUG_atypical = [
['&', 'VALID_INDEX_STATUS', '==', 1],
['&', 'VALID_DX_STATUS', '==', 1],
['&', 'VALID_REG_STATUS', '==', 1],
['&', 'VALID_RX_STATUS_CONTROL_DRUG_ATYPICAL', '==', 1],
]
subjectGrp_filter_DRUG_A = [
['&', 'VALID_INDEX_STATUS', '==', 1],
['&', 'VALID_DX_STATUS', '==', 1],
['&', 'VALID_REG_STATUS', '==', 1],
['&', 'VALID_RX_STATUS_DRUG_A', '==', 1],
]
subjectGrp_obj = SubjectGrouping_Project1()
subjectGrp_obj.subject_selection_steps()
subjectGrp_obj.filter_master_df(new_var='FINAL_GROUP_DRUG_A_SG', filter_command_list=subjectGrp_filter_DRUG_A_sg)
df_final_DRUG_A_sg = subjectGrp_obj.return_filtered_master_df()
print(len(df_final_DRUG_A_sg))
print(df_final_DRUG_A_sg.PATIENT_ID.nunique())
print(df_final_DRUG_A_sg.head())
subjectGrp_obj.filter_master_df(new_var='FINAL_GROUP_CONTROL_DRUG_ATYPICAL', filter_command_list=subjectGrp_filter_CONTROL_DRUG_atypical)
df_final_CONTROL_DRUG_atypical = subjectGrp_obj.return_filtered_master_df()
print(len(df_final_CONTROL_DRUG_atypical))
print(df_final_CONTROL_DRUG_atypical.PATIENT_ID.nunique())
print(df_final_CONTROL_DRUG_atypical.head())
subjectGrp_obj.filter_master_df(new_var='FINAL_GROUP_DRUG_A', filter_command_list=subjectGrp_filter_DRUG_A)
df_final_DRUG_A = subjectGrp_obj.return_filtered_master_df()
print(len(df_final_DRUG_A))
print(df_final_DRUG_A.PATIENT_ID.nunique())
print(df_final_DRUG_A.head())
</code></pre>
<p>I used a lot of new coding techniques (i.e., <code>df.query</code>, inheritance, composition) and design patterns (i.e., template method) that I haven't used extensively before. I wonder if overall I am incorporating them correctly. Any other tips/suggestions on how to improve my code will be greatly appreciated.</p>
| [] | [
{
"body": "<p>You have put up a lot of code for review<sup>1</sup>, so my feedback cuts some corners. Maybe other members of the community will jump on.</p>\n\n<hr>\n\n<h2>Style</h2>\n\n<p>Since your code base is quite substantial, there are some places where the style is not consistent. I will link to the relevant parts in <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"nofollow noreferrer\">Python's official Style Guide (PEP8)</a> in the following. Before pointing out some of these spots, I would highly recommend to look into an IDE (e.g. PyCharm, Spyder, Visual Studio Code, Atom, ...) with a built-in style checker (e.g. <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a> or <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a>, both may also be used standalone). These will help you to avoid those pesky traps and the overall appearance will be more consistent.</p>\n\n<p><strong><a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">Whitespace in Expressions</a></strong><br/>\nThere are some places like </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_dict = {\n 'df_validIndexDate':self.df_validIndexDate, \n 'df_validDx':self.df_validDx, \n 'df_validRx':self.df_validRx, \n 'df_validResidence_is1only':self.df_validResidence_is1only,\n }\n</code></pre>\n\n<p>where you miss out on spaces between the colons in dictionary definitions. The same goes for lines like <code>signal_total+=1</code> (should be <code>signal_total += 1</code>), etc.</p>\n\n<p><strong><a href=\"https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions\" rel=\"nofollow noreferrer\">Names</a></strong><br/>\nThe official recommendation is to use <code>snake_case</code> for variables and method/function names and <code>CamelCase</code> for classes, and most Python libraries consent with it. You also follow it most of the time, but some variable and function names use a funny mix one may call <code>snake_camelCase</code>, e.g. <code>self.df_validIndexDate</code> or <code>def spRx_addOn_tag(...)</code>. IMHO it's best to pick either one and follow it consistently.</p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\"><strong>Blank lines</strong></a><br/>\nUse the power of blank lines to give a more robust visual structure to your code. E.g. it is common to seperate class definitions and top-level functions with two blank lines. You may also use a single blank line within function/method bodies where appropriate to group lines of code.</p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\"><strong>Imports</strong></a><br/>\nThis topic is closely related to the previous one. The PEP8 recommendation is to group import by 1) standard library imports, 2) third-library imports, 3) imports from within your module/code-structure. It sometimes also makes sense to use subgroubs, e.g. if you import a lot of third-party libraries with different topics. Applying this principle to your code could look like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nimport random\nimport ctypes\nimport datetime\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\nimport pandas as pd\nimport pysnooper\n\nimport var_creator.var_creator as vc\nimport feature_tagger.feature_tagger as ft\nimport data_descriptor.data_descriptor as dd\nimport data_transformer.data_transformer as dt\nimport helper_functions.helper_functions as hf\nimport sec1_data_preparation as data_prep\nimport sec2_prepped_data_import as prepped_data_import\n</code></pre>\n\n<p>Side note: Visual Studio Code tells me that the imports of <code>sys</code>, <code>random</code>, and <code>pysnooper</code> (as well as <code>dd</code>, <code>dt</code>, and <code>hf</code>) are actually not used in the code you posted. But that might be an artifact of bringing the code to this site.</p>\n\n<p><strong><a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">Documentation</a></strong><br/>\nI'ld say you did a reasonable job here. Most of your methods/functions have a little something of documentation. However, your classes lack any form of real documentation. There are some loose bits speaking of a <code>Main class</code> and a <code>Helper class</code>, but I think you could significantly improve it. Classes can also be documented using the <code>'''docstring style'''</code> and I would highly recommend to do so. Since you are working in the \"scientific Python stack\", you could also have a look at <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\">NumPy's docstring conventions</a> to boost the expressiveness even further.</p>\n\n<h2>Code</h2>\n\n<p>After picking on the style for a while, lets have a look at some parts of the actual code.</p>\n\n<p><strong>Parenthesis in conditions</strong><br/>\nThis is on the brink between style and code. Usually, you won't find lines like <code>if (self.df_id.lower() == 'dad'):</code> a lot in Python code. Most often it'll just be <code>if self.df_id.lower() == 'dad':</code>, since parenthesis are usually only put around the condition if it spans multiple lines.</p>\n\n<p><strong>Assignments and copies</strong><br/>\nFrom what I know about Python and pandas, I would say <code>self.df_master = self.df_initialPool</code> does not create a copy. Instead, you will also modify <code>self.df_initialPool</code> when manipulating <code>self.df_master</code> afterwards. Since you are using <code>merge</code>, and <code>merge</code> will create a copy if not told otherwise, I think you can get away with it at that point. You will have to check if this is acceptable if there are other instances of this \"pattern\".</p>\n\n<p><strong>Iterating over dictionary</strong><br/>\nThere is</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_dict = {\n 'df_validIndexDate': self.df_validIndexDate,\n 'df_validDx': self.df_validDx,\n 'df_validRx': self.df_validRx,\n 'df_validResidence_is1only': self.df_validResidence_is1only,\n}\nfor df in df_dict.values():\n ...\n</code></pre>\n\n<p>almost at the same spot as the previous one. If I have not missed out on a substantial part of the function, the keys of the dictionary are never actually used. This means, the same effect can be accomplished using a simple list:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_list = [self.df_validIndexDate, self.df_validDx, \n self.df_validRx, self.df_validResidence_is1only]\nfor df in df_list:\n self.df_master = self.df_master.merge(df, on='PATIENT_ID', how='left')\n</code></pre>\n\n<p>As a bonus, this will guarantee that the order in which these dataframes are merged is preserved also in Python versions prior to 3.6, where dicts where unordered (as far as a I know, this is still not an official language feature and considered an implementation detail). However, from what I can see that should be not an issue here.</p>\n\n<p><strong>Exception handling</strong><br/>\nCode parts like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try:\n first_signal_date = signal_date_list[0]\nexcept:\n first_signal_date = np.NaN\n</code></pre>\n\n<p>can have unexpected/unwanted effects. Since you're catching all exceptions here, you may also miss things like wrong variables names or keyboard interrupts. So when catching exceptions, be as specific as possible on what you expect to go wrong. You can even catch <a href=\"https://stackoverflow.com/a/6470452/5682996\">multiple exceptions on a single line</a> (just in case you were not aware of this). Using</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try:\n ...\nexcept Exception:\n pass\n</code></pre>\n\n<p>is only a miniscule improvement, since <code>Exception</code> is still quite high up in the <a href=\"https://docs.python.org/3/library/exceptions.html#exception-hierarchy\" rel=\"nofollow noreferrer\">exception hierarchy</a>.</p>\n\n<p><strong>Memory management</strong><br/>\nI just wanted to bring to your attention that using <code>del t_obj, df_dict</code> does not immediately free the memory occupied by those variables. It only decrements the internal reference count. The excact moment when the memory will be freed still depends fully on the garbage collector. See also <a href=\"https://stackoverflow.com/a/14969798/5682996\">this</a> SO post on that topic.</p>\n\n<hr>\n\n<p>Well, that's it for the first round. Maybe other members of the community or future me can give you more detailed feedback regarding the coding techniques you asked about.</p>\n\n<hr>\n\n<p><sup>1</sup> It may be worth to split those 600+ lines into more files for you to work with.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:50:52.780",
"Id": "219960",
"ParentId": "219904",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T02:18:37.930",
"Id": "219904",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"design-patterns",
"pandas"
],
"Title": "Subject group creation/selection using multiple filter tags derived from multiple databases"
} | 219904 |
<p>I'm in the midst of exploring SSO with JWT & Wordpress, I'm not too sure if it's a good practice or does this setup/flow have any security vulnerabilities.</p>
<p>Currently JWT/SSO method i'm using is based on this <a href="https://stackoverflow.com/questions/33723033/single-sign-on-flow-using-jwt-for-cross-domain-authentication#answer-37392811">answer/method</a> which is getting JWT token using iFrame method instead of redirection method eg: from domain1.com > sso.com (retrieve JWT) > domain1.com</p>
<p>Please refer below for my setup/codebase fmi:</p>
<p><strong>Main SSO domain (using Wordpress and JWT)</strong></p>
<ul>
<li><a href="https://sso.com/login" rel="nofollow noreferrer">https://sso.com/login</a></li>
<li><a href="https://sso.com/validation" rel="nofollow noreferrer">https://sso.com/validation</a></li>
</ul>
<p><strong>Platform 1 (using plain PHP)</strong></p>
<ul>
<li><a href="https://domain1.com" rel="nofollow noreferrer">https://domain1.com</a></li>
</ul>
<p><strong>Platform 2 (using plain PHP)</strong></p>
<ul>
<li><a href="https://domain2.com" rel="nofollow noreferrer">https://domain2.com</a></li>
</ul>
<hr>
<p><strong>sso.com/login (Wordpress)</strong></p>
<pre><code><h3>Passport</h3>
<br>
<input type="text" name="username" value="admin"/><br>
<input type="text" name="password" value="admin"/><br>
<br>
<a href="javascript:void(0);" id='submit_btn'>Submit</a>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
$(document).on('click','#submit_btn',function(){
$.ajax({
url: "https://sso.com/wp-json/jwt-auth/v1/token",
type: "POST",
data: {
username : $('input[name=username]').val(),
password : $('input[name=password]').val(),
},
success: function(data){
localStorage.setItem('token',data.token);
//Which means sso.com/validation able retrieve localStorage('token'); too!
}
});
});//endClick
</script>
</code></pre>
<hr>
<p><strong>Platform 1 & Platform 2 (PHP)</strong></p>
<p><em>Questions: is it safe if i'm using postMessage to retrieve JWT token from iframe/sso.com? Any security vulnerability i need to concern?</em></p>
<pre><code><html>
<head>
<meta charset="UTF-8">
<title>Platform 1</title>
</head>
<body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
var passport_url = 'https://sso.com/validation/';
passport_url+= '?parent='+encodeURI(window.location.href);
$('<iframe>', {
src : passport_url,
id : 'passport',
frameborder : 0,
scrolling : 'no',
style : 'display:none;',
width : 0,
height : 0,
}).appendTo('body');
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// listen to message from sso.com/validation
eventer(messageEvent,function(e) {
alert("Token received: \n"+e.data)
//got the token! will be authenticate using ajax and redirect to logged in page...
},false);
</script>
</body>
</html>
</code></pre>
<hr>
<p><strong>sso.com/validation (Wordpress)</strong></p>
<p><em>Questions: Since we'll have multiple platform eg: domain1.com, domain2.com, etc, is it a good practice to pass a dynamic parameter in postMessage function using parentUrl?</em></p>
<pre><code><script>
var token = localStorage.getItem('token');
if(token && is_inIFrame())
{
//or using PHP validate "Parent" ... using config/application.php
var parentUrl = getParameterByName('parent');
parent.postMessage(token,parentUrl);
}
function is_inIFrame() {try {return window.self !== window.top;} catch (e) {return true;}}
function getParameterByName(name, url) {if (!url) url = window.location.href;name = name.replace(/[\[\]]/g, '\\$&');var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),results = regex.exec(url);if (!results) return null;if (!results[2]) return '';return decodeURIComponent(results[2].replace(/\+/g, ' '));}
</script>
</code></pre>
<hr>
<p>tldr; is this the right direction to create SSO/JWT authentication with cross domains with PHP? is above method is a secure way to code it?</p>
| [] | [
{
"body": "<p>I don't know why an iframe was suggested to you, but I do see some possibilities for vulnerability.</p>\n\n<p>For your platforms, I would validate server-2-server.</p>\n\n<p>Flow:</p>\n\n<p>If client claims to be logged in ( in JS / has token in local storage), send token to the platform itself.</p>\n\n<p>The receiving endpoint (let's say platform1_showProfile.php) sends a curl-request to the SSO platform in order to validate (and or logout/refresh if expired etc)</p>\n\n<p>For performance reasons, you will want to ask yourself whether </p>\n\n<ol>\n<li><p>JWT is only your SSO authentication method while maintaining state on each platform or if you want to go stateless and use the sso-endpoint on each call.</p></li>\n<li><p>WordPress is the right solution for this. Consider setting up an authentication server with slimframework or neoan3</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T12:59:32.753",
"Id": "221482",
"ParentId": "219908",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T04:41:22.903",
"Id": "219908",
"Score": "2",
"Tags": [
"php",
"security",
"jwt"
],
"Title": "SSO login & authenticate Wordpress users with JWT token"
} | 219908 |
<p>The is my code to compute BMI (body mass index).</p>
<p>How can I make this code better?</p>
<pre><code>const computeBMI = (weight, height, country) => {
const countries = ["Chad", "Sierra Leone", "Mali", "Gambia", "Uganda", "Ghana", "Senegal", "Somalia", "Ivory Coast", "Isreal"];
let heightInMeters = height * 0.3048;
let BMI = weight / (heightInMeters * heightInMeters);
for (let i = 0; i < countries.length; i++) {
if (countries[i] === country) {
const bmiTotal = BMI * 0.82;
return Math.round(bmiTotal, 2);
}
}
return Math.round(BMI, 2);
};
</code></pre>
| [] | [
{
"body": "<p>Avoid magic numbers. That's <code>0.3048</code> and <code>0.82</code>. When another developer comes in and looks at the code, they won't know what those numbers are. Put them in variables that are named accordingly.</p>\n\n<p>You converted height into meters, which implies that <code>height</code> isn't in meters. What unit does it come in? Is it some other metric unit or is it another unit? You didn't convert <code>weight</code>. Is <code>weight</code> already in metric? Would be better to use units as argument names instead.</p>\n\n<p>Also, stick to one unit for calculation. Move conversions elsewhere. For instance, write in metric for everything. Then create separate APIs for other units, doing the conversion to metric there, then call the metric APIs.</p>\n\n<p>That loop is a long-winded way to modify BMI for specific countries. It took me a while to figure that out. Would be nice to add comments on what that entire block does. Also, there's <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>array.includes()</code></a>.</p>\n\n<p>Lastly, any constant values in a function (values that literally never change, like your countries list and ratio), you should pull out of the function. Keeps the function less cluttered. Also, you wouldn't want to recreate those values every time the function is called.</p>\n\n<pre><code>const adjustedRatio = 0.82\nconst countries = [...];\n\nconst computeBMI = (kilograms, meters, country) => {\n const baseBMI = weight / (meters * meters);\n const shouldRatio = countries.includes(country)\n const modifiedBMI = shouldRatio ? baseBMI * adjustedRatio : baseBMI\n return Math.round(modifiedBMI, 2);\n};\n\n// For non-metric users\nconst computeBMINonMetric = (pounds, feet, country) => {\n // TODO: convert pounds to kilograms\n // TODO: convert feet to meters\n return computeBMI(kilograms, meters, country)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:32:37.617",
"Id": "424924",
"Score": "0",
"body": "Thank you for your response"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:58:46.410",
"Id": "219936",
"ParentId": "219920",
"Score": "2"
}
},
{
"body": "<h2>Some points</h2>\n<ul>\n<li>Put magic numbers in constants to give them meaning.</li>\n<li>Variables that do not change should be defined as constants</li>\n<li>Use appropriate <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\">Array</a> functions rather than iterating over the array.</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\" rel=\"nofollow noreferrer\"><code>Math.round</code></a> only takes one argument. I do not know why you pass 2 as a second argument. If I guess you want to round to 2 decimal places. To do that you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed\" rel=\"nofollow noreferrer\"><code>Number.toFixed()</code></a> however that returns the number as a String so to be safe and return the same type you would use <code>Number(BMI.toFixed(2))</code> or you can use <code>Math.round(BMI * 100) / 100</code></li>\n<li>You can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Exponentiation_assignment\" rel=\"nofollow noreferrer\"><code>**</code></a> operator to raise a value to a power.</li>\n</ul>\n<h2>Examples</h2>\n<pre><code>const computeBMI = (weight, height, country) => {\n const FEET_2_METERS = 0.3048;\n const BMI_SCALE = 0.82;\n const COUNTRIES = ["Chad", "Sierra Leone", "Mali", "Gambia", "Uganda", "Ghana", "Senegal", "Somalia", "Ivory Coast", "Isreal"];\n return Math.round(weight / (height * FEET_2_METERS) ** 2 *\n (COUNTRIES.includes(country) ? BMI_SCALE : 1));\n \n};\n</code></pre>\n<p>Though it would be better to have the constants held in closure if you are to use them in other functions.</p>\n<pre><code>const compute = (()=> {\n const FEET_2_METERS = 0.3048;\n const BMI_SCALE = 0.82;\n const COUNTRIES = ["Chad", "Sierra Leone", "Mali", "Gambia", "Uganda", "Ghana", "Senegal", "Somalia", "Ivory Coast", "Isreal"]; \n return {\n BMI(weight, height, country) {\n return Math.round(weight / (height * FEET_2_METERS) ** 2 * (COUNTRIES.includes(country) ? BMI_SCALE : 1));\n }\n };\n})();\n\ncompute.BMI(90, 6.2, "Somewhere");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:32:22.623",
"Id": "424923",
"Score": "0",
"body": "Thank you for your response"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:59:51.520",
"Id": "219937",
"ParentId": "219920",
"Score": "1"
}
},
{
"body": "<p>This is pretty much how I would do it. Only part that you can trim down a bit is the use of for loop for finding out if the person is from the list of countries. There you can use countries.indexOf(country) that returns the index of the country in the array or -1 if the country is not in the array. You can use that in the if clause.</p>\n\n<p>Otherwise it looks good to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T08:50:10.090",
"Id": "219962",
"ParentId": "219920",
"Score": "1"
}
},
{
"body": "<p>Your code looks quite good already. However there are a few details to improve:</p>\n\n<p>1) There is <code>Array.includes</code> which will abstract away the <code>for</code> loop, making the code more concise.</p>\n\n<p>2) You use <code>bmiTotal</code> and <code>BMI</code>, although both mean the same.</p>\n\n<pre><code> const countriesWithLowerBIP = [\"Chad\", \"Sierra Leone\", \"Mali\", \"Gambia\", \"Uganda\", \"Ghana\", \"Senegal\", \"Somalia\", \"Ivory Coast\", \"Isreal\"];\n\n const computeBMI = (weight /*in kg*/, height /*in feet*/, country) => {\n const heightInMeters = height * 0.3048;\n let BMI = weight / (heightInMeters ** 2);\n\n if (countriesWithLowerBIP.includes(country)) \n BMI *= 0.82;\n\n return Math.round(BMI, 2);\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T10:36:37.983",
"Id": "424989",
"Score": "0",
"body": "odd i could have sworn you only had a single asterisk i must have misread"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T09:07:50.017",
"Id": "219963",
"ParentId": "219920",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T09:37:40.533",
"Id": "219920",
"Score": "3",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Computing the BMI"
} | 219920 |
<p>I have developed a tic-tac-toe game in native JavaScript.
Can you tell me how to optimize more and what are the missing things? <a href="https://jsbin.com/wabigon/edit?html,css,js,output" rel="noreferrer">JSBIN</a></p>
<p>The logic, modular approach, testable and scalable?</p>
<pre><code>(function() {
var playerOneData = {
name: null,
arr: []
};
var playerTwoData = {
name: null,
arr: []
};
winnerFound = false;
var clickCount = 2;
var start = document.getElementById('start');
var resultsList = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
var setApplicationView = function(screenId, display) {
// hide user infor form
document.getElementById(screenId).style.display = display;
};
start.addEventListener('click', function() {
// fetch username
playerOneData.name = document.getElementById('player-one-name').value;
playerTwoData.name = document.getElementById('player-two-name').value;
// hide user info form
setApplicationView('user', 'none');
// show game board
setApplicationView('game-board', 'block');
// set the player's name
document.querySelector('#p1-info span').innerHTML = playerOneData.name;
document.querySelector('#p2-info span').innerHTML = playerTwoData.name;
});
var ifClicked = function(index, tile) {
var i = 0;
while (i < tile.length) {
if (index == tile[i])
return false;
i++;
}
return true
};
var selectedTiles = [];
var winnerFinder = function(playersData, resultsList) {
if(playersData.arr.length<2) return true;
var player = playersData.arr;
var i = 0;
resultsList.forEach(function(element) {
i = 0;
player.forEach(function(ele) {
if (element.indexOf(ele) >= 0) {
i++;
}
});
if (i == element.length) {
matrix.removeEventListener('click', startMatrix);
document.getElementById('result').innerHTML = "Winner is " + playersData.name;
winnerFound = true;
return false;
}
});
};
var matrix = document.getElementById('matrix');
var startMatrix = function($event) {
var target = $event.target;
var tileIndex = +target.getAttribute('tile-index');
var alreadyClickedStatus = ifClicked(tileIndex, selectedTiles);
if (target.className === 'tile' && alreadyClickedStatus === true) {
selectedTiles.push(tileIndex);
if (clickCount % 2 === 0) {
playerOneData.arr.push(tileIndex);
target.className = 'tile red';
if (winnerFinder(playerOneData, resultsList) === false) {
matrix.removeEventListener('click', startMatrix);
}
} else {
playerTwoData.arr.push(tileIndex);
target.className = 'tile blue';
if (winnerFinder(playerTwoData, resultsList) === false) {
matrix.removeEventListener('click', startMatrix);
}
}
clickCount++;
if (clickCount === 11 && winnerFound === false) {
document.getElementById('result').innerHTML = 'Match drawn';
}
}
}
matrix.addEventListener('click', startMatrix);
var resetBoard = function() {
winnerFound = false;
clickCount = 2;
matrix.addEventListener('click', startMatrix);
document.getElementById('result').innerHTML = '';
selectedTiles = [];
var tile = document.querySelectorAll('.tile')
tile.forEach(function(ele, index) {
tile[index].className = 'tile';
});
playerOneData.arr = [];
playerTwoData.arr = [];
};
var restart = document.getElementById('restart');
restart.addEventListener('click', function() {
resetBoard();
});
var newGame = document.getElementById('new-game');
newGame.addEventListener('click', function() {
// show user info form
setApplicationView('user', 'block');
// hide game board
setApplicationView('game-board', 'none');
resetBoard();
});
})();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T12:22:14.863",
"Id": "424880",
"Score": "1",
"body": "Hey, since this question involves the DOM, you will need to include the associated HTML."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T05:58:16.847",
"Id": "425002",
"Score": "0",
"body": "Please visit if you miss the application link https://jsbin.com/wabigon/edit?html,css,js,output"
}
] | [
{
"body": "<p>Note, some of these require a build process</p>\n\n<ul>\n<li>the iife should be added in the build process, it's distracting</li>\n<li>The code doesn't expose anything. It's untestable. </li>\n<li>var should be let or const</li>\n<li>You can use arrow functions to turn some of the functions into one liners</li>\n<li>Inconsistent formatting - I recommend getting a linter</li>\n<li>setApplicationView - Should probably be replaced with show/hide functions. The current name is not very descriptive to me.</li>\n<li>// hide game board - You can make this a function and get rid of the comment. Several other similar issues.</li>\n<li>ifClicked - A function name should generally describe what the functions does, not what happened when it was called. You could also just inline it.</li>\n<li>winnerFinder - It would be so much nicer if this was called findWinner, and returned the result instead of storing it globally. Then you could test it as well.\nAs it stands, it actually returns false when winnerFound is true. Even more confusing.</li>\n<li>winnerFinder - You can use player.filter here to get rid of the index variable</li>\n<li>playerData.arr - What is arr?</li>\n<li>var player = playersData.arr; - How can a player be an array?</li>\n<li>document.getElementById - You can run all these calls at the top to shorten the code and get rid of unnecessary dom queries.</li>\n<li>innerHTML - It's quite hard to tell how this whole thing works with view logic and game logic all mixed in together.\nIn general I would recommend separating the view logic from the game logic as much as possible, and even better would be to make the view logic declarative.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:07:12.470",
"Id": "425059",
"Score": "0",
"body": "Magnus thanks for the inputs, i just updated the comments as you mentioned above, can you just do one more review? https://jsbin.com/wabigon/edit?html,js,output"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T07:29:49.653",
"Id": "425167",
"Score": "0",
"body": "the updated url is https://jsbin.com/wabigon/18/edit?html,css,js,output"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T09:32:57.970",
"Id": "425497",
"Score": "0",
"body": "You still haven't fixed everything, but it's better. You should read up a bit more on .filter, you can get rid of elementsMatchCount."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T19:29:19.273",
"Id": "219951",
"ParentId": "219922",
"Score": "5"
}
},
{
"body": "<p><strong>Disclosure</strong>: I know that it has been ~6 days since Mangus's answer was submitted and <a href=\"https://codereview.stackexchange.com/questions/219922/tic-tac-toe-code-in-javascript#comment425167_219951\">you have already updated your code</a>. However, I still have suggestions that will hopefully help.</p>\n\n<h2>Your Questions</h2>\n\n<blockquote>\n <p>Can you tell me how to optimize more and what are the missing things?</p>\n</blockquote>\n\n<p>See the suggestions below for optimizing code. I am not really sure what is \"missing\"... that could be a very broad subject.</p>\n\n<blockquote>\n <p>The logic, modular approach, testable and scalable?</p>\n</blockquote>\n\n<p>I'm not sure what exactly to say about the logic. It does seem a bit complex - possibly more complicated than it needs to be. In that same vein, the code that adds and removes event handlers depending on the state of the game seems excessive. Could the click handler just be registered once and have it check the state of the game?</p>\n\n<p>Obviously the code is <em>testable</em> using manual testing. If you want to use automated testing then that may be possible -perhaps with a framework like mocha/chai or something similar. I haven't worked with testing UI code much but you could write unit tests for the various functions.</p>\n\n<h2>Feedback and Suggestions</h2>\n\n<h3>ES-6, constants</h3>\n\n<p>As Magnus's answer mentioned - <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> can be used to limit the scope of variables and avoid accidental re-assignment. And most idiomatic code in c-based languages have constants in all capitals. So you could do that for <code>resultsList</code>. Also, a more appropriate name would be something like <code>WINNING_COMBINATIONS</code> or something instead of <code>RESULTS_LIST</code>, because it is a list of combinations.</p>\n\n<hr>\n\n<h3>DOM references can be simplified</h3>\n\n<p>Let's look at the callback function for the click events for <code>start</code> - every time that function runs, there are DOM queries for four elements: <code>#player-one-name</code>, <code>#player-two-name</code>, <code>#p1-infospan</code>, <code>#p2-info span</code>. Those should all happen once when the DOM is ready and be stored in Javascript variables.</p>\n\n<h3>Scope of variable <code>i</code> in <code>winnerFinder()</code></h3>\n\n<p>In <code>winnerFinder()</code> I see this:</p>\n\n<blockquote>\n<pre><code>var i = 0;\nresultsList.forEach(function(element) {\n i = 0;\n player.forEach(function(ele) {\n if (element.indexOf(ele) >= 0) {\n i++;\n }\n });\n</code></pre>\n</blockquote>\n\n<p>Initially I am confused why <code>i</code> is set to <code>0</code> outside the <code>foreach</code> and then set to <code>0</code> in each iteration. One could just declare <code>i</code> inside the loop, since it doesn't appear to be used outside the inner function. After really thinking about this, <code>i</code> is a count of the elements that are contained with <code>element</code>... so <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter()</code></a> could be used:</p>\n\n<pre><code>i = player.filter(function(ele) {\n return element.indexOf(ele) >= 0;\n}).length;\n</code></pre>\n\n<p>This could also be simplified using arrow function notation:</p>\n\n<pre><code>i = player.filter( ele => element.indexOf(ele) >= 0 ).length;\n</code></pre>\n\n<p>And if <code>element</code> is an array, then <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>Array.includes()</code></a> could be used instead of <code>indexOf()</code>.</p>\n\n<h3>Resetting class names for tiles</h3>\n\n<p>Inside <code>resetBoard</code> I see this:</p>\n\n<blockquote>\n<pre><code>tile.forEach(function(ele, index) {\n tile[index].className = 'tile';\n});\n</code></pre>\n</blockquote>\n\n<p>Why not use <code>ele</code> instead of <code>tile[index]</code>? </p>\n\n<p>It appears that you are removing any color class - so you could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods\" rel=\"nofollow noreferrer\"><code>classList.remove()</code></a> and do something like:</p>\n\n<pre><code>ele.classList.remove('red', 'blue');\n</code></pre>\n\n<p>And <code>classList.add()</code> could be used to add the class name in the <code>startMatrix</code> function.</p>\n\n<h3>Registering the click handler on the restart button</h3>\n\n<p>Towards the end of the JS code I see this:</p>\n\n<blockquote>\n<pre><code>var restart = document.getElementById('restart');\nrestart.addEventListener('click', function() {\n resetBoard();\n});\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p>When adding an event listener with an anonymous function that merely calls a single function, a function reference can be used instead:</p>\n\n<pre><code>restart.addEventListener('click', resetBoard);\n</code></pre></li>\n<li><p><code>restart</code> is only used once so it is a waste of memory to assign it to a variable - use it without the variable:</p>\n\n<pre><code>document.getElementById('restart').addEventListener('click', resetBoard);\n</code></pre>\n\n<p>Though if you take my suggestion of caching DOM references when the DOM is ready, ideally you would use a reference like <code>restartButton</code>:</p>\n\n<pre><code>restartButton.addEventListener('click', resetBoard);\n</code></pre></li>\n</ol>\n\n<h3>click handler function: <code>startMatrix()</code></h3>\n\n<p>The name of this function could have a more appropriate name, like <code>matrixClickHandler()</code> or something along those lines.</p>\n\n<p>I see it accepts the <code>event</code> parameter, but as <code>$event</code>. </p>\n\n<pre><code>var startMatrix = function($event) {\n var target = $event.target;\n</code></pre>\n\n<p>It isn't wrong to name variables with a dollar sign in the beginning. jQuery code has a convention of doing this but many JavaScript developers believe that should be left to jQuery core code or plugins, or variables that come from library code like jQuery. This event object should just be <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent\" rel=\"nofollow noreferrer\">MouseEvent</a>, so there isn't really a need to prefix it with a dollar sign. See responses to <a href=\"https://stackoverflow.com/q/205853/1575353\">Why would a JavaScript variable start with a dollar sign?</a> for more context. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:01:56.387",
"Id": "220311",
"ParentId": "219922",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219951",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T11:25:33.697",
"Id": "219922",
"Score": "6",
"Tags": [
"javascript",
"game",
"tic-tac-toe",
"event-handling",
"dom"
],
"Title": "Tic-Tac-Toe code in JavaScript"
} | 219922 |
<blockquote>
<p>Algorithm: Determine if an array of arrays of characters can be
concatenated in order, into a substring of haystack.</p>
<p>Example:</p>
<pre><code>[['a','A','@'], ['b','B','8'], ['c','(','[']]
</code></pre>
<p>This list can be combined by selecting from each of the subarrays in
order, such as:</p>
<p><code>abc, ab(, ab[, Abc, Ab(</code> etc.</p>
<p>Are any of these combinations substrings of the search string?</p>
<pre><code>"123 easy as Ab(" # True
"123 easy as Abb" # False
"123 easy as @b(" # True
"123 easy as Abc" # False
</code></pre>
</blockquote>
<p>Python 3</p>
<pre><code>combos = [['a','A','@'], ['b','B','8'], ['c','(','[']]
search = "123 easy as Ab(" # True
def find_mutated_string(offset, combos, search):
for i, char in enumerate(search):
for mutant in combos[offset]:
if mutant == char:
if len(combos) == (offset+1):
# Last letter combo found
return True
else:
return find_mutated_string(offset+1, combos, search[i+1:])
# Didn't find mutant char in search string
return False
print(find_mutated_string(0, combos, search))
</code></pre>
| [] | [
{
"body": "<h1>bug</h1>\n\n<p>You don't reset the <code>offset</code> when there is a mismatch, so <code>\"123 easy as b(\"</code> also returns <code>True</code>. Just add:</p>\n\n<pre><code> else:\n offset = 0\n</code></pre>\n\n<h1>optional parameter <code>offset</code></h1>\n\n<p>The caller of the function should not care about the offset if he wants to check whether a combination is part of the string. I would change the method signature to <code>def find_mutated_string2(combos, search, offset=0)</code>. Then your user doesn't need to worry about this</p>\n\n<h1>in</h1>\n\n<p>Python has the <code>in</code> statement.</p>\n\n<p>Your code says</p>\n\n<pre><code> for mutant in combos[offset]:\n if mutant == char:\n</code></pre>\n\n<p>but actually mean: <code>if char in combos[offset]</code></p>\n\n<p>Since <code>in</code> in a <code>list</code> traverses the list to look for a match, while set uses a lookup, defining the combos as <code>set</code>s helps here</p>\n\n<pre><code>combos = [{\"@\", \"A\", \"a\"}, {\"8\", \"B\", \"b\"}, {\"(\", \"[\", \"c\"}]\n\n\ndef find_mutated_string2(combos, search, offset=0):\n for i, char in enumerate(search):\n if char in combos[offset]:\n if len(combos) == (offset + 1):\n return True\n else:\n return find_mutated_string2(combos, search[i+1:], offset+1)\n else:\n offset = 0\n return False\n</code></pre>\n\n<h1>match substring</h1>\n\n<p>You could write a helper function that takes a substring and checks whether this matches the combo's</p>\n\n<pre><code>def matches_combos(substring, combos):\n return len(substring) == len(combos) and all(\n char in combo for char, combo in zip(substring, combos)\n )\n</code></pre>\n\n<p>This can be easily tested:</p>\n\n<pre><code>test_cases = {\n \"abc\": True,\n \"Ab[\": True,\n \"abd\": False,\n \"ab\": False,\n \"abcd\": False,\n}\nfor substring, answer in test_cases.items():\n result = matches_combos(substring, combos)\n assert result == answer\n</code></pre>\n\n<h1>recursion</h1>\n\n<p>If your string is long, you will run into the <a href=\"https://stackoverflow.com/q/3323001/1562285\">recursion limit</a>. </p>\n\n<pre><code>for i in range(10000):\n try:\n _ = find_mutated_string2(combos, \"a\"*i)\n except RecursionError:\n print(f\"fails for string length: {i}\")\n break\n</code></pre>\n\n<blockquote>\n<pre><code>fails for string length: 5921\n</code></pre>\n</blockquote>\n\n<p>for a recursionlimit of 3000</p>\n\n<p>You can easily rewrite this proble iteratively</p>\n\n<pre><code>def find_mutated_string3(combos, search):\n if len(search) < len(combos):\n return False\n for i in range(len(search) - 2):\n substring = search[i : i + len(combos)]\n if matches_combos(substring, combos):\n return True\n</code></pre>\n\n<p>or using <code>any</code></p>\n\n<pre><code>def find_mutated_string4(combos, search):\n if len(search) < len(combos):\n return False\n return any(\n matches_combos(search[i : i + len(combos)], combos)\n for i in range(len(search) - 2)\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:01:55.743",
"Id": "424920",
"Score": "0",
"body": "Thanks a bunch! How likely am I to hit the recursion limit? I guess the search string must be at least 998 characters or so for this to happen?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:42:51.963",
"Id": "219929",
"ParentId": "219923",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:10:46.173",
"Id": "219923",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"strings"
],
"Title": "Determine if an array of arrays of characters can be concatenated in order, into a substring of haystack"
} | 219923 |
<p>The <code>.proto</code> file is as below:</p>
<pre><code>syntax = "proto3";
package bamboo;
// -----------------Cart service-----------------
service CartService {
rpc AddItem(AddItemRequest) returns (Empty) {}
rpc GetCart(GetCartRequest) returns (Cart) {}
rpc EmptyCart(EmptyCartRequest) returns (Empty) {}
}
message CartItem {
string product_id = 1;
int32 quantity = 2;
}
message AddItemRequest {
string user_id = 1;
CartItem item = 2;
}
message EmptyCartRequest {
string user_id = 1;
}
message GetCartRequest {
string user_id = 1;
}
message Cart {
string user_id = 1;
repeated CartItem items = 2;
}
message Empty {}
</code></pre>
<p>And I have a <code>Cart</code> service on gRPC that is as simple as below:</p>
<pre><code>from grpczoo import bamboo_pb2_grpc, bamboo_pb2
from concurrent import futures
import grpc
import time
class CartService(bamboo_pb2_grpc.CartServiceServicer):
def AddItem(self, request, context):
print(request.user_id, request.item)
return bamboo_pb2.Empty()
if __name__ == "__main__":
channel = grpc.insecure_channel('127.0.0.1')
cart_stub = bamboo_pb2_grpc.CartServiceStub(channel)
# create gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# add class to gRPC server
service = CartService()
bamboo_pb2_grpc.add_CartServiceServicer_to_server(service, server)
# start server
server.add_insecure_port('[::]:9000')
server.start()
# keep alive
try:
while True:
time.sleep(10000)
except KeyboardInterrupt:
server.stop(0)
</code></pre>
<p>Let's assume that starting a service like above seems good when you have 40 services (We can create a base class for starting a service)</p>
<p>The most annoying part of the system is where I have to initiate a client when I need to send a RPC call to a service (here cart service):</p>
<pre><code>import grpc
# set up server stub
from grpczoo import bamboo_pb2_grpc, bamboo_pb2
channel = grpc.insecure_channel('localhost:9000')
stub = bamboo_pb2_grpc.CartServiceStub(channel)
# form request
request = bamboo_pb2.AddItemRequest(user_id="123", item={'product_id': '21', 'quantity': 2})
# make call to server
response = stub.AddItem(request)
print(response)
</code></pre>
<p>As you can see for a simple RPC call like above I have to open channel to that service and form a request and then call the remote method <code>AddItem</code>. In a real world micro-service project I have to call at least 5 different methods and for each I have to create a channel and for the request and so on.</p>
<p><strong>The question is</strong> how should I manage RPC calls to different methods when project gets bigger and I have 20 to 50 different services? The above code does not seems maintainable at all. How do you handle such cases?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T18:12:19.350",
"Id": "424952",
"Score": "0",
"body": "You should change your title according to [*Titling your question*](https://codereview.stackexchange.com/help/how-to-ask) to make it more descriptive."
}
] | [
{
"body": "<p>Worked with gRPC client in C#. There you can initialize the client in the constructor with no additional code needed on request. It should be the same in Python.</p>\n\n<pre><code>public MyClient(IConfiguration configuration, ILogger < MyClient > logger) {\n _logger = logger;\n _configuration = configuration;\n var config = _configuration.GetGrpcConfigObject(...);\n var myConfig = config.HostName + \":\" + config.Port;\n _channel = new Channel(myConfig, ChannelCredentials.Insecure);\n _client = new ServiceClient(_channel);\n}\n\npublic async Task <IEnumerable<Model.Permission>> GetPermissions() {\n IEnumerable <Model.Permission> resultList = null;\n try {\n PermissionResponse response = await _client.GetPermissionsAsync(new Empty());\n resultList = _mapper.Map <IEnumerable <Permission > , IEnumerable <Model.Permission >> (response.PermissionList);\n\n } catch (Exception ex) {\n _logger.LogError($ \"BatchSave failed:{ex}\");\n }\n return resultList;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:12:43.220",
"Id": "230749",
"ParentId": "219924",
"Score": "0"
}
},
{
"body": "<h2>Keep-alive</h2>\n<p>Your <code>sleep</code> method is curious. There are alternates here:</p>\n<p><a href=\"https://stackoverflow.com/questions/20170251/how-to-run-the-python-program-forever\">https://stackoverflow.com/questions/20170251/how-to-run-the-python-program-forever</a></p>\n<p>but those are generic to Python; there is a better option for <a href=\"https://grpc.io/docs/languages/python/basics/\" rel=\"nofollow noreferrer\">gRPC</a>:</p>\n<blockquote>\n<p>In this case, you can call <code>server.wait_for_termination()</code> to cleanly block the calling thread until the server terminates.</p>\n</blockquote>\n<h2>Stopping</h2>\n<p>You should not only call it on <code>KeyboardInterrupt</code>; you should put it in a <code>finally</code>:</p>\n<pre><code> server.start()\n try:\n # ...\n finally:\n server.stop(0)\n</code></pre>\n<p>This way, the server will be stopped if the user breaks with Ctrl+C, or if there is any other exception. However, I doubt it's necessary to call this at all if you use <code>wait_for_termination</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-11T15:59:18.783",
"Id": "245327",
"ParentId": "219924",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:36:16.253",
"Id": "219924",
"Score": "6",
"Tags": [
"python",
"server",
"e-commerce",
"client",
"grpc"
],
"Title": "Python gRPC shopping cart service"
} | 219924 |
<p>I'm writing a simulator which checks how many balls we need to occupy every box or how many balls we need for any box has at least 2 balls (birthday paradox). I wrote the script in python and it is so slow. My friend wrote a program in C++ and the script is much faster. For boxes_max_num = 1000 it takes few minutes when in my python script it takes 'eternity'.</p>
<p>There is my code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def check_every_box_is_occupied(boxes):
for box in boxes:
if box == 0:
return False
return True
def check_birthday_paradox(boxes):
for box in boxes:
if box >= 2:
return True
return False
def main():
number_of_tests = 250
birthday_paradox_graph = [[], []]
every_box_is_occupied_graph = [[], []]
boxes_max_num = 1000
for number_of_boxes in range(10, boxes_max_num + 1, 1):
print(number_of_boxes)
average_frequency_birthday_paradox = 0
average_frequency_every_box_is_occupied = 0
for index in range(number_of_tests):
number_of_balls = 1
boxes = np.array([0] * number_of_boxes)
while True:
boxes[np.random.randint(number_of_boxes)] += 1
if check_birthday_paradox(boxes):
average_frequency_birthday_paradox += number_of_balls
break
number_of_balls += 1
number_of_balls = number_of_boxes
boxes = np.array([0] * number_of_boxes)
while True:
boxes[np.random.randint(number_of_boxes)] += 1
if check_every_box_is_occupied(boxes):
average_frequency_every_box_is_occupied += number_of_balls
break
number_of_balls += 1
plt.rcParams.update({'font.size': 15})
birthday_paradox_graph[0].append(number_of_boxes)
birthday_paradox_graph[1].append(average_frequency_birthday_paradox / number_of_tests)
every_box_is_occupied_graph[0].append(number_of_boxes)
every_box_is_occupied_graph[1].append(average_frequency_every_box_is_occupied / number_of_tests)
plt.figure(1)
plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')
plt.title("Conajmniej jedna urna ma conajmniej dwie kule")
plt.xlabel("Liczba urn")
plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
plt.figure(2)
plt.title("Wszystkie urny są zapełnione")
plt.xlabel("Liczba urn")
plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')
plt.show()
if __name__ == '__main__':
main()
</code></pre>
<p>Can you help me to improve the code to make it faster? Is it possible in raw python?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:27:34.607",
"Id": "424900",
"Score": "2",
"body": "@Slothario Comments arn't the place to post answers, and con be deleted at any time without notice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:40:48.197",
"Id": "424916",
"Score": "1",
"body": "Regarding `for number_of_boxes in range(10, boxes_max_num + 1, 1)`, that's going to perform the following tests for _every_ number between 10 and `boxes_max_num` _+1_. Is that the intended behavior?"
}
] | [
{
"body": "<h1>Format</h1>\n\n<p>Firstly when performance is a concern you should firstly make the code as readable as possible. This is as when looking for performance gains it reduces the readability of the code, and as this is an incremental process it slowly degrades your code to possibly unmanageable levels, whilst making it harder for you to accurately improve performance. And is basically a modern explanation of the house of the rock parable.</p>\n\n<p>You have some issues a linter can notice:</p>\n\n<ul>\n<li>Imports should be ordered alphabetically so they are easier to read when there's lots of them.</li>\n<li><code>index</code> is unused, and so should be named <code>_</code> or <code>_index</code>.</li>\n<li>You should try to keep lines no longer than 79 characters wide.</li>\n<li>Don't mix quote delimiters, pick either <code>'</code> or <code>\"</code>.</li>\n<li>It's good that you have kept PEP8 spacing between your functions, it should be noted this spacing is between functions and anything, and so having one space between <code>main</code> and the main guard is a violation of this.</li>\n</ul>\n\n<p>From here I'd also:</p>\n\n<ul>\n<li>Split <code>main</code> into a program that performs the <code>birthday_problem</code> and the one that is <code>main</code>.</li>\n<li>Replace <code>check_every_box_is_occupied</code> with <code>all</code>.</li>\n<li>Replace <code>check_birthday_paradox</code> with <code>any</code> and a comprehension.</li>\n<li>Move the generation of infinite amounts of random numbers out of <code>birthday_problem</code>, by creating an infinite generator.</li>\n<li>Wrap the infinite generator in an enumerate to simplify the <code>number_of_balls</code> incrementation.</li>\n<li>Move the <code>while True</code> loops into their own functions.</li>\n<li>Change the <code>for index</code> loop into two comprehensions wrapped in a <code>sum</code>.</li>\n<li>Simplify your naming, you have very long variables that only make the code harder to understand.</li>\n<li>It'd be simpler if you set <code>birthday_paradox_graph[0]</code> to the same <code>range</code> that you iterate over.</li>\n</ul>\n\n<p>And so would get the following code. I have left main uncleaned:</p>\n\n<pre><code>import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef random_numbers(limit):\n while True:\n yield np.random.randint(limit)\n\n\ndef check_birthday_paradox(values):\n return any(value >= 2 for value in values)\n\n\ndef simulate_one_pairing(size):\n boxes = np.array([0] * size)\n for number_of_balls, choice in enumerate(random_numbers(size), 1):\n boxes[choice] += 1\n if check_birthday_paradox(boxes):\n return number_of_balls\n\n\ndef simulate_all_days_set(size):\n boxes = np.array([0] * size)\n for number_of_balls, choice in enumerate(random_numbers(size), size):\n boxes[choice] += 1\n if all(boxes):\n return number_of_balls\n\n\ndef birthday_problem(tests, boxes_limit):\n domain = range(10, boxes_limit + 1, 1)\n paired = [domain, []]\n every_box_is_occupied_graph = [domain, []]\n for boxes in domain:\n total = sum(simulate_one_pairing(boxes) for _ in range(tests))\n paired[1].append(total / tests)\n\n total = sum(simulate_all_days_set(boxes) for _ in range(tests))\n every_box_is_occupied_graph[1].append(total / tests)\n return paired, every_box_is_occupied_graph\n\n\ndef main():\n number_of_tests = 250\n boxes_max_num = 1000\n birthday_paradox_graph, every_box_is_occupied_graph = birthday_problem(number_of_tests, boxes_max_num)\n plt.rcParams.update({'font.size': 15})\n plt.figure(1)\n plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')\n plt.title(\"Conajmniej jedna urna ma conajmniej dwie kule\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.figure(2)\n plt.title(\"Wszystkie urny są zapełnione\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.plot(\n every_box_is_occupied_graph[0],\n every_box_is_occupied_graph[1],\n 'ko')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>From this I can see a couple of problems off the bat.</p>\n\n<ol>\n<li>Why does <code>simulate_all_days_set</code>'s start enumerate start at <code>size</code>?<br>\nI'll assume this is a mistake.</li>\n<li>The function <code>check_birthday_paradox</code> is wasting time as it runs in <span class=\"math-container\">\\$O(n)\\$</span> time, where all you need to check is that <code>boxes[choice]</code> is equal or greater than two.</li>\n<li>You're building two simulations each test <code>simulate_one_pairing</code> and <code>simulate_all_days_set</code>, you can just make this a single loop and reduce duplicate simulations.</li>\n<li><p>The performance of <code>np.random.randint</code> should be tested against when passing <code>size=None</code> and <code>size=n</code>. To see if chunking can reduce the performance.</p>\n\n<p>And yes it does increase performance: <<a href=\"https://github.com/Peilonrayz/Stack-Exchange-contributions/blob/master/code-review/219925/extra/chunked_randoms.py\" rel=\"nofollow noreferrer\">source</a>></p>\n\n<p><a href=\"https://i.stack.imgur.com/Uc52W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Uc52W.png\" alt=\"Comparison of random with chunk sizes\"></a></p>\n\n<p>And so I'd use chunk at the same size as <code>size</code>. You may be able to get better performance if you use a different value however.</p></li>\n</ol>\n\n<pre><code>import matplotlib.pyplot as plt\nimport numpy as np\nimport timeit\n\n\ndef random_numbers(limit):\n while True:\n yield from np.random.randint(limit, size=limit)\n\n\ndef simulate(size):\n boxes = np.array([0] * size)\n pair = None\n all_set = None\n for iteration, choice in enumerate(random_numbers(size), 1):\n boxes[choice] += 1\n if pair is None and boxes[choice] >= 2:\n pair = iteration\n if all_set is not None:\n break\n if all_set is None and all(boxes):\n all_set = iteration\n if pair is not None:\n break\n return pair, all_set\n\n\ndef birthday_problem(tests, boxes_limit):\n domain = range(10, boxes_limit + 1, 1)\n paired = [domain, []]\n all_set = [domain, []]\n for boxes in domain:\n pairs, all_sets = zip(*(simulate(boxes) for _ in range(tests)))\n paired[1].append(sum(pairs) / tests)\n all_set[1].append(sum(all_sets) / tests)\n return paired, all_set\n\n\ndef main():\n start = timeit.default_timer()\n number_of_tests = 20\n boxes_max_num = 200\n birthday_paradox_graph, every_box_is_occupied_graph = birthday_problem(number_of_tests, boxes_max_num)\n print(timeit.default_timer() - start)\n plt.rcParams.update({'font.size': 15})\n plt.figure(1)\n plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')\n plt.title(\"Conajmniej jedna urna ma conajmniej dwie kule\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.figure(2)\n plt.title(\"Wszystkie urny są zapełnione\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.plot(\n every_box_is_occupied_graph[0],\n every_box_is_occupied_graph[1],\n 'ko')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I tested both yours and mine and at <code>number_of_tests</code>=20 and <code>boxes_max_num</code>=200. You can see this in the code above. Yours unchanged runs in ~13.5-14 seconds. Mine runs in ~3.5-4 seconds.</p>\n\n<p>My code takes ~16.5 seconds to run at <code>boxes_max_num</code>=1000 and <code>number_of_tests</code>=1. This means it will take roughly an hour to run all of your tests. As I've taken the low-hanging fruit if you need it to be faster, then you'll have to use a <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profiler</a>. Your code also is very unlikely to be as fast as your friends, as Python is slow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:45:44.097",
"Id": "219940",
"ParentId": "219925",
"Score": "2"
}
},
{
"body": "<p>First, let's break some of the loop bodies out into their own functions. If you're having difficulty reasoning about the behavior of your code, then you can <em>definitely</em> afford the (theoretical) performance hit of a function call.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplotlib.pyplot as plt\n\ndef check_every_box_is_occupied(boxes):\n for box in boxes:\n if box == 0:\n return False\n return True\n\ndef check_birthday_paradox(boxes):\n for box in boxes:\n if box >= 2:\n return True\n return False\n\ndef run_test(number_of_boxes):\n number_of_balls = 1\n boxes = np.array([0] * number_of_boxes)\n result = {\n 'balls_for_paradox': 0,\n 'balls_for_full': 0,\n }\n while True:\n boxes[np.random.randint(number_of_boxes)] += 1\n if check_birthday_paradox(boxes):\n result['balls_for_paradox'] = number_of_balls\n break\n number_of_balls += 1\n number_of_balls = number_of_boxes\n boxes = np.array([0] * number_of_boxes)\n while True:\n boxes[np.random.randint(number_of_boxes)] += 1\n if check_every_box_is_occupied(boxes):\n result['balls_for_full'] = number_of_balls\n break\n number_of_balls += 1\n return result\n\ndef run_tests(number_of_boxes, number_of_tests):\n print(number_of_boxes)\n average_frequency_birthday_paradox = 0\n average_frequency_every_box_is_occupied = 0\n for index in range(number_of_tests):\n result = run_test(number_of_boxes)\n average_frequency_birthday_paradox += result['balls_for_paradox']\n average_frequency_every_box_is_occupied += result['balls_for_full']\n plt.rcParams.update({'font.size': 15})\n return {\n 'average_frequency_birthday_paradox': average_frequency_birthday_paradox / number_of_tests,\n 'average_frequency_every_box_is_occupied': average_frequency_every_box_is_occupied / number_of_tests,\n }\n\ndef main():\n number_of_tests = 250\n birthday_paradox_graph = [[], []]\n every_box_is_occupied_graph = [[], []]\n boxes_max_num = 1000\n for number_of_boxes in range(10, boxes_max_num + 1, 1):\n results = run_tests(number_of_boxes, number_of_tests)\n birthday_paradox_graph[0].append(number_of_boxes)\n birthday_paradox_graph[1].append(results['average_frequency_birthday_paradox'])\n every_box_is_occupied_graph[0].append(number_of_boxes)\n every_box_is_occupied_graph[1].append(results['average_frequency_every_box_is_occupied'])\n plt.figure(1)\n plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')\n plt.title(\"Conajmniej jedna urna ma conajmniej dwie kule\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.figure(2)\n plt.title(\"Wszystkie urny są zapełnione\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')\n plt.show()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>The above is a pretty literal translation of your code. I introduced some dictionaries as return values; tuples would have worked but would have required some kind of documentation. Explicit classes would be more maintainable, but let's not worry about that for this project.</p>\n\n<p>Next, <strong>I'm pretty sure you have a math error in your calculations of the \"every box occupied\" condition.</strong> The line where you <em>reset</em> <code>number of balls</code> should be resetting it to <code>1</code>, right?<br>\nI'm also going to use explicit <code>else</code> statements in this round, because I think they look better.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def run_test(number_of_boxes):\n number_of_balls = 1\n boxes = np.array([0] * number_of_boxes)\n result = {\n 'balls_for_paradox': 0,\n 'balls_for_full': 0,\n }\n while True:\n boxes[np.random.randint(number_of_boxes)] += 1\n if check_birthday_paradox(boxes):\n result['balls_for_paradox'] = number_of_balls\n break\n else:\n number_of_balls += 1\n number_of_balls = 1\n boxes = np.array([0] * number_of_boxes)\n while True:\n boxes[np.random.randint(number_of_boxes)] += 1\n if check_every_box_is_occupied(boxes):\n result['balls_for_full'] = number_of_balls\n break\n else:\n number_of_balls += 1\n return result\n</code></pre>\n\n<p>Now we can implement <a href=\"https://codereview.stackexchange.com/users/190497/slothario\">Slothario</a>'s suggestion, but we'll have to rethink how we're running these tests. The birthday paradox is easy enough, but to avoid checking every cell for the \"all occupied\" condition, we need to <em>remember</em> cells we've already visited. We can think of this as crossing items off a list. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def run_test(number_of_boxes):\n number_of_balls = 1\n boxes = np.array([0] * number_of_boxes)\n result = {\n 'balls_for_paradox': 0,\n 'balls_for_full': 0,\n }\n while True:\n box = np.random.randint(number_of_boxes)\n boxes[box] += 1\n if 2 <= boxes[box]:\n result['balls_for_paradox'] = number_of_balls\n break\n else:\n number_of_balls += 1\n number_of_balls = 1\n boxes = set(range(number_of_boxes))\n while True:\n box = np.random.randint(number_of_boxes)\n if box in boxes:\n boxes.remove(box)\n if not boxes:\n result['balls_for_full'] = number_of_balls\n break\n else:\n number_of_balls += 1\n return result\n</code></pre>\n\n<p>We have two <em>similar</em> loops. In a lot of contexts I would suggest that they're different enough that they should go in completely separate functions, but since we're going for speed, maybe we should combine them. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def run_test(number_of_boxes):\n number_of_balls = 1\n boxes = np.array([0] * number_of_boxes)\n unoccupied_indexes = set(range(number_of_boxes))\n result = {\n 'balls_for_paradox': 0,\n 'balls_for_full': 0,\n }\n while not (result['balls_for_paradox'] and result['balls_for_full']):\n box = np.random.randint(number_of_boxes)\n if not result['balls_for_paradox']:\n boxes[box] += 1\n if 2 <= boxes[box]:\n result['balls_for_paradox'] = number_of_balls\n if not result['balls_for_full']:\n if box in unoccupied_indexes:\n unoccupied_indexes.remove(box)\n if not unoccupied_indexes:\n result['balls_for_full'] = number_of_balls\n number_of_balls += 1\n return result\n</code></pre>\n\n<p>Let's tidy up some other little things. You had a call to set the font-size of your plot inside one of the loops, I don't think that belonged. I also removed a print statement, which takes up more time than you might think. I'm also replacing several of the loops with list comprehensions, which won't improve performance but it's a little nicer to read. We could go a lot further in this direction, but I wanted to keep the basic structure of your code intact.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplotlib.pyplot as plt\n\ndef check_every_box_is_occupied(boxes):\n for box in boxes:\n if box == 0:\n return False\n return True\n\ndef check_birthday_paradox(boxes):\n for box in boxes:\n if box >= 2:\n return True\n return False\n\ndef run_test(number_of_boxes):\n number_of_balls = 1\n boxes = np.array([0] * number_of_boxes)\n unoccupied_indexes = set(range(number_of_boxes))\n result = {\n 'balls_for_paradox': 0,\n 'balls_for_full': 0,\n }\n while not (result['balls_for_paradox'] and result['balls_for_full']):\n box = np.random.randint(number_of_boxes)\n if not result['balls_for_paradox']:\n boxes[box] += 1\n if 2 <= boxes[box]:\n result['balls_for_paradox'] = number_of_balls\n if not result['balls_for_full']:\n if box in unoccupied_indexes:\n unoccupied_indexes.remove(box)\n if not unoccupied_indexes:\n result['balls_for_full'] = number_of_balls\n number_of_balls += 1\n return result\n\ndef run_tests(number_of_boxes, number_of_tests):\n results = [run_test(number_of_boxes) for _ in range(number_of_tests)]\n return {\n 'average_frequency_birthday_paradox': sum([r['balls_for_paradox'] for r in results]) / number_of_tests,\n 'average_frequency_every_box_is_occupied': sum([r['balls_for_full'] for r in results]) / number_of_tests,\n }\n\ndef main():\n number_of_tests = 250\n boxes_max_num = 1000\n all_results = [{\n 'n': number_of_boxes,\n 'results': run_tests(number_of_boxes, number_of_tests)\n }\n for number_of_boxes\n in range(10, boxes_max_num + 1, 1)]\n birthday_paradox_graph = [\n [r['n'] for r in all_results],\n [r['results']['average_frequency_birthday_paradox'] for r in all_results]\n ]\n every_box_is_occupied_graph = [\n [r['n'] for r in all_results],\n [r['results']['average_frequency_every_box_is_occupied'] for r in all_results]\n ]\n plt.rcParams.update({'font.size': 15})\n plt.figure(1)\n plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')\n plt.title(\"Conajmniej jedna urna ma conajmniej dwie kule\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.figure(2)\n plt.title(\"Wszystkie urny są zapełnione\")\n plt.xlabel(\"Liczba urn\")\n plt.ylabel(\"Średnia liczba kul potrzebna do spełnienia warunku\")\n plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')\n plt.show()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p><strong>*Runs in ...<br>\nmy paitence ran out. \nBut if I follow <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">Pelionrayz</a> and use <code>boxes_max_num=1000</code> and <code>number_of_tests=1</code>, then it takes about 7 seconds.</strong></p>\n\n<p>(just a heads up that I didn't test ever iteration of this; so i don't know if the earlier versions will actually run.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:55:44.110",
"Id": "424946",
"Score": "0",
"body": "An embarrassing error on the \"code review\" SE: I left in the two unused test functions!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T17:22:12.513",
"Id": "219944",
"ParentId": "219925",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:41:52.540",
"Id": "219925",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"numpy",
"simulation"
],
"Title": "Birthday paradox simulation"
} | 219925 |
<p>I would like to disable the popper.js tooptip if there is an element with a specific class on the page.</p>
<p>Let me explain ... I have a plugin that creates notifications dynamically, these notifications disappear every so often. I would like, that when a notification appears, the tooltip of popper.js will be disabled, and when the notification is closed, the tooltip will be enabled again.</p>
<p>This is what I have implemented so far, it works well, but I was wondering if there was another way a little more elegant.</p>
<pre><code> new Plugin({
callbacks: {
beforeShow: function() {
$('.navbar-nav [title]').tooltip('disable');
},
afterClose: function () {
if (!$('.notification').length) {
$('.navbar-nav [title]').tooltip('enable');
}
}
}
});
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:02:51.437",
"Id": "219931",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Enable/Disable Popper.js tooltip if element exists"
} | 219931 |
<p>Exercise:</p>
<blockquote>
<p>Using a <code>read7()</code> method that returns 7 characters from a file,
implement <code>readN(n)</code> which reads n characters.</p>
<p>For example, given a file with the content <code>"Hello world"</code>, three
<code>read7()</code> returns <code>"Hello w"</code>, <code>"orld"</code> and then <code>""</code>.</p>
</blockquote>
<p>I made a version using <code>std::deque</code>. It seems inefficient to me with all the loops to read/write a string, but I couldn't think of an alternative for this FIFO. Any comments on that part would be especially appreciated.</p>
<pre><code>#include <iostream>
#include <sstream>
#include <deque>
inline auto read7()
{
static std::istringstream is("1234567890123456789012345678901234567890");
char res[8]{};
is.get(res, 8);
return std::string(res);
}
template <typename T1, typename T2>
auto& operator<<(std::deque<T1>& deq, const T2& seq)
{
for (const auto& elm : seq)
{
deq.push_back(elm);
}
return deq;
}
template <typename T1, typename T2>
auto get(std::deque<T2>& deq, std::size_t n)
{
T1 res;
while (res.size() != n && !deq.empty())
{
res += deq.front();
deq.pop_front();
}
return res;
}
auto readN(std::size_t n)
{
static std::deque<char> buffer;
while (n > buffer.size())
{
auto old_sz = buffer.size();
buffer << read7();
if (old_sz == buffer.size())
break;
}
return get<std::string>(buffer, n);
}
int main()
{
std::size_t sz;
while(std::cin >> sz)
std::cout << readN(sz) << '\n';
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Why is <code>read7</code> declared <code>inline</code>? You should only do this when it's needed as an optimization. (And it's particularly confusing when the function contains a <code>static</code> variable.)</p>\n\n<p>It's not necessary for <code>is</code> to be static. It should really be an argument to <code>read7</code>, so it can work on any <code>istream</code>. (In real code, <code>buffer</code> should also be a parameter to <code>readN</code>, but for this toy problem it's reasonable to have it static.)</p>\n\n<p>Bug: what happens if the input contains null characters?</p>\n\n<p>You could avoid the queue by using a string as the queue. You can simply append the result of each <code>read7</code> to it until you have enough characters, then remove and return the first <code>n</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T21:08:04.927",
"Id": "443058",
"Score": "0",
"body": "`is` is static because `read7` is supposed to be that magic function that gives you 7 characters. Maybe like `std::getline`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T21:12:09.803",
"Id": "443059",
"Score": "1",
"body": "Removing first `n` characters from string is really inefficient, isn't it? How is this an improvement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T10:20:37.233",
"Id": "443093",
"Score": "0",
"body": "@Ayxan Making it an argument allows you to read from any stream, for example a file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:02:37.840",
"Id": "443157",
"Score": "0",
"body": "@L.F. `read7` is not a part of the exercise. It's a \"magic\" function that returns 7 characters. If I had the stream in the first place, I would read n characters without the need of `readN`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T01:24:07.793",
"Id": "443193",
"Score": "0",
"body": "@Ayxan Oh, now I understand. That's a really interesting exercise :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T20:40:17.707",
"Id": "227535",
"ParentId": "219939",
"Score": "3"
}
},
{
"body": "<p>Pedantically, none of the included headers are guaranteed to define <code>std::size_t</code>. It is (in principle) possible to implement those headers without defining that type, and we're required to include one of the headers that <em>does</em> define it (e.g. <code><cstddef></code>).</p>\n\n<p>We could avoid the <code>push_back</code> loop by using the <code>std::copy()</code> algorithm with a <code>std::back_inserter</code> as the destination. More simply, we could just use the deque's <code>insert()</code> like this:</p>\n\n<pre><code>template <typename T1, typename T2>\nauto& operator<<(std::deque<T1>& deq, const T2& seq)\n{\n using std::begin();\n using std::end();\n\n deq.insert(end(deq), begin(seq), end(seq));\n return deq;\n}\n</code></pre>\n\n<p>I think the <code>old_sz</code> check in <code>readN()</code> is less clear than simply checking whether the input chunk is an empty string:</p>\n\n<pre><code>std::string s;\nwhile (buffer.size() < n && !(s = read7()).empty()) {\n buffer << std::move(s);\n}\n</code></pre>\n\n<p>Or, just inline the <code><<</code>, given that it's a one-liner and not used anywhere else:</p>\n\n<pre><code>using std::begin();\nusing std::end();\n\nstd::string s;\nwhile (buffer.size() < n && !(s = read7()).empty()) {\n buffer.insert(end(buffer), start(s), end(s));\n}\n</code></pre>\n\n<hr>\n\n<p>On the choice of approach: I probably wouldn't use a deque. We only need to store a surplus of up to 7 characters, which is fine to hold in a string (most implementations use a \"small-string\" optimisation to avoid allocating heap space for the characters). I would implement <code>readN()</code> by starting with an empty, <code>n</code>-capacity string and building it up in place, storing the new surplus back to the string where we keep it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T08:09:26.683",
"Id": "227555",
"ParentId": "219939",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "227555",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:31:26.627",
"Id": "219939",
"Score": "6",
"Tags": [
"c++",
"programming-challenge",
"io"
],
"Title": "Implement a readN() from read7()"
} | 219939 |
<p>This is by far the biggest project i've ever made. The main goal was just to make a bitset class but it expanded into making several classes based off of that main bitset class. Some things I would like suggestions on is how to optimize it better, and if I'm using any bad programming habits or there is a better way of doing something. Thanks.</p>
<p>Classes:</p>
<blockquote>
<p>bitset - This is the base program which has no dependencies and is a
building block for the other classes</p>
<p>i_bitset - This is used to store integers. It is dependant on the
bitset class. It has 5 operator overloads and can convert a bitset to
an integer.</p>
<p>c_bitset - This is used to store chars. It is dependant on the
i_bitset class. It has 4 operator overloads and can convert a bitset
to a char and is used as a building block for s_bitset.</p>
<p>s_bitset - This is used to store strings. It is dependant on the
c_bitset class. It has 5 operator overloads and can convert a bitset
to a string. This class also contains several standard functions for a
string such as append, length, erase and clear.</p>
</blockquote>
<p>Here is the github link to the full project: <a href="https://github.com/CowNation/cpp-Bitset/" rel="nofollow noreferrer">https://github.com/CowNation/cpp-Bitset/</a></p>
<p>There is too much code to paste the entire project all in this thread, but here is a demo of cpp-Bitset in action, the base bitset class and the i_bitset class:</p>
<p>main.cpp:</p>
<pre><code>#include "s_bitset.h"
int main() {
i_bitset set;
set = 176; // = operator is overloaded
std::cout << set << std::endl; // << operator is overloaded
i_bitset k;
k = 176;
std::cout << (set == 420) << std::endl;
std::cout << (set == k) << std::endl;
c_bitset character;
character = 'k';
std::cout << character << std::endl;
s_bitset ree;
ree.Append(character);
ree.Append("k");
s_bitset xd;
xd = ree + " xd";
std::cout << xd << std::endl;
s_bitset jeff;
jeff = "Jeff"; // = operator is overloaded
std::cout << jeff + " _--" << std::endl; // << and + operator are overloaded
for (int i = 0; i < jeff.length(); i++){
jeff.at(i).print();
std::cout << std::endl;
}
s_bitset st;
std::cout << "Enter string: ";
std::cin >> st;
std::cout << st << std::endl;
}
</code></pre>
<p>bitset.h:</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <math.h>
class bitset {
protected:
std::vector< bool >BitSet;
int GetValue(int Index) const;
public:
bitset(int bits);
void setbit(int Index, bool Value);
bool getbit(int Index);
void print();
};
</code></pre>
<p>bitset.cpp:</p>
<pre><code>#include "bitset.h"
int bitset::GetValue(int Index) const {
return pow(2, Index);
}
bitset::bitset(int bits){
BitSet.clear();
for(int i = 0; i < bits; i++){
BitSet.push_back(false);
}
}
void bitset::setbit(int Index, bool Value){
BitSet[Index] = Value;
}
bool bitset::getbit(int Index){
return BitSet[Index];
}
void bitset::print(){
for (int i = 0; i < BitSet.size(); i++)
std::cout << BitSet[i] << "/" << GetValue(i) << " ";
}
</code></pre>
<p>i_bitset.h:</p>
<pre><code>#include "bitset.h"
class i_bitset : public bitset {
private:
int pGet() const;
public:
i_bitset() : bitset(8){}
friend std::ostream & operator<<(std::ostream & _stream, i_bitset const & mc);
operator int() const;
int operator=(const int& b);
bool operator==(const i_bitset& b);
bool operator==(const int& b);
};
i_bitset Integer(int i);
</code></pre>
<p>i_bitset.cpp:</p>
<pre><code>#include "i_bitset.h"
int i_bitset::pGet() const {
int ret = 0;
for (int i = 0; i < BitSet.size(); i++)
ret += BitSet[i] * GetValue(i);
return ret;
}
std::ostream & operator<<(std::ostream & _stream, i_bitset const & mc) {
_stream << mc.pGet();
return _stream;
}
i_bitset::operator int() const {
return pGet();
}
void checkValue(int& iLetter, i_bitset& integer, int Num, int Index){
if (iLetter >= Num && integer.getbit(Index) == false){
integer.setbit(Index, true);
iLetter -= Num;
}
}
i_bitset Integer(int i){
i_bitset integer;
while (i > 0){
checkValue(i, integer, 128, 7);
checkValue(i, integer, 64, 6);
checkValue(i, integer, 32, 5);
checkValue(i, integer, 16, 4);
checkValue(i, integer, 8, 3);
checkValue(i, integer, 4, 2);
checkValue(i, integer, 2, 1);
checkValue(i, integer, 1, 0);
}
return integer;
}
int i_bitset::operator=(const int& b) {
i_bitset integer = Integer(b);
for (int i = 0; i < 8; i++){
setbit(i, integer.getbit(i));
}
return b;
}
bool i_bitset::operator==(const i_bitset& b){
return (int)b == pGet();
}
bool i_bitset::operator==(const int& b){
return b == pGet();
}
</code></pre>
| [] | [
{
"body": "<p>I'm not sure how to review your code, because I don't understand what you're aiming for. There is a <code>std::bitset</code> class but it's different from yours: its size is known at compile-time and it's chiefly designed to function as a group of flags you would have coded into an integer of some kind in a more basic language.</p>\n\n<p>But you use <code>std::vector<bool></code> as the underlying data-structure of your class, which has a different goal, although it's hard to define precisely: <code>std::vector<bool></code> is designed to manage collections of bits whose size isn't known beforehand, so I would say it's best used to represent a collection of something else very densely, or more accurately a collection's projection. An example would be an Eratosthenes's sieve, where each integer (let's say 32 bits) is only considered as whether prime or not (1 bit).</p>\n\n<p>Anyway, you seem to aim for yet something else, something like providing an easier to manipulate binary interface to third-part classes: integers, characters, even strings. I have some reservations about this:</p>\n\n<ol>\n<li><p>binary manipulation is already handy in C++: you have dedicated operators, they aren't arcane C++, there's no need to build a complex class hierarchy to extract one bit from an object.</p></li>\n<li><p>binary manipulation is often not what you desire: when you copy a string, which essentially is a pointer, you don't want to copy that pointer but to copy what is pointed to in a different memory location, and keep a pointer to that new location. The semantic of a class is implemented through its constructor and can't be summed up into its binary lay-out. On that topic, your <code>s_bitset</code> class is ill-named, because it offers the binary representation of a <code>char[]</code>, not of a string.</p></li>\n<li><p>From 1 and 2, I conclude that your project is not well conceived (unless of course it only has a learning purpose), because it ties down the object to its binary representation, and doesn't offer many more functionalities than the language itself. It leads to strange things, like the translation of a vector of booleans into a integer (in <code>int i_bitset::pGet()</code>), although the integer already is a sequence of 0's and 1's.</p></li>\n</ol>\n\n<p>So, my first piece of advice is to think more deeply about what you're trying to achieve, and to look more closely at what's already been done. And then decide: do I want to reinvent the wheel to learn how it rolls? Then re-implement <code>std::bitset</code>, <code>std::vector<bool></code>, or more ambitiously implement a <code>big_integer</code> class; all three offer different challenges: <code>std::bitset</code> is template-programming oriented, <code>std::vector<bool></code> needs memory manipulation and proxies, and <code>big_integer</code> is more mathematically / algorithmically intensive.</p>\n\n<p>Now onto the review of some details in your code:</p>\n\n<ul>\n<li>use initialization lists in constructors:</li>\n</ul>\n\n<p>For instance, when you write:</p>\n\n<pre><code>bitset::bitset(int bits){\n BitSet.clear();\n for(int i = 0; i < bits; i++){\n BitSet.push_back(false);\n }\n}\n</code></pre>\n\n<p>what is done is: <code>Bitset</code> is created and initialized before entering the constructor's body. It is then cleared, which doesn't really make sense because it's empty. Finally, you fill it one bit at a time through proxy references. All this comes at a cost. You could have written:</p>\n\n<pre><code>bitset::bitset(int bits) : Bitset(bits, false) {}\n</code></pre>\n\n<p>Bitset is then directly constructed with these two arguments (number of elements, element initial value).</p>\n\n<ul>\n<li><p>do not assume that integers are 8 bits long. It's generally false: 32- or 64-bits sized integers are more frequent.</p></li>\n<li><p>it isn't idiomatic to take a const reference to a built-in type: so rather <code>int operator=(int b);</code> than <code>int operator=(const int& b);</code></p></li>\n<li><p>it isn't idiomatic, and even surprising, not to return a reference to the <code>bitset</code> in this assignment, so rather <code>bitset& operator=(int b);</code> than <code>int operator=(const int& b);</code>. It allows chained assignment.</p></li>\n<li><p>it is also dangerous to have a constructor and an assignment operator with identical arguments but different semantics: <code>i_bitset bs(8)</code> is a bitset of eight bits, but <code>bs = 8;</code> means it contains the binary representation of eight.</p></li>\n<li><p>try to insulate the basic operations from the more complex ones. For instance, you define a <code>get_bit</code> function, but don't use it in your <code>print</code> function. It's a pity, because you could very well forget to actualize it if you change the underlying data structure (for instance to a <code>std::vector<char></code> instead).</p></li>\n<li><p>try to offer an easier to use interface: it seems you can't initialize a bitset from another one (<code>i_bitset& operator=(const i_bitset& b);</code> for instance.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T12:39:16.430",
"Id": "425195",
"Score": "0",
"body": "Thanks for the in-depth review, the project was initially just for learning. What do you mean by 'std::vector<bool> needs memory manipulation and proxies'? Also, what do you mean by 'try to offer an easier to use interface: it seems you can't initialize a bitset from another one (i_bitset& operator=(const i_bitset& b); for instance.' when you just got done suggesting me to 'it isn't idiomatic, and even surprising, not to return a reference to the bitset in this assignment, so rather bitset& operator=(int b); than int operator=(const int& b);. It allows chained assignment.'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T14:04:07.640",
"Id": "425201",
"Score": "0",
"body": "@CowNation: about `vector<bool>`, memory manipulation because it can be grown or shrinked during execution, proxies because the interface forces you to return a reference to a bit, which can only be done through a proxy class, i.e emulating the behavior of an individual byte. / about the interface: references to built-in types (such as an integer) aren't idiomatic, but references to custom classes -such as your `bitset` are the norm."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:49:46.720",
"Id": "219977",
"ParentId": "219941",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219977",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T16:45:44.967",
"Id": "219941",
"Score": "4",
"Tags": [
"c++",
"integer",
"overloading",
"bitset"
],
"Title": "Program containing several bitset based classes including chars, strings, ints and a base bitset class"
} | 219941 |
<p>I have been working on a side project for input filtering/Validation.</p>
<p>First I would like to go over my interface.</p>
<pre><code>public interface IValidatable<T> : IValidatable
{
MyAction<T> ModifyInput { get; set; }
Predicate<T> PreCheck { get; set; }
bool Equals(object obj);
int GetHashCode();
}
public interface IValidatable
{
}
</code></pre>
<p>The action is used to filter or modify the input data, the predicate is used to check the input meets a bool condition, and standard overrides.</p>
<p>Next up is the implementation of the class. This class provides the backing field and proxy to input of that field. The private data field becomes the instance of the type you pass in with builder class function AddColumnToHeader. </p>
<p>The new thing here is the private function SetData that is ran on sets of the Data Property, which in turn gets a private field, and sets a private field based on configuration passed in, by the builder class function AddPredicateToColumn and AddHandlerToColumn.</p>
<pre><code>public class Validatable<T> : IValidatable<T>
{
public Validatable()
{
}
private T data = default;
public T Data { get => data; set => data = SetData(value); }
public Predicate<T> PreCheck { get; set; } = default;
public MyAction<T> ModifyInput { get; set; } = default;
private T SetData(T _value)
{
if (ModifyInput == default)
{
if (PreCheck != default)
{
if (PreCheck(_value) == true)
{
return _value;
}
return default;
}
return _value;
}
else
{
ModifyInput(ref _value);
if (PreCheck != default)
{
if (PreCheck(_value) == true)
{
return _value;
}
return default;
}
return _value;
}
}
public override bool Equals(object other)
{
Validatable<T> column = other as Validatable<T>;
return column != null &&
EqualityComparer<T>.Default.Equals(Data, column.Data);
}
public override int GetHashCode()
{
return HashCode.Combine(Data);
}
public static bool operator ==(Validatable<T> column1, Validatable<T> column2)
{
return EqualityComparer<Validatable<T>>.Default.Equals(column1, column2);
}
public static bool operator !=(Validatable<T> column1, Validatable<T> column2)
{
return !(column1 == column2);
}
}
</code></pre>
<p>The next class is my builder class. This class builds out the Validatable objects that will be used to input validate the underlying object. It does this using the builder pattern. </p>
<p>The pattern I used for this follows. <code>AddColumnToHeader<T></code> returns the this, so you can chain call it until the number of types fits your needs, and in the last call we have to set <code>true</code> to the 2nd parameter _typeCompleted, to signal the builder can move on to adding predicates and handlers.I do have a need for it to be split up in this way. I want GetTypedRow to return a deep clone of the HeaderContainer object you have defined, enforcing a immutable type on to it, and returning it.. You could remove 2nd parameter from <code>AddColumnToHeader<T></code> and create and add dynamically, without issue I suppose.</p>
<pre><code>public delegate void MyAction<T>(ref T Parameter);
public sealed class ValidatableBuilder
{
private Validatable<T> HeaderColumnFactory<T>() => new Validatable<T>();
public IQueryable<(string Name, IValidatable Value, Type ColumnType)> QueryableHeader { get => HeaderContainer.AsQueryable(); }
private List<(string Name, IValidatable Value, Type ColumnType)> HeaderContainer { get; set; } = default;
private bool TypesCompleted = false;
private bool SetupCompleted = false;
public ValidatableBuilder()
{
HeaderContainer = new List<(string Name, IValidatable Value, Type ColumnType)>();
}
public ValidatableBuilder AddColumnToHeader<T>(string _columnName, bool _typesComplete = false)
{
if (!TypesCompleted)
{
if (typeof(T).IsValueType)
{
if (!HeaderContainer.Exists(x => x.Name == _columnName))
{
HeaderContainer.Add((_columnName, HeaderColumnFactory<T>(), typeof(T)));
if (_typesComplete)
{
TypesCompleted = true;
}
}
}
}
return this;
}
public ValidatableBuilder AddPredicateToColumn<T>(string _columnName, Predicate<T> _predicate)
{
if(TypesCompleted)
{
Validatable<T> validatable = QueryableHeader.FirstOrDefault(x => x.Name == _columnName).Value as Validatable<T>;
validatable.PreCheck = _predicate;
}
return this;
}
public ValidatableBuilder AddHandlerToColumn<T>(string _columnName, MyAction<T> _action)
{
if (TypesCompleted)
{
Validatable<T> validatable = QueryableHeader.FirstOrDefault(x => x.Name == _columnName).Value as Validatable<T>;
validatable.ModifyInput = _action;
}
return this;
}
private void SetupComplete()
{
if (HeaderContainer.Count > 0)
{
if (TypesCompleted)
{
SetupCompleted = true;
}
}
}
public IQueryable<(string Name, IValidatable Value, Type DataType)> GetTypedRow()
{
if (!SetupCompleted)
{
SetupComplete();
if (SetupCompleted)
{
return QueryableHeader;
}
return default;
}
else
{
return QueryableHeader;
}
}
}
</code></pre>
<p>Testing class, is not much in the way of <code>finished</code>, but it shows usage of the code and that is important.</p>
<p>First up, I create a <code>ValidatableBuilder</code> then I use it to add 2 columns of type ReadonlyMemory and int. I then add a condition to the int setter to say this value must be 106 to be set, and for the ReadOnlyMemory setter I tell it length must be in range 0(exclusive) to 11(inclusive). I then iterate over the Queryable I return from GetTypedRow and try to set the Property <code>Data</code> to incorrect values and assert against those values. </p>
<pre><code>public class ValidationTests
{
public ValidationTests()
{
ValidatableBuilder builder = new ValidatableBuilder();
void PredicateTests()
{
builder
.AddColumnToHeader<ReadOnlyMemory<byte>>("Test")
.AddColumnToHeader<int>("Test2", _typesComplete: true)
.AddPredicateToColumn<int>("Test2", x => x == 106)
.AddPredicateToColumn<ReadOnlyMemory<byte>>("Test", x => x.Length > 0 & x.Length <= 11);
foreach( var (Name, Value, DataType) in builder.GetTypedRow())
{
if(Value is IValidatable<ReadOnlyMemory<byte>>)
{
var ourValue = Value as Validatable<ReadOnlyMemory<byte>>;
ourValue.Data = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes("Hello World!"));
Debug.Assert(ourValue.Data.Span.SequenceEqual(Encoding.UTF8.GetBytes("Hello World!")), "Not Equal");
}
else if(Value is IValidatable<int>)
{
var ourValue = Value as Validatable<int>;
ourValue.Data = 105;
Debug.Assert(ourValue.Data == 105, "Not Equal");
}
}
}
PredicateTests();
}
}
</code></pre>
<p>I tried to incorporate everything, but if I left something out or something is unclear, please let me know. All input is welcomed. :)</p>
<p>Edit: In response to Pieter's questions, I got further insight into where I could improve and the goals and completeness of my tool. I have decided to rename it ProgrammableSetter and instead of working directly towards validation before setting a property, I will change direction and work towards making it as Configurable and reusable as possible, it will probably take me a few days to retool/rewrite. Thanks for the valued input.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T21:32:09.897",
"Id": "424970",
"Score": "0",
"body": "This code seems rather sketchy and unfinished. It's hard to say what exactly we are to review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T21:57:39.543",
"Id": "424973",
"Score": "0",
"body": "It is finished up to the point I want to have someone else review it. The code semantics, the code layout, you can review any part of it. What can I do to make the code less sketchy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:58:06.743",
"Id": "424982",
"Score": "0",
"body": "Does the code work, we can only review working code, also it would be best to have full classes. Please see https://codereview.stackexchange.com/help/dont-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T00:38:55.583",
"Id": "424987",
"Score": "0",
"body": "@pacmaninbw code does work as intended. Full class listing updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T01:22:51.053",
"Id": "424992",
"Score": "2",
"body": "There are a lot of TODO placeholders. We can't really review your intentions; I'd prefer to see the placeholders filled in or removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T07:50:05.923",
"Id": "425011",
"Score": "0",
"body": "Why is this getting close votes? The code may not be as easy to understand as the OP thinks it is, but it does work as intended. Those TODO comments can be ignored - they're part of a (useless) piece of boilerplate disposal code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T08:09:00.657",
"Id": "425014",
"Score": "1",
"body": "@BanMe: in what context is this validation code meant to be used? What's the point of `ModifyInput`: why can't a caller do that before calling `SetData`? And how are you going to detect validation failures if `PreCheck` failures are not reported?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:07:40.087",
"Id": "425018",
"Score": "0",
"body": "@PieterWitvoet you ask the question: _Why is this getting close votes?_ and give yourself an answer: _in what context is this validation code meant to be used_ ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T09:40:05.427",
"Id": "425022",
"Score": "0",
"body": "@t3chb0t: asking for clarifications does not mean that there's insufficient context for a review - just that more context can result in a better review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T11:39:47.497",
"Id": "425036",
"Score": "0",
"body": "@200_success I will remove log todo placeholders from my upload."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T11:50:06.070",
"Id": "425037",
"Score": "0",
"body": "@PieterWitvoet this type of validation is intended to be used as part of a tool I am building to creates excel files via local web input. The point of ModifyInput is to provide a method to modify or sanitize the input in some way.. in my next debugging session, I will I plan to set the predicate for int to x => x == 106 and for the action I will do x => x + 1; I will then try to set 105, it should increment it and validate against 106.. Caller should not call SetData Directly, as this function is the proxy between the private T backing object 'data', for consistence I will set it to private."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T18:06:34.010",
"Id": "425103",
"Score": "0",
"body": "@PieterWitvoet `PreCheck` failure is going to eventually initiate a review request process for the failing items only to be uploaded in the response message. I left this part out as it is not complete, or even testable at the moment."
}
] | [
{
"body": "<h3><code>IValidatable<T></code></h3>\n\n<ul>\n<li><code>ModifyInput</code> and <code>PreCheck</code> are problematic: their public setters allow any code to modify or disable sanitizing and validation. Surely that's something that only the initializing code should be able to do? I also don't see why these properties need to be exposed at all: they're implementation details.</li>\n<li>Why does <code>IValidatable<T></code> contain an <code>Equals</code> and <code>GetHashCode</code> method? They're not used anywhere.</li>\n<li>Because of the above two issues, <code>IValidatable<T></code> is rather pointless in its current shape. Why doesn't it contain a <code>T Data { get; set; }</code> property? And if you're only ever going to have one implementation then I don't see much use for an interface. <code>Validatable<T></code> seems flexible enough.</li>\n</ul>\n\n<h3><code>Validatable<T></code></h3>\n\n<ul>\n<li>You don't need to initialize properties with <code>= default</code> - that already happens by default.</li>\n<li>I'd expect <code>Validatable<T></code>'s constructor to accept <code>modifyInput</code> and <code>preCheck</code> as arguments, and to store them in private fields.</li>\n<li>Why does <code>ModifyInput</code> take a <code>ref</code> parameter instead of returning the result? This prevents you from using lambda's.</li>\n<li><code>SetData</code> is a confusing name: it doesn't actually set <code>Data</code> - it returns a sanitized and validated value.</li>\n<li>Most people would expect a setter to store the value given to it. Getting a different value back would be rather surprising - and not in a good way. Consider using a clearly named method instead: <code>v.Value = 105</code> versus <code>v.SanitizeAndStore(105)</code>.</li>\n<li>Returning <code>default</code> when validation fails is problematic: is <code>0</code> an intended, valid value, or the result of a validation failure? I'd expect an exception to be thrown instead, or some other failure-handling mechanism. I would also clearly document the chosen behavior.</li>\n<li><code>SetData</code> can be simplified to just <code>ModifyInput?.Invoke(ref _value); return (PreCheck?.Invoke(_value) == false) ? default : _value;</code>.</li>\n<li>A boolean is already either true or false, so the <code>== true</code> in your code is superfluous. Note that <code>?.</code> returns a nullable bool, which is why the <code>== false</code> part above is necessary.</li>\n<li>In <code>Equals</code>, instead of using <code>as</code> and a null-check, you can use pattern matching instead: <code>return other is Validatable<T> column && ...;</code>.</li>\n</ul>\n\n<h3><code>ValidatableBuilder</code></h3>\n\n<ul>\n<li>Why do <code>QueryableHeader</code> and <code>GetTypesRow</code> return an <code>IQueryable<></code>? It's an in-memory list, so <code>IEnumerable<></code> would make more sense.</li>\n<li><code>GetTypedRow</code> always returns the same row, including data that was set previously. I can't imagine that to be the intended behavior.</li>\n<li><code>Property { get => ...; }</code> can be simplified to <code>Property => ...;</code>.</li>\n<li>Why explicitly initialize <code>HeaderContainer</code> to <code>default</code>, only to override that in the constructor? Just initialize it to a new list directly.</li>\n<li>The various <code>Add</code> methods are very brittle: they fail silently depending on whether <code>TypesCompleted</code> is true or not. If a method cannot be called when an object is in a certain state, then I'd expect an exception to be thrown, but I'd much rather look for a better design. Perhaps a <code>CreateRowBuilder</code> method that returns a <code>RowBuilder</code> with the current configuration, which can then be used to create rows.</li>\n<li>Likewise, silently ignoring reference types is brittle. Use a generic type constraint instead, so you can prevent the use of reference types at compile-time.</li>\n<li>Why have separate methods for adding columns, handlers and predicates? Why not add optional arguments for handlers and predicates to <code>AddColumnToHeader</code>?</li>\n</ul>\n\n<h3><code>ValidationTests</code></h3>\n\n<ul>\n<li>Inside that foreach loop, you're using both <code>is</code> and <code>as</code>, but with different types. An <code>IValidatable<T></code> is not necessarily a <code>Validatable<T></code> - it could be any other type that implements <code>IValidatable<T></code>. Note also that pattern matching can be used here: <code>switch (Value) { case Validatable<ReadOnlyMemory<byte>> vmem: vmem.Data = ...; case Validatable<int> vint: vint.Data = ...; }</code>.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Leading underscores are typically used for private fields. Parameter names are written in camelCase, without leading underscore. PascalCase is used for property names, not fields.</li>\n<li>I prefer to add a bit of whitespace between methods and properties, especially when they have different visibilities (public/private).</li>\n<li>There's a general lack of documentation/comments.</li>\n</ul>\n\n<h3>Alternative approach</h3>\n\n<p>A property that silently modifies or rejects data is quite surprising. I'd rather see code that is more obvious about what it does:</p>\n\n<pre><code>var sanitizedValue = column.Sanitize(inputValue);\nif (!column.IsValid(sanitizedValue))\n{\n // log, throw error, ...\n}\nelse\n{\n // store value\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T15:07:08.983",
"Id": "425426",
"Score": "0",
"body": "This is excellent stuff, thank you so much for spending the time. I will take all that you say and try and address each point as best as I can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T15:11:48.940",
"Id": "425427",
"Score": "0",
"body": "ModifyInput and PreCheck are problematic: Many are in agreement on this point. I have moved the function set to the contstructor for my class. I now have 4 optional parameters to address this issue.\n\nWhy does IValidatable<T> contain an Equals and GetHashCode method? Not sure where I was going, removed from next Implementation.\n\nI was just updating the Interface definitions now. new one will have `T Data` and `T Set(T Value)` defined, this gives me the option to setup the validation and not use the inner field to receive the value"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:00:33.377",
"Id": "425430",
"Score": "0",
"body": "Validatable<T>: 1st point: Interesting I did not know that about C#, this can definitely reduce my typing. 2nd point: Addressed last comment, 3rd: ModifyInput has been adjusted to not take a reference but to return the modified value to a local variable for future use.4th I definitely agree it is misleading, I have a hard time naming things, I will try to Describe functions by their Impl better.5th this makes a good point, SanitizeOrSetAndStore? 6th: this should be addressed by the new Success/Fail Callbacks in my next version."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T08:35:04.420",
"Id": "220171",
"ParentId": "219948",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220171",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T18:48:49.780",
"Id": "219948",
"Score": "2",
"Tags": [
"c#",
"validation"
],
"Title": "Filtering and Validating value in SETTER"
} | 219948 |
<p>I implemented basic <code>pushd</code> and <code>popd</code> functionality for a Python script. What's a more academic/formal way to implement a directory stack?</p>
<pre class="lang-py prettyprint-override"><code>_directory_stack = {0:getcwd()}
def pushd(target: str):
"""Push a new directory to the top of the stack and changes to it.
Arguments:
target {str} -- Where you want to go
"""
highest_seen = max(_directory_stack.keys())
_directory_stack[highest_seen+1] = target
chdir(target)
def popd():
"""Pops the most recent directory off the stop of the stack and returns you to the previous directory
"""
current_top = max(_directory_stack.keys())
_directory_stack.pop(current_top, None)
chdir(_directory_stack[current_top-1])
</code></pre>
| [] | [
{
"body": "<p><em>Academic/formal</em> is not what's needed here. <em>Simple</em> is what's needed.</p>\n\n<p>A dict whose keys are all integers from 0 to n is suspicious. Why not use a list instead? You can add items to the end with <code>.append</code> and remove them with <code>.pop</code>. Then you don't have to bother with <code>max(_directory_stack.keys())</code>.</p>\n\n<p>This is the usual way to implement a stack in Python.</p>\n\n<p>Edit: oh, wait, here's an academic/formal issue: <code>popd</code> doesn't restore correctly with relative paths. For example:</p>\n\n<pre><code>pushd('foo')\npushd('bar')\npopd()\n</code></pre>\n\n<p>Should the directory now be <code>foo</code> or <code>foo/bar/foo</code>?</p>\n\n<p>There are two ways to fix this:</p>\n\n<ol>\n<li><code>pushd</code> can convert the path to an absolute path with <code>os.path.abspath</code>.</li>\n<li>Instead of saving the directory it's changing to, <code>pushd</code> can save the current directory (<code>getcwd</code>), and <code>popd</code> can just <code>chdir</code> to whatever it popped.</li>\n</ol>\n\n<p>Which one to do depends on where you want to restore to if someone changes the directory without telling <code>pushd</code>. Consider this sequence:</p>\n\n<pre><code>pushd('/foo')\nchdir('bar')\npushd('/baz')\npopd()\n</code></pre>\n\n<p>Should the directory now be <code>/foo</code> or <code>/foo/bar</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:53:33.007",
"Id": "425099",
"Score": "0",
"body": "I liked this. I ended up going with your recommendations. Thanks! https://gist.github.com/mxplusb/c895b90d1df65f1e741267d395b3e674"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T18:41:02.677",
"Id": "425111",
"Score": "1",
"body": "If you post that version as a new question, you can get someone else to review it. (There's some unnecessary complexity.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T20:17:54.640",
"Id": "219952",
"ParentId": "219950",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "219952",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T19:17:46.380",
"Id": "219950",
"Score": "4",
"Tags": [
"python",
"stack"
],
"Title": "Directory Stacks with Python"
} | 219950 |
<p>In response to <a href="https://security.stackexchange.com/questions/209775/limiting-the-number-of-duplicate-character-types-in-crunch/209788">a question on Information Security</a> on brute-forcing passwords, I wrote code that helped solve the problem:</p>
<blockquote>
<p>Generate a password list of 10 character passwords containing only a combination of 3 - 6 numbers and 3 - 6 uppercase letters.</p>
</blockquote>
<p>I'd like a code review done of the snippet I wrote. I don't know really anything about optimizing software. I can write it (self-taught) but I don't have the deep insights needed to improve already working software, so I've started posting code snippets in here for you guys to give me insights. I really think this channel is great and without further ado, I'll get to it.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <vector>
#include <random>
#include <string>
const char charset[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','8','9'};
int main()
{
std::cout << "Please enter the number of passwords to generate here: ";
int num_pass;
std::cin >> num_pass;
std::random_device dev;
std::mt19937_64 rng(dev());
std::vector<std::string> passwds;
std::uniform_int_distribution<std::mt19937_64::result_type> dist(0, sizeof(charset) - 1);
for (int i = 0; i < num_pass; ++i) {
std::string pass = "";
int num_nums = 0, num_chars = 0;
while (pass.length() < 10) {
char c = charset[dist(rng)];
if (isdigit(c) && num_nums < 6) {
pass += c;
num_nums++;
}
else if (isalpha(c) && num_chars < 6) {
pass += c;
num_chars++;
}
}
passwds.push_back(pass);
std::cout << pass << std::endl;
}
std::cin.get();
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T00:37:09.750",
"Id": "424986",
"Score": "0",
"body": "If you have a 10 character password, with 3 digits, and at most 6 uppercase letters, what is the 10th character? Or with 3 uppercase letters and at most 6 digits, what is the 10th character?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T00:39:07.380",
"Id": "424988",
"Score": "0",
"body": "I saw that discrepancy. I believe the OP meant 4 to 6 not 3 to 6 letters/digits. So it just uses 4-6 random digits. Which means it either has 4 letters and 6 digits or 6 digits and 4 letters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T04:27:21.027",
"Id": "424998",
"Score": "2",
"body": "You shouldn't edit the code in the question after you have received an answer. See [this help topic](https://codereview.stackexchange.com/help/someone-answers)."
}
] | [
{
"body": "<p>Your passwords will be biased, with more letters appearing towards the front of the password and more digits towards the end.</p>\n\n<p>A better approach would be to determine how many digits you will have in the password. Then, for each character, determine if it should be a digit based on the number of digits you want to have and the number of characters left to fill by checking if (random(characters_left) < digits_left). Then select either a random digit or letter for that position.</p>\n\n<p>When you declare <code>pass</code>, you don't need to pass it an empty string. It is default constructed as empty.</p>\n\n<pre><code>std::string pass;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T01:09:14.993",
"Id": "424990",
"Score": "0",
"body": "Can you tell me why it would be biased? It's easily solved with one line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T01:10:43.140",
"Id": "424991",
"Score": "1",
"body": "@leaustinwile 26 times out of 36, the first character will be a letter (since you have 26 letters and 10 digits). Since this continues for the remaining characters, you'll run thru letters faster than digits, resulting in more digits at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T01:31:11.967",
"Id": "424993",
"Score": "0",
"body": "Review the code again, I've solved this problem and fixed the \"\" declaration of the string. (Old java habits)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T01:49:56.613",
"Id": "424994",
"Score": "0",
"body": "sorry for fuzzing your points. having read the previous question, i understand that some of what's going on is a design requirement for whatever reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T18:34:39.410",
"Id": "425109",
"Score": "0",
"body": "I ran the password generator for 100_000 random passwords, and there is how often a letter came up in the positions: `[72102, 72331, 72292, 72208, 72302, 71974, 62152, 44757, 28754, 16336]`. This bias is much more extreme than I expected."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T01:07:48.520",
"Id": "219964",
"ParentId": "219954",
"Score": "7"
}
},
{
"body": "<p>In general, placing constraints on your passwords, such as that they have x-many numerals and y-many letters, makes your password generation scheme slightly <em>worse</em>; there's no advantage.<br>\nBut sometimes we're required to do silly things. </p>\n\n<p>In this situation, it looks like the requirement is to have at least four of each, but that could change, as could the desired length of the password. So if this is going to be a reusable tool, it sounds like it should take at least 4 parameters, three of them optional:</p>\n\n<ul>\n<li>password_length</li>\n<li>max_alpha - default password_length</li>\n<li>max_num - default password_length</li>\n<li>quantity - default 1</li>\n</ul>\n\n<p>This will give you useful and appropriate behavior by default. The other convenient thing is that you can exclude a character class altogether by setting the max_x to 0.<br>\nDo remember to check that the input values are reasonable (non-negative or whatever).</p>\n\n<p>I think the problem <a href=\"https://codereview.stackexchange.com/users/85680/1201programalarm\">1201ProgramAlarm</a> points out is real, but his proposed solution is a little vague (and sounds hard to maintain), and the edit you made to solve the problem doesn't look like it addresses it at all. </p>\n\n<p><strong>Here's what I would do</strong>, both for the above reason and for maintainability:</p>\n\n<ul>\n<li>Define each character class as a separate vector. (Should upper-case and lower-case be their own classes? this could get complicated fast. Let's assume for now that there are just the <strong>2</strong> classes)</li>\n<li>Calculate the <strong>minimum</strong> number of characters we need from each class.</li>\n<li>Define a vector containing the union of the character classes. We'll use this to select <strong>only</strong> the characters who's class we don't care about. </li>\n<li>Calculate how many don't-care characters there will be, such that<br>\n<code>min_alpha + min_num + dont_care == password_length</code>.<br>\nCounting the don't-care's, we have <strong>3</strong> \"classes\", and an exact number of characters we want from each class.</li>\n<li>For each of the target character quantities, select that many characters (uniformly at random with replacement) from the respective class (vector). You could probably be pushing all of these to a single string/buffer as you go.</li>\n<li>Shuffle the string.</li>\n</ul>\n\n<p>Also, because this is Code Review:</p>\n\n<ul>\n<li>You're building a list <code>passwds</code>, but you're not using it.</li>\n<li>Taking arguments from stdin isn't as user-friendly as taking them as arguments to main(), <em>in my opinion</em>.</li>\n<li>The whole business of removing duplicates from the list seems fishy to me, but I guess it's better to do it in a separate step than to bake it into your password generator.</li>\n<li>Is the business with the clock purely diagnostic? </li>\n<li>Similarly, the part at the end where you hold for the user to hit enter seems un-friendly to me, but I guess I don't know your use-case.</li>\n<li>If you do implement my advice above, then you're almost certainly going to want to break this up into a couple different functions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T04:56:42.953",
"Id": "424999",
"Score": "0",
"body": "So I hear all your points, but you have to remember, this wasn't programmed for maximum efiiciency. It was just written as a PoC for another question in a different channel. I just thought I'd post it in here to learn. The business with the clock is purely diagnostic. That was simply in there for my purposes, to see when it ended during debug, if the strings generated were in fact non-uniform. I agree about the stdin vs. argv point too, again, it was just created in VS as a PoC for someone else's problem. Good points, but shuffling the array and then again picking a random index"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T11:35:29.263",
"Id": "425035",
"Score": "0",
"body": "Hi! To clarify: None of my points will make the program more _efficient_. A lot of it is about making the code easier to _use_, which might not matter. My suggestion about using multiple character-class vectors is would solve @1201ProgramAlarm's point, and would make the code _more obviously_ correct. **Shuffling the source array adds nothing; it does not solve this problem.**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:37:33.497",
"Id": "425095",
"Score": "1",
"body": "But wouldn't using two vectors and then selecting from a randomized union of them have the same effect as just combining them into one vector? I'm not talking about code-correctness, I'm just referring to the bias that ProgramAlarm identified. But I also just realized, that there's no way to remove that bias without violating the constraints that the person who needed the code had."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:58:11.943",
"Id": "425100",
"Score": "1",
"body": "Ah; I understand your confusion. I've edited the answer to clarify what I mean."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T02:21:29.150",
"Id": "219967",
"ParentId": "219954",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "219967",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T20:59:15.060",
"Id": "219954",
"Score": "6",
"Tags": [
"c++",
"performance",
"beginner",
"strings",
"random"
],
"Title": "Generating 10-character passwords, with 3-6 digits and 3-6 uppercase letters, in C++"
} | 219954 |
<p>My programming foundations were formed in Java, but I've decided to only use C++ from now on for my projects as a personal learning experience. Static utility classes are common in Java; but I don't think they work the same as in C++. I'd like the following:</p>
<ul>
<li>Code review of the functions to determine potential function-specific improvements</li>
<li>Analysis of the general architecture/structure to determine if static methods are the way to go.
If they are not, what would one recommend to achieve the desired result (which is to have a globally accessible set of utility methods)?</li>
</ul>
<p>Here's the code:</p>
<h2>util.h</h2>
<pre class="lang-cpp prettyprint-override"><code>#ifndef STDAFX_INCLUDE
#define STDAFX_INCLUDE
#include "stdafx.h"
#endif
#include <sstream>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <random>
// Utility class to manage misc. functions
class Util {
public:
static std::string serialize_http_args(std::map<std::string, std::string>);
static std::string serialize_http_headers(std::map<std::string, std::string>);
static int randrange(int min, int max);
static void trim(std::string&);
static void ltrim(std::string&);
static void rtrim(std::string&);
static std::string trim_copy(std::string);
static std::string ltrim_copy(std::string);
static std::string rtrim_copy(std::string);
static std::string int2str(int);
static std::string lowercase(std::string);
static std::vector<std::string> split(std::string, std::string);
static std::vector<std::string> split_once(std::string, std::string);
};
</code></pre>
<h2>util.c</h2>
<pre><code>#include "util.h"
// returns a random number in range min through max, inclusive.
int Util::randrange(int min, int max) {
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<> distr(min, max); // define the range
return distr(eng);
}
// takes a map of arguments and converts it to a string representation
std::string Util::serialize_http_args(std::map<std::string, std::string> _args) {
if (_args.size() > 0) {
size_t counter = 1;
std::string args_str = "";
for (auto const& arg : _args) {
args_str += arg.first + "=" + arg.second;
if (counter < _args.size())
args_str += "&";
counter++;
}
return args_str;
}
return "";
}
// takes a map of headers and converts it to the string representation
std::string Util::serialize_http_headers(std::map<std::string, std::string> _headers) {
if (_headers.size() > 0) {
std::string headers_ser = "";
for (auto const& header : _headers)
headers_ser += header.first + ": " + header.second + "\r\n";
return (headers_ser + "\r\n");
}
return "";
}
// splits a string infinitely by delimiter until completely tokenized
std::vector<std::string> Util::split(std::string s, std::string delimiter) {
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while ((pos = s.find(delimiter, pos)) != std::string::npos)
{
std::string substring(s.substr(prev_pos, pos - prev_pos));
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos - prev_pos)); // Last word
return output;
}
// splits a string by the first instance of delimiter
std::vector<std::string> Util::split_once(std::string s, std::string delimiter)
{
std::vector<std::string> output;
std::string::size_type pos = 0;
if ((pos = s.find(delimiter, pos)) != std::string::npos) {
output.push_back(std::string(s.substr(0, pos)));
output.push_back(std::string(s.substr(pos + 1)));
}
return output;
}
// trim from start (in place)
void Util::ltrim(std::string & s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
}
// trim from end (in place)
void Util::rtrim(std::string & s) {
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
}
// trim from both ends (in place)
void Util::trim(std::string & s) {
ltrim(s);
rtrim(s);
}
// trim from start (copying)
std::string Util::ltrim_copy(std::string _s) {
std::string s = _s;
ltrim(s);
return s;
}
// trim from end (copying)
std::string Util::rtrim_copy(std::string _s) {
std::string s = _s;
rtrim(s);
return s;
}
// trim from both ends (copying)
std::string Util::trim_copy(std::string _s) {
std::string s = _s;
trim(s);
return s;
}
// convert string to lowercase version of same string
std::string Util::lowercase(std::string _s) {
std::string s = _s;
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return s;
}
//convert type integer to string
std::string Util::int2str(int i) {
std::string out;
std::stringstream ss;
ss << i;
return ss.str();
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>Your functions themselves are pretty broad, so I'm not going to review each one. However, I can tell you that what you're probably looking for is a <code>namespace</code>. A <code>namespace</code> is just a way to group together similar functions/classes/static objects. They're a little bit like Java's <code>package</code> in that they can be used to organize your code into related groups.</p>\n\n<p>A class with only static functions can be converted to a namespace very easily:</p>\n\n<pre><code>#ifndef STDAFX_INCLUDE\n#define STDAFX_INCLUDE\n\n#include \"stdafx.h\"\n\n#endif\n\n#include <sstream>\n#include <algorithm> \n#include <functional> \n#include <cctype>\n#include <locale>\n#include <random>\n\n// Namespace containing utility functions\n\nnamespace Util {\n std::string serialize_http_args(std::map<std::string, std::string>);\n std::string serialize_http_headers(std::map<std::string, std::string>);\n int randrange(int min, int max);\n void trim(std::string&);\n void ltrim(std::string&);\n void rtrim(std::string&);\n std::string trim_copy(std::string);\n std::string ltrim_copy(std::string);\n std::string rtrim_copy(std::string);\n std::string int2str(int);\n std::string lowercase(std::string);\n std::vector<std::string> split(std::string, std::string);\n std::vector<std::string> split_once(std::string, std::string);\n}\n</code></pre>\n\n<p>Note how <code>class</code> was changed to <code>namespace</code>, <code>public:</code> was removed (all items in a namespace are public), <code>static</code> was removed (it has different meaning outside of a class) and there is no semicolon after the final closing brace.</p>\n\n<p>Each function is referenced the same as it was before, e.g. <code>int random = Util::randrange(0, 100)</code>.</p>\n\n<p>Your include files also look strange compared to what you're actually using - based on the given function definitions, you should only need <code><string></code>, <code><map></code> and <code><vector></code> in this header. Best practice with include files is to <em>only</em> include the headers that you need for the current file. A user of this utility namespace doesn't care if your <code>randrange</code> function uses the <code><random></code> library for its implementation - that is a detail that should only appear in the source file.</p>\n\n<p>As a side note, since it looks like you're developing on Windows, best practice is to put</p>\n\n<pre><code>#include \"stdafx.h\"\n</code></pre>\n\n<p>as the first line in every <em>source</em> file, and leave it out of your <em>header</em> files completely. See <a href=\"https://stackoverflow.com/a/5234347/8365363\">this answer on StackOverflow</a> for more details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:28:07.710",
"Id": "424976",
"Score": "1",
"body": "Thank you. I did not know that about the includes, I thought best practice was to put all includes in the header file. But that makes sense. With regards to stdafx. I've seen several different answers about when/how/bestpractices for stdafx. Could you update your answer to explain how it would apply in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:36:35.087",
"Id": "424978",
"Score": "0",
"body": "@leaustinwile I've updated my post with a link to a relevent StackOverflow answer, and added some more information about namespaces at the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:44:19.987",
"Id": "424979",
"Score": "0",
"body": "For sake of brevity and clarity, would you recommend against using stdafx? This is intended to be a cross-platform project upon completion. Operable on at the minimum, linux and windows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:03:15.450",
"Id": "425070",
"Score": "0",
"body": "@leaustinwile That depends on your project. `stdafx` represents the concept of precompiled headers, which can be used to drastically improve compilation time for a large project. The idea is that you put all commonly-used headers into `stdafx.h`, which is then precompiled and cached, reducing the cost of subsequent compilations. The trade-off is that you lose the ability to see, at a glance, the dependencies for each file in your project (since common library includes are extracted to `stdafx.h`). If your compilation time isn't a big issue, then precompiled headers probably aren't necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:41:16.600",
"Id": "425097",
"Score": "0",
"body": "No. This will probably be a small to medium sized project upon completion. I don't think that compilation time will be a problem. I'm going to remove it for clarity sake. I just thought I'd use it in the beginning because I wanted to try out new C++ features I've never used! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T18:20:51.260",
"Id": "425108",
"Score": "0",
"body": "Also, what is the benefit of using a namespace vs. the static class I wrote? Functionally it seems the same, but what's happening in the compiler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:13:09.033",
"Id": "425129",
"Score": "0",
"body": "@leaustinwile Functionally (and as far as the compiler is concerned), a class with only static methods is equivalent to a namespace. The biggest advantage you gain here is intent. Classes are used to create objects. A class with only static methods is [surprising](https://en.wikipedia.org/wiki/Principle_of_least_astonishment), because you would never create an object out of that class. In Java, we use static utility classes to convey the intent of \"this is a grouping of related items, which cannot be instantiated\". In C++, this purpose is served by `namespace`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:30:41.223",
"Id": "425132",
"Score": "1",
"body": "Makes perfect sense to me! Thanks a lot."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:24:17.010",
"Id": "219959",
"ParentId": "219957",
"Score": "7"
}
},
{
"body": "<ul>\n<li><p>In <code>randrange</code>, you initialize the random device, the engine, and the distribution on every call. So this is not suitable for every situation, i.e., when performance matters.</p></li>\n<li><p>In <code>serialize_http_args</code> and in general, <strong>never</strong> query the size of a container when you want to determine whether it is empty or not. For that, you should use <code>empty()</code>. This is idiomatic and saves you from costly surprises like with container implementations where <code>empty()</code> is a constant time method while <code>size()</code> needs linear time.</p></li>\n<li><p>At least for both <code>serialize_http_args</code> and <code>serialize_http_headers</code>, you might consider first checking whether <code>_args.empty()</code> (or <code>_headers.empty()</code>), and then returing an empty string, i.e.,:</p>\n\n<pre><code>std::string serialize_http_args(std::map<std::string, std::string> _args) \n{\n if (_args.empty())\n return \"\";\n\n size_t counter = 1;\n std::string args_str = \"\";\n for (auto const& arg : _args) \n {\n args_str += arg.first + \"=\" + arg.second;\n if (counter < _args.size())\n args_str += \"&\";\n counter++;\n }\n\n return args_str;\n}\n</code></pre>\n\n<p>I find this cleaner and easier to read, especially if the functions were any longer.</p></li>\n<li><p>You don't need your own <code>int2str</code> anymore, you can just use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"noreferrer\"><code>std::to_string</code></a>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:39:40.097",
"Id": "425096",
"Score": "0",
"body": "Good points. I'm still learning all the methods and functions I have available so I've just been hacking it together with my Java/Python know-how. Could you clarify on constant vs. linear time methods/functions and what they are?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:49:44.123",
"Id": "425098",
"Score": "0",
"body": "@leaustinwile Sure. For example [the `size` method of `std::list`](https://en.cppreference.com/w/cpp/container/list/size) could have been a linear-time method pre-C++11. IIRC, this had something to do with splicing then."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T08:11:01.587",
"Id": "219974",
"ParentId": "219957",
"Score": "5"
}
},
{
"body": "<p>The function for serializing URL parameters is horribly broken since it leaves out URL escaping. Don't invent these functions yourself. Since you're from a Java background, have a look at Apache Commons and Spring Framework, they already implemented this function and took care about all edge cases.</p>\n\n<p>There's probably a C++ library that provides URL encoding. You're definitely not the first one to need this function in a C++ program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:12:14.560",
"Id": "220031",
"ParentId": "219957",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T21:46:12.060",
"Id": "219957",
"Score": "8",
"Tags": [
"c++",
"strings",
"static"
],
"Title": "Static utility class for string manipulation in C++"
} | 219957 |
<p>I have some files containing 16-bit words in big-endian order, and a tool to process them that assumes little-endian order. I therefore need to swap the order of each pair of bytes in my files.</p>
<p>This is almost a one-liner in Python (<code>data[0::2], data[1::2] = data[1::2], data[0::2]</code>). However, since I need to do this manipulation often, I decided to write a standalone tool to do it. Also, for learning purposes, I decided to write this simple tool as my first Go program.</p>
<p>I look forward to any comments you may have about this code:</p>
<p><strong>byteswap16.go</strong></p>
<pre><code>package main
import "fmt"
import "io/ioutil"
import "os"
func parseArgs(args []string) (string, string, error) {
if len(args) != 3 {
return "", "", fmt.Errorf("Usage: %s infile outfile", args[0])
}
return args[1], args[2], nil
}
func byteswap16(data []byte) ([]byte, error) {
length := len(data)
if length%2 != 0 {
return nil, fmt.Errorf("Length is not a multiple of 2 bytes")
}
swapped := make([]byte, length)
for i := 0; i < length; i++ {
swapped[i] = data[i^1]
}
return swapped, nil
}
func run() error {
infile, outfile, err := parseArgs(os.Args)
if err != nil {
return err
}
data, err := ioutil.ReadFile(infile)
if err != nil {
return err
}
swapped, err := byteswap16(data)
if err != nil {
return fmt.Errorf("%s: %v", infile, err)
}
if err := ioutil.WriteFile(outfile, swapped, 0666); err != nil {
return err
}
return nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
</code></pre>
<p>A couple of comments of my own:</p>
<ol>
<li><p>As with the Python, the core algorithm is very little code, but it's written very differently - an explicit <code>for</code> loop over individual bytes rather than higher-level manipulation of many values at a time. I think I like the explicit loop more, because it's a more general solution - changing to <code>byteswap32</code> wouldn't require much more than changing <code>i^1</code> to <code>i^3</code>.</p></li>
<li><p>A common complaint about Go, but I don't really like the repetitive <code>if err != nil</code> in <code>run</code>. However, it does provide an obvious place to wrap <code>err</code> to add context, as is done after the call to the <code>byteswap16</code> function. If exceptions were used instead, the code would be more concise but the error message would be worse, because I don't think I would catch and re-throw to add context.</p></li>
</ol>
<p>In general, would this be considered good-quality, idiomatic Go code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T15:28:43.803",
"Id": "425765",
"Score": "0",
"body": "Though a bit more explicit, it's a go oneliner, too (if you know you're just swapping 16 bytes): `data[0], data[1], data[2], data[3] = data[1], data[0], data[3], data[2]`. Alternatively, you can just swap pairs in a loop: `for i := 0; i<len(data); i+=2 { data[i], data[i+1] = data[i+1], data[i]} `"
}
] | [
{
"body": "<p>Several things come to mind right away:</p>\n\n<ul>\n<li><p>I wouldn't make a custom <code>parseArgs</code> function, I'd use <a href=\"https://golang.org/pkg/flag#Parse\" rel=\"nofollow noreferrer\"><code>flag.Parse</code></a>. For just a pair of positional arguments it might be overkill but it makes it trivial to add more options, usage output, etc. And either way, it's better to only access <code>os.Args</code> from <code>main</code></p></li>\n<li><p>Instead of <code>fmt.Fprint</code> to <code>os.Stderr</code> followed by <code>os.Exit</code> it's more idomatic to just use <a href=\"https://golang.org/pkg/log#Fatal\" rel=\"nofollow noreferrer\"><code>log.Fatal</code></a> (or <code>Fatalf</code> or <code>Fatalln</code>).</p></li>\n<li><p>Avoid reading and writing entire files with <code>ioutil</code> if you can do work while streaming data. If the files are guarenteed to be small it's just a bad habit but if someone ever runs your tool on gigabytes or terabytes of data they'll be in for unpleasant surprise.</p></li>\n<li><p>In the same vein, I'd make your function API steam-able. Either by implementing an <a href=\"https://golang.org/pkg/io#Reader\" rel=\"nofollow noreferrer\"><code>io.Reader</code></a> wrapper or by a function that takes an <a href=\"https://golang.org/pkg/io#Writer\" rel=\"nofollow noreferrer\"><code>io.Writer</code></a> and an <code>io.Reader</code> (like <a href=\"https://golang.org/pkg/io#Copy\" rel=\"nofollow noreferrer\"><code>io.Copy</code></a>).</p>\n\n<p>You could also implementing it as a <a href=\"https://godoc.org/golang.org/x/text/transform#Transformer\" rel=\"nofollow noreferrer\"><code>transform.Transformer</code></a>; but that's probably overkill, although perhaps an interesting exercise.</p></li>\n<li><p>Typically such command line tools in unix act as pipes, that is, if not given file arguments they read from <code>stdin</code> and write to <code>stdout</code>. Either you only work with stdin/stdout and make callers use shell redirection if they want to work to work on files or you make the filenames optional. Just initialise an <code>io.Reader</code> (or <code>io.ReadCloser</code>) variable to <code>os.Stdin</code> and an <code>io.WriteCloesr</code> variable to <code>os.Stdout</code>. Then when processing the arguments, if provided, open the relevant files and change the variables. Your choice if you use positional arguments as you've done or option arguments (as <code>dd</code> does and as I did below). Make sure to check for errors closing the destination.</p></li>\n<li><p>By the way, on unix you can use the standard <code>dd</code> command to do the byte swapping for you with the <code>conv=swab</code> operand:</p>\n\n<pre><code>dd conv=swab if=someinput_file of=someoutput_file\n</code></pre>\n\n<p>using files, or in a pipe like this:</p>\n\n<pre><code>bigendian_command | dd conv=swab | littleendian_command\n</code></pre></li>\n</ul>\n\n<p>A quick stab at implementing it this way gave me the following.</p>\n\n<p>(Also available at <a href=\"https://gist.github.com/dchapes/9d795a04e471319abbc5ff016afbbee9\" rel=\"nofollow noreferrer\">https://gist.github.com/dchapes/9d795a04e471319abbc5ff016afbbee9</a>\nthe gist also has your version as revision 1, and a version using a function with an <code>io.Copy</code> like signature as revision 2).</p>\n\n<p><code>swab.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"flag\"\n \"fmt\"\n \"io\"\n \"log\"\n \"os\"\n)\n\nfunc main() {\n log.SetPrefix(\"swab: \")\n log.SetFlags(0)\n infile := flag.String(\"in\", \"\", \"input `path`, blank for stdin\")\n outfile := flag.String(\"out\", \"\", \"output `path`, blank for stdout\")\n flag.Usage = func() {\n fmt.Fprintf(flag.CommandLine.Output(),\n \"Usage: %s [options]\\n\", os.Args[0],\n )\n flag.PrintDefaults()\n }\n flag.Parse()\n if flag.NArg() > 0 {\n flag.Usage()\n os.Exit(2) // To match the exit code flag.Parse uses.\n }\n\n var src io.ReadCloser = os.Stdin\n var dst io.WriteCloser = os.Stdout\n if *infile != \"\" {\n f, err := os.Open(*infile)\n if err != nil {\n log.Fatal(err)\n }\n src = f\n }\n // Closing the input isn't strictly required in main\n // nor for stdio, but it's a good habit. No need to\n // check any error; we rely on Read reporting errors of interest.\n defer src.Close()\n\n if *outfile != \"\" {\n f, err := os.Create(*outfile)\n if err != nil {\n log.Fatal(err)\n }\n dst = f\n }\n\n if _, err := io.Copy(dst, NewSwabReader(src)); err != nil {\n // Not this calls os.Exit so no defers get run\n // and we don't close the output either, not\n // an issue from main.\n log.Fatal(err)\n }\n if err := dst.Close(); err != nil {\n log.Fatal(err)\n }\n}\n\ntype SwabReader struct {\n r io.Reader\n b byte // extra byte, not yet swapped\n haveByte bool // true if b is valid\n err error\n}\n\n// NewSwabReader returns an io.Reader that reads from r\n// swapping adjacent bytes. The trailing odd byte, if any,\n// is left as-is.\nfunc NewSwabReader(r io.Reader) *SwabReader {\n return &SwabReader{r: r}\n}\n\nfunc (sr *SwabReader) Read(p []byte) (n int, err error) {\n if len(p) == 0 || sr.err != nil {\n return 0, sr.err\n }\n i := 0\n if sr.haveByte {\n // Copy in the previous saved byte.\n p[0] = sr.b\n i = 1\n //sr.haveByte = false // not strictly required\n }\n n, sr.err = sr.r.Read(p[i:])\n n += i\n p = p[:n]\n for i := 1; i < len(p); i += 2 {\n p[i-1], p[i] = p[i], p[i-1]\n }\n // Remove and save any non-swapped trailing odd byte.\n if sr.err == nil {\n if sr.haveByte = (n&1 != 0); sr.haveByte {\n n--\n sr.b = p[n]\n //p = p[:n] // not strictly required\n }\n }\n return n, sr.err\n}\n</code></pre>\n\n<p>And a simple test, \n<code>swab_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"io\"\n \"strings\"\n \"testing\"\n \"testing/iotest\"\n)\n\nvar readFilters = []struct {\n name string\n fn func(io.Reader) io.Reader\n}{\n {\"\", nil},\n {\"DataErrReader\", iotest.DataErrReader},\n {\"HalfReader\", iotest.HalfReader},\n {\"OneByteReader\", iotest.OneByteReader},\n //{\"TimeoutReader\", iotest.TimeoutReader},\n}\n\nfunc TestSwab(t *testing.T) {\n const sz = 32<<10 + 1\n cases := []struct{ in, out string }{\n {\"\", \"\"},\n {\"a\", \"a\"},\n {\"ab\", \"ba\"},\n {\"abc\", \"bac\"},\n {\"abcd\", \"badc\"},\n {strings.Repeat(\"\\x01\\x80\", sz) + \"x\",\n strings.Repeat(\"\\x80\\x01\", sz) + \"x\"},\n }\n var dst strings.Builder\n var r io.Reader\n for _, rf := range readFilters {\n for _, tc := range cases {\n r = strings.NewReader(tc.in)\n if rf.fn != nil {\n r = rf.fn(r)\n }\n dst.Reset()\n //t.Logf(\"swabbing %s %.16q\", rf.name, tc.in)\n //r = iotest.NewReadLogger(\"<<< src\", r)\n n, err := io.Copy(&dst, NewSwabReader(r))\n if err != nil {\n t.Errorf(\"swab on %s %q failed: %v\",\n rf.name, tc.in, err,\n )\n continue\n }\n if want := int64(len(tc.out)); n != want {\n t.Errorf(\"swab on %s %q returned n=%d, want %d\",\n rf.name, tc.in, n, want,\n )\n }\n if got := dst.String(); got != tc.out {\n t.Errorf(\"swab on %s %q\\n\\tgave %q\\n\\twant %q\",\n rf.name, tc.in, got, tc.out,\n )\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T22:19:02.933",
"Id": "221750",
"ParentId": "219972",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T07:59:11.213",
"Id": "219972",
"Score": "1",
"Tags": [
"array",
"file",
"io",
"go",
"bitwise"
],
"Title": "Go command-line tool to do some simple byte manipulation"
} | 219972 |
<p>I'm trying to group all the types which have ordered-list-item & unordered-list-item into new object.</p>
<p>How can I simplify the function and reduce multiple return statements?</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 data = {
data: [{
areas: [{
sections: [{
rjf: [{
"type": "heading-1",
"text": "A title",
},
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
},
{
"type": "heading-1",
"text": "A title",
}
]
}]
},
{
sections: [{
rjf: [{
"type": "heading-1",
"text": "Block 2 A title",
},
{
"type": "ordered-list-item",
"text": "Block 2 Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Block 2 Ordered Item B",
},
{
"type": "heading-1",
"text": "Block 2 A title",
}
]
}]
}
]
}]
};
function parseAreas() {
data[0].areas.forEach(area => {
this.moveToNewObject(area);
})
}
function moveToNewObject(data) {
const areas = data[0].areas;
//console.log(data[0].areas)
const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
return areas.map((area) => {
var sec = area.sections;
return sec.map((section) => {
let lastHeadingIndex = -1;
return section.rjf.reduce((acc, current, index) => {
if (!current.type || !listItemTypes.includes(current.type)) {
lastHeadingIndex = acc.length;
return [...acc, current]
} else {
let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');
if (!listObject) {
listObject = {
type: 'list',
items: [current]
}
return [...acc, listObject];
}
listObject.items = [...listObject.items, current];
return acc;
}
}, [])
});
});
}
console.log('sections', moveToNewObject(data.data));</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T20:22:39.373",
"Id": "425307",
"Score": "1",
"body": "an you give an example of what you expect the output to be? It's not clear from the description what the expected behavour is."
}
] | [
{
"body": "<blockquote>\n <p>How can I simplify the function and reduce multiple return statements?</p>\n</blockquote>\n\n<p>You <em>could</em> reduce the number of <code>return</code> statements by building up the new object in a more imperative way, without using the <code>map</code> and <code>reduce</code> functions,\nbut I'm not sure that would be better.\nI think it's fine using functions as it is.</p>\n\n<p>This part doesn't look great:</p>\n\n<blockquote>\n<pre><code> let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');\n</code></pre>\n</blockquote>\n\n<p>The problem with it is that you are using <code>lastHeadingIndex</code> to find the last heading added in <code>acc</code>,\nbut <code>acc.find</code> will search from the beginning.\nWith a large <code>data</code>, that would be a waste,\ninstead of searching from the end.</p>\n\n<p>In fact, I'm wondering if <code>lastHeadingIndex</code> is important at all.\nIsn't your real intention more like <em>\"consecutive items of list type should be combined into a list object\"</em>?\nIf that's the case, then you don't need to search from the end,\nit's enough to look at the last item of <code>acc</code>:\nif it's a list type, then append to it, if not, then create a new list type.</p>\n\n<p>If this is indeed your real intention,\nthen you could get rid of <code>lastHeadingIndex</code>, and write a bit simpler:</p>\n\n<pre><code>function moveToNewObject(data) {\n const listItemTypes = ['unordered-list-item', 'ordered-list-item'];\n return data[0].areas.map(area => {\n var sec = area.sections;\n return sec.map(section => {\n return section.rjf.reduce((acc, current, index) => {\n if (!listItemTypes.includes(current.type)) {\n acc.push(current);\n return acc;\n }\n\n if (!acc.length || acc[acc.length - 1].type !== 'list') {\n acc.push({type: 'list', items: [current]});\n return acc;\n }\n\n acc[acc.length - 1].items.push(current);\n return acc;\n }, [])\n });\n });\n}\n</code></pre>\n\n<p>I would also change the name of the function,\nbecause <code>moveToNewObject</code> sounds overly generic,\nit doesn't seem to describe its real purpose.\nHow about <code>combineListItemTypes</code>,\nor <code>transformCombiningListItemTypes</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T18:59:40.307",
"Id": "220755",
"ParentId": "219980",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T10:55:11.813",
"Id": "219980",
"Score": "3",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "Separating items into ordered and unordered lists"
} | 219980 |
<p>Our professor has given us the following task (its part of a bigger document full of tasks):</p>
<p>Write a function in C that handles strings like "233+343" and parse them into the variables "iNum1", "cOp" and "iNum2". (I tried to translate it into english).</p>
<p>We mostly program in Java and my C knowledge consists of mostly provisional half knowledge.</p>
<p>But is my program beautiful enough to show it to a professor?</p>
<pre><code>#include <stdio.h>
#include <string.h>
#define ASCII_POS_OF_0 0x30
#define ASCII_POS_OF_9 0x39
void parse_calc_string(char string[])
{
// get first number
int iNum1 = 0;
int index = 0;
char current_char = string[index];
while (current_char >= ASCII_POS_OF_0 && current_char <= ASCII_POS_OF_9)
{
iNum1 *= 10;
iNum1 += (int)current_char - ASCII_POS_OF_0;
current_char = string[++index];
}
// get operation symbol
char cOp = current_char;
current_char = string[++index];
// get second number
int iNum2 = 0;
while (current_char >= ASCII_POS_OF_0 && current_char <= ASCII_POS_OF_9)
{
iNum2 *= 10;
iNum2 += (int)current_char - ASCII_POS_OF_0;
current_char = string[++index];
}
printf("iNum1: %i\n", iNum1);
printf("cOp : %c\n", cOp);
printf("iNum2: %i\n", iNum2);
printf("\n");
}
int main()
{
parse_calc_string("219+43");
parse_calc_string("195-143");
parse_calc_string("15*13");
parse_calc_string("212/14");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T13:49:00.587",
"Id": "425056",
"Score": "1",
"body": "This question (or more correctly the aspect that this is homework which has not been handed in yet) is being discussed on meta: https://codereview.meta.stackexchange.com/questions/9154/the-ethics-of-answering-a-homework-question-before-it-is-handed-in, please voice your opinions regarding that matter there. Thanks!"
}
] | [
{
"body": "<p>You can get the value for <code>ASCII_POS_OF_0</code> easily by using <code>'0'</code>. </p>\n\n<p>Your code doesn't deal with malformed strings well.</p>\n\n<p>If the string is only <code>\"123\"</code> it will attempt to read beyond the contents of the string. You can fix this by checking for <code>'\\0'</code> at the correct places.</p>\n\n<p>It also doesn't handle any type of whitespace in the string at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T12:37:02.990",
"Id": "425042",
"Score": "0",
"body": "Exception handling and handling whitespace was not included in the task. Also it would bloat up this little task."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T12:17:35.587",
"Id": "219984",
"ParentId": "219982",
"Score": "3"
}
},
{
"body": "<p>it is a poor programming practice to include header files those contents are not used.</p>\n\n<p>I.E. in the posted code, the contents of the header file: <code>string.h</code> are not being used. Suggest removing the statement:</p>\n\n<pre><code>#include <string.h>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T20:34:18.100",
"Id": "425220",
"Score": "0",
"body": "I think this could be a comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T20:45:09.583",
"Id": "425221",
"Score": "0",
"body": "@DexterThorn, in CodeReview, there isn't supposed to be any comments. Just answers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T11:37:11.733",
"Id": "220050",
"ParentId": "219982",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219984",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T12:00:10.537",
"Id": "219982",
"Score": "2",
"Tags": [
"beginner",
"c",
"parsing",
"homework"
],
"Title": "Split calculation string into parts"
} | 219982 |
<p>I'm working with Google Maps and want to read in location objects into the map. I'm loading them in from a .csv file and create Shelter objects for each location that I save in an ArrayList. To actually add them to the map I iterate through this ArrayList and create marker objects with each object's data. Each actual Marker object created is also saved into another ArrayList so that I can reference them later (show/hide them on map when wanted). I feel like I'm doing something wrong. I included the relevant methods below.</p>
<pre><code>private ArrayList<ShelterObject> shelterObjects;
private ArrayList<Marker> shelterMarkers;
// Generates the Shelter objects from the csv file and adds them to the ArrayList.
private void generateShelterObjects()
{
shelterObjects = new ArrayList<>();
Log.i("SHELTER_TEST", "METHOD generateShelterObjects() STARTED");
InputStream is = getResources().openRawResource(R.raw.shelters_csv_file);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
// Split the line into different tokens (using the comma as a separator).
String[] tokens = line.split(",");
String address = tokens[0];
double latitude = Double.parseDouble(tokens[1]);
double longitude = Double.parseDouble(tokens[2]);
int numberOfOccupants = Integer.parseInt(tokens[3]);
ShelterObject object = new ShelterObject(address, latitude, longitude, numberOfOccupants);
shelterObjects.add(object);
}
} catch (IOException e1) {
Log.e("MapsActivity2", "Error" + line, e1);
e1.printStackTrace();
}
Log.i("SHELTER_TEST", "The size of the arraylist after reading in objects: " + shelterObjects.size());
}
// Iterates through the ArrayList of Shelter objects and adds a marker with data from that object to the map. The markers are saved in another ArrayList so they can be referenced later.
private void addShelterMarkersToMap()
{
shelterMarkers = new ArrayList<>();
for (ShelterObject obj : shelterObjects) {
LatLng latLng = new LatLng(obj.getLatitude(), obj.getLongitude());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(obj.getAddress())
.snippet("Antal platser: " + obj.getNumberOfOccupants()));
shelterMarkers.add(marker);
}
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Your Marker and ShelterObject instances have the same data inside. (except the additional hardcoded (!) string \"Antal platser:\", whatever that means) Now you have two islands of data. You collect them in two different lists, shelterObjects and shelterMarkers. That is bad, High memory usage and difficult modifications are the drawback. If you want to add/delete/modify one you have to to it in two lists and keep it synchronized. I recommend to only have one island of data (ShelterObjects-array) and whenever you need ShelterMarkers, you convert them. For example you can add a method getAsMarker() to your ShelterObject class that returns itself as Marker. If you have enough memory and want to save performance you only create them when needed and store them for later re-use(see Lazy Instantiation), like so </p>\n\n<pre><code>class ShelterObject {\n ...\n int Marker marker;\n public Marker getAsMarker(... mMap) { // or pass mMap in constructor. \n if (marker != null) {\n return marker;\n }\n LatLng geoPosition = new LatLng(this.getLatitude(), this.getLongitude());\n marker = mMap.addMarker(...); // creates marker via MarkerOptions\n return marker;\n }\n ...\n}\n</code></pre></li>\n<li><p>What is \"LatLng\"? You barely can speak that out. If you mean just a pair of latitude and longitude coordinates, then just name it like that: geoPosition, coordinates, latitudeAndLongitude. Try to use short and meaningful names, but no abbreviations. In old times, even Microsoft used code abbreviations like \"lptcstr\" (google it). Because of bad experience, this is discouraged now. I can't count how many times I have looked up which combination of manager and number the managerNumber was abbreviated: \"num\", \"nbr\", \"no\", \"numero\", \"man\", \"mgr\", \"mangr\" etc.</p></li>\n<li><p>Delete the code line below. You overwrite it right away, so you can leave it out for less code clutter.</p>\n\n<p>String line = \"\";</p></li>\n<li><p>You forgot to close your stream in a finally-statement of your try-block. This is a severe bug since it's hard to detect when files remain open and suddenly your program crashes when it runs out of file handles. Alternatively you can use a try-with-resources statement. </p></li>\n<li><p>Avoid using member variables like they are global. Just pass them as parameters. You can better test it and make your code more stable.\nI will give you an example what I mean:\nAssume you have following lines inside your init-method:</p>\n\n<p>generateShelterObjects();\naddShelterMarkersToMap();</p></li>\n</ol>\n\n<p>Now somebody changes it to following code that crashes or does not add the shelterMarkers:</p>\n\n<pre><code>addShelterMarkersToMap();\ngenerateShelterObjects();\n</code></pre>\n\n<p>Does he know that he is not allowed to swap the lines when he needs to refactor?\nMaybe he does it by accident?</p>\n\n<p>You can avoid that by coding:</p>\n\n<pre><code>ArrayList<ShelterObject> newShelterObjects = generateShelterObjects();\nArrayList<Markers> newShelterMarkers = addShelterMarkersToMap(shelterObjects);\nshelterMarkers = newShelterMarkers;\nshelterObjects = newShelterObjects;\n</code></pre>\n\n<p>Now when you swap the first two lines, it will not compile anymore. Also there is no possibility that you can have a nullPointerException in addShelterMarkersToMap() anymore. (I assume that you return an empty Map instead of null in generateShelterObjects() or throw an exception there).\nYou also cannot have inconsistent data anymore. Just imagine in generateShelterObjects() your map is half-filled when an error occurs. Or your markers are half created when an error occurs. You need to catch the exception and clean both maps. Having inconsistent data is worse than just keeping the old, consistent ones.</p>\n\n<ol start=\"6\">\n<li>Use \"/** comment **/\" instead of \"// comment\" on top of your methods, so you can create javadocs easily and the IDE can show it as mouseover-message</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:13:43.490",
"Id": "425113",
"Score": "0",
"body": "Thank you so much! This will help a lot. :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:20:04.160",
"Id": "220000",
"ParentId": "219983",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220000",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T12:01:21.050",
"Id": "219983",
"Score": "5",
"Tags": [
"java",
"android"
],
"Title": "Google Maps API - reading locations from file and displaying markers on map"
} | 219983 |
<p>I wrote a small utility for searching our web app log files for certain strings. The idea is that if the search string is found somewhere in the entry, the entire entry should be printed.</p>
<p>The constraints are:</p>
<ul>
<li>One log entry can have one to many lines (stacktraces for example)</li>
<li>Each log entry starts with an uppercase string specifying log type, followed by a pipe character ("ERROR|...")</li>
<li>Each log entry ends with a pipe character followed by an exclamation mark ("|!")</li>
<li>The utility should work much like a regular grep command, meaning that it takes input either from a list of files or from STDIN.</li>
</ul>
<p>The script works as expected, but it is quite slow. Writing the same logic in an AWK script is about twice as fast when processing a large amount of data. Any suggestions on how to improve the performance?</p>
<p><strong>logentrygrep.py</strong></p>
<pre class="lang-py prettyprint-override"><code>#!/bin/python2.7
from __future__ import print_function
import argparse
import fileinput
import re
import signal
import sys
# Disable printing stacktrace on KeyboardInterrupt
signal.signal(signal.SIGINT, lambda x,y: sys.exit(1))
# Parse arguments
parser = argparse.ArgumentParser(description='Tool for greping log entry contents')
parser.add_argument('pattern', help='Pattern to search for')
parser.add_argument('file', nargs='*', help='Files to search')
parser.add_argument('-i', '--ignore-case', dest="ignorecase", action='store_true', help='Case insensitive greping')
parser.add_argument('-v', '--verbose', dest="verbose", action='store_true', help='Print verbose messages')
args = parser.parse_args()
VERBOSE = args.verbose
if VERBOSE:
print("Pattern to search for: " + args.pattern)
print("File(s): " + (str(args.file) if args.file else "STDIN"))
class LogDataProcessor:
entryHeadPattern = re.compile("^[A-Z]{3,}\|")
entryTailPattern = re.compile("\|!$")
totalLinesProcessed = 0
lineBuffer = []
matchFound = False
def __init__(self, regex_pattern, ignorecase):
if ignorecase:
self.pattern = re.compile(regex_pattern, re.IGNORECASE)
else:
self.pattern = re.compile(regex_pattern)
def process(self, indata):
for line in fileinput.input(indata):
self.processLine(line.rstrip())
def processLine(self, line):
self.totalLinesProcessed += 1
if self.isEntryHead(line):
# Flush in case previous entry did not terminate correctly
self.flush()
self.addToBuffer(line)
# If it's a one-line entry (head and tail on the same line)
if self.isEntryTail(line):
self.flush()
elif not self.isBufferEmpty():
self.addToBuffer(line)
if self.isEntryTail(line):
self.flush()
def flush(self):
if self.matchFound:
self.printBuffer()
self.lineBuffer = []
self.matchFound = False
def printBuffer(self):
for line in self.lineBuffer:
print(line)
def addToBuffer(self, line):
if not self.matchFound and self.lineMatches(line):
self.matchFound = True
self.lineBuffer.append(line)
def isBufferEmpty(self):
return not self.lineBuffer
def isEntryHead(self, line):
return self.entryHeadPattern.match(line)
def isEntryTail(self, line):
return self.entryTailPattern.search(line)
def lineMatches(self, line):
return self.pattern.search(line)
processor = LogDataProcessor(args.pattern, args.ignorecase)
processor.process(args.file)
if VERBOSE:
print("Lines searched: " + str(processor.totalLinesProcessed))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:23:14.690",
"Id": "425072",
"Score": "1",
"body": "How many lines would such a log file have? Just to have a rough estimate for this would be nice. Are we talking about 1.000, 10.000 or 1.000.000 lines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T18:04:40.633",
"Id": "425102",
"Score": "0",
"body": "Why not use `awk` for what it is good for?... If I remember correctly it's possible to parse command line arguments with an `awk` script too. Hint, Python could still be used, could even [_`pipe`_](https://stackoverflow.com/a/15414341/2632107) things around to-&-fro between [`gawk`](https://www.gnu.org/software/gawk/manual/html_node/Executable-Scripts.html) and Python, and using [_`unbuffer`ing_](https://superuser.com/a/898806/666508) tricks it's still possible to sorta _`yield`_ a sub-process into Python. Isn't easy but it reads like ya want more performance than convenience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:26:34.197",
"Id": "425114",
"Score": "0",
"body": "@AlexV I tested it with a few thousand lines, but if I'd search through all log files of our 50-odd servers it would be more along the lines of a few million, so that's what I'd like to optimise for. A single log entry will not be more than maybe 50 lines though, so the lineBuffer will not grow very large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:28:54.773",
"Id": "425115",
"Score": "1",
"body": "@S0AndS0 I already wrote an awk script that does pretty much exactly the above, but I wanted to try writing it in python to get more convenience and to get more used to python, since I don't get to use it much. And when I noticed how much slower it was I got curious to see if it could somehow be tweaked to reduce that difference. I do realise that it will never be faster than awk, but perhaps it could be faster than what it is now?"
}
] | [
{
"body": "<p>On my windows 10 laptop, I ran your program on a dummy log file under the python \nprofiler using the command line:</p>\n\n<pre><code>python -m cProfile -s cumulative loggrep.py \"speech\" \\data\\test.log \n</code></pre>\n\n<p>The dummy log file has about 4.3 Mbytes of text spread across about 100k lines \ncomprising 32772 log entries. The search pattern was \"speech\", which occured \n444 times. </p>\n\n<p>This is the ouput of the profiler:</p>\n\n<pre><code> 1322924 function calls (1322872 primitive calls) in 2.006 seconds\n\nOrdered by: cumulative time\n\nncalls tottime percall cumtime percall filename:lineno(function)\n 7/1 0.000 0.000 2.006 2.006 {built-in method builtins.exec} \n 1 0.000 0.000 2.006 2.006 loggrep.py:3(<module>)\n 1 0.077 0.077 1.997 1.997 loggrep.py:38(process)\n100003 0.136 0.000 1.788 0.000 loggrep.py:42(processLine)\n 32772 0.013 0.000 1.369 0.000 loggrep.py:60(flush) <-----\n 444 0.014 0.000 1.355 0.003 loggrep.py:67(printBuffer) <-----\n 9722 1.341 0.000 1.341 0.000 {built-in method builtins.print} <-----\n100003 0.061 0.000 0.132 0.000 loggrep.py:71(addToBuffer)\n100004 0.042 0.000 0.116 0.000 fileinput.py:248(__next__)\n100003 0.028 0.000 0.075 0.000 loggrep.py:80(isEntryHead)\n100004 0.060 0.000 0.071 0.000 {method 'readline' of '_io.TextIOWrapper' objects}\n195293 0.068 0.000 0.068 0.000 {method 'search' of '_sre.SRE_Pattern' objects}\n100003 0.027 0.000 0.062 0.000 loggrep.py:83(isEntryTail)\n 95290 0.027 0.000 0.060 0.000 loggrep.py:86(lineMatches)\n100010 0.047 0.000 0.047 0.000 {method 'match' of '_sre.SRE_Pattern' objects}\n</code></pre>\n\n<p>The header shows the program took 2.006 seconds to run. Looking at the \nlines marked with \"<-----\", we see that <code>flush()</code> was called 32772 times \nand took about 1.369 seconds. From the code, we know <code>flush()</code> calls \n<code>printbuffer()</code>, which calls <code>print()</code>. The profile says <code>print()</code> was \ncalled 9722 times taking 1.341 seconds, or about 65% of the total run time.</p>\n\n<p>I changed <code>entryTailPattern</code> to <code>\"\\|!\\s*$\"</code>. This let me get rid of the \n<code>.rstrip()</code> on each line so that the lines would keep the '\\n' at the end. \nThis let me change the <code>print()</code> for loop in <code>printBuffer()</code> to a call to \n<code>sys.stdout.writelines()</code>. This saved about 0.5 seconds over the <code>print()</code> \nfor loop.</p>\n\n<p>All the other function calls seem to be in the noise, so i don't see any other \npromising things to try. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T06:35:00.193",
"Id": "223116",
"ParentId": "219985",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T12:38:30.623",
"Id": "219985",
"Score": "4",
"Tags": [
"python",
"performance",
"regex",
"search",
"logging"
],
"Title": "Python log entry search utility"
} | 219985 |
<p>I'm new to coding and made a small Node script that checks when a website is down because of high traffic. It's a website that sells tickets and I don't want to press F5 every 10 seconds to check if the website works again. </p>
<p>Because I send a ping so often I sometimes receive something back from the website. But when I check it again a couple of seconds later I get a request timeout again.</p>
<p>So I made a counter to track how stable the website is. If I receive a request timeout subtract from the counter.</p>
<p>It works, but I was wondering if there is a better way or solution to do this. Because I'm still new I don't have much experience with other solutions to this sort of problem.</p>
<p>This is my code:</p>
<pre><code>const Monitor = require('ping-monitor');
const sendEmail = require('./Email.js')
const myMonitor = new Monitor({
website: 'https://www.pathe.nl/',
title: 'Pathe',
interval: 0.1 // minutes, so 0.1 is 6 seconds
});
let counterUp = 0;
myMonitor.on('up', function (res, state) {
counterUp++
console.log('counter is ' + counterUp)
console.log('Yay!! ' + res.website + ' is up.');
// send email when script made sure the website is really up and stable. Otherwise we receive an email when the website isn't fully up and running. Because we send a ping every 6 seconds.
if (counterUp == 20) {
sendEmail(myMonitor.title)
console.log('sending email')
}
});
myMonitor.on('down', function (res) {
counterUp--
console.log('counter is ' + counterUp)
console.log('Oh Snap!! ' + res.website + ' is down! ' + res.statusMessage);
});
myMonitor.on('stop', function (website) {
console.log(website + ' monitor has stopped.');
});
myMonitor.on('error', function (error) {
console.log(error);
});
</code></pre>
| [] | [
{
"body": "<p>In reality, people just use third-party services for that. For instance, uptime website monitoring can be done <a href=\"https://www.statuscake.com/\" rel=\"nofollow noreferrer\">StatusCake</a>. If you own the target site, you install infrastructure tools like <a href=\"https://newrelic.com/products/infrastructure\" rel=\"nofollow noreferrer\">New Relic</a>. Cloud services these days also provide uptime data and tools out of the box.</p>\n\n<p>The only reason I would write my own uptime monitor is if you're doing this for a small project or doing it for fun.</p>\n\n<p>Now the problem with the uptime monitor you wrote is that it contributes to the site traffic. To the website, you're just another client trying to connect to the site. Together with your traffic are other sources of traffic, like legitimate users, web crawlers, malicious site scanners, DDOS bots, etc.</p>\n\n<p>The reason you get the Request Timeout (<a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_errors\" rel=\"nofollow noreferrer\">HTTP 504</a>) is because the site is already overloaded. It can be worse though. The site may choose to ignore you, block you temporarily, or even permanently. If you've seen a captcha appear when doing a Google search, that's one example.</p>\n\n<p>So, what I recommend is to:</p>\n\n<ul>\n<li>Reduce the rate you ping. Every 5, 15, or 60 minutes is reasonable. You're probably not going to need it every 6 seconds.</li>\n<li>Hit a static asset on the domain instead, like the favicon. Hitting actual pages will cause 504s since it requires logic and probably database calls to generate the page. Just make sure it's not cached or served from a CDN. \n\n<ul>\n<li>This only tells you if the static server/caching proxy is up, not the actual server with the logic.</li>\n</ul></li>\n<li>If the website has an API for uptime or a status page that you can scrape, use that instead. Those are usually served by a separate server so they can still tell you the status even if the main site is down.</li>\n<li>If you own the website, monitor the infrastructure instead.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:33:15.300",
"Id": "425063",
"Score": "0",
"body": "Thank you for your feedback! I made this project just for fun and to learn. So I'm going to implement your suggestions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:23:33.687",
"Id": "219991",
"ParentId": "219988",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T13:23:56.307",
"Id": "219988",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"node.js",
"status-monitoring"
],
"Title": "Tracking the stability of a website using ping monitor"
} | 219988 |
<p>Inspired by a <a href="https://stackoverflow.com/q/55938014/1968">bioinformatics question on Stack Overflow</a>, I wanted to brush up on my Ruby knowledge, since I’ve been meaning to replace my command-line use of Perl by Ruby.</p>
<p>Briefly, the problem description is as follows:</p>
<blockquote>
<p>Given is a SAM file. This is a whitespace-delimited file with at least 11 columns. After the 11th column, there can be further optional columns in a specific format<sup>1</sup>. If there is an optional column starting with <code>RX:Z:</code> then remove all dashes in that column.</p>
</blockquote>
<p>Here’s my Ruby “one-liner”:</p>
<pre class="lang-bsh prettyprint-override"><code>ruby -ane '
$F[11..].grep(/^RX:Z:/).map! {|x| x.gsub!(/-/, "")}
puts $F.join("\t")
' file.sam
</code></pre>
<p>This works but I’m wondering if there’s a way of making this more idiomatic and/or more concise. For instance, I’m puzzled by the apparent necessity to manually join the modified <code>$F</code> back together. There doesn’t seem to be a way of using the <code>-p</code> flag instead of <code>-n</code>, and getting the in-place changes to <code>$F</code> to propagate to <code>$_</code>. <code>perl -ae</code> has the same limitation as far as I know.</p>
<hr>
<p><sub><sup>1</sup> This isn’t relevant to the question but each optional column is roughly described by the regular expression <code>[a-zA-Z][a-zA-Z0-9]:[AifZHB]:\S*</code>. The actual description is more complicated (for instance, if the character between the two colons is <code>Z</code> then the field after the second colon is a zero-terminated C-string of printable characters, and notably can include space).</sub></p>
| [] | [
{
"body": "<p>There isn't much to say here, it is clear what your solution is doing, and attempts to make it more concise would just make it harder to read.</p>\n\n<p>I recommend replacing <code>map!</code> with <code>each</code> - <code>map!</code> indicates that you want the values returned by <code>grep</code> to be changed in place. Since that result is then discarded, it makes the code more difficult to understand.</p>\n\n<p>Personally, I avoid <code>!</code> methods whenever possible. The hidden mutation which can occur makes code harder to reason about. It is fine in this small example (especially once <code>map!</code> is replaced with <code>each</code>), but in a larger program it will hide bugs.</p>\n\n<p>Avoiding mutation in this case makes the code a bit longer, but it has the benefit of not needing to stop and think about what has changed and if it matters. I spent several minutes trying to figure out why your code <em>didn't</em> fail when a field didn't include a <code>-</code> since <code>gsub!</code> returns <code>nil</code> when no replacements are made.</p>\n\n<p>Though less concise, I prefer the following version:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>ruby -ane '\n$F[11..] = $F[11..].map { |x| x.start_with?(\"RX:Z:\") ? x.gsub(/-/, \"\") : x }\nputs $F.join \"\\t\"\n' file.sam\n</code></pre>\n\n<p>Not automatically joining <code>$F</code> back together to create <code>$_</code> makes sense, what should ruby do if you use (or modify) <code>$F</code> but then set <code>$_</code> to something else? Setting <code>$_</code> whenever <code>$F</code> is modified would be rather confusing and bad for performance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:19:44.527",
"Id": "220301",
"ParentId": "219989",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220301",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T13:59:39.630",
"Id": "219989",
"Score": "3",
"Tags": [
"ruby",
"shell",
"bioinformatics"
],
"Title": "Ruby command to edit a field in a SAM file"
} | 219989 |
<p>I am solving some problems from CodeChef but I am stuck on the <a href="https://www.codechef.com/MAY19B/problems/MATCHS" rel="nofollow noreferrer">Matches problem</a>:</p>
<blockquote>
<p>Ari and Rich are playing a pretty confusing game. Here are the rules
of the game:</p>
<ol>
<li><p>The game is played with two piles of matches. Initially, the first pile contains N matches and the second one contains M matches.</p></li>
<li><p>The players alternate turns; Ari plays first.</p></li>
<li><p>On each turn, the current player must choose one pile and remove a positive number of matches (not exceeding the current number of
matches on that pile) from it.</p></li>
<li><p>It is only allowed to remove X matches from a pile if the number of matches in the other pile divides X.</p></li>
<li><p>The player that takes the last match from any pile wins.</p></li>
</ol>
<p>Solve(N,M)</p>
<ol>
<li>If its Ari's turn and N%M==0 then Ari wins else Rich wins.</li>
<li>If N%M!=0 then player try every possible moves and check if he wins any one of them in end.</li>
</ol>
</blockquote>
<p>My solution uses Dynamic Programmming, so I have used <code>functools.lru_cache</code> to save function results. But I am getting TLE error in some test cases.How can I further optimize the code?</p>
<pre class="lang-py prettyprint-override"><code>from functools import lru_cache
@lru_cache(maxsize=None)
def Solve(X,Y,Player=True):
if X%Y==0:
return Player
else:
temp=X
X=X%Y
if Player==Solve(max(X,Y),min(X,Y),not Player):
return Player
while temp!=X+Y:
X=X+Y
if Player==Solve(max(X,Y),min(X,Y),not Player):
return Player
return not Player
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:26:49.357",
"Id": "425061",
"Score": "0",
"body": "Can you give an example input for which it takes too long?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:50:41.303",
"Id": "425067",
"Score": "0",
"body": "@PeterTaylor the test cases are not visible.But the range of X and Y is 1 to 10^18"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:44:41.000",
"Id": "425087",
"Score": "0",
"body": "Rolled back major code edit. See meta on [what you can do after you receive an answer](https://codereview.meta.stackexchange.com/a/1765/1402)."
}
] | [
{
"body": "<p>The whitespace needs a lot of changes to be PEP8-compliant. The capitalisation is also unconventional: functions and variables in Python usually start with a lower-case letter.</p>\n\n<hr>\n\n<p>The meaning of <code>Player</code> is not entirely clear, and the logic is hard to follow because of that. The convention for this type of combinatorial game is to denote a position as \"N\" (<strong>N</strong>ext player wins) or \"P\" (<strong>P</strong>revious player wins). So I think that <code>Solve</code> should be renamed <code>position_is_N</code>, and then the <code>Player</code> variable becomes unnecessary.</p>\n\n<p><code>if condition: return</code> doesn't need a following <code>else:</code>.</p>\n\n<p>The loop can be tidied up considerably with <code>range</code> and <code>any</code>. I think this is equivalent:</p>\n\n<pre><code>@lru_cache(maxsize=None)\ndef position_is_N(x, y):\n return x % y == 0 or \\\n any(not position_is_N(max(x2, y), min(x2, y))\n for x2 in range(x % y, x, y))\n</code></pre>\n\n<p>A comment about the constraint that <code>x >= y</code> would be nice.</p>\n\n<hr>\n\n<blockquote>\n <p>range of both X and Y is 1 to 10^18</p>\n</blockquote>\n\n<p>Consider inputs <code>10**18, 3</code> (or other similarly small <code>y</code>). How many times might the loop run in the worst case?</p>\n\n<p>As a rule of thumb, for a challenge like this if you need to do anything more than <code>10**9</code> times your algorithm is wrong. I can only suggest that you will need a complete rewrite to pass the time limit, so you should build a table of small values and see whether you can spot and prove a pattern. The problem is probably far more about mathematics than programming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:12:54.157",
"Id": "425071",
"Score": "0",
"body": "Player denote turn of player. If Player=True then its Ari's turn else Rich"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:25:11.400",
"Id": "425073",
"Score": "0",
"body": "I stand by my observation that it's not clear. `ari_moves_next` would be clearer, although then the function should be called something like `ari_wins`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:35:24.847",
"Id": "425084",
"Score": "0",
"body": "I have changed my code to more readable form"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:56:11.460",
"Id": "219992",
"ParentId": "219990",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219992",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T14:12:03.910",
"Id": "219990",
"Score": "0",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"dynamic-programming",
"memoization"
],
"Title": "CodeChef Matches challenge"
} | 219990 |
<p>I'm writing a library to register the <code>b</code>, <code>B</code> conversion specifiers and make them work the closest possible to <code>o</code>, <code>u</code>, <code>x</code>, <code>X</code>.</p>
<p>Requirements:</p>
<ul>
<li>All "flag characters" should behave as in <code>x</code>, <code>X</code> (or as close as possible, while being meaningful).</li>
<li>"Field width" and "precision" should behave as in <code>x</code>, <code>X</code> (or as close as possible, while being meaningful).</li>
<li>All "length modifiers" that are valid on <code>o</code>, <code>u</code>, <code>x</code>, <code>X</code> should be valid.</li>
<li>They should work on any <code>printf</code> family function (such as <code>fprintf</code>, <code>snprintf</code>, ...).</li>
<li>There are some flags that override others in the case of <code>o</code>, <code>u</code>, <code>x</code>, <code>X</code>. Those behaviours should be kept the same.</li>
</ul>
<p>Basically, they should work so that a user can predict the output from reading the <code>man printf</code> page.</p>
<p>I decided that the <code>'</code> flag character, which normally should group the output in thousands, would be more meaningful here if it grouped nibbles (half bytes), and instead of using the locale for thousands separator, it should use <code>_</code>. But I'm open to improvements here.</p>
<p>Here goes the code:</p>
<pre><code>/* 2019 - Alejandro Colomar Andrés */
/******************************************************************************
******* headers **************************************************************
******************************************************************************/
#include "libalx/base/stdio/printf.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <printf.h>
/******************************************************************************
******* macros ***************************************************************
******************************************************************************/
/******************************************************************************
******* enums ****************************************************************
******************************************************************************/
/******************************************************************************
******* structs / unions *****************************************************
******************************************************************************/
/******************************************************************************
******* variables ************************************************************
******************************************************************************/
/******************************************************************************
******* static functions (prototypes) ****************************************
******************************************************************************/
static int printf_output_b (FILE *stream,
const struct printf_info *info,
const void *const *args);
static int printf_arginf_sz_b (const struct printf_info *info,
size_t n, int *argtypes, int *size);
/******************************************************************************
******* global functions *****************************************************
******************************************************************************/
int alx_printf_init (void)
{
if (register_printf_specifier('b', printf_output_b, printf_arginf_sz_b))
return -1;
if (register_printf_specifier('B', printf_output_b, printf_arginf_sz_b))
return -1;
return 0;
}
/******************************************************************************
******* static functions (definitions) ***************************************
******************************************************************************/
static int printf_output_b (FILE *stream,
const struct printf_info *info,
const void *const *args)
{
uintmax_t val;
uintmax_t utmp;
bool bin[sizeof(val) * 8];
int min_len;
int bin_len;
int pad_len;
int tmp;
char pad_ch;
size_t len;
len = 0;
if (info->is_long_double)
val = *(unsigned long long *)args[0];
else if (info->is_long)
val = *(unsigned long *)args[0];
else if (info->is_char)
val = *(unsigned char *)args[0];
else if (info->is_short)
val = *(unsigned short *)args[0];
else
val = *(unsigned *)args[0];
/* Binary representation */
memset(bin, 0, sizeof(bin));
utmp = val;
for (min_len = 0; utmp; min_len++) {
if (utmp % 2)
bin[min_len] = 1;
utmp >>= 1;
}
if (info->prec > min_len)
bin_len = info->prec;
else
bin_len = min_len;
/* Padding char */
if ((info->prec != -1) || (info->pad == ' ') || info->left)
pad_ch = ' ';
else
pad_ch = '0';
/* Padding length */
if (pad_ch == ' ') {
pad_len = info->width - bin_len;
if (info->alt)
pad_len -= 2;
if (info->group)
pad_len -= (bin_len - 1) / 4;
if (pad_len < 0)
pad_len = 0;
}
/* Padding with ' ' (right aligned) */
if ((pad_ch == ' ') && !info->left) {
for (int i = pad_len; i; i--) {
if (fputc(' ', stream) == EOF)
return EOF;
}
len += pad_len;
}
/* "0b"/"0B" prefix */
if (info->alt && val) {
if (fputc('0', stream) == EOF)
return EOF;
if (fputc(info->spec, stream) == EOF)
return EOF;
len += 2;
}
/* Padding with '0' */
if (pad_ch == '0') {
tmp = info->width - (info->alt * 2);
if (info->group)
tmp -= (tmp - min_len + 3) / 4;
for (int i = tmp - 1; i > min_len - 1; i--) {
if (fputc('0', stream) == EOF)
return EOF;
if (info->group && !(i % 4) && i) {
if (fputc('_', stream) == EOF)
return EOF;
len++;
}
}
len += tmp - min_len;
}
/* Print leading zeros to fill precission */
for (int i = bin_len - 1; i > min_len - 1; i--) {
if (fputc('0', stream) == EOF)
return EOF;
if (info->group && !(i % 4) && i) {
if (fputc('_', stream) == EOF)
return EOF;
len++;
}
}
len += bin_len - min_len;
/* Print number */
for (int i = min_len - 1; i; i--) {
if (fputc('0' + bin[i], stream) == EOF)
return EOF;
if (info->group && !(i % 4) && i) {
if (fputc('_', stream) == EOF)
return EOF;
len++;
}
}
if (fputc('0' + bin[0], stream) == EOF)
return EOF;
len += min_len;
/* Padding with ' ' (left aligned) */
if (info->left) {
for (int i = pad_len; i; i--) {
if (fputc(' ', stream) == EOF)
return EOF;
}
len += pad_len;
}
return len;
}
static int printf_arginf_sz_b (const struct printf_info *info,
size_t n, int *argtypes, int *size)
{
if (n > 0)
argtypes[0] = PA_INT;
return 1;
}
/******************************************************************************
******* end of file **********************************************************
******************************************************************************/
</code></pre>
<p>It seems that it works as expected (at least on my tests), but I feel like the code is very heavy and long and could be simplified.</p>
<p>Here is what I've tested:</p>
<pre><code>#include "libalx/base/stdio/printf.h"
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
int main()
{
alx_printf_init();
printf("....----....----....----....----\n");
printf("%llb;\n", 0x5Ellu);
printf("%lB;\n", 0x5Elu);
printf("%b;\n", 0x5Eu);
printf("%hB;\n", 0x5Eu);
printf("%hhb;\n", 0x5Eu);
printf("%jb;\n", (uintmax_t)0x5E);
printf("%zb;\n", (size_t)0x5E);
printf("....----....----....----....----\n");
printf("%#b;\n", 0x5Eu);
printf("%#B;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("%10b;\n", 0x5Eu);
printf("%010b;\n", 0x5Eu);
printf("%.10b;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("%-10B;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("%'B;\n", 0x5Eu);
printf("....----....----....----....----\n");
printf("....----....----....----....----\n");
printf("%#16.12b;\n", 0xAB);
printf("%-#'20.12b;\n", 0xAB);
printf("%#'020B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#020B;\n", 0xAB);
printf("%'020B;\n", 0xAB);
printf("%020B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#021B;\n", 0xAB);
printf("%'021B;\n", 0xAB);
printf("%021B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#022B;\n", 0xAB);
printf("%'022B;\n", 0xAB);
printf("%022B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%#023B;\n", 0xAB);
printf("%'023B;\n", 0xAB);
printf("%023B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%-#'19.11b;\n", 0xAB);
printf("%#'019B;\n", 0xAB);
printf("%#019B;\n", 0xAB);
printf("....----....----....----....----\n");
printf("%'019B;\n", 0xAB);
printf("%019B;\n", 0xAB);
printf("%#016b;\n", 0xAB);
printf("....----....----....----....----\n");
return 0;
}
</code></pre>
<p>And its output:</p>
<pre><code>....----....----....----....----
1011110;
1011110;
1011110;
1011110;
1011110;
1011110;
1011110;
....----....----....----....----
0b1011110;
0B1011110;
....----....----....----....----
1011110;
0001011110;
0001011110;
....----....----....----....----
1011110 ;
....----....----....----....----
101_1110;
....----....----....----....----
....----....----....----....----
0b000010101011;
0b0000_1010_1011 ;
0B000_0000_1010_1011;
....----....----....----....----
0B000000000010101011;
0_0000_0000_1010_1011;
00000000000010101011;
....----....----....----....----
0B0000000000010101011;
0_0000_0000_1010_1011;
000000000000010101011;
....----....----....----....----
0B00000000000010101011;
00_0000_0000_1010_1011;
0000000000000010101011;
....----....----....----....----
0B000000000000010101011;
000_0000_0000_1010_1011;
00000000000000010101011;
....----....----....----....----
0b000_1010_1011 ;
0B00_0000_1010_1011;
0B00000000010101011;
....----....----....----....----
0000_0000_1010_1011;
0000000000010101011;
0b00000010101011;
....----....----....----....----
</code></pre>
<p>I understood the use of <code>printf_output_b</code>, but I still don't know very well the use of <code>printf_arginf_sz_b</code>, and if I'm missing anything.</p>
<p>Is there anything you miss here, or you think could be improved?</p>
<p>Also, let's say that <code>uintmax_t</code> or <code>size_t</code> are wider than <code>unsigned long long</code>. How would I handle that? I don't receive any information about those in the <code>struct</code>, AFAIK.</p>
<p><strong>EDIT:</strong> Add the struct and enum definitions from <code><printf.h></code></p>
<pre><code>struct printf_info{
int prec; /* Precision. */
int width; /* Width. */
wchar_t spec; /* Format letter. */
unsigned int is_long_double:1;/* L flag. */
unsigned int is_short:1; /* h flag. */
unsigned int is_long:1; /* l flag. */
unsigned int alt:1; /* # flag. */
unsigned int space:1; /* Space flag. */
unsigned int left:1; /* - flag. */
unsigned int showsign:1; /* + flag. */
unsigned int group:1; /* ' flag. */
unsigned int extra:1; /* For special use. */
unsigned int is_char:1; /* hh flag. */
unsigned int wide:1; /* Nonzero for wide character streams. */
unsigned int i18n:1; /* I flag. */
unsigned int is_binary128:1; /* Floating-point argument is ABI-compatible with IEC 60559 binary128. */
unsigned int __pad:3; /* Unused so far. */
unsigned short int user; /* Bits for user-installed modifiers. */
wchar_t pad; /* Padding character. */
};
enum{ /* C type: */
PA_INT, /* int */
PA_CHAR, /* int, cast to char */
PA_WCHAR, /* wide char */
PA_STRING, /* const char *, a '\0'-terminated string */
PA_WSTRING, /* const wchar_t *, wide character string */
PA_POINTER, /* void * */
PA_FLOAT, /* float */
PA_DOUBLE, /* double */
PA_LAST
};
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:58:17.857",
"Id": "425075",
"Score": "0",
"body": "What exactly are you asking, do you want us to explain what `printf_arginf_sz_b()` does as well as the size of uintmax_t and size_t?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:12:12.247",
"Id": "425080",
"Score": "0",
"body": "@pacmaninbw I'd like to see improvements in code cleanness/performance and if I anticipated (as per the requirements) all possible combinations of flags (including `\"%jb\"` (`uint_max`) for example). Also, obviously, if there is any UB, I would like to know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:34:10.733",
"Id": "425083",
"Score": "0",
"body": "Could you please add the file(s) that define `struct printf_info` and PA_INT."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:00:47.990",
"Id": "425122",
"Score": "1",
"body": "@pacmaninbw They're all from `<printf.h>` from glibc (https://github.com/lattera/glibc/blob/master/stdio-common/printf.h). I edited the question to add them."
}
] | [
{
"body": "<p><strong>zero</strong></p>\n\n<p><code>min_len</code> is calculated as 0 when <code>val == 0</code>. I'd expect <code>min_len</code> to be 1.</p>\n\n<p><strong>Casual conversion</strong></p>\n\n<p>Pedantic: code returns <code>size_t len</code> as <code>int</code> with no range check in the conversion. Might as well just use <code>int len</code>.</p>\n\n<p><strong><code>len</code> calculation</strong></p>\n\n<p>Code does not display the return value of <code>printf()</code> in its tests. I have suspicions about its correctness. Suggest instead to simply pair each <code>fputc()</code> with a <code>len++</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T08:21:02.120",
"Id": "220037",
"ParentId": "219994",
"Score": "3"
}
},
{
"body": "<p><strong>EDIT:</strong> I also fixed a typo: <code>main</code> should be <code>int main(void)</code>!</p>\n\n<hr>\n\n<p>After fixing the bugs <strong>@chux</strong> found, there was still another bug:</p>\n\n<p>This line:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code> tmp -= (tmp - min_len + 3) / 4;\n</code></pre>\n\n<p>should be:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code> tmp -= tmp / 5 - !(tmp % 5);\n</code></pre>\n\n<p>I also restructured the big function into smaller functions, and used <code>CHAR_BIT</code> instead of the magic number <code>8</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>/* 2019 - Alejandro Colomar Andrés */\n/******************************************************************************\n ******* headers **************************************************************\n ******************************************************************************/\n#include \"libalx/base/stdio/printf.h\"\n\n#include <limits.h>\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <printf.h>\n\n\n/******************************************************************************\n ******* macros ***************************************************************\n ******************************************************************************/\n#define BIN_REPR_BUFSIZ (sizeof(uintmax_t) * CHAR_BIT)\n\n\n/******************************************************************************\n ******* enums ****************************************************************\n ******************************************************************************/\n\n\n/******************************************************************************\n ******* structs / unions *****************************************************\n ******************************************************************************/\nstruct Printf_Pad {\n char ch;\n int len;\n};\n\n\n/******************************************************************************\n ******* variables ************************************************************\n ******************************************************************************/\n\n\n/******************************************************************************\n ******* static functions (prototypes) ****************************************\n ******************************************************************************/\nstatic int printf_b_output (FILE *stream,\n const struct printf_info *info,\n const void *const args[]);\nstatic int printf_b_arginf_sz (const struct printf_info *info,\n size_t n, int *argtypes, int *size);\n\nstatic uintmax_t printf_b_value (const struct printf_info *info,\n const void *arg);\nstatic int printf_b_bin_repr (bool bin[BIN_REPR_BUFSIZ],\n const struct printf_info *info,\n const void *arg);\nstatic int printf_b_bin_len (const struct printf_info *info,\n int min_len);\nstatic int printf_b_pad_len (const struct printf_info *info,\n int bin_len);\nstatic int printf_b_print_prefix (FILE *stream,\n const struct printf_info *info);\nstatic int printf_b_pad_zeros (FILE *stream,\n const struct printf_info *info,\n int min_len);\nstatic int printf_b_print_number (FILE *stream,\n const struct printf_info *info,\n bool bin[BIN_REPR_BUFSIZ],\n int min_len, int bin_len);\nstatic char printf_pad_ch (const struct printf_info *info);\nstatic int printf_pad_spaces (FILE *stream, int pad_len);\n\n\n\n\n/******************************************************************************\n ******* global functions *****************************************************\n ******************************************************************************/\nint alx_printf_init (void)\n{\n\n if (register_printf_specifier('b', printf_b_output, printf_b_arginf_sz))\n return -1;\n if (register_printf_specifier('B', printf_b_output, printf_b_arginf_sz))\n return -1;\n\n return 0;\n}\n\n\n/******************************************************************************\n ******* static functions (definitions) ***************************************\n ******************************************************************************/\nstatic int printf_b_output (FILE *stream,\n const struct printf_info *info,\n const void *const args[])\n{\n struct Printf_Pad pad = {0};\n bool bin[BIN_REPR_BUFSIZ];\n int min_len;\n int bin_len;\n int len;\n int tmp;\n\n len = 0;\n\n min_len = printf_b_bin_repr(bin, info, args[0]);\n bin_len = printf_b_bin_len(info, min_len);\n\n pad.ch = printf_pad_ch(info);\n if (pad.ch == ' ')\n pad.len = printf_b_pad_len(info, bin_len);\n\n /* Padding with ' ' (right aligned) */\n if ((pad.ch == ' ') && !info->left) {\n tmp = printf_pad_spaces(stream, pad.len);\n if (tmp == EOF)\n return EOF;\n len += tmp;\n }\n\n /* \"0b\"/\"0B\" prefix */\n if (info->alt) {\n tmp = printf_b_print_prefix(stream, info);\n if (tmp == EOF)\n return EOF;\n len += tmp;\n }\n\n /* Padding with '0' */\n if (pad.ch == '0') {\n tmp = printf_b_pad_zeros(stream, info, min_len);\n if (tmp == EOF)\n return EOF;\n len += tmp;\n }\n\n /* Print number (including leading 0s to fill precission) */\n tmp = printf_b_print_number(stream, info, bin, min_len, bin_len);\n if (tmp == EOF)\n return EOF;\n len += tmp;\n\n /* Padding with ' ' (left aligned) */\n if (info->left) {\n tmp = printf_pad_spaces(stream, pad.len);\n if (tmp == EOF)\n return EOF;\n len += tmp;\n }\n\n return len;\n}\n\nstatic int printf_b_arginf_sz (const struct printf_info *info,\n size_t n, int *argtypes, int *size)\n{\n\n (void)info;\n (void)size;\n\n if (n > 0)\n argtypes[0] = PA_INT;\n\n return 1;\n}\n\nstatic uintmax_t printf_b_value (const struct printf_info *info,\n const void *arg)\n{\n\n if (info->is_long_double)\n return *(unsigned long long *)arg;\n if (info->is_long)\n return *(unsigned long *)arg;\n if (info->is_char)\n return *(unsigned char *)arg;\n if (info->is_short)\n return *(unsigned short *)arg;\n return *(unsigned *)arg;\n}\n\nstatic int printf_b_bin_repr (bool bin[BIN_REPR_BUFSIZ],\n const struct printf_info *info,\n const void *arg)\n{\n uintmax_t val;\n int min_len;\n\n val = printf_b_value(info, arg);\n\n memset(bin, 0, sizeof(bin[0]) * BIN_REPR_BUFSIZ);\n for (min_len = 0; val; min_len++) {\n if (val % 2)\n bin[min_len] = 1;\n val >>= 1;\n }\n\n if (!min_len)\n return 1;\n return min_len;\n}\n\nstatic int printf_b_bin_len (const struct printf_info *info,\n int min_len)\n{\n\n if (info->prec > min_len)\n return info->prec;\n return min_len;\n}\n\nstatic int printf_b_pad_len (const struct printf_info *info,\n int bin_len)\n{\n int pad_len;\n\n pad_len = info->width - bin_len;\n if (info->alt)\n pad_len -= 2;\n if (info->group)\n pad_len -= (bin_len - 1) / 4;\n if (pad_len < 0)\n pad_len = 0;\n\n return pad_len;\n}\n\nstatic int printf_b_print_prefix (FILE *stream,\n const struct printf_info *info)\n{\n int len;\n\n len = 0;\n if (fputc('0', stream) == EOF)\n return EOF;\n len++;\n if (fputc(info->spec, stream) == EOF)\n return EOF;\n len++;\n\n return len;\n}\n\nstatic int printf_b_pad_zeros (FILE *stream,\n const struct printf_info *info,\n int min_len)\n{\n int len;\n int tmp;\n\n len = 0;\n tmp = info->width - (info->alt * 2);\n if (info->group)\n tmp -= tmp / 5 - !(tmp % 5);\n for (int i = tmp - 1; i > min_len - 1; i--) {\n if (fputc('0', stream) == EOF)\n return EOF;\n len++;\n if (info->group && !(i % 4)) {\n if (fputc('_', stream) == EOF)\n return EOF;\n len++;\n }\n }\n\n return len;\n}\n\nstatic int printf_b_print_number (FILE *stream,\n const struct printf_info *info,\n bool bin[sizeof(uintmax_t) * CHAR_BIT],\n int min_len, int bin_len)\n{\n int len;\n\n len = 0;\n\n /* Print leading zeros to fill precission */\n for (int i = bin_len - 1; i > min_len - 1; i--) {\n if (fputc('0', stream) == EOF)\n return EOF;\n len++;\n if (info->group && !(i % 4)) {\n if (fputc('_', stream) == EOF)\n return EOF;\n len++;\n }\n }\n\n /* Print number */\n for (int i = min_len - 1; i; i--) {\n if (fputc('0' + bin[i], stream) == EOF)\n return EOF;\n len++;\n if (info->group && !(i % 4)) {\n if (fputc('_', stream) == EOF)\n return EOF;\n len++;\n }\n }\n if (fputc('0' + bin[0], stream) == EOF)\n return EOF;\n len++;\n\n return len;\n}\n\nstatic char printf_pad_ch (const struct printf_info *info)\n{\n\n if ((info->prec != -1) || (info->pad == ' ') || info->left)\n return ' ';\n return '0';\n}\n\nstatic int printf_pad_spaces (FILE *stream, int pad_len)\n{\n int len;\n\n len = 0;\n for (int i = pad_len; i; i--) {\n if (fputc(' ', stream) == EOF)\n return EOF;\n len++;\n }\n\n return len;\n}\n\n\n/******************************************************************************\n ******* end of file **********************************************************\n ******************************************************************************/\n</code></pre>\n\n<p>I also added some more tests to be able to detect that bug, which I was suspecting that existed; now I also show the value of <code>len</code> (calculated indirectly from the return value of <code>printf</code>):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>/* Test */\n#include \"libalx/base/stdio/printf.h\"\n\n\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\nint main(void)\n{\n int len;\n char buff[BUFSIZ];\n\n alx_printf_init();\n\n snprintf(buff, 30, \"Hey, %i == %#b :)\\n\", 5, 5);\n printf(\"%s\", buff);\n printf(\"\\n\");\n\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%llb;\\n\", 0x5Ellu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%lB;\\n\", 0x5Elu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%b;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%hB;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%hhb;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%jb;\\n\", (uintmax_t)0x5E);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%zb;\\n\", (size_t)0x5E);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%#b;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#B;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%10b;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%010b;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%.10b;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%-10B;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'B;\\n\", 0x5Eu);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\"); \n printf(\"....----....----....----....----\\n\");\n len = printf(\"%#16.12b;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%-#'20.12b;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'020B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%#020B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'020B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%020B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%#021B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'021B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%021B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%#022B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'022B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%022B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%#023B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'023B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%023B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%-#'19.11b;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'019B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#019B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'019B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%019B;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#016b;\\n\", 0xAB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'010B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'010B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'010B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'010B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'010B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'010B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'011B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'011B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'012B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'012B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'013B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'013B;\\n\", 0xB);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'010B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'011B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'011B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'012B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'012B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'013B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'013B;\\n\", 0x1B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'010B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'011B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'011B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'012B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'012B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'013B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'013B;\\n\", 0x2B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'010B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'011B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'011B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'012B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'012B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'013B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'013B;\\n\", 0x4B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n len = printf(\"%'010B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'010B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'011B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'011B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'012B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'012B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%'013B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n len = printf(\"%#'013B;\\n\", 0x8B);\n printf(\"%i\\n\", len - strlen(\";\\n\"));\n printf(\"....----....----....----....----\\n\");\n\n return 0;\n}\n</code></pre>\n\n<p>Which shows the following output:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>Hey, 5 == 0b101 :)\n\n....----....----....----....----\n1011110;\n7\n1011110;\n7\n1011110;\n7\n1011110;\n7\n1011110;\n7\n1011110;\n7\n1011110;\n7\n....----....----....----....----\n0b1011110;\n9\n0B1011110;\n9\n....----....----....----....----\n 1011110;\n10\n0001011110;\n10\n0001011110;\n10\n....----....----....----....----\n1011110 ;\n10\n....----....----....----....----\n101_1110;\n8\n....----....----....----....----\n....----....----....----....----\n 0b000010101011;\n16\n0b0000_1010_1011 ;\n20\n0B000_0000_1010_1011;\n20\n....----....----....----....----\n0B000000000010101011;\n20\n0_0000_0000_1010_1011;\n21\n00000000000010101011;\n20\n....----....----....----....----\n0B0000000000010101011;\n21\n0_0000_0000_1010_1011;\n21\n000000000000010101011;\n21\n....----....----....----....----\n0B00000000000010101011;\n22\n00_0000_0000_1010_1011;\n22\n0000000000000010101011;\n22\n....----....----....----....----\n0B000000000000010101011;\n23\n000_0000_0000_1010_1011;\n23\n00000000000000010101011;\n23\n....----....----....----....----\n0b000_1010_1011 ;\n19\n0B00_0000_1010_1011;\n19\n0B00000000010101011;\n19\n....----....----....----....----\n0000_0000_1010_1011;\n19\n0000000000010101011;\n19\n0b00000010101011;\n16\n....----....----....----....----\n....----....----....----....----\n0_0000_1011;\n11\n0B000_1011;\n10\n0_0001_1011;\n11\n0B001_1011;\n10\n0_0010_1011;\n11\n0B010_1011;\n10\n0_0100_1011;\n11\n0B100_1011;\n10\n0_1000_1011;\n11\n0B1000_1011;\n11\n....----....----....----....----\n0_0000_1011;\n11\n0B000_1011;\n10\n0_0000_1011;\n11\n0B0000_1011;\n11\n00_0000_1011;\n12\n0B0_0000_1011;\n13\n000_0000_1011;\n13\n0B0_0000_1011;\n13\n....----....----....----....----\n0_0001_1011;\n11\n0B001_1011;\n10\n0_0001_1011;\n11\n0B0001_1011;\n11\n00_0001_1011;\n12\n0B0_0001_1011;\n13\n000_0001_1011;\n13\n0B0_0001_1011;\n13\n....----....----....----....----\n0_0010_1011;\n11\n0B010_1011;\n10\n0_0010_1011;\n11\n0B0010_1011;\n11\n00_0010_1011;\n12\n0B0_0010_1011;\n13\n000_0010_1011;\n13\n0B0_0010_1011;\n13\n....----....----....----....----\n0_0100_1011;\n11\n0B100_1011;\n10\n0_0100_1011;\n11\n0B0100_1011;\n11\n00_0100_1011;\n12\n0B0_0100_1011;\n13\n000_0100_1011;\n13\n0B0_0100_1011;\n13\n....----....----....----....----\n0_1000_1011;\n11\n0B1000_1011;\n11\n0_1000_1011;\n11\n0B1000_1011;\n11\n00_1000_1011;\n12\n0B0_1000_1011;\n13\n000_1000_1011;\n13\n0B0_1000_1011;\n13\n....----....----....----....----\n<span class=\"math-container\">````</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T17:05:29.787",
"Id": "220581",
"ParentId": "219994",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220037",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:29:18.483",
"Id": "219994",
"Score": "7",
"Tags": [
"c",
"formatting",
"integer",
"bitwise",
"gcc"
],
"Title": "Register \"%b\" conversion specifier"
} | 219994 |
<p>to learn <code>Reagent</code>, <code>re-frame</code> and <code>spec</code> I made a little personal project.</p>
<p>Description:</p>
<ul>
<li>Given a list of Employees (name, date of when the mission end, and role of the employee), ouput a table with their information.</li>
<li>Add visual cue if the mission is already finished, soon to be finished (I choose 30days) or will not finish soon.</li>
<li>Add filters to the table (a bit like in Excel spreadsheet) for names and for roles</li>
</ul>
<p>Here is the code</p>
<pre><code>(ns my.reagent-examples
(:require [reagent.core :as reagent]
[cljs.spec.alpha :as s]
[re-frame.db :as db]
[re-frame.core :as rf]))
;; -- Specs --
;; -----------
(s/def ::name string?) ; Name is a string
(s/def ::date-fin-mandat inst?) ; date is of type #inst (a timestamp)
(s/def ::role keyword?) ;role is a keyword
; One people is a map with required keys name, date and role and no optional keys
(s/def ::people (s/keys :req [::name ::date-fin-mandat ::role] ;; ?Should I use :req or :un-req ?
:opt []))
; Peoples is a vector of 0 to many people
(s/def ::peoples (s/coll-of ::people :kind vector? :min-count 0))
; A filter is a 2 elements vector of keyword like [:role :dev]
(s/def ::filter (s/tuple keyword? (s/or :s string? :k keyword?)))
; Filters is a vector of 0 to many filter
(s/def ::filters (s/coll-of ::filter :kind vector? :min-count 0))
; Spec for the whole db
(s/def ::db (s/keys :req-un [::peoples ::filters]))
;; -- Data --
;; --------
(def peoples [
{::name "julien"
::date-fin-mandat (js/Date.)
::role :dev}
{::name "juscellino"
::date-fin-mandat (js/Date. 2019 7 21)
::role :dev}
{::name "danny"
::date-fin-mandat (js/Date. 2019 4 15)
::role :dev}
{::name "nathalie"
::date-fin-mandat (js/Date. 2031 9 22)
::role :rh}
{::name "malik"
::date-fin-mandat (js/Date. 2019 1 22)
::role :analyste}
{::name "daniel"
::date-fin-mandat (js/Date. 2019 8 15)
::role :dev}])
;; -- Helpers --
;; -------------
(defn filter-people
[peoples filters]
(into
[]
(set
(flatten
(mapv
(fn [[k v]]
(filter
#(= (k %1) v)
peoples))
filters)))))
(def end-soon-style {:background-color "red"})
(def end-not-so-soon-style {:background-color "orange"})
(def end-very-not-soon-style {:background-color "green"})
(defn date+30
[date]
(js/Date. (.getFullYear date) (.getMonth date) (+ (.getDate date) 30)))
(defn date+90
[date]
(js/Date. (.getFullYear date) (.getMonth date) (+ (.getDate date) 90)))
(defn style-by-date
[date end-soon end-not-so-soon end-very-not-soon]
(let [today (js/Date.)]
(cond
(>= today date) end-soon
(< date (date+30 today)) end-not-so-soon
:else end-very-not-soon)))
;; -- 1 - Dispatch event --
;; ------------------------
; Do i need this?
(defn dispatch-add-filter-event
[new-filter]
(rf/dispatch [:add-filter [:role :dev]]))
;; -- 2 - Event Handler --
;; -----------------------
;; -- Interceptor --
;; -----------------
; Interceptor for validating spec after every add into db
(defn check-and-throw
"Throws an exception if `db` doesn't match the Spec `a-spec`."
[a-spec db]
(when-not (s/valid? a-spec db)
(throw (ex-info (str "spec check failed: " (s/explain-str a-spec db)) {}))))
;; now we create an interceptor using `after`
(def check-spec-interceptor (rf/after (partial check-and-throw ::db)))
;; -- Define Event Handlers --
;; ---------------------------
; Initialize the app state
(rf/reg-event-db
:initialize
[check-spec-interceptor]
(fn [_ _]
{:peoples peoples
:filters [[::role :dev] [::name "julien"]]}))
; Add a new filter in app state
(rf/reg-event-db
:add-filter
[check-spec-interceptor]
(fn [db [_ new-filter]]
(assoc db :filters (conj (:filters db) new-filter))))
; Add all filters for a particular key
(rf/reg-event-db
:add-all-filters-for-key
[check-spec-interceptor]
(fn [db [_ key1 values]]
(assoc db
:filters
(into
(:filters db)
(map
#(vec [key1 %1])
values)))))
; Remove a filter from app state
(rf/reg-event-db
:remove-filter
[check-spec-interceptor]
(fn [db [_ old-filter]]
(assoc db
:filters
(filterv
#(not (= %1 old-filter))
(:filters db)))))
; Remove all filters from app state for a particular key
(rf/reg-event-db
:remove-all-filters-for-key
[check-spec-interceptor]
(fn [db [_ key1]]
(assoc db
:filters
(filterv
#(not (= (first %1) key1))
(:filters db)))))
;; -- 3 - Effect Handler --
;; ------------------------
;; ?? Probably nothing here??
;; -- 4 - Subscription Handler --
;; ------------------------------
; Return the vector of filters
(rf/reg-sub
:filters
(fn [db _]
(:filters db)))
; Return the peoples, unfiltered
(rf/reg-sub
:peoples
(fn [db _]
(:peoples db)))
; Return a list of filtered peoples
(rf/reg-sub
:peoples-filtered
(fn [db _]
(filter-people (:peoples db) (:filters db))))
; Given a key k, return a vector of values representing all the values present in peoples
(rf/reg-sub
:values-for-key
(fn [db [_ k]]
(map #(k %1) (:peoples db))))
; Does filter contains the value k in it?
(rf/reg-sub
:filter-contains?
(fn [db [_ k]]
(contains? (set (:filters db)) k)))
;; -- 5 - View Function --
;; -----------------------
(defn list-people
[]
[:p (pr-str @(rf/subscribe [:peoples]))])
(defn list-people-filtered
[]
[:p (pr-str @(rf/subscribe [:peoples-filtered]))])
(defn list-filter
[]
[:p (pr-str @(rf/subscribe [:filters]))])
(defn button-add-role
[role]
[:button
{:on-click (fn [e] (rf/dispatch [:add-filter [::role role]]))}
(pr-str "Add filter" role)])
(defn button-remove-role
[role]
[:button
{:on-click (fn [e] (rf/dispatch [:remove-filter [::role role]]))}
(pr-str "Remove filter" role)])
(defn ressource
[data]
[:tr
[:td (data ::name)]
[:td {:style (style-by-date
(data ::date-fin-mandat)
end-soon-style
end-not-so-soon-style
end-very-not-soon-style)}(str (data ::date-fin-mandat))]
[:td (data ::role)]
])
(defn checklist-filter
[key1]
(let [list-values (set @(rf/subscribe [:values-for-key key1]))]
(into
[:form
[:input
{:type "checkbox"
:id (str "all-" key1)
:name (str "all-" key1)
:on-change (fn [e] (if (.. e -target -checked)
(rf/dispatch [:add-all-filters-for-key key1 list-values])
(rf/dispatch [:remove-all-filters-for-key key1])))}]
[:label {:for (str "all-" key1)} "All"]
]
(for [value list-values]
[:div
[:input
{:type "checkbox"
:id value
:name value
:on-change (fn [e] (if (.. e -target -checked)
(rf/dispatch [:add-filter [key1 value]])
(rf/dispatch [:remove-filter [key1 value]])))
:checked @(rf/subscribe [:filter-contains? [key1 value]])
}]
[:label {:for value} value]]
))))
(defn peoples-ui-filtered
[]
(let [pf @(rf/subscribe [:peoples-filtered])]
(into
[:table
[:tr
[:th "NAME"]
[:th "DATE FIN MANDAT"]
[:th "ROLE"]]
[:tr
[:td [checklist-filter ::name]]
[:td ]
[:td [checklist-filter ::role]]]
]
(doall
(for [p pf]
[ressource p])))))
(defn ui
[]
[:div
[peoples-ui-filtered]
])
;; -- Kickstart the application --
;; -------------------------------
(defn ^:export run
[]
(rf/dispatch-sync [:initialize]) ;; puts a value into application state
(reagent/render [ui] ;; mount the application's ui into ''
(js/document.getElementById "app")))
(run)
</code></pre>
<p>You can also look at <a href="https://gist.github.com/JulienRouse/32b3119f305491f70c70b30df0b64859" rel="nofollow noreferrer">this gist</a> that has the same code in <code>table.cljs</code>, and also <code>klipse.html</code> which is a html page with Klipse setup to try the code in the browser.</p>
<p>As for the review, every feedbacks is appreciated but especially about re-frame and spec. </p>
<ul>
<li><p>Did I understand correctly the separation of event handlers, effect handlers etc in re-frame? </p></li>
<li><p>Like I know that I did not use Dispatch Event much, where should I use those?</p></li>
<li><p>I did not use Effect Handler, but if I understand correctly, that would be the place for database query, localStorage operations, call to external API etc. No use in my project, am I correct?</p></li>
<li><p>Following the <a href="https://github.com/Day8/re-frame/blob/master/examples/todomvc/src/todomvc/events.cljs#L49" rel="nofollow noreferrer">re-frame todomvc example</a>, I added specs and a spec interceptor (copy-pasted from this example). Does my specs looks correct?</p></li>
<li><p>Is defining specs and an Interceptor something I should do in every project? Or is there case I should avoid it?</p></li>
</ul>
<p>And finally, how is my overall clojure/script code?</p>
<p>I am aware that I should have many files in a real project (<code>core</code>, <code>db</code>, <code>events</code>, <code>subs</code> and <code>views</code>) but I coded in my browser with the help of Klipse so I put everything in the same file for now.</p>
| [] | [
{
"body": "<p>Unfortunately, I've never used spec, reframe or clojurescript before, but I can note general Clojure things that can be fixed up.</p>\n\n<p><code>filter-people</code> has far too much nesting. Having code like you do affects readability (you need to read it bottom-up instead of top-down like you would most code), and makes it harder to add to (as you'll need to need adjust indentation and be careful with bracket addition). It would be much cleaner if you used <code>->></code> (the thread last macro) instead:</p>\n\n<pre><code>(defn filter-people\n [peoples filters]\n (->> filters\n (mapv\n (fn [[k v]]\n (filter #(= (k %1) v) peoples)))\n (flatten)\n (set)\n (vec))) ; Instead of (into [])\n</code></pre>\n\n<hr>\n\n<p>Your <code>date+</code> functions have unnecessary duplication. I'd add a parameter for <code>days</code> to generalize them:</p>\n\n<pre><code>(defn date+days [date days]\n (js/Date. (.getFullYear date) (.getMonth date) (+ (.getDate date) days)))\n</code></pre>\n\n<p>If you <em>really</em> wanted a <code>date+90</code> and other such functions, define them in terms of the generalized function:</p>\n\n<pre><code>(defn date+90 [date]\n (date+days date 90))\n</code></pre>\n\n<p>Now if you need to make changes to the implementation, you aren't needing to change several functions. </p>\n\n<hr>\n\n<p>If I were you, I'd indent a little more. You have a single space of indentation in many places. Code like</p>\n\n<pre><code>(fn [db [_ old-filter]]\n (assoc db \n :filters \n (filterv \n #(not (= %1 old-filter))\n (:filters db)))))\n</code></pre>\n\n<p>Is harder to read than it needs to be. I would prefer putting small anonymous functions on the same line as the function they're being passed to, and use at least 2 spaces to indent. In this case, I might also use a <code>let</code> binding the break it up a bit so it's easier to process what's going on. Something closer to:</p>\n\n<pre><code>(fn [db [_ old-filter]]\n (let [filtered (filterv #(not (= %1 old-filter))\n (:filters db))]\n (assoc db :filters filtered)))\n</code></pre>\n\n<p>Also note, <code>(filter #(not ...</code> is common and has a shortcut function called <code>remove</code>. You could make use of it here:</p>\n\n<pre><code>(remove #(= %1 old-filter) (:filters db))\n</code></pre>\n\n<p>Although this returns a lazy sequence and there is no <code>removev</code> version so if you definitely need a vector, you'll need to add a call to <code>vec</code>, or just use the version you had.</p>\n\n<hr>\n\n<p>Here</p>\n\n<pre><code>(assoc db\n :filters\n (into \n (:filters db)\n (map\n #(vec [key1 %1])\n values)))))\n</code></pre>\n\n<p>You're <code>assoc</code>iating to <code>db</code>, but the new value is dependent on the old value. When that's the case, it's often preferred to use <code>update</code> instead:</p>\n\n<pre><code>(fn [db [_ key1 values]]\n (update db :filters\n (fn [fs]\n (into fs (map #(vec [key1 %1]) values)))))\n</code></pre>\n\n<p>Unfortunately, the gain isn't huge here because you're already using a short-hand function macro (<code>#()</code>), and they can't be nested. It often leads to cleaner code though.</p>\n\n<hr>\n\n<p>I'll just point out that here</p>\n\n<pre><code>(contains? (set (:filters db)) k)))\n</code></pre>\n\n<p><code>contains?</code> is unnecessary. Sets can be invoked to test for membership.</p>\n\n<pre><code>((set (:filters db)) k)\n</code></pre>\n\n<p>In some cases, (not necessarily here; see below though), that can lead to cleaner code.</p>\n\n<p>Putting it in a set just to test for membership though seems rather inefficient. If it was already in a set, ya, a membership test would be fast. With how you have it now though, you're doing a full iteration of <code>(:filters db)</code> just so you can do an efficient lookup. A lookup of <code>(:filters db)</code> only requires a full iteration anyways though (in the worst case). I'd use <code>some</code> and check for equality:</p>\n\n<pre><code>(some #(= k %) (:filters db))\n</code></pre>\n\n<p>or, to use the above set-as-a-function tip:</p>\n\n<pre><code>(some #{k} (:filters db)) ; Use the set as a predicate\n</code></pre>\n\n<p>This will return the first true result, or <code>nil</code> (falsey) if a result isn't found. The early exit ensures it only does as much work as it needs to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:33:25.923",
"Id": "425116",
"Score": "0",
"body": "Wow so much good tips here, thank you very much!\n\nFor the last point, I had in mind to change `filters` to be a set instead of a vector, I don't think I would lose anything and that might be a bit better. But your way of doing with `some` is interesting! Especially with the tip for set membership.\n\nAs for `->>`, is there a particular nesting point where you switch from nesting to threading macros or are they like a must do in most situations regardless?\n\nAnd for every other good tips here, thank you very much! `update` in place of `assoc` looks good and `remove` looks interesting too:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:56:36.640",
"Id": "425119",
"Score": "1",
"body": "@JulienRousé No problem. And for nesting limits, this is honestly something that I've gone back and forth on for the past couple years. I used to change it to threading macros once I had 4+ functions, but I've recently started starting at only 2 functions; especially if I think there's any chance that I'll need to add more functions to thread through later. I often write it with the macro from the start. I find threading macros to be much neater in really any circumstance when used properly. If you're transforming a list, you should probably be using `->>` unless you're just using one function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:56:53.853",
"Id": "425121",
"Score": "1",
"body": "@JulienRousé A thing you may want to keep in mind when writing your own functions is to allow them to work with the macros well. The rule I stick to are if the functions transforms a list, put the list as the last argument (so it works well with `map` and `filter` chains), else, put the data to be transformed as the first argument (so it works well with `->` chains that use functions like `assoc`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:36:50.997",
"Id": "220006",
"ParentId": "219996",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220006",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:32:42.023",
"Id": "219996",
"Score": "2",
"Tags": [
"clojure",
"clojurescript"
],
"Title": "Table of employee with end of mission visual clue"
} | 219996 |
<p>I wrote a version of sieve of eratosthenes:</p>
<pre><code>number =100000000
def eratos_sieve(n:"find prime below this"=None):
if not(n):
n = number
numbers = [x for x in range(0, n+1)]
current_prime = 2
sqrt_limit = int(math.sqrt(n))+1
while numbers[current_prime] <= sqrt_limit:
#(len(numbers)-1) is the actual size since
#since, len([0,...,n])=n+1
for i in range(current_prime, ((len(numbers)-1)//current_prime)+1):
numbers[current_prime*i]=-1
current_prime += 1
for i in range(current_prime, sqrt_limit):
if numbers[i]>0:
current_prime=i
break
#this part is optional
j = 0
for i in range(len(numbers)):
if numbers[i]>0:
numbers[j]=numbers[i]
j += 1
#uptil here if later primes are to be found using indices
#else all primes upto n are returned as a single list
return numbers[1:j]
</code></pre>
<p>It seems to perform fast enough for my purposes. I'd like to get some review about it's performance since I'm a novice. Also, I'd like someone with enough memory (if possible) to run the below two tests:</p>
<pre><code>import time
import math
num1 = 100000000 #100 million
num2 = 1000000000 #1 billion
start = time.perf_counter()
eratos_sieve(num1)
total_100_m = time.perf_counter()-start()
start = time.perf_counter()
eratos_sieve(num2)
total_1_b = time.perf_counter()-start()
print("For 100m it takes: ", total_100_m)
print("For 1b it takes: ", total_1_b)
</code></pre>
| [] | [
{
"body": "<h2>Four<sup>*</sup> letters to rule them all</h2>\n\n<p>The Sieve of Eratosthenes is an algorithm which heavily relies on loops. Unfortunately, Python's convenient scripty nature comes at a cost: it's <a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"noreferrer\">not terribly fast</a> when it comes to loops, so it's best to <a href=\"https://www.youtube.com/watch?v=zQeYx87mfyw\" rel=\"noreferrer\">avoid them</a>.</p>\n\n<p>However, this is not always possible, or one, like me in this case, is not so much into algorithms to transform them into another form. Enter <a href=\"http://numba.pydata.org/\" rel=\"noreferrer\">numba</a>. numba is a just-in-time compiler for Python code. The just-in-time compiler can transform plain Python code into \"native\" code for your system. So what are those magical four letters I was talking about? It's <code>@jit</code>. </p>\n\n<p>This simple decorator and no further code changes brought the time for n = 100 000 000 from 36s down to about 3s on my machine. The larger test case did not work out to well with my 16GB RAM and some other things to do apart from Code Review.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from numba import jit\n\n@jit\ndef eratos_sieve(n:\"find prime below this\"=100000000):\n # ... the rest of your code here\n</code></pre>\n\n<p>You can also have a look at <a href=\"https://stackoverflow.com/a/3941967/5682996\">this generator based implementation</a> of the algorithm presented on Stack Overflow. The implementation can benefit from just-in-time compilation as well. A quick test using the SO approach and <code>@jit</code> for the previous n brought the execution time down to just below 2s on the same machine as before.</p>\n\n<h2>What numba cannot fix for you</h2>\n\n<p>There are a few aspects with respect to style and idiomatic language features (often called pythonic code) that you have to/can improve yourself.</p>\n\n<p>While </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>number =10000000\ndef eratos_sieve(n:\"find prime below this\"=None):\n if not(n):\n n = number\n ...\n</code></pre>\n\n<p>might be working and syntactically valid, I find it very, very uncommon and would not recommend it. A more \"pythonic\" way to express this would be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def eratos_sieve(n: int = 100000000):\n \"\"\"Find all primes below a given whole number n\"\"\"\n ...\n</code></pre>\n\n<p>This makes use of Python 3's <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">type hinting</a> and the recommended way to write function documentation using <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\">docstrings</a>.</p>\n\n<p>The way you construct your candidate list using <code>numbers = [x for x in range(0, n+1)]</code> is also a little bit complicated, and may be simplified to <code>numbers = list(range(n+1))</code>. <code>0</code> is the implicit starting value for <code>range(...)</code> and since <code>range(...)</code> already returns a generator you can simply pass it to a list constructor and work with it.</p>\n\n<p>You should also have a look at the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> (PEP8) and follow it's recommendations regarding <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"noreferrer\">whitespace within expressions and statements</a>.</p>\n\n<p>If you intend to supply your testing code together with your function in a single script, wrap it in the well known <code>if __name__ == \"__main__\":</code> construct to ensure it is only run if your code is used as a script.</p>\n\n<hr>\n\n<p><sup>*</sup> Well not strictly speaking, but it's close.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:22:30.063",
"Id": "425152",
"Score": "0",
"body": "Could you also give feedback about the performance of this implementation? And, also, did you run the tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:32:02.930",
"Id": "425159",
"Score": "0",
"body": "I mention your tests directly above the first code block. The first case took about 36s on average and was the base for all further testing. The second one didn't finish because my 16GB of RAM (or maybe rather 13GB of it) don't seem to be sufficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T07:41:22.237",
"Id": "425170",
"Score": "0",
"body": "oh, sorry I didn't see the line, thank you for testing it. But it seems on average I bet the record of using set implementation given here: https://idlecoding.com/making-eratosthenes-go-faster-1/ , and also with your idea of using jit, it surpasses it waaaay past. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T16:12:18.010",
"Id": "425520",
"Score": "0",
"body": "`@jit` doesn't work in class methods, right? There seems to be `@jitclass` but, that seems to be in development."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:37:05.910",
"Id": "425528",
"Score": "0",
"body": "This not really suited to be answered in a comment, but [this SO post](https://stackoverflow.com/a/52722636) might help."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:08:20.213",
"Id": "220007",
"ParentId": "219998",
"Score": "8"
}
},
{
"body": "<p>AlexV has made some great points. I’ll try not to duplicate them.</p>\n\n<pre><code>while numbers[current_prime] <= sqrt_limit:\n</code></pre>\n\n<p>This seems like odd code. <code>numbers[x] == x</code> is true, or <code>numbers[x] == -1</code> is true. You should save the indirect lookup in the <code>numbers</code> array, and just loop:</p>\n\n<pre><code>while current_prime <= sqrt_limit:\n</code></pre>\n\n<p>You take great pains to explain in a comment that <code>len(numbers) == n+1</code>, but then you evaluate <code>len(numbers)-1</code> anyway. It is just <code>n</code>. So you could simply write:</p>\n\n<pre><code>for i in range(current_prime, n // current_prime + 1):\n numbers[current_prime * i] = -1\n</code></pre>\n\n<p>Now, <code>i</code> starts at <code>current_prime</code>, and goes up to the last multiplier that results in <code>current_prime * i</code> still being within the bounds of the <code>numbers</code> list. You could simply use the <code>range()</code> method to count by multiples of <code>current_prime</code>, and let it figure out when it has gone beyond the limit for you:</p>\n\n<pre><code>for index in range(current_prime*current_prime, n+1, current_prime):\n numbers[index] = -1\n</code></pre>\n\n<p>Your summary loop at the end is not Pythonic:</p>\n\n<pre><code>for i in range(len(numbers)):\n # code which only uses numbers[i], never i on its own.\n</code></pre>\n\n<p>Instead of looping over the indices of the <code>numbers</code> list, you simply want to loop over the values of the list.</p>\n\n<pre><code>j = 0\nfor value in numbers:\n if value > 0:\n numbers[j] = value\n j += 1\n</code></pre>\n\n<p>But this loop is simply filtering values from one list into another list (although you are reusing the original list to store the new list). Python excels at filtering lists, using list comprehension. The above code can be written simply as:</p>\n\n<pre><code>numbers = [ value for value in numbers if value > 0 ]\n</code></pre>\n\n<p>Which you could then follow by:</p>\n\n<pre><code>return numbers[1:]\n</code></pre>\n\n<p>to trim off the first value of the list.</p>\n\n<hr>\n\n<p>There are a number of things which you can do to further improve the performance. The easiest would be to special case “2” as prime, and then start at 3 and count by 2’s to skip over the even numbers. When clearing out multiples of <code>prime_number</code>, you would again skip the even multiples by incrementing the index by <code>2*prime_number</code>, approximately doubling the speed of the algorithm by cutting the work in half.</p>\n\n<hr>\n\n<h1>Memory</h1>\n\n<p>Python is a great scripting language, but that ease of use comes with a cost. Everything is an object, and the Python environment manages the object allocation for you. This results in a lot of memory usage per object. With a few thousand objects, that isn't a problem. With hundreds of millions, that overhead starts to have a serious impact.</p>\n\n<pre><code>>>> sys.getsizeof(0)\n24\n>>> sys.getsizeof(1)\n28\n>>> sys.getsizeof(0x3fffffff)\n28\n>>> sys.getsizeof(0x40000000)\n32\n</code></pre>\n\n<p>Positive integers between 1 and 1.07 billion take up 28 bytes each. If you have a list of the first billion integers, you're going to need 28 GB of memory for those integers. Plus ...</p>\n\n<pre><code>>>> sys.getsizeof([])\n64\n>>> sys.getsizeof([0])\n72\n>>> sys.getsizeof([0,1])\n80\n>>> sys.getsizeof([0,1,2])\n88\n</code></pre>\n\n<p>... a list takes 64 bytes, plus 8 per object in the list. So the list of a billion entries is going to take an addition 8 GB of memory, for a total of 36 GB!</p>\n\n<p>Instead of storing integer objects in a list, we can be way more efficient if we ask Python to store integers directly in an <a href=\"https://docs.python.org/3/library/array.html\" rel=\"nofollow noreferrer\">array</a>.</p>\n\n<pre><code>>>> import array\n>>> a = array.array('L', [0]*1000000000)\n>>> sys.getsizeof(a)\n4000000064\n</code></pre>\n\n<p><code>a</code> is an array of 4-byte unsigned integers. And it only requires a mere 4 GB of memory.</p>\n\n<p>As pointed out by @Graipher, you don't need to store the integers in the array for the sieve; you can simply store boolean flags. The <code>array.array</code> object is designed for numbers, not booleans, but we can store <code>True</code> and <code>False</code> as a <code>1</code> and a <code>0</code>, in which case we only need 1 byte integers, so we can reduce the memory requirements down to 1 GB.</p>\n\n<pre><code>>>> a = array.array('B', [0, 1]*500000000)\n>>> a[0:10]\narray('B', [0, 1, 0, 1, 0, 1, 0, 1, 0, 1])\n>>> sys.getsizeof(a)\n1000000064\n</code></pre>\n\n<p>Instead of filling in the memory with a billion 0's, I've initialized all the odd elements to <code>1</code>, for possibly prime, and <code>0</code> for the even elements, for not possibly prime. We just need a minor correction, so <code>a[1]</code> is flagged as not prime, and <code>a[2]</code> is prime.</p>\n\n<p><code>array.array</code> is overly complex for this issue; it has to do calculation based on the size of the elements. Since we are storing individual flags in bytes, a <code>bytearray</code> should be faster:</p>\n\n<pre><code>>>> a = bytearray(1000000000)\n>>> a[1::2] = [1]*500000000 # Mark odd numbers as possible prime\n>>> a[1:3] = [0, 1] # Mark 1 as not prime, 2 as prime\n>>> list(a[0:20])\n[0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]\n>>> sys.getsizeof(a)\n1000000057\n</code></pre>\n\n<p>Now you can proceed with your sieve, testing only odd numbers, and marking as not prime only the odd multiples of a prime number, start with its square, up to the end of the sieve:</p>\n\n<pre><code>for i in range(3, int(sqrt(1000000000)), 2):\n if a[i]:\n a[i*i::2*i] = bytes(len(a[i*i::2*i]))\n</code></pre>\n\n<p>How many primes do you have? Just add up all of the <code>1</code> flags!</p>\n\n<pre><code>n = sum(a)\n</code></pre>\n\n<p>Where are you going to store these? How about in an <code>array</code> object, for efficiency? Since the prime number will go up to 1 billion, we'll again need 4-byte integer storage.</p>\n\n<pre><code>primes = array.array('L', (i for i, flag in enumerate(a) if flag))\n</code></pre>\n\n<hr>\n\n<pre><code>import array, math, time\n\n#n = 100\n#n = 1000000\n#n = 100000000\nn = 1000000000\n\nstart = time.perf_counter()\na = bytearray(n)\na[1::2] = [1]*len(a[1::2])\na[1:3] = [0, 1]\n\nfor i in range(3, int(math.sqrt(n)), 2):\n if a[i]:\n a[i*i::2*i] = bytes(len(a[i*i::2*i]))\n\nprimes = array.array('L', (i for i, flag in enumerate(a) if flag))\n\nend = time.perf_counter()\nmins, secs = divmod(end - start, 60)\n\ncount = len(primes)\nprint(f\"Found {count} primes below {n} in {int(mins)}m:{secs:06.3f}s\")\nif count < 30:\n print(primes)\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>Found 78498 primes below 1000000 in 0m:00.071s\nFound 5761455 primes below 100000000 in 0m:06.623s\nFound 50847534 primes below 1000000000 in 1m:09.585s\n</code></pre>\n\n<p>If our machine speeds are comparable, this sample point would fall between the eratos_sieve_jit (orange) and prime_sieve2_ (red) in @Graipher's plot.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:23:31.290",
"Id": "220033",
"ParentId": "219998",
"Score": "5"
}
},
{
"body": "<p>At the <a href=\"https://codereview.stackexchange.com/a/220033/98493\">end of their answer</a>, <a href=\"https://codereview.stackexchange.com/users/100620/ajneufeld\">@AJNeufeld</a> has the right idea to improve the algorithm even further (in pure Python). You want to minimize the amount of numbers you have to mark off as being composite for every new prime you find. In order to do this, you can actually start at <code>current_prime * current_prime</code>, since you should already have marked up all smaller multiples of <code>current_prime</code> when you found all primes smaller than <code>current_prime</code>.</p>\n\n<p>In addition I would use a slightly different data structure. Instead of having a list of all numbers up to limit, just have a list of <code>True</code>/<code>False</code>, indicating whether or not the number is (potentially) prime. You can immediately mark off 0 and 1 as not prime (by the usual definition) and then just need to proceed to the next <code>True</code> in the array, the index of which is the next prime number. Then mark off all multiples off that prime number as composite (<code>False</code>).</p>\n\n<pre><code>def prime_sieve(limit):\n prime = [True] * limit\n prime[0] = prime[1] = False\n\n for i, is_prime in enumerate(prime):\n if is_prime:\n yield i\n for n in range(i * i, limit, i):\n prime[n] = False\n</code></pre>\n\n<p>This function is a generator. You can just iterate over it to get one prime number at a time, or consume the whole generator using <code>list(prime_sieve(1000))</code>.</p>\n\n<p>Using a <code>for</code> loop to mark off composites can be improved further using slicing:</p>\n\n<pre><code>prime[i*i:limit:i] = [False] * len(range(i*i, limit, i))\n</code></pre>\n\n<p>This uses the fact that the <code>range</code> object in Python 3 is a generator-like object which has a quick calculation of <code>len</code> implemented.</p>\n\n<p>As for timings, here are a few. In the end, compiling it with <code>numba</code> is usually going to win, but you can get a factor of two just by making the algorithm a bit easier. And this factor of two carries through when jitting this answer as well.</p>\n\n<p><a href=\"https://i.stack.imgur.com/XKvlC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XKvlC.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T16:24:27.673",
"Id": "425211",
"Score": "0",
"body": "thats a great comparison chart. Thanks! :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:03:55.377",
"Id": "425767",
"Score": "0",
"body": "I've been thinking about the generator function above, even we do cut down the memory cost, It still builds a large prime[limit] list right? If we take a number say n in the order of $10^30$, this would mean infeasible memory capacity requirement, but without having to build a list, how can we generate primes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:16:17.970",
"Id": "425769",
"Score": "2",
"body": "@mathmaniage Yes, it would. Apparantly you can get the space requirements down to `O(sqrt(n))` with algorithms more clever than this, though: https://stackoverflow.com/a/10733621/4042267 (and the other answers to that question). If you want `O(1)` space requirements, you are probably stuck with explicitly checking all relevant divisors for each number, which is quite a lot slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:30:01.860",
"Id": "425771",
"Score": "0",
"body": "even O(sqrt(n)) is a pain for n in order of 30, but, we only store boolean in the list, and if there was a way to use just one bit for this indication that'd do the trick, but a boolean in python is 28 bytes, is there a way we can store just one bit ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:36:06.130",
"Id": "425773",
"Score": "1",
"body": "@mathmaniage Apparently yes, not sure how practical it is going to be, though: https://stackoverflow.com/questions/5602155/numpy-boolean-array-with-1-bit-entries The accepted answer won't directly work, though, since here we do need to modify the contents of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:53:48.087",
"Id": "425776",
"Score": "0",
"body": "yeah, turns out it'd require 3500000GB of storage, but, seems in practical one would just generate and use tests to determine primality. Had I known that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T22:51:45.483",
"Id": "425922",
"Score": "1",
"body": "I think your 3500000GB of memory is overstating the requirements by quite a bit. I've added memory usage analysis to my [review](https://codereview.stackexchange.com/a/220033/100620)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T02:50:40.263",
"Id": "425930",
"Score": "0",
"body": "@mathmaniage True, a Boolean is 28 bytes. But you only need 56 bytes for all possible Boolean values (28 for `True`, 28 for `False`). If you have a list of a million booleans, that becomes a list of a million pointers to either of those two values ... so effectively only 8 bytes per boolean, not 28."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T04:37:14.837",
"Id": "425933",
"Score": "0",
"body": "@AJNeufeld, hm... that'd be true, but that still means extremely large amount of memory required. In cryptography, we could use a number in the order of 10^30 but, sieve cannot be used for such then(?)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T10:58:31.610",
"Id": "220048",
"ParentId": "219998",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "220007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T15:53:08.900",
"Id": "219998",
"Score": "9",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"sieve-of-eratosthenes"
],
"Title": "Implementing Sieve of Eratosthenes faster"
} | 219998 |
<p>I attached below a small working example of a function that is able to perform <code>x^y</code>. As it is possible to see the base (x) takes <code>double</code> and the power takes an <code>int</code>. As last the <code>main</code> loop will also round up or down the result accordingly. </p>
<p>Not always I have these type of formats, and I could have base as <code>int</code> and power as <code>double</code> or base as <code>long int</code> and power as additional type. How can I improve this function to make it more general with different type format using template <code>template <class identifier></code> or/and <code>template <typename identifier></code>? </p>
<pre><code>#include <cmath>
using namespace std;
class Power {
public:
double raiseToPower(double x, int power)
{
double result;
int i;
result = 1.0;
for(i = 1; i <=power; i++){
result = result*x;
}
return result;
}
double floor0(double num)
{
if( (num + 0.5) >= (int(num) + 1) )
return int(num)+1;
else
return int(num);
}
};
int main()
{
double x;
int i;
Power example;
std::cout<<"please enter the number"<<std::endl;
std::cin>>x;
std::cout<<"please enter the integer power that you want this number raised to"<<std::endl;
std::cin>>i;
std::cout<<"rise to power "<<i<<" is equal to "<<example.raiseToPower(x,i)<<std::endl;
std::cout<<"the result rounded is "<< example.floor0(example.raiseToPower(x,i))<<std::endl;
}
</code></pre>
<p>Thank for any insight and point to the right direction.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:30:34.040",
"Id": "425082",
"Score": "0",
"body": "Is something wrong with [`std::pow`](https://en.cppreference.com/w/cpp/numeric/math/pow) though?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:37:54.623",
"Id": "425086",
"Score": "0",
"body": "@Juho, thank for reading my question, there is nothing wrong with `std::pow` but I would like to have another way of expressing this type of function or future functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:38:54.587",
"Id": "425127",
"Score": "0",
"body": "The logic you have for raiseToPower currently will only work for positive integer exponents. So before you can meaningfully support other types as exponents, you need to expand that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:21:17.453",
"Id": "425130",
"Score": "0",
"body": "@Errorsatz, thanks for your comment and for reading the question, how could I modify the function and make it better then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T09:01:45.310",
"Id": "425178",
"Score": "0",
"body": "Are you from Java? Your functions make more sense being free functions in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T13:41:41.203",
"Id": "425197",
"Score": "0",
"body": "@L.F., thank for your comment and for reading the question. No I am from C++ I was wondering how to make that function better using template function for my future reference"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T22:55:47.837",
"Id": "425230",
"Score": "0",
"body": "For fractional exponents, https://stackoverflow.com/questions/3606734/calculate-fractional-exponent-in-for-loop-without-power-function might be what you're looking for."
}
] | [
{
"body": "<h1>Headers and namespaces</h1>\n\n<p>Don't <code>using namespace</code>, especially a big and growing namespace like <code>std</code> that's not designed for it.</p>\n\n<p>There's no need to include <code><cmath></code>. On the other hand, there is a clear need for <code><iostream></code>, which has been omitted.</p>\n\n<h1>Structure</h1>\n\n<p>There's no need for the <code>Power</code> class; it maintains no state. The functions should simply be free functions, perhaps in a namespace.</p>\n\n<h1>Consider full range of types</h1>\n\n<p><code>raiseToPower()</code> only works with non-negative exponents; it should either accept an unsigned type or be modified to work correctly with negative inputs. Perhaps like this:</p>\n\n<pre><code> if (power < 0) {\n return raiseToPower(1/x, -power);\n }\n</code></pre>\n\n<h1>Improve the algorithm</h1>\n\n<p>For large <code>power</code>, the loop is executed many times. We can use <em>binary exponentation</em> to reduce that to <code>log₂ power</code> iterations of the loop.</p>\n\n<h1>Avoid over-complication</h1>\n\n<p><code>floor0()</code> doesn't need that <code>if</code>/<code>else</code>; simply add 0.5 <em>before</em> truncating:</p>\n\n<pre><code>constexpr double floor0(double num)\n{\n return int(num + 0.5);\n}\n</code></pre>\n\n<p>It might be better to use <code>long</code> or <code>long long</code> there; in any case, you'll still suffer bugs when the value is too big for the integer type. <code>std::floor()</code> doesn't have that problem.</p>\n\n<h1>Validate inputs</h1>\n\n<p>If I enter a non-number, I don't get a clear error message. Instead, the program uses uninitialised values, which is Undefined Behaviour. Don't do that; instead check that <code>std::cin</code> is still good before using <code>x</code> or <code>i</code>.</p>\n\n<h1>Avoid <code>std::endl</code> unless you need output flushing</h1>\n\n<p>None of the uses of <code>std::endl</code> here are necessary, and we can use <code>\\n</code> instead. (Remember that using <code>std::cin</code> flushes the output streams, and returning from <code>main()</code> also flushes outputs).</p>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<pre><code>double raiseToPower(double x, int power)\n{\n if (power < 0) {\n return raiseToPower(1/x, -power);\n }\n\n double result = 1.0;\n double m = x;\n\n for (; power; power /= 2) {\n if (power % 2) {\n result *= m;\n }\n m *= m;\n }\n return result;\n}\n\nconstexpr double floor0(double num)\n{\n return int(num + 0.5);\n}\n</code></pre>\n\n \n\n<pre><code>#include <iostream>\n\nint main()\n{\n double x;\n int i;\n std::cout << \"Please enter the number\\n\";\n std::cin >> x;\n std::cout << \"Please enter the integer power that \"\n \"you want this number raised to\\n\";\n std::cin >> i;\n if (!std::cin) {\n std::cerr << \"Input format error\\n\";\n return 1;\n }\n auto const result = raiseToPower(x,i);\n std::cout << x << \" raised to power \" << i << \" is equal to \"\n << result << '\\n';\n std::cout << \"The result rounded is \"\n << floor0(result) << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T20:43:20.430",
"Id": "429108",
"Score": "0",
"body": "thank you very much for the very detailed and comprehensive explanation on how to improve the code! Exactly what I was looking for! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:28:59.407",
"Id": "221788",
"ParentId": "220001",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221788",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:26:29.120",
"Id": "220001",
"Score": "3",
"Tags": [
"c++",
"c++11",
"template"
],
"Title": "Elevation to power function using class templates"
} | 220001 |
<p>The code below compares recv.rcpt_dtim (which is a datetime type) against the current date/time. It calculates an elapsed time resulting in hours and minutes formatted like: "04:22". It took me a while to get it functional, which it is, but it just seems sloppy. Does anyone have any tips to clean it up?</p>
<pre><code>TRIM((((CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL SECOND(9) to
SECOND)/3600)::VARCHAR(12) || ':' || CASE WHEN (MOD(MOD(((CURRENT YEAR TO
MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9) to
MINUTE)::VARCHAR(12)::INT,60),60))<10 THEN "0" ELSE "" END ||
(MOD(MOD(((CURRENT YEAR TO MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9)
to MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T22:52:31.670",
"Id": "425135",
"Score": "0",
"body": "Question asked on [Stack Overflow](https://stackoverflow.com/questions/56064149/how-to-clean-up-sql-expression) too. Essentially the same answer, but less verbose, was given on SO by A.N.Other user than me."
}
] | [
{
"body": "<p>When I use your complex expression, I don't get the leading zeros on the hour field that your code suggests that you want. AFAICS, the expression that tries to add a leading zero is fiddling with the minutes field. I'm not sure why you're doing the double MOD operations, either.</p>\n\n<p>I think it is sufficient to use the vastly simpler <code>CAST</code> expression shown in the following SELECT statement. Here, instead of using <code>CURRENT YEAR TO SECOND</code> (or minor variants thereupon), I've created a second table, <code>reference_times</code>, with a single column <code>reftime</code> of type <code>DATETIME YEAR TO SECOND</code>. That allows me to test many different reference times reliably, in a way that using CURRENT simple does not. I use an explicit CROSS JOIN between the reference times and the <code>recv</code> table to compare every row in each table with each of the rows in the other.</p>\n\n<pre><code>SELECT reft.reftime,\n recv.rcpt_dtim,\n (reft.reftime - recv.rcpt_dtim) AS delta_t_1,\n CAST(reft.reftime - recv.rcpt_dtim AS INTERVAL HOUR(4) TO MINUTE) AS delta_t_2,\n TRIM((((reft.reftime - recv.rcpt_dtim)::INTERVAL SECOND(9) TO SECOND)/3600)::VARCHAR(12) ||\n ':' ||\n CASE WHEN (MOD(MOD(((reft.reftime - recv.rcpt_dtim)::INTERVAL MINUTE(9) TO MINUTE)::VARCHAR(12)::INT,60),60))<10\n THEN \"0\"\n ELSE \"\" END || \n (MOD(MOD(((reft.reftime - recv.rcpt_dtim)::INTERVAL MINUTE(9) TO MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12)) AS delta_t_3\n FROM reference_times AS reft JOIN recv ON 1 = 1\n ORDER BY reft.reftime, recv.rcpt_dtim;\n</code></pre>\n\n<p>Given the setup code:</p>\n\n<pre><code>CREATE TEMP TABLE reference_times\n(\n reftime DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY\n);\nINSERT INTO reference_times VALUES('2019-05-01 03:01:03');\nINSERT INTO reference_times VALUES('2019-05-01 05:32:27');\nINSERT INTO reference_times VALUES('2019-05-01 10:22:44');\nINSERT INTO reference_times VALUES('2019-05-01 12:49:00');\nINSERT INTO reference_times VALUES('2019-05-01 14:59:59');\nINSERT INTO reference_times VALUES('2019-05-01 23:59:58');\n\nCREATE TEMP TABLE recv\n(\n rcpt_dtim DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY\n);\nINSERT INTO recv VALUES('2019-05-01 01:10:11');\nINSERT INTO recv VALUES('2019-05-01 02:00:00');\nINSERT INTO recv VALUES('2019-04-30 22:19:45');\nINSERT INTO recv VALUES('2019-04-30 18:37:21');\nINSERT INTO recv VALUES('2019-04-30 03:31:00');\nINSERT INTO recv VALUES('2019-04-30 01:19:45');\nINSERT INTO recv VALUES('2019-04-30 00:00:00');\nINSERT INTO recv VALUES('2019-04-29 20:10:58');\nINSERT INTO recv VALUES('2019-04-10 22:09:00');\nINSERT INTO recv VALUES('2019-04-01 22:09:00');\n</code></pre>\n\n<p>I get output such as:</p>\n\n<pre><code>reftime rcpt_dtim delta_t_1 delta_t_2 delta_t_3\n2019-05-01 03:01:03 2019-04-01 22:09:00 29 04:52:03 700:52 700:52\n2019-05-01 03:01:03 2019-04-10 22:09:00 20 04:52:03 484:52 484:52\n2019-05-01 03:01:03 2019-04-29 20:10:58 1 06:50:05 30:50 30:50\n2019-05-01 03:01:03 2019-04-30 00:00:00 1 03:01:03 27:01 27:01\n2019-05-01 03:01:03 2019-04-30 01:19:45 1 01:41:18 25:41 25:41\n2019-05-01 03:01:03 2019-04-30 03:31:00 0 23:30:03 23:30 23:30\n2019-05-01 03:01:03 2019-04-30 18:37:21 0 08:23:42 8:23 8:23\n2019-05-01 03:01:03 2019-04-30 22:19:45 0 04:41:18 4:41 4:41\n2019-05-01 03:01:03 2019-05-01 01:10:11 0 01:50:52 1:50 1:50\n2019-05-01 03:01:03 2019-05-01 02:00:00 0 01:01:03 1:01 1:01\n2019-05-01 05:32:27 2019-04-01 22:09:00 29 07:23:27 703:23 703:23\n2019-05-01 05:32:27 2019-04-10 22:09:00 20 07:23:27 487:23 487:23\n2019-05-01 05:32:27 2019-04-29 20:10:58 1 09:21:29 33:21 33:21\n2019-05-01 05:32:27 2019-04-30 00:00:00 1 05:32:27 29:32 29:32\n2019-05-01 05:32:27 2019-04-30 01:19:45 1 04:12:42 28:12 28:12\n2019-05-01 05:32:27 2019-04-30 03:31:00 1 02:01:27 26:01 26:01\n2019-05-01 05:32:27 2019-04-30 18:37:21 0 10:55:06 10:55 10:55\n2019-05-01 05:32:27 2019-04-30 22:19:45 0 07:12:42 7:12 7:12\n2019-05-01 05:32:27 2019-05-01 01:10:11 0 04:22:16 4:22 4:22\n2019-05-01 05:32:27 2019-05-01 02:00:00 0 03:32:27 3:32 3:32\n2019-05-01 10:22:44 2019-04-01 22:09:00 29 12:13:44 708:13 708:13\n2019-05-01 10:22:44 2019-04-10 22:09:00 20 12:13:44 492:13 492:13\n2019-05-01 10:22:44 2019-04-29 20:10:58 1 14:11:46 38:11 38:11\n2019-05-01 10:22:44 2019-04-30 00:00:00 1 10:22:44 34:22 34:22\n2019-05-01 10:22:44 2019-04-30 01:19:45 1 09:02:59 33:02 33:02\n2019-05-01 10:22:44 2019-04-30 03:31:00 1 06:51:44 30:51 30:51\n2019-05-01 10:22:44 2019-04-30 18:37:21 0 15:45:23 15:45 15:45\n2019-05-01 10:22:44 2019-04-30 22:19:45 0 12:02:59 12:02 12:02\n2019-05-01 10:22:44 2019-05-01 01:10:11 0 09:12:33 9:12 9:12\n2019-05-01 10:22:44 2019-05-01 02:00:00 0 08:22:44 8:22 8:22\n2019-05-01 12:49:00 2019-04-01 22:09:00 29 14:40:00 710:40 710:40\n2019-05-01 12:49:00 2019-04-10 22:09:00 20 14:40:00 494:40 494:40\n2019-05-01 12:49:00 2019-04-29 20:10:58 1 16:38:02 40:38 40:38\n2019-05-01 12:49:00 2019-04-30 00:00:00 1 12:49:00 36:49 36:49\n2019-05-01 12:49:00 2019-04-30 01:19:45 1 11:29:15 35:29 35:29\n2019-05-01 12:49:00 2019-04-30 03:31:00 1 09:18:00 33:18 33:18\n2019-05-01 12:49:00 2019-04-30 18:37:21 0 18:11:39 18:11 18:11\n2019-05-01 12:49:00 2019-04-30 22:19:45 0 14:29:15 14:29 14:29\n2019-05-01 12:49:00 2019-05-01 01:10:11 0 11:38:49 11:38 11:38\n2019-05-01 12:49:00 2019-05-01 02:00:00 0 10:49:00 10:49 10:49\n2019-05-01 14:59:59 2019-04-01 22:09:00 29 16:50:59 712:50 712:50\n2019-05-01 14:59:59 2019-04-10 22:09:00 20 16:50:59 496:50 496:50\n2019-05-01 14:59:59 2019-04-29 20:10:58 1 18:49:01 42:49 42:49\n2019-05-01 14:59:59 2019-04-30 00:00:00 1 14:59:59 38:59 38:59\n2019-05-01 14:59:59 2019-04-30 01:19:45 1 13:40:14 37:40 37:40\n2019-05-01 14:59:59 2019-04-30 03:31:00 1 11:28:59 35:28 35:28\n2019-05-01 14:59:59 2019-04-30 18:37:21 0 20:22:38 20:22 20:22\n2019-05-01 14:59:59 2019-04-30 22:19:45 0 16:40:14 16:40 16:40\n2019-05-01 14:59:59 2019-05-01 01:10:11 0 13:49:48 13:49 13:49\n2019-05-01 14:59:59 2019-05-01 02:00:00 0 12:59:59 12:59 12:59\n2019-05-01 23:59:58 2019-04-01 22:09:00 30 01:50:58 721:50 721:50\n2019-05-01 23:59:58 2019-04-10 22:09:00 21 01:50:58 505:50 505:50\n2019-05-01 23:59:58 2019-04-29 20:10:58 2 03:49:00 51:49 51:49\n2019-05-01 23:59:58 2019-04-30 00:00:00 1 23:59:58 47:59 47:59\n2019-05-01 23:59:58 2019-04-30 01:19:45 1 22:40:13 46:40 46:40\n2019-05-01 23:59:58 2019-04-30 03:31:00 1 20:28:58 44:28 44:28\n2019-05-01 23:59:58 2019-04-30 18:37:21 1 05:22:37 29:22 29:22\n2019-05-01 23:59:58 2019-04-30 22:19:45 1 01:40:13 25:40 25:40\n2019-05-01 23:59:58 2019-05-01 01:10:11 0 22:49:47 22:49 22:49\n2019-05-01 23:59:58 2019-05-01 02:00:00 0 21:59:58 21:59 21:59\n</code></pre>\n\n<p>Column names/types:</p>\n\n<pre><code>reftime DATETIME YEAR TO SECOND\nrcpt_dtim DATETIME YEAR TO SECOND\ndelta_t_1 INTERVAL DAY(8) TO SECOND\ndelta_t_2 INTERVAL HOUR(4) TO MINUTE\ndelta_t_3 VARCHAR(26)\n</code></pre>\n\n<p>Observe that the <code>delta_t_2</code> column produces the same output as the <code>delta_t_3</code> column — apart from type (interval vs string); the left vs right adjustment is mostly an artefact of the way the program that generated the data futzes with the formatting.</p>\n\n<p>Consequently, your elaborate expression can be simplified to:</p>\n\n<pre><code>CAST(CURRENT YEAR TO SECOND - recv.rcpt_dtim AS INTERVAL HOUR(4) TO MINUTE)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>(CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL HOUR(4) TO MINUTE\n</code></pre>\n\n<p>And if your time gaps are small enough, you can change the <code>4</code> to <code>2</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T22:48:24.250",
"Id": "220018",
"ParentId": "220003",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T16:57:15.450",
"Id": "220003",
"Score": "4",
"Tags": [
"sql",
"datetime",
"formatting",
"informix"
],
"Title": "Calculating elapsed time"
} | 220003 |
<p>I'm trying to write billions of strings lines to a file, it works for up to 40 million lines, but it's throwing out "java.nio.BufferOverflowException" error for 400 million lines. I also think my solution is slow as it takes 45 seconds to write 40 million lines. Below is the code.</p>
<pre><code>public static void main(String[] args) throws FileNotFoundException, IOException {
byte[] buffer = "Help I am trapped in a fortune cookie factory\n".getBytes();
int number_of_lines = 400000000;
FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel();
ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length * number_of_lines);
for (int i = 0; i < number_of_lines; i++) {
wrBuf.put(buffer);
}
rwChannel.close();
}
</code></pre>
<p>How can I make it be faster if possible and also write more than 2 billion lines of string?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:41:09.787",
"Id": "425118",
"Score": "2",
"body": "40M lines * 46 chars = 1.7GB, but 400M lines = 17 GB, and `size` \"must be non-negative and no greater than `Integer.MAX_VALUE`\". Do you specifically want memory-mapped I/O, or could you just use `RandomAccessFile.write`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:56:47.147",
"Id": "425120",
"Score": "0",
"body": "@Anonymous I just want to write 2 billion lines of string to a file very fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:01:17.577",
"Id": "425123",
"Score": "0",
"body": "For *very fast*, can you do it in larger chunks than 46 bytes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:04:33.130",
"Id": "425124",
"Score": "0",
"body": "How to go about it, please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:44:11.330",
"Id": "425134",
"Score": "0",
"body": "You have indicated this is a programming-challenge, could you put the text of the challenge and a link to the challenge in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T23:05:21.883",
"Id": "425136",
"Score": "2",
"body": "Can you assemble a buffer that contains many lines, and then write that buffer all at once? This may be faster than writing one line at a time. But this is off-topic for codereview. Try [a StackOverflow question on this subject](https://stackoverflow.com/questions/1062113/fastest-way-to-write-huge-data-in-text-file-java). ...why is your code nearly identical to one of the answers there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:13:25.223",
"Id": "425150",
"Score": "0",
"body": "_\"45 seconds to write 40 million lines\"_ That seems pretty fast. Have you tried increasing the heap size? e.g `-Xms<size>`"
}
] | [
{
"body": "<p>It sure sounds like you're running out of memory as you try to build (or allocate) the buffer. </p>\n\n<ul>\n<li>You need to figure out how big a buffer you can (or want to) use. You'll need to ask the system how much RAM it has, and how much is available, and make your buffer that large.</li>\n<li>You might get a small boost by opening the file as explicitly write-only.</li>\n<li>You'll need to flush the buffer as you go. Something shaped like this psudo-code might work:</li>\n</ul>\n\n<pre><code>free = system.free_ram();\nuse = hungry * free;\nbuffer = new bytes_buffer_to_file(\"filename\", size=use);\ntry{\n current_buffer = 0;\n while(line = get_bytes_needing_to_be_written()){\n if(current_buffer + line.length > use){\n buffer.flush();\n current_buffer = 0;\n }\n buffer.append(line);\n current_buffer += line.length;\n }\n}\nfinally{\n buffer.flush();\n buffer.destroy();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:38:38.473",
"Id": "425126",
"Score": "0",
"body": "I don't really understand your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:33:23.033",
"Id": "425133",
"Score": "0",
"body": "If this was written in C or C++ the file block size would also be important here as well as the disc cache size. The speed can be running into hardware limitations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:15:08.693",
"Id": "220009",
"ParentId": "220008",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T19:11:30.347",
"Id": "220008",
"Score": "1",
"Tags": [
"java",
"performance",
"programming-challenge",
"file",
"file-system"
],
"Title": "Writing billions of lines to text file in java"
} | 220008 |
<p>I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.</p>
<p>Example: </p>
<p><strong>Input String</strong>: The quick brown fox jumped over the fence, <strong>K</strong>: 11</p>
<p><strong>Output</strong>: The quick</p>
<p>Here is what I have tried:</p>
<pre><code> function crop(message, K) {
var originalLen = message.length;
if(originalLen<K)
{
return message;
}
else
{
var words = message.split(' '),substr;
for(var i=words.length;i > 0;i--)
{
words.pop();
if(words.join(' ').length<=K)
{
return words.join(' ');
}
}
}
}
</code></pre>
<p>This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work? </p>
| [] | [
{
"body": "<p>This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if <code>words</code> contains a whole book and <code>K</code> is some small number.</p>\n\n<p>In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.</p>\n\n<p>A regular expression is an efficient and compact way to find text that meets your criteria. Consider:</p>\n\n<pre><code>function crop(message, K) {\n if(K<1) return \"\";\n const reK = new RegExp( `^.{0,${K-1}}[^ ](?= |$)` );\n return ( message.match(reK) || [ \"\" ] )[0];\n}\n</code></pre>\n\n<p><code>.match</code> returns an array with the matched text as the first element, or <code>null</code> if no match. The alternative <code>[ \"\" ]</code> will provide an empty string as a return value if there is no match (when the first word is longer than <code>K</code>). </p>\n\n<p>The regular expression, broken down, means:</p>\n\n<ul>\n<li><code>^</code>: match start of string</li>\n<li><code>.</code>: followed by any character</li>\n<li><code>{0,10}</code>: ... up to ten times (one less than <code>K</code>)</li>\n<li><code>[^ ]</code>: followed by a character that is not a space</li>\n<li><code>(?=…)</code>: this is an assertion; it means the following expression must match, but is not included in the result:\n\n<ul>\n<li><code></code>: followed by a space</li>\n<li><code>|</code>: or</li>\n<li><code>$</code>: end-of-string</li>\n</ul></li>\n</ul>\n\n<p><strong>Exercise</strong>: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:07:58.300",
"Id": "425148",
"Score": "0",
"body": "Why do you have `[^ ]`? When thinking of what the answer would be I got `/^.{1,11}(?=\\s)/` yours is better as it check for `$` too. But I can't understand the addition of `[^ ]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:41:31.450",
"Id": "425153",
"Score": "1",
"body": "`/^.{1,11}(?=\\s)/` will include a trailing space in the match if there are two spaces together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:44:07.343",
"Id": "425154",
"Score": "0",
"body": "Ah, that makes sense. Thank you :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:16:08.620",
"Id": "220015",
"ParentId": "220011",
"Score": "12"
}
},
{
"body": "<p>Your code looks great.</p>\n\n<blockquote>\n <p><a href=\"https://codereview.stackexchange.com/users/131732/oh-my-goodness\">Oh My Goodness</a>'s solution is really great. </p>\n</blockquote>\n\n<hr>\n\n<p>If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in <a href=\"https://regex101.com/r/tSjyyG/1\" rel=\"noreferrer\">this link</a>, but it might give you an idea, how you may do so: </p>\n\n<pre><code>([A-z0-9\\s]{1,11})(\\s)(.*)\n</code></pre>\n\n<p>This expression is relaxed from the right and has three capturing groups with just a list of chars that I have just added in the first capturing group and I'm sure you might want to change that list. </p>\n\n<p>You may also want to add or reduce the boundaries. </p>\n\n<p><a href=\"https://i.stack.imgur.com/QHLI0.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QHLI0.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Graph</h3>\n\n<p>This graph shows how the expression would work and you can visualize other expressions in this <a href=\"https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24\" rel=\"noreferrer\">link</a>: </p>\n\n<p><a href=\"https://i.stack.imgur.com/Og67Q.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Og67Q.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Performance Test</h3>\n\n<p>This JavaScript snippet shows the performance of that expression using a simple 1-million times <code>for</code> loop.</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 repeat = 1000000;\nconst start = Date.now();\n\nfor (var i = repeat; i >= 0; i--) {\n const string = 'The quick brown fox jumped over the fence';\n const regex = /([A-z0-9\\s]{1,11})(\\s)(.*)/gm;\n var match = string.replace(regex, \"$1\");\n}\n\nconst end = Date.now() - start;\nconsole.log(\"YAAAY! \\\"\" + match + \"\\\" is a match \");\nconsole.log(end / 1000 + \" is the runtime of \" + repeat + \" times benchmark test. \");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Testing Code</h3>\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 regex = /([A-z0-9\\s]{1,11})(\\s)(.*)/s;\nconst str = `The quick brown fox jumped over the fence`;\nconst subst = `$1`;\n\n// The substituted value will be contained in the result variable\nconst result = str.replace(regex, subst);\n\nconsole.log('Substitution result: ', result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T01:59:59.280",
"Id": "425146",
"Score": "1",
"body": "FWIW I found `(/^.{1,11}(?=\\s)/gm).exec(string)[0]` to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:10:37.707",
"Id": "425149",
"Score": "1",
"body": "I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T22:49:51.340",
"Id": "220019",
"ParentId": "220011",
"Score": "7"
}
},
{
"body": "<h2>A Code Review</h2>\n<p>Your code is a mess,</p>\n<ul>\n<li>Inconsistent indenting.</li>\n<li>Poor use of space between tokens, and operators.</li>\n<li>Inappropriate use of variable declaration type <code>let</code>, <code>var</code>, <code>const</code>.</li>\n<li>Contains irrelevant / unused code. eg <code>substr</code></li>\n</ul>\n<h2>Fails to meet requirements.</h2>\n<p>You list the requirement</p>\n<blockquote>\n<p><em>"no trailing spaces in the end."</em></p>\n</blockquote>\n<p>Yet your code fails to do this in two ways</p>\n<p>When string is shorter than required length</p>\n<pre><code> crop("trailing spaces ", 100); // returns "trailing spaces "\n</code></pre>\n<p>When string contains 2 or more spaces near required length.</p>\n<pre><code> crop("Trailing spaces strings with extra spaces", 17); // returns "Trailing spaces "\n</code></pre>\n<p><strong>Note:</strong> There are various white space characters not just the space. There are also special unicode characters the are visually 1 character (depending on device OS) yet take up 2 or more characters. eg <code>"".length === 5</code> is <code>true</code>. All JavaScript strings are Unicode.</p>\n<h2>Rewrite</h2>\n<p>Using the same logic (build return string from array of split words) the following example attempts to correct the style and adherence to the requirements.</p>\n<p>I prefer 4 space indentation (using spaces not tabs as tabs always seem to stuff up when copying between systems) however 2 spaces is acceptable (only by popularity)</p>\n<p>I assume that the <code>message</code> was converted from ASCII and spaces are the only white spaces of concern.</p>\n<pre><code>function crop(message, maxLength) { // use meaningful names\n var result = message.trimEnd(); // Use var for function scoped variable\n if (result.length > maxLength) { // space between if ( > and ) {\n const words = result.split(" "); // use const for variables that do not change\n do {\n words.pop();\n result = words.join(" ").trimEnd(); // ensure no trailing spaces\n if (result.length <= maxLength) { // not repeating same join operation\n break;\n }\n } while (words.length);\n }\n return result;\n}\n</code></pre>\n<p><strong>Note:</strong> Check runtime has <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd\" rel=\"nofollow noreferrer\"><code>String.trimEnd</code></a> or use a polyfill or transpiler.</p>\n<h2>Update <span class=\"math-container\">\\$O(1)\\$</span> solution</h2>\n<p>I forgot to put in a better solution.</p>\n<p>Rebuilding the string is slow, or passing the string through a regExp requires iteration over the whole string.</p>\n<p>By looking at the character at the desired length you can workout if you need to move down to find the next space and then return the end trimmed sub string result, or just return the end Trimmed sub string.</p>\n<p>The result has a complexity of <span class=\"math-container\">\\$O(1)\\$</span> or in terms of <span class=\"math-container\">\\$n = K\\$</span> (maxLength) <span class=\"math-container\">\\$O(n)\\$</span></p>\n<pre><code>function crop(message, maxLength) {\n if (maxLength < 1) { return "" }\n if (message.length <= maxLength) { return message.trimEnd() }\n maxLength++;\n while (--maxLength && message[maxLength] !== " ");\n return message.substring(0, maxLength).trimEnd();\n}\n</code></pre>\n<p>It is significantly faster than any other solutions in this question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T12:58:30.923",
"Id": "425281",
"Score": "1",
"body": "regexp runtime is \\$O( K )\\$ too, just like your solution, and definitely does not iterate over the whole string. As to \"significantly faster\"—did your benchmark include the polyfill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T19:35:04.563",
"Id": "425303",
"Score": "1",
"body": "@AuxTaco Oh dear, my bad I managed to not submit a previous edit, fixed it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T00:54:54.090",
"Id": "220025",
"ParentId": "220011",
"Score": "4"
}
},
{
"body": "<p>A fairly simple alternative. Take the <code>maxLength</code> String plus one letter and cut it at the last space. If the <code>maxLength</code> was at the end of a word, the \"plus one letter\" will take care of that.</p>\n\n<p>The > signs in the tests are there to make any trailing spaces visible. </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 crop = (message, maxLength) => {\n const part = message.substring(0, maxLength + 1);\n return part.substring(0, part.lastIndexOf(\" \")).trimEnd();\n}\n\nconsole.log(crop(\"The quick brown fox jumped over the fence\", 11)+\">\");\nconsole.log(crop(\"The quick brown fox jumped over the fence\", 9)+\">\");\nconsole.log(crop(\"The quick brown fox jumped over the fence\", 8)+\">\");\nconsole.log(crop(\"The \", 6)+\">\");\nconsole.log(crop(\"The quick \", 20)+\">\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The other answers have very good explanations. I just felt a really simple solution was missing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T15:45:27.830",
"Id": "425210",
"Score": "0",
"body": "+1. I think this is actually a really elegant way to accomplish the request."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T10:52:26.363",
"Id": "220045",
"ParentId": "220011",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:29:01.970",
"Id": "220011",
"Score": "12",
"Tags": [
"javascript",
"performance",
"strings",
"array",
"formatting"
],
"Title": "Cropping a message using array splits"
} | 220011 |
<p><a href="https://projecteuler.net/problem=357" rel="nofollow noreferrer">Project Euler Problem 357</a> asks:</p>
<blockquote>
<p>Consider the divisors of 30: 1,2,3,5,6,10,15,30.
It can be seen that for every divisor d of 30, <span class="math-container">$$d+30/d$$</span> is prime.</p>
<p>Find the sum of all positive integers n not exceeding 100 000 000
such that for every divisor d of n, <span class="math-container">$$d+n/d$$</span> is prime.</p>
</blockquote>
<pre><code>import time
start = time.time()
import math
def divisor_generator(n):
'''Generates the divisiors of input num'''
large_divisors = []
for i in range(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
def is_prime(n):
'''simple prime tester'''
if n == 2 or n == 3 :
return True
for i in range(2,int(n**(1/2))+1):
if n % i == 0:
return False
return True
def test_condition (divisor_array, num):
''' Testing the condition of d+n/d by taking the input as array of divisor and num'''
if len(divisor_array) %2 != 0: # the divisors of num = d3 is [1,d2,d3], and d2*d2=d3 hence d2+d3/d2 = 2d2 which is not prime
return False
if sum(divisor_array) %2 != 0: # the divisors of num = d4, [1,d2,d3,d4] (1+d4)=Prime and (d2+d3)==Prime hence sum([1,d2,d3,d4]) must be even
return False
if len(divisor_array)%2 == 0:
for i in range(len(divisor_array)//2):
if is_prime(divisor_array[i] + divisor_array[-i-1]) == False:
return False
return True
Count = 0
for num in range(2,31,2): #since for odd num we do not have prime numbers
divisor_list_num = list(divisor_generator(num))
if test_condition(divisor_list_num,num) == True:
Count += num
print(Count)
end = time.time()
print(end-start,"sec")
</code></pre>
<p>It's good up to <span class="math-container">\$\text{num} = 10^6\$</span> but then it gets slow after that. I find that at it takes 16 min to find the <span class="math-container">\$\text{num} < 10^7\$</span>.</p>
<p>How can I inrease the speed of my code ?</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>def divisor_generator(n):\n '''Generates the divisiors of input num'''\n large_divisors = []\n for i in range(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\n</code></pre>\n</blockquote>\n\n<p>I would rename this just <code>divisors</code>, but other than that it seems like a reasonable general-purpose divisor enumerator for very small numbers with a couple of caveats: the doc comment has a typo and uses the wrong name for the input, and if this is supposed to work in Python 3 (which I'm guessing it is from the use of <code>range</code> rather than <code>xrange</code>) then it should use integer division: <code>n // i</code>.</p>\n\n<p>However:</p>\n\n<ol>\n<li>This task doesn't call for a general-purpose divisor enumerator. IMO it would make more sense to return pairs <code>(i, n // i)</code>.</li>\n<li>To scale to larger numbers it's worth finding the prime factorisation and constructing the divisors from them. The best way I know to do that is to build an array like Eratosthenes' sieve, but instead of storing a Boolean to indicate prime/composite store a prime divisor. (I generally store the lowest prime divisor, but it depends on what you want to do with it). Then you can find the prime factorisation by chaining down the array.</li>\n</ol>\n\n<hr>\n\n<blockquote>\n<pre><code>def is_prime(n):\n '''simple prime tester'''\n if n == 2 or n == 3 :\n return True\n for i in range(2,int(n**(1/2))+1):\n if n % i == 0:\n return False\n return True\n</code></pre>\n</blockquote>\n\n<p>If you're going to be testing a lot of numbers from just over 0 to N for primality then you definitely want to use a sieve, effectively testing them in parallel and caching the results.</p>\n\n<p>There are a couple of PEP8 violations in this function: space before colon, no space after comma.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def test_condition (divisor_array, num):\n\n ''' Testing the condition of d+n/d by taking the input as array of divisor and num'''\n\n if len(divisor_array) %2 != 0: # the divisors of num = d3 is [1,d2,d3], and d2*d2=d3 hence d2+d3/d2 = 2d2 which is not prime\n return False\n</code></pre>\n</blockquote>\n\n<p>Nice special case, but it can be generalised a <em>long</em> way. How can you restate the test \"<code>num</code> can be split as <code>i</code> and <code>num/i</code> which are not coprime\"?</p>\n\n<p>Argue this through all the way and it gives you a completely different high-level algorithm which should be much more efficient. But since this is Project Euler, I'm not going to say more than that hint.</p>\n\n<blockquote>\n<pre><code> if sum(divisor_array) %2 != 0: # the divisors of num = d4, [1,d2,d3,d4] (1+d4)=Prime and (d2+d3)==Prime hence sum([1,d2,d3,d4]) must be even\n return False\n</code></pre>\n</blockquote>\n\n<p>I don't think I follow this argument. Why does the sum of more than two factors matter?</p>\n\n<blockquote>\n<pre><code> if len(divisor_array)%2 == 0:\n</code></pre>\n</blockquote>\n\n<p>This condition is unnecessary, because if it failed then we've already returned <code>False</code>.</p>\n\n<blockquote>\n<pre><code> for i in range(len(divisor_array)//2):\n if is_prime(divisor_array[i] + divisor_array[-i-1]) == False:\n return False\n return True\n</code></pre>\n</blockquote>\n\n<p>It would be more Pythonic to use <code>all(comprehension)</code>. Also, this highlights my point about returning pairs of divisors rather than using a general-purpose divisor enumerator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T08:40:09.143",
"Id": "428670",
"Score": "0",
"body": "Sorry for my late reply. I was busy with my finals. I added sum because I thought it would be faster to check it rather then just passing for loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T08:54:14.230",
"Id": "428672",
"Score": "0",
"body": "I actually did not create the divisor generator thing myself. I still dont know sieve. I ll leanr it right now and then change my prime tester. In the test part thing. $i$ must be prime I think"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:27:30.833",
"Id": "220034",
"ParentId": "220012",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220034",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:36:29.940",
"Id": "220012",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "Project Euler #357: Prime generating integers"
} | 220012 |
<p>I have tons of location points with several attributes like <code>time_stamp</code>, <code>latitude</code>, <code>longitude</code>, <code>accuracy</code>, <code>velocity</code> etc. Now I want to remove duplicate location points on these conditions:</p>
<ol>
<li>Latitude is same</li>
<li>Longitude is same</li>
<li>Month is same </li>
<li>Day is same</li>
</ol>
<p>The other attributes dont matter at all for comparison. My strategy is to modify <code>__hash__</code>, <code>__eq__</code> and <code>__ne__</code> methods to include the above conditions and feed them into <code>set</code> function to remove the duplicates.</p>
<pre><code>item1 = Location(1510213074679, 286220203, 772454413, 1414, None, None, None, 78, None)
item2 = Location(1510213074679, 286220203, 772454413, 5, 6, 80, 226, None, None)
item3 = Location(1523620644975, 286265651, 772427842, 65, None, None, 193, 10, None)
x = set()
x.add(item1)
x.add(item2)
x.add(item3)
print(x)
{<__main__.Location at 0x7fd725559eb8>, <__main__.Location at 0x7fd725604dd8>}
</code></pre>
<p>Length of set is as expected i.e 2 (two elements with same attributes).</p>
<p>The result which I expect, can be obtained as follows </p>
<pre><code>[f.data() for f in x]
</code></pre>
<p>Is there any other pythonic way to achieve the same result?</p>
<pre class="lang-py prettyprint-override"><code>class Location(object):
def __init__(self, time_stamp, latitude, longitude, accuracy, velocity,
heading, altitude, vertical_accuracy, activity):
self.time_stamp = float(time_stamp) / 1000
self.latitude = float(latitude) / 10000000
self.longitude = float(longitude) / 10000000
self.accuracy = accuracy
self.velocity = velocity
self.heading = heading
self.altitude = altitude
self.vertical_accuracy = vertical_accuracy
self.activity = activity
self.timestamp, self.year, self.month = month_aware_time_stamp(
self.time_stamp)
self.hash = self.hashed()
def data(self):
return self.__dict__
def hashed(self):
string = str(self.latitude) + str(self.longitude)
return hashlib.sha3_224(string.encode()).hexdigest()
def __hash__(self):
string = str(self.latitude) + str(self.longitude)
return hash(string.encode())
def __eq__(self, other):
"""Override the default Equals behavior"""
if isinstance(other, self.__class__):
return self.hash == other.hash and self.month == other.month and self.year == other.year
return False
def __ne__(self, other):
"""Override the default Unequal behavior"""
return self.hash != other.hash or self.month != other.month or self.year != other.year
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T23:09:28.577",
"Id": "425137",
"Score": "0",
"body": "Where are your data coming from? Is the `Location` object used for any other purpose in your code, or is it solely for deduplication?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T08:38:03.047",
"Id": "425176",
"Score": "0",
"body": "The data is in JSON file, each JSON will have more than 100000 entries. My task at hand is to find the most visited locations in a month of a year."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T21:40:36.920",
"Id": "425225",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<h1><code>hash</code></h1>\n\n<p>Since tuples are hashable if their elements are hashable, you can just do</p>\n\n<pre><code>def __hash__(self):\n return hash((self.latitude, self.longitude, self.year, self.month))\n</code></pre>\n\n<p>If you want to have locations that are near each other be set as the same, you might have to round the coordinates</p>\n\n<h1><code>repr</code></h1>\n\n<p>for debugging, adding a repr can be handy:</p>\n\n<pre><code>def __repr__(self):\n return (\n \"Position(\"\n f\"lat: {self.latitude}, \"\n f\"lon: {self.longitude}, \"\n f\"year: {self.year}, \"\n f\"month: {self.month}, \"\n \")\"\n )\n</code></pre>\n\n<h1>Counting</h1>\n\n<p>To count, you can use a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>, and just feed it an iterable of Positions.</p>\n\n<pre><code>counter = Counter(locations)\nmost_visited = counter.most_common(<n>)\n</code></pre>\n\n<p>You will need one Counter per year/month, but this can be done with a <code>defaultdict(Counter)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T08:47:45.517",
"Id": "425177",
"Score": "0",
"body": "I exactly did it like this, rounding off latitude and longitude to three decimal places, thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T08:43:50.320",
"Id": "220040",
"ParentId": "220013",
"Score": "3"
}
},
{
"body": "<p>First - you are expected to provide complete and working code. To fully understand your code <code>month_aware_time_stamp</code> is missing (I'll try to guess what it probably returns).</p>\n\n<p>Second - I think your approach and your class <code>Location</code> is broken by design. Also the implementation is a mess but let's stick to the design first. What your class does</p>\n\n<pre><code>>>> item1 = Location(1510213074679, 286220203, 772454413, 1414, None, None, None, 78, None)\n>>> item2 = Location(1510213074679, 286220203, 772454413, 5, 6, 80, 226, None, None)\n>>> item1 == item2\nTrue\n</code></pre>\n\n<p>This is weird behavior. Nobody would expect that. Your code is not maintainable and will cause surprising behavior when being maintained.</p>\n\n<ul>\n<li><p>If you do not need all the other attributes - do not store them at all. Just store the attributes you want to compare and do your stuff without strange hash implementations</p></li>\n<li><p>If you need all that attributes in your class, then your implementation will render the class useless for any other use. Do not overwrite the comparison behavior but either extract the relevant data to a second data structure (tuple, ...) or provide an external comparison function for calling functions like <code>sort()</code>. You can always do comprehension to extract relevant attributes to a tuple</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>some_set = {(s.latitude, s.longitude, s.year, s.month) for s in x}\n</code></pre>\n\n<p>or you immediately count with <code>collections.Counter</code></p>\n\n<pre><code>import collections\nc = collections.Counter((s.latitude, s.longitude, s.year, s.month) for s in x)\n</code></pre>\n\n<p>I will skip the review of the concrete implementetion as the design has to change. But</p>\n\n<ul>\n<li>never implement some homebrew hash if the builtin <code>hash()</code> is sufficient.</li>\n<li>if you think you have to implement <code>__hash__()</code> and/or `<strong>eq</strong>() please follow the guidelines in [<a href=\"https://docs.python.org/3/reference/datamodel.html#object.__hash__]\" rel=\"nofollow noreferrer\">https://docs.python.org/3/reference/datamodel.html#object.<strong>hash</strong>]</a></li>\n<li>never keep hash values unless you can guarantee consistency</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T21:23:24.227",
"Id": "425223",
"Score": "0",
"body": "I have changed my code, never keep hash values unless you can guarantee consistency but couldnt understand your statement , Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T21:13:02.680",
"Id": "220069",
"ParentId": "220013",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220040",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:47:44.170",
"Id": "220013",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Pythonic way to find duplicate objects in a set"
} | 220013 |
<p>A friend of mine is a huge fan of a <a href="https://dilbert.com" rel="noreferrer">well-known comic website</a> and he recently said that it'd be great to have a tool that downloads comic strips for a given date range, instead of clicking through the website.</p>
<p>So I thought I'd write a script that does just that. And I did. </p>
<p>It's far from perfect, but it does its job. </p>
<p>However, as I'm a weekend Python dabbler, I'd be delighted to not only improve the script but also learn a lesson or two about the language the script is written in.</p>
<p>Therefore, I submit this rather clumsy script for your evaluation. I'd appreciate any feedback and suggestion regarding the implementation and potential improvements.</p>
<p><em>Note: I can already see a potential bottleneck, which is the method that attempts to download all published comics (almost 11,000 of them). If you see a way to improve this part, please do let me know.</em></p>
<pre><code>#!/usr/bin/python3.6
"""
A simple comic strip scraper for dilbert.com
"""
import os
import subprocess
import time
import sys
import colorama
from colorama import Fore
from datetime import date, timedelta
import requests
from bs4 import BeautifulSoup as bs
from tqdm import tqdm
from dateutil.relativedelta import relativedelta
LOGO = """
_ _ _ _ _ _ _
| | (_) | (_) | | | |
___| |_ _ __ _ _ __ __| |_| | |__ ___ _ __| |_
/ __| __| '__| | '_ \ / _` | | | '_ \ / _ \ '__| __|
\__ \ |_| | | | |_) | | (_| | | | |_) | __/ | | |_
|___/\__|_| |_| .__/ \__,_|_|_|_.__/ \___|_| \__|
| |
|_| version: 0.2 | 2019
"""
DEFAULT_DIR_NAME = "my_dilberts"
COMICS_DIRECTORY = os.path.join(os.getcwd(), DEFAULT_DIR_NAME)
BASE_URL = "https://dilbert.com/strip/"
FIRST_COMIC = date(1989, 4, 16) # The earliest diblert comic strip published
NEWEST_COMIC = date.today()
def clear_screen():
"""
Clears terminal screen
"""
if os.name in ('nt', 'dos'):
subprocess.call('cls')
elif os.name in ('linux', 'osx', 'posix'):
subprocess.call('clear')
else:
print("\n" * 120)
def show_logo():
"""
Displays the ascii logo
"""
clear_screen()
colorama.init(autoreset=True)
print("\nA simple comic strip scraper for dilbert.com")
print(Fore.RED + LOGO)
print("author: baduker | repo: github.com/baduker/strip_dilbert\n")
def show_main_menu():
"""
Main download menu
"""
print("Choose a menu item to download:\n")
print("1. Today's comic strip: {}".format(get_today()))
print("2. This week's strips: {} - {}".format(get_this_week()[0], get_this_week()[1]))
print("3. Last week's strips: {} - {}".format(get_last_week()[0], get_last_week()[1]))
print("4. This month's strips: {} - {}".format(get_this_month()[0], get_this_month()[1]))
print("5. Last month's strips: {} - {}".format(get_last_month()[0], get_last_month()[1]))
print("6. Custom date ragne:")
print("-"*20)
print("0. Type 0 to Exit.\n")
def get_main_menu_item():
"""
Takes and checks the main menu selection input
"""
while True:
try:
main_menu_item = int(input("Type your selection here: "))
except ValueError:
print("\nError: expected a number! Try again.\n")
continue
if main_menu_item < 0:
print("\nSorry, that didn't work! Try again.\n")
continue
elif main_menu_item > 6:
print("\nNo such menu item! Try again.\n")
continue
elif main_menu_item == 0:
sys.exit()
else:
break
return main_menu_item
def handle_main_menu(menu_item):
"""
Handles the main menu and invokes the download engine
"""
if menu_item == 1:
download_engine(get_today(), get_today())
elif menu_item == 2:
download_engine(get_this_week()[0], get_this_week()[1])
elif menu_item == 3:
download_engine(get_last_week()[0], get_last_week()[1])
elif menu_item == 4:
download_engine(get_this_month()[0], get_this_month()[1])
elif menu_item == 5:
download_engine(get_last_month()[0], get_last_month()[1])
elif menu_item == 6:
clear_screen()
today = date.today()
print("\nNOTE! Since {}, there has been {} (as of {}) dilberts published.".format(FIRST_COMIC.strftime('%d/%b/%Y'), get_number_of_dilberts_till_now(), today.strftime('%d/%b/%Y')))
print("So, if you want to download all of them bear in mind that it might take a while.\n")
print("1. Downlaod all dilberts ({})!".format(get_number_of_dilberts_till_now()))
print("2. Enter a custom date range.")
print("-"*20)
print("0. Type 0 to Exit.\n")
minor_item = get_minor_menu_item()
handle_minor_menu(minor_item)
def get_minor_menu_item():
"""
Takes and checks the minor menu selection input
"""
while True:
try:
minor_menu_item = int(input("Type your selection here: "))
except ValueError:
print("\nError: expected a number! Try again.\n")
continue
if minor_menu_item < 0:
print("\nSorry, that didn't work! Try again.\n")
continue
elif minor_menu_item > 2:
print("\nNo such menu item! Try again.\n")
continue
elif minor_menu_item == 0:
sys.exit()
else:
break
return minor_menu_item
def handle_minor_menu(menu_item):
"""
Handles the minor menu and invokes the custom date range download engine
"""
if menu_item == 1:
download_engine(FIRST_COMIC, NEWEST_COMIC)
elif menu_item == 2:
first_strip_date = get_comic_strip_start_date()
last_strip_date = get_comic_strip_end_date()
download_engine(first_strip_date, last_strip_date)
def get_today():
"""
Returns today's date
"""
today = date.today()
return today
def get_this_week():
"""
Returns dates for current week
"""
today = date.today()
week_start = today - timedelta(days = today.weekday())
delta = (today - week_start).days
week_end = week_start + timedelta(days= delta)
return week_start, week_end
def get_last_week():
"""
Returns last week's date range
"""
today = date.today()
last_week_start = today - timedelta(days = today.weekday(), weeks = 1)
last_week_end = last_week_start + timedelta(days=6)
return last_week_start, last_week_end
def get_this_month():
"""
Returns dates for current month
"""
today = date.today()
if today.day > 25:
today += timedelta(7)
first_day_of_this_month = today.replace(day=1)
return first_day_of_this_month, today
def get_last_month():
"""
Returns last month's date range
"""
today = date.today()
today_but_a_month_ago = today - relativedelta(months = 1)
first_day_of_previous_month = date(today_but_a_month_ago.year, today_but_a_month_ago.month, 1)
last_day_of_the_previous_month = date(today.year, today.month, 1) - relativedelta(days = 1)
return first_day_of_previous_month, last_day_of_the_previous_month
def get_number_of_dilberts_till_now():
"""
Counts all the comic strips published since April 16th, 1989
"""
today = date.today()
delta = (today - FIRST_COMIC).days + 1
return delta
def get_comic_strip_start_date():
"""
Asks for initial comic strip date for custom date range
"""
print("Type a dilbert comic start date in YYYY/MM/DD format:")
while True:
start_year, start_month, start_day = map(int, input(">> ").split("/"))
start_date = date(start_year, start_month, start_day)
if start_date < FIRST_COMIC:
print("The oldest comic is from 1989/04/16. Try again.")
continue
elif start_date > date.today():
print("You can't download anything from the future yet. Try again.")
continue
else:
break
return start_date
def get_comic_strip_end_date():
"""
Asks for final comic strip date for custom date range
"""
print("Type a dilbert comic end date in YYYY/MM/DD format:")
while True:
end_year, end_month, end_day = map(int, input(">> ").split("/"))
end_date = date(end_year, end_month, end_day)
if end_date < FIRST_COMIC:
print("The oldest comic is from 1989/04/16. Try again.")
continue
elif end_date > date.today():
print("You can't download anything from the future yet. Try again.")
continue
else:
break
return end_date
def get_comic_strip_url(start_date, end_date):
"""
Outputs the comic strip date url in the https://dilbert.com/YYYY-MM-DD format
"""
full_url = []
delta = end_date - start_date
for day in range(delta.days + 1):
full_url.append(BASE_URL+str(start_date + timedelta(day)))
return full_url
def get_image_comic_url(session, response):
"""
Fetches the comic strip image source url based on the strip url
"""
soup = bs(response.text, 'lxml')
for div in soup.find_all('div', class_="img-comic-container"):
for a in div.find_all('a', class_="img-comic-link"):
for img in a.find_all('img', src=True):
return "https:" + img['src']
def download_dilbert(s, u):
"""
Downloads and saves the comic strip
"""
filne_name = u.split('/')[-1]
with open(os.path.join(COMICS_DIRECTORY, filne_name), "wb") as file:
response = s.get(u)
file.write(response.content)
def download_engine(fcsd, lcsd): #fcsd = first comic strip date & lcsd = last comis strip date
"""
Based on the strip url, fetches the comic image source and downloads it
"""
start = time.time()
url_list = get_comic_strip_url(fcsd, lcsd)
os.mkdir(DEFAULT_DIR_NAME)
for url in url_list:
session = requests.Session()
response = session.get(url)
download_url = get_image_comic_url(session, response)
pbar = tqdm(range(len(url_list)))
for i in pbar:
pbar.set_description("Fetching {}".format(url[8:]))
download_dilbert(session, download_url)
end = time.time()
print("{} dilbert comics downloaded in {:.2f} seconds!".format(len(url_list), end - start))
def main():
"""
Encapsulates and executes all methods in the main function
"""
show_logo()
show_main_menu()
the_main_menu_item = get_main_menu_item()
handle_main_menu(the_main_menu_item)
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>Thanks for reminding me about Dilbert comics. I had somehow forgotten about them and it's nice to see new comics are still being written.</p>\n\n<p>I'm not a python guy, so hopefully you receive other responses but here are a few minor suggestions:</p>\n\n<p>Use <code>NEWEST_COMIC</code> instead of <code>date.today()</code> on line 240:</p>\n\n<pre><code>elif start_date > date.today():\n</code></pre>\n\n<p>You've defined a method for <code>get_today</code> but also use <code>date.today()</code></p>\n\n<p>Don't shorten parameter names. Instead of a comment describing them, use the full length name</p>\n\n<pre><code>def download_dilbert(s, u):\ndef download_engine(fcsd, lcsd): #fcsd = first comic strip date & lcsd = last comis strip date\n</code></pre>\n\n<p>You could implement some limiting functions to prevent spamming the Dilbert web page. \"GoComics.com\" hosts older Dilbert Comics in case you need to make lots of requests.</p>\n\n<p>Saving the images locally might be breaking some rules/laws, but you could keep a list of URL's (E.g <a href=\"https://assets.amuniversal.com/264ee6a0674001301b57001dd8b71c47\" rel=\"nofollow noreferrer\">https://assets.amuniversal.com/264ee6a0674001301b57001dd8b71c47</a>) with the date/name of the comic so you're not re-loading an entire page to get a previously loaded Image.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T07:50:05.340",
"Id": "425172",
"Score": "1",
"body": "Thanks a lot for those tips! I've just checked the GoComics.com website and it's great. Also, I like the idea of keeping a list of source URL's."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:54:57.793",
"Id": "220027",
"ParentId": "220014",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220027",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:55:33.423",
"Id": "220014",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"web-scraping"
],
"Title": "Strip Dilbert Comics"
} | 220014 |
<p>This program takes the filename as the input and outputs to a file the number of requests that were more than 1000 bytes and the total bytes. </p>
<p>Log file example:</p>
<pre class="lang-none prettyprint-override"><code>site.com - - [01/Jul/1995:00:00:01 -0400] "GET /images/launch-logo.gif HTTP/1.0" 200 183
</code></pre>
<p>Any suggestions/recommendations on the code or structure? </p>
<pre><code>import re
import os
filename = input()
filename_regex = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+)\s?(\S+)?\s?(\S+)?" (\d{3}|-) (\d+|-)\s'
nbr_of_requests = 0
sum_of_bytes = 0
def parse_file(filename):
with open(filename, 'r', encoding='utf-8') as fin:
print(f"Opening file: {filename}")
for line in fin.readlines():
if os.path.exists(filename):
line = re.findall(filename_regex, line)
yield line
def save_to_file(filename):
output_filename = "bytes_" + filename
with open(output_filename, 'w+') as fout:
fout.write(str(nbr_of_requests) + '\n' + str(sum_of_bytes))
if __name__ == '__main__':
for line in parse_file(filename):
if line and int(line[0][8]) >= 1000:
nbr_of_requests += 1
sum_of_bytes = sum_of_bytes + int(line[0][8])
save_to_file(filename)
</code></pre>
| [] | [
{
"body": "<p>If you don't need fields other than size, and have no use for lines with no size, a simpler regex like <code>\\s(\\d+)$</code> is going to be appreciably faster. You could even go with <code>\\s(\\d{4,})$</code> and skip the <code>>= 1000</code> test. </p>\n\n<p>If you do keep the full regex, I'd simplify the date portion because date formats are notoriously unpredictable. <code>\\[[^]]+\\]</code> does the job more robustly. </p>\n\n<p><code>(\\S+)?</code> is better written as <code>(\\S*)</code>.</p>\n\n<p><code>filename_regex</code> is better named like <code>log_entry_regex</code>, since that's what it matches.</p>\n\n<p>Overwriting the string <code>line</code> with an array of captures is ugly. And <code>re.findall</code> is not the best choice, because the regex should never match more than once per line (and your code ignores subsequent matches anyway). Try something like: </p>\n\n<pre><code>matched = re.search(log_entry_regex, line)\nif (matched) \n yield matched.groups()\n</code></pre>\n\n<p>This eliminates the array-of-arrays in the result and ensures results are always a set of matches. <code>if line and int(line[0][8]) >= 1000</code> becomes just <code>if int(line[8]) >= 1000</code>.</p>\n\n<p>The global variables are better placed inside the functions where they're used. <code>save_to_file</code> would need to take arguments then, but it's three lines and could just be inline in the main function.</p>\n\n<p>When you have an array with many values, where each value means something different, a useful pattern is to create \"fake enums\" with constant field identifiers. It makes your uses of that array easier to write and easier to read. It doesn't make much difference here, where the code is short and only one element is actually used; however it becomes invaluable as line count and complexity increase. Python doesn't have constants, variables will work too:</p>\n\n<pre><code>HOST = 0\n…\nSIZE = 8\n…\nif int( line[SIZE] ) >= 1000:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T07:45:59.777",
"Id": "425171",
"Score": "1",
"body": "wow, thank you so much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T22:33:30.440",
"Id": "220017",
"ParentId": "220016",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T21:41:59.670",
"Id": "220016",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"parsing",
"regex",
"logging"
],
"Title": "Analyzing a web access log to obtaining totals for requests"
} | 220016 |
<p>I am developing a simple <strong>Chained Flow</strong> (should I call it by this name?) that uses <strong>waterfall</strong> as main operation behavior.</p>
<p>Basically we will have a Flow and he will have some dialogs with functions to be executed. So, when you call start on Flow (passing the name of the dialog) some Waterfall objects will be created taking the pointers to the functions pre-stored and executing them. The functions to be executed can call its parent functions to execute some tasks (like calling the next function or reseting to the begin function).</p>
<p>Just take an example in Javascript (easy to understand) code:</p>
<pre><code>var status = false;
var array_of_functions = [
function(parent) {
print("first");
parent.next();
},
function(parent) {
print("second");
if (!status) {
status = true;
// call itself again (not the whole array, reset() should do it)
parent.restart();
}
}
];
doMagic(array_of_functions);
</code></pre>
<blockquote>
<p>Output: first -> second -> second;</p>
</blockquote>
<p>I'm concerned about the method that I used to make it. Should I try to rewrite in another way or is it good?</p>
<p>Probably the code is a little messy, but I can't find a better way to solve. And I am using templates to later add some more arguments to the functions that will be called. Taking that, I'm using lambda expressions too to avoid declaring the types in each function (passing a Course object).</p>
<p>The code takes only 2 files, excluding main.</p>
<h3>main.cpp</h3>
<p>(just a example, I will embed Flow into another Class later)</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "Flow.h"
bool status = false;
void one(Course* course) {
std::cout << "one" << std::endl;
course->doNext();
}
void two(Course* course) {
std::cout << "two" << std::endl;
if (!status) {
status = true;
course->doRestart();
} else {
course->doReplace("another");
}
}
void three(Course* course) {
std::cout << "three" << std::endl;
course->doNext();
}
int main() {
std::vector<std::function<void(Course*)>> init = {one, two};
std::vector<std::function<void(Course*)>> another = {three};
Flow<void, Course*> flow;
flow.setDialog("init", steps_x);
flow.setDialog("another", steps_y);
flow.doStart("init");
return 1;
}
</code></pre>
<h3>Flow.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef FLOW_H
#define FLOW_H
#include <string>
#include <vector>
#include <functional>
#include "Waterfall.h"
template <typename rtype, typename ...fargs> class Waterfall;
template <typename rtype, typename ...fargs> class Flow {
public:
Flow() {}
~Flow() {}
struct Node {
std::string name;
std::vector<std::function<rtype(fargs...)>> functions;
};
bool doTrigger(std::string name) {
Node* node;
bool found = false;
for (Node& tmp : _dialogs) {
if (tmp.name == name) {
node = &tmp;
found = true;
break;
}
}
if (!found) return false;
Waterfall<rtype, fargs...> waterfall(this, node->functions);
waterfall.doTrigger();
return true;
}
bool setDialog(std::string name, std::vector<std::function<rtype(fargs...)>> functions) {
for (const Node& node : _dialogs) {
if (node.name == name) {
return false;
}
}
Node node = {name, functions};
_dialogs.push_back(node);
return true;
}
private:
std::vector<Node> _dialogs;
};
#endif
</code></pre>
<h3>Waterfall.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef WATERFALL_H
#define WATERFALL_H
#include <vector>
#include <functional>
#include <iostream>
#include "Flow.h"
struct Course {
std::function<void()> doNext;
std::function<void()> doRestart;
std::function<void()> doReset;
std::function<void(std::string)> doReplace;
};
template <typename rtype, typename ...fargs> class Flow;
template <typename rtype, typename ...fargs> class Waterfall {
public:
Waterfall(Flow<rtype, fargs...>* flow, std::vector<std::function<rtype(fargs...)>>& functions) :
_index(0),
_flow(flow)
{
for (unsigned int i = 0; i < functions.size(); i++) {
Step step;
step.callback = &functions[i];
_steps.push_back(step);
}
}
~Waterfall() {}
Flow<rtype, fargs...>* getFlow() {return _flow;}
struct Step {
unsigned int count = 0;
std::function<rtype(fargs...)>* callback;
};
bool doTrigger() {
if (_index >= _steps.size()) return false;
Step* step = &_steps[_index];
unsigned int& count = step->count;
Course course;
course.doNext = [this]() {
this->doNext();
};
course.doRestart = [this]() {
this->doRestart();
};
course.doReset = [this]() {
this->doReset();
};
course.doReplace = [this](std::string name) {
this->getFlow()->doTrigger(name);
};
count++;
(*(step->callback))(&course);
return true;
}
bool doNext() {
if (_index >= _steps.size()) return false;
_index++;
return doTrigger();
}
bool doRestart() {
return doTrigger();
}
bool doReset() {
_index = 0;
return doTrigger();
}
private:
unsigned int _index;
Flow<rtype, fargs...>* _flow;
std::vector<Step> _steps;
};
#endif
</code></pre>
<p>You can use this to compile:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
g++ -W -Wall -Werror -Wextra -pedantic -O2 \
main.cpp \
Flow.h \
Waterfall.h \
-o main.exe
./main.exe
</code></pre>
<p>Thanks in advance.</p>
| [] | [
{
"body": "<p>Prefer passing a std::string_view instead of a std::string in parameters. This avoids needing to create (and allocate) std::string when they don't need to be. Std::string should still be used in Node to ensure the string remains valid. </p>\n\n<p>Having said that using integer keys is better. Using an enum for the keys means that a typo in the key becomes a compile error instead of a bug and if you take care to make them sequential and start from 0 the lookup is a vector index instead of a linear search.</p>\n\n<p>the template parameters for the function type is meaningless. You can only use <code>std::function<void(Course*)></code> in it. Any other parameter list will result in a compilation error. </p>\n\n<p>Your control flow through the <code>Course</code> object is deeply recursive when it doesn't need to be. This means that the user could create a stack overflow by jumping back and forth between menu items.</p>\n\n<p>Instead you can keep the index and current node as a local and manipulate it, if you get rid of the Waterfall class this becomes a bit easier:</p>\n\n<pre><code>bool doStart(std::string_view name) {\n\n Node* currentNode = //find the corresponding Node;\n size_t functionIndex = 0;\n Course course;\n course.doNext = [&]() {\n functionIndex ++;\n };\n\n course.doRestart = [&]() {\n //nop\n };\n\n course.doReset = [&]() {\n functionIndex = 0;\n };\n\n course.doReplace = [&](std::string_view name) {\n currentNode = //find the corresponding Node;\n functionIndex = 0;\n };\n\n while(currentNode != nullptr && functionIndex < currentNode->funcs.length){\n currentNode->funcs[functionIndex](&course);\n }\n}\n</code></pre>\n\n<p>However looking at that code it makes sense to make <code>Node* currentNode</code>, <code>size_t functionIndex</code> and a <code>Flow* flow</code> as fields of <code>Course</code> and make the functions normal instance functions:</p>\n\n<pre><code>struct Course {\n Node* currentNode = nullptr;\n size_t functionIndex = 0;\n Flow* flow;\n\n void doNext(){\n functionIndex ++;\n }\n void doRestart() {\n //nop\n }\n void doReset() {\n functionIndex = 0;\n }\n void doReplace(std::string_view name) {\n currentNode = flow->findNode(name);\n functionIndex = 0;\n }\n};\n\n\nbool doStart(std::string_view name) {\n\n Course course;\n course.currentNode = findNode(name);\n course.functionIndex = 0;\n course.flow = this;\n\n while(course.currentNode != nullptr && \n course.functionIndex < course.currentNode->funcs.length){\n course.currentNode->funcs[course.functionIndex](&course);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T18:04:50.270",
"Id": "425213",
"Score": "0",
"body": "Thank you, this makes too much simple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:27:49.880",
"Id": "425375",
"Score": "0",
"body": "I followed your resolution, was way better than mine. Just to complement, I added a counter to manage the times that the functions will be called, and if none functions is next or is up to replace, the counter drops to 0 and the flow just ends."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:30:37.443",
"Id": "425376",
"Score": "0",
"body": "Another obs that I found that probably can be useful to someone: if the code still remains Node and Course objects, than you must to separate both and passing by lambda to avoid nested classes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T09:25:16.047",
"Id": "220043",
"ParentId": "220020",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T23:08:52.823",
"Id": "220020",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Simple Chained Flow"
} | 220020 |
<p>I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as <code>a3b2c4d1</code> for the solution below.</p>
<p>i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.</p>
<p>Here is my current solution:</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>let countLetters = (str) => {
let arr = str.split(''),
map = {},
ret = '';
for (var i = 0; i < arr.length; i++) {
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length
}
for (let i in map) {
ret += `${i + map[i]}`
}
return ret;
}
console.log(countLetters('aaabbccccd'));</code></pre>
</div>
</div>
</p>
<p>Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T03:25:29.283",
"Id": "425157",
"Score": "0",
"body": "Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop."
}
] | [
{
"body": "<h2>Big <span class=\"math-container\">\\$O\\$</span></h2>\n<p>Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.</p>\n<p>In this case the metric <span class=\"math-container\">\\$n\\$</span> is the string length. The first loop that uses <code>String.match</code> must for each character check all characters to find a count. That means at least <span class=\"math-container\">\\$n * n\\$</span> steps need to be performed to do the operation.</p>\n<p>Thus the complexity of the function is said to be <span class=\"math-container\">\\$O(n^2)\\$</span></p>\n<p>If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of <span class=\"math-container\">\\$O(n)\\$</span></p>\n<p>Maps use a hash function to locate an item <span class=\"math-container\">\\$O(1)\\$</span>. So the time complexity to find out if you have counted a character before is <span class=\"math-container\">\\$O(1)\\$</span>, rather than your regExp <span class=\"math-container\">\\$O(n)\\$</span></p>\n<pre><code>function countLetters(str) {\n const charCounts = {};\n var result = "";\n for (const c of str) { \n if (charCounts[c]) { charCounts[c] += 1 }\n else { charCounts[c] = 1 }\n }\n for (const [char, count] of Object.entries(charCounts)) {\n result += char + " has " + count + " ";\n }\n return result;\n}\n</code></pre>\n<p>The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is <span class=\"math-container\">\\$2n\\$</span> In big <span class=\"math-container\">\\$O\\$</span> notation the scale <span class=\"math-container\">\\$2\\$</span> is insignificant compared to powers, even if it was <span class=\"math-container\">\\$1000000n\\$</span> we ignore the scale and make it just <span class=\"math-container\">\\$n\\$</span></p>\n<p>It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.</p>\n<h2>Style Notes.</h2>\n<ul>\n<li>Use <code>;</code> or not, never use them sometimes.</li>\n<li>Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.</li>\n<li>Use Function declarations in favor of arrow functions when in global scope.</li>\n<li>Variables that do not change should be declared as constants <code>const</code></li>\n<li>Use <code>for of</code> rather than <code>for in</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T02:55:37.213",
"Id": "220028",
"ParentId": "220026",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220028",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T01:58:11.860",
"Id": "220026",
"Score": "3",
"Tags": [
"javascript",
"performance",
"algorithm",
"compression"
],
"Title": "Print a string of characters with their occurrences"
} | 220026 |
<p>I have taken <a href="https://codepen.io/irinakramer/pen/jcLlp" rel="nofollow noreferrer">someone else's HTML and CSS code for grid layouts</a> and reactified it. When converting the code to React, I tried to make it as simpler. I would like to learn from community, if any improvement can be done in the below code or not. If there is any suggestion, improvement, enhancement that can be done, please do suggest me on improving my code which will help me to learn the best practices.</p>
<p>Here is my code </p>
<pre><code>import Cell from './Cell'
import {GridWrapper} from './styled'
const Grid = ({children, ...props}) => {
return (
<GridWrapper {...props} data-id="Grid">
{children}
</GridWrapper>
)
}
Grid.propTypes = {
children : PropTypes.node.isRequired,
full : PropTypes.bool,
gridAlign : PropTypes.oneOf(['top', 'bottom', 'center', 'right', 'left']),
gutters : PropTypes.bool,
textCenter: PropTypes.bool,
}
Grid.defaultProps = {
gutters : true,
full : false,
textCenter: false,
gridAlign : 'left',
}
Grid.displayName = 'Grid'
Grid.Cell = Cell
</code></pre>
<p>Cell.js</p>
<pre><code>const Cell = ({children}) => {
return <GridCell data-id="GridCell">{children}</GridCell>
}
Cell.propTypes = {
children: PropTypes.node.isRequired,
}
Cell.displayName = 'Grid.Cell'
</code></pre>
<p>styled.js</p>
<pre><code>import styled from 'styled-components'
const colsFirstOfType = ['cols-1of3', 'cols-1of4', 'cols-1of6']
function styleGridAlign(position) {
// may be hAlign and vAlign tersm will sound best
switch (position) {
case 'top':
return 'align-items: flex-start;'
case 'bottom':
return 'align-items: flex-end'
case 'right':
return 'justify-content: flex-end'
case 'left':
return 'justify-content: flex-start'
case 'center':
return 'justify-content: center; align-items: center'
default:
return 'flex-start'
}
}
export const GridCell = styled.div`
flex: 1;
`
function styleColumn(column, firstOfType) {
if (firstOfType) {
switch (column) {
case 'cols-1of4':
case 'cols-1of3':
return '0 0 100%'
case 'cols-1of6':
return '0 0 50%'
default:
return '0 0 100%'
}
} else {
switch (column) {
case 'cols-2':
case 'cols-3':
case 'cols-4':
return '0 0 100%'
case 'cols-6':
return '0 0 calc(50% - 1em)'
case 'cols-12':
return '0 0 calc(33.3333% - 1em)'
case 'cols-1of2':
return '0 0 50%'
default:
return '0 0 100%'
}
}
}
function styleColumnForTablet(column, firstOfType) {
if (firstOfType) {
switch (column) {
case 'cols-1of4':
return '0 0 50%'
case 'cols-1of3':
return '0 0 100%'
case 'cols-1of6':
return '0 0 30%'
default:
return ''
}
} else {
switch (column) {
case 'cols-4':
return '0 0 calc(50% - 1em)%'
case 'cols-6':
return '0 0 calc(33.3333% - 1em)'
case 'cols-12':
return '0 0 calc(16.6666% - 1em)'
case 'cols-1of2':
return '0 0 50%'
default:
return ''
}
}
}
/* Large screens */
function styleColumnForLargeScreen(column, firstOfType) {
if (firstOfType) {
switch (column) {
case 'cols-1of4':
return '0 0 25%'
case 'cols-1of3':
return '0 0 30%'
case 'cols-1of6':
return '0 0 16.6666%'
default:
return ''
}
} else {
switch (column) {
case 'cols-2':
case 'cols-3':
case 'cols-4':
case 'cols-6':
case 'cols-12':
return '1'
case 'cols-1of2':
return '0 0 50%'
default:
return '1'
}
}
}
export const GridWrapper = styled.div`
display: flex;
flex-flow: row;
flex-wrap: wrap;
${props =>
props.full &&
`
flex: 0 0 100%;
`}
${props =>
props.nested &&
`
${GridCell}:first-of-type {
margin-right: 1em;
}
`}
${props =>
props.textCenter &&
`
text-align: center;
`}
${props =>
props.gutters &&
`
margin-left: -1em;
${GridCell} {
padding-left: 1em;
}
`}
${props => props.gridAlign && `${styleGridAlign(props.gridAlign)}`};
${props =>
props.col && colsFirstOfType.includes(props.col)
? `
> ${GridCell}:first-of-type {
flex: ${styleColumn(props.col, true)}
}
`
: `
> ${GridCell} {
flex: ${styleColumn(props.col, false)}
}
`};
@media (min-width: 30em) {
${props =>
props.col && colsFirstOfType.includes(props.col)
? `
> ${GridCell}:first-of-type {
flex: ${styleColumnForTablet(props.col, true)}
}
`
: `
> ${GridCell} {
flex: ${styleColumnForTablet(props.col, false)}
}
`}
}
@media (min-width: 48em) {
${props =>
props.col && colsFirstOfType.includes(props.col)
? `
> ${GridCell}:first-of-type {
flex: ${styleColumnForLargeScreen(props.col, true)}
}
`
: `
> ${GridCell} {
flex: ${styleColumnForLargeScreen(props.col, false)}
}
`}
}
`
</code></pre>
<p>Here is the CodeSandbox for demo: <a href="https://codesandbox.io/s/ov6k5xnn4q" rel="nofollow noreferrer">https://codesandbox.io/s/ov6k5xnn4q</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T04:57:57.880",
"Id": "220030",
"Score": "3",
"Tags": [
"react.js",
"jsx",
"layout"
],
"Title": "Reusable grid layout for React.js"
} | 220030 |
<p>The software that I develop uses large floating-point arrays up to the maximum size that can be allocated in C#. I have a large number of algorithms such as convolutions and filters that get executed over those large arrays. I am currently updating as many algorithms as possible to fully threaded and vectorized.</p>
<p>By utilizing the <code>System.Numerics.Vector<T></code> methods, I am seeing typically a 300%+ performance improvement in many of the algorithms on computers equipped with AVX (where <code>Vector<float>.Count</code> returns 4) and a 600%+ performance improvement in many of the algorithms on computers equipped with AVX2 (where <code>Vector<float>.Count</code> returns 8).</p>
<p>NET Standard 2.1 <code>System.Numerics.Vector<T></code> here:</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.numerics.vector-1?view=netstandard-2.1" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.numerics.vector-1?view=netstandard-2.1</a></p>
<p>One of the functions that I require on a number of the algorithms is to Clamp the array element value to a bounds Minimum or Maximum value after performing some mathematical operation on it. That is of course really easy to do with the single-threaded and multi-threaded algorithms that use standard arithmetic operations.</p>
<p>The issue that I am having is that <code>System.Numerics.Vector<T></code> doesn't include any kind of Clamp method (Vector2, 3, 4 do). So, for example, if I loop over a large array, modifying the array in <code>Vector<float>.Count</code> chunks, I need to clamp each vector result to a min and/or max bounds prior to writing that vector-sized chunk back to the array.</p>
<p>I tried doing the Clamp in a loop on the array chunk data after the Vector operations, but the performance is abysmal. It is as slow or slower than simply doing the algorithm without vectorization.</p>
<p>Is there any way that I can conceivably improve the performance of this Clamp method?</p>
<p>This is some typical code of how I tried clamping. I fill the vector with a chunk of the array, perform some vector math, write the chunk back to the array, this is all nice and speedy, but then Clamping the array chunk in a loop after just kills the vectorization performance advantage.</p>
<pre><code>int length = array.Length;
int floatcount = System.Numerics.Vector<float>.Count;
for (int i = 0; i < length; i += floatcount)
{
System.Numerics.Vector<float> arrayvector = new System.Numerics.Vector<float>(array, i);
arrayvector = System.Numerics.Vector.Multiply<float>(arrayvector, 2.0f);
// There may be different or multiple vector operations in here.
arrayvector.CopyTo(array, i);
// This is how I tried clamping the array data after the vector operation:
for (int j = 0; j < floatcount; j++)
{
if (array[i + j] > maximimum) { array[i + j] = maximimum; }
}
}
</code></pre>
<p>I'm probably being myopic and missing something really simple. That's what months of 16-hour programming days gets you. ;) Thanks for any insight.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:40:33.410",
"Id": "425160",
"Score": "0",
"body": "This sounds like an interesting question but edited code like _generalized code of how I tried clamping_ usually results in _poor_ reviews because it's very likely that you'll replay _I'm already doing this but remove that part_ etc... so it backfires in most cases. It's always best to post the origial code, however, you can add this _edited_ version as an explanation of the algorithm you are using if you think that it helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:44:25.310",
"Id": "425161",
"Score": "0",
"body": "Thanks. What I mean by \"generalized code\" is that this specific example of the code is doing a simple Vector.Multiply by 2.0f. I actually do a wide range of Add, Subtract, Multiply, and in many cases multiple vector methods, etc. The method of clamping in this code, the \"for loop\" at the end, is EXACTLY what I tried and it results in poor performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:48:14.107",
"Id": "425162",
"Score": "0",
"body": "ok, then I believe it's fine. Do you think you could provide something like a simple console-example where you are calling this from the `Main` function? In questions about performance it's good when _we_ could actually run and test it ourselves with a profiler or something - it'd be easier to compare the results and see whether the suggested improvement makes it really better ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:54:56.063",
"Id": "425163",
"Score": "1",
"body": "Sure. It won't be until tomorrow though, it's after midnight here. It won't be a menial task since the array length is vector aligned etc. And you would probably want both non-vector and vector code to compare."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:56:16.157",
"Id": "425164",
"Score": "0",
"body": "Coool, no hurry, we'll wait ;-)"
}
] | [
{
"body": "<p>Have you tried something like this:</p>\n\n<p>Create the following vector:</p>\n\n<pre><code> System.Numerics.Vector<float> maxima = new System.Numerics.Vector<float>(maximimum);\n</code></pre>\n\n<p>Then after the multiplication call:</p>\n\n<pre><code>arrayvector = System.Numerics.Vector.Min(arrayvector, maxima);\n</code></pre>\n\n<p>Here you may have to create an new vector instead of reassigning to arrayvector?</p>\n\n<hr>\n\n<p>So all in all it ends up like:</p>\n\n<pre><code> int length = array.Length;\n\n int floatcount = System.Numerics.Vector<float>.Count;\n System.Numerics.Vector<float> maxima = new System.Numerics.Vector<float>(maximimum);\n\n for (int i = 0; i < length; i += floatcount)\n {\n System.Numerics.Vector<float> arrayvector = new System.Numerics.Vector<float>(array, i);\n\n arrayvector = System.Numerics.Vector.Multiply(arrayvector, 2.0f);\n arrayvector = System.Numerics.Vector.Min(arrayvector, maxima);\n // There may be different or multiple vector operations in here.\n\n arrayvector.CopyTo(array, i);\n\n }\n</code></pre>\n\n<p>Disclaimer: I haven't tested the above, so don't hang me if it's not an improvement :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T13:06:52.443",
"Id": "425196",
"Score": "2",
"body": "In addition to this, if you want to implement a double-ended clamp, you can use the min-max definition of a clamp: `clamp(a, b, x) = max(a, min(b, x))`, where `a` is the lower bound and `b` is the upper bound."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T21:49:47.740",
"Id": "425226",
"Score": "1",
"body": "YES! You are awesome! :) It works perfect. I can't believe that I didn't think of that. I have only done one set of benchmark tests on one system, I will do a lot more profiling before I settle on the code, but initial tests look like this method will work fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T21:54:39.770",
"Id": "425227",
"Score": "1",
"body": "On my first quick profiling test, I am iterating over a floating-point array of 67,108,864 items, 268MB, and only performing a few math functions in the loop. On an AVX equipped system, release build, the standard single-threaded method takes 231310 ticks, while the vectorized method takes 104573 ticks. That is a better than doubling in performance. I will test it against the multi-threaded code and also on my AVX2 systems. AVX2 will hopefully be even better. I am running into memory bandwidth and cache performance issues at these speeds. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T21:59:22.340",
"Id": "425228",
"Score": "1",
"body": "There is one major issue that I have found in my work with the System.Numerics.Vectors methods, is *never* use Multiply<T>(Vector<T>, T), it is horribly slow. I don't know what they are doing in the code but it is the worst performing method I have tried. It is multiple times slower than non-vectored Multiply for each float. So I always use Multiply<T>(Vector<T>, Vector<T>) instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T10:05:32.033",
"Id": "425266",
"Score": "1",
"body": "@deegee it probably creates a new vector very time, but I can't seem to find the source code for these things..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T10:55:41.160",
"Id": "425275",
"Score": "1",
"body": "@VisualMelon: I think you are right: `Multiply(Vector<T>, T factor)` calls `operator *` which creates a new Vector before the operation: [source](https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/Numerics/Vector.cs) (scroll to line 2254)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T08:41:45.397",
"Id": "220038",
"ParentId": "220035",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220038",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T06:36:08.757",
"Id": "220035",
"Score": "4",
"Tags": [
"c#",
"vectors",
"vectorization"
],
"Title": "C# System.Numerics.Vector<T> Clamp"
} | 220035 |
<p>I have implemented a event aggregator for our backend. </p>
<pre><code>public class EventAggregator : IEventAggregator
{
private readonly WeakReferenceList<object> _subscribers = new WeakReferenceList<object>();
public void Subscribe(object subscriber)
{
_subscribers.Add(subscriber);
}
public Task PublishAsync<T>(T message) where T : class
{
foreach (var handler in _subscribers.OfType<IHandle<T>>())
handler.Handle(message);
var handlers = _subscribers
.OfType<IHandleAsync<T>>()
.Select(s => s.HandleAsync(message))
.Where(t => t.Status != TaskStatus.RanToCompletion)
.ToList();
if (handlers.Any()) return Task.WhenAll(handlers);
return Task.CompletedTask;
}
}
</code></pre>
<p>You can then choose to handle the events async or none async </p>
<p>None async </p>
<pre><code>public class CreatedListener : IBusinessContextListener, IHandle<SavingChangesEvent>
{
public CreatedListener(IEventAggregator eventAggregator)
{
eventAggregator.Subscribe(this);
}
public void Handle(SavingChangesEvent message)
{
foreach (var created in message.Context.Db.ChangeTracker.Entries<ICreated>().Where(c => c.State == EntityState.Added))
{
created.Entity.CreatedBy = message.Context.Username;
created.Entity.CreatedUTC = DateTime.UtcNow;
}
}
}
</code></pre>
<p>Async</p>
<pre><code>public class AzureFileStorageExternalAdapter : IExternalPartAdapter, IHandleAsync<TransactionCommitedEvent>
{
private readonly IBusinessContext _ctx;
private readonly List<CloudFile> _proccessedFiles;
public AzureFileStorageExternalAdapter(IBusinessContext ctx, IEventAggregator eventAggregator)
{
_ctx = ctx;
_proccessedFiles = new List<CloudFile>();
eventAggregator.Subscribe(this);
}
public Task<IEnumerable<byte[]>> ListResponses()
{
var folder = GetRemoteFolder($"In:{_ctx.ExecutionContext.Name}");
var files = folder.ListFilesAndDirectories()
.Select(fi => fi as CloudFile)
.Where(file => file != null)
.ToList();
_proccessedFiles.AddRange(files);
return files
.Select(async file =>
{
using (var stream = await file.OpenReadAsync())
{
using (var mem = new MemoryStream())
{
await stream.CopyToAsync(mem);
mem.Position = 0;
return mem.ToArray();
}
}
})
.WhenAll();
}
public Task HandleAsync(TransactionCommitedEvent message)
{
if (!_proccessedFiles.Any()) return Task.CompletedTask;
return _proccessedFiles
.Select(file => file.DeleteAsync())
.WhenAll();
}
}
</code></pre>
<p>Publisher has to be async even though only none async listeners are currently listenting</p>
<pre><code>public class BusinessContext : IBusinessContextController, IDisposable
{
private readonly IEventAggregator _eventAggregator;
private IDbContextTransaction _dbContextTransaction;
public BusinessContext(DbContext ctx, IEnumerable<IBusinessContextListener> ctxListeners, IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
Db = ctx;
if(ctxListeners == null) throw new ApplicationException("Do not remove this dependency, it ensures that listeners are awake");
}
public DbContext Db { get; }
public string Username { get; set; }
public ExecutionContext ExecutionContext { get; set; }
public async Task SaveChangesAsync()
{
await _eventAggregator.PublishAsync(new SavingChangesEvent(this));
await Db.SaveChangesAsync();
}
public async Task StartTransactionAsync()
{
if (_dbContextTransaction != null) return;
_dbContextTransaction = await Db.Database.BeginTransactionAsync();
}
public void Dispose()
{
_dbContextTransaction?.Dispose();
}
public Task CommitTransactionAsync()
{
_dbContextTransaction?.Commit();
return _eventAggregator.PublishAsync(new TransactionCommitedEvent());
}
public void RollbackTransaction()
{
_dbContextTransaction?.Rollback();
}
}
</code></pre>
<p>Bonus question the interface <code>IBusinessContextListener</code> is a empty markup interface that is only used to mark classes that have no other purpose than to be a event listener (Otherwise they would not be 'awake' and there Handle methods would not invoke. Solid design?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:08:26.577",
"Id": "438954",
"Score": "0",
"body": "Is the WeakReferenceList the [internal one from MS.Internal](https://referencesource.microsoft.com/#windowsbase/Shared/MS/Internal/WeakReferenceList.cs)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:54:04.670",
"Id": "438975",
"Score": "0",
"body": "I am not convinced weak references should be used here in the first place :s see guidelines: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/weak-references."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:50:38.463",
"Id": "439013",
"Score": "0",
"body": "It's a custom list"
}
] | [
{
"body": "<h3>Scheduling & Latency</h3>\n<p>One single handler could block all other handlers by performing a long-running calculation:</p>\n<pre><code>public void Handle(SavingChangesEvent message)\n{\n Thread.Sleep(10000); // long running code ..\n}\n</code></pre>\n<p>While this is the exact same behavior of the default Event Pattern in C#, you might expect an aggregator to be able to work around this - especially since the method is called <code>PublishAsync</code>. It's not the best design decision to have this method perform both synchronous <code>IHandle<T></code> and asynchronous <code>IHandleAsync<T></code> event handler notifications.</p>\n<p>In addition, if you have a single listener on <code>EventT1</code> and 1000 listeners on <code>EventT2</code>, you'd always loop all those listeners (even twice in your code) to find the listeners <code>OfType<RequestedType>()</code>. Using one container list for all listeners is something I would try to avoid. A dictionary by <code>Type</code> and its listeners is a better approach.</p>\n<h3>Thread-Safety</h3>\n<p>While <code>WeakReferenceList</code> is thread-safe when adding and removing items, enumerating the items while adding, removing items concurrently is not. You'd have to implement a custom threading mechanism that safeguards against registration during event notification.</p>\n<h3>Error-Handling</h3>\n<p>Any error in a synchronous-aware handler exits notifications early. Since the synchronous notifications take priority over the asynchronous ones, these won't even be notified. Perhaps implementing an <code>UnobservedExceptionHandler</code> could help you make a robust design.</p>\n<h3>Micro-optimisations</h3>\n<p>Filtering out <code>Where(t => t.Status != TaskStatus.RanToCompletion)</code> and returning <code>Task.CompletedTask</code> when <code>handler.Any()</code> is false, is not going to gain you much. In fact, in between checking the status and returning the completed task, the status may have already been changed. I would disregard the status and always return <code>return Task.WhenAll(handlers)</code>. Let the waiters handle the status, which is built in using <code>async</code>/<code>await</code>.</p>\n<h3>Ambiguously-defined handlers</h3>\n<p>Handlers that implement both interfaces are not able to define which of the interfaces they want to see handled. By default, both their handlers will be notified. Is this as designed or should more fine-grained registration be allowed?</p>\n<h3>Weak Reference Pattern</h3>\n<p>I am not sure using weak references is the best design decision here. According to <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/weak-references\" rel=\"nofollow noreferrer\">Microsoft</a>:</p>\n<blockquote>\n<p>Avoid using weak references as an automatic solution to memory\nmanagement problems. Instead, develop an effective caching policy for\nhandling your application's objects.</p>\n</blockquote>\n<p>And I would agree. Instead I would use registration and deregistration methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:49:02.167",
"Id": "439011",
"Score": "2",
"body": "I should remove that weak reference list, we use this aggregator on a per request lifetime using DI so it never lives longer than a request. Maintainability over performance, if we run into performance we can easily refactor for performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:49:42.993",
"Id": "439012",
"Score": "0",
"body": "I would say that is a good call :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:14:37.010",
"Id": "442780",
"Score": "1",
"body": "Got and upvote so revisited and I noticed you favor Type lookup, our IHandle interface is contravariant so you can handle a set of messages if you listen to the baseclass since OfType works with contravariances. You need to implement this with your type look up. Either by lazy lookup with IsAssignableFrom and append to type lookup, or by iterating all types in assembly at startup and add them to the lookup"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:51:40.360",
"Id": "225984",
"ParentId": "220039",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "225984",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T08:43:18.900",
"Id": "220039",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"memory-management",
"event-handling",
"async-await"
],
"Title": "Implicit Async and none async event handlers"
} | 220039 |
<p>I have an algorithm to create a version for an entity and then I save that version against below 2 entity:</p>
<p>1) Variant</p>
<p>2) Category</p>
<pre><code>interface IEntityVersion
{
string GetVersion();
}
public class EntityVersion : IEntityVersion
{
public string GetVersion()
{
return null;
}
}
public interface IVariant
{
void Process(Variant model, string connectionString);
}
public abstract class BaseVariant : IVariant
{
private readonly IEntityVersion _entityVersion = new EntityVersion();
public void Process(Variant model, string connectionString)
{
try
{
Transform();
string variantVersion = _entityVersion.GetVersion();
using (var myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
using (var transaction = myConnection.BeginTransaction())
{
try
{
VariantRepo.UpdateVariantVersion(
myConnection,
transaction, model.VariantId, variantVersion);
CategoryRepo.UpdateCategoryVariantMapping(
myConnection,
transaction, model.CategoryId, variantVersion);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
DeleteStep1Data();
}
}
}
}
catch (Exception)
{
//log error
}
}
protected abstract void DeleteStep1Data();
protected abstract void Transform();
}
public class Variant
{
public int VariantId { get; set; }
public int CategoryId { get; set; }
}
public class VariantRepo
{
public static void UpdateVariantVersion(SqlConnection sqlConnection,
SqlTransaction transaction, int variantId, string version)
{
//save logic here
}
public static void RemoveAggregateStatistics(int variantId)
{
//remove logic here from Aggregate statistics table
}
public static void RemoveAdditionStatistics(int variantId)
{
//remove logic here from Addition statistics table
}
}
public class CategoryRepo
{
public static void UpdateCategoryVariantMapping(SqlConnection sqlConnection,
SqlTransaction transaction, int categoryId, string version)
{
//save logic here
}
}
</code></pre>
<p>I have 2 derived types(<code>AggregateCalculator</code> and <code>AdditionCalculator</code>) each having their own implementation of <code>Transform</code> and <code>DeleteStep1Data</code> methods.</p>
<pre><code>public class AggregateCalculator : BaseVariant
{
protected override void DeleteStep1Data() // Is it violating SRP ?
{
VariantRepo.RemoveAggregateStatistics(int variantId);
}
protected override void Transform()
{
throw new NotImplementedException();
}
}
public class AdditionCalculator : BaseVariant
{
protected override void DeleteStep1Data()// Is it violating SRP ?
{
VariantRepo.RemoveAdditionStatistics(int variantId);
}
protected override void Transform()
{
throw new NotImplementedException();
}
}
</code></pre>
<p>I feel like the <code>Process</code> method is doing too much work and if it would be possible to hide version saving related logic behind the <code>EntityVersion</code> class so that the <code>Process</code> method looks simple.</p>
<p><code>Step1</code> and <code>Step2</code> are in sync so that if there is an error in <code>Step2</code>, I call the <code>DeleteStep1Data</code> method to delete all the data saved in <code>Step1</code>.</p>
<p>Also I feel like my 2 derived classes <code>AggregateCalculator</code> and <code>AdditionCalculator</code> are handling more than 1 responsibility, i.e. running a transformation and also deleting the data stored during the transformation process, although I am not sure if this is true or not.</p>
<p>Is there a possibility to refactor above code to improve readability and handle SRP ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T14:52:09.087",
"Id": "425205",
"Score": "2",
"body": "_// Is it violating SRP ?_ - for now it's violating Code Review's rules because this is hypothetical code and this is off-topic here. You either need to post the complete code or alternatively ask it on [Software Engineering](https://softwareengineering.stackexchange.com/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T05:43:53.933",
"Id": "425384",
"Score": "1",
"body": "@t3chb0t Someone on SO suggested me to post this question on Code review as it is most suitable here and you are saying I should post on SE.Also I have posted those code which is required for the question because posting everything will make this question very very big.Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T05:53:44.543",
"Id": "425385",
"Score": "0",
"body": "I guess that someone doesn't know how Code Review works and gave you a wrong advice. You have to ask yourself what you really want? Is it about code? Then we obviously need code, you cannot remove the most of it and expect a review beceause we cannot review what we don't see. If you, however, don't wish a code review but other concepts that are not necessarily related to the implementation then SE is the place to ask. It's your choice. Here, we require complete and working code and you're _always_ free to updte your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:07:37.807",
"Id": "425386",
"Score": "0",
"body": "@t3chb0t I have posted most of the code required to help on my question and if required any further clarification or code then I am ready to include it in my question and also there is not syntactical error in the code.So could you please remove the ONHOLD tag from this question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:09:26.377",
"Id": "425387",
"Score": "0",
"body": "_most of the code_ is not good enough on **Code** Review. Just copy/paste what you have and don't worry about the limit. It's very generous here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:29:40.450",
"Id": "425389",
"Score": "0",
"body": "@t3chb0t Ok I have updated question with all the code.Now could you please remove the onhold tag from this question please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:45:25.577",
"Id": "425390",
"Score": "2",
"body": "There are still a lot of placeholders like `//save logic here` or `NotImplementedException`. What happened to that code?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T10:42:22.813",
"Id": "220044",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
".net"
],
"Title": "Way to hide logic behind class for better readability of method and refactor class to follow SRP"
} | 220044 |
<p><a href="https://leetcode.com/problems/find-bottom-left-tree-value/" rel="nofollow noreferrer">https://leetcode.com/problems/find-bottom-left-tree-value/</a></p>
<p>Given a binary tree, find the leftmost value in the last row of the tree.</p>
<p>Example 1:
Input:</p>
<pre><code> 2
/ \
1 3
</code></pre>
<p>Output:
1
Example 2:
Input:</p>
<pre><code> 1
/ \
2 3
/ / \
4 5 6
/
7
</code></pre>
<p>Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.</p>
<p>Please review for performance. Thanks </p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
/// <summary>
/// https://leetcode.com/problems/find-bottom-left-tree-value/
/// </summary>
[TestClass]
public class FindBottomLeftTreeValue
{
//Input:
// 2
// / \
// 1 3
[TestMethod]
public void SmallTreeTest()
{
TreeNode root = new TreeNode(2);
root.left = new TreeNode(1);
root.right = new TreeNode(3);
Assert.AreEqual(1, FindBottomLeftValue(root));
}
//Input:
// 1
// / \
// 2 3
// / / \
// 4 5 6
// /
// 7
[TestMethod]
public void BigTreeTest()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.left = new TreeNode(4);
root.right = new TreeNode(3);
root.right.left = new TreeNode(5);
root.right.right = new TreeNode(6);
root.right.left.left = new TreeNode(7);
Assert.AreEqual(7, FindBottomLeftValue(root));
}
public int FindBottomLeftValue(TreeNode root)
{
if (root == null)
{
throw new NullReferenceException("root is empty");
}
Queue<TreeNode> Q = new Queue<TreeNode>();
Q.Enqueue(root);
int left = root.val;
while (Q.Count > 0)
{
// we always push the left node first then we peek, so the first item is the most left
//for the entire level of the tree
int qSize = Q.Count;
left = Q.Peek().val;
for (int i = 0; i < qSize; i++)
{
var current = Q.Dequeue();
if (current.left != null)
{
Q.Enqueue(current.left);
}
if (current.right != null)
{
Q.Enqueue(current.right);
}
}
}
return left;
}
}
/*
Definition for a binary tree node.*/
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Please review for performance.</p>\n</blockquote>\n\n<p>The performance looks fine to me. Some key observations:</p>\n\n<ul>\n<li>It's clear that all nodes must be visited to compute the correct answer, so the solution cannot be better than <span class=\"math-container\">\\$O(n)\\$</span> time.</li>\n<li>Traversing in level order as you did will require as much additional space as the number of nodes on the most dense level.</li>\n<li>Traversing depth first would require as much additional space as the longest path from root to leaf.</li>\n</ul>\n\n<p>Without knowing in advance the shape of the tree (whether it's deep or wide),\nand given <code>TreeNode</code> as defined and no additional helper data structures,\nit's not possible to tell whether DFS or BFS is better.\nSo they are both equally fine, as neither uses space excessively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T18:22:55.603",
"Id": "220751",
"ParentId": "220049",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220751",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T10:59:57.657",
"Id": "220049",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"breadth-first-search"
],
"Title": "Leetcode: Find-bottom-left-tree-value"
} | 220049 |
<p>I've written shortcuts for the Three.js library. This is mainly for my personal use. I'm not that good with remembering the complex name of the Three.js library, so these shortcuts are meant to make it easier. I'm looking for code efficiency and compactness, since I know compactness is a big concern for javascript files. The comments are all for myself, so even if they seem verbose, they help me remember how to use the functions. Thank you in advance for any suggestions/improvements.</p>
<pre><code>/*
* Shortcuts for Three.js object creation
*/
/*
* Creates a scene with a sepcific background color
* Example Usage:
* var scene = createScene(0xffffff);
*/
function createScene(color) {
let scene = new THREE.Scene();
scene.background = new THREE.Color(color);
return scene;
}
/*
* Creates a camera for the scene
* Example usage:
* var camera = createCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
*/
function createCamera(fov, aspect, near, far) {
let camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
}
/*
* Creates a cube with a mesh(color) and geometry
* Example Usage:
* var cube = createCube(7, 7, 7, 0x005500);
*/
function createCube(width, height, depth, c) {
let geometry = new THREE.BoxGeometry(width, height, depth);
let material = new THREE.MeshBasicMaterial({color: c});
let cube = new THREE.Mesh(geometry, material);
return cube;
}
/*
* Creates a WebGLRenderer, with a given width and height
* Example Usage:
* var renderer = createRenderer(window.innerWidth, window.innerHeight);
* document.body.appendChild(renderer.domElement);
*/
function createRenderer(width, height) {
let renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
return renderer;
}
/*
* Usage Example for all the functions:
*
* var scene = createScene(0xffffff);
* var camera = createCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
* var renderer = createRenderer(window.innerWidth, window.innerHeight);
* document.body.appendChild(renderer.domElement);
* var cube = createCube(7, 7, 7, 0x005500);
* scene.add(cube);
*
* // User can write rest of implementation //
*/
</code></pre>
| [] | [
{
"body": "<h2>Style points</h2>\n<ul>\n<li><p>Why assign a variable when the reference is immediately dropped on returning from the function. In function <code>createCamera</code> the variable <code>let camera = new THREE.PerspectiveCamera(fov, aspect, near, far);</code> is never used???</p>\n</li>\n<li><p>Use <code>const</code> for variables that do not change.</p>\n</li>\n<li><p>Name arguments when possible such that you can use object property shorthand to put them in an object. Eg you named color <code>col</code> and then create an object <code>{ color: col }</code> but if you named the argument <code>color</code> you could then create the same object as <code>{ color }</code></p>\n</li>\n</ul>\n<h2>Building a framework</h2>\n<p>You will be better of putting all this functionality into an object, keeping the global namespace free of clutter and providing a framework that you can build upon as the needs arise.</p>\n<h2>Example</h2>\n<pre><code>const utils = {\n create: {\n material(color) { return new THREE.MeshBasicMaterial({color}) },\n camera(...args) { return new THREE.PerspectiveCamera(...args) },\n cube(width, height, depth, color) {\n return new THREE.Mesh(\n new THREE.BoxGeometry(width, height, depth), \n utils3.create.material(color)\n );\n },\n scene(color) {\n const scene = new THREE.Scene();\n scene.background = new THREE.Color(color);\n return scene;\n },\n renderer(width, height) {\n const renderer = new THREE.WebGLRenderer();\n renderer.setSize(width, height);\n return renderer;\n },\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T07:37:48.887",
"Id": "220082",
"ParentId": "220052",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220082",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T14:22:43.017",
"Id": "220052",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Three.js Shortcuts"
} | 220052 |
<p>I would like to hear opinions from people with bigger experience about KeyboardTeacher application. It fetches text from a text file, and shows the first line in console. If user types the whole line correctly, then it shows the next line from the file, and so on till the end of the text file. Otherwise it shows the first bad index and show again line which has been written badly. At the end it shows the result in seconds and save the result in the text file. </p>
<p>I added ranking system by which people can see who was the fastest. </p>
<p>I would like to know if I can change there anything, improve etc.</p>
<p>Here are some of the main classes. The entire project is on GitHub: <a href="https://github.com/must1/KeyBoardTeacher/tree/bb2bbaffda3863db570544b7bb70b7631a3d9a84" rel="nofollow noreferrer">https://github.com/must1/KeyBoardTeacher</a></p>
<p>Main: </p>
<pre><code>import conditionchecker.ConditionChecker;
import conditionchecker.ConditionCheckerService;
import contentfile.ContentFileRetriever;
import contentfile.ContentFileRetrieverService;
import rankingsystem.RankingSystemFacade;
import rankingsystem.RankingSystemService;
import view.GameMessages;
import view.KeyBoardTeacherView;
public class Main {
public static void main(String[] args) {
ConditionChecker conditionChecker = new ConditionCheckerService();
ContentFileRetriever contentFileRetriever = new ContentFileRetrieverService();
GameMessages gameMessages = new KeyBoardTeacherView();
RankingSystemService rankingSystemService = new RankingSystemService(contentFileRetriever);
RankingSystemFacade rankingSystemFacade = new RankingSystemFacade(rankingSystemService, gameMessages);
KeyBoardTeacherEngine keyBoardTeacherEngine = new KeyBoardTeacherEngine(contentFileRetriever,
conditionChecker, gameMessages, rankingSystemFacade);
keyBoardTeacherEngine.startKeyBoardTeacherEngine();
}
}
</code></pre>
<p>KeyboardEngine</p>
<pre><code>import conditionchecker.ConditionChecker;
import contentfile.ContentFileRetriever;
import rankingsystem.RankingSystemFacade;
import view.GameMessages;
import java.util.Arrays;
import java.util.Scanner;
class KeyBoardTeacherEngine {
private static final int NANOSECONDS_IN_SECOND = 1000000000;
private ConditionChecker conditionChecker;
private ContentFileRetriever contentFileRetriever;
private GameMessages gameMessages;
private RankingSystemFacade rankingSystemFacade;
private Scanner scanner;
KeyBoardTeacherEngine(ContentFileRetriever contentFileRetriever, ConditionChecker conditionChecker,
GameMessages gameMessages, RankingSystemFacade rankingSystemFacade) {
this.contentFileRetriever = contentFileRetriever;
this.conditionChecker = conditionChecker;
this.gameMessages = gameMessages;
this.rankingSystemFacade = rankingSystemFacade;
scanner = new Scanner(System.in);
}
void startKeyBoardTeacherEngine() {
String name = getName();
String[] contentFileArray = contentFileRetriever.getContent(getPathFileOfGame());
String lineGivenByUser;
long startTime = System.nanoTime();
for (String modelLine : contentFileArray) {
do {
System.out.println(modelLine);
lineGivenByUser = scanner.nextLine();
if (modelLine.equals(lineGivenByUser)) {
break;
}
for (int index = 0; index < modelLine.length(); index++) {
int modelLineNumber = Arrays.asList(contentFileArray).indexOf(modelLine);
if (conditionChecker.checkIfCharactersAreUnequal(modelLine.charAt(index), lineGivenByUser.charAt(index))) {
gameMessages.executeBadIndexMessage(index);
break;
} else if ((lineGivenByUser.length() < contentFileArray[modelLineNumber].length())) {
if (conditionChecker.checkIfIndexEqualsToLengthOfLineGivenByUser(index, lineGivenByUser)) {
gameMessages.executeMessageOfCaseWhenGivenLineIsShorterThanProper(lineGivenByUser);
break;
}
} else if ((lineGivenByUser.length() > contentFileArray[modelLineNumber].length())) {
gameMessages.executeMessageOfCaseWhenGivenLineIsLongerThanProper();
break;
}
}
}
while (true);
}
long endTime = System.nanoTime();
long durationTimeInSeconds = (endTime - startTime) / NANOSECONDS_IN_SECOND;
rankingSystemFacade.executeRankingSystemProcess(name, durationTimeInSeconds);
gameMessages.executeCongratulationsAboutEndingGame(durationTimeInSeconds, name);
}
private String getPathFileOfGame() {
gameMessages.executeGettingContentPathMessage();
return scanner.nextLine();
}
private String getName() {
gameMessages.askAboutName();
return scanner.nextLine();
}
}
</code></pre>
<p>KeyboardTeacherView - it implements GameMessage which is of course interface.</p>
<pre><code>package view;
public class KeyBoardTeacherView implements GameMessages {
@Override
public void executeCongratulationsAboutEndingGame(long durationTimeInSeconds, String name) {
System.out.println("Congratulations " + name + ", you have ended in " + durationTimeInSeconds + " seconds.");
}
@Override
public void executeBadIndexMessage(int index) {
System.out.println("Bad " + index + " index. (starting from 0)");
}
@Override
public void executeGettingContentPathMessage() {
System.out.println("Provide path of the file in which we can find text for the game(if the file is in the project" +
" folder, then just write a name of the file) i.e tekst.txt");
}
@Override
public void executeMessageOfCaseWhenGivenLineIsShorterThanProper(String lineGivenByUser) {
System.out.println("Bad character at " + lineGivenByUser.length() + " index. (starting from 0)");
}
@Override
public void askAboutName() {
System.out.println("Please, put your name");
}
@Override
public void executeMessageOfCaseWhenGivenLineIsLongerThanProper() {
System.out.println("Your line is longer than proper, please try again!");
}
@Override
public void executeMessageAboutPlaceInRankingOfPlayer(int position, int size) {
System.out.println("You are " + position + " of " + size + " players in ranking!!!!");
}
@Override
public void executeGettingRankingFilePathMessage() {
System.out.println("Provide path of the ranking file(if the file is in the project folder, " +
"then just write a name of the file) i.e ranking.txt");
}
}
</code></pre>
<p>RankingSystem</p>
<pre><code>package rankingsystem;
import contentfile.ContentFileRetriever;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class RankingSystemService {
private static final int FIRST_PART = 0;
private static final int SECOND_PART = 1;
private ContentFileRetriever contentFileRetriever;
public RankingSystemService(ContentFileRetriever contentFileRetriever) {
this.contentFileRetriever = contentFileRetriever;
}
int findGivenNameInRanking(String name, Map<String, Long> sortedRankingArray) {
return new ArrayList<>(sortedRankingArray.keySet()).indexOf(name);
}
Map<String, Long> getSortedLinkedHashMappedRankingArray(String[] rankingArray) {
return Arrays
.stream(rankingArray)
.map(it -> it.split("\\s+"))
.collect(Collectors.toMap(it -> it[FIRST_PART], it -> Long.valueOf(it[SECOND_PART])))
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
}
String[] retrieveRankingData(String rankingPathFile) {
return contentFileRetriever.getContent(rankingPathFile);
}
void overwriteFileWithGivenResult(String name, long timeOfFinishingGame, String rankingPathFile) {
try (FileWriter writer = new FileWriter(rankingPathFile, true);
BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
bufferedWriter.write(name + " " + timeOfFinishingGame);
bufferedWriter.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>RankingSystemFacade</p>
<pre><code>package rankingsystem;
import view.GameMessages;
import java.util.Map;
import java.util.Scanner;
public class RankingSystemFacade {
private RankingSystemService rankingSystemService;
private GameMessages gameMessages;
private Scanner scanner;
public RankingSystemFacade(RankingSystemService rankingSystem, GameMessages gameMessages) {
this.rankingSystemService = rankingSystem;
this.gameMessages = gameMessages;
scanner = new Scanner(System.in);
}
public void executeRankingSystemProcess(String name, long timeOfFinishGame) {
String rankingPathFile = getPathOfRankingFile();
rankingSystemService.overwriteFileWithGivenResult(name, timeOfFinishGame,rankingPathFile);
String[] rankingArray = rankingSystemService.retrieveRankingData(rankingPathFile);
Map<String, Long> linkedSortedHashMappedRankingArray = rankingSystemService.getSortedLinkedHashMappedRankingArray(rankingArray);
int position = rankingSystemService.findGivenNameInRanking(name, linkedSortedHashMappedRankingArray);
gameMessages.executeMessageAboutPlaceInRankingOfPlayer(++position, linkedSortedHashMappedRankingArray.size());
}
private String getPathOfRankingFile()
{
gameMessages.executeGettingRankingFilePathMessage();
return scanner.nextLine();
}
}
</code></pre>
<p>ContentFileRetiever:</p>
<pre><code>package contentfile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ContentFileRetrieverService implements ContentFileRetriever {
@Override
public String[] getContent(String pathName) {
try (Stream<String> contentFileStream = Files.lines(Paths.get(pathName))) {
return contentFileStream.toArray(String[]::new);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
</code></pre>
<p>ConditionCheckerService</p>
<pre><code>package conditionchecker;
public class ConditionCheckerService implements ConditionChecker {
@Override
public boolean checkIfCharactersAreUnequal(char firstCharacter, char secondCharacter) {
return firstCharacter != secondCharacter;
}
//if index+1 equals to length of line given by user (which is shorter than proper),
// then we know that there is a bad index at the end of given line.
@Override
public boolean checkIfIndexEqualsToLengthOfLineGivenByUser(int index, String lineGivenByUser) {
return index + 1 == lineGivenByUser.length();
}
}
</code></pre>
<p>ContentFileServiceTest</p>
<pre><code>package contentfile;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static org.junit.Assert.*;
public class ContentFileRetrieverServiceTest {
private ContentFileRetriever contentFileRetriever = new ContentFileRetrieverService();
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void getContentFile() throws IOException {
File textFile = tempFolder.newFile("testText.txt");
String pathFile = textFile.getPath();
FileWriter fileWriter = new FileWriter(textFile);
fileWriter.write("Line1 a\nLine2 b c\nLine 3");
fileWriter.close();
String[] testedContent = contentFileRetriever.getContent(pathFile);
String[] expected = {"Line1 a", "Line2 b c", "Line 3"};
textFile.deleteOnExit();
assertArrayEquals(expected, testedContent);
}
@Test(expected = IllegalArgumentException.class)
public void getContentFileWhenFileDoesNotExist() {
String pathFile = "unknown";
String[] testedContent = contentFileRetriever.getContent(pathFile);
}
}
</code></pre>
<p>RankingSystemServiceTest</p>
<pre><code>package rankingsystem;
import contentfile.ContentFileRetrieverService;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class RankingSystemServiceTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private ContentFileRetrieverService contentFileRetrieverService = new ContentFileRetrieverService();
private RankingSystemService rankingSystemService = new RankingSystemService(contentFileRetrieverService);
@Test
public void getLinkedHashMappedRankingArray() {
String[] testedArray = {"Piotr 3", "Anna 1", "Andrzej 2"};
Map<String, Long> linkedSortedHashMappedRankingArray = rankingSystemService.getSortedLinkedHashMappedRankingArray(testedArray);
Map<String, Long> expectedLinkedSortedHashMappedRankingArray = new LinkedHashMap<>();
expectedLinkedSortedHashMappedRankingArray.put("Anna", 1L);
expectedLinkedSortedHashMappedRankingArray.put("Andrzej", 2L);
expectedLinkedSortedHashMappedRankingArray.put("Piotr", 3L);
int actualPosition = rankingSystemService.findGivenNameInRanking("Piotr", linkedSortedHashMappedRankingArray);
int exceptedPosition = rankingSystemService.findGivenNameInRanking("Piotr", expectedLinkedSortedHashMappedRankingArray);
assertEquals(exceptedPosition, actualPosition);
}
@Test
public void overwriteFileWithGivenResult() throws IOException {
File rankingFile = tempFolder.newFile("rankingText.txt");
String rankingFilePath = rankingFile.getPath();
String[] actualResultBeforeOverwriting = rankingSystemService.retrieveRankingData(rankingFilePath);
String[] expectedResultBeforeOverwriting = {};
assertArrayEquals(expectedResultBeforeOverwriting, actualResultBeforeOverwriting);
rankingSystemService.overwriteFileWithGivenResult("Piotr", 1L, rankingFilePath);
String[] afterOverwriting = rankingSystemService.retrieveRankingData(rankingFilePath);
String[] expectedResultAfterOverwriting = {"Piotr 1"};
rankingFile.deleteOnExit();
assertArrayEquals(expectedResultAfterOverwriting, afterOverwriting);
}
}
</code></pre>
| [] | [
{
"body": "<p><strong>Here are some minor suggestions relating to Java/programming standards etc:</strong></p>\n\n<p><code>ConditionChecker</code> Might not be a good name as it's not very descriptive. However you should be able to remove this entirely as the two methods are very simple and you don't really need a method for either of them.</p>\n\n<p>Negative names such as <code>checkIfCharactersAreUnequal</code> can lead to double negatives. For example, to check if the characters are unequal you'd have to check if they are not unequal. I'd suggest either refactoring the method, or removing it entirely since it simply checks if two characters are equal.</p>\n\n<p><code>checkIfIndexEqualsToLengthOfLineGivenByUser</code> \nIf you ever use this method to check a different String, you'd have to rename the method. When naming public methods, you should only think in terms of the method itself. In other words, the ConditionCheckerService class doesn't care if it's a String given by the user or not. Also try to use explanatory names, instead of <code>check</code> use <code>is</code>. For example, <code>isIndexEqualToLength(int, String)</code></p>\n\n<p><code>KeyBoardTeacherEngine</code> \n<code>startKeyboardTeacherEngine</code> should be public. Currently it's in the same package as the calling method <code>Main</code>, but I don't think it actually relates to Main.</p>\n\n<p><strong>General suggestions:</strong></p>\n\n<p>Consider having the user able to select the path of the file via a 'file chooser'. Example being that File Explorer like window that pops up to allow the user to select a location.</p>\n\n<p>Instead of displaying the index of the failed character, display the failed line with a '^' underneath the unlatching character.</p>\n\n<p>Different modes, such as allowing the user to make mistakes but keeping a record throughout the duration of the test, and printing the results at the end. You could look at online typing tests for ideas.</p>\n\n<p>In your console: <code>Provide path of the file in which we can find text for the game(if the file is in the project folder, then just write a name of the file) i.e tekst.txt</code></p>\n\n<p>Change the example file name to \"text.txt\" or \"file.txt\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T08:49:55.483",
"Id": "425323",
"Score": "0",
"body": "About `ConditionChecker`.1) I agree that I should remove `checkIfCharactersAreUnequal` as it is simple, and it's done.I do not understand suggestion about `checkIfIndexEqualsToLengthOfLineGivenByUser `. Should it be named as `checkIfIndexEqualsToLengthOfLine` ? Also why `startKeyboardTeacherEngine ` should be public? It is not public as I dont have to make it public as it is in the same package."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T08:54:44.653",
"Id": "425324",
"Score": "0",
"body": "Could you explain suggestions at General Suggestions? I mean, what do you mean by file chooser and why it is better? \"Different modes, such as allowing the user to make mistakes but keeping a record throughout.\" what do you mena by that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T14:26:45.650",
"Id": "425349",
"Score": "0",
"body": "@pipilam Yeah or maybe `isEqualToSize`. I'll update my answer. I believe `startKeyboardTeacherEngine` should be public since it does not relate to the Main method. A file chooser opens a file-explorer like window for the user to select a file, it's easier to use than manually entering the file path"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T14:58:42.780",
"Id": "425351",
"Score": "0",
"body": "Okay, got it. Anything else? Do you think that this code is in good quality? Btw. Is there any file chooser that I can use or I need to make it on my own?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T01:31:42.573",
"Id": "220112",
"ParentId": "220054",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T15:19:50.363",
"Id": "220054",
"Score": "4",
"Tags": [
"java"
],
"Title": "KeyboardTeacher"
} | 220054 |
<p>I'm working on FFI wrapper for SDL2 library in Racket. The library includes several variadic functions (e.g. <a href="https://wiki.libsdl.org/SDL_SetError" rel="nofollow noreferrer">SDL_SetError</a>, <a href="https://wiki.libsdl.org/SDL_LogMessage" rel="nofollow noreferrer">SDL_LogMessage</a> etc); Racket FFI does not have straight way for importing those, but there's a workaround showcased <a href="https://github.com/racket/racket/blob/2d4f3e2ac995b7bcdd896fc6a92fa83050b71d79/pkgs/racket-doc/ffi/examples/c-printf.rkt#L20" rel="nofollow noreferrer">here</a>. Despite having little experience with Racket macros, I've decided to create one from the linked code to avoid excess code duplication. Here's my code:</p>
<pre class="lang-lisp prettyprint-override"><code>#lang racket
(require (for-syntax racket/syntax)
(for-syntax racket/format)
ffi/unsafe)
(define sdl-lib (ffi-lib "libSDL2-2.0" '("0" #f)))
(define-syntax (define-vararg-func stx)
(syntax-case stx ()
[(_ name (arg-types ...) ret-type)
(with-syntax*
([name-str (~a (syntax->datum #'name))]
[arglist
(map
(lambda (arg)
(gensym (syntax->datum arg)))
(syntax->list #'(arg-types ...)))]
[full-arglist (append (syntax->list #'arglist) 'args)]
[final-call (append '(apply fun) (syntax->list #'arglist) '(args))])
#'(define name
(let ([interfaces (make-hash)])
(lambda full-arglist
(define itypes
(append (list arg-types ...)
(map (lambda (x)
(cond
[(and (integer? x) (exact? x)) _int]
[(and (number? x) (real? x)) _double*]
[(string? x) _string]
[(bytes? x) _bytes]
[(symbol? x) _symbol]
[else
(error
"don't know how to deal with ~e" x)]))
args)))
(let ([fun (hash-ref
interfaces itypes
(lambda ()
(let ([i (get-ffi-obj
name-str sdl-lib
(_cprocedure itypes ret-type))])
(hash-set! interfaces itypes i)
i)))])
final-call)))))]))
;; macro usage
(define-vararg-func SDL_SetError (_string) _int)
(SDL_SetError "test %s %d" "test" 42)
(define SDL_GetError (get-ffi-obj "SDL_GetError" sdl-lib (_cprocedure '() _string)))
(displayln (SDL_GetError))
</code></pre>
<p>I'd love any feedback on the macro and suggestions on how to improve its readability.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T15:27:56.873",
"Id": "220055",
"Score": "3",
"Tags": [
"macros",
"sdl",
"variadic",
"racket",
"native-code"
],
"Title": "Racket macro for variadic FFI"
} | 220055 |
<p>I need to make a program that receives a set of currencies and tests which values between 1 and 10,000 units can <strong>not</strong> be produced with these currencies.</p>
<p>The program must have 2 input data:</p>
<blockquote>
<ol>
<li>The number n of existing coin values, with n between 1 and 10.</li>
<li>The values a1, a2, ..., an of these currencies.</li>
</ol>
</blockquote>
<p>The program should read this data and determine how many values between 1 and 10000 currency units can not be achieved using these currencies.</p>
<p>For example, if we wanted to provide the data on some existing currencies we would have the following entry:</p>
<blockquote>
<p><strong>1</strong></p>
<p><strong>5</strong></p>
<p><strong>10</strong></p>
<p><strong>25</strong></p>
<p><strong>50</strong></p>
<p><strong>100</strong></p>
</blockquote>
<p><strong>Of course, since this system supplies one cent, all values can be obtained.</strong></p>
<p>I would like to know how I can improve the performance of my code or some part that is poorly written.</p>
<pre class="lang-java prettyprint-override"><code>import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;
public class CoinChallange {
private static int [] coins = {5, 11, 13, 23, 29};
private static int [] numbers;
private static int [] quantity = { 0, 0, 0, 0, 0};
private static int i, n, a, b, c, d, e, sum;
public static void main(String[] args)
{
long start = System.currentTimeMillis();
numbers = new int[10001];
i = 0;
for (n = 0; n <= 10000; n++) {
numbers[n] = n;
}
for ( quantity[0] = 0; quantity[ 0 ] <= 2000; quantity[0]++ ) {
for ( quantity[1] = 0; quantity[ 1 ] <= 2000; quantity[1]++ ) {
for ( quantity[2] = 0; quantity[ 2 ] <= 2000; quantity[2]++ ) {
for ( quantity[3] = 0; quantity[ 3 ] <= 2000; quantity[3]++ ) {
for ( quantity[4] = 0; quantity[ 4 ] <= 2000; quantity[4]++ ) {
System.out.println( " " + quantity[0] + " " + quantity[1] + " " + quantity[2] + " " + quantity[3] + " " + quantity[4] );
sum = quantity[0]*coins[0]+
quantity[1]*coins[1]+
quantity[2]*coins[2]+
quantity[3]*coins[3]+
quantity[4]*coins[4];
if ( sum <= 10000 ) {
numbers[ sum ] = -1;
}
}
}
}
}
}
for (n = 1; n <= 10000; n++) {
if ( numbers[n] > 0 ) {
System.out.println( numbers[n] );
}
}
long end = System.currentTimeMillis();
System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start)));
}
}
</code></pre>
<p>I get to the right result, but it is taking a long time, I believe my logic is very bad.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T04:59:12.097",
"Id": "425240",
"Score": "1",
"body": "`import Vector`? Your teacher or textbook must be living in the past. We don't use `Vector` anymore since Java 1.2 has been released, which was in 1998."
}
] | [
{
"body": "<p>Your code looks frighteningly slow because of the 5 nested <code>for</code> loops, and indeed it is.</p>\n\n<p>To find an efficient algorithm, you should switch off the computer, take out a sheet of paper and solve the following task on paper:</p>\n\n<blockquote>\n <p>Given an infinite amount of coins labelled 5, 7, 16, which amounts between 1 and 100 can be composed?</p>\n</blockquote>\n\n<p>While you solve that task, ask yourself in every step:</p>\n\n<ul>\n<li><em>what</em> am I doing?</li>\n<li><em>why</em> do I do this?</li>\n<li>what do I want to <em>achieve</em>?</li>\n<li>can I formulate a <em>general rule</em> for this that sounds reasonable, appropriate for the task?</li>\n</ul>\n\n<p>Your current code counts up to 2000 several times. In this manual task there is no point counting up to 2000. This alone makes your algorithm more specialized than it needs to.</p>\n\n<p>Essentially your code should be defined in a function like this:</p>\n\n<pre><code>/**\n * @return the amounts between min and max that are <i>not</i> composable\n * from an infinite supply of coins of the given values.\n */\npublic static BitSet uncomposable(int min, int max, List<Integer> coinValues) {\n …\n}\n</code></pre>\n\n<p>In that code, neither the number 100 nor 10000 nor 2000 must appear.\nThere should be at most 2 nested loops.\nHow exactly the code looks like depends on how you solved the task on paper.\nI'm sure you won't choose a time-consuming algorithm when having to do this task manually.</p>\n\n<p>Bonus question: is there a limit beyond which <em>all</em> amounts are composable? That could be used to stop the computation early, which is a nice optimization. Try with these test cases:</p>\n\n<ul>\n<li>{1}: the limit is 0, obviously</li>\n<li>{2}: there's no limit since only even numbers are covered</li>\n<li>{2, 4, 6}: …</li>\n<li>{3, 5}: …</li>\n<li>{1, 7, 14}: …</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T04:46:26.903",
"Id": "220075",
"ParentId": "220056",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220075",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T16:24:40.080",
"Id": "220056",
"Score": "5",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "Find amounts that cannot be composed using the given coins"
} | 220056 |
<h1>Design</h1>
<p>My desired outcome is as follows:</p>
<ol>
<li><p>S3 event triggers Lambda Function <code>startTextractStateMachine</code></p>
</li>
<li><p>Lambda Function <code>startTextractStateMachine</code> kicks off State Machine <code>textractStepFunc</code> execution (AWS Step Functions)</p>
</li>
<li><p>State Machine <code>textractStepFunc</code> starts with Lambda Function <code>callTextract</code>; calls Textract async command to start process</p>
</li>
<li><p>Output of Textract command is attached to SQS queue <code>TextractSQS</code></p>
</li>
<li><p>SQS queue output triggers Lambda Function <code>getTextractOutput</code></p>
</li>
<li><p>Lambda Function <code>getTextractOutput</code> publishes message to SNS Topic</p>
</li>
<li><p>SNS Topic triggers final Lambda Function <code>parseTextractOutput</code> via subscription</p>
</li>
<li><p>Done</p>
</li>
</ol>
<h1>Implementation</h1>
<p>I made this system work <em>without</em> any AWS Step Functions initially, but realized that I needed more control over retry/failure of the individual Lambda Functions (especially <code>callTextract</code>), so I've tried to move the system to AWS Step Functions <em>and</em> the Serverless Framework at the same time.</p>
<p>I've come to realize it was harder than I thought it would be. I keep running into roadblocks with the Serverless Framework.</p>
<p>I used several guides, blog posts and Github issues (<a href="https://serverless.com/blog/how-to-manage-your-aws-step-functions-with-serverless/" rel="nofollow noreferrer">here</a>, <a href="https://medium.com/@mebnoah/aws-step-functions-serverless-framework-752cce8f29fd" rel="nofollow noreferrer">here</a> and <a href="https://github.com/DavidWells/serverless-workshop/blob/master/lessons-code-complete/events/step-functions/serverless.yml" rel="nofollow noreferrer">here</a>) to reach this point, but am permanently stuck.</p>
<h2>Serverless Setup</h2>
<p>I've left out much of my Design ideas and simply need to have the S3 event trigger when a file is added to the Bucket.</p>
<p>Here is my configuration file:</p>
<pre><code># serverless.yml
service: textract-service
provider:
name: aws
runtime: python3.7
timeout: 10
region: us-east-1
environment:
STATE_MACHINE_ARN: ${self:resources.Outputs.TextractStepFunctions.Value}
iamRoleStatements:
- Effect: "Allow"
Action:
- "s3:PutObject"
- "states:*"
Resource:
Fn::Join:
- ""
- - "<the-chumiest-bucket's ARN> or *"
- ${self:resources.Outputs.TextractStepFunctions.Value}
plugins:
- serverless-plugin-existing-s3
- serverless-step-functions
- serverless-pseudo-parameters
layers:
boto3Layer:
package:
artifact: boto3_layer.zip
allowedAccounts:
- "*"
functions:
startTextractStateMachine:
handler: src/start_textract_state_machine.lambda_handler
role: arn:...lambda-s3-role
layers:
- {Ref: Boto3LayerLambdaLayer}
events:
- existingS3:
bucket: the-chumiest-bucket
events:
- s3:ObjectCreated:*
rules:
- prefix: input1/
- suffix: .pdf
- existingS3:
bucket: the-chumiest-bucket
events:
- s3:ObjectCreated:*
rules:
- prefix: input2/
- suffix: .pdf
callTextract:
handler: src/call_textract.lambda_handler
role: arn:...lambda-s3-role
layers:
- {Ref: Boto3LayerLambdaLayer}
getTextractOutput:
handler: src/get_textract_output.lambda_handler
role: arn:...lambda-s3-role
layers:
- {Ref: Boto3LayerLambdaLayer}
parseTextractOutput:
handler: src/parse_textract_output.lambda_handler
role: arn:...lambda-s3-role
layers:
- {Ref: Boto3LayerLambdaLayer}
stepFunctions:
stateMachines:
textractStepFunc:
name: TextractStepFunctions
definition:
StartAt: StartTextractStateMachine
States:
StartTextractStateMachine:
Type: Task
Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-startTextractStateMachine"
Next: CallTextract
CallTextract:
Type: Task
Resource: "arn:aws:lambda:#{AWS::Region}:#{AWS::AccountId}:function:#{AWS::StackName}-callTextract"
End: true
resources:
Outputs:
TextractStepFunctions:
Description: The ARN of the state machine
Value:
Ref: TextractStepFunctions
</code></pre>
<p>How I deploy it:</p>
<pre><code>sls deploy -v && sls s3deploy
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T16:41:27.943",
"Id": "220057",
"Score": "1",
"Tags": [
"amazon-web-services",
"yaml"
],
"Title": "AWS Lambda stack definition YAML"
} | 220057 |
<p>I am fairly new to c++ and am attempting to write a simple 2D game engine. I am currently working on my object model: a pure component system, similar to that described in the Data Locality chapter in <a href="https://gameprogrammingpatterns.com/data-locality.html" rel="nofollow noreferrer">Game Programming Patterns</a>, whereby the components are fixed types, each stored in a separate array in the game world class. My current code looks a bit like this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#define SID(str) HashString(str)
typedef unsigned long long StringID;
// Simple FNV string hash.
StringID HashString(const char* str) {
const unsigned int fnv_prime = 0x811C9DC5;
unsigned int hash = 0;
unsigned int i = 0;
unsigned int len = strlen(str);
for (i = 0; i < len; i++) {
hash *= fnv_prime;
hash ^= (str[i]);
}
return hash;
}
// Component base class
class Component
{
public:
static const int MAX_COMPONENTS = 10;
Component() {};
virtual ~Component() {};
virtual void Update() = 0;
StringID mID;
};
// Basic 2D vector.
struct Vec2 {
float x;
float y;
};
// Component for storing world position.
class TransformComponent : public Component
{
public:
TransformComponent() {}
TransformComponent(float x, float y) {
Vec2 mPosition = { x, y };
}
virtual ~TransformComponent() {};
virtual void Update() { /* No need to update- only to store data */ };
private:
Vec2 mPosition;
};
// A struct for storing components in a contiguous way.
struct Components
{
int CurrentTransformComponents = 0;
TransformComponent* TransformComponents = new TransformComponent[Component::MAX_COMPONENTS];
};
// Variarg function to add all listed components
template <typename T>
inline void AddComponents(StringID gameObjectID, T component) {
Application* app = Application::GetApplication();
std::cout << "Adding component..." << std::endl;
// Ugly placement of componet in array :)
if (typeid(T) == typeid(TransformComponent)) {
component.mID = gameObjectID;
// Add component to the correct place in the array;
app->mComponents.TransformComponents[app->mComponents.CurrentTransformComponents] = component;
++app->mComponents.CurrentTransformComponents;
}
}
template <typename Arg, typename ... Args>
inline void AddComponents(StringID gameObjectID, Arg first, Args ... args) {
AddComponents(gameObjectID, first);
AddComponents(gameObjectID, args...);
}
// Adds componets AND returns ID.
template <typename ... Args>
inline StringID CreateGameObject(const char* name, Args ... args) {
std::cout << "Creating GameObject " << name << " ";
StringID id = SID((char*)name);
std::cout << "Hash ID is " << id << std::endl;
AddComponents(id, args...);
return id;
}
// A base app class.
// This is a singleton :(
class Application
{
template <typename T>
friend void AddComponents(StringID gameObjectID, T component);
public:
Application() : mComponents() {
if (mApplication != nullptr) {
std::cout << "Application already exists. You can only create 1 Application" << std::endl;
}
mApplication = this;
}
virtual ~Application() {}
static Application* GetApplication() { return mApplication; }
// Debug run to check components have been added correctly.
void Run() {
StringID testObject1ID = CreateGameObject("testObject1", TransformComponent(0, 0));
StringID testObject2ID = CreateGameObject("testObject2", TransformComponent(0, 0), TransformComponent(10, 10));
std::cin.get();
}
private:
Components mComponents;
static Application* mApplication;
};
Application* Application::mApplication = nullptr;
class TestGame : public Application {
};
int main() {
TestGame* testGame = new TestGame();
testGame->Run();
delete testGame;
return 0;
}
</code></pre>
<h1>Pros:</h1>
<ul>
<li>It is cache-friendly</li>
<li>It is relatively flexible</li>
</ul>
<h1>Cons:</h1>
<ul>
<li>Template functions are slow</li>
<li>The repeated <code>typeid</code> is very bad :)</li>
</ul>
<p>I don't know if using variarg templates is the best option, because it means i have to use all of those <code>typeid</code>s. Also, I feel like the variarg template functions aren't the best either, however the only alternatives I can think of are functions for each component, eg.</p>
<pre class="lang-cpp prettyprint-override"><code>void AddTransformComponent(StringID gameObjectID, TransformComponent component);
</code></pre>
<p>or overloaded functions, such as</p>
<pre class="lang-cpp prettyprint-override"><code>void AddComponent(StringID gameObjectID, TransformComponent component);
</code></pre>
<p>If there is any code which you need which is missing, please say.</p>
<p>Thanks for the help, and i would appreciate any advice. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T19:37:55.597",
"Id": "425217",
"Score": "0",
"body": "Oh, there is code that is missing... what happened to `//Data...` or `/* Data args... */`? Can't I read `c++` or have you removed anything? On Code Review you need to post complete code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T07:19:09.017",
"Id": "425246",
"Score": "1",
"body": "Thank you for the feedback. I have now edited the code and it compiles correctly on Visual Studio 2017."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T07:30:11.830",
"Id": "425247",
"Score": "0",
"body": "Great! I now voted to reopen it. Could you tell us one more thing, which c++ version this is targetting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T07:34:47.813",
"Id": "425248",
"Score": "0",
"body": "I am currently targeting C++17. Hope that helps :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:48:58.110",
"Id": "425379",
"Score": "0",
"body": "I don’t have time to write a full answer, but what is the point of the `Application` class? This construct looks like a way to try to legitimize global variables. Why not put the code in `Run` in `main` or at least a free function?"
}
] | [
{
"body": "<p><strong>Note</strong>: I first looked at modernizing your code, after that, I've resolved your questions in the assumption you applied my suggestions.</p>\n\n<p>Looking at your code, I'm a bit worried that you are trying to reeinvent some weels. First of all: <code>SID</code> and <code>HashString</code>.</p>\n\n<p>I'm really worried about this, as it ain't as readable, predictable and performant as it could be.</p>\n\n<p>Let's start with readable: Why would you redefine <code>HashString</code> to <code>SID</code>? This introduces an extra indirection that doesn't add any value. I can see some arguments of making an alias, however, as you are using C++17, just make it an inline function.</p>\n\n<p>Secondly: Predictable. HashString returns a <code>StringId</code>. All <code>std::hash</code> return <code>std::size_t</code>. I suspect it's the same type, however, all your calculations use <code>unsigned int</code> instead of <code>StringId</code>. So any hash you create will have several zeros.</p>\n\n<p>Finally: Performance. Your function accepts <code>const char *</code>. Why don't you use <code>std::string_view</code> instead? If you would have a <code>std::string</code>, it already knows the size, so you shouldn't recalculate it. It can still be called with a zero-terminated char*, in which case strlen will be called in the Ctor of the view.</p>\n\n<p>As already said, it looks like a reimplementation of <code>std::hash<std::string_view></code>. However, I see an argument in having your own hash function.</p>\n\n<p>Still looking at the same function: <code>fnv_prime</code> is a constant. Why don't you use <code>constexpr</code> for it instead of <code>const</code>?</p>\n\n<p>I also see a for-loop. Whenever, I see <code>for (i = 0</code>, I immediately worry about the scope of the variable, do we need it after the loop? Having to check this increases the complexity for me. How about <code>for (unsigned int i = 0; i < len; ++i)</code>? However, as you will be using <code>std::string_view</code>, it can become: <code>for (auto c : str)</code>, even easier to read/understand;</p>\n\n<p>Moving on: the Component class. Again, you have a constant that could be constexpr. However, I'm worried much more about <code>mID</code>. This ID is free to access for everyone and free to update. Make it private and provide a getter/setter for it.</p>\n\n<p>Your constructor/dtor are implemented as <code>{}</code>, while this could be <code>= default;</code> and the move/copy ctor/assignment are missing. Best to check on <code>the rule of 5</code>.</p>\n\n<p>Going forward: TransformComponent. Are you compiling with compiler warnings (<code>-Weverything -Werror</code> in Clang, <code>/WX /W4</code> in MSVC)? You have a nice example of what is called shadowing. The member <code>mPosition</code> will never be initialized as you create a variable with the same name in a different scope. One could even wonder why you pass <code>x</code> and <code>y</code> separately, I would expect a single argument of type <code>Vec2</code>.</p>\n\n<p>The struct <code>Components</code> creeps me out. Looking at it, its a really bad implementation of <code>std::vector</code>. Get rid of it! (And prereserve the vector if relevant).</p>\n\n<p><code>AddComponents</code> also looks pre-C++17. An alternative:</p>\n\n<pre><code>template <typename Arg, typename ... Args>\ninline void AddComponents(StringID gameObjectID, Arg first, Args ... args) {\n // Do the work\n if constexpr (sizeof...(args))\n AddComponents(gameObjectID, args...);\n}\n</code></pre>\n\n<p>Moving to <code>CreateGameObject</code> why do a c-style cast to <code>char*</code> when not needed?</p>\n\n<p>Up to the <code>Application</code> class. This looks like an attempt for a singleton pattern. I would at least use <code>std::cerr</code> instead of <code>std::cout</code> for reporting failures. However, I'd even recommend <code>assert</code>. Your destructor also never resets the static to <code>nullptr</code>.</p>\n\n<p>And a final remark for <code>main</code>: Why would you even allocate memory here. Try writing it as:</p>\n\n<pre><code>TestGame testGame{};\ntestGame.Run();\nreturn 0;\n</code></pre>\n\n<p>Looking at your questions: </p>\n\n<p><strong>Templates ain't slow</strong>, please compile with optimizations: <code>-O3</code> in clang, <code>/O2</code> in MSVC. It might hurt you for compile time, however, it hurts less as having to write everything manually.</p>\n\n<p>I agree, <code>typeid</code> is bad. You don't need it. Having the overload will work good enough without the runtime overhead. However, I wouldn't overload <code>AddComponents</code> on the type. I would have an overloaded function that returns you the correct <code>std::vector</code>. Much less code to duplicate, much easier to reuse at other places.</p>\n\n<pre><code>template<typename T>\nauto &getStorage()\n{\n if constexpr (std::is_same_v<T, TransformComponent>)\n return TransformComponents;\n else if constexpr (std::is_same_v<T, OtherComponent>)\n return OtherComponents;\n}\ntemplate<typename T>\nconst auto &getStorage() const\n{\n return const_cast<ThisType &>(*this).getStorage();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T13:29:51.497",
"Id": "425344",
"Score": "0",
"body": "Thanks for the advice! Just one quick question. How would the overloaded function returning the vector be implemented? What would its declaration look like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T15:59:24.943",
"Id": "425357",
"Score": "0",
"body": "I've added a possible implementation.\nAnother could be by having a templated function and specialized functions that return the right vector. As your example only contains a single type, its a bit hard to know how you are currently intending to store it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:46:54.287",
"Id": "425378",
"Score": "0",
"body": "It took me a while to figure this out: “iso” = “instead of”. Your answer would benefit if you wrote that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:18:06.443",
"Id": "425388",
"Score": "0",
"body": "@CrisLuengo I've updated it, thanks for the input"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T11:31:22.877",
"Id": "220133",
"ParentId": "220060",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220133",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T17:48:34.877",
"Id": "220060",
"Score": "3",
"Tags": [
"c++",
"c++17",
"variadic",
"entity-component-system"
],
"Title": "Creating a cache-friendly component system"
} | 220060 |
<p>Suppose I have this query and want to convert into an object </p>
<blockquote>
<p>a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2</p>
</blockquote>
<p>output for this should be </p>
<blockquote>
<pre><code>article1: 'DRAFT',
article2: 'REVISION',
article3: 'DRAFT',
article16: 'READY'
</code></pre>
</blockquote>
<p>Please review my code. Is this the right way to do perform this task?</p>
<pre><code>let a = "a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2";
let con = {'0':'DRAFT', '1':'REVISION', '2':'READY'}
let obj = {};
a = a.replace(/-abc/g, "");
a = a.replace(/[.!]/g, "&");
a = a.split("&").forEach((v, i) => {
let b = v.split("=");
if (b.length > 1) {
Object.assign(obj,{[b[0]]:con[b[1]]})
}
});
</code></pre>
<p>I'm wondering if there any optimized way to do this.</p>
| [] | [
{
"body": "<p>I suggest you use the standard query string syntax to avoid future problems. Because the weirder this query string gets, the more cases you'll have to add to this piece of code. And when a case that's not covered in your code appears, it will unexpectedly break your code.</p>\n\n<p>Also, this used to be the way to parse query strings (i.e. split by <code>&</code>, loop through the items, split by <code>=</code>). Now, there is a built-in API, <code>URLSearchParams</code>, that parses query strings for you. It exists for both <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">browser JS</a> as well as <a href=\"https://nodejs.org/api/url.html#url_class_urlsearchparams\" rel=\"nofollow noreferrer\">NodeJS</a>. It exposes several methods as well as methods that return iterables, which allow you to loop through the items.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T11:12:01.887",
"Id": "426054",
"Score": "0",
"body": "Thank you for the answer but the question is not specific about URL parameters"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T20:26:42.343",
"Id": "220067",
"ParentId": "220062",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T18:26:52.467",
"Id": "220062",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"regex",
"url"
],
"Title": "Convert query string into object in JavaScript"
} | 220062 |
<p>I have a project where I would develop a nutrition label and a recipe list in a C++ class. I am facing problems when I run past void menu. The choice integer is when the user decided earlier if they would like to work with nutrition labels or recipes so that the program knows which array to work on.</p>
<p>I'm just asking for help on fixing any mistakes I made. I am a beginner in writing code so I'll gladly take any tips in the right direction.</p>
<p>Full code:</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
void initialization(int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void getLabel(int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10]);
void getRecipe(int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void menu(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void save(int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void add(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void addManual(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void addFile(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void edit(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void del(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void print(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
void view(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100]);
int main()
{
char recipes[50][50]; // array for recipe names
char reciIngred[50][10][100]; // array for recipe ingredients
char itemName[50][100]; // array for line integer
char nutriIngred[50][10][500]; // array for nutrition ingredients
char component[50][20]; // array for nutrition names
double measurement[50][10]; // array for nutrition values
char metric[50][10][10]; // array for nutrition units of measurement
int dailyPercent[50][10]; // array for nutrition daily percent of nutritional needs
int choice = 0; // user's answer
int labeltotal = 0; // total amount of nutrition labels
int recipetotal = 0; // total amount of recipes
initialization(labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
do
{
cout << "Beginning of the program" << endl;
cout << "Would you like to work with: " << endl
<< "1 - Labels" << endl << "2 - Recipes" << endl << "3 - Save" << endl << "4 - Quit" << endl;
cin >> choice;
switch (choice)
{
// nutrition label
case 1:
{
menu(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
// recipe
case 2:
{
menu(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
// saving
case 3:
{
save(labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
case 4:
{
cout << "goodbye" << endl;
break;
}
default:
{
cout << "error" << endl;
}
}
} while (choice != 4); // loops until 4 has been entered
system("pause");
return 0;
}
void initialization(int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
ifstream fin, fin2;
// open files
fin.open("Labels.txt");
fin2.open("recipes.txt");
fin >> labeltotal; // total amount of labels in first line
fin2 >> recipetotal; // total amount of recipes in first line
fin.ignore();
fin2.ignore();
for (int i = 0; i < labeltotal; i++)
{
fin.getline(itemName[i], 100);
for (int j = 0; j < 10; j++)
{
fin >> nutriIngred[i][j];
}
for (int n = 0; n < 26; n++)
{
fin.getline(component[n], 20);
fin >> measurement[i][n];
fin >> metric[i][n];
fin >> dailyPercent[i][n];
}
}
for (int k = 0; k < recipetotal; k++)
{
fin2 >> recipes[k]; // get name of the recipes
for (int l = 0; l < 10; l++)
{
fin2 >> reciIngred[k][l];
}
}
// close files
fin.close();
fin2.close();
return;
}
void getLabel(int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10])
{
for (int i = 0; i < labeltotal; i++)
{
cout << "Label line: " << i << endl;
cout << itemName[i] << endl;
for (int j = 0; j < 10; j++)
{
if (nutriIngred[i][j][0] != '#')
{
cout << nutriIngred[i][j] << " ";
}
else
{
break;
}
}
cout << endl;
for (int n = 0; n < 26; n++)
{
cout << " " << component[n] << ": " << measurement[i][n] << " " << metric[i][n] << " ";
if (dailyPercent[i][n] != -1)
{
cout << dailyPercent[i][n];
}
else
{
break;
}
cout << endl;
}
}
cout << endl;
cout << "What label line would you like to work with: ";
}
void getRecipe(int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
for (int k = 0; k < recipetotal; k++)
{
cout << "recipe line: " << k << endl;
for (int l = 0; l < recipetotal; l++)
{
cout << recipes[k][l];
}
for (int m = 0; m < 10; m++)
{
cout << " " << reciIngred[k][m] << endl;
}
}
cout << "What recipe line would you like to work with?" << endl; // ask user what recipe to work on
}
void menu(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
int option;
cout << "Menu function" << endl; // display function name
cout << "Make a menu choice:" << endl // display choices
<< "1 - add " << endl << "2 - edit " << endl << "3 - delete" << endl << "4 - print" << endl << "5 - view" << endl;
cin >> option;
switch (option) // switch function for user's choice
{
case 1:
{
add(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
case 2:
{
edit(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
case 3:
{
del(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
case 4:
{
print(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
case 5:
{
view(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
default:
{
cout << "Bad entry choice" << endl;
}
}
return;
}
void add(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
char quitpro = 'n';
int option;
int itemIndex = 0;
cout << "adding function" << endl;
do
{
cout << "Make a choice: " << endl
<< "1 - quit" << endl << "2 - add manually" << endl << "3 - add from a file" << endl;
cin >> option;
switch (option)
{
case 1:
{
cout << "Are you sure you want to quit? ";
cin >> quitpro;
break;
}
case 2:
{
addManual(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
case 3:
{
addFile(choice, labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent,
recipetotal, recipes, reciIngred);
break;
}
default:
{
cout << "error input" << endl;
}
}
for (int i = 0; i < 50; i++)
{
cout << itemName[i] << component[i] << measurement[i] << metric[i] << dailyPercent[i] << endl;
}
} while (quitpro == 'n' || quitpro == 'N');
return;
}
void addManual(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
cout << "Add manual function" << endl;
switch (choice)
{
case 1:
{
for (int i = labeltotal + 1; i < (labeltotal + 2); i++)
{
cout << "Enter additional item name: ";
cin >> itemName[i];
while (itemName[i] != "#")
{
for (int j = 0; j < 10; j++)
{
cout << "Insert additional ingredients: ";
cin >> nutriIngred[i][j];
}
cout << "Enter additional component: ";
cin >> component[i];
for (int n = 0; n < 26; n++)
{
cout << "insert additional measurement: ";
cin >> measurement[i][n];
cout << "insert additional metric: ";
cin >> metric[i][n];
cout << "insert additional daily percent: ";
cin >> dailyPercent[i][n];
}
}
}
break;
}
case 2:
{
for (int k = (recipetotal + 1); k < (recipetotal + 2); k++)
{
cout << "insert additional recipe: ";
cin >> recipes[k];
for (int l = 0; l < 10; l++)
{
cout << "insert additional ingredients: ";
cin >> reciIngred[k][l];
}
}
break;
}
default:
{
cout << "error" << endl;
}
}
labeltotal = (labeltotal + 1);
recipetotal = (recipetotal + 1);
return;
}
void addFile(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
int x = 0, y = 0;
ifstream fin, fin2;
// open file
fin.open("labelsInput.txt");
fin2.open("recipesInput.txt");
fin >> x;
fin2 >> y;
cout << "Add from file function" << endl;
// if nutrition was chosen in the beginning
if (choice == 1)
{
for (int i = labeltotal; i < (labeltotal + x); i++)
{
fin >> itemName[i];
for (int n = 0; n < 26; n++)
{
fin.getline(nutriIngred[i][n], 500);
fin >> component[n];
fin >> measurement[i][n];
fin >> metric[i][n];
fin >> dailyPercent[i][n];
}
}
}
// if recipe was chosen in the beginning
else if (choice == 2)
{
for (int k = (recipetotal + 1); k < (recipetotal + y); k++)
{
fin2 >> recipes[k]; // get name of the recipes
for (int l = 0; l < 10; l++)
{
fin2 >> reciIngred[k][l];
}
}
}
labeltotal = (labeltotal + x);
recipetotal = (recipetotal + y);
return;
}
void edit(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
char quitpro = 'n';
int option;
int itemIndex = 0;
int newItem, newIngred, newComponent, newMeasurement, newMetric, newDaily, newRecipe, newtotal;
do
{
cout << "edit function" << endl;
cout << "Make a choices: " << endl
<< "1 - stop" << endl << "2 - continue editing" << endl;
cin >> option;
switch (option)
{
case 1:
{
cout << "Are you sure you want to quit? (Y/N)" << endl;
cin >> quitpro;
break;
}
case 2:
{
if (choice == 1)
{
getLabel(labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent);
cin >> itemIndex;
cout << "Insert new item name: ";
cin >> newItem;
cout << "Insert new ingredients list: ";
cin >> newIngred;
cout << "Insert new component: ";
cin >> newComponent;
cout << "Insert new measurement: ";
cin >> newMeasurement;
cout << "New metric: ";
cin >> newMetric;
cout << "New daily percentage: ";
cin >> newDaily;
for (int i = 0; i < labeltotal; i++)
{
if (i = itemIndex)
{
itemName[i][100] = newItem;
nutriIngred[i][10][500] = newIngred;
component[i][10] = newComponent;
measurement[i][10] = newMeasurement;
metric[i][10][10] = newMetric;
dailyPercent[i][10] = newDaily;
}
}
}
else if (choice == 2)
{
getRecipe(recipetotal, recipes, reciIngred);
cin >> itemIndex;
cout << "Insert new recipe name: ";
cin >> newRecipe;
cout << "Insert new ingredients: ";
cin >> newIngred;
for (int k = 0; k < recipetotal; k++)
{
if (k = itemIndex)
{
recipes[k][50] = newRecipe;
reciIngred[k][10][100] = newIngred;
}
}
}
break;
}
}
} while (quitpro == 'n' || quitpro == 'N');
return;
}
void del(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
char quitpro = 'n';
int option;
int itemIndex = 0;
int newItem, newIngred, newComponent, newMeasurement, newMetric, newDaily;
cout << "delete function" << endl;
do
{
cout << "Make a choice: " << endl
<< "1 - stop" << endl << "2 - continue deleting" << endl;
cin >> option;
switch (option)
{
case 1:
{
cout << "Are you sure you want to quit? (Y/N)" << endl;
cin >> quitpro;
break;
}
case 2:
{
if (choice == 1)
{
getLabel(labeltotal, itemName, nutriIngred, component, measurement, metric, dailyPercent);
cin >> itemIndex;
for (int i = 0; i < labeltotal; i++)
{
if (i = itemIndex)
{
itemName[i][100] = 0;
nutriIngred[i][10][500] = 0;
component[i][10] = 0;
measurement[i][10] = 0;
metric[i][10][10] = 0;
dailyPercent[i][10] = 0;
}
}
}
else if (choice == 2)
{
getRecipe(recipetotal, recipes, reciIngred);
cin >> itemIndex;
for (int k = 0; k < recipetotal; k++)
{
if (k = itemIndex)
{
recipes[k][50] = 0;
reciIngred[k][10][100] = 0;
}
}
}
break;
}
}
} while (quitpro == 'n' || quitpro == 'N');
return;
}
void print(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
ofstream fout, foutt;
fout.open("tempLabels.txt");
foutt.open("tempRecipes.txt");
cout << "Printing to file" << endl;
switch (choice)
{
case 1:
{
fout << labeltotal << endl;
for (int i = 0; i < labeltotal; i++)
{
fout << itemName[i] << endl;
for (int j = 0; j < 10; j++)
{
fout << nutriIngred[i][j] << " ";
}
fout << endl;
for (int n = 0; n < 26; n++)
{
fout << component[n] << measurement[i][n] << " " << metric[i][n] << " " << dailyPercent[i][n];
}
fout << endl;
}
break;
}
case 2:
{
foutt << recipetotal << endl;
for (int k = 0; k < recipetotal; k++)
{
foutt << recipes[k] << " ";
for (int l = 0; l < 10; l++)
{
foutt << reciIngred[k][l] << " ";
}
foutt << endl;
}
break;
}
default:
{
cout << "error" << endl;
}
}
fout.close();
foutt.close();
return;
}
void view(int & choice, int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
cout << "Viewing on screen" << endl;
// display new array on console
switch (choice)
{
case 1:
{
for (int i = 0; i < labeltotal; i++)
{
cout << itemName[i] << endl;
for (int j = 0; j < 10; j++)
{
if (nutriIngred[i][j][0] != '#')
{
cout << nutriIngred[i][j] << " ";
}
else
{
break;
}
}
cout << endl;
for (int n = 0; n < 26; n++)
{
cout << component[n] << ": " << measurement[i][n] << " " << metric[i][n] << " ";
if (dailyPercent[i][n] != -1)
{
cout << dailyPercent[i][n];
}
cout << endl;
}
}
cout << endl;
break;
}
case 2:
{
for (int k = 0; k < recipetotal; k++)
{
cout << recipes[k] << ": ";
for (int l = 0; l < 10; l++)
{
if (reciIngred[k][l][0] != '#')
{
cout << reciIngred[k][l] << " "; //temp
}
else
{
break;
}
}
cout << endl;
}
break;
}
default:
{
cout << "error" << endl;
}
}
return;
}
void save(int & labeltotal, char itemName[][100], char nutriIngred[][10][500], char component[][20], double measurement[][10], char metric[][10][10], int dailyPercent[][10],
int & recipetotal, char recipes[][50], char reciIngred[][10][100])
{
ofstream fout, fout2;
fout.open("Labels.txt");
fout2.open("Recipes.txt");
cout << "Saving function" << endl;
fout << labeltotal << endl;
for (int i = 0; i < labeltotal; i++)
{
fout << itemName[i] << endl;
for (int j = 0; j < 10; j++)
{
fout << nutriIngred[i][j] << " ";
}
fout << endl;
for (int n = 0; n < 26; n++)
{
fout << component[n] << " " << measurement[i][n] << " " << metric[i][n] << " " << dailyPercent[i][n] << endl;
}
fout << endl;
}
fout2 << recipetotal << endl;
for (int k = 0; k < recipetotal; k++)
{
fout2 << recipes[k] << " ";
for (int l = 0; l < 10; l++)
{
fout2 << reciIngred[k][l] << " ";
}
fout2 << endl;
}
fout2 << endl;
// close files
fout.close();
fout2.close();
return;
}
</code></pre>
<p>Nutrition Labels</p>
<p>In order:<br>
* labeltotal<br>
* itemName<br>
* nutriIngred<br>
* Component measurement metric dailyPercent</p>
<pre><code>1
Cereal
Wheat, milk
calories 120 kcals -1
fatCalories 15 kcals 2
totalFat 1.5 g 2
satFat 2 g 3
transFat 3 g 4
polyFat 4 g 5
monoFat 5 g 6
cholesterol 6 g 7
sodium 7 g 8
potassium 9 g 10
totalCarbs 10 g 11
dietaryFiber 11 g 12
sugar 12 g 13
otherCarbs 13 g 14
protein 14 g 15
vitaminA 15 g 16
vitaminC 16 g 17
calcium 17 g 18
iron 18 g 19
thiamine 19 g 20
riboflavin 20 g 21
niacin 21 g 22
vitaminB6 22 g 23
folicAcid 23 g 24
phosphorus 24 g 25
zinc 25 g 26
</code></pre>
<p>Recipes<br>
* In order:<br>
* recipetotal<br>
* recipes reciIngred</p>
<pre><code>10
Tacos tortilla, lettuce, cheese, meat #
Doritos cheese powder, chip #
Salad lettuce #
Tostitos tortilla, salsa #
Pizza cheese, pepperoni #
Pepsi co2 #
Coke co2 #
Sprite co2, lime #
Pretzels salt, pretzel #
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T04:25:08.287",
"Id": "425237",
"Score": "1",
"body": "Please add the `main` function to your code, so that we can actually run your program during the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T05:34:44.947",
"Id": "425242",
"Score": "1",
"body": "`I am facing problems when I run past void menu` What kind of problems? Does this work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T05:36:34.703",
"Id": "425243",
"Score": "0",
"body": "I'm saying that some of the void functions past menu don't work like addFile."
}
] | [
{
"body": "<p>Looking at your code, it's indeed obvious that you are still learning C++. Actually, I call it C with some sparkles of C++, as I recognize several constructs that one tries to avoid in C++ in favor of better encapsulated constructs. I'll point them out later.</p>\n\n<p>First of all, I like to congratulate you for your naming. I barely see beginners that take the time to choose good names for the variables. All companies have IDEs that can help you type these, so keep up the good work and use good names.</p>\n\n<p>That said, there were a few things that I wouldn't consider good C++: <code>char recipes[][50]</code> to name one. From what I can deduce, this should be <code>std::vector<std::string></code>. This can prevent a lot of confusion, has a dynamic size (you can prealloc) and the <code>std::string</code> part of it allows you to simply a lot of string operations.</p>\n\n<p>Secondly, I'm noticing that you have several variables that go hand-in-hand. <code>itemName</code>, <code>nutriIngred</code> ... Even in C, one would recommend putting this in structs. In C++, we use classes/structs. (They are almost the same, however, C++ allows you to put methods to both structs and classes).</p>\n\n<p>For example:</p>\n\n<pre><code>class Ingredient\n{\n std::string name;\n std::string metric;\n double measurement;\n int dailyPercent;\n};\nclass Recipe\n{\n std::string name;\n std::vector<Ingredient> ingredients;\n};\n</code></pre>\n\n<p>I suggest you already start by trying to incorporate these classes, so the data is more structured. Once we have that, you can post a second iteration, in which we can look at splitting the functions into smaller logical blocks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T08:21:51.733",
"Id": "220085",
"ParentId": "220070",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T03:48:39.907",
"Id": "220070",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Modifying nutrition labels and recipes from files"
} | 220070 |
<p>What is a Pythonic way to construct intervals from a sequence of integer numbers? E.g. sequence <code>[1, 2, 3, 6, 7, 9]</code> could be converted to <code>['1-3', '6-7', '9']</code>. I have implemented it like this:</p>
<pre><code>def sequence_to_intervals(seq):
intervals = []
interval_start = None
interval_end = None
for i in sorted(seq):
if interval_start is None:
interval_start = i
interval_end = i
elif interval_end + 1 >= i:
interval_end = i
else:
if interval_start == interval_end:
intervals.append(str(interval_start))
else:
intervals.append(f'{interval_start}-{interval_end}')
interval_start = i
interval_end = i
else:
if interval_start == interval_end:
intervals.append(str(interval_start))
else:
intervals.append(f'{interval_start}-{interval_end}')
return intervals
</code></pre>
<p>Simple test:</p>
<pre><code>seq = [1, 2, 3, 6, 7, 9]
sequence_to_intervals(seq)
['1-3', '6-7', '9']
</code></pre>
<p>Converting intervals back to sequence:</p>
<pre><code>def intervals_to_sequence(intervals):
seq = []
for interval in intervals:
if '-' in interval:
start, stop = interval.split('-')
seq += list(range(int(start), int(stop) + 1))
else:
seq += [int(interval)]
return seq
</code></pre>
<p>Simple test:</p>
<pre><code>intervals = ['1-3', '6-7', '9']
intervals_to_sequence(intervals)
[1, 2, 3, 6, 7, 9]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T06:48:04.570",
"Id": "425244",
"Score": "0",
"body": "`interval_end is None` is never true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T08:42:23.310",
"Id": "425260",
"Score": "0",
"body": "@bipll Good remark. Should I remove this check from my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T08:58:50.203",
"Id": "425261",
"Score": "0",
"body": "Yes, makes sense."
}
] | [
{
"body": "<p>For the first part of making sequence to intervals, you could do this instead (prob. more Pythonic?) (This can be converted to a function easier - leave for the exercise)</p>\n<pre><code>>>> # if x-1 not in seq: x becomes start point\n>>> # if y+1 not in seq: y becomes end point\n>>> starts = [x for x in seq if x-1 not in seq]\n>>> ends = [y for y in seq if y+1 not in seq]\n>>> ends\n[3, 7, 9]\n>>> intervals = [str(a)+'-'+str(b) for a, b in zip(starts, ends)]\n>>> intervals\n['1-3', '6-7', '9-9']\n>>> \n</code></pre>\n<p>[Note - last interval could be 'fixed' too - if we see start_point == end_point. Leave as an exercise.]</p>\n<p>Then for the second part, it would be quite similar:</p>\n<pre><code>>>> seq = []\n>>> for inter in intervals:\n s, e = inter.split('-')\n seq += list(range(int(s), int(e)+1))\n>>> seq\n[1, 2, 3, 6, 7, 9]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:51:34.193",
"Id": "499267",
"Score": "1",
"body": "Please read a couple of well received answers \"in tags\" that interest you, then revisit [How do I write a Good Answer?](https://codereview.stackexchange.com/help/how-to-answer) to get the knack of what CodeReview@SE answers should be about - as with [your first answer](https://codereview.stackexchange.com/a/253157), your observation is about the problem where it should be about the code put up for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:58:51.567",
"Id": "499269",
"Score": "0",
"body": "(When presenting code, \"ready for cut, paste&run\" has its advantages. Granted, \"one of the conventional prompts\" boosts confidence this is cut&pasted from an interactive session and actually works as far as demonstrated. Which made me wonder how interval '9' could have passed and notice your alternative solution uses a deviating, but not erroneous format.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T02:56:01.533",
"Id": "253204",
"ParentId": "220072",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T04:01:27.223",
"Id": "220072",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"interval"
],
"Title": "Construct intervals from a sequence of numbers and vice versa"
} | 220072 |
A general RPC (Remote Procedure Call) framework over HTTP/2, initially developed at Google. gRPC is a language neutral and platform neutral framework that allows users to write applications where independent services can work with each other as if they were native. It uses Protocol Buffers as the interface description language. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T04:01:52.527",
"Id": "220074",
"Score": "0",
"Tags": null,
"Title": null
} | 220074 |
<p>It's a simple word guessing game. The game picks a random word - you guess a letter until it's correct, the game automatically starts a new one.</p>
<p>Is my code readable? Am I doing anything that could be simplified?
Am I doing the right thing by using only one class besides Main?</p>
<pre><code>import java.util.Scanner;
import java.util.Random;
class Word {
private String censoredWord = "";
private String word = "";
private String[] words = {"cow", "giraffe", "deer", "cat", "dog", "cheese"}; ////words
public String randomizeWord() { //randomizes word
Random rand = new Random();
int randNum = rand.nextInt(words.length);
word = words[randNum];
for (int i = 0; i < word.length(); i++) { //makes a word filled with blank spots the same length as the word chosen
censoredWord = censoredWord + "_";
}
return word;
}
public String showProgress(char letter) { //uncensors letters
char[] wordArray = word.toCharArray(); //sets the word to an array so it can loop though it
char[] censoredWordArray = censoredWord.toCharArray();
for (int i = 0; i < wordArray.length; i++) {
char ichar = wordArray[i];
if (letter == ichar) {
censoredWordArray[i] = ichar; //fills in censored letter
}
}
censoredWord = String.valueOf(censoredWordArray);
System.out.println(censoredWord);
return censoredWord;
}
}
class Main {
public static void main(String[] args) {
Word word = new Word();
String currentWord = word.randomizeWord();
while (true) { //handles the game structure and guessing
System.out.println("Guess!");
Scanner guessLetter = new Scanner(System.in); //takes input
char letterGuessed = guessLetter.nextLine().charAt(0); //puts input into variable
//checks if user got the word
guessLetter.close();
if (word.showProgress(letterGuessed).equals(currentWord)) {
System.out.println("Hooray! Resetting...");
word = new Word();
currentWord = word.randomizeWord();
}
}
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<h2>Performance</h2>\n\n<p>You create a new <code>Scanner</code> for every guess. this is unnecessary. the same scanner can be used to read all user input. the scanner should be closed only at the end of the program. and if you adopt that, you can also use <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">Java 7 try-with-resources</a> feature. it is a safe(r) way to open and process external resources.</p>\n\n<h2>JDK library features</h2>\n\n<ol>\n<li><p>in order to fill an array with the same character, you can use <a href=\"https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#fill(char[],%20char)\" rel=\"nofollow noreferrer\"><code>Arrays.fill()</code></a> method: <code>Arrays.fill(censoredWordArray, '_');</code> and you do not need to keep the String representation of the array, just print the string value to the user. However, FYI, Java 11 gives us <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)\" rel=\"nofollow noreferrer\"><code>String::repeat</code></a> to fill a String with one character: <code>String censoredWord = \"_\".repeat(word.length());</code></p></li>\n<li><p>I assume this is CS course homework, so I do not know if this comment is applicable. However, Java 8 (which has been around for over 5 years) gave us stream processing of collections, which, compared to for loops, is a more expressive (and sometimes performant) way to iterate over collections and arrays. for example, the loop in <code>showProgress</code> can be re-written like this </p>\n\n<pre><code>IntStream.range(0, wordArray.length)\n .filter(i -> wordArray[i] == letter)\n .findFirst()\n .ifPresent(i -> censoredWordArray[i] = letter);\n</code></pre></li>\n</ol>\n\n<h2>Best practices</h2>\n\n<p>Avoid magic numbers and literals: \n<code>private static final String EMPTY_LETTER = \"_\";</code><br>\nnot only it makes the code more readable, it will eliminate typo bugs in case you need to specify the literal in multiple places in the code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T07:51:18.977",
"Id": "220125",
"ParentId": "220077",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220125",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T05:35:54.860",
"Id": "220077",
"Score": "3",
"Tags": [
"java",
"performance",
"beginner",
"game",
"hangman"
],
"Title": "A simple Java game where the player guesses the word"
} | 220077 |
<p>I know this is kind of stuff is somewhat done to death but please still try to review it fairly.</p>
<p>My code will only go within the interval of [1,9]</p>
<pre class="lang-py prettyprint-override"><code>def guessing_game():
no_of_guess = 0
c = "y"
import random
a = random.randint(1,9)
while c == "y":
b = input("Enter a guess: ")
if b.isdigit():
if int(b) == a:
c = input("You got it! Play again? Enter \"Y\" if yes, and anything else to exit. ").lower()
no_of_guess +=1
a = random.randint(1,9)
elif int(b) > a:
c = input("Too high. Try again? Enter \"Y\" if yes, and anything else to exit. ").lower()
no_of_guess +=1
else:
c = input("Too small. Try again? Enter \"Y\" if yes, and anything else to exit. ").lower()
no_of_guess +=1
else:
c = input("Haha. Try again? Enter \"Y\" if yes, and anything else to exit. ").lower()
if c != "y":
print("How unfortunate. Well, you made %s guess(es)."%no_of_guess)
guessing_game()
</code></pre>
| [] | [
{
"body": "<p>A few minor things:</p>\n\n<ul>\n<li><p>Imports should generally be at the module level, not inside functions. </p></li>\n<li><p>Use more intention-revealing variable names. <code>no_of_guess</code> is borderline OK, but <code>a</code>, <code>b</code> and <code>c</code> don't tell me anything. </p></li>\n<li><p>Think about control flow more carefully. For example:</p>\n\n<ul>\n<li><p>you increment the guess counter for any numerical input, so you don't necessarily need to wait for the conditional checks; and</p></li>\n<li><p>outside the loop do you really need to recheck whether the input wasn't <code>\"y\"</code>?</p></li>\n</ul></li>\n<li><p>You can use single-quoted strings to avoid escaping double quote within them. </p></li>\n<li><p>You can also reduce duplication by extracting functions and constants</p></li>\n</ul>\n\n<p>With these suggestions addressed:</p>\n\n<pre><code>import random\n\nRULES = 'Enter \"Y\" if yes, and anything else to exit. '\n\ndef win_prompt():\n return input(\"You got it! Play again? \" + RULES).lower()\n\ndef lose_prompt(message):\n return input(message + \" Try again? \" + RULES).lower()\n\ndef guessing_game():\n number_of_guesses = 0\n target = random.randint(1,9)\n continuing = \"y\"\n while continuing == \"y\":\n guess = input(\"Enter a guess: \")\n if guess.isdigit():\n number_of_guesses += 1\n if int(guess) == target:\n continuing = win_prompt() \n target = random.randint(1,9)\n elif int(guess) > target:\n continuing = lose_prompt(\"Too high.\")\n else:\n continuing = lose_prompt(\"Too small.\") \n else:\n continuing = lose_prompt(\"Haha.\")\n print(\"How unfortunate. Well, you made %s guess(es).\" % number_of_guesses)\n\n\nguessing_game()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T07:26:51.027",
"Id": "425481",
"Score": "0",
"body": "Thanks a bunch! This helps a lot, especially the technique with the lose_prompt functions. I used a,b,c because I got lazy lol, but yeah I'll try to be more specific next time. Also that was a big brain fart with the c!='y' check, haha. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T08:02:26.690",
"Id": "220083",
"ParentId": "220080",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T06:21:08.957",
"Id": "220080",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"number-guessing-game"
],
"Title": "Guess the Number(Python)"
} | 220080 |
<h2>Introduction</h2>
<p><a href="https://classactivitycalculator.github.io/" rel="nofollow noreferrer"><strong>Class Activity Calculator</strong></a> is an online application to calculate the students' class activity grades. The class activity grade (CA) is calculated based on the marks a student gets during the term. Here's a sample grade sheet we use in class:</p>
<p><a href="https://i.stack.imgur.com/AceoS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AceoS.jpg" alt="enter image description here"></a></p>
<p>Please review the source code and provide feedback.</p>
<p><br></p>
<h2>Adults: Old</h2>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Calculate the class activity grades of the ILI students.">
<title>Class Activity Calculator</title>
<link rel="icon" href="favicon.ico">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<img src="logo.png" alt="Logo">
<h1>Class Activity Calculator</h1>
</header>
<nav>
<a href="index.html" id="current">Adults: Old</a>
<a href="adults-new.html">Adults: New</a>
<a href="young-adults.html">Young Adults</a>
<a href="kids.html">Kids</a>
</nav>
<main>
<form autocomplete="off">
<fieldset data-weight="4">
<legend>Listening & Speaking</legend>
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<output></output>
</fieldset>
<fieldset data-weight="3">
<legend>Reading</legend>
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<output></output>
</fieldset>
<fieldset data-weight="1">
<legend>Writing</legend>
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<input type="number" step="any" min="0" max="100">
<output></output>
</fieldset>
<div>
<button type="button">Calculate</button>
<output></output>
<button type="reset">Reset</button>
</div>
</form>
</main>
<footer>
Share on <a href="https://t.me/share/url?url=https%3A%2F%2Fclassactivitycalculator.github.io%2F&text=Class%20Activity%20Calculator%3A%20Calculate%20the%20class%20activity%20grades%20of%20the%20ILI%20students." title="Telegram: Share Web Page">Telegram</a> |
<a href="https://www.facebook.com/dialog/share?app_id=2194746457255787&href=https%3A%2F%2Fclassactivitycalculator.github.io%2F" title="Post to Facebook">Facebook</a>
<address><a href="https://t.me/MortezaMirmojarabian" title="Telegram: Contact @MortezaMirmojarabian" rel="author">Give feedback</a></address>
</footer>
<script>
function setOutputValues() {
var totalWeightedAverage = 0;
var totalWeight = 0;
var fieldsets = form.querySelectorAll('fieldset');
for (var fieldset of fieldsets) {
var average = averageInputValues(fieldset);
var fieldsetOutput = fieldset.querySelector('output');
if (average == undefined) {
fieldsetOutput.value = 'You may only enter 0 to 100.';
} else if (isNaN(average)) {
fieldsetOutput.value = 'Please enter a grade.';
} else {
fieldsetOutput.value = 'avg: ' + average.toFixed(1);
}
totalWeightedAverage += average * fieldset.dataset.weight;
totalWeight += Number(fieldset.dataset.weight);
}
var classActivity = totalWeightedAverage / totalWeight;
var divOutput = form.querySelector('div output');
if (isNaN(classActivity)) {
divOutput.value = '';
} else {
divOutput.value = 'CA: ' + classActivity.toFixed(1);
}
}
</script>
<script src="global.js"></script>
</body>
</html>
</code></pre>
<p><br></p>
<h2>style.css</h2>
<pre><code>html,
body {
margin: 0;
padding: 0;
}
header {
padding: 16px 0;
text-align: center;
background: linear-gradient(#999, #333);
}
img {
width: 36px;
height: 36px;
vertical-align: bottom;
}
h1 {
font-size: 1.125rem;
font-family: 'Times New Roman';
color: #FFF;
text-shadow: 0 3px #000;
letter-spacing: 1px;
}
nav {
display: flex;
justify-content: center;
background: #333;
border-top: 2px solid;
}
a {
color: #FFF;
}
nav a {
padding: 12px 6px;
font: bold 0.75rem Verdana;
text-decoration: none;
}
nav a:not(:last-child) {
margin-right: 2px;
}
nav a:hover,
nav a:focus,
#current {
outline: 0;
border-top: 2px solid;
margin-top: -2px;
}
main,
div {
display: flex;
}
form {
margin: 32px auto;
}
fieldset {
margin: 0 0 16px;
padding: 12px 12px 0;
border: 1px solid #CCC;
background: linear-gradient(#FFF, #CCC);
}
legend,
input,
output,
button {
font-family: Arial;
}
legend,
button {
color: #333;
}
legend {
padding: 0 4px;
font-size: 0.875rem;
}
input,
button,
div output {
font-size: 0.833rem;
}
input {
width: 4em;
}
input:invalid {
outline: 1px solid red;
}
output {
color: #C00;
}
fieldset output {
display: block;
margin: 8px 0 8px 6px;
font-size: 0.75rem;
}
fieldset output::after {
content: "\00A0";
}
/* a placeholder */
div output {
margin: auto auto auto 6px;
}
footer {
padding: 12px;
background: #333;
font: 0.75rem Arial;
color: #FFF;
}
address {
float: right;
}
</code></pre>
<p><br></p>
<h2>global.js</h2>
<pre><code>var form = document.querySelector('form');
function averageInputValues(fieldset) {
var totalValue = 0;
var totalNumber = 0;
var inputs = fieldset.querySelectorAll('input');
for (var input of inputs) {
if (!input.validity.valid) {
return;
}
totalValue += Number(input.value);
totalNumber += Boolean(input.value);
}
return totalValue / totalNumber;
}
form.querySelector('[type="button"]').addEventListener('click', setOutputValues);
function detectChange() {
var inputs = form.querySelectorAll('input');
for (var input of inputs) {
if (input.value) {
return true;
}
}
}
form.querySelector('[type="reset"]').addEventListener('click', function(event) {
if (detectChange() && !confirm('Your changes will be lost.\nAre you sure you want to reset?')) {
event.preventDefault();
}
});
window.addEventListener('beforeunload', function(event) {
if (detectChange()) {
event.returnValue = 'Your changes may be lost.';
}
});
</code></pre>
<p><br></p>
<h2>Note</h2>
<p>Please see the <a href="https://codereview.stackexchange.com/a/220503/33793"><strong>updates</strong></a>.<br>
<br></p>
| [] | [
{
"body": "<p><strong>Edit : as asked, I've edited my code to make a good proof of concept. I've also adapted it to the reworked version of the script, since it doesn't really matter.</strong></p>\n\n<p>Well, I'm lazy and I love to let my script do all the work for me. And you should too !</p>\n\n<p>So instead of <code>index</code>, <code>adults-new</code>, <code>young-adults</code> and <code>kids</code> having one page each, how about something like that :</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>var listForm={\n 'adult_old':{\n 'Listening & Speaking':{'weight':4,'fields':5,'max':100},\n 'Reading':{'weight':3,'fields':5,'max':100},\n 'Writing':{'weight':1,'fields':5,'max':100}\n },\n 'adult_young':{\n 'Listening':{'weight':4,'fields':4,'max':5},\n 'Speaking':{'weight':3,'fields':4,'max':5},\n 'Reading':{'weight':2,'fields':4,'max':5},\n 'Writing':{'weight':1,'fields':4,'max':5},\n }\n};\nvar form = document.querySelector('form');\n\nfunction toggleForm(formSelected){\n let myForm=listForm[formSelected];\n let formContent='';\n for(activity in myForm){\n var myActivity=myForm[activity];\n formContent+='<fieldset data-weight=\"'+myActivity['weight']+'\">';\n formContent+='<legend>'+activity+'</legend>';\n for(i=0;i<myActivity['fields'];i++)formContent+='<input type=\"number\" step=\"any\" min=\"0\" max=\"'+myActivity['max']+'\">';\n formContent+='<output></output></fieldset>';\n }\n document.getElementById('classActivity').innerHTML=formContent;\n}\n\nfunction averageInputValues(fieldset) {\n var totalValue = 0;\n var totalNumber = 0;\n var inputs = fieldset.querySelectorAll('input');\n for (var input of inputs) {\n if (!input.validity.valid) {\n return;\n }\n totalValue += Number(input.value);\n totalNumber += Boolean(input.value);\n }\n return totalValue / totalNumber;\n}\n\nfunction setOutputValues() {\n var max = form.querySelector('input').max;\n var totalWeightedAverage = 0;\n var totalWeight = 0;\n var fieldsets = form.querySelectorAll('fieldset');\n for (var fieldset of fieldsets) {\n var average = averageInputValues(fieldset);\n var fieldsetOutput = fieldset.querySelector('output');\n if (average == undefined) {\n fieldsetOutput.value = 'You may only enter 0 to ' + max + '.';\n } else if (isNaN(average)) {\n fieldsetOutput.value = 'Please enter a grade.';\n } else {\n fieldsetOutput.value = 'avg: ' + average.toFixed(1);\n }\n var weight = fieldset.dataset.weight;\n if (!weight) {\n weight = 1;\n }\n totalWeightedAverage += average * weight;\n totalWeight += Number(weight);\n }\n var classActivity = totalWeightedAverage / totalWeight;\n var divOutput = document.getElementById('total_output');\n if (isNaN(classActivity)) {\n divOutput.value = '';\n } else if (max == 5) { // Adults: New\n divOutput.value = 'CA: ' + (classActivity / (max / 100)).toFixed(1); // The class activity grade must be calculated out of 100.\n } else {\n divOutput.value = 'CA: ' + classActivity.toFixed(1);\n }\n}\n\nfunction detectChange() {\n var inputs = form.querySelectorAll('input');\n for (var input of inputs) {\n if (input.value) {\n return true;\n }\n }\n}\n\nvar nav_items=document.querySelectorAll('.nav_item');\nfor (var nav_item of nav_items) {\n nav_item.addEventListener('click', function(){\n document.querySelector('.current').classList.remove('current');\n this.classList.add('current');\n toggleForm(this.id); \n });\n}\ntoggleForm('adult_old');//default form\n\nform.querySelector('[type=\"button\"]').addEventListener('click', setOutputValues);\n\nform.addEventListener('reset', function(event) {\n if (detectChange() && !confirm('Your changes will be lost.\\nAre you sure you want to reset?')) {\n event.preventDefault();\n }\n});\n\nwindow.addEventListener('beforeunload', function(event) {\n if (detectChange()) {\n event.returnValue = 'Your changes may be lost.';\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\nbody {\n margin: 0;\n padding: 0;\n}\n\nheader {\n padding: 16px 0;\n text-align: center;\n background: linear-gradient(#999, #333);\n}\n\nimg {\n width: 36px;\n height: 36px;\n vertical-align: bottom;\n}\n\nh1 {\n font-size: 1.125rem;\n font-family: 'Times New Roman';\n color: #FFF;\n text-shadow: 0 3px #000;\n letter-spacing: 1px;\n}\n\nnav {\n display: flex;\n justify-content: center;\n background: #333;\n border-top: 2px solid;\n}\n\nspan {\n color: #FFF;\n}\n\nnav span {\n padding: 12px 6px;\n font: bold 0.75rem Verdana;\n text-decoration: none;\n cursor:pointer;\n}\n\nnav span:not(:last-child) {\n margin-right: 2px;\n}\n\nnav span:hover,\nnav span:focus,\n.current {\n outline: 0;\n border-top: 2px solid;\n margin-top: -2px;\n}\n\nmain,\ndiv {\n display: flex;\n}\n\nform {\n margin: 32px auto;\n}\n\nfieldset {\n margin: 0 0 16px;\n padding: 12px 12px 0;\n border: 1px solid #CCC;\n background: linear-gradient(#FFF, #CCC);\n}\n\nlegend,\ninput,\noutput,\nbutton {\n font-family: Arial;\n}\n\nlegend,\nbutton {\n color: #333;\n}\n\nlegend {\n padding: 0 4px;\n font-size: 0.875rem;\n}\n\ninput,\nbutton,\ndiv output {\n font-size: 0.833rem;\n}\n\ninput {\n width: 4em;\n}\n\ninput:invalid {\n outline: 1px solid red;\n}\n\noutput {\n color: #C00;\n}\n\nfieldset output {\n display: block;\n margin: 8px 0 8px 6px;\n font-size: 0.75rem;\n}\n\nfieldset output::after {\n content: \"\\00A0\";\n}\n/* a placeholder */\n\ndiv output {\n margin: auto auto auto 6px;\n}\n\nfooter {\n padding: 12px;\n background: #333;\n font: 0.75rem Arial;\n color: #FFF;\n}\n\naddress {\n float: right;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"description\" content=\"Calculate the class activity grades of the ILI students.\">\n <title>Class Activity Calculator</title>\n <link rel=\"icon\" href=\"favicon.ico\">\n <link rel=\"stylesheet\" href=\"style.css\">\n</head>\n\n<body>\n <header>\n <img src=\"logo.png\" alt=\"Logo\">\n <h1>Class Activity Calculator</h1>\n </header>\n <nav>\n <span class=\"nav_item current\" id=\"adult_old\">Adults: Old</span>\n <span class=\"nav_item\" id=\"adult_young\">Young Adults</span>\n </nav>\n <main>\n <form autocomplete=\"off\">\n <div id=\"classActivity\" style=\"display:block;\"></div><!--didn't want to touch the css-->\n <div>\n <button type=\"button\">Calculate</button>\n <output id=\"total_output\"></output>\n <button type=\"reset\">Reset</button>\n </div>\n </form>\n </main>\n <footer>\n Share on <a href=\"https://t.me/share/url?url=https%3A%2F%2Fclassactivitycalculator.github.io%2F&text=Class%20Activity%20Calculator%3A%20Calculate%20the%20class%20activity%20grades%20of%20the%20ILI%20students.\" title=\"Telegram: Share Web Page\">Telegram</a> |\n <a href=\"https://www.facebook.com/dialog/share?app_id=2194746457255787&href=https%3A%2F%2Fclassactivitycalculator.github.io%2F\" title=\"Post to Facebook\">Facebook</a>\n <address><a href=\"https://t.me/MortezaMirmojarabian\" title=\"Telegram: Contact @MortezaMirmojarabian\" rel=\"author\">Give feedback</a></address>\n </footer>\n</body>\n\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>That way, you'll only need to change the object at the start if an activity (or class, or evaluation) is added or removed.</p>\n\n<p>You should also put all your JS in <code>global.js</code> (or another file if you use <code>global.js</code> somewhere else, but I don't think so), it's good practice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T08:16:49.557",
"Id": "425487",
"Score": "0",
"body": "\"_instead of `index`, `adults-new`, `young-adults` and `kids` having one page each, how about something like that_\" Using JavaScript to dynamically create content would be beneficial if I had the same HTML across my site pages. As you see on [Kids](https://classactivitycalculator.github.io/kids.html), I don't have even the same number of `input`s in each `fieldset` of the same page. \"_You should also put all your JS in `global.js`_\" I can't as the `setOutputValues` function is different on each page. My `global.js` file includes only what the pages have in common."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T08:38:21.967",
"Id": "425489",
"Score": "0",
"body": "Err, guess I should have called `fields` `input_number` instead, my bad ^^ I just swapped `adult_old` and `adult_young` (and changed the `fields` number) in my example as to show the number of inputs adapting. Likewise, if your only difference in `setOutputValues` is the max value of each input, you can just add another attribute (`max`) in the `listForm` object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T15:36:44.920",
"Id": "220185",
"ParentId": "220084",
"Score": "1"
}
},
{
"body": "<h2>Overall Assessment</h2>\n\n<p>Overall this code is fine but it has a lot of excess DOM queries. Those could be optimized using the tips below.</p>\n\n<p>I noticed that if I calculate an average and then click the reset button, it still asks me to confirm when leaving the page. Should it still prompt to confirm even if the user has calculated an (overall) average?</p>\n\n<h2>More specific feedback</h2>\n\n<p>It is confusing having <code>setOutputValues()</code> defined in the inline script whereas all other functions are declared in global.js. It would make more sense to have everything together, unless something is being abstracted into a module. But I see <a href=\"https://codereview.stackexchange.com/questions/220084/class-activity-calculator#comment425487_220185\">your comment</a> that explains that <code>setOutputValues</code> will be different on each page. I would question what actually changes within that function depending on the page - is it the range values and/or strings? If so, perhaps those could be output as variables or else as hidden DOM elements.</p>\n\n<hr>\n\n<p>I see some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features used, like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for..of</code></a>, which means other features from that specification could be used as well. For instance, any variable that doesn't get re-assigned could be declared with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> and any value that does get re-assigned can be declared with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a>.</p>\n\n<hr>\n\n<p>I see the code queries for the form element:</p>\n\n<blockquote>\n<pre><code>var form = document.querySelector('form');\n</code></pre>\n</blockquote>\n\n<p>I know that you were told \"<em><code>querySelectorAll</code> is your friend.</em>\"<sup><a href=\"https://codereview.stackexchange.com/a/215201/120114\">1</a></sup>. However, use it with caution. There are other DOM query functions that run quicker than it. One could add an <code>id</code> attribute to the element and query for it using <code>document.getElementById()</code><sup><a href=\"https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2\" rel=\"nofollow noreferrer\">2</a></sup>. But then again, there is a reference to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/forms\" rel=\"nofollow noreferrer\"><code>forms</code></a> property of <code>document</code>, which could remove the need to query the DOM altogether. The first form could be referenced via <code>document.forms[0]</code> or a name attribute could also be applied to allow reference by name.</p>\n\n<p>For example, you could add the <em>name</em> attribute to the form:</p>\n\n<pre><code><form autocomplete=\"off\" name=\"activityCalc\">\n</code></pre>\n\n<p>Then utilize that name when referencing <code>document.forms</code>:</p>\n\n<pre><code> const form = document.forms.activityCalc;\n</code></pre>\n\n<p>That way there is no need to query the DOM with a function like <code>querySelector</code>.</p>\n\n<p>The same is true for the <code><output></code> elements - a name could be added to the last one and then there is no need to query for that element when displaying the cumulative average, as well as the button labeled <em>Calculate</em>.</p>\n\n<p>And instead of using <code>querySelectorAll()</code> to get the elements under a fieldset, you could use <code>.getElementsByTagName()</code> since the selector is just a tag name. As <a href=\"https://stackoverflow.com/a/18247327/1575353\">this SO answer</a> explains: </p>\n\n<blockquote>\n <p><code>getElementsByTagName</code> is probably faster, since it is simpler, but that is unlikely to have a noticeable impact on anything you do with it.</p>\n</blockquote>\n\n<hr>\n\n<p>I see that a handler for click events on the reset button is added via </p>\n\n<blockquote>\n<pre><code>form.querySelector('[type=\"reset\"]').addEventListener('click', function(event) {...});\n</code></pre>\n</blockquote>\n\n<p>this can be simplified by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset_event\" rel=\"nofollow noreferrer\">form event <em>reset</em></a>.</p>\n\n<pre><code>form.addEventListener('reset', function(event) { ... });\n</code></pre>\n\n<hr>\n\n<p>When loading a simple document like this with modern browsers it may be unlikely that the DOM would not be ready before the JavaScript code runs (depending on where it is included) but it is still wise to wait for the DOM to be ready before accessing DOM elements. This can be done with <code>document.addEventListener()</code> for the 'DOMContentLoaded` event. This also allows the scope of the variables to be limited to a callback function instead of global variables. </p>\n\n<hr>\n\n<p>It is a best practice to use strict equality when comparing values.</p>\n\n<p>On this line:</p>\n\n<blockquote>\n<pre><code>if (average == undefined) {\n</code></pre>\n</blockquote>\n\n<p>the value for <code>average</code> is assigned the return value from <code>averageInputValues()</code> which will likely either be <code>undefined</code> or a floating point number that is the result of a division operation. Using strict equality comparison eliminates the need for the types to be checked. Use the strict equality operator here and anywhere else there is no need to convert types when comparing:</p>\n\n<pre><code>if (average === undefined) {\n</code></pre>\n\n<hr>\n\n<h2>Rewritten code</h2>\n\n<p>The code below uses advice from above to simplify some parts of the code.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.addEventListener('DOMContentLoaded', function() {\n //DOM queries/accesses run once\n const form = document.forms.activityCalc;\n const fieldsets = form.getElementsByTagName('fieldset');\n const inputs = form.getElementsByTagName('input');\n const divOutput = form.elements.classActivity;\n \n function setOutputValues() {\n let totalWeightedAverage = 0;\n let totalWeight = 0;\n for (const fieldset of fieldsets) {\n const average = averageInputValues(fieldset);\n\n // should there be handling for no output element found below?\n const fieldsetOutput = fieldset.getElementsByTagName('output')[0];\n if (average === undefined) {\n fieldsetOutput.value = 'You may only enter 0 to 100.';\n } else if (isNaN(average)) {\n fieldsetOutput.value = 'Please enter a grade.';\n } else {\n fieldsetOutput.value = 'avg: ' + average.toFixed(1);\n }\n totalWeightedAverage += average * fieldset.dataset.weight;\n totalWeight += Number(fieldset.dataset.weight);\n }\n const classActivity = totalWeightedAverage / totalWeight;\n if (isNaN(classActivity)) {\n divOutput.value = '';\n } else {\n divOutput.value = 'CA: ' + classActivity.toFixed(1);\n }\n }\n\n function averageInputValues(fieldset) {\n let totalValue = 0;\n let totalNumber = 0;\n const inputs = fieldset.getElementsByTagName('input');\n for (const input of inputs) {\n if (!input.validity.valid) {\n return;\n }\n totalValue += Number(input.value);\n totalNumber += Boolean(input.value);\n }\n return totalValue / totalNumber;\n }\n\n form.elements.calculate.addEventListener('click', setOutputValues);\n\n function detectChange() {\n for (const input of inputs) {\n if (input.value) {\n return true;\n }\n }\n }\n\n form.addEventListener('reset', function(event) {\n if (detectChange() && !confirm('Your changes will be lost.\\nAre you sure you want to reset?')) {\n event.preventDefault();\n }\n });\n\n window.addEventListener('beforeunload', function(event) {\n if (detectChange()) {\n event.returnValue = 'Your changes may be lost.';\n }\n });\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\nbody {\n margin: 0;\n padding: 0;\n}\n\nheader {\n padding: 16px 0;\n text-align: center;\n background: linear-gradient(#999, #333);\n}\n\nimg {\n vertical-align: bottom;\n}\n\nh1 {\n font-size: 1.125rem;\n font-family: 'Times New Roman';\n color: #FFF;\n text-shadow: 0 3px #000;\n letter-spacing: 1px;\n}\n\nnav {\n display: flex;\n justify-content: center;\n background: #333;\n border-top: 2px solid;\n}\n\na {\n color: #FFF;\n}\n\nnav a {\n padding: 12px 6px;\n font: bold 0.75rem Verdana;\n text-decoration: none;\n}\n\nnav a:not(:last-child) {\n margin-right: 2px;\n}\n\nnav a:hover,\nnav a:focus,\n#current {\n outline: 0;\n border-top: 2px solid;\n margin-top: -2px;\n}\n\nmain,\ndiv {\n display: flex;\n}\n\nform {\n margin: 32px auto;\n}\n\nfieldset {\n margin: 0 0 16px;\n padding: 12px 12px 0;\n border: 1px solid #CCC;\n background: linear-gradient(#FFF, #CCC);\n}\n\nlegend,\ninput,\noutput,\nbutton {\n font-family: Arial;\n}\n\nlegend,\nbutton {\n color: #333;\n}\n\nlegend {\n padding: 0 4px;\n font-size: 0.875rem;\n}\n\ninput,\nbutton,\ndiv output {\n font-size: 0.833rem;\n}\n\ninput {\n width: 4em;\n}\n\ninput:invalid {\n outline: 1px solid red;\n}\n\noutput {\n color: #C00;\n}\n\nfieldset output {\n display: block;\n margin: 8px 0 8px 6px;\n font-size: 0.75rem;\n}\n\nfieldset output::after {\n content: \"\\00A0\";\n}\n\n\n/* a placeholder */\n\ndiv output {\n margin: auto auto auto 6px;\n}\n\nfooter {\n padding: 12px;\n background: #333;\n font: 0.75rem Arial;\n color: #FFF;\n}\n\naddress {\n float: right;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><header>\n <img src=\"https://cdn.sstatic.net/Sites/codereview/img/logo.svg?v=0dfb1294dc6e\" alt=\"Logo\">\n <h1>Class Activity Calculator</h1>\n</header>\n<nav>\n <a href=\"index.html\" id=\"current\">Adults: Old</a>\n <a href=\"adults-new.html\">Adults: New</a>\n <a href=\"young-adults.html\">Young Adults</a>\n <a href=\"kids.html\">Kids</a>\n</nav>\n<main>\n <form autocomplete=\"off\" name=\"activityCalc\">\n <fieldset data-weight=\"4\">\n <legend>Listening & Speaking</legend>\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <output></output>\n </fieldset>\n <fieldset data-weight=\"3\">\n <legend>Reading</legend>\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <output></output>\n </fieldset>\n <fieldset data-weight=\"1\">\n <legend>Writing</legend>\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <output></output>\n </fieldset>\n <div>\n <button type=\"button\" name=\"calculate\">Calculate</button>\n <output name=\"classActivity\"></output>\n <button type=\"reset\">Reset</button>\n </div>\n </form>\n</main>\n<footer>\n Share on <a href=\"https://t.me/share/url?url=https%3A%2F%2Fclassactivitycalculator.github.io%2F&text=Class%20Activity%20Calculator%3A%20Calculate%20the%20class%20activity%20grades%20of%20the%20ILI%20students.\" title=\"Telegram: Share Web Page\">Telegram</a> |\n <a href=\"https://www.facebook.com/dialog/share?app_id=2194746457255787&href=https%3A%2F%2Fclassactivitycalculator.github.io%2F\" title=\"Post to Facebook\">Facebook</a>\n <address><a href=\"https://t.me/MortezaMirmojarabian\" title=\"Telegram: Contact @MortezaMirmojarabian\" rel=\"author\">Give feedback</a></address>\n</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><sup>1</sup><sub><a href=\"https://codereview.stackexchange.com/a/215201/120114\">https://codereview.stackexchange.com/a/215201/120114</a></sub></p>\n\n<p><sup>2</sup><sub><a href=\"https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2\" rel=\"nofollow noreferrer\">https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:29:22.940",
"Id": "425587",
"Score": "0",
"body": "Thanks for the detailed review! \"_what actually changes within that function depending on the page - is it the range values and/or strings?_\" The `max` and `weight` values (no `weight`s on two pages), and the _CA_ ranges. I can't find a short way to generalize `setOutputValues()`. \"_should there be handling for no output element found below?_\" I'm not sure I understand what you mean. Each `fieldset` has an `output`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:21:18.323",
"Id": "425770",
"Score": "1",
"body": "No `weight` and a `weight` == 1 is the same so you could go with this (if you don't want to test if `weight` exist in `setOutputValues`). For the `max` you really just need to do exactly like you did for the `weight` (set a `data-max` and use it). The CA range is taking care of itself (with your `for`), in fact `setOutputValues()` is already mostly generalized really. For the `output `part he wanted to know if there was a need to test if `output` existed (you answered it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T07:39:51.147",
"Id": "426032",
"Score": "0",
"body": "@Nomis: \"_No `weight` and a `weight` == 1 is the same so you could go with this_\" Please see the [updates](https://codereview.stackexchange.com/a/220503/33793)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T16:22:33.630",
"Id": "220241",
"ParentId": "220084",
"Score": "4"
}
},
{
"body": "<h2>Updates</h2>\n\n<ul>\n<li>Simplified<pre>form.querySelector('[type=\"reset\"]').addEventListener('click', function(event) {</pre>to<pre>form.addEventListener('reset', function(event) {</pre>Thanks @Sᴀᴍ Onᴇᴌᴀ<br>\n<br></li>\n<li>Generalized <code>setOutputValues()</code> mainly by adding a <code>weight</code> to the rest of the <code>fieldset</code>s:<pre>var weight = fieldset.dataset.weight;<br>if (!weight) {weight = 1;}</pre>Thanks @Nomis<br>\n<br></li>\n<li>Simplified<pre>divOutput.value = 'CA: ' + (classActivity / (max / 100)).toFixed(1);</pre>to<pre>divOutput.value = 'CA: ' + (classActivity * 100 / max).toFixed(1);</pre><br>\n<br></li>\n</ul>\n\n<h2>script.js</h2>\n\n<pre><code>var form = document.querySelector('form');\n\nfunction averageInputValues(fieldset) {\n var totalValue = 0;\n var totalNumber = 0;\n var inputs = fieldset.querySelectorAll('input');\n for (var input of inputs) {\n if (!input.validity.valid) {\n return;\n }\n totalValue += Number(input.value);\n totalNumber += Boolean(input.value);\n }\n return totalValue / totalNumber;\n}\n\nfunction setOutputValues() {\n var max = form.querySelector('input').max;\n var totalWeightedAverage = 0;\n var totalWeight = 0;\n var fieldsets = form.querySelectorAll('fieldset');\n for (var fieldset of fieldsets) {\n var average = averageInputValues(fieldset);\n var fieldsetOutput = fieldset.querySelector('output');\n if (average == undefined) {\n fieldsetOutput.value = 'You may only enter 0 to ' + max + '.';\n } else if (isNaN(average)) {\n fieldsetOutput.value = 'Please enter a grade.';\n } else {\n fieldsetOutput.value = 'avg: ' + average.toFixed(1);\n }\n var weight = fieldset.dataset.weight;\n if (!weight) {\n weight = 1;\n }\n totalWeightedAverage += average * weight;\n totalWeight += Number(weight);\n }\n var classActivity = totalWeightedAverage / totalWeight;\n var divOutput = form.querySelector('div output');\n if (isNaN(classActivity)) {\n divOutput.value = '';\n } else if (max == 5) { // Adults: New\n divOutput.value = 'CA: ' + (classActivity * 100 / max).toFixed(1); // The class activity grade must be calculated out of 100.\n } else {\n divOutput.value = 'CA: ' + classActivity.toFixed(1);\n }\n}\n\nform.querySelector('[type=\"button\"]').addEventListener('click', setOutputValues);\n\nfunction detectChange() {\n var inputs = form.querySelectorAll('input');\n for (var input of inputs) {\n if (input.value) {\n return true;\n }\n }\n}\n\nform.addEventListener('reset', function(event) {\n if (detectChange() && !confirm('Your changes will be lost.\\nAre you sure you want to reset?')) {\n event.preventDefault();\n }\n});\n\nwindow.addEventListener('beforeunload', function(event) {\n if (detectChange()) {\n event.returnValue = 'Your changes may be lost.';\n }\n});\n</code></pre>\n\n<p><br></p>\n\n<h2>Adults: Old</h2>\n\n<pre><code><!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"description\" content=\"Calculate the class activity grades of the ILI students.\">\n <title>Class Activity Calculator</title>\n <link rel=\"icon\" href=\"favicon.ico\">\n <link rel=\"stylesheet\" href=\"style.css\">\n</head>\n\n<body>\n <header>\n <img src=\"logo.png\" alt=\"Logo\">\n <h1>Class Activity Calculator</h1>\n </header>\n <nav>\n <a href=\"index.html\" id=\"current\">Adults: Old</a>\n <a href=\"adults-new.html\">Adults: New</a>\n <a href=\"young-adults.html\">Young Adults</a>\n <a href=\"kids.html\">Kids</a>\n </nav>\n <main>\n <form autocomplete=\"off\">\n <fieldset data-weight=\"4\">\n <legend>Listening & Speaking</legend>\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <output></output>\n </fieldset>\n <fieldset data-weight=\"3\">\n <legend>Reading</legend>\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <output></output>\n </fieldset>\n <fieldset>\n <legend>Writing</legend>\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <input type=\"number\" step=\"any\" min=\"0\" max=\"100\">\n <output></output>\n </fieldset>\n <div>\n <button type=\"button\">Calculate</button>\n <output></output>\n <button type=\"reset\">Reset</button>\n </div>\n </form>\n </main>\n <footer>\n Share on <a href=\"https://t.me/share/url?url=https%3A%2F%2Fclassactivitycalculator.github.io%2F&text=Class%20Activity%20Calculator%3A%20Calculate%20the%20class%20activity%20grades%20of%20the%20ILI%20students.\" title=\"Telegram: Share Web Page\">Telegram</a> |\n <a href=\"https://www.facebook.com/dialog/share?app_id=2194746457255787&href=https%3A%2F%2Fclassactivitycalculator.github.io%2F\" title=\"Post to Facebook\">Facebook</a>\n <address><a href=\"https://t.me/MortezaMirmojarabian\" title=\"Telegram: Contact @MortezaMirmojarabian\" rel=\"author\">Give feedback</a></address>\n </footer>\n <script src=\"script.js\"></script>\n</body>\n\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T12:27:28.467",
"Id": "426164",
"Score": "0",
"body": "If it wasn't for those meddling kids with there 60 max, you could get away with only `divOutput.value = 'CA: ' + (classActivity / (max / 100)).toFixed(1);` for every classes in your last condition, since 100/100=1. Also, do you want me to update my example to show you how you could use only one page or is it clearer now ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T03:51:47.227",
"Id": "426234",
"Score": "0",
"body": "@Nomis: \"_If it wasn't for those meddling kids with there 60 max, you could get away with only `divOutput.value = 'CA: ' + (classActivity / (max / 100)).toFixed(1);` for every classes in your last condition, since 100/100=1._\" Exactly! \"_Also, do you want me to update my example to show you how you could use only one page or is it clearer now?_\" Yes, please: It will be useful at least for future reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T16:34:27.607",
"Id": "426329",
"Score": "0",
"body": "There you go, now my previous answer is alive (work on click). I made some adaptations to get a bug-free, similar-looking screen. On that note you should try to use more ids and classes and less tags in your `querySelector` (I had to change the `div output` one)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T07:25:53.253",
"Id": "220503",
"ParentId": "220084",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220241",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T08:11:53.277",
"Id": "220084",
"Score": "6",
"Tags": [
"javascript",
"html",
"css",
"calculator"
],
"Title": "Class Activity Calculator"
} | 220084 |
<p>I have written an answer to <a href="https://stackoverflow.com/questions/55924768/what-else-do-i-need-for-codehs-8-3-8-word-ladder">this question</a> on Stack Overflow. To make it easier for you, I have copy-pasted the question below.</p>
<blockquote>
<p>Your friend wants to try to make a word ladder! This is a list of
words where each word has a one-letter difference from the word before
it. </p>
<p>Here’s an example:</p>
<pre><code>cat
cot
cog
log
</code></pre>
<p>Write a program to help your friend. It should do the following:</p>
<ul>
<li><p>Ask your friend for an initial word.</p></li>
<li><p>Repeatedly ask them for an index and a letter.</p></li>
<li><p>You should replace the letter at the index they provided with the letter they enter.</p></li>
<li><p>You should then print out the new word.</p></li>
<li><p>Stop asking for input when the user enters -1 for the index.</p></li>
</ul>
</blockquote>
<p>My answer to this is:</p>
<pre><code>import os
get_index = 0
word = input("Enter a word: ")
for i in range(len(word)):
while True:
try:
get_index = int(input("Enter an index (-1 to quit): "))
if get_index == -1:
os._exit(0)
elif get_index < -1 or get_index > 2:
raise ValueError
except ValueError:
print ("Invalid index!")
else:
while True:
try:
letter = input("Enter a letter: ")
for c in letter:
if c.isupper():
raise ValueError
except ValueError:
print ("Character must be a lowercase letter!")
else:
if len(letter) > 1:
print ("Must be exactly one character!")
else:
word = word[:get_index] + letter + word[get_index + 1:]
print (word)
break
</code></pre>
<p>NOTE #1: Here is a link to the program run (output): <a href="https://stackoverflow.com/questions/55924768/what-else-do-i-need-for-codehs-8-3-8-word-ladder/55926231#55926231">OUTPUT</a></p>
<p>NOTE #2: I would also like to use an alternative for <code>os._exit()</code> as it takes time for the program to completely end.</p>
<p>So, I would like to know whether I could make this code shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [] | [
{
"body": "<p>While your code seems to work, the next step should be separating the different responsibilities of your code. As far as I can see, there are three:</p>\n\n<ul>\n<li>You have to ask the user for an index. It needs to be an integer in the range [-1, len(s)).</li>\n<li>You have to ask them for a replacement character. It must be exactly one lower case character.</li>\n<li>You need to actually run the game.</li>\n</ul>\n\n<p>The first two can be combined into a general function asking the user for input with type and validation:</p>\n\n<pre><code>def ask_user(message, type_=str, valid=lambda: True, invalid=\"Invalid\"):\n while True:\n try:\n user_input = type_(input(message))\n except ValueError:\n print(invalid)\n continue\n if not valid(user_input):\n print(invalid)\n continue\n return user_input\n</code></pre>\n\n<p>And your main program can then use this function. I would also change the internal data of the word to be a <code>list</code>, so you can easily replace characters. When printing the word, just use <code>\"\".join(word)</code>.</p>\n\n<pre><code>def play_word_ladder():\n word = list(input(\"Enter a word: \"))\n\n def valid_index(i):\n return i in range(-1, len(word))\n\n def valid_character(c):\n return len(c) == 1 and c.islower()\n\n while True:\n index = ask_user(\"Enter an index (-1 to quit): \",\n int, valid_index, \"Invalid index!\")\n if index == -1:\n return\n char = ask_user(\"Enter a letter: \", str, valid_character,\n \"Character must be one lowercase letter!\")\n word[index] = char\n print(\"\".join(word))\n</code></pre>\n\n<p>Note that your outer <code>for</code> loop is completely unnecessary.</p>\n\n<p>The game can be started under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script. Note that you don't need to manually exit the script, it will do so automatically at the end.</p>\n\n<pre><code>if __name__ == \"__main__\":\n play_word_ladder()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T12:50:33.000",
"Id": "425336",
"Score": "1",
"body": "Upvoted! I tested it and it worked perfectly. Definitely more efficiently than my code above :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T12:26:19.743",
"Id": "220134",
"ParentId": "220086",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220134",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T08:42:53.590",
"Id": "220086",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"game"
],
"Title": "Program for CodeHS 8.3.8: Word Ladder in Python 3"
} | 220086 |
<p>I want to write a python script to sort a huge file, say 2 GB in size, which contains logs in the following format - </p>
<pre><code>Jan 1 02:32:40 other strings but may or may not unique in all those lines
Jan 1 02:32:40 other strings but may or may not unique in all those lines
Mar 31 23:31:55 other strings but may or may not unique in all those lines
Mar 31 23:31:55 other strings but may or may not unique in all those lines
Mar 31 23:31:55 other strings but may or may not unique in all those lines
Mar 31 23:31:56 other strings but may or may not unique in all those lines
Mar 31 23:31:56 other strings but may or may not unique in all those lines
Mar 31 23:31:56 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Feb 1 03:52:26 other strings but may or may not unique in all those lines
Feb 1 03:52:26 other strings but may or may not unique in all those lines
Jan 1 02:46:40 other strings but may or may not unique in all those lines
Jan 1 02:44:40 other strings but may or may not unique in all those lines
Jan 1 02:40:40 other strings but may or may not unique in all those lines
Feb 10 03:52:26 other strings but may or may not unique in all those lines
</code></pre>
<p>I want to sort them basted on the timestamp.</p>
<p>I was able to get this working but for my code to succeed, I need to load the WHOLE file into a list.. this means it will be extremely inefficient from a memory utilization point of view. </p>
<p>Can you please suggest if there is a more efficient way where I can sort this by reading the file line by line or perhaps some other approach that I am not aware of ?</p>
<p>Here is my code - </p>
<pre><code># convert the log into a list of strings
with open("log.txt", 'r') as f:
lines = f.read().splitlines()
# writing the method which will be fed as a key for sorting
def convert_time(logline):
# extracting hour, minute and second from each log entry
h, m, s = map(int, logline.split()[2].split(':'))
time_in_seconds = h * 3600 + m * 60 + s
return time_in_seconds
sorted_log_list = sorted(lines, key=convert_time)
''' sorted_log_list is a "list of lists". Each list within it is a representation of one log entry. We will use print and join to print it out as a readable log entry'''
for lines in sorted_log_list:
print lines
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T11:00:43.250",
"Id": "425277",
"Score": "0",
"body": "Is `sort -M <logfile>` not working in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T11:07:42.667",
"Id": "425278",
"Score": "0",
"body": "Hi @yuri ! Sorry forgot to mention that I am trying to write a python script for this. Updated the title and description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T11:09:25.563",
"Id": "425279",
"Score": "0",
"body": "Ah apologies, I thought `or perhaps some other approach` meant approaches other than Python. Thanks for clarifying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T14:03:28.820",
"Id": "425284",
"Score": "0",
"body": "How did the entries become scrambled in the first place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T18:22:23.493",
"Id": "425296",
"Score": "0",
"body": "@200_success - This is a quiz question :) In real world, although the timestamps won't be scrambled, the ask would likely be to sort the log file by severity or some other column. Those would definitely always be all over the place as each log entry is unique."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T18:55:09.673",
"Id": "425300",
"Score": "0",
"body": "Try putting them in a list, and use [name of list].sort().\nhttps://www.geeksforgeeks.org/python-list-sort/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T19:09:44.893",
"Id": "425301",
"Score": "1",
"body": "@BadAtGeometry - Won't the list take the same amount of memory as the file data? My code at present is doing what you are suggesting already :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T20:19:41.500",
"Id": "425305",
"Score": "0",
"body": "2GB isn't really huge and there's nothing inefficient about reading the whole thing into memory. A merge sort (which is how you sort data that doesn't fit in memory) is going to be slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T01:31:04.040",
"Id": "425309",
"Score": "2",
"body": "@OhMyGoodness - 2 GB is a random size picked up. The problem statement is \"how to sort a HUGE file in python in the most efficient way\". It could be something with millions of records or more. I found this article that so far seems to be the closest match for what I am looking to do . It is written in python 3 - http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T02:03:04.113",
"Id": "425311",
"Score": "2",
"body": "the most efficient way is to load the file into memory and sort it there. If that's infeasible, you'll get better answers if you provide concrete details, like how big the log files are, how long the records are, and how much memory is available."
}
] | [
{
"body": "<p>You're ignoring the Date-part of the timestamps; it doesn't sound like that's on purpose. \n(Also, the year is missing altogether, which should make us quite nervous.) \nAlso, let's use explicit <a href=\"https://docs.python.org/3.5/library/datetime.html#datetime.datetime\" rel=\"nofollow noreferrer\">datetime utilities</a> and <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">regexes</a>. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\nimport re\n\ntimestamp_regex = re.compile(\"[^:]+:\\d\\d:\\d\\d\")\n\ndef convert_time(logline):\n stamp = timestamp_regex.match(logline).group() #this will error if there's no match.\n d = datetime.strptime(stamp, \"%b %e %H:%M:%S\")\n return int(d.timestamp())\n</code></pre>\n\n<p>As for the rest, the comments are right that we can't do much unless we know exactly <em>what it would mean for the solution to be improved</em>. </p>\n\n<p>If the concern is just to handle the biggest file with the least ram, something like this might work: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def save_where_we_can_find_it(line, temp_file):\n retval = temp_file.tell()\n temp_file.write(line)\n return retval\n\ndef fetch_line(location, temp_file):\n temp_file.seek(location)\n return temp_file.readline()\n\nitems = []\n\nwith open(\"log.txt\", 'r') as original, open(\".temp.log.txt\", 'w') as temp:\n for line in original:\n items.append((convert_time(line), save_where_we_can_find_it(line, temp)))\n\nitems.sort(key = lambda pair: pair[0]) #sort-in-place isn't necessarily a good idea; whatever.\n\nwith open(\".temp.log.txt\", 'r') as temp:\n for (stamp, location) in items:\n print(fetch_line(location, temp))\n\nimport os\nos.remove(\".temp.log.txt\")\n</code></pre>\n\n<p>But this is just a really inefficient way using a scratch-file. Better to register scratch-space in the OS, and then do your file manipulation \"in memory\". </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T17:21:18.130",
"Id": "220195",
"ParentId": "220089",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T10:56:35.410",
"Id": "220089",
"Score": "2",
"Tags": [
"python",
"python-2.x",
"sorting",
"datetime",
"memory-optimization"
],
"Title": "Python script for sorting a huge log file based on timestamps"
} | 220089 |
<p><code>pointer_traits</code> is a lightweight trait that provides a uniform interface to builtin pointers and user-defined fancy pointers. That said, things like <code>element_type</code> require
template metaprogramming techniques to determine. This makes <code>pointer_traits</code> a good exercise.</p>
<p>Here's my re-implementation under the name <code>my_std::pointer_traits</code>, put in a separate header <code>pointer_traits.hpp</code> because <code><memory></code> is way too comprehensive:</p>
<pre><code>// C++17 pointer_traits implementation
#ifndef INC_POINTER_TRAITS_HPP_60HzB0lbek
#define INC_POINTER_TRAITS_HPP_60HzB0lbek
#include <cstddef> // for std::ptrdiff_t
#include <memory> // for std::addressof
#include <type_traits> // for std::add_lvalue_reference
namespace my_std {
template <class Ptr>
struct pointer_traits;
namespace pt_detail {
template <class Tmpl>
struct get_first_param { };
template <template <class, class...> class Tmpl, class T, class... Args>
struct get_first_param<Tmpl<T, Args...>> {
using type = T;
};
template <class Tmpl>
using get_first_param_t = typename get_first_param<Tmpl>::type;
template <class Tmpl, class U>
struct rebind_first_param { };
template <template <class, class...> class Tmpl, class T, class... Args, class U>
struct rebind_first_param<Tmpl<T, Args...>, U> {
using type = Tmpl<U, Args...>;
};
template <class Tmpl, class U>
using rebind_first_param_t = typename rebind_first_param<Tmpl, U>::type;
template <class Ptr>
auto element(int) -> typename Ptr::element_type;
template <class Ptr>
auto element(long) -> get_first_param_t<Ptr>;
template <class Ptr>
auto diff(int) -> typename Ptr::difference_type;
template <class Ptr>
auto diff(long) -> std::ptrdiff_t;
template <class Ptr, class U>
auto rebind(int) -> typename Ptr::template rebind<U>;
template <class Ptr, class U>
auto rebind(long) -> rebind_first_param_t<Ptr, U>;
}
template <class Ptr>
struct pointer_traits {
using pointer = Ptr;
using element_type = decltype(pt_detail::element<Ptr>(0));
using difference_type = decltype(pt_detail::diff<Ptr>(0));
template <class U>
using rebind = decltype(pt_detail::rebind<Ptr, U>(0));
static pointer pointer_to(std::add_lvalue_reference<element_type> r)
{
return Ptr::pointer_to(r);
}
};
template <class T>
struct pointer_traits<T*> {
using pointer = T*;
using element_type = T;
using difference_type = std::ptrdiff_t;
template <class U>
using rebind = U*;
static pointer pointer_to(std::add_lvalue_reference<element_type> r)
{
return std::addressof(r);
}
};
}
#endif
</code></pre>
<p>I used <a href="https://timsong-cpp.github.io/cppwp/n4659/" rel="nofollow noreferrer">N4659</a> as a reference.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-18T08:44:14.947",
"Id": "533398",
"Score": "0",
"body": "Do you have a test program? Or at least a motivating example of where this is useful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-18T09:05:19.867",
"Id": "533401",
"Score": "0",
"body": "I'd like to know what the `rebind` member is for - that's one thing that's not also in `iterator_traits<T*>`."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T11:20:26.890",
"Id": "220090",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"template-meta-programming"
],
"Title": "C++17 pointer_traits implementation"
} | 220090 |
<p>I would like to extracts small word parts (quadgrams) from text. Example:</p>
<pre><code>hello world
</code></pre>
<p>results in:</p>
<pre><code>_hel, hell, ello, llo_, lo_w ...
</code></pre>
<p>This my basic attempt thus far:</p>
<pre><code>text <- "hello world"
number_of_characters <- nchar(text)
quad_gram_list <- ""[-1]
for (i in 1:number_of_characters) {
end <- i + 3
if (end > number_of_characters) {
end <- number_of_characters
}
temp <- substring(text, i, end)
if (nchar(temp) == 4) {
quad_gram_list <- append(quad_gram_list, temp)
}
}
</code></pre>
<p>Any improvement suggestions would be very much appreciated.</p>
| [] | [
{
"body": "<p>Your loop approach works but seems a bit convoluted. For instance you could rewrite the <code>for</code> loop this way:</p>\n\n<pre><code>for (i in 1:number_of_characters) {\n\n end <- i + 3\n\n if (end <= number_of_characters) {\n temp <- substring(text, i, end)\n quad_gram_list <- append(quad_gram_list, temp)\n }\n}\n</code></pre>\n\n<p>But anyway it's generally better to avoid loops in R.</p>\n\n<p>Also note that:</p>\n\n<ul>\n<li>you should use <code>character(0)</code> instead of <code>\"\"[-1]</code></li>\n<li><code>:</code> is to be avoided because of undesired behaviour on edge cases. It's better to use <code>seq_len()</code>.</li>\n</ul>\n\n<p>Here are two alternative solutions:</p>\n\n<p><strong>1) Using base R:</strong></p>\n\n<pre><code>unlist(lapply(seq_len(nchar(text) - 3), function(i) substring(text, i, i + 3)))\n# [1] \"hell\" \"ello\" \"llo \" \"lo w\" \"o wo\" \" wor\" \"worl\" \"orld\"\n</code></pre>\n\n<p><strong>2) Using <code>tokenizers</code>:</strong></p>\n\n<pre><code>library(tokenizers)\n\ntokenize_character_shingles(\n text,\n n = 4,\n strip_non_alphanum = FALSE,\n simplify = TRUE\n)\n# [1] \"hell\" \"ello\" \"llo \" \"lo w\" \"o wo\" \" wor\" \"worl\" \"orld\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T00:28:17.907",
"Id": "425469",
"Score": "2",
"body": "`substring` is vectorized so you can do: `start <- head(seq(nchar(text)), -3); stop <- tail(seq(nchar(text)), -3); substring(text, start, stop)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T23:33:47.140",
"Id": "220157",
"ParentId": "220092",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220157",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T11:37:35.797",
"Id": "220092",
"Score": "3",
"Tags": [
"strings",
"r"
],
"Title": "Extracting small word parts (quadgrams) from text using R"
} | 220092 |
<p>Inspired by <a href="https://stackoverflow.com/questions/55808053/how-to-check-if-a-integer-is-a-cube-or-not-in-common-lisp">a question</a> on SO I was checking how to calculate the cube root of an integer and found a C-ish solution on <a href="http://www.hackersdelight.org/hdcodetxt/icbrt.c.txt" rel="nofollow noreferrer">Hacker's Delight</a>:</p>
<pre class="lang-c prettyprint-override"><code>// Program for computing the integer cube root.
// Max line length is 57, to fit in hacker.book.
#include <stdio.h>
#include <stdlib.h> //To define "exit", req'd by XLC.
// Execution time is 3 + (11 + mul)11 = 124 + 11*mul (avg) cycles.
// ------------------------------ cut ----------------------------------
int icbrt1(unsigned x) {
int s;
unsigned y, b;
y = 0;
for (s = 30; s >= 0; s = s - 3) {
y = 2*y;
b = (3*y*(y + 1) + 1) << s;
if (x >= b) {
x = x - b;
y = y + 1;
}
}
return y;
}
</code></pre>
<p>I tried to adapt this to Common Lisp and came up with this:</p>
<pre class="lang-lisp prettyprint-override"><code>(defun icbrt (x)
"Returns the integer cube root of X."
(assert (plusp x) (x) "Please provide a positive integer! ~D < 0" x)
(loop for s downfrom 30 to 0 by 3
for y of-type integer = 0 then (* 2 y)
for b of-type integer = (ash (1+ (* 3 y (1+ y))) s)
when (>= x b)
do (incf y)
(setf x (- x b))
finally (return y)))
</code></pre>
<p>While it works I am still wondering if it could be express more idiomatic. I am especially unsure about the <code>setf</code> within the <code>loop</code> construct.</p>
<p>Any comment is gratefully acknowledged.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T19:45:51.050",
"Id": "425304",
"Score": "2",
"body": "I find the translation substantially correct and even idiomatic: a minor point is to change `(setf x (- x b))` with the more concise `(decf x b)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T09:58:34.783",
"Id": "425398",
"Score": "0",
"body": "Thanks! I forget about `decf` too often."
}
] | [
{
"body": "<p>There is not much to say about this code, it is fine.</p>\n\n<p>You can get rid of <code>incf</code> and <code>setf</code>; the varying <code>x</code> is replaced by a variable named <code>z</code>; I express the comparison as a boolean variable <code>greater</code> (for lack of a better name), which gives:</p>\n\n<pre><code>(defun icbrt (x)\n \"Returns the integer cube root of X.\"\n (check-type x (integer 1))\n (locally (declare (type (integer 1) x))\n (loop\n for s downfrom 30 to 0 by 3\n for z of-type integer = x then (if greater (- z b) z)\n for y of-type integer = 0 then (* 2 (if greater (1+ y) y))\n for b of-type integer = (ash (1+ (* 3 y (1+ y))) s)\n for greater = (>= z b)\n finally (return y))))\n</code></pre>\n\n<p>Note also that I removed the assertion and used <code>check-type</code> instead. While the additional comment is nice in the <code>assert</code> expression, it adds to the things developers have to maintain (think consistency of error messages), whereas check-type is supposedly already displaying the right amount of information to the user, and throws the right kind of exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T10:00:55.143",
"Id": "425399",
"Score": "0",
"body": "Very helpful hint to use `check-type`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T10:27:57.740",
"Id": "425403",
"Score": "0",
"body": "@MartinBuchmann Thanks. I did not suggest it first because I am not sure if it is correct, but maybe using more specific types like fixnums is possible here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T12:52:31.280",
"Id": "425414",
"Score": "0",
"body": "For most cases `fixnum` should be sufficient, i guess."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T09:52:03.823",
"Id": "220174",
"ParentId": "220093",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220174",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T12:46:08.173",
"Id": "220093",
"Score": "6",
"Tags": [
"integer",
"common-lisp"
],
"Title": "Calculating the cube root"
} | 220093 |
<p>I'm learning python and created a number guessing game on which I would like to get your feedback on the structure and style of the program.</p>
<pre><code>import random
LOWER_NUMBER = 1
HIGHEST_NUMBER = 10
def print_header():
print("-" * 40)
print("Welcome to the number guessing game")
print("-" * 40)
def user_input():
"""Collect and validate the entries made by the users
Returns
-------
int
Gives back the validated number entered by the user.
"""
while True:
try:
guess = int(
input(f'Enter your Guess of a number between '
f'{LOWER_NUMBER} - {HIGHEST_NUMBER}: '))
if guess < LOWER_NUMBER or guess > HIGHEST_NUMBER:
print("The entered number is out of range, try again.")
continue
except ValueError:
print('you did not enter a number, please try again.')
continue
else:
break
return guess
def generate_number_to_guess(lower_number, higher_number):
"""Generates a random number between the given lowest and highest number
Parameters
----------
lower_number : int
Lowest number for the generator
higher_number : int
highest number for the generator
Returns
-------
int
returns the generated random number that is in the given range.
"""
return random.randint(lower_number, higher_number)
def play_again():
"""Perform and validate entry for a next game
Returns
-------
string
returns the validated user entry for a next game.
"""
while True:
new_game = input(
"Would you like to play again? [y]es/[n]o: ")
if new_game.lower() not in ["n", "y"]:
print('Wrong entry please use y or n')
continue
else:
break
return new_game.lower()
def start_game():
"""This is the main loop that runs the app.
"""
highscore = 0
while True:
print_header()
number_to_guess = generate_number_to_guess(LOWER_NUMBER,
HIGHEST_NUMBER)
guess = 0
count = 0
while guess != number_to_guess:
guess = user_input()
count += 1
if guess < number_to_guess:
print("It's higher")
elif guess > number_to_guess:
print("It's lower")
else:
print(
f'\nYou geussed the right number and needed {count} tries')
if count < highscore or highscore == 0:
highscore = count
# validate the input for a new game
another_game = play_again()
if another_game == 'y':
print(f"\n\nThe HIGHSCORE is {highscore}")
continue
elif another_game == 'n':
print("\n Thanks for playing, see you next time!")
break
if __name__ == "__main__":
start_game()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T18:32:14.387",
"Id": "425298",
"Score": "0",
"body": "Take a look at this - https://codereview.stackexchange.com/questions/220080/guess-the-numberpython and see if you find anything that helps you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T07:57:23.783",
"Id": "425394",
"Score": "0",
"body": "Removing the info about a bug won't fix the code... it's still broken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T10:42:03.187",
"Id": "425405",
"Score": "0",
"body": "@t3chb0t I did not remove info about a bug. \nThe additional info that has been removed was related to an optimization that did not work as I expected, but this seems to be out of scope of the questions that should be put forward here, as this is about code review, not exploring suggestions."
}
] | [
{
"body": "<p>There is a lot of things done right in your program. The code is structured into functions, there are docstrings, you validate user input and you even have a main guard. Still there is room for improvement.</p>\n\n<h1>code duplication</h1>\n\n<p>This is a minor issue in your code but I do not want to skip it. In</p>\n\n<pre><code>def print_header():\n print(\"-\" * 40)\n print(\"Welcome to the number guessing game\")\n print(\"-\" * 40)\n</code></pre>\n\n<p>which could read</p>\n\n<pre><code>def print_header():\n dashed_line = \"-\" * 40\n print(dashed_line)\n print(\"Welcome to the number guessing game\")\n print(dashed_line)\n</code></pre>\n\n<p>The reason for not duplicate code (even if it is less code) is maintenance. If you ever chose to increase the line length there is a single place to edit.\nIn your case the chance to miss the other number is low. But keep that in mind.</p>\n\n<h1>naming of functions and variables</h1>\n\n<p><code>user_input()</code> is not the best name as there is many user interaction. A better name would be <code>get_user_guess()</code>.\nAlso <code>play_again()</code> does not play but getting user input again. Might be <code>get_user_play_again()</code>.</p>\n\n<h1>overdone design</h1>\n\n<p>Your function</p>\n\n<pre><code>def generate_number_to_guess(lower_number, higher_number):\n \"\"\"Generates a random number between the given lowest and highest number\n\n Parameters\n ----------\n lower_number : int\n Lowest number for the generator\n\n higher_number : int\n highest number for the generator\n\n Returns\n -------\n int\n returns the generated random number that is in the given range.\n \"\"\"\n return random.randint(lower_number, higher_number)\n</code></pre>\n\n<p>does nothing but calling a standard(!) function with the same parameter signature. Instead call the standard function directly.\nSuch detors are not good in terms of maintainability. Every reasonably experienced python programmer does know <code>randint()</code>.\nIf reading that in a code he exactly knows what's happening. If he stumbles onto a call of your function he must immediately look upon your implementation to get to know what it does.\nHe must not trust your docstring (<code>between</code>?!) but read the code. He is even forced to write unittests if they are not existing and there are some lines of implementation.\nIn your case it is a pure delegation to a standard function, so the reviewer is happy to find a reliable implementation. But he lost time for no reason.\nDo not do this.</p>\n\n<p>Beside that issues your code is very maintainable! It is structured and readable. The complexity of your functions is reasonable. Be very careful with docstrigs.\nYour docstring starts with</p>\n\n<pre><code>\"\"\"Generates a random number between the given lowest and highest number\n</code></pre>\n\n<p>while <code>randint.__doc__</code> returns</p>\n\n<pre><code>'Return random integer in range [a, b], including both end points.\\n '\n</code></pre>\n\n<p>This is 'between' vs 'including both endpoints'.</p>\n\n<h1>global constants</h1>\n\n<p>Simply try to avoid them, especially if they are not naturally constant. You nearly did it right in the superfluous function <code>generate_number_to_guess</code> where you decided to pass tarameters instead of accessing the globals directly.\nHowever you stopped early on the process of passing. If you also pass the variables to <code>start_game()</code></p>\n\n<pre><code>def start_game(lower_number, higher_number):\n</code></pre>\n\n<p>and call the generator</p>\n\n<pre><code> number_to_guess = generate_number_to_guess(lower_number,\n higher_number)\n</code></pre>\n\n<p>you are done with that path. Now you also pass these numbers to <code>user_input()</code></p>\n\n<pre><code>def user_input(lower_number, higher_number):\n</code></pre>\n\n<p>and eliminate the globals in there.</p>\n\n<p>You end up with shouting variable names (no global constants)</p>\n\n<pre><code>LOWER_NUMBER = 1\nHIGHEST_NUMBER = 10\n\n# [...]\n\nif __name__ == \"__main__\":\n start_game()\n</code></pre>\n\n<p>which you change to</p>\n\n<pre><code>if __name__ == \"__main__\":\n start_game(1, 10)\n</code></pre>\n\n<p>If a value is not globally constant for a function - pass it as a parameter.\nThe function is then loosly coupled to the rest and is perfectly testable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T21:03:07.740",
"Id": "427032",
"Score": "0",
"body": "Thank you very much for the time you took to give me such detailed feedback, it's very much appreciated.\n\nI'm always doubting if I'm not going too granular in breaking down things. So thanks for the insight into the mistakes that I made.\n\nI also take your comments to heart on constants and will keep this in mind for future programs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:11:02.760",
"Id": "220418",
"ParentId": "220095",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220418",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T13:56:48.893",
"Id": "220095",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"number-guessing-game"
],
"Title": "Number guessing game in Python"
} | 220095 |
<p>Am trying to write a function that takes an array as a parameter, and then returns the highest and lowest number from the array without sorting the array. Below is my code, How can I make it better.</p>
<pre><code>function lowestAndHighest(arr) {
this.lowest = 0;
this.highest = 1;
//This function returns the lowest number
this.lowestNum = () => {
arr.forEach(elem => {
if(this.lowest > elem) {
return this.lowest = elem;
}
});
return this.lowest;
}
//This function returns the higest number
this.highestNum = () => {
arr.forEach(elem => {
if(this.highest < elem) {
this.highest = elem;
}
});
return this.highest;
}
}
let num = new lowestAndHighest([30,3,6,8,1,0,-10, -60]);
console.log(num.lowestNum());
console.log(num.highestNum());
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T14:03:44.323",
"Id": "425285",
"Score": "3",
"body": "Unless I am mistaken, your code would compute the lowest number in [3, 4, 5] as 0, and the highest number in [-3, -4, -5] as 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T14:06:11.300",
"Id": "425286",
"Score": "0",
"body": "Yes exactly the problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T14:48:23.387",
"Id": "425288",
"Score": "2",
"body": "Welcome to CR! I'm voting to close this as [off-topic](https://codereview.stackexchange.com/help/on-topic) because the code is not working as intended. Having said that, why not simply use builtins: `Math.max(...[1,4,5,6,7])`?"
}
] | [
{
"body": "<p>I just saw my error now </p>\n\n<pre><code>function lowestAndHighest(arr) {\n\n this.lowest = arr[0];//corrected\n this.highest = arr[0];//corrected\n\n //This function returns the lowest number\n this.lowestNum = () => {\n arr.forEach(elem => {\n if(this.lowest > elem) {\n return this.lowest = elem; \n } \n });\n return this.lowest;\n }\n\n //This function returns the higest number\n this.highestNum = () => {\n arr.forEach(elem => {\n if(this.highest < elem) {\n this.highest = elem;\n }\n });\n return this.highest;\n }\n}\n\nlet num = new lowestAndHighest([30,3,6,8,1,0,-10, -60]);\nconsole.log(num.lowestNum());\nconsole.log(num.highestNum());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T03:30:16.877",
"Id": "425312",
"Score": "0",
"body": "Now, what is the result for [Martin R's arrays](https://codereview.stackexchange.com/questions/220096/highest-and-lowest-number/220097#comment425285_220096)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T15:18:28.800",
"Id": "425353",
"Score": "0",
"body": "It is working as intended"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:30:40.100",
"Id": "425365",
"Score": "0",
"body": "I misread the lambda assigned to this.lowestNum - irritating for the extraneous `return` the lambda assigned to this.highestNum doesn't show."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T14:21:49.270",
"Id": "220097",
"ParentId": "220096",
"Score": "-1"
}
},
{
"body": "<p><code>How can I make [the code presented] better</code> </p>\n\n<p>Give <a href=\"https://en.m.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">Test First</a> a try. </p>\n\n<p>Document your source code, <em>in the source code</em>: what is the goal of \"any\" given piece? (\"The <code>This function returns the higest number</code> comments\" <em>are</em> a step in the right direction. (Your IDE doesn't check spelling?))</p>\n\n<p>Be consistent. (In addition to a double blank,) There is an irritating difference between</p>\n\n<pre><code>if(this.lowest > elem) {\n return this.lowest = elem;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if(this.highest < elem) {\n this.highest = elem;\n}\n</code></pre>\n\n<p>If your goal was to keep the number of comparisons low, there is a simple technique taking you half way to optimal.</p>\n\n<p>(For all I don't know about ECMAScript & JSDoc, The Simplest Thing That Could Possibly Work might be</p>\n\n<pre><code>/* Returns minimum and maximum value in values\n * @param {Array<number>} values */\nfunction lowestAndHighest(values) {\n return [ Math.min.apply(Math, values),\n Math.max.apply(Math, values) ];\n}\n</code></pre>\n\n<p>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T06:08:39.273",
"Id": "220120",
"ParentId": "220096",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T13:59:17.463",
"Id": "220096",
"Score": "-4",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Highest and lowest number"
} | 220096 |
<p>Made a very simple calculator in Python. The program has the following features:</p>
<ol>
<li>All the basic operators can be used. '+', '-', '*', '**', '/', and '//'.</li>
<li>The user can start the program again.</li>
<li>The previous output is available for the user to use again.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def start(out='temp'):
# Get the input from the user and pass all the values to verify.
# Explicit test is used because the output can be zero.
if out != 'temp':
x = out
print('\nFirst number: ', x)
else:
x = input('\nFirst number: ')
op = input('Operator: ')
y = input('Second number: ')
verify(x, op, y)
def verify(x, op, y):
# Check if the operator and the numbers entered are valid.
# If any input is invalid call start and get input again.
# If inputs are valid pass all the values to calc.
ops = ['+', '-', '*', '**', '/', '//']
if op in ops:
try:
x, y = int(x), int(y)
except ValueError:
print('Numbers are not valid.\n')
start()
else:
calc(x, op, y)
else:
print('Please enter a valid operator.\n')
start()
def calc(x, op, y):
# Use eval to calculate the output and pass the output to
# restart.
out = eval(f'x {op} y')
print('Output:', out)
restart(out)
def restart(out):
# User can start the process again. The previous output can be used as
# the first number.
re = input('Start again? (y/n): ')
if re == 'y':
use_out = input(
'Use the previous output as the first number? (y/n): ')
if use_out == 'y':
start(out=out)
else:
start()
else:
print('Calc is now closed.')
start()
</code></pre>
<p>Here's a sample output.</p>
<pre><code>First number: 5
Operator: *
Second number: 9
Output: 45
Start again? (y/n): y
Use the previous output as the first number? (y/n): y
First number: 45
Operator: //
Second number: 2
Output: 22
Start again? (y/n): n
Calc is now closed.
</code></pre>
<p>I am looking for ways to make the code more readable, minimize redundancy, improving the overall design, etc. Any help would be appreciated!</p>
| [] | [
{
"body": "<p>Your program is easy to read and does all the necessary input validation. That's good.</p>\n\n<p>The error messages should be more helpful. If the user enters an invalid operator, you should tell them which operators are valid:</p>\n\n<pre><code>print(f'Please enter a valid operator: {' '.join(ops)}\\n')\n</code></pre>\n\n<p>Every use of <code>eval</code> is dangerous. If you pass unvalidated input to it, users might be able to run arbitrary Python code. You currently do the validation in <code>verify</code> and the actual calculation in <code>calc</code>. That's nicely separated, but it can also lead to a situation where you later call <code>calc</code> by accident with unvalidated input. To avoid this, most calculator programs use a dictionary of operators:</p>\n\n<pre><code>binops = {\n '+': lambda a, b: return a + b,\n '-': lambda a, b: return a - b,\n # and so on\n}\n\ntry:\n return binops[op](x, y)\nexcept KeyError, e:\n print(f'Invalid operator {op!r}, valid operators are {sorted(ops.keys())}')\n</code></pre>\n\n<p>One unfortunate thing about the above code is that <code>ops.keys()</code> returns the operators in an unspecified order. Therefore I had to add the <code>sorted</code> call.</p>\n\n<p>Each of your functions calls the continuation function at the end. When you try a long session with the calculator (about 5000 calculations), it will raise an exception. Whenever a function is called, Python remembers where it was called from, and it can remember only a few nested function calls. Therefore it is more common to use <code>while</code> loops for representing repetition. See <a href=\"https://stackoverflow.com/q/1359197\">https://stackoverflow.com/q/1359197</a> for more details.</p>\n\n<p>As a user of the calculator, I don't like to enter the numbers and operators separately. As the next step the calculator should allow inputs like <code>3+5</code> and <code>7 - -9</code> and <code>+7--9</code>. You can do this by using regular expressions.</p>\n\n<p>The current code asks many questions individually. Instead of asking whether to reuse the result from the last calculation, you could print the result in the form <code>ans1 = 8</code> and allow the user to write expressions like <code>ans4 * ans5</code>. A calculator session might then look like:</p>\n\n<pre><code>> 123\nans1 = 123\n\n> 456\nans1 = 456\n\n> 3 + ans1\nans3 = 126\n\n> ans3 + ans3\nans4 = 252\n\n> result = ans4\nresult = 252\n\n> result + result\nans5 = 504\n</code></pre>\n\n<p>This way the calculator remembers all previous results, and by using the <code>=</code> operator, you can name individual results and refer to them via that name, just like variables in Python. All you need for this is a dictionary and a counter (for the automatic variable names like <code>ans4</code>):</p>\n\n<pre><code>vars = {}\nans = 0\n\ndef store_var(name, value):\n vars[name] = value\n\ndef store_auto_var(value):\n global ans\n ans += 1\n name = 'ans' + ans\n vars[name] = value\n</code></pre>\n\n<p>These are the basic building blocks for building a really powerful calculator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T05:36:08.503",
"Id": "425317",
"Score": "2",
"body": "A better solution to using regular expressions to parse the input is to use the [shuntung yard algorithm](https://en.m.wikipedia.org/wiki/Shunting-yard_algorithm)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T04:34:10.537",
"Id": "220115",
"ParentId": "220098",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T14:33:47.587",
"Id": "220098",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "A simple python3 calculator"
} | 220098 |
<p>I have started learning PyQt5 and wanted to create a simple window to test my skills.
So I have created this window and I want to receive reviews on any aspect of the code.</p>
<pre><code>from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtWidgets import QVBoxLayout,QSplitter, QFormLayout, QLabel, QFrame, QPushButton
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.create_menu_bar()
self.vbox = QVBoxLayout()
self.create_body()
self.show()
def create_menu_bar(self):
title = 'First Porgram'
self.setWindowTitle(title)
self.setGeometry(300, 150, 500, 300)
self.setStyleSheet('background-color:#333;color:#ccc')
self.setFont(QFont('Serif', 10))
self.menu_bar = self.menuBar()
self.file_menu = self.menu_bar.addMenu("File")
self.file_menu.addAction('New')
self.file_menu.addAction('Open')
self.file_menu.addAction('Save')
self.file_menu.addAction('Save as')
self.file_menu.addAction('Exit')
self.view_menu = self.menu_bar.addMenu("View")
self.view_menu.addAction('set Full Screen')
self.view_menu.addAction('show Status Bar')
self.edit_menu = self.menu_bar.addMenu("Edit")
self.edit_menu.addAction('Cut')
self.edit_menu.addAction('Copy')
self.edit_menu.addAction('Paste')
self.edit_menu.addAction('Find')
self.edit_menu.addAction('Replace')
self.help_menu = self.menu_bar.addMenu("Help")
self.help_menu.addAction('Help')
self.help_menu.addAction('About')
def create_body(self):
form_frame = QFrame()
form_frame.setFrameShape(QFrame.StyledPanel)
form_frame.setMinimumWidth(150)
form_lay = QFormLayout()
f_label = QLabel('Welcome')
s_label = QLabel('Installation')
p_push = QPushButton('Sign in')
p_push.setContentsMargins(10, 20, 10, 10)
self.vbox = QVBoxLayout()
form_lay.addRow(f_label)
form_lay.addRow(s_label)
form_lay.addRow(p_push)
form_frame.setLayout(form_lay)
ver_frame = QFrame()
ver_frame.setFrameShape(QFrame.StyledPanel)
ver_box = QVBoxLayout()
ver_box.setContentsMargins(25, 20, 25, 25)
intro_label = QLabel("Welcome to The Open Space ")
intro_label.setFont(QFont('Serif', 16))
ver_box.addWidget(intro_label)
ver_frame.setLayout(ver_box)
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(form_frame)
splitter.addWidget(ver_frame)
self.vbox.addWidget(splitter)
self.setCentralWidget(splitter)
def contextMenuEvent(self, event):
men = QMenu()
men.addAction('New')
men.addAction('Open')
quit = men.addAction('Quit')
action = men.exec_(self.mapToGlobal(event.pos()))
if action is quit:
self.close()
def main():
app = QApplication(sys.argv)
win = Window()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
<p>here is a screenshot of my window
<a href="https://i.stack.imgur.com/JGN8t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JGN8t.png" alt="enter image description here"></a></p>
<p>Also, how can I add to a top margin on my sign in button, and is there any way I can inherit my context menu's color from my class?</p>
| [] | [
{
"body": "<p><strong>Qt Style Sheets</strong> Reference <a href=\"https://doc.qt.io/qt-5/stylesheet-reference.html\" rel=\"nofollow noreferrer\">https://doc.qt.io/qt-5/stylesheet-reference.html</a></p>\n\n<blockquote>\n <p>Qt Style Sheets support various properties, pseudo-states, \n .and subcontrols that make it possible to customize the look of widgets.</p>\n</blockquote>\n\n<p><strong>Qt Style Sheets Examples</strong> <a href=\"https://doc.qt.io/archives/qt-4.8/stylesheet-examples.html\" rel=\"nofollow noreferrer\">https://doc.qt.io/archives/qt-4.8/stylesheet-examples.html</a></p>\n\n<p>Try it:</p>\n\n<pre><code>import sys\nfrom PyQt5.QtWidgets import (QMainWindow, QApplication, QVBoxLayout, QSplitter, \n QFormLayout, QLabel, QFrame, QPushButton, \n QMenu, QAction) # + \nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont, QIcon\n\n\nclass Window(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.create_menu_bar()\n# self.vbox = QVBoxLayout() # -\n self.create_body()\n\n def create_menu_bar(self):\n self.menu_bar = self.menuBar()\n\n self.file_menu = self.menu_bar.addMenu(\"File\")\n self.file_menu.addAction('New')\n self.file_menu.addAction('Open')\n self.file_menu.addAction('Save')\n self.file_menu.addAction('Save as')\n\n# self.file_menu.addAction('Exit') \n # +++\n self.exit_menu = QAction(QIcon(\"D:/_Qt/img/exit.png\"),'&Exit', self)\n self.exit_menu.setShortcut('Ctrl+Q')\n self.exit_menu.triggered.connect(self.close)\n self.file_menu.addAction(self.exit_menu) \n\n self.view_menu = self.menu_bar.addMenu(\"View\")\n self.view_menu.addAction('set Full Screen')\n self.view_menu.addAction('show Status Bar') \n\n self.edit_menu = self.menu_bar.addMenu(\"Edit\")\n self.edit_menu.addAction('Cut')\n self.edit_menu.addAction('Copy')\n self.edit_menu.addAction('Paste')\n self.edit_menu.addAction('Find')\n self.edit_menu.addAction('Replace') \n\n self.help_menu = self.menu_bar.addMenu(\"Help\")\n self.help_menu.addAction('Help')\n self.help_menu.addAction('About')\n\n def create_body(self):\n form_frame = QFrame()\n form_frame.setFrameShape(QFrame.StyledPanel)\n form_frame.setMinimumWidth(150)\n\n f_label = QLabel('Welcome')\n s_label = QLabel('Installation')\n p_push = QPushButton('Sign in')\n p_push.setContentsMargins(10, 20, 10, 10)\n\n form_lay = QFormLayout()\n form_lay.addRow(f_label)\n form_lay.addRow(s_label)\n form_lay.addRow(p_push)\n form_frame.setLayout(form_lay)\n\n ver_frame = QFrame()\n ver_frame.setFrameShape(QFrame.StyledPanel)\n intro_label = QLabel(\"Welcome to The Open Space \")\n intro_label.setFont(QFont('Serif', 16))\n\n ver_box = QVBoxLayout()\n ver_box.setContentsMargins(25, 20, 25, 25) \n ver_box.addWidget(intro_label)\n ver_frame.setLayout(ver_box)\n\n splitter = QSplitter(Qt.Horizontal)\n splitter.addWidget(form_frame)\n splitter.addWidget(ver_frame)\n\n self.vbox = QVBoxLayout()\n self.vbox.addWidget(splitter)\n self.setCentralWidget(splitter)\n\n def contextMenuEvent(self, event):\n men = QMenu()\n men.addAction('New')\n men.addAction('Open')\n quit = men.addAction('Quit')\n action = men.exec_(self.mapToGlobal(event.pos()))\n if action is quit:\n self.close()\n\n\nStyleSheet = '''\nQMainWindow {\n background-color: #333;\n color: red;\n}\n\n/* QMenuBar --------------------------------------------------------------- */\n\nQMenuBar {\n background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,\n stop:0 lightgray, stop:1 darkgray);\n}\nQMenuBar::item {\n spacing: 3px; \n padding: 2px 10px;\n background-color: rgb(210,105,30);\n color: rgb(255,255,255); \n border-radius: 5px;\n}\nQMenuBar::item:selected { \n background-color: rgb(244,164,96);\n}\nQMenuBar::item:pressed {\n background: rgb(128,0,0);\n}\n\n/* QMenu ------------------------------------------------------------------ */\n\nQMenu {\n font: 12pt;\n background-color: white;\n color: black;\n}\nQMenu::item:selected {\n color: gray;\n}\n\n/* QSplitter -------------------------------------------------------------- */\n\nQSplitter::handle:horizontal {\n width: 2px;\n background-color : green;\n}\n\nQSplitter::handle:vertical {\n height: 2px;\n background-color : green;\n}\n\n/* ------------------------------------------------------------------------ */\n\nQLabel {\n/* background-color : blue;*/\n color: #ccc;\n}\n\nQPushButton {\n min-width: 36px;\n min-height: 36px;\n border-radius: 7px;\n background: #777;\n}\nQPushButton:hover {\n color: white;\n background: #999;\n}\nQPushButton:pressed {\n background-color: #bbdefb;\n color: green;\n}\n\n'''\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n app.setStyleSheet(StyleSheet) # <---\n\n win = Window()\n win.setWindowTitle('First Porgram')\n win.setWindowIcon(QIcon(\"D:/_Qt/img/qt-logo.png\")) \n win.setGeometry(300, 150, 500, 300)\n win.show()\n app.exec_()\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/RcGEW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RcGEW.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T14:45:37.843",
"Id": "426071",
"Score": "1",
"body": "Welcome to Code Review. Good answers that get upvoted contain observations about the Original Posters code. Good answers may not contain any code at all. Could you please comment on the users code as well. Please take a look at our guidelines for a good answer at https://codereview.stackexchange.com/help/how-to-answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T14:07:44.610",
"Id": "220511",
"ParentId": "220101",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T16:45:42.207",
"Id": "220101",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"gui",
"pyqt"
],
"Title": "Simple PyQt5 Window"
} | 220101 |
<p>In relation to <a href="https://codereview.stackexchange.com/questions/215657/interactive-auction-board">this question</a>, an upcoming exam (on the 20th May 2019) requires me to carry out this task using Visual Basic, Python or Pascal/Delphi. I am using Python (version 2.7/3.7) since the program is easier to read and write in this language. Here is the pre-release for my exam:</p>
<blockquote>
<p><em>An auction company has an interactive auction board at their</em>
<em>salerooms, which allows buyers to place bids at any time during the</em>
<em>auction. Before the auction starts, the sellers place their items in</em>
<em>the saleroom with a unique number attached to each item (item number).</em>
<em>The following details about each item need to be set up on the</em>
<em>interactive auction board system: the item number, number of bids,</em>
<em>description, and reserve price. The number of bids is initially set to</em>
<em>zero.</em></p>
<p><em>During the auction, buyers can look at the items in the saleroom and</em>
<em>then place a bid on the interactive auction board at the saleroom.</em>
<em>Each buyer is given a unique number for identification (buyer number).</em>
<em>All the buyer needs to do is enter their buyer number, the item</em>
<em>number, and their bid. Their bid must be greater than any existing</em>
<em>bids.</em></p>
<p><em>At the end of the auction, the company checks all the items and marks</em>
<em>those that have bids greater than the reserve as sold. Any items sold</em>
<em>will incur a fee of 10% of the final bid to be paid to the auction</em>
<em>company.</em></p>
<p><em>Write and test a program or programs for the auction company.</em></p>
<p><em>• Your program or programs must include appropriate prompts for the</em>
<em>entry of data, data must be validated on entry.</em></p>
<p><em>• Error messages and other output need to be set out clearly and</em>
<em>understandably.</em></p>
<p><em>• All variables, constants, and other identifiers must have meaningful</em>
<em>names.</em></p>
<p><em>You will need to complete these <strong>three</strong> tasks. Each task must be fully</em>
<em>tested.</em></p>
<p><strong><em>Task 1 – Auction set up.</em></strong></p>
<p><em>For every item in the auction the item number, description, and the</em>
<em>reserve price should be recorded. The number of bids is set to zero.</em>
<em>There must be at least 10 items in the auction.</em></p>
<p><strong><em>Task 2 – Buyer bids.</em></strong></p>
<p><em>A buyer should be able to find an item and view the item number,</em>
<em>description, and the current highest bid. A buyer can then enter their</em>
<em>buyer number and bid, which must be higher than any previously</em>
<em>recorded bids. Every time a new bid is recorded the number of bids for</em>
<em>that item is increased by one. Buyers can bid for an item many times</em>
<em>and they can bid for many items.</em></p>
<p><strong><em>Task 3 – At the end of the auction.</em></strong></p>
<p><em>Using the results from TASK 2, identify items that have reached their</em>
<em>reserve price, mark them as sold, calculate 10% of the final bid as</em>
<em>the auction company fee and add this to the total fee for all sold</em>
<em>items. Display this total fee. Display the item number and final bid</em>
<em>for all the items with bids that have not reached their reserve price.</em>
<em>Display the item number of any items that have received no bids.</em>
<em>Display the number of items sold, the number of items that did not</em>
<em>meet the reserve price and the number of items with no bids.</em></p>
</blockquote>
<p>Here is my solution (program) to the question, task by task:</p>
<pre><code>number_of_bids = 0
count = 0
auction_fee = 0.0
item_no = 0
sold_items = 0
less_than_reserve = 0
zero_bids_items = 0
min_items = 10
while True:
try:
n = int(input("Enter the number of items in the auction: "))
if n < min_items:
raise ValueError
except ValueError:
print ("Number of items have to be at least 10!")
else:
current_highest_bid = [0.0]*n
item_bids = [0]*n
item_description = []*n
reserve_price = []*n
item_numbers = []*n
buyer_no_Array = [0]*n
break
#TASK 1
for i in range(n):
item_no = item_no + 1
item_numbers.append(item_no)
print ("ENTER DETAILS FOR ITEM NO.", item_no)
description = input("Enter description for item no. " + str(item_no))
item_description.append(description)
reserve = float(input("Enter reserve price for item no. " + str(item_no)))
reserve_price.append(reserve)
#TASK 2
while count != "y":
for i in range(n):
print ("Item number:", item_numbers[i], "Description:", item_description[i], "Reserve price:", reserve_price[i], end = " ")
print ("Current highest bid:", current_highest_bid[i], "No. of bids:", item_bids[i], end = " ")
print ("Buyer with highest bid:", buyer_no_Array[i])
choice = input("Do you want to bid for items in this auction? (y/n): ")
if (choice == "y"):
buyer_no = int(input("Enter your buyer ID: "))
item_choice = int(input("Enter the item number for your choice of item: "))
if item_choice in item_numbers:
index = item_numbers.index(item_choice)
while True:
try:
bid_price = float(input("Please enter your bid: "))
if (bid_price <= current_highest_bid[index]):
raise ValueError
except ValueError:
print ("Bid should be higher than the current highest bid!")
else:
current_highest_bid[index] = bid_price
number_of_bids = int(item_bids[index]) + 1
item_bids[index] = number_of_bids
print ("Bids for", item_description[index], "are:", item_bids[index])
buyer_no_Array[index] = buyer_no
break
else:
print ("Invalid item code!")
elif (choice == "n"):
count = input("END THE AUCTION? Enter 'n' to continue bidding or 'y' to end the auction: ")
#TASK 3
if (count == "y"):
sold = False
for i in range(len(current_highest_bid)):
if (current_highest_bid[i] >= reserve_price[i]):
sold = True
sold_items = sold_items + 1
auction_fee = auction_fee + (current_highest_bid[i] * 0.1)
print ("The total auction company fee is: $", auction_fee)
for i in range(len(current_highest_bid)):
if (current_highest_bid[i] < reserve_price[i]):
less_than_reserve = less_than_reserve + 1
print ("Item code", item_numbers[i], "with final bid $", current_highest_bid[i], "has not reached the reserve price.")
for i in range(len(current_highest_bid)):
if (current_highest_bid[i] == 0):
zero_bids_items = zero_bids_items + 1
print ("Item code", item_numbers[i], "has not received any bids.")
print ("Number of items sold are:", sold_items)
print ("Number of items that did not meet the reserve price are:" , less_than_reserve)
print ("Number of items with no bids are:", zero_bids_items)
else:
print ("Invalid input!")
</code></pre>
<p>NOTE: I would recommend you to test the program by using a smaller value of <code>min_items</code> so that it is easier to test the program.</p>
<p>So, I would like to know whether I could make this code shorter and more efficient (to achieve the best marks), as my exam board focuses more on the efficiency of a program.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T12:56:12.513",
"Id": "425337",
"Score": "3",
"body": "Are you sure this works? `[]*n` does not create a list of length `n`, you need an element to repeat, so probably `[0]*n` or `[\"\"]*n`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T12:59:48.270",
"Id": "425338",
"Score": "2",
"body": "No this is just done to create a list of length `n`, so that you cannot append any more values to the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T13:01:26.220",
"Id": "425339",
"Score": "2",
"body": "But it doesn't matter. You can remove the `*n`'s for the empty lists but leave the ones which have 0's in them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T13:05:28.230",
"Id": "425340",
"Score": "2",
"body": "I need `item_description`, `reserve_price` and `item_numbers` to be empty lists as I am supposed to append values to the list."
}
] | [
{
"body": "<p>Performance and efficiency are not the main points that you should care about at this stage, especially for this simple task. Since your code will be scored by other persons, you should aim for readability and clarity. There is an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> that especially Python novices should try to adapt in order to write good-looking Python code. I will try to link to relevant parts of the style guide where appropriate. With this in mind, let's have a look at your code.</p>\n\n<h2>Data structures</h2>\n\n<p>Keeping data consistent that is spread out over several list can be tedious, as you may have experienced yourself while writing the code. In your case, you will have to work with 6 (! - if I did not misscount) parallel lists, e.g. when placing a bid. A far more convenient approach would be to have a single collection of auction items, where each item has all the fields you have spread out over those lists at the moment. Depending on your level of Python experience, you may write a class for that, or use some of Python's builtin data structures. For the moment, I will stick with the second alternative.</p>\n\n<p>So, what do we need? Each item has the following properties:</p>\n\n<ul>\n<li>item description </li>\n<li>reserve price </li>\n<li>current highest bid </li>\n<li>number of bids</li>\n<li>buyer with highest bid</li>\n</ul>\n\n<p>as well as an item number (why this is separate will hopefully become clearer in a few moments).</p>\n\n<p>Python offers several possible solutions for that:</p>\n\n<ol>\n<li>have a tuple/list where each element can be accessed by an index, and you have to know which index represents which part of the information</li>\n<li>use a dictionary where the name of the properties above is used as keys</li>\n</ol>\n\n<p>I'ld tend to use the second approach in your case, just because it's more explicit to use and it's harder to make misstakes. With this in our mind, lets look at how such an \"item\" might look like as a Python dict:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>item = {\"description\": \"\", \"reserve price\": 0.0, \n \"current highest bid\": 0.0, \"buyer with highest bid\": None,\n \"number of bids\": 0}\n</code></pre>\n\n<p>As you can see, the properties can be used verbatim as keys in the dicitionary which makes it as straightforward as <code>item[\"number of bids\"] += 1</code> to update the number of bids placed on an item. All the other properties may be used in the same fashion.</p>\n\n<p>So 5 of 6 down, one to go: item number. I chose to exclude the item number from the list above, since it's role is a little bit special here. Why? Because the item number is used to identify the item. If you'ld like to stick to simple, consecutive item numbers, the easiest way is to put a bunch of these dictionaries in a list and use the position in the list as implicit item number.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>items = []\nfor i in range(n):\n items.append({\n \"description\": \"\",\n \"reserve price\": 0.0,\n \"current highest bid\": 0.0,\n \"buyer with highest bid\": None,\n \"number of bids\": 0\n })\n</code></pre>\n\n<p>You could also use a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehension</a> for this<sup>1</sup>. Since we're now in a situtation where the position in the list matters and identifies the element, it might be wise to convert the list into a tuple after its creation: <code>items = tuple(items)</code>. Python tuples are not mutable, which means for your purpose you are not allowed to add and remove items. The dictionaries, which are elements of the tuple, can still be modified. </p>\n\n<p>You basically can go full berserk from here on. You want non-consecutive item numbers? Use a dict with the item numbers as keys and the corresponding item dicts as values. Include the bid validation into the items themselves? Write a class with methods.</p>\n\n<hr>\n\n<blockquote>\n <p>All the feedback below refers to your original code, but can easily\n adapted to the new data structure above. Some of it will even become\n obsolete.</p>\n</blockquote>\n\n<hr>\n\n<h2>Handling user input</h2>\n\n<p>There a various part where you have to handle user input. Although you have tagged your question with Python 2 and Python 3, I sincerly hope you are actually using Python 3. Otherwise you are setting yourself up for some trouble because <a href=\"https://stackoverflow.com/a/4915366/5682996\">using <code>input(...)</code> in Python 2 is \"risky\"</a>, to put it mildly. So let's assume Python 3 from here on.</p>\n\n<p>The part where you're asking for the number of items is relatively robust, and even includes some input validation, which is good. However, it would be best to wrap it into a function and separate it from the list initialization. That would lead to something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_number_of_items(min_items):\n \"\"\"Get the number of items offered during the auction\"\"\"\n while True:\n try:\n n = int(input(\"Enter the number of items in the auction: \"))\n if n < min_items:\n raise ValueError\n except ValueError:\n print (f\"Number of items have to be at least {min_items}!\")\n else:\n return n\n</code></pre>\n\n<p>Apart from wrapping the code into a function, two other things have happened here. First, the function got a short <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">docstring</a>. Second, the error message now includes the actual value of <code>min_items</code> and not just a fixed value of 10. To read more about the type of string formatting that's happening here, go and look for \"Python 3 f-strings\", e.g. at the <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting\" rel=\"nofollow noreferrer\">Python doc</a> or <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">this</a> blog post.</p>\n\n<p>On the second instance of user input, you took way less care to validate the input. There are no checks in place to actually make sure that a description is given, or that the reserve price is actually a non-negative number. To be fair, the task does not explicitely state that, but I think it's fair to assume that the reserve price is at least <code>0</code>. You can also take advantage of string formatting when creating the prompts, so use <code>description = input(f\"Enter description for item no. {item_no}\")</code> instead of <code>description = input(\"Enter description for item no. \" + str(item_no))</code>. Since this is for you to learn something and you already have an example for a function that performs a similar task, I leave the implementation as an exercise to you.</p>\n\n<h2>String formatting</h2>\n\n<p>String formatting was alread mentioned above, but I just want to point out, that basically all of your calls to <code>print(...)</code> with dynamic output should be refactored to use it. Example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"Item number: {item_numbers[i]} \"\n f\"Description: {item_description[i]} \"\n f\"Reserve price: {reserve_price[i]} \"\n f\"Current highest bid: {current_highest_bid[i]} \"\n f\"No. of bids: {item_bids[i]} \"\n f\"Buyer with highest bid: {buyer_numbers[i]}\")\n</code></pre>\n\n<p>The example also makes use of Python's <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#implicit-line-joining\" rel=\"nofollow noreferrer\">implicit line joining</a> within function parenthesis. It would also be possible to put <code>+</code> in front of all the strings apart from the first one to make it clearer that these strings are supposed to be joined.</p>\n\n<h2>Avoid globals</h2>\n\n<p>After you have packed everything into nice, single purpose functions, reduced the variable clutter, and the myriad of lists, it's now time to cut down the amout of global variables in your script. Global variables are all variables outside of functions at the script's top-level. You should try to avoid them whenever possible since they leak into functions and more unexpected things. A best-practice often found in Python code is to define a final <code>main()</code> function that uses the other functions and implements the scripts actual functionality. So the high-level code structure could now look something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_number_of_items(min_items):\n \"\"\"Get the number of items offered during the auction\"\"\"\n ...\n\n\n# other functions\n...\n\n\ndef main():\n \"\"\"Hold the auction\"\"\"\n min_items = 10\n ...\n n = get_number_of_items(min_items)\n items = []\n for i in range(n):\n ...\n\n # Task 1\n ...\n\n # Task 2\n ...\n\n # Task 3\n ...\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>The only thing that's new here is <code>if __name___ == \"__main__\":</code>, which is <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">Python's way</a> of telling \"this part (<code>main()</code>) is only run if the file is used as a script\".</p>\n\n<h2>Miscellaneous</h2>\n\n<p>What follows is a loose collection of minor bits and pieces, that are not as severe as the aspects I have already talked about. You might consider them as \"good to know\".</p>\n\n<p>There are some parts of the code which seem to be overly complicated and/or \"non-Pythonic\", like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>number_of_bids = int(item_bids[index]) + 1\nitem_bids[index] = number_of_bids\n</code></pre>\n\n<p>which could be expressed as simple as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>item_bids[index] += 1\n</code></pre>\n\n<p>Another instance of \"overcomplicated\" code is</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(n):\n item_no = item_no + 1\n ...\n</code></pre>\n\n<p>I would consider</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(n):\n item_no = i + 1\n ...\n</code></pre>\n\n<p>as a clearer alternative, since this is a more direct way to see that you are actually asigning consecutive item IDs in a loop.</p>\n\n<p>As others have already told you</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>item_description = []*n\nreserve_price = []*n\nitem_numbers = []*n\n</code></pre>\n\n<p>does not create empty lists of length <code>n</code>. In your code this is no problem since you simply append to these lists until they have length <code>n</code>, so you should just work with</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>item_description = []\nreserve_price = []\nitem_numbers = []\n</code></pre>\n\n<p>When performing the final evaluation described in Task 3, I would strongly recommend to define those \"summary\" variables like <code>sold_items</code>, <code>auction_fee</code>, and so on, just there where they are actually used and not at the start of the script. Especially if you have followed the initial advice on the data structure and the final evaluation might also easily be put into its own function.</p>\n\n<hr>\n\n<p><sup>1</sup> <strong>A word of warning:</strong> Although it might be tempting to use <code>items = [item for i in range(n)]</code>, be aware that this would <strong>not</strong> lead to the same result! In that case, all elements of <code>items</code> whould point to <strong>a single object in memory</strong> and altering any element, e.g. <code>items[0]</code> whould also alter <code>items[1]</code> and so forth.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T22:49:29.267",
"Id": "220383",
"ParentId": "220103",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220383",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T17:33:23.650",
"Id": "220103",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Interactive auction board in Python 3"
} | 220103 |
<p>I am writing a program that has a row-based data table class. It also has an encoder class that is intended to take in some .csv data and convert it into a 2darray of encoded data of unknown type at compile time. </p>
<p>The idea is that the user will point to a .csv file they would like to read from and specify a runtime schema (column 1 == int, column 2 == bool, column 3 == string, etc) that will be used to encode the raw .csv data into the proper types needed for comparison and such elsewhere in the program. </p>
<p>I have been reading a lot about this and decided to try a union based approach.
I mocked this up in a simple project to see how this might work out on one single piece of data ("DataPoint."). Here is the code. </p>
<pre class="lang-cpp prettyprint-override"><code>
#include "pch.h"
#include <iostream>
#include <sstream>
union DataPoint
{
bool Bool;
int Integer;
float FloatingPoint;
//std::string String;
};
enum DataTypes
{
Bool,
Integer,
FloatingPoint,
//String
};
DataPoint EncodeData(DataPoint InDataPoint, DataTypes InDataTypes, std::string InData)
{
std::stringstream DataStream(InData);
switch (InDataTypes)
{
case Bool:
std::cout << "Type is Bool" << std::endl;
if (InData == "True" || InData == "true" || InData == "1") InDataPoint.Bool = true;
else if (InData == "False" || InData == "false" || InData == "0") InDataPoint.Bool = false;
else std::cout << "This data is not compatable with the bool type." << std::endl;
break;
case Integer:
std::cout << "Type is Integer" << std::endl;
DataStream >> InDataPoint.Integer;
break;
case FloatingPoint:
std::cout << "Type is Floating Point" << std::endl;
DataStream >> InDataPoint.FloatingPoint;
break;
/*
case String: InDataPoint.String = InData;
break;
*/
default:
break;
}
return InDataPoint;
}
void PrintData(DataPoint InDataPoint, DataTypes InDataTypes)
{
switch (InDataTypes)
{
case Bool: std::cout << "Encoded data value : " << InDataPoint.Bool << std::endl;
break;
case Integer: std::cout << "Encoded data value : " << InDataPoint.Integer << std::endl;
break;
case FloatingPoint: std::cout << "Encoded data value : " << InDataPoint.FloatingPoint<< std::endl;
break;
/*
case String:
break;
*/
default:
break;
}
}
int main()
{
DataPoint DataPoint1{};
DataTypes DataType{ Bool };
std::string Data{ "true" };
std::cout << "Raw data value : " << Data << std::endl;
PrintData(EncodeData(DataPoint1, DataType, Data), DataType);
return 0;
}
</code></pre>
<p>This all seems to work, however, as you can see... I have commented out string entries because I cannot figure out a good way to handle them. One issue I run into is though unions apparently support strings in c++ now, I error out when I try to add a string as a union member. Here is the error I get if I uncomment the string member of the union. </p>
<p><em>Severity Code Description Project File Line Suppression State
Error (active) E1776 function "DataPoint::DataPoint(const DataPoint &)" (declared implicitly) cannot be referenced -- it is a deleted function</em> </p>
<p>Is there some way to handle the string?
Also, in general, does this approach seem sound? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T09:04:56.443",
"Id": "425495",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
}
] | [
{
"body": "<p>I don't have time to check all now but I found some things I want to share</p>\n\n<p>If you are using C++17 consider using <code>std::variant</code> instead of the weak union inherited from c. It will probaly also solve youre isue with <code>std::string</code>. See: <a href=\"https://en.cppreference.com/w/cpp/utility/variant\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/utility/variant</a></p>\n\n<p>Consider using <code>'\\n'</code> instead of <code>std::endl</code>. Im pretty sure you only want a newline and not also a expensive flush of the buffer: <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">https://stackoverflow.com/questions/213907/c-stdendl-vs-n</a>.</p>\n\n<p>Consider using the more safe <code>enum class</code> instead of plain c <code>enum</code>. It is available since C++11.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:15:00.697",
"Id": "425374",
"Score": "0",
"body": "The std::variant is a much better option it seems. Thanks for the other notes as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T19:55:56.370",
"Id": "220107",
"ParentId": "220104",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220107",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T18:30:32.690",
"Id": "220104",
"Score": "2",
"Tags": [
"c++",
"parsing",
"csv"
],
"Title": "Union based encoding of .csv file into a data table with different types"
} | 220104 |
<p>I have simple database with many to many relations. </p>
<p><a href="https://i.stack.imgur.com/n2LKS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/n2LKS.png" alt="enter image description here"></a></p>
<p>I wrote simple method <code>GetAuthors()</code> </p>
<pre><code>[HttpGet]
public JsonResult GetAuthors()
{
var books = db.Authors
.Where(c => c.Name == "FirstAuthor")
.Include(b => b.AuthorsBooks)
.Select(p => new
{
author = p.Name,
books = p.AuthorsBooks.Select(z => z.Book.Name)
})
.ToList();
return new JsonResult(books);
}
</code></pre>
<p>that returns expected result.</p>
<p><code>[{"author":"FirstAuthor","books":["GoodBook1","GoodBook2","GoodBook3"]}]</code></p>
<p>The main question <code>how</code> to simplify <code>LINQ</code> in funtion <code>GetAuthors()</code> currently it looks over complicated. Maybe exist other way to simplify with StoredProcedure? how to improve it?</p>
<p><strong>Controller code:</strong></p>
<pre><code>namespace DataFromMSSQL.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly StrangeContext db;
public ValuesController(StrangeContext context)
{
db = context;
}
[HttpGet]
public JsonResult GetAuthors()
{
var books = db.Authors
.Where(c => c.Name == "FirstAuthor")
.Include(b => b.AuthorsBooks)
.Select(p => new
{
author = p.Name,
books = p.AuthorsBooks.Select(z => z.Book.Name)
})
.ToList();
return new JsonResult(books);
}
}
}
</code></pre>
<p>Data base script </p>
<pre><code>/****** Object: Table [dbo].[Authors] Script Date: 5/11/2019 10:24:25 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Authors](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](30) NULL,
CONSTRAINT [PK_Versions] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AuthorsBooks] Script Date: 5/11/2019 10:24:25 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AuthorsBooks](
[Id] [int] IDENTITY(1,1) NOT NULL,
[AuthorId] [int] NOT NULL,
[BookId] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Books] Script Date: 5/11/2019 10:24:25 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Books](
[Id] [int] NOT NULL,
[Name] [nvarchar](30) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Authors] ON
INSERT [dbo].[Authors] ([Id], [Name]) VALUES (1, N'FirstAuthor')
INSERT [dbo].[Authors] ([Id], [Name]) VALUES (2, N'SecondAuthor')
SET IDENTITY_INSERT [dbo].[Authors] OFF
SET IDENTITY_INSERT [dbo].[AuthorsBooks] ON
INSERT [dbo].[AuthorsBooks] ([Id], [AuthorId], [BookId]) VALUES (1, 1, 1)
INSERT [dbo].[AuthorsBooks] ([Id], [AuthorId], [BookId]) VALUES (2, 1, 2)
INSERT [dbo].[AuthorsBooks] ([Id], [AuthorId], [BookId]) VALUES (3, 1, 3)
INSERT [dbo].[AuthorsBooks] ([Id], [AuthorId], [BookId]) VALUES (4, 2, 1)
INSERT [dbo].[AuthorsBooks] ([Id], [AuthorId], [BookId]) VALUES (5, 2, 3)
SET IDENTITY_INSERT [dbo].[AuthorsBooks] OFF
INSERT [dbo].[Books] ([Id], [Name]) VALUES (1, N'GoodBook1')
INSERT [dbo].[Books] ([Id], [Name]) VALUES (2, N'GoodBook2')
INSERT [dbo].[Books] ([Id], [Name]) VALUES (3, N'GoodBook3')
ALTER TABLE [dbo].[AuthorsBooks] WITH CHECK ADD FOREIGN KEY([AuthorId])
REFERENCES [dbo].[Authors] ([Id])
GO
ALTER TABLE [dbo].[AuthorsBooks] WITH CHECK ADD FOREIGN KEY([BookId])
REFERENCES [dbo].[Books] ([Id])
GO
/****** Object: StoredProcedure [dbo].[GetBooksByAuthor] Script Date: 5/11/2019 10:24:26 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetBooksByAuthor]
AS
Select authors.Name, books.Name from dbo.Authors authors
INNER JOIN dbo.AuthorsBooks authorsBooks on authors.Id=authorsBooks.AuthorId
INNER JOIN dbo.Books books on books.Id=authorsBooks.BookId
GO
USE [master]
GO
ALTER DATABASE [Strange] SET READ_WRITE
GO
</code></pre>
| [] | [
{
"body": "<p>I don't see how to optimize the linq-query, and it doesn't look complicated to me. It's a method that returns authors with a specific name. That is of course of very little use, so the first thing to do, is to provide the name to search for as a parameter to the method:</p>\n\n<pre><code>public JsonResult GetAuthors(string name) {... .Where(b => b.Name == name) ...}\n</code></pre>\n\n<hr>\n\n<p>The generated Json object is also not very \"helpful\" to the client in that it only contains names of the authors and their books. Returned to the client and displayed in a list it's OK, but when the user clicks on one of the authors or books, I suppose, you'll want to fetch more information about the selected object from the server. Therefore you should provide the Id for both authors and books, in order to return that to the server, when the user clicks on an item - which on the server can be handled by:</p>\n\n<pre><code>public JsonResult GetAuthor(int id) {...}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public JsonResult GetBook(int id) {...}\n</code></pre>\n\n<p>So I would change your method to:</p>\n\n<pre><code> [HttpGet]\n public JsonResult GetAuthors(string name)\n {\n var books = db.Authors\n .Where(c => c.Name == name)\n .Include(b => b.AuthorsBooks)\n .Select(p => new\n {\n id = p.Id,\n name = p.Name,\n books = p.AuthorsBooks.Select(z => new { id = z.Id, name = z.Book.Name })\n })\n .ToList();\n\n return new JsonResult(books);\n }\n</code></pre>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:58:06.213",
"Id": "425419",
"Score": "0",
"body": "The `.Include()` shouldn't be necessary since there is a projection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T05:33:22.560",
"Id": "220119",
"ParentId": "220109",
"Score": "2"
}
},
{
"body": "<p>Not linked directly to your question but here are some things I would change:</p>\n\n<p>I'd name my tables slightly different: <code>Author</code>, <code>Book</code> and then <code>AuthorsBooks</code>. And the ID column of each of the two main tables would be <code>AuthorId</code> and <code>BookId</code>. </p>\n\n<p>Please note that this is highly debatable and perhaps even just a matter of personal prefference, if you do a search here and stackoverflow you'll see what I mean.</p>\n\n<p>From my point of view a datatable represents a definition of a single entity (Author), the rows inside then represent many of those entities.</p>\n\n<p>ID column naming <code>AuthorId</code> and <code>BookId</code> is more of a DB thing where SQL statements become more readable in JOIN scenarios, if you do a join on these two tables then you must alias the columns in results (<code>Author.Id As AuthorId</code> and <code>Book.Id As BookId</code>) because SQL doesn't allow column results with same names in complex statements.</p>\n\n<p>The many-to-many table doesn't need an ID column. You generally need and ID column if you plan on deleting/updating or referencing rows. In a many-to-many link table you're suppose to have only one combination of AuthorId and BookId so there's no need for deletions and updates also referencing by row ID is not needed in this table.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T08:39:56.687",
"Id": "220127",
"ParentId": "220109",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T21:36:18.677",
"Id": "220109",
"Score": "6",
"Tags": [
"c#",
"asp.net-core"
],
"Title": "Getting Authors and Books from a simple database"
} | 220109 |
<p>Inspired by my earlier question <a href="https://codereview.stackexchange.com/q/220090">C++17 <code>pointer_traits</code> implementation</a>, I re-implemented <code>allocator_traits</code> under the name <code>my_std::allocator_traits</code>, put in a separate header <code>allocator_traits.hpp</code> because <code><memory></code> is way too comprehensive:</p>
<pre><code>// C++17 allocator_traits implementation
#ifndef INC_ALLOCATOR_TRAITS_HPP_D6XSISB6AD
#define INC_ALLOCATOR_TRAITS_HPP_D6XSISB6AD
#include <limits> // for std::numeric_limits
#include <memory> // for std::pointer_traits
#include <type_traits> // for std::false_type, etc.
#include <utility> // for std::forward
namespace my_std {
template <class Alloc>
struct allocator_traits;
namespace at_detail {
template <class Tmpl, class U>
struct rebind_first_param { };
template <template <class, class...> class Tmpl, class T, class... Args, class U>
struct rebind_first_param<Tmpl<T, Args...>, U> {
using type = Tmpl<U, Args...>;
};
template <class Tmpl, class U>
using rebind_first_param_t = typename rebind_first_param<Tmpl, U>::type;
template <class Alloc, class T>
auto pointer(int) -> typename Alloc::pointer;
template <class Alloc, class T>
auto pointer(long) -> T*;
template <class Alloc, class T, class Ptr>
auto const_pointer(int) -> typename Alloc::const_pointer;
template <class Alloc, class T, class Ptr>
auto const_pointer(long) -> typename std::pointer_traits<Ptr>::template rebind<const T>;
template <class Alloc, class Ptr>
auto void_pointer(int) -> typename Alloc::void_pointer;
template <class Alloc, class Ptr>
auto void_pointer(long) -> typename std::pointer_traits<Ptr>::template rebind<void>;
template <class Alloc, class Ptr>
auto const_void_pointer(int) -> typename Alloc::const_void_pointer;
template <class Alloc, class Ptr>
auto const_void_pointer(long) -> typename std::pointer_traits<Ptr>::template rebind<const void>;
template <class Alloc, class Ptr>
auto difference_type(int) -> typename Alloc::difference_type;
template <class Alloc, class Ptr>
auto difference_type(long) -> typename std::pointer_traits<Ptr>::difference_type;
template <class Alloc, class Diff>
auto size_type(int) -> typename Alloc::size_type;
template <class Alloc, class Diff>
auto size_type(long) -> std::make_unsigned_t<Diff>;
template <class Alloc>
auto pocca(int) -> typename Alloc::propagate_on_container_copy_assignment;
template <class Alloc>
auto pocca(long) -> std::false_type;
template <class Alloc>
auto pocma(int) -> typename Alloc::propagate_on_container_move_assignment;
template <class Alloc>
auto pocma(long) -> std::false_type;
template <class Alloc>
auto pocw(int) -> typename Alloc::propagate_on_container_swap;
template <class Alloc>
auto pocw(long) -> std::false_type;
template <class Alloc>
auto iae(int) -> typename Alloc::is_always_equal;
template <class Alloc>
auto iae(long) -> std::is_empty<Alloc>::type;
template <class Alloc, class T>
auto rebind_alloc(int) -> typename Alloc::rebind<T>::other;
template <class Alloc, class T>
auto rebind_alloc(long) -> rebind_first_param_t<Alloc, T>;
}
template <class Alloc>
struct allocator_traits {
using allocator_type = Alloc;
using value_type = typename Alloc::value_type;
using pointer = decltype(at_detail::pointer<Alloc, value_type>(0));
using const_pointer = decltype(at_detail::const_pointer<Alloc, value_type, pointer>(0));
using void_pointer = decltype(at_detail::void_pointer<Alloc, pointer>(0));
using const_void_pointer = decltype(at_detail::const_void_pointer<Alloc, pointer>(0));
using difference_type = decltype(at_detail::difference_type<Alloc, pointer>(0));
using size_type = decltype(at_detail::size_type<Alloc, difference_type>(0));
using propagate_on_container_copy_assignment = decltype(at_detail::pocca<Alloc>(0));
using propagate_on_container_move_assignment = decltype(at_detail::pocma<Alloc>(0));
using propagate_on_container_swap = decltype(at_detail::pocw<Alloc>(0));
using is_always_equal = decltype(at_detail::iae<Alloc>(0));
template <class T>
using rebind_alloc = decltype(at_detail::rebind_alloc<Alloc, T>(0));
static pointer allocate(Alloc& a, size_type n)
{
return a.allocate(n);
}
static pointer allocate(Alloc& a, size_type n, const_void_pointer hint)
{
return allocate_(a, n, hint, 0);
}
static void deallocate(Alloc& a, pointer p, size_type n)
{
a.deallocate(p, n);
}
template <class T, class... Args>
static void construct(Alloc& a, T* p, Args&&... args)
{
construct_(a, p, 0, std::forward<Args>(args)...);
}
template <class T>
static void destroy(Alloc& a, T* p)
{
destroy_(a, p, 0);
}
static size_type max_size(const Alloc& a) noexcept
{
return max_size_(a, 0);
}
static Alloc select_on_container_copy_construction(const Alloc& rhs)
{
return soccc(rhs, 0);
}
private:
static auto allocate_(Alloc& a, size_type n, const_void_pointer hint, int)
-> decltype(a.allocate(n, hint), void(), std::declval<pointer>())
{
return a.allocate(n, hint);
}
static auto allocate_(Alloc& a, size_type n, const_void_pointer, long)
-> pointer
{
return a.allocate(n);
}
template <class T, class... Args>
static auto construct_(Alloc& a, T* p, int, Args&&... args)
-> decltype(a.construct(p, std::forward<Args>(args)...), void())
{
a.construct(p, std::forward<Args>(args)...);
}
template <class T, class... Args>
static void construct_(Alloc&, T* p, long, Args&&... args)
{
::new(static_cast<void*>(p)) T(std::forward<Args>(args)...);
}
template <class T>
static auto destroy_(Alloc& a, T* p, int)
-> decltype(a.destroy(p), void())
{
a.destroy(p);
}
template <class T>
static void destroy_(Alloc&, T* p, long)
{
p->~T();
}
static auto max_size_(const Alloc& a, int) noexcept
-> decltype(a.max_size(), std::declval<size_type>())
{
return a.max_size();
}
static auto max_size_(const Alloc&, long) noexcept
-> size_type
{
return std::numeric_limits<size_type>::max() / sizeof(value_type);
}
static auto soccc(const Alloc& rhs, int)
-> decltype(rhs.select_on_container_copy_construction(), std::declval<Alloc>())
{
return rhs.select_on_container_copy_construction();
}
static auto soccc(const Alloc& rhs, long)
-> Alloc
{
return rhs;
}
};
}
#endif
</code></pre>
<p>I used <a href="https://timsong-cpp.github.io/cppwp/n4659/" rel="nofollow noreferrer">N4659</a> as a reference.</p>
| [] | [
{
"body": "<p>Well, it looks pretty clean, nice and right.</p>\n\n<ol>\n<li><p>Of course, if it really was part of the implementation, it would have to use solely reserved identifiers to avoid interacting with weird and ill-advised user-defined macros, making it look much less nice.</p></li>\n<li><p><code>Tmpl</code> is a curious name for the primary type template-parameter. Please stay with the customary <code>T</code>, unless you have a much more telling name like <code>Alloc</code>.</p></li>\n<li><p><code>Tmpl</code> is also a curious name for a template template parameter. <code>TT</code> is customary and more concise.</p></li>\n<li><p>Consider leaving names out if you don't need one, and they do not pull their weight conveying useful extra-information to the reader.</p></li>\n<li><p>I wonder what kind of logic you used to decide whether to put something as a private member, or in a private namespace for implementation-details. While there are good reasons for either, better use only one.</p></li>\n<li><p>A real implementation would probably mark ODR-used internal functions as always_inline in some implementation-defined way.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T11:30:40.910",
"Id": "220176",
"ParentId": "220113",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T01:45:53.867",
"Id": "220113",
"Score": "5",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"template-meta-programming"
],
"Title": "C++17 allocator_traits implementation"
} | 220113 |
<p>I've written a tiny function for asking questions intended for my POSIX shell scripts, where I often need user input.</p>
<p>The function takes 2+ arguments, where:</p>
<ol>
<li>Is a string containing the question.</li>
<li>, 3., ... = arguments containing the right answers (case insensitive)</li>
</ol>
<p>I also changed my style by a bit, no longer use <code>${var}</code> instead of just <code>$var</code>.</p>
<p>The requirement was simple: Check for exactly the answers given. So, not matching <code>yeahh</code> if given answer is <code>yeah</code>.</p>
<p>I also included a maybe performance-wise quick test if the user answer is in the list of answers, so answering <code>no</code> will not make the script iterate through all the answers and just dies at that check.</p>
<hr>
<pre><code>#!/bin/sh
set -u
confirmation ()
# $1 = a string containing the question
# $2,.. = arguments containing the right answers (case insensitive)
{
question=$1; shift
correct_answers=$*
correct_answers_combined=$( printf '%s' "$correct_answers" | sed 's/\( \)\{1,\}/\//g' )
printf '%b' "$question\\nPlease answer [ $correct_answers_combined ] to confirm (Not <Enter>): "
read -r user_answer
# this part is optional in hope it would speed up the whole process
printf '%s' "$correct_answers" | grep -i "$user_answer" > /dev/null 2>&1 ||
return 1
# this part iterates through the list of correct answers
# and compares each as the whole word (actually as the whole line) with the user answer
for single_correct_answer in $correct_answers; do
printf '%s' "$single_correct_answer" | grep -i -x "$user_answer" > /dev/null 2>&1 &&
return 0
done
# this might be omitted, needs verification, or testing
return 1
}
# EXAMPLE usage, can be anything, DO NOT review this part please
if confirmation 'Is dog your favorite pet?' y yes yep yeah
then
tput bold; tput setaf 2; echo 'TRUE: You just love dogs! :)'; tput sgr0
else
tput bold; tput setaf 1; echo 'FALSE: Dog hater, discontinuing! :('; tput sgr0
exit 1
fi
# do other stuff here in TRUE case
echo 'And here comes more fun...'
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T04:46:50.520",
"Id": "425313",
"Score": "0",
"body": "What if I answer `.*`? That's not in the list of accepted answers, yet it is accepted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T04:48:20.180",
"Id": "425314",
"Score": "0",
"body": "What if one of the valid answers contains a space?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T04:55:00.310",
"Id": "425316",
"Score": "0",
"body": "@RolandIllig it can't contain space, I didn't think of `.*`, thanks"
}
] | [
{
"body": "<p>A couple of thoughts. There really isn't any need for <code>correct_answers_combined</code>. After <code>shift</code>, <code>$*</code> will hold the combined remaining arguments (answers) to your question. The additional <code>printf</code>, pipe, and call to <code>sed</code> are simply incurring additional overhead in the form of subshells and separate utility calls. You could do:</p>\n\n<pre><code> correct_answers=\"$*\"\n\n ## prompt\n printf '%b' \"$question\\\\nPlease answer [ $correct_answers ] to confirm (Not <Enter>): \"\n read -r user_answer\n</code></pre>\n\n<p>Since you do not want to accept <kbd>[Enter]</kbd> as an answer, a validation that <code>user_answer</code> is unset can provide the answer and return for your function in that case, e.g.</p>\n\n<pre><code> ## validate answer provided\n [ -z \"$user_answer\" ] && return 1\n</code></pre>\n\n<p>Your <code>\"optional... speed up the whole process\"</code>, with a bit of rearranging can be used as a single call to provide a return to your function. Since you want to know whether the <code>user_answer</code> exists among the <code>correct_answers</code> you can simply return the result of <code>grep -qi</code>:</p>\n\n<pre><code> # this part is can be the whole process\n printf '%s\\n' $correct_answers | grep -qi \"$user_answer\" > /dev/null 2>&1\n return $?\n}\n</code></pre>\n\n<p>(<strong>note:</strong> using <code>printf '%s\\n' \"$correct_answers\"</code> will separate each of the whitespace separated answers by <code>newline</code> which eliminates any possible combination of parts of adjacent answers returning true)</p>\n\n<p>With those suggestions, your <code>confirmation ()</code> function would reduce to:</p>\n\n<pre><code>confirmation ()\n# $1 = a string containing the question\n# $2,.. = arguments containing the right answers (case insensitive)\n{\n question=\"$1\"; shift\n correct_answers=\"$*\"\n\n ## prompt\n printf '%b' \"$question\\\\nPlease answer [ $correct_answers ] to confirm (Not <Enter>): \"\n read -r user_answer\n\n ## validate answer provided\n [ -z \"$user_answer\" ] && return 1\n\n # this part is can be the whole process\n printf '%s\\n' \"$correct_answers\" | grep -qi \"$user_answer\" > /dev/null 2>&1\n return $?\n}\n</code></pre>\n\n<p>I haven't tested all corner cases, but for single word answers it should function as you intend. If you want the some delimiter between the answers inside <code>[ ... ]</code> then an additional command substitution can be used, but space separated options appear fine between the brackets.</p>\n\n<p>Let me know if you have any questions over the changes.</p>\n\n<p><strong>Edit In Response to You Comments</strong></p>\n\n<p>As stated above, if you want delimiters between the possible correct answers, simply use a <em>command substitution</em>, e.g.</p>\n\n<pre><code>## prompt\nprintf '%b' \"$question\\\\nPlease answer [ $(echo $correct_answers | tr ' ' /) ] to confirm (Not <Enter>): \"\nread -r user_answer\n</code></pre>\n\n<p>If you are concerned about the expansion of <code>printf '%s\\n'</code>, don't quote the <code>$correct answers</code>, </p>\n\n<pre><code># this part is can be the whole process\nprintf '%s\\n' $correct_answers | grep -qi \"$user_answer\" > /dev/null 2>&1\n return $?\n</code></pre>\n\n<p>Otherwise based on your stated question, it performs identical to the original saving at least half-a-dozen unnecessary subshells.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T07:12:12.283",
"Id": "220123",
"ParentId": "220116",
"Score": "3"
}
},
{
"body": "<p><code>printf '%b'</code> will expand backslash escapes in <code>$question</code> and in <code>$correct_answers_combined</code>. It's not obvious that both of those are desirable.</p>\n<p>I'd probably re-write that to expand only <code>$question</code>, and to avoid an unnecessary pipeline:</p>\n<pre><code>printf '%b\\nPlease answer [ ' "$question"\nprintf '%s ' "$@"\nprintf '] to confirm (Not <Enter>): '\n</code></pre>\n<p>You almost certainly want <code>fgrep</code> (or <code>grep -F</code>) rather than standard regular-expression <code>grep</code>, and it would be simpler to search through the items one per line, rather than using a <code>for</code> loop:</p>\n<pre><code>read -r user_answer\n\nprintf '%s\\n' "$@" | grep -qFx "$user_answer"\n</code></pre>\n<p>If this is the last command in the function, then the return status will be that of the <code>grep</code> command, which is just what we need.</p>\n<p>Finally, be aware that <code>read</code> can fail (e.g. when it reaches EOF). If you don't want that to be an automatic "no", then make provision for that. I don't know what the right behaviour is for this application so I'll leave that as an open issue for you to address appropriately.</p>\n<hr />\n<h1>Modified version</h1>\n<p>Here's what I ended up with:</p>\n<pre><code># $1 = a string containing the question\n# $2,.. = arguments containing the right answers (case insensitive)\nconfirmation()\n{\n question=$1; shift\n\n printf '%b\\nPlease answer [ ' "$question"\n printf '%s ' "$@"\n printf '] to confirm (Not <Enter>): '\n read -r user_answer\n\n printf '%s\\n' "$@" | grep -qFxi "$user_answer"\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T12:06:07.533",
"Id": "220280",
"ParentId": "220116",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220280",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T04:37:12.043",
"Id": "220116",
"Score": "3",
"Tags": [
"validation",
"console",
"shell",
"sh",
"posix"
],
"Title": "POSIX shell function for asking questions"
} | 220116 |
<p>This is my first Python program in years, it's just a simple string manipulation program. Given a string, determine if it contains repetitions of any substring. For example, <code>testtest</code> contains two substring <code>test</code> and nothing else.</p>
<pre class="lang-py prettyprint-override"><code>def onlySubstrings(stringOrig):
stringCopy = (stringOrig+'.')[:-1] # copy string contents
for i in range(1, len(stringCopy)): # for each character
stringCopy = stringCopy[1:]+stringCopy[0] # shift first char to end
if stringCopy == stringOrig: # if equivalent to original input
return True # it consists of substrings only
else: # otherwise the only substring is the string itself
return False
if __name__ == '__main__':
wordList = ['testtest','testteste','test','tetestst'] # some test words
print('The below words only contain substring repetitions:')
for word in wordList: # for each word
print(onlySubstrings(word), '\t', word)
</code></pre>
<p>If you imagine the string as circular unto itself, the string can only contain equal substring(s) if you can move the characters to the left or right and get the same original string in less than <code>len</code> shifts:</p>
<pre><code>testtest - 0 shifts, original string
esttestt - 1 shift, not original
sttestte - 2 shifts, not original
ttesttes - 3 shifts, not original
testtest - 4 shifts, original again
</code></pre>
<p>Since <code>4 < len</code>, it contains only substring repetitions.</p>
<pre><code>testteste - 0 shifts, original string
esttestet - 1 shift, not original
...
etesttest - (len-1) shifts, not original
testteste - len shifts, original again
</code></pre>
<p>Since we couldn't find the original string again in under <code>len</code> shifts, it does not only contain repetitions of a substring.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T05:43:21.400",
"Id": "425318",
"Score": "0",
"body": "I also just realized that a string containing >1 equal substrings must have maximum substring length no more than half the string length. I don't need to shift `len-1` times, rather I need to shift `ceil(len/2)` times. Saves a little time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T07:52:44.147",
"Id": "425322",
"Score": "0",
"body": "another optimization: you don't need to check if `i` does not evenly divide `len(str)` since doing so would attempt to match partials which we know won't be true"
}
] | [
{
"body": "<p>The code is relatively concise and easy to read. Here are some points that could be improved:</p>\n\n<ul>\n<li>A general thing is the amount of commenting, you should generally resort to comments only when it's hard to make the code self-explanatory. You don't really need to comment each line of the code.</li>\n<li><p><code>stringCopy = (stringOrig+'.')[:-1] # copy string contents</code><br/>\nYou can make a copy this way instead <code>stringCopy = stringOrig[:]</code>.</p></li>\n<li><p>To make the code more readable, you can create a function that shifts a string n characters. This will really help make the code more readable.</p></li>\n<li><p>The <code>else</code> keyword after the <code>for</code> loop is not needed since you return anyway if you didn't finish the loop. <code>else</code> is usually used with <code>break</code> in the <code>for</code> loop.</p></li>\n<li><p>The name of the function could be slightly improved, maybe <code>consists_of_repeated_substrings</code>. This is longer but is very easy to understand.</p></li>\n<li><p>A note on performance: your algorithm creates a copy of the original string in each iteration. This works fine for shorter strings, but if you wanna make it more efficient you can consider matching the string without making a shifted copy of it.</p></li>\n</ul>\n\n<p>Incorporating these comments you could rewrite the code as follows:</p>\n\n<pre><code>def shifted_string(str, n):\n return str[n:] + str[:n]\n\ndef consists_of_repeated_substrings(str):\n '''\n Checks whether a string consists of a substring repeated multiple times.\n Ex. 'testtesttest' is the string 'test' repeated 3 times.\n '''\n\n # The string can only contain equal substrings if you can shift it n \n # times (0 < n < len) and get the same original string.\n for i in range(1, len(str)):\n if shifted_string(str, i) == str:\n return True\n return False\n</code></pre>\n\n<hr>\n\n<p>A clever algorithm for doing the same thing is as follows:</p>\n\n<pre><code>double_str = (str + str)[1:-1]\nreturn double_str.find(str) != -1\n</code></pre>\n\n<p>The idea is similar to yours, so I will leave understanding it as an exercise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T06:59:18.440",
"Id": "425320",
"Score": "0",
"body": "That is quite clever and an impressive truncated-to-one-line."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T06:31:57.993",
"Id": "220121",
"ParentId": "220117",
"Score": "5"
}
},
{
"body": "<p>My impression is that the code seems good: no suggestions at that level,\nother than a very minor one. Python's <code>for-else</code> structure is a bit of\nan oddball: I never use it and a almost never see it used. More to\nthe point, it adds no clarity in this specific case. Just return <code>False</code>\noutside the loop.</p>\n\n<p>Regarding the algorithm, however, I do have a suggestion. It\nseems fairly low level (in the sense of mucking around with character\nshifting and copying), not super easy to explain, and it did not\nseem intuitive at first glance to me.</p>\n\n<p>A different approach is to rely on string multiplication: if the\nfull string equals exactly N copies of a substring, then return <code>True</code>.\nYou just need to loop over all possible substring lengths. For example:</p>\n\n<pre><code>def onlySubstrings(orig):\n orig_len = len(orig)\n max_len = int(orig_len / 2)\n for i in range(1, max_len + 1):\n substr = orig[0:i]\n n_copies = int(orig_len / i)\n if orig == substr * n_copies:\n return True\n return False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T06:38:48.510",
"Id": "220122",
"ParentId": "220117",
"Score": "2"
}
},
{
"body": "<p>This can be shortened to a one-liner using regular expressions:</p>\n\n<pre><code>import re\ndef isMadeFromRepeatedSubstrings(text):\n return re.search(r'^(.+?)\\1+$', text)\n</code></pre>\n\n<p>The returned object will evaluate true or false, as in the original, and the substring itself is accessible via <code>.groups(1)</code>:</p>\n\n<pre><code>>>> isMadeFromRepeatedSubstrings(\"testtest\").groups(1)\n('test',)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T15:46:40.640",
"Id": "425356",
"Score": "1",
"body": "This is exactly what I thought of when I read the question title (under HNQ) but I would go with `(.+?)` instead of `(.+)`. It will make a difference if the input is something like \"TestTestTestTest\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T16:26:54.230",
"Id": "425358",
"Score": "0",
"body": "excellent point, edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:14:57.323",
"Id": "425364",
"Score": "0",
"body": "Please change your code to `snake_case` so people don't think `camelCase` is a widely accepted style in Python."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T08:21:23.697",
"Id": "220126",
"ParentId": "220117",
"Score": "4"
}
},
{
"body": "<p>On top of the other great answers, here are a few additional comments.</p>\n\n<p><strong>Style</strong></p>\n\n<p>There is a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python code called PEP 8</a> and I'd recommend reading it and trying to follow it more or less strictly.\nIt your case, you could change the functions/variables names.</p>\n\n<p><strong>Better tests</strong></p>\n\n<p>Your test suite can be improved with a few simple details:</p>\n\n<ul>\n<li><p>add the edge cases (strings of length 0 or 1) - also, these would need to be documented in the function docstring</p></li>\n<li><p>add to your structure the expected output so that you can check the result automatically</p></li>\n</ul>\n\n<p>You could write something like:</p>\n\n<pre><code>def unit_test_only_substring():\n # test cases - list of (input, expected_output)\n tests = [\n # Edge cases\n ('', False), # To be confirmed\n ('t', False), # To be confirmed\n # No repetition\n ('ab', False),\n ('tetestst', False),\n ('testteste', False),\n # Repetition\n ('tt', True),\n ('ttt', True),\n ('testtest', True),\n ('testtesttest', True),\n ]\n\n for str_input, expected_out in tests:\n out = onlySubstrings(str_input)\n print(out, '\\t', expected_out, '\\t', str_input)\n assert out == expected_out\n\nif __name__ == '__main__':\n unit_test_only_substring()\n</code></pre>\n\n<p>You could go further and use a proper unit-test framework.</p>\n\n<p><strong>More code improvement</strong></p>\n\n<p>(Based on Hesham Attia)\nThis is great chance to learn about Python builtins <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> and <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a>:</p>\n\n<pre><code>def onlySubstrings(string):\n # The string can only contain equal substrings if you can shift it n\n # times (0 < n < len) and get the same original string.\n return any(shiftedString(string, i) == string for i in range(1, len(string)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T10:31:07.270",
"Id": "220130",
"ParentId": "220117",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220121",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T05:07:24.047",
"Id": "220117",
"Score": "5",
"Tags": [
"python",
"strings"
],
"Title": "Determine if a string only contains repetitions of a substring"
} | 220117 |
<p>I watched a YouTube video and completed the Todo List using Pure JavaScript.</p>
<p>Below is the code I wrote. I want to improve this code, but it 's not clear how.</p>
<p>I want to change this code to constructor function, but it's not easy. I think that the addItemTodo code is not bad, but the code in removeItem and completeItem are not good.</p>
<pre><code>function TodoList(todo) {
this.todo = todo;
}
function UI() {
this.addItemTodo = function(todo) {
var list = document.getElementById('todo');
var item = document.createElement('li');
item.innerText = todo.todo;
var buttons = document.createElement('div');
buttons.classList.add('buttons');
var remove = document.createElement('button');
remove.classList.add('remove');
remove.innerHTML = removeSVG;
remove.addEventListener('click', this.removeItem);
var complete = document.createElement('button');
complete.classList.add('complete');
complete.innerHTML = completeSVG;
complete.addEventListener('click', this.completeItem);
buttons.appendChild(remove);
buttons.appendChild(complete);
item.appendChild(buttons);
list.insertBefore(item, list.childNodes[0]); // 최신 순으로 목록 삽입
};
this.removeItem = function(e) {
console.log(e.target);
var item = this.parentNode.parentNode;
var parent = item.parentNode;
parent.removeChild(item);
};
this.completeItem = function() {
var item = this.parentNode.parentNode;
var parent = item.parentNode;
var id = parent.id;
var target = (id === 'todo') ? document.getElementById('completed') : document.getElementById('todo');
parent.removeChild(item);
target.insertBefore(item, target.childNodes[0]);
};
this.clearFields = function() {
document.getElementById('item').value = "";
}
}
var addBtn = document.getElementById('add');
addBtn.addEventListener('click', function() {
var value = document.getElementById('item').value;
var todoList = new TodoList(value);
var ui = new UI();
if(value) {
ui.addItemTodo(todoList);
ui.clearFields();
} else {
console.log("리스트를 입력해 주세요")
}
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T12:29:43.507",
"Id": "425412",
"Score": "2",
"body": "Can you provide HTML please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T08:29:16.407",
"Id": "425708",
"Score": "0",
"body": "it's html code \n`\n<div id=\"wrapper\">\n <header>\n <input type=\"text\" placeholder=\"오늘 할일을 입력해 주세요.\" id=\"item\">\n <button id=\"add”>…</button>\n </header>\n <div class=\"container\">\n <ul class=\"todo\" id=\"todo\"></ul>\n <ul class=\"todo\" id=\"completed\"></ul>\n </div>\n</div>\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:24:19.813",
"Id": "425894",
"Score": "0",
"body": "Where is `completeSVG` defined?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T05:30:54.173",
"Id": "220118",
"Score": "6",
"Tags": [
"javascript",
"object-oriented",
"dom",
"to-do-list"
],
"Title": "Todo list using pure JavaScript"
} | 220118 |
<p>I have written a query to generate payroll based on attendance for a month, for about 4000 employees. It takes quite a long time to execute. Basically, what I am doing is to joining two different queries using a common key for a single line of output per employee. But some blog suggests that <strong>UNION</strong> on this type of join would perform better. Is there any way to reduce time with my current query, or would UNION help?</p>
<pre><code>DECLARE @EmployeePayrollDataTable AS TABLE (EmployeeId int,LegalOverTime int,ExtraOverTime int,ToatalOverTime int,OK int,LateDays int,
AbsentDays int, LeaveDays int, HolidayOffdays int,BasicPay decimal,GrossPay decimal,HouseRent decimal,MedicalFoodTransportCost decimal,
BasicPayRate decimal,GrossPayRate decimal,OverTimeRate float,AttendanceBonus decimal,StampDeduction decimal);
DECLARE @EmployeePayrollTable AS TABLE (EmployeeId int,BasicSalary decimal,HouseRent decimal,MedicalFoodTransportCost decimal,GrossSalary decimal, TotalPresents int,
HolidayOffdays int, LeaveDays int,AbsentDays int, TotalDeduction decimal, TotalSalary decimal, AttendanceBonus decimal, OvertimeHours int, OvertimeRate float,
OvertimeAmount decimal, StampCharge decimal, FinalSalary decimal)
INSERT INTO @EmployeePayrollDataTable
SELECT A.EmployeeId,A.LegalOverTime,A.ExtraOverTime,A.ToatalOverTime,A.OK,A.LateDays,A.AbsentDays,A.LeaveDays,A.HolidayOffdays,
B.BasicPay,B.GrossPay,B.HouseRent,B.MedicalFoodTransportCost,B.BasicPayRate,B.GrossPayRate,B.OverTimeRate,B.AttendanceBonus,B.StampDeduction FROM
(SELECT TT.EmployeeId,
SUM(TT.LegalOverTime) AS LegalOverTime,
SUM(TT.ExtraOverTime) AS ExtraOverTime,
SUM(TT.LegalOverTime)+SUM(TT.ExtraOverTime) AS ToatalOverTime,
ISNULL(COUNT(OK), 0 ) OK,
ISNULL(COUNT(LateDays), 0 ) LateDays,
ISNULL(COUNT(AbsentDays), 0 ) AbsentDays,
ISNULL(COUNT(LeaveDays), 0 ) LeaveDays,
ISNULL(COUNT(HolidayOffdays), 0 ) HolidayOffdays
FROM
(SELECT HAH.EmployeeId,
CASE WHEN HAH.AttendanceStatus!=5 OR HAH.AttendanceStatus!=6 THEN
CASE WHEN HAH.PayableOverTime<=2 THEN HAH.PayableOverTime
WHEN HAH.PayableOverTime>2 THEN 2
ELSE 0
END
ELSE 0
END AS LegalOverTime,
CASE WHEN HAH.AttendanceStatus!=5 OR HAH.AttendanceStatus!=6 THEN
CASE WHEN HAH.PayableOverTime<=2 THEN 0
WHEN HAH.PayableOverTime>2 THEN HAH.PayableOverTime-2
ELSE 0
END
ELSE HAH.PayableOverTime
END AS ExtraOverTime,
CASE WHEN
(AttendanceStatus=1 and HAH.[Status]=1) THEN AttendanceStatus END AS OK,
CASE WHEN
(AttendanceStatus=2 and HAH.[Status]=1) THEN AttendanceStatus END AS LateDays,
CASE WHEN
(AttendanceStatus=3 and HAH.[Status]=1) THEN AttendanceStatus END AS AbsentDays,
CASE WHEN
(AttendanceStatus=4 and HAH.[Status]=1) THEN AttendanceStatus END AS LeaveDays,
CASE WHEN
((AttendanceStatus=5 or AttendanceStatus=6) and HAH.[Status]=1) THEN AttendanceStatus END AS HolidayOffdays
FROM HRMS_Attendance_History as HAH
JOIN HRMS_Employee HE on HAH.EmployeeId=HE.ID
WHERE HE.Present_Status=1 and CAST(HE.Joining_Date as Date)<='2019-04-01' and CAST([Date] as Date)>='2019-04-01' and CAST([Date] as Date)<='2019-04-30') TT
GROUP BY TT.EmployeeId) A
JOIN
(SELECT
T.EmployeeId,
ISNULL(SUM(BasicPay), 0 ) BasicPay,
ISNULL(SUM(GrossPay), 0 ) GrossPay,
ISNULL(SUM(HouseRent), 0 ) HouseRent,
ISNULL(SUM(MedicalFoodTransportCost), 0 ) MedicalFoodTransportCost,
ISNULL(SUM(BasicPay)/30, 0 ) BasicPayRate,
ISNULL(SUM(GrossPay)/30, 0 ) GrossPayRate,
ISNULL(SUM(OverTimeRate), 0 ) OverTimeRate,
ISNULL(SUM(AttendanceBonus), 0 ) AttendanceBonus,
ISNULL(SUM(StampDeduction), 0 ) StampDeduction
FROM (SELECT EmployeeId,
CASE WHEN
(Eod_RefFk=1 and er.[Status]=1) THEN ActualAmount END AS BasicPay,
CASE WHEN
((Eod_RefFk=1 or Eod_RefFk=2 or Eod_RefFk=3) and er.[Status]=1) THEN ActualAmount END AS GrossPay,
CASE WHEN
(Eod_RefFk=2 and er.[Status]=1) THEN ActualAmount END AS HouseRent,
CASE WHEN
(Eod_RefFk=3 and er.[Status]=1) THEN ActualAmount END AS MedicalFoodTransportCost,
CASE WHEN
(Eod_RefFk=11 and er.[Status]=1) THEN ActualAmount END AS OverTimeRate,
CASE WHEN
(Eod_RefFk=7 and er.[Status]=1) THEN ActualAmount END AS AttendanceBonus,
CASE WHEN
(Eod_RefFk=12 and er.[Status]=1) THEN ActualAmount END AS StampDeduction
FROM HRMS_EodRecord er JOIN HRMS_Employee e on er.EmployeeId=e.ID WHERE e.Present_Status=1 and CAST(e.Joining_Date as Date)<='2019-04-01') t
group by t.EmployeeId) B ON A.EmployeeId=B.EmployeeId
INSERT INTO @EmployeePayrollTable
SELECT EmployeeId,
BasicPay,
HouseRent,
MedicalFoodTransportCost,
GrossPay,
(OK+LateDays+LeaveDays+HolidayOffdays),
HolidayOffdays,
LeaveDays,
AbsentDays,
AbsentDays*BasicPayRate,
GrossPay-(AbsentDays*BasicPayRate),
CASE WHEN AbsentDays>0 or LeaveDays>0 or LateDays>2 THEN 0
ELSE AttendanceBonus END AS AttendanceBonus,
LegalOverTime,
OverTimeRate,
LegalOverTime*OverTimeRate,
StampDeduction,
CASE WHEN AbsentDays>0 or LeaveDays>0 or LateDays>2 THEN(LegalOverTime*OverTimeRate)+(GrossPay-(AbsentDays*BasicPayRate))-StampDeduction
ELSE (LegalOverTime*OverTimeRate)+(GrossPay-(AbsentDays*BasicPayRate)+AttendanceBonus)-StampDeduction END AS OvertimeAmount
FROM @EmployeePayrollDataTable
select * from @EmployeePayrollTable
</code></pre>
| [] | [
{
"body": "<p>Without specific explain plan details, consider these broad stroke recommendations. Currently, I do not see how <code>UNION</code> fits into your needs as you are essentially joining two conditional aggregation queries. And due to re-use of calculated columns, you require sub-select derived tables.</p>\n\n<ol>\n<li><p>Of course as always, analyze each <code>SELECT</code> queries' <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/performance/analyze-an-actual-execution-plan?view=sql-server-2017\" rel=\"nofollow noreferrer\">explain plan</a> and add necessary indexes on <code>JOIN</code> fields such as <em>EmployeeId</em> across the tables.</p></li>\n<li><p>Avoid unnecessary date casting such as with date fields in <code>WHERE</code> clauses using <code>CAST(... AS Date)</code>. If date fields are already date or datetime, simply <a href=\"https://stackoverflow.com/questions/1947436/datetime-in-where-clause\">compare directly</a> using the ISO-8601 standard format (<code>'YYYYMMDD'</code>) that is agnostic to language and regional settings. If these fields are not dates, consider changing them with <code>ALTER</code>.</p>\n\n<pre><code>WHERE HE.Present_Status = 1 \n AND HE.Joining_Date <= '20190401'\n AND [Date] >= '20190401' \n AND [Date] <= '20190430'\n</code></pre></li>\n<li><p>Avoid unnecessary <code>ISNULL(..., 0)</code> conversion. Instead use a 1 or 0 conditional calculation and then run <code>SUM</code> on top level query which are essentially counts of the boolean flags:</p>\n\n<pre><code>CASE WHEN (AttendanceStatus=1 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS OK,\nCASE WHEN (AttendanceStatus=2 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS LateDays,\nCASE WHEN (AttendanceStatus=3 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS AbsentDays,\nCASE WHEN (AttendanceStatus=4 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS LeaveDays,\n\n...\n\nSUM(TT.LateDays) AS LateDays,\nSUM(TT.AbsentDays) AS AbsentDays,\nSUM(TT.LeaveDays) AS LeaveDays,\nSUM(TT.HolidayOffdays) AS HolidayOffdays\n</code></pre></li>\n<li><p>Consider a CTE instead of a table variable to bypass the <code>DECLARE</code> and <code>INSERT</code> lines. However, do note this may <a href=\"https://stackoverflow.com/questions/690465/which-are-more-performant-cte-or-temporary-tables\">depend on your situation</a>.</p>\n\n<pre><code>WITH EmployeePayrollDataTable AS\n (...inner join of A and B aggregate subqueries...)\n\nSELECT EmployeeId, BasicPay, HouseRent, MedicalFoodTransportCost, GrossPay,\n (OK+LateDays+LeaveDays+HolidayOffdays), HolidayOffdays, LeaveDays,\n AbsentDays, AbsentDays*BasicPayRate, GrossPay-(AbsentDays*BasicPayRate),\n CASE WHEN AbsentDays>0 or LeaveDays>0 or LateDays>2 \n THEN 0\n ELSE AttendanceBonus \n END AS AttendanceBonus,\n LegalOverTime, OverTimeRate, LegalOverTime*OverTimeRate, StampDeduction, \n CASE WHEN AbsentDays>0 or LeaveDays>0 or LateDays>2 \n THEN (LegalOverTime*OverTimeRate) +\n (GrossPay-(AbsentDays*BasicPayRate))-StampDeduction\n ELSE (LegalOverTime*OverTimeRate) + \n (GrossPay-(AbsentDays*BasicPayRate) + AttendanceBonus) -\n StampDeduction \n END AS OvertimeAmount\nFROM EmployeePayrollDataTable\n</code></pre></li>\n<li><p>Since you use <code>INNER JOIN</code> across all <code>SELECT</code> queries and levels, you can conceivably join both aggregates to avoid the main query's <code>JOIN</code> and facilitate readability. </p>\n\n<pre><code>SELECT ...all unit level CASE statements...\n\nFROM HRMS_Attendance_History HAH\nJOIN HRMS_Employee HE ON HAH.EmployeeId = HE.ID\nJOIN HRMS_EodRecord er ON HAH.EmployeeId = er.EmployeeId\nJOIN HRMS_Employee e ON er.EmployeeId = e.ID \nWHERE HE.Present_Status = 1 \n AND HE.Joining_Date <= '20190401'\n AND [Date] >= '20190401' \n AND [Date] <= '20190430'\n AND e.Present_Status = 1\n AND e.Joining_Date as Date <= '20190401'\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>Overall re-factoring of SQL:</p>\n\n<pre><code>WITH EmployeePayrollDataTable AS\n (SELECT A.EmployeeId, A.LegalOverTime, A.ExtraOverTime, A.ToatalOverTime, \n A.OK, A.LateDays, A.AbsentDays, A.LeaveDays, A.HolidayOffdays,\n A.BasicPay, A.GrossPay, A.HouseRent, A.MedicalFoodTransportCost, A.BasicPayRate, \n A.GrossPayRate, A.OverTimeRate, A.AttendanceBonus, A.StampDeduction \n FROM \n (SELECT TT.EmployeeId, \n SUM(TT.LegalOverTime) AS LegalOverTime,\n SUM(TT.ExtraOverTime) AS ExtraOverTime, \n SUM(TT.LegalOverTime) + SUM(TT.ExtraOverTime) AS ToatalOverTime,\n SUM(TT.OK) AS OK,\n SUM(TT.LateDays) AS LateDays,\n SUM(TT.AbsentDays) AS AbsentDays,\n SUM(TT.LeaveDays) AS LeaveDays,\n SUM(TT.HolidayOffdays) AS HolidayOffdays,\n\n SUM(TT.BasicPay) AS BasicPay,\n SUM(TT.GrossPay) AS GrossPay,\n SUM(TT.HouseRent) AS HouseRent,\n SUM(TT.MedicalFoodTransportCost) AS MedicalFoodTransportCost,\n SUM(TT.BasicPay)/30 AS BasicPayRate,\n SUM(TT.GrossPay)/30 AS GrossPayRate,\n SUM(TT.OverTimeRate) AS OverTimeRate,\n SUM(TT.AttendanceBonus) AS AttendanceBonus,\n SUM(TT.StampDeduction) AS StampDeduction \n FROM\n (SELECT HAH.EmployeeId,\n CASE WHEN HAH.AttendanceStatus!=5 OR HAH.AttendanceStatus!=6 \n THEN \n CASE WHEN HAH.PayableOverTime <= 2 THEN HAH.PayableOverTime\n WHEN HAH.PayableOverTime > 2 THEN 2\n ELSE 0\n END\n ELSE 0\n END AS LegalOverTime,\n\n CASE WHEN HAH.AttendanceStatus!=5 OR HAH.AttendanceStatus!=6 \n THEN \n CASE WHEN HAH.PayableOverTime <= 2 THEN 0\n WHEN HAH.PayableOverTime > 2 THEN HAH.PayableOverTime-2\n ELSE 0\n END\n ELSE HAH.PayableOverTime\n END AS ExtraOverTime,\n\n CASE WHEN (AttendanceStatus=1 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS OK,\n CASE WHEN (AttendanceStatus=2 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS LateDays,\n CASE WHEN (AttendanceStatus=3 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS AbsentDays,\n CASE WHEN (AttendanceStatus=4 AND HAH.[Status]=1) THEN 1 ELSE 0 END AS LeaveDays,\n CASE WHEN ((AttendanceStatus=5 OR AttendanceStatus=6) AND HAH.[Status]=1) THEN AttendanceStatus END AS HolidayOffdays,\n\n CASE WHEN (Eod_RefFk=1 AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS BasicPay,\n CASE WHEN ((Eod_RefFk=1 OR Eod_RefFk=2 OR Eod_RefFk=3) AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS GrossPay,\n CASE WHEN (Eod_RefFk=2 AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS HouseRent,\n CASE WHEN (Eod_RefFk=3 AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS MedicalFoodTransportCost,\n CASE WHEN (Eod_RefFk=11 AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS OverTimeRate,\n CASE WHEN (Eod_RefFk=7 AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS AttendanceBonus,\n CASE WHEN (Eod_RefFk=12 AND er.[Status]=1) THEN ActualAmount ELSE 0 END AS StampDeduction\n\n FROM HRMS_Attendance_History HAH\n JOIN HRMS_Employee HE ON HAH.EmployeeId = HE.ID\n JOIN HRMS_EodRecord er ON HAH.EmployeeId = er.EmployeeId\n JOIN HRMS_Employee e ON er.EmployeeId=e.ID \n WHERE HE.Present_Status = 1 \n AND HE.Joining_Date <= '20190401'\n AND [Date] >= '20190401' \n AND [Date] <= '20190430'\n AND e.Present_Status = 1\n AND e.Joining_Date as Date <= '20190401'\n ) TT\n GROUP BY TT.EmployeeId) A\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T06:34:04.523",
"Id": "427411",
"Score": "0",
"body": "thanks @Parfait for your analysis and answer.Your query very nice to remove some redundant cast and ISNULL expression with simple if else. However, I can't get required result using single join as you had answered. Basically problem is you join Salary table with attendance and then SUM. The problem is this sum produce huge figure as it not represent single salary rather than 30 same salary due to attendance of 30 days. For example. If basic salary 5000 then 30 days sum make (5000*30)=150000 which is incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T06:45:06.430",
"Id": "427412",
"Score": "0",
"body": "I solved this using MAX rather than SUM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:59:41.093",
"Id": "427544",
"Score": "0",
"body": "Great to hear! Yes, this was untested solution without data but glad you can work it for final solution. Please don't forget the StackExchange way of saying [thanks](https://meta.stackexchange.com/a/5235) if solution helped of course!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-23T16:32:25.473",
"Id": "220851",
"ParentId": "220124",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T07:38:58.417",
"Id": "220124",
"Score": "1",
"Tags": [
"performance",
"sql",
"sql-server",
"t-sql",
"join"
],
"Title": "Query to generate payroll based on attendance for a month"
} | 220124 |
<p>I am trying to improve the performance of my cellular automata lab. I have two arrays of <code>Double</code>s representing the current values and the next values.</p>
<p>If I run the calculation in a single thread I get about 28 steps per second. However, if I break the work down into 2, 3 or 4 chunks and pass them into a concurrency queue I still get about 28 steps per second. If I increase the chunks further the algorithm takes longer and longer to complete, for example 10 chunks drops the performance to about 10 steps per second.</p>
<p>I'm testing this on a 3rd generation iPad Pro with 4 performance cores and 4 efficiency cores.</p>
<pre><code>func step(from: Int, to: Int) {
for j in from..<to {
for i in 0..<w {
AEMemoryClear(memory);
AEMemorySetValue(memory, sI, cells[i + (j )*w])
AEMemorySetValue(memory, aI, i != 0 && j != 0 ? cells[i-1 + (j-1)*w] : 0)
AEMemorySetValue(memory, bI, j != 0 ? cells[i + (j-1)*w] : 0)
AEMemorySetValue(memory, cI, i != wB && j != 0 ? cells[i+1 + (j-1)*w] : 0)
AEMemorySetValue(memory, dI, i != wB ? cells[i+1 + (j )*w] : 0)
AEMemorySetValue(memory, eI, i != wB && j != hB ? cells[i+1 + (j+1)*w] : 0)
AEMemorySetValue(memory, fI, j != hB ? cells[i + (j+1)*w] : 0)
AEMemorySetValue(memory, gI, i != 0 && j != hB ? cells[i-1 + (j+1)*w] : 0)
AEMemorySetValue(memory, hI, i != 0 ? cells[i-1 + (j )*w] : 0)
AERecipeExecute(recipe, memory)
next[i + j*w] = memory.pointee.slots[index].obj.a.x
}
}
}
func step() {
let start = DispatchTime.now()
let n: Int = 4
let z: Int = h/n
let group = DispatchGroup()
for i in 0..<n {
group.enter()
DispatchQueue.global(qos: .userInteractive).async { [unowned self] in
self.step(from: i*z, to: i == n-1 ? self.h : (i+1)*z)
group.leave()
}
}
group.notify(queue: .main) { [unowned self] in
(self.cells, self.next) = (self.next, self.cells)
let end = DispatchTime.now()
let delta = Double(end.uptimeNanoseconds - start.uptimeNanoseconds)/1000000000
let target: Double = 1.0/60
print("Time to calculate: \(delta) or \(round(1/delta)) SPS which is \(round(delta/target*100*10)/10)% of target; # of cells: \(self.w)^2 = \(self.w*self.h); seconds per cell: \(delta/Double(self.w*self.w))")
}
group.wait()
}
</code></pre>
<p>Also, another weird thing I'm noticing: if I run the calculation once a second it takes more than twice as long to complete than if I run it several times a second. The only reason I can possibly think is that its using the efficiency core instead of the performance core in that case.</p>
<p>Note: <code>AEMemorySetValue</code>, <code>AERecipeExecute</code>, <code>AEMemoryClear</code> are C functions.</p>
<p><code>h</code> and <code>w</code> are the cell dimensions of the cellular automata; the height and width. In practice they are the same and are about 300-500, depending on the device. Also, <code>h</code>, <code>w</code>, <code>index</code>, <code>sI</code>, <code>aI</code>...<code>hI</code> are all static values that do not change at all through this entire process.</p>
<p>I also entirely moved the inner step function from Swift to C, but that had zero effect on the performance, positive or negative.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T10:45:59.317",
"Id": "425326",
"Score": "2",
"body": "This may be instructive: https://stackoverflow.com/a/46499306/1187415."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T18:24:39.177",
"Id": "425532",
"Score": "1",
"body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 7 → 5."
}
] | [
{
"body": "<p>Before we comment on the speed issue, perhaps we should talk about the multithread correctness of <code>step(from:to:)</code>. You are referencing <code>memory</code> and <code>index</code>. You appear to be updating the same memory from all of your threads. That is not thread-safe. Your don’t want multiple threads updating the same memory reference. If you temporarily turn on the thread sanitizer (known as TSAN, found in “Product” » “Scheme” » “Edit Scheme...” (or press <kbd>⌘</kbd>+<kbd><</kbd>) and then choose the “Diagnostics” tab), it may well warn you of this problem.</p>\n\n<p>Let’s assume for a second that we get the thread-safety question behind us. The multithreaded performance concerns include:</p>\n\n<ol>\n<li><p>Make sure you are striding to ensure that there is enough work on each thread, to ensure that the parallelism benefits are not outweighed by thread management overhead. That having been said, you are striding already with sufficient work on each thread, so that’s unlikely to be the problem here, but it often plagues naive parallelism attempts.</p></li>\n<li><p>You may want to use <code>concurrentPerform</code> rather than just dispatching a bunch of blocks to a global queue and using a dispatch group to determine when they finished. The <code>concurrentPerform</code> will spin up the correct number of threads appropriate for your hardware, whereas if you write your own dispatching to concurrent queues, you might suboptimize the solution (e.g. you can exhaust the limited number of worker threads if you’re not careful).</p>\n\n<p>In your case, the benefit of <code>concurrentPerform</code> will likely not be material, but it’s the first thing to consider when writing code that is effectively parallelized <code>for</code> loops. See <a href=\"https://stackoverflow.com/a/46499306/1187415\">https://stackoverflow.com/a/46499306/1187415</a> and <a href=\"https://stackoverflow.com/a/39949292/1271826\">https://stackoverflow.com/a/39949292/1271826</a> for introductions to <code>concurrentPerform</code>.</p></li>\n<li><p>The key issue here is that one needs good algorithm design to minimize memory contention issues, cache sloshing, etc.</p>\n\n<p>But let’s assume that you are really accessing/updating different <code>index</code> values through something not shared in your code snippet and are updating adjacent memory addresses. That can still result in problems. See below.</p>\n\n<p>You said:</p>\n\n<blockquote>\n <p>I believe <code>memory</code> (and “recipe”) are going to need separate instances per “stride”. It's not clear to me exactly how that is slowing things down...</p>\n</blockquote>\n\n<p>Yes, that’s likely the issue in this case. When writing multithreaded code, you have to be sensitive to the memory locations updated by parallel threads. For example, consider the following that adds the numbers between 0 and 100 million, updating an array of four values as it goes along, in parallel:</p>\n\n<pre><code>var array = Array(repeating: 0, count: 4)\n\nDispatchQueue.global().async {\n DispatchQueue.concurrentPerform(iterations: 4) { index in\n for i in 0 ..< 100_000_000 {\n array[index] += i\n }\n }\n ...\n}\n</code></pre>\n\n<p>Optimized for speed, that takes roughly 1.3 seconds on my machine (almost 3× slower than singled-threaded implementation). The issue in this contrived example is that we have multiple threads updating memory addresses very close to each other. You end up having CPU cores “sloshing” memory caches back and forth as the four threads are all trying to update the same block of memory.</p>\n\n<p>For illustration purposes, consider the same code, except that instead of updating items right next to each other, I space them out by padding the array, grabbing the items at index values of 0, 1000, 2000, and 3000 (reducing CPU cache misses):</p>\n\n<pre><code>var array = Array(repeating: 0, count: 4 * 1000)\n\nDispatchQueue.global().async {\n DispatchQueue.concurrentPerform(iterations: 4) { index in\n let updatedIndex = index * 1000\n for i in 0 ..< 100_000_000 {\n array[updatedIndex] += i\n }\n }\n ...\n}\n</code></pre>\n\n<p>This is deliberately not touching much of the array, just updating four values. This looks absurd (and is not advisable) and one wouldn’t be faulted for assuming that this is far less efficient with all of that wasted memory. But it is actually 5× faster, taking roughly 0.25 seconds on the same machine.</p>\n\n<p>That’s obviously an absurd example, but it illustrates the problem. But we can make it far more efficient like so:</p>\n\n<pre><code>var array = Array(repeating: 0, count: 4)\n\nlet synchronizationQueue = DispatchQueue(label: \"sync\")\nDispatchQueue.global().async {\n DispatchQueue.concurrentPerform(iterations: 4) { index in\n var value = synchronizationQueue.sync { array[index] }\n for i in 0 ..< 100_000_000 {\n value += i\n }\n synchronizationQueue.async { array[index] = value }\n }\n ...\n}\n</code></pre>\n\n<p>Even with the extra synchronization code to make sure that I have thread-safe interaction with this <code>array</code>, it’s still now another 5× faster, taking 0.05 seconds. If you can minimize updates to the same block of memory, you can have a material impact on performance, starting to enjoy the benefits of parallelism.</p></li>\n</ol>\n\n<p>Bottom line, you have to be very careful about how multiple threads update shared memory blocks and balance workloads between the threads. It can have a considerable impact on performance. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T03:28:30.820",
"Id": "425475",
"Score": "0",
"body": "Umm, wow this is just awesome. I'm going to squeeze some time into working on this later today and will report back. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T21:48:19.763",
"Id": "425548",
"Score": "0",
"body": "I've posted the result of your help as an answer here. Thanks again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T01:36:44.743",
"Id": "220213",
"ParentId": "220128",
"Score": "3"
}
},
{
"body": "<p>The first thing I tried is to convert my inner step function to C and then to move from DispatchGroup to concurrentPerform. Neither had any effect and I was still getting about 28 steps per second.</p>\n\n<p>I then created a new C struct that contains all the data needed to perform the calculation and created an array of these objects; one for each \"iteration\". Finally, this gave me a significant speed boost. The code looks like this:</p>\n\n<p>Ionian.h</p>\n\n<pre><code>#import \"Aegean.h\"\n\ntypedef struct Automata {\n Recipe* recipe;\n Memory* memory;\n int w;\n byte sI;\n byte aI;\n byte bI;\n byte cI;\n byte dI;\n byte eI;\n byte fI;\n byte gI;\n byte hI;\n byte rI;\n} Automata;\n\nAutomata* AXAutomataCreate(Recipe* recipe, Memory* memory, int w, byte sI, byte aI, byte bI, byte cI, byte dI, byte eI, byte fI, byte gI, byte hI, byte rI);\nAutomata* AXAutomataCreateClone(Automata* automata);\nvoid AXAutomataRelease(Automata* automata);\nvoid AXAutomataStep(Automata* automata, double* cells, double* next, int from, int to);\n</code></pre>\n\n<p>Ionian.c</p>\n\n<pre><code>#include <stdlib.h>\n#include \"Ionian.h\"\n\nAutomata* AXAutomataCreate(Recipe* recipe, Memory* memory, int w, byte sI, byte aI, byte bI, byte cI, byte dI, byte eI, byte fI, byte gI, byte hI, byte rI) {\n Automata* automata = (Automata*)malloc(sizeof(Automata));\n automata->recipe = AERecipeCreateClone(recipe);\n automata->memory = AEMemoryCreateClone(memory);\n automata->w = w;\n automata->sI = sI;\n automata->aI = aI;\n automata->bI = bI;\n automata->cI = cI;\n automata->dI = dI;\n automata->eI = eI;\n automata->fI = fI;\n automata->gI = gI;\n automata->hI = hI;\n automata->rI = rI;\n return automata;\n}\nAutomata* AXAutomataCreateClone(Automata* automata) {\n Automata* clone = (Automata*)malloc(sizeof(Automata));\n clone->recipe = AERecipeCreateClone(automata->recipe);\n clone->memory = AEMemoryCreateClone(automata->memory);\n clone->w = automata->w;\n clone->sI = automata->sI;\n clone->aI = automata->aI;\n clone->bI = automata->bI;\n clone->cI = automata->cI;\n clone->dI = automata->dI;\n clone->eI = automata->eI;\n clone->fI = automata->fI;\n clone->gI = automata->gI;\n clone->hI = automata->hI;\n clone->rI = automata->rI;\n return clone;\n}\nvoid AXAutomataRelease(Automata* automata) {\n if (automata == 0) return;\n AERecipeRelease(automata->recipe);\n AEMemoryRelease(automata->memory);\n free(automata);\n}\n\nvoid AXAutomataStep(Automata* a, double* cells, double* next, int from, int to) {\n for (int j = from; j < to; j++) {\n for (int i = 0; i < a->w; i++) {\n\n AEMemoryClear(a->memory);\n\n AEMemorySetValue(a->memory, a->sI, cells[i + (j )*a->w]);\n AEMemorySetValue(a->memory, a->aI, i != 0 && j != 0 ? cells[i-1 + (j-1)*a->w] : 0);\n AEMemorySetValue(a->memory, a->bI, j != 0 ? cells[i + (j-1)*a->w] : 0);\n AEMemorySetValue(a->memory, a->cI, i != a->w-1 && j != 0 ? cells[i+1 + (j-1)*a->w] : 0);\n AEMemorySetValue(a->memory, a->dI, i != a->w-1 ? cells[i+1 + (j )*a->w] : 0);\n AEMemorySetValue(a->memory, a->eI, i != a->w-1 && j != a->w-1 ? cells[i+1 + (j+1)*a->w] : 0);\n AEMemorySetValue(a->memory, a->fI, j != a->w-1 ? cells[i + (j+1)*a->w] : 0);\n AEMemorySetValue(a->memory, a->gI, i != 0 && j != a->w-1 ? cells[i-1 + (j+1)*a->w] : 0);\n AEMemorySetValue(a->memory, a->hI, i != 0 ? cells[i-1 + (j )*a->w] : 0);\n\n AERecipeExecute(a->recipe, a->memory);\n\n next[i + j*a->w] = a->memory->slots[a->rI].obj.a.x;\n }\n }\n}\n</code></pre>\n\n<p>And the Swift code:</p>\n\n<pre><code>func compile(aether: Aether) {\n\n //...\n\n let automata = AXAutomataCreate(recipe, memory, Int32(w), sI, aI, bI, cI, dI, eI, fI, gI, hI, byte(index));\n for _ in 0..<iterations {\n automatas.append(AXAutomataCreateClone(automata))\n }\n AXAutomataRelease(automata)\n}\nfunc step() {\n let start = DispatchTime.now()\n let stride: Int = h/iterations\n\n DispatchQueue.global(qos: .userInitiated).async {\n\n DispatchQueue.concurrentPerform(iterations: self.iterations, execute: { (i: Int) in\n AXAutomataStep(self.automatas[i], self.cells, self.next, Int32(i*stride), Int32(i == self.strides-1 ? self.h : (i+1)*stride))\n })\n\n (self.cells, self.next) = (self.next, self.cells)\n\n let end = DispatchTime.now()\n let delta = Double(end.uptimeNanoseconds - start.uptimeNanoseconds)/1000000000\n let target: Double = 1.0/60\n print(\"Time to calculate: \\(delta) or \\(round(1/delta)) SPS which is \\(round(delta/target*100*10)/10)% of target; # of cells: \\(self.w)^2 = \\(self.w*self.h); seconds per cell: \\(delta/Double(self.w*self.w))\")\n }\n}\n</code></pre>\n\n<p>I obtained the following results on my 3rd gen iPad Pro:</p>\n\n<pre><code>Iterations Steps per Second\n 1 27\n 2 50\n 3 76\n 4 54-60\n 5 60-72\n 6 53-74\n 10 47-76\n 99 65-81\n999 27\n</code></pre>\n\n<p>On my current device, breaking the work into 3 parts gets me a consistent 76 sps, which gets me beyond my goal of 60 sps on a 503x503 grid = 253,009 cells.</p>\n\n<p>Although, I'm still a bit mystified about the various results of the various iteration numbers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T21:47:15.240",
"Id": "220255",
"ParentId": "220128",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "220213",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T08:49:24.587",
"Id": "220128",
"Score": "1",
"Tags": [
"performance",
"c",
"multithreading",
"swift",
"concurrency"
],
"Title": "Multi-Threaded Cellular Automata Lab"
} | 220128 |
<p>I wrote this Java game where the user memorizes a list, gets given letters and needs to find a word that contains those letters. The player has only a few seconds to enter the word.</p>
<p><strong>Example:</strong></p>
<p>Program outputs: <strong>AN</strong></p>
<p>Player can input: <strong>AN</strong>TILIBERALISM, HUM<strong>AN</strong>ITARI<strong>AN</strong>ISM, N<strong>AN</strong>OTECHNOLOGY if those are in the memorized list file and they haven't been entered yet.</p>
<p>Other possible inputs for the player:</p>
<ul>
<li><strong>pause</strong>: Pauses the game until the player types something. </li>
<li><strong>skip</strong>: Skips the current letters.</li>
<li><strong>stop</strong>: Stops the game, prints the scores.</li>
<li><strong>new</strong>: Prints the new words that the player didn't memorize yet, those are at the end of the file.</li>
</ul>
<p><strong>Code:</strong></p>
<pre><code>import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
class Game {
private static final String F_NAME = "LIST.txt";
private static final int TIME_PER_ANSWER = 10;
private Map<String, List<String>> answersMap;
private volatile String answer;
private final Map<String, String> COMMANDS_OUTPUT_MAP = Collections.unmodifiableMap(Map.of(
"STOP", "Game stopped manually.",
"PAUSE", "Game paused.",
"ANSWER_DOESNT_CONTAIN_SYLL", "Doesn't contain letters...",
"WORDSLIST_DOESNT_CONTAIN_WORD", "The word is not in the list...",
"ANSWER_ALREADY_TYPED", "Already put..."
));
private final List<String> STOP_WAITING_FOR_ANSWER_COMMANDS = Collections.unmodifiableList(List.of(
"STOP",
"PAUSE",
"SKIP"
));
class ReaderThread implements Runnable {
@Override
public void run() {
Scanner in = new Scanner(System.in);
while (!Thread.interrupted()) {
answer = in.nextLine().toUpperCase();
}
}
}
public static void main(String[] args) {
new Game();
}
private Game() {
System.out.println("New game. Input file: " + F_NAME + ". Time per answer: " + TIME_PER_ANSWER + " seconds.");
System.out.println("Commands: " + STOP_WAITING_FOR_ANSWER_COMMANDS);
this.answersMap = new TreeMap<>();
Random rand = new Random();
int wordCounter = 0, lifeCounter = 0;
List<String> syllsList = Objects.requireNonNull(getSyllsList());
List<String> wordsList = Objects.requireNonNull(getWordsList());
Optional<List<String>> newWordsListOptional = getNewWordsListOptional(wordsList);
newWordsListOptional.ifPresent((list) -> System.out.println("New words: " + list));
Optional<List<String>> noSyllsMatchListOptional = getNoSyllsMatchListOptional(syllsList, wordsList);
noSyllsMatchListOptional.ifPresent(list -> {
System.out.println("WARNING: THESE LETTERS ARE IN NO WORDS: " + list);
syllsList.removeAll(list);
});
Optional<List<String>> noWordsMatchListOptional = getNoWordsMatchListOptional(syllsList, wordsList);
noWordsMatchListOptional.ifPresent(list -> {
System.out.println("WARNING: THESE WORDS CONTAIN NO INPUT LETTERS: " + list);
wordsList.removeAll(list);
});
Collections.shuffle(wordsList);
int syllsListTotal = syllsList.size();
String hint;
new Thread(new ReaderThread()).start();
while(syllsList.size() > 0) {
resetAnswer();
String syll = syllsList.get(rand.nextInt(syllsList.size()));
if(findMatchingWord(syll, wordsList) == null) {
syllsList.remove(syll);
printSyllChangeMessage(syll, syllsListTotal, syllsList);
continue;
}
System.out.println(syll);
try {
do {
if(answer.equals("PAUSE"))
Awaitility.await().forever().until(() -> !answer.equals("PAUSE"));
Awaitility.await().atMost(TIME_PER_ANSWER, TimeUnit.SECONDS).until(() -> checkAnswer(syll, wordsList, newWordsListOptional));
} while(answer.equals("PAUSE"));
} catch (ConditionTimeoutException ignore) { }
if(answer.equals("STOP")) break;
if (answer.equals("") || answer.equals("SKIP")) {
hint = findMatchingWord(syll, wordsList);
System.out.println("HINT: " + hint +".");
lifeCounter++;
} else {
answersMap.computeIfAbsent(syll, liste -> new ArrayList<>()).add(answer);
wordCounter++;
}
}
for(String key : answersMap.keySet()) {
System.out.println(key + " : " + answersMap.get(key));
}
System.out.println("Number of words : " + wordCounter + " | Number of lifes lost : " + lifeCounter);
System.exit(0);
}
private LinkedList<String> getSyllsList() {
try {
return new LinkedList<>(Arrays.asList(Files.lines(Paths.get(F_NAME))
.findFirst()
.orElse("")
.split("\\|")));
} catch(IOException io) {
io.printStackTrace();
return null;
}
}
private List<String> getWordsList() {
try {
return Files.lines(Paths.get(F_NAME))
.skip(1)
.collect(Collectors.toList());
} catch(IOException io) {
io.printStackTrace();
return null;
}
}
private Optional<List<String>> getNoSyllsMatchListOptional(List<String> syllsList, List<String> wordsList) {
final String wordsListString = wordsList.toString();
List<String> noSyllsMatchList = syllsList.stream()
.filter(s -> !wordsListString.contains(s))
.collect(Collectors.toList());
return Optional.ofNullable(noSyllsMatchList.isEmpty() ? null : noSyllsMatchList);
}
private Optional<List<String>> getNoWordsMatchListOptional(List<String> syllsList, List<String> wordsList) {
List<String> noWordsMatchList = wordsList.stream()
.filter(word -> {
for(String syll : syllsList)
if(word.contains(syll)) return false;
return true;
})
.collect(Collectors.toList());
return Optional.ofNullable(noWordsMatchList.isEmpty() ? null : noWordsMatchList);
}
private boolean checkAnswer(String syll, List<String> wordsList, Optional<List<String>> newWordsListOptional) {
if(answer.equals("")) return false;
if(answer.equals("NEW")) {
if(newWordsListOptional.isPresent())
System.out.println("New words: " + newWordsListOptional.get());
else
System.out.println("No new words.");
resetAnswer();
return false;
}
String command = answer;
if(!STOP_WAITING_FOR_ANSWER_COMMANDS.contains(command)) {
if (!answer.contains(syll)) command = "ANSWER_DOESNT_CONTAIN_SYLL";
else if (answerAlreadyTyped(answer)) command = "ANSWER_ALREADY_TYPED";
else if (!wordsList.contains(answer)) command = "WORDSLIST_DOESNT_CONTAIN_WORD";
}
final Optional<String> OUTPUT_MESSAGE = Optional.ofNullable(COMMANDS_OUTPUT_MAP.get(command));
if(OUTPUT_MESSAGE.isPresent()) {
System.out.println(OUTPUT_MESSAGE.get());
if (!STOP_WAITING_FOR_ANSWER_COMMANDS.contains(command)) {
resetAnswer();
return false;
}
}
return true;
}
private void resetAnswer() {
answer = "";
}
private boolean answerAlreadyTyped(String answer) {
return answersMap.values()
.stream()
.flatMap(List::stream)
.collect(Collectors.toList())
.contains(answer);
}
private String findMatchingWord(String syll, List<String> wordsList) {
return wordsList.stream()
.filter(word -> word.contains(syll))
.filter(word -> !answerAlreadyTyped(word))
.findAny()
.orElse(null);
}
private Optional<List<String>> getNewWordsListOptional (List<String> wordsList) {
Optional<String> newWordsSeparator = wordsList.stream()
.filter(word -> word.startsWith("-"))
.findFirst();
if(newWordsSeparator.isPresent()) {
int index = wordsList.indexOf(newWordsSeparator.get());
wordsList.remove(index);
return Optional.of(List.copyOf(wordsList.subList(index, wordsList.size())));
}
return Optional.empty();
}
private void printSyllChangeMessage(String syll, int syllsListTotal, List<String> syllsList) {
System.out.println("ALL WORDS HAVE BEEN PUT FOR LETTERS: " + syll + ". LETTERS REMOVED. " +
"ALL LETTERS PUT FOR: " + (syllsListTotal - syllsList.size()) + " / " + (syllsListTotal));
}
}
</code></pre>
<p><strong>Test with file <code>LIST.txt</code>:</strong></p>
<pre><code>BE|AN|IS|XY
BENEDICTION
BEAUTIFULLNESS
ANTILIBERALISM
RADIOLABELLING
IMPRESSIONISTIC
UNDISTINGUISHED
HUMANITARIANISM
AUTOTRANSFORMER
INTELLIGENT
-------------------------- MY NEW WORDS TO MEMORIZE -------------------------
FEATHERBEDDING
BIOGEOCHEMISTRY
CIRCUMSTANTIAL
NANOTECHNOLOGY
ANTIAPHRODISIAC
ESSENTIALISM
</code></pre>
<p><strong>A few questions:</strong></p>
<ul>
<li>I use <a href="https://github.com/awaitility/awaitility" rel="nofollow noreferrer">Awaibility</a> (there was no tag for it...) to wait for the user input until his words is correct or time is running out, won't work without it. If you want to test the code, download <code>awaibility</code> and <code>awaibility-dependancies</code> from <a href="https://github.com/awaitility/awaitility/wiki/Downloads" rel="nofollow noreferrer">there</a>. <strong>Is there an easy alternative to it?</strong></li>
<li>I don't think the code is optimized. <strong>How could I optimize it?</strong></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T08:56:20.437",
"Id": "220129",
"Score": "2",
"Tags": [
"java",
"game",
"multithreading",
"file",
"collections"
],
"Title": "Game involving finding words containing letters from a memorized list"
} | 220129 |
<p>I'm learning backend dev and python and django<sup>1</sup>.</p>
<p>My first app is a basic auction site. Users sign up, submit an auction, and other users bid on the auctions.</p>
<p>I would highly appreciate any experienced eyes running over the code and letting me know if I am doing anything wrong. I don't want to start the rather labrorious process of writing tests, or add extra functionality, until the code I'm testing has been checked to not be flawed.</p>
<p>I have two particular concerns with my code which I would like some input on. </p>
<p>First, I have "ATOMIC_REQUESTS" turned on in my settings file. In the <code>form_valid</code> method of the <code>AuctionBid</code> class, below, I generate a message depending on whether the update of the two models - called by the <code>Bid.new_winner()</code> static method - is successful or not. Is this the correct approach ? If it is, I am interested to know how I would rollback all the queries in a view if any error-ed. In my case there are none. But if update queries had been called in the <code>AuctionBid</code> class view prior to one of the queries called by <code>Bid.new_winner()</code> and I wanted to rollback everything how do I achieve this? Looking at the docs I think I am supposed to use nesting transaction blocks like in my case but pass a "savepoint=False" flag to each so that it rollbacks back to the prior parent block. So if I did this for each nested block in my view it would roll all the way back. Is this right? </p>
<p>Second, about the <code>Bid.new_winner</code> static method again. I check if the bidder is the auction creator and if so raise a <code>PermissionDenied</code> exception. Is this best approach? </p>
<p>Any tips or comments would be very welcome.</p>
<p><strong>admin.py</strong></p>
<pre><code>from django.contrib import admin
from .models import Duration, Win, Bid, Auction, Payment
admin.site.register(Duration)
admin.site.register(Win)
admin.site.register(Bid)
admin.site.register(Auction)
admin.site.register(Payment)
</code></pre>
<p><strong>apps.py</strong></p>
<pre><code>from django.apps import AppConfig
class AuctionConfig(AppConfig):
name = 'auction'
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>from django import forms
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
import datetime
from .models import Auction, Bid, Duration
class AuctionBidForm(forms.ModelForm):
class Meta:
model = Bid
fields = ["value"]
labels = {'value': _('Bid')}
def __init__(self, *args, **kwargs):
self.auction = kwargs.pop("auction")
super().__init__(*args, **kwargs)
def clean_value(self):
value = self.cleaned_data["value"]
if self.auction.reserve > value:
raise ValidationError(_('Bid less than the reserve'))
if (self.auction.winning_bid is not None
and self.auction.winning_bid.value >= value):
raise ValidationError(_('Bid not greater than current winning bid'))
return value
class AuctionCreateForm(forms.ModelForm):
class Meta:
model = Auction
fields = ['title', 'reserve']
labels = {'reserve': _('Reserve')}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["duration_value"] = forms.ModelChoiceField(
queryset=Duration.objects.all(),
empty_label=None,
to_field_name="value",
)
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>from django.conf import settings
import uuid
from datetime import datetime, timedelta
import humanfriendly
from django.core.exceptions import PermissionDenied
from django.db import models
from django.db.models import Max, Sum
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.http import Http404
from dateutil.relativedelta import relativedelta
from django.db.models import DateTimeField, F, ExpressionWrapper
import re
def time_x_months_ago(x):
now = timezone.now()
return now - relativedelta(months=x)
class Duration(models.Model):
""" Choice durations for auction """
value = models.DurationField()
class Meta:
ordering = ['value']
def __str__(self):
return humanfriendly.format_timespan(self.value)
class WinQuerySet(models.QuerySet):
""" Personalised queryset to improve
usability """
# To be a perodic task -- when i learn Celery
def find(self):
undeclaredWinners = (
Auction.objects
.select_related("winning_bid")
.select_related("winning_bid__win")
.annotate(
valid_until=ExpressionWrapper(
F('valid_from') + F('duration__value'), output_field=DateTimeField()
)
)
.filter(valid_until__lt=timezone.now())
.exclude(winning_bid=None)
.filter(winning_bid__win=None)
)
if undeclaredWinners:
for auction in undeclaredWinners:
winning_bid = auction.winning_bid
win = self.create(
duration=Duration.objects.get(value=timedelta(seconds=4*60*60)),
bid=winning_bid
)
winning_bid.win = win
winning_bid.save()
def seller(self, **kwargs):
seller = kwargs["seller"]
return (
self.filter(bid__auction__creator=seller)
)
def sales(self):
back_three_months = time_x_months_ago(3)
return (
self.select_related("bid")
.select_related("bid__auction")
.filter(payment__paid_timestamp__gt=back_three_months)
.filter(payment__paid=True)
)
def total(self, **kwargs):
return (
self.aggregate(Sum('bid__value'))
)
def buyer(self, **kwargs):
buyer = kwargs["buyer"]
return (
self.filter(bid__bidder=buyer)
)
def offers(self):
return (
self.annotate(
valid_until=ExpressionWrapper(
F('valid_from') + F('duration__value'), output_field=DateTimeField()
)
)
.filter(valid_until__gt=timezone.now())
.filter(payment=None)
)
# We need lots of foreign properties for the
# __str__ method so this is important to avoid
# a deluge of db hits
def get_queryset(self):
return super().get_queryset().select_related()
class Win(models.Model):
""" Model representing
a win on an auction """
uuid = models.UUIDField(
db_index=True,
default=uuid.uuid4,
editable=False
)
valid_from = models.DateTimeField(auto_now_add=True)
duration = models.ForeignKey(
Duration,
on_delete=models.SET_NULL,
null=True
)
bid = models.ForeignKey(
'Bid',
related_name='win_bid',
on_delete=models.SET_NULL,
null=True,
)
payment = models.ForeignKey(
'Payment',
related_name='win_payment',
on_delete=models.SET_NULL,
null=True,
blank=True,
)
objects = WinQuerySet.as_manager()
def __str__(self):
""" String representing a win """
# In the Model Manager we override get_queryset
# to avoid hitting the db several times in this method
now = timezone.now()
if self.payment:
if self.payment.paid:
# RP = Payment received
return (
f"""RP, val: {self.bid.value}, """
f"""auction: {self.bid.auction.id}"""
)
else:
# PNR = Payment not received
return (
f"""PNR, val: {self.bid.value}, """
f"""auction: {self.bid.auction.id} """
)
else:
# NRP = Never received payment
if self.valid_from + self.duration.value < now:
return (
f"""NRP, val: {self.bid.value}, """
f"""auction: {self.bid.auction.id}"""
)
# AP = Awaiting payment
if self.valid_from + self.duration.value > now:
return (
f"""AP, {self.bid.value}, """
f"""auction: {self.bid.auction.id}"""
)
class BidQuerySet(models.QuerySet):
""" Personalised queryset to improve
usability """
def get_queryset(self):
return super().get_queryset().select_related()
def bidder(self, **kwargs):
bidder = kwargs["bidder"]
return (
self.filter(bidder=bidder)
)
def bids(self):
return (
self.annotate(
valid_until=ExpressionWrapper(
F('auction__valid_from') + F('auction__duration__value'), output_field=DateTimeField()
)
)
.filter(valid_until__gt=timezone.now())
.values('auction', 'auction__uuid', 'auction__title', 'auction__winning_bid__value')
.annotate(last_bid=Max('value'))
)
def total(self):
return (
self.aggregate(Sum('last_bid'))
)
class Bid(models.Model):
""" Model representing
a bid in an auction """
uuid = models.UUIDField(
db_index=True,
default=uuid.uuid4,
editable=False
)
auction = models.ForeignKey(
'Auction',
related_name='bid_auction',
on_delete=models.SET_NULL,
null=True
)
bid_time = models.DateTimeField(auto_now_add=True)
bidder = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='bid_user',
on_delete=models.SET_NULL,
null=True
)
value = models.PositiveIntegerField()
win = models.ForeignKey(
Win,
related_name='bid_win',
on_delete=models.SET_NULL,
null=True,
blank=True,
)
objects = BidQuerySet.as_manager()
def __str__(self):
return f"£{self.value} in Auction No: {self.auction.id}"
def get_absolute_url(self):
""" Returns the url to access
a particular auction """
return reverse_lazy(
'auction:list'
)
@staticmethod
def new_winner(auction, bidder, bid_value):
""" Method to create a new winning bid
on the auction
:param auction: the auction the bid in
:param bidder: the user who made the bid
:param bid_value: the bid value
"""
if not auction.isRunning:
return
if bid_value < auction.reserve:
return
if (auction.winning_bid and
bid_value < auction.winning_bid.value):
return
if bidder.id is auction.creator.id:
raise PermissionDenied
new_winning_bid = Bid.objects.create(
auction=auction,
bidder=bidder,
value=bid_value
)
auction.winning_bid = new_winning_bid
auction.save()
class AuctionQuerySet(models.QuerySet):
""" Personalised queryset to improve
usability """
def get_object_or_404(self, **kwargs):
uuid = kwargs["uuid"]
now = timezone.now()
try:
a = (self.annotate(
valid_until=ExpressionWrapper(
F('valid_from') + F('duration__value'), output_field=DateTimeField()
)
).filter(valid_until__gt=now)
.get(uuid=uuid)
)
except Auction.DoesNotExist:
raise Http404("No live auction found")
return a
class Auction(models.Model):
""" Model for an auction """
uuid = models.UUIDField(
db_index=True,
default=uuid.uuid4,
editable=False,
)
title = models.CharField(max_length=10)
valid_from = models.DateTimeField(auto_now_add=True)
duration = models.ForeignKey(
Duration,
on_delete=models.SET_NULL,
null=True
)
reserve = models.PositiveIntegerField(default=0)
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
)
winning_bid = models.ForeignKey(
'Bid',
related_name='highest_bid',
on_delete=models.SET_NULL,
null=True,
blank=True,
)
objects = AuctionQuerySet.as_manager()
def __str__(self):
return f"Auction: {self.id}"
def get_absolute_url(self):
""" Returns the url to access
a particular auction """
return reverse_lazy(
'auction:detail',
kwargs={'uuid': self.uuid}
)
def isRunning(self):
expiration = self.valid_from + self.duration.value
return timezone.now() < expiration
class Payment(models.Model):
""" Model for a payment
i.e. represents a payment via
Stripe """
win = models.ForeignKey(
Win,
related_name='payment_win',
on_delete=models.SET_NULL,
null=True,
)
valid_from = models.DateTimeField(auto_now_add=True)
duration = models.ForeignKey(
Duration,
on_delete=models.SET_NULL,
null=True
)
paid_timestamp = models.DateTimeField(
null=True,
blank=True
)
paid = models.BooleanField(default=False)
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>from django.urls import path
from . import views
app_name = 'auction'
urlpatterns = [
path('', views.AuctionList.as_view(), name='list'),
path('create/', views.AuctionCreate.as_view(), name='create'),
path('<uuid:uuid>/', views.AuctionBid.as_view(), name='detail'),
path('dashboard/', views.dashboard, name="dashboard"),
path('sales/', views.Sales.as_view(), name='sales-list'),
path('purchases/', views.Purchases.as_view(), name='purchases-list'),
path('offers/', views.Offers.as_view(), name='offers-list'),
path('bids/', views.Bids.as_view(), name='bids-list'),
path('offers/<uuid:uuid>/', views.Buy.as_view(), name="buy"),
]
</code></pre>
<p><strong>utils.py</strong></p>
<pre><code>from django.utils import timezone
from datetime import datetime, timedelta
import re
def days_hours_minutes_seconds(td):
s = (td.seconds % 3600) // 60, (td.seconds % 3600) % 60
st = days_hours_minutes(td)
st += " s "
st = re.sub("^((00 [dhms] )|(0 [dhms] ))+","", st)
return st
def days_hours_minutes(td):
d, h = td.days, td.seconds //3600
m = (td.seconds % 3600) // 60
st = ""
st += str(d) + " d "
st += str(h) + " h "
st += str(m) + " m "
st = re.sub("^((00 [dhm] )|(0 [dhm] ))+","", st)
return st
def calculate_time_remaining(expiration):
remaining = expiration - timezone.now()
remaining -= timedelta(microseconds=remaining.microseconds) # cut off microseconds
remaining = days_hours_minutes(remaining)
return remaining
</code></pre>
<p>utils.py</p>
<pre><code>from django.core.exceptions import PermissionDenied
from django.views import generic, View
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic.detail import DetailView
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.shortcuts import render, get_object_or_404
from datetime import datetime, timedelta
from django.utils.dateparse import parse_duration
from django.utils import timezone
from django.db import Error, IntegrityError, transaction
from django.db.models import DateTimeField, F, ExpressionWrapper
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.forms.utils import ErrorList
from django.urls import reverse
from .utils import calculate_time_remaining
from .models import Auction, Bid, Duration, Win, Payment
from .forms import AuctionBidForm, AuctionCreateForm
class Buy(LoginRequiredMixin, UpdateView):
""" View for making a payment for
a win on an auction """
model = Win
template_name = "auction/buy.html"
context_object_name = "offer"
fields = [] # keep django happy
success_url = "/auction/offers"
def get_object(self):
buyer = self.request.user
uuid = self.kwargs.get("uuid")
try:
offer = Win.objects.buyer(buyer=buyer).offers().get(uuid=uuid)
offer.remaining = calculate_time_remaining(offer.valid_until)
except self.model.DoesNotExist:
raise Http404("No such offer exists") # Will need our own 404.html template i think
return offer
def form_valid(self, form):
win = self.object
try:
with transaction.atomic():
duration = Duration.objects.get(value=timedelta(seconds=4*60*60))
payment = Payment.objects.create(
win=win,
duration=duration,
paid_timestamp=timezone.now(),
paid=True
)
win.payment = payment
win.save()
except IntegrityError:
# return a failure message to the user
return Http404("Something went wrong")
# db updates were successful
# send back a success message to the user
return super().form_valid(form)
class Sales(LoginRequiredMixin, ListView):
""" List of users' sales
over 3 month period """
model = Win
paginate_by = 10
context_object_name = "sales_list"
template_name = "auction/sales_list.html"
def get_queryset(self):
user = self.request.user
queryset = (
Win.objects.seller(seller=user)
.sales()
)
q = self.request.GET.get("q")
if q:
return queryset.filter(bid__auction__title__icontains=q)
return queryset
class Purchases(LoginRequiredMixin, ListView):
""" List of users' purchases
over 3 month period """
model = Win
paginate_by = 10
context_object_name = "purchases_list"
template_name = "auction/purchases_list.html"
def get_queryset(self):
user = self.request.user
queryset = (
Win.objects.buyer(buyer=user)
.sales()
)
q = self.request.GET.get("q")
if q:
return queryset.filter(bid__auction__title__icontains=q)
return queryset
class Offers(LoginRequiredMixin, ListView):
""" List of offers """
model = Win
paginate_by = 10
template_name = "auction/offers_list.html"
context_object_name = "offers_list"
def get_context_data(self, **kwargs):
""" Add the time remaining to the
model object """
cxt = super().get_context_data()
offerList = cxt['object_list']
for offer in offerList:
expiration = offer.valid_until # added to the object on the queryset
offer.remaining = calculate_time_remaining(expiration)
return cxt
def get_queryset(self):
user = self.request.user
queryset = (
Win.objects.buyer(buyer=user)
.offers()
)
q = self.request.GET.get("q")
if q:
return queryset.filter(bid__auction__title__icontains=q)
return queryset
class Bids(LoginRequiredMixin, ListView):
""" List of bids """
model = Bid
paginate_by = 10
template_name = "auction/bids_list.html"
def get_queryset(self):
user = self.request.user
return Bid.objects.bidder(bidder=user).bids()
class AuctionList(ListView):
""" List of Live Auctions """
model = Auction
paginate_by = 10
def get_context_data(self, **kwargs):
""" Add the time remaining to the
model object """
cxt = super().get_context_data()
auctionList = cxt['object_list']
for auction in auctionList:
expiration = auction.valid_until # added to the object on the queryset
auction.remaining = calculate_time_remaining(expiration)
return cxt
def get_queryset(self):
""" Live Auctions only """
now = timezone.now()
queryset = (
Auction.objects
.select_related('winning_bid')
.select_related('duration')
.annotate(
valid_until=ExpressionWrapper(
F('valid_from') + F('duration__value'), output_field=DateTimeField()
)
)
.filter(valid_until__gt=now)
)
# Get the q GET parameter -- pg 140 of Two Scoops
q = self.request.GET.get("q")
if q:
return queryset.filter(title__icontains=q)
return queryset
class AuctionCreate(LoginRequiredMixin, CreateView):
""" View function for creating an auction """
form_class = AuctionCreateForm
template_name = "auction/auction_form.html"
success_url = "/auction/"
def post(self, request, *args, **kwargs):
request.POST = request.POST.copy() # beause request.POST is immutable first off
duration_value = request.POST["duration_value"]
duration_value = parse_duration(duration_value)
request.POST["duration_value"] = duration_value
return super().post(request, *args, **kwargs)
def form_valid(self, form):
form.instance.start = timezone.now()
duration_value = form.cleaned_data.get('duration_value')
form.instance.duration = duration_value
form.instance.creator = self.request.user
return super().form_valid(form)
class AuctionBid(LoginRequiredMixin, CreateView):
model = Bid
form_class = AuctionBidForm
template_name = "auction/auction_detail.html"
def get_context_data(self, **kwargs):
user = self.request.user
c = super().get_context_data(**kwargs)
c["auction"] = self.auction
if user.id is self.auction.creator.id:
c["form"] = None
return c
def get_form_kwargs(self):
fkwargs = super().get_form_kwargs()
uuid = self.kwargs.get("uuid")
auction = Auction.objects.get_object_or_404(uuid=uuid)
auction.remaining = calculate_time_remaining(
auction.valid_from + auction.duration.value
)
fkwargs["auction"] = auction
self.auction = auction
return fkwargs
def form_invalid(self, form):
return super().form_invalid(form)
def form_valid(self, form):
bid_value = form.cleaned_data["value"]
try:
with transaction.atomic():
Bid.new_winner(
self.auction,
self.request.user,
bid_value
)
except IntegrityError:
messages.error(self.request, "An unexpected error occured so your bid did not submit")
messages.success(self.request, "Bid submitted successfully!")
return super().form_valid(form)
@login_required
def dashboard(request):
# this should be a periodic task but until
# i learn about Celery this will have to do
user = request.user
Win.objects.find()
context = {}
sales = Win.objects.seller(seller=user).sales().total()
context["sales"] = sales
purchases = Win.objects.buyer(buyer=user).sales().total()
context["purchases"] = purchases
offers = Win.objects.buyer(buyer=user).offers().total()
context["offers"] = offers
bids = Bid.objects.bidder(bidder=user).bids().total()
context["bids"] = bids
return render(
request,
'auction/dashboard.html',
context
)
</code></pre>
<hr>
<p><sup>1</sup> What I've read so far: I've been using the excellent resource <a href="https://www.fullstackpython.com/" rel="nofollow noreferrer">https://www.fullstackpython.com/</a> as a roadmap. This led me to complete the official tutorial first, the book "Django for beginners" second, the MDN tutorial third, and a lot of the book "Two Scoops of Django" finally.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:01:11.147",
"Id": "425360",
"Score": "0",
"body": "Welcome to Code Review! I edited your question title so that it is more descriptive of what your are actually trying to accomplish. You can read more about this at [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T13:18:16.503",
"Id": "220136",
"Score": "3",
"Tags": [
"python",
"beginner",
"django"
],
"Title": "Simple auction application in Django"
} | 220136 |
<p>I'm making a robot with Raspberry. My goal is:</p>
<ol>
<li>Code a server on Rasbperry using Python that captures the image from camera and sends data via socket</li>
<li>Code a client on PC using Java that reads data from socket and show it in a JavaSwing window</li>
</ol>
<p>So I can see in real time what the Raspberry Camera see.</p>
<p>I tried this code for my project and I get the same latency.
My python code is:</p>
<pre><code>import socket
from time import sleep
import picamera
ADDRESS = '192.168.1.XXX' # My Address - SERVER
PORT = 2000 # Port to listen on (non-privileged ports are > 1023)
server = socket.socket()
server.bind((ADDRESS, PORT))
server.listen(0)
connection, addr = server.accept() # Accept one connection
params = (1280, 720, 48, 25000000)
client = connection.makefile('wb')
print('Connected to', addr)
camera = picamera.PiCamera()
camera.rotation = 180
camera.resolution = ( int(params[0]), int(params[1]) )
camera.framerate = int(params[2]) #48
try:
camera.start_recording(client, format='h264', intra_period=0, quality=0,
bitrate=int(params[3]) )
print("Recording started...")
camera.wait_recording(60)
finally:
camera.stop_recording()
print("Recording stopped...")
client.close()
server.close()
camera.stop_preview()
print("Connection closed")
</code></pre>
<p>My Java code is the next:</p>
<pre><code>private final int WIDTH = 1280, HEIGHT = 720;
private final int FPS = 48;
private final int BITRATE = 25000000;
public InputStream connect(String address, int port) throws IOException {
socket = new Socket( InetAddress.getByName(address), port )
return socket.getInputStream();
}
public void openWindow(VideoPane video) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) { ex.printStackTrace(); }
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(video);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setPreferredSize( new Dimension(WIDTH, HEIGHT) );
frame.setVisible(true);
}
});
}
public void avvia() throws IOException {
VideoPane video = new VideoPane(WIDTH, HEIGHT);
openWindow(video);
InputStream in = connect(serverAddress, serverPort);
streamToImageView( "h264", FPS, BITRATE*2, "ultrafast", 0, in, video);
try {
socket.close();
} catch (IOException e) {e.printStackTrace(); }
}
public void streamToImageView( final String format, final double frameRate, final int bitrate,
final String preset, final int numBuffers, InputStream input, VideoPane video) {
try{
final FrameGrabber grabber = new FFmpegFrameGrabber( input );
final Java2DFrameConverter converter = new Java2DFrameConverter();
grabber.setFrameRate(frameRate);
grabber.setFormat(format);
grabber.setVideoBitrate(bitrate);
grabber.setVideoOption("preset", preset);
grabber.setNumBuffers(numBuffers);
grabber.setMaxDelay(10);
grabber.start();
Frame frame;
BufferedImage bufferedImage;
while (!stop) {
frame = grabber.grab();
if (frame != null) {
bufferedImage = converter.convert(frame);
if (bufferedImage != null) {
video.updateFrame(bufferedImage);
}
}//if frame
}//while
grabber.close();
}//try
catch (IOException e) { e.printStackTrace(); }
}//streamToImageView
public class VideoPane extends JPanel {
private BufferedImage currentFrame;
public VideoPane(int width, int height) {
this.setPreferredSize( new Dimension(width, height) );
Timer timer = new Timer(FPS, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
public void updateFrame(BufferedImage frame) {
this.currentFrame = frame;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (currentFrame != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - currentFrame.getWidth()) / 2;
int y = (getHeight() - currentFrame.getHeight()) / 2;
g2d.drawImage(currentFrame, x, y, this);
g2d.dispose();
}
}//paintComponent
}//VideoPane
</code></pre>
<p>I notice that the RPiCamera library code the stream video to h264 before sending to socket. I think that latency maybe is due to this computational overhead.
I'd like to try another conversion format but I'm unable to decode the stream when received.
I also tried to use UDP protocol but FFmpegFrameGrabber needs a InputStream and the UDP can only provide the ByteStream ofreceived packet.
The other possible problem maybe a connection delay, so I tryed to connect raspberry with Ethernet. This video show the latency when raspberry is connected via Ethernet to router and PC via Wireless:
<a href="https://drive.google.com/drive/folders/1gTHuADfncll_rlY0a5zC0ikxEax00_JG?usp=sharing" rel="nofollow noreferrer">LatencyVideo</a></p>
<p>Have you some ideas for reducing this latency?
Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T15:24:09.913",
"Id": "425355",
"Score": "1",
"body": "Related: https://codereview.stackexchange.com/q/163042/31562"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T14:35:30.753",
"Id": "220137",
"Score": "2",
"Tags": [
"python",
"java",
"raspberry-pi"
],
"Title": "Streaming video from PiCamera to Windows using Java and Python"
} | 220137 |
<p>The below code is aimed at providing you the most amount of control and flexibility with control which value gets set to a property.</p>
<p>I Introduce to you, the <code>ConstrainedSetter<T></code> Generic Class.
This class Takes a input type, creates a private field to represent that type, and provides a framework for controlling how that field is set, It also provides a method for logging failures, changing what the error messages say, optionally taking action on success or failure, optionally modifying the input, optionally validating the input to see if meets the criteria setup, and finally with no <code>ModifyAction</code> Function and <code>PreCheck</code> Predicate setup it acts as a normal setter. </p>
<pre><code>[Serializable]
public class ConstrainedSetter<T> : IConstrainedSetter<T>
{
public int HashId = default;
public ConstrainedSetter()
{
}
#region logging
public ILogger Logger { get; set; }
public Action FailAction { get; set; } = default;
public string pcnmLogFail { get; set; }
public string pcmLogFail { get; set; }
#endregion
#region ControlFlow
public Predicate<T> CheckBeforeSet { get; set; } = default;
public Func<T,T> ModifyBeforeSet { get; set; } = default;
public Action SuccessAfterSet { get; set; } = default;
#endregion
private T data = default;
public T Data { get => data; set => data = Set(value); }
public virtual T ModifyInput(T value)
{
return ModifyBeforeSet(value);
}
public virtual void Log(string Message)
{
Logger.Log(Message);
}
private T Set(T _value)
{
if (ModifyBeforeSet == default)
{
if (CheckBeforeSet != default)
{
if (CheckBeforeSet(_value) == true)
{
if (SuccessAfterSet != default)
{
SuccessAfterSet();
}
return _value;
}
if (Logger != default)
{
Log(pcnmLogFail);
}
if (FailAction != default)
{
FailAction();
}
return default;
}
return _value;
}
else
{
T Local = ModifyInput(_value);
if (CheckBeforeSet != default)
{
if (CheckBeforeSet(Local) == true)
{
if (SuccessAfterSet != default)
{
SuccessAfterSet();
}
return Local;
}
if (Logger != default)
{
Log(pcmLogFail);
}
if (FailAction != default)
{
FailAction();
}
return default;
}
return _value;
}
}
}
public static class ConstrainedSetterExtensions
{
public static ConstrainedSetter<T> Setup<T>(this ConstrainedSetter<T> set,Action _logFailAction = default, string _preCheckNoModify = default, string _preCheckModify = default)
{
set.FailAction = _logFailAction;
set.pcnmLogFail = _preCheckNoModify;
set.pcmLogFail = _preCheckModify;
return set;
}
public static ConstrainedSetter<T> Setup<T>(this ConstrainedSetter<T> set, Func<T,T> _modifyAction = default, Predicate<T> _preCheck = default, Action _successAction = default)
{
set.ModifyBeforeSet = _modifyAction;
set.CheckBeforeSet = _preCheck;
set.SuccessAfterSet = _successAction;
set.HashId = HashCode.Combine(set.Data, set.SuccessAfterSet, set.CheckBeforeSet, set.ModifyBeforeSet);
return set;
}
public static ConstrainedSetter<T> Clone<T>(this ConstrainedSetter<T> ObjSource )
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, ObjSource);
ms.Position = 0;
return (ConstrainedSetter<T>)formatter.Deserialize(ms);
}
}
public static ConstrainedSetter<T> CreateNewType<T>(this ConstrainedSetter<T> Source)
{
return new ConstrainedSetter<T>();
}
}
</code></pre>
<p>So rather then explaining it further, I will show my current test for it.</p>
<p>This test demonstrates the creation of a Int where I add every option to the setter for the Data Property.</p>
<p>The define Failure callback and the success callback. Both do nothing in this implementation, but they can do whatever you want them to do. I then Create the type I want, add my logging service to it, and call setup to add the failure callback and the failures strings. The next setup call, adds the modify action, the precheck predicate and the SuccessCallback.</p>
<pre><code> public ConstrainedSetterTests()
{
void FailureCallBack()
{
}
void SuccessCallBack()
{
}
ConstrainedSetter<int> programmable = new ConstrainedSetter<int>();
programmable.Logger = new Logger();
programmable.Setup(FailureCallBack, "Prechecker routine failed", "Precheck after modification failed")
.Setup(_modifyAction: x => { return x = x + 1; }, x => x == 100, SuccessCallBack);
programmable.Data = 98;
}
</code></pre>
<p>The result of this test is that the data is set to 0 and the log for <code>pcmLogFail</code> is received by the logger and failure callback is run.</p>
<p>Any thoughts on improvements or anything really helps. What can I do to improve my post, and what can I do to make it more generic?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T05:36:56.260",
"Id": "425382",
"Score": "1",
"body": "What's the definition of the IConstrainedSetter interface ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:11:23.693",
"Id": "425523",
"Score": "0",
"body": "Sorry about this adrian, but for this version there way no interface definition, in Other words IConstrainedSetter<T> was blank."
}
] | [
{
"body": "<p>This might actually be useful in some cases, however, we first need to get rid of its weaknesses and clean-up the code a little bit:</p>\n\n<ul>\n<li>Every property of <code>ConstrainedSetter</code> is mutable, so it can be modified by anyone, anytime. This is not good because it allows me to override your settings whenever I desire. This should definitely be immutable.</li>\n<li>Both the <code>FailureCallBack</code> and <code>SuccessCallBack</code> should pass the instance of the <code>ConstrainedSetter</code> as a parameter so that one has the necessary context about what went wrong or what succeeded. The former should also pass the reason it didn't work.</li>\n<li><code>ILogger</code> should not be part of this class. There are already two callbacks to handle failures and successes. Let the user handle this. Adding a logger makes it redundant.</li>\n<li>Your naming convention here is exactly the other way around. Names prefixed with an <code>_</code> underscore are usually private fields and not public parameters. Similar, lowercase properties should not be public and abbreviating them to a magic <code>pc[n]m</code> is a no-go.</li>\n<li>I cannot figure out what the <code>HashId</code> is for. You should document it better.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T11:04:56.577",
"Id": "425406",
"Score": "0",
"body": "Thank you for the guidance, I really hope this does become useful., I was thinking about this mutability issue today actually,,.if I do set a private read only field or property to bring about immutability, then the class would need more internal functions as input parameter handlers, or more parameters in the constructor, if I don't want more functions. is there another way to approach this that doesn't lead to this scenario?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T11:07:34.543",
"Id": "425408",
"Score": "0",
"body": "@BanMe you could create a mutable builder and once an instance is created from it then _forever_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T12:41:50.297",
"Id": "425504",
"Score": "0",
"body": "hello, small query.. Do I just continually repost the code after making modifications?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T13:01:16.790",
"Id": "425508",
"Score": "0",
"body": "@BanMe you can ask a new question when you have something new to review or a self-answer if you just want to share the latest version. The question's code must remain unchanged after reviews are posted."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T07:17:18.063",
"Id": "220170",
"ParentId": "220138",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220170",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T15:04:00.250",
"Id": "220138",
"Score": "4",
"Tags": [
"c#",
"validation",
"callback",
"properties",
"fluent-interface"
],
"Title": "Constraining a property setter fluently"
} | 220138 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/find-common-characters/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given an array A of strings made only from lowercase letters, return a
list of all characters that show up in all strings within the list
(including duplicates). For example, if a character occurs 3 times in
all strings but not 4 times, you need to include that character three
times in the final answer.</p>
<p>You may return the answer in any order.</p>
<p><strong>Example 1:</strong></p>
<p>Input: ["bella","label","roller"]</p>
<p>Output: ["e","l","l"]</p>
<p><strong>Example 2:</strong></p>
<p>Input: ["cool","lock","cook"]</p>
<p>Output: ["c","o"] </p>
<p><strong>Note:</strong></p>
<p>1 <= A.length <= 100</p>
<p>1 <= A[i].length <= 100</p>
<p>A[i][j] is a lowercase letter</p>
</blockquote>
<p>My imperative solution:</p>
<pre><code>function commonChars(A) {
const [first, ...rest] = A.sort((a,b) => -(a.length - b.length));
const duplicates = [];
[...first].forEach(e => {
let isDuplicate = true;
for (let x = 0, len = rest.length; x < len; x++) {
let letters = rest[x];
const i = letters.search(e);
if (i !== -1) {
letters = letters.slice(0, i) + letters.slice(i + 1);
rest[x] = letters;
} else {
isDuplicate = false;
}
}
if (isDuplicate) {
duplicates.push(e);
}
});
return duplicates;
}
const arr = ["cool","lock","cook"];
console.log(commonChars(arr));
</code></pre>
<p><strong>My declarative solution</strong></p>
<pre><code>const commonChars2 = A => {
const [first, ...rest] = A.sort((a,b) => b.length - a.length));
return [...first].reduce((duplicates, e) => {
let isDuplicate = true;
for (let x = 0, len = rest.length; x < len; x++) {
const letters = rest[x];
const i = letters.search(e);
if (i !== -1) {
rest[x] = letters.slice(0, i) + letters.slice(i + 1);
} else {
isDuplicate = false;
}
}
if (isDuplicate) { duplicates.push(e); }
return duplicates;
}, []);
};
const arr = ["cool","lock","cook"];
console.log(commonChars2(arr));
</code></pre>
<p>Is there also a good functional approach?</p>
| [] | [
{
"body": "<h2>Opportunities missed</h2>\n\n<p>You have essentially the same algorithm in both examples. When I first looked at the solutions the sort at the start was a worry. The logic is sound, to work from the smallest word as there will be no more characters to test then is contained in that word.</p>\n\n<p>However you have the sort AoT and the result is you set <code>first</code> to be the longest word in the array.</p>\n\n<p>Changing the sort to be the other direction works great improving the performance near 3-4 times if there is a much shorter word in the array. However there is no real benefit with the sort if all the words are of similar length.</p>\n\n<p>Another missed optimization is breaking out of the inner loop when you set <code>isDuplicates</code> to false. Adding a break saves having to do any further iteration and gives another 10% performance. BTW the name <code>duplicates</code> would have just as much meaning.</p>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search\" rel=\"nofollow noreferrer\">String.search(arg)</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf\" rel=\"nofollow noreferrer\"><code>String.indexOf(arg)</code></a></h2>\n\n<p>The real bottle neck is in the inner loop where you locate the current character <code>e</code> in the current word. <code>letters.search(e)</code></p>\n\n<p>It may look innocent but this is where knowing the language well come into play. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search\" rel=\"nofollow noreferrer\">String.search(arg)</a> takes as the first argument a <code>regExp</code> but also works with just a string. The catch is that the string is first converted to a <code>regExp</code> before the search starts. This is a huge overhead.</p>\n\n<p>If you use <code>String.indexOf</code> instead your code is almost twice as fast. I tried to write something that could beat it using Maps to reduce time complexity, and as such only starts to outperform when the word lengths get much longer 50+ characters.</p>\n\n<h2>Rewrite</h2>\n\n<p>So for small words your solution with slight modification is very fast.</p>\n\n<ul>\n<li>Sort now from smallest to largest,\nBreaks from inner loop when no duplicates found.</li>\n<li>Uses faster <code>String.indexOf</code> to do inner character search.</li>\n</ul>\n\n<p>And some name changes..</p>\n\n<pre><code>function commonCharsNo(words) {\n const [first, ...rest] = words.sort((a, b) => (a.length - b.length));\n const duplicates = [];\n [...first].forEach(e => {\n let duplicate = true;\n for (let x = 0, len = rest.length; x < len; x++) {\n let word = rest[x];\n const i = word.indexOf(e);\n if (i !== -1) {\n rest[x] = word.slice(0, i) + word.slice(i + 1);\n } else {\n duplicate = false;\n break;\n }\n }\n if (duplicate) {\n duplicates.push(e);\n }\n });\n return duplicates;\n}\n</code></pre>\n\n<h2>Reduce complexity</h2>\n\n<p>The <code>search</code> (now <code>indexOf</code>) is where the code gets poor complexity <span class=\"math-container\">\\$O(m)\\$</span>. Its <span class=\"math-container\">\\$O(n.m)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the number of characters in the smallest word and <span class=\"math-container\">\\$m\\$</span> is the mean number of characters per word.</p>\n\n<p>You can reduce this to approx <span class=\"math-container\">\\$O(w.m)\\$</span> where <span class=\"math-container\">\\$w\\$</span> is the number of words and <span class=\"math-container\">\\$m\\$</span> is the mean number of characters per word.</p>\n\n<p>The improvement is small and only pays out for longer words.</p>\n\n<pre><code>function findCommonChars(words) {\n var chars;\n const result = [];\n words = [...words.sort((a,b)=>b.length - a.length)];\n const countChars = (word, res = new Map()) => {\n for (const char of word) {\n res.has(char) && (!chars || chars.has(char)) ? \n res.get(char)[0]++ : res.set(char, [1]);\n }\n return res;\n }\n chars = countChars(words.pop());\n const charCounts = words.map(word => countChars(word));\n for (let [char, count] of chars.entries()) {\n for (const word of charCounts) {\n if (word.has(char)) { count = Math.min(count, word.get(char)[0]) }\n else {\n count = 0;\n break;\n }\n }\n while (count--) { result.push(char) }\n } \n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:25:25.200",
"Id": "425434",
"Score": "0",
"body": "Why sort the words at all? Why not just pick any of shortest as the pivot?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T22:40:13.860",
"Id": "425467",
"Score": "0",
"body": "@janos It reduces storage complexity and when there is a short word in the set, improves performance by a significant amount, as the pivot removes the overhead of mapping character not needed. If performance were critical then it would have to test at start hte best method to use, the OP's, the one I gave, and another variant more suited to high word counts"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T04:23:51.593",
"Id": "220166",
"ParentId": "220142",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:31:49.863",
"Id": "220142",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Find common characters (LeetCode)"
} | 220142 |
<p>I've recently come across <code>SQLAlchemy</code>, and as I had just been attempting to code something very similar to it, I think it's amazing. I've started on a new website, and I've just been working on some models to deal with users, which includes various bits such as remembering logins and resetting passwords.</p>
<p>Since I'm completely new to this, I'd appreciate if someone could take a glance and see if I'm using any bad practices that should not be done, or if any bits could be improved/made more efficient. I'd prefer to get it right from the start, instead of a year or two down the line when its too late to make any changes.</p>
<p>As to the layout of the models, I tried to group the physical columns together (so the order of the columns is correct if you need to open the database with something else), then set up a generic order that each model should follow to make things easier to deal with at a glance:</p>
<ol>
<li>Columns (physical columns to edit)</li>
<li>Automatic (physical columns that are automatically edited by events)</li>
<li>Relationships</li>
<li>Other (things like hybrid_methods that act like columns)</li>
<li>Validators</li>
<li>Overrides (<code>__init__</code>, <code>__repr__</code>, etc)</li>
<li>Additional (methods that add functionality)</li>
</ol>
<p>So a few things to note, retreiving the persistent login is actually done via a <code>classmethod</code>, where it'll search the database if you have a session open, and delete all sessions if the identifier check fails. I relied on the <code>validates</code> decorator to override setting values, doing things such as hashing the password. I also didn't use <code>backref</code> in relationships as it seems like it's better practice to give yourself more control over it.</p>
<pre><code>import bcrypt
import time
import uuid
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import exc, validates
__all__ = ['db', 'User', 'Email', 'Activation', 'LoginAttempts', 'PasswordReset', 'PersistentLogin']
db = SQLAlchemy()
def unix_timestamp():
return int(time.time())
def generate_uuid():
return uuid.uuid4().hex
def password_hash(password, rounds=12):
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=rounds))
def quick_hash(x=None):
if x is None:
x = uuid.uuid4().hex
return hashlib.sha256(str(x)).hexdigest()
class User(db.Model):
"""User accounts."""
# Columns
row_id = db.Column(db.Integer, primary_key=True)
email_id = db.Column(db.Integer, db.ForeignKey('email.row_id'), nullable=False)
username = db.Column(db.String(80), unique=True, nullable=True)
password = db.Column(db.CHAR(60), nullable=False)
activated = db.Column(db.Boolean, default=0)
permissions = db.Column(db.SmallInteger, default=0)
# Automatic
password_edited = db.Column(db.Integer, nullable=False)
created = db.Column(db.Integer, nullable=False)
updated = db.Column(db.Integer, nullable=False)
# Relationships
email = db.relationship('Email')
activation_codes = db.relationship('Activation', lazy=True)
password_resets = db.relationship('PasswordReset', lazy=True)
persistent_logins = db.relationship('PersistentLogin', lazy=True)
# Other
@hybrid_property
def identifier(self):
"""Generate an identifier unique to the email and password."""
return quick_hash(self.password + self.email.address)
# Validation
@validates('email')
def validate_email(self, key, email):
if not isinstance(email, Email):
email = Email(email)
return email
@validates('password')
def validate_password(self, key, password):
return password_hash(password)
# Overrides
def __init__(self, email, password, username=None):
super(User, self).__init__(email=email, password=password, username=username)
def __repr__(self):
return '<{} "{} ({})">'.format(self.__class__.__name__, self.username, self.email.address)
@db.event.listens_for(User, 'before_insert')
def user_insert(mapper, connection, target):
target.created = unix_timestamp()
target.updated = unix_timestamp()
target.password_edited = unix_timestamp()
@db.event.listens_for(User, 'before_update')
def user_update(mapper, connection, target):
target.updated = int(time.time())
@db.event.listens_for(User.password, 'set')
def user_password_update(target, value, oldvalue, initiator):
"""Update password edited time"""
if value != oldvalue:
target.password_edited = unix_timestamp()
class Email(db.Model):
"""Email addresses.
More than one account can have the same email, but the intention is that it will have the
permission of UserPermissions.Deleted.
"""
# Columns
row_id = db.Column(db.Integer, primary_key=True)
address = db.Column(db.String(128), unique=True, nullable=False)
# Automatic
created = db.Column(db.Integer, nullable=False)
updated = db.Column(db.Integer, nullable=False)
# Relationships
users = db.relationship('User', lazy=True)
login_attempts = db.relationship('LoginAttempts', lazy=True)
# Validators
@validates('address')
def validate_address(self, key, address):
assert '@' in address
return address
# Overrides
def __init__(self, address):
super(Email, self).__init__(address=address)
def __repr__(self):
return '<{} "{}">'.format(self.__class__.__name__, self.address)
@db.event.listens_for(Email, 'before_insert')
def email_insert(mapper, connection, target):
target.created = unix_timestamp()
target.updated = unix_timestamp()
@db.event.listens_for(Email, 'before_update')
def email_update(mapper, connection, target):
target.updated = unix_timestamp()
class Activation(db.Model):
"""Activate user accounts.
The (unhashed) code will be sent to the user via email, and visiting the URL within the
allocated time will activate their account.
If a new activation code is sent, then delete this record.
"""
# Columns
row_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.row_id'), nullable=False)
code = db.Column(db.CHAR(64), nullable=False, unique=True)
# Automatic
created = db.Column(db.Integer, nullable=False)
# Relationships
user = db.relationship('User')
# Validators
@validates('user')
def validate_email(self, key, user):
if not isinstance(user, User):
user = User(user)
return user
@validates('code')
def validate_code(self, key, code):
return quick_hash(code)
# Overrides
def __init__(self, user, token):
super(PasswordReset, self).__init__(user=user, code=code)
def __repr__(self):
return '<{} "{}">'.format(self.__class__.__name__, self.user.email.address)
@db.event.listens_for(Activation, 'before_insert')
def activation_insert(mapper, connection, target):
target.created = unix_timestamp()
class LoginAttempts(db.Model):
"""Keep track of failed login attempts."""
# Columns
row_id = db.Column(db.Integer, primary_key=True)
email_id = db.Column(db.Integer, db.ForeignKey('email.row_id'), nullable=False)
success = db.Column(db.Boolean, default=0)
# Automatic
created = db.Column(db.Integer, nullable=False)
# Relationships
email = db.relationship('Email')
# Validators
@validates('email')
def validate_email(self, key, email):
if not isinstance(email, Email):
email = Email(email)
return email
# Overrides
def __init__(self, email, success):
super(PasswordReset, self).__init__(email=email, success=success)
def __repr__(self):
return '<{} "{}">'.format(self.__class__.__name__, self.user.email.address)
@db.event.listens_for(LoginAttempts, 'before_insert')
def login_attempt_insert(mapper, connection, target):
target.created = unix_timestamp()
class PasswordReset(db.Model):
"""Reset user account password.
Make sure to delete this record as soon as its used.
"""
# Columns
row_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.row_id'), nullable=False)
code = db.Column(db.CHAR(64), nullable=False, unique=True)
# Automatic
created = db.Column(db.Integer, nullable=False)
# Relationships
user = db.relationship('User')
# Validators
@validates('user')
def validate_email(self, key, user):
if not isinstance(user, User):
user = User(user)
return user
@validates('code')
def validate_code(self, key, code):
return quick_hash(code)
# Overrides
def __init__(self, user, token):
super(PasswordReset, self).__init__(user=user, code=code)
def __repr__(self):
return '<{} "{}">'.format(self.__class__.__name__, self.user.email.address)
@db.event.listens_for(PasswordReset, 'before_insert')
def password_reset_insert(mapper, connection, target):
target.created = unix_timestamp()
class PersistentLogin(db.Model):
"""Save logins between sessions.
Information read from https://stackoverflow.com/a/244907/2403000.
Identifier:
The same between all login sessions.
1-64 = random hash, 65-128 = email hash
When comparing the identifier, only force all the sessions to end if the email is correct.
Otherwise someone could log everyone out by using the wrong session.
Token:
Unique for each session.
This is just a basic check of whether it exists or not.
If a match, generate a fresh token and overwrite.
"""
# Columns
row_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.row_id'), nullable=False)
identifier = db.Column(db.CHAR(128), unique=True)
token = db.Column(db.CHAR(64), unique=True)
# Automatic
created = db.Column(db.Integer, nullable=False)
updated = db.Column(db.Integer, nullable=False)
# Relationships
user = db.relationship('User')
# Validators
@validates('user')
def validate_email(self, key, user):
if not isinstance(user, User):
user = User(user)
return user
@validates('token')
def validate_token(self, key, token):
return quick_hash(token)
# Overrides
def __init__(self, user, token):
super(PersistentLogin, self).__init__(user=user, token=token)
self.identifier = quick_hash() + user.identifier
def __repr__(self):
return '<{} "{}">'.format(self.__class__.__name__, self.user.email.address)
# Extra
@classmethod
def get_session(cls, user, token, identifier):
"""Use the token and identifier to get the current session.
Returns the session model and the new token.
"""
# Find record with matching token
token = quick_hash(token)
try:
session = PersistentLogin.query.filter(PersistentLogin.token==token).one()
except exc.NoResultFound:
return None
# Find if identifier is valid
if session.identifier != identifier:
if session.identifier[64:128] == session.user.identifier:
all_sessions = PersistentLogin.query.filter(PersistentLogin.user.identifier==session.identifier)
all_sessions.delete()
db.session.commit()
return None
# Check the user identifier in case email/password has been changed
elif session.identifier[64:128] != session.user.identifier:
return None
# Return the session with a new token
return (session, session.regenerate_token())
def regenerate_token(self):
"""Generate and set a new token."""
token = generate_uuid()
self.token = token
return token
@db.event.listens_for(PersistentLogin, 'before_insert')
def persistent_login_insert(mapper, connection, target):
target.created = unix_timestamp()
target.updated = unix_timestamp()
@db.event.listens_for(PersistentLogin, 'before_update')
def persistent_login_update(mapper, connection, target):
target.updated = int(time.time())
</code></pre>
<p>Here's my messy testing file, mainly to see if the persistent logins work</p>
<pre><code>import os
import sys
from flask import Flask
# Import everything from the above file
app = Flask(__name__)
app.secret_key = 123
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialise the database and set the context (https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts)
db.init_app(app)
app.app_context().push()
db.create_all()
# Insert test user
admin = User(username='admin', email='admin@example.com', password='test')
db.session.add(admin)
db.session.commit()
# Setup persistent login for admin
token_gen = '35269gjgr942jg'
p = PersistentLogin(user=admin, token=token_gen)
db.session.add(p)
db.session.commit()
# Read persistent login for admin
session, new_token = PersistentLogin.get_session(admin, token_gen, p.identifier)
# If password or email changes, then the persistent login should return None
admin.email = 'new@admin.com'
print PersistentLogin.get_session(admin, new_token, p.identifier)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:44:22.430",
"Id": "220143",
"Score": "1",
"Tags": [
"python",
"sqlalchemy"
],
"Title": "Setting up user models with Flask-SQLAlchemy"
} | 220143 |
<p>I have a private class that I want to be able to find the shortest Hamming Distance between two Strings of equal length in Java. The private class holds a <code>char[]</code> and contains a method to compare against other char arrays. It returns true if there is only a hamming distance of one.</p>
<p>The average length of the Strings used is 9 characters. They range from 1 to 24 characters.</p>
<p>Is there a way to make the <code>isDistanceOne(char[])</code> method go any faster?</p>
<pre><code>private class WordArray {
char[] word;
/**
* Creates a new WordArray object.
*
* @param word The word to add to the WordArray.
*/
private WordArray(String word) {
this.word = word.toCharArray();
}
/**
* Returns whether the argument is within a Hamming Distance of one from
* the char[] contained in the WordArray.
*
* Both char[]s should be of the same length.
*
* @param otherWord The word to compare with this.word.
* @return boolean.
*/
private boolean isDistanceOne(char[] otherWord) {
int count = 0;
for(int i = 0; i < otherWord.length; i++) {
if (this.word[i] != otherWord[i])
count++;
}
return (count == 1);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:52:47.320",
"Id": "425366",
"Score": "1",
"body": "How large are the Strings? The fastest solution would differ for many short Strings versus very large strings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T18:04:16.123",
"Id": "425367",
"Score": "0",
"body": "@dustytrash The range is from 1 to 24. The average length is 9. I've edited my question to mention this."
}
] | [
{
"body": "<p>I don't think you can beat that linear complexity since you need to look at each character to determine the Hamming distance.</p>\n\n<p>One small optimization you can do is to short-circuit once your count goes above one, but that adds an extra check in every iteration, so it might have worse runtime depending on the inputs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T20:10:47.180",
"Id": "220151",
"ParentId": "220144",
"Score": "6"
}
},
{
"body": "<p>Given the limited context, and no information about where the hotspot is in the code, it's difficult to give concrete advice. Here are some musings for your consideration:</p>\n\n<p>For ease of reading, it's preferable to have whitespace after control flow keywords and before the <code>(</code>.</p>\n\n<p>It is suggested to always include curly braces, even when they're not required by the compiler.</p>\n\n<p>Use <code>final</code> where possible to reduce cognitive load on the readers of your code.</p>\n\n<p><code>word</code> should be private.</p>\n\n<p>There's no apparent reason to use <code>char[]</code> instead of just keeping a pointer to the original <code>String</code>. They're costing you time and space to make, to no benefit.</p>\n\n<p>You can short-circuit out of your <code>for</code> loop if the count ever becomes greater than one. Unless a significant fraction of your inputs have a distance of one, you should see some performance gain here.</p>\n\n<p>Using a <code>boolean</code> instead of an <code>int</code> <em>might</em> make a very small difference in execution time, but that would need to be tested. It also makes the code harder to read.</p>\n\n<pre><code>private class WordArray {\n\n private final String word;\n\n private WordArray(final String word) {\n this.word = word;\n }\n\n private boolean isDistanceOne(final char[] otherWord) {\n assert word.length() == otherWord.length;\n\n int distance = 0;\n\n for (int i = 0; i < otherWord.length; i++) {\n if (this.word.charAt(i) == otherWord[i]) {\n continue;\n }\n\n if (distance > 0) {\n return false;\n }\n\n distance++;\n }\n\n\n return distance == 1;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T20:15:41.517",
"Id": "220152",
"ParentId": "220144",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "220152",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T17:50:15.383",
"Id": "220144",
"Score": "5",
"Tags": [
"java",
"performance",
"strings",
"array",
"edit-distance"
],
"Title": "Find hamming distance between two Strings of equal length in Java"
} | 220144 |
<p>This is my first attempt at creating a small module to wrap the .NET library EasyNetQ in F# to make it more functional.</p>
<p>I am pretty new to F# and I would like to get feedbacks on everything: types, naming conventions, functional thinking, etc.</p>
<p><code>RabbitMQ.fs</code>:</p>
<pre><code>module RabbitMQ
open EasyNetQ
open System
type BusConnection = {
Address: string
Port: uint16
Username: string
Password: string
}
type NamingConventions = {
RetrieveQueueName: Type -> string -> string
RetrieveExchangeName: Type -> string
RetrieveErrorQueueName: MessageReceivedInfo -> string
RetrieveErrorExchangeName: MessageReceivedInfo -> string
}
type Subscription<'T> = {
Id: string
OnMessageReceived: 'T -> unit
}
let private buildConnectionString (busConnection: BusConnection) =
sprintf "host=%s:%d;username=%s;password=%s"
busConnection.Address
busConnection.Port
busConnection.Username
busConnection.Password
let createBus (connection: BusConnection) =
let connectionString = buildConnectionString connection
RabbitHutch.CreateBus(connectionString)
let publishAsync<'T> (bus: IBus) (message: 'T) = bus.PubSub.PublishAsync<'T>(message)
|> Async.AwaitTask
let subscribeAsync<'T> (bus: IBus) (subscription: Subscription<'T>) = bus.PubSub.SubscribeAsync<'T>(subscription.Id, subscription.OnMessageReceived).AsTask()
|> Async.AwaitTask
let setNamingConventions (bus: IBus) (namingConventions: NamingConventions) =
bus.Advanced.Conventions.QueueNamingConvention <- new QueueNameConvention(namingConventions.RetrieveQueueName)
bus.Advanced.Conventions.ExchangeNamingConvention <- new ExchangeNameConvention(namingConventions.RetrieveExchangeName)
bus.Advanced.Conventions.ErrorQueueNamingConvention <- new ErrorQueueNameConvention(namingConventions.RetrieveErrorQueueName)
bus.Advanced.Conventions.ErrorExchangeNamingConvention <- new ErrorExchangeNameConvention(namingConventions.RetrieveErrorExchangeName)
</code></pre>
<p><code>Program.fs</code>:</p>
<pre><code>
open RabbitMQ
type Message = {
Text: string
}
[<EntryPoint>]
let main argv =
let busConnection = {
Address = "localhost"
Port = 5672 |> uint16
Username = "guest"
Password = "guest"
}
let namingConventions = {
RetrieveQueueName = fun messageType subscriptionId -> "Queue: " + (messageType.FullName + subscriptionId)
RetrieveExchangeName = fun messageType -> "Exchange: " + messageType.FullName
RetrieveErrorQueueName = fun messageReceivedInfo -> messageReceivedInfo.Queue + " - Error"
RetrieveErrorExchangeName = fun messageReceivedInfo -> messageReceivedInfo.Exchange + " - Error"
}
use bus = createBus busConnection
setNamingConventions bus namingConventions
let subscription = {
Id = "subscription_id"
OnMessageReceived = fun (message: Message) -> printfn "%A" message
}
async {
let! result = subscribeAsync<Message> bus subscription
do! publishAsync<Message> bus {Text = "1"}
do! publishAsync<Message> bus {Text = "2"}
do! publishAsync<Message> bus {Text = "3"}
} |> Async.RunSynchronously
Console.waitPressKey
0
</code></pre>
<p><code>Console.fs</code></p>
<pre><code>module Console
open System
let waitPressKey = Console.ReadKey() |> ignore
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T18:09:47.623",
"Id": "220145",
"Score": "3",
"Tags": [
"f#",
"rabbitmq"
],
"Title": "A simple functional F# wrapper for EasyNetQ"
} | 220145 |
<p>I have built a simple JS class with functional methods that create a Rock, Paper, Scissors game.</p>
<p>I would be happy to get a non-opinionated review in terms of code being optimal.</p>
<pre><code>class Rps{
constructor(){
this.signs = {1:'rock',2:'paper',3:'scissors'};
this.winMatrix = [
{1:3},
{2:1},
{3:2}
];
}
randomizePlay(){
const keys = Object.keys(this.signs);
return 1 + Math.floor(keys.length * Math.random());
}
play(){
return this.roundResult([this.randomizePlay(),this.randomizePlay()]);
}
roundResult(resultArray) {
let victorious = {};
if (resultArray[0] === resultArray[1]) {
return 'rematch';
}
this.winMatrix.forEach((value, index) => {
const p1Result = resultArray[0];
const p2Result = resultArray[1];
const p1WinMatrix = parseInt(Object.keys(this.winMatrix[index]));
const p2WinMatrix = parseInt(Object.values(this.winMatrix[index]));
if (p1Result === p1WinMatrix && p2Result === p2WinMatrix){
return victorious = {1:p1Result}
}else{
return victorious = {2:p2Result}
}
});
return victorious;
}
}
const theRpsArray = [];
const theRpsAverage = 0;
let rps = new Rps;
rps.play()
</code></pre>
| [] | [
{
"body": "<h2>Simulate only the result</h2>\n<p>A common problem in learning to program is over complicating the code. Complicated code is longer, harder to understand, and more prone to bugs. When the app is large even tiny over complications can lead to thousands of unneeded lines that must be tested and debugged.</p>\n<p>All that matters is what comes out the other end of a function, how that is done does not matter.</p>\n<p>Your code is way too complicated for what it needs to do. At its most simplest Rock paper scissors can be one line...</p>\n<p><code>(["Tie ","P1 WINS with ","P2 WINS with "])[Math.random()*3|0]+ ((["Rock","Paper","Scissors"])[Math.random()*3|0])</code></p>\n<h2>Rewrite</h2>\n<p>The object <code>rps</code> is equivalent to yours. Calling <code>rps.play()</code> returns the same results, and is statistically identical to your results</p>\n<pre><code>const rps = (() => {\n const rand3 = () => Math.random() * 3 | 0;\n const plays = [\n () => "rematch", \n () => ({"1": rand3() + 1}), \n () => ({"2": rand3() + 1})\n ];\n return { play() { return plays[rand3()]() } };\n})();\n</code></pre>\n<p>You do not need to simulate the game mechanics, just the game results.</p>\n<p>There are 9 possible results.</p>\n<ul>\n<li>1/3rd are draws,</li>\n<li>1/3rd player 1 wins and</li>\n<li>1/3rd player 2 wins.</li>\n</ul>\n<p>When a player wins there is a 1 in 3 chance for any move type.</p>\n<p>Thus a result first picks a random winner or draw, if there is a winner assign that player a random hand. There is no need calculate the hand the winner beats as that is inferred by the result.</p>\n<h2>Example 2</h2>\n<p>The following example produces a more readable result as an Example</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const rps = (() => {\n const moves = [\"Rock\", \"Paper\", \"Scissors\"];\n const rand = (range = 3) => Math.random() * range | 0;\n const win = (m = rand()) => `Player ${rand(2) + 1} ${moves[m]} beats ${moves[(m + 2) % 3]}`;\n const plays = [win, win, (m = moves[rand()]) => `${m} draws with ${m}`];\n return { play() { return plays[rand()]() } };\n})();\n\nvar games = 20;\nwhile (games --) { log(rps.play()) }\n\n\n\nfunction log(textContent) {\n info.appendChild(Object.assign(document.createElement(\"div\"),{textContent}));\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"info\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T00:58:32.947",
"Id": "220162",
"ParentId": "220146",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T18:32:24.287",
"Id": "220146",
"Score": "2",
"Tags": [
"javascript",
"rock-paper-scissors"
],
"Title": "JavaScript Rock, Paper, Scissors"
} | 220146 |
<p>I made a QT version of "<em><a href="https://codereview.stackexchange.com/questions/219886/snake-console-game-in-c">Snake console game in C++</a></em>" using Qt Creator 4.9.0 on Windows 7:</p>
<p><a href="https://i.stack.imgur.com/Fdlip.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Fdlip.png" alt="Picture of the running game"></a></p>
<p>I would like to know what can be improved, focused on the QT stuff since im new to it.<br>
I seperated the program as followed:</p>
<h3>QT-Classes</h3>
<ul>
<li><strong>SnakeWindow:</strong> Contains the GUI Elements like the Buttons, LCD Displays and The <code>SnakeBoard</code> to display the game. It also sends the button signals to the <code>SnakeBoard</code> and receives the score and delay to be displayed in the LCD Displays.</li>
<li><strong>SnakeBoard</strong>: This is basically an extended QFrame which runs all the events like moving the snake and reacting to button events. It uses the non QT class <strong>Board</strong> which was already used in the console snakeGame</li>
</ul>
<h3>Non-QT-Classes</h3>
<ul>
<li><strong>Board</strong>: Describes the field were the snake is moved arround. Also generates food at a random position, let the snake grow and check for
the game over conditions wall or snake hit. It contains a <code>Snake</code> to
handle snake related stuff.</li>
<li><strong>Snake</strong>: Represents the Snake. Places the snake in the middle of the board. Enables to move the snake in all directions. Also the
snake can be grown.</li>
</ul>
<h3>main.cpp</h3>
<pre><code>#include "SnakeWindow.h"
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
try{
QApplication app(argc, argv);
SnakeWindow window;
//window.show();
window.showFullScreen();
return app.exec();
}
catch(...) {
qDebug() << "Unknown Error\n";
}
</code></pre>
<h3>SnakeWindow.h</h3>
<pre><code>#ifndef SNAKEWINDOW_H
#define SNAKEWINDOW_H
#include <QWidget>
namespace Ui {
class SnakeWindow;
}
class SnakeWindow : public QWidget
{
Q_OBJECT
public:
explicit SnakeWindow(QWidget *parent = nullptr);
~SnakeWindow();
private:
Ui::SnakeWindow *ui;
};
#endif // SNAKEWINDOW_H
</code></pre>
<h3>SnakeWindow.cpp</h3>
<pre><code>#include "SnakeWindow.h"
#include "ui_SnakeWindow.h"
SnakeWindow::SnakeWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::SnakeWindow)
{
ui->setupUi(this);
connect(ui->startButton, &QPushButton::clicked,
ui->snakeBoard, &SnakeBoard::start);
connect(ui->quitButton, &QPushButton::clicked,
qApp, &QApplication::quit);
connect(ui->pauseButton, &QPushButton::clicked,
ui->snakeBoard, &SnakeBoard::pause);
connect(ui->snakeBoard, &SnakeBoard::scoreChanged,
[=](int score) {ui->scoreLcd->display(score);});
connect(ui->snakeBoard, &SnakeBoard::delayChanged,
[=](int level) {ui->delayLcd->display(level);});
}
SnakeWindow::~SnakeWindow()
{
delete ui;
}
</code></pre>
<h3>SnakeBoard.h</h3>
<pre><code>#ifndef SNAKEBOARD_H
#define SNAKEBOARD_H
#include <QFrame>
#include <QBasicTimer>
#include "Board.h"
class SnakeBoard : public QFrame {
Q_OBJECT
public:
SnakeBoard(QWidget* parent = nullptr);
QSize sizeHint() const override;
QSize minimumSizeHint() const override;
public slots:
void start();
void pause();
void gameOver();
signals:
void scoreChanged(int score);
void delayChanged(int delay);
protected:
void paintEvent(QPaintEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void timerEvent(QTimerEvent *event) override;
private:
int squareWidth();
int squareHeight();
void drawField(
QPainter& painter, int x, int y, snakeGame::FieldType fieldType);
void drawWall(QPainter& painter, int x, int y);
void drawFood(QPainter& painter, int x, int y);
void drawSnakeHead(QPainter& painter, int x, int y);
void drawSnakeSegment(QPainter& painter, int x, int y);
static constexpr auto boardWidth{40};
static constexpr auto boardHeight{20};
static constexpr auto initDelay{300};
static constexpr auto initPoints{100};
QBasicTimer timer;
snakeGame::Board board{boardWidth, boardHeight};
snakeGame::SnakeDirection snakeDirection{snakeGame::SnakeDirection::right};
bool isStarted{false};
bool isPaused{false};
bool isGameOver{false};
bool snakeWasMoved{true};
int score{0};
int delay{initDelay};
int points{initPoints};
};
#endif // SNAKEBOARD_H
</code></pre>
<h3>SnakeBoard.cpp</h3>
<pre><code>#include "SnakeBoard.h"
#include <QKeyEvent>
#include <QColor>
#include <QPainter>
#include <QRgb>
#include <QTimerEvent>
#include <QDebug>
using namespace snakeGame;
SnakeBoard::SnakeBoard(QWidget* parent)
: QFrame{parent},
board{boardWidth, boardHeight},
snakeDirection{SnakeDirection::right}
{
setFrameStyle(QFrame::Panel | QFrame::Sunken);
setFocusPolicy(Qt::StrongFocus);
board.updateSnakePosition();
board.placeFood();
}
QSize SnakeBoard::sizeHint() const
{
return QSize(boardWidth * 15 + frameWidth() * 2,
boardHeight * 15 + frameWidth() * 2);
}
QSize SnakeBoard::minimumSizeHint() const
{
return QSize(boardWidth * 5 + frameWidth() * 2,
boardHeight * 5 + frameWidth() * 2);
}
void SnakeBoard::start()
{
if (isGameOver) {
isGameOver = false;
board.reset();
board.updateSnakePosition();
board.placeFood();
score = 0;
points = initPoints;
delay = initDelay;
}
if (isPaused)
return;
isStarted = true;
emit scoreChanged(score);
emit delayChanged(delay);
timer.start(delay, this);
}
void SnakeBoard::pause()
{
if (!isStarted)
return;
isPaused = !isPaused;
if (isPaused) {
timer.stop();
}
else {
timer.start(delay, this);
}
update();
}
void SnakeBoard::gameOver()
{
timer.stop();
isGameOver = true;
isStarted = false;
}
void SnakeBoard::paintEvent(QPaintEvent *event)
{
QFrame::paintEvent(event);
QPainter painter(this);
QRect rect = contentsRect();
if(isGameOver) {
QFont font;
font.setPixelSize(20);
painter.setFont(font);
painter.drawText(rect, Qt::AlignCenter, tr("Game Over"));
return;
}
if(!isStarted) {
QFont font;
font.setPixelSize(20);
painter.setFont(font);
painter.drawText(rect, Qt::AlignCenter, tr(
"Press start\n Use arrow keys to control the Snake"));
return;
}
if (isPaused) {
QFont font;
font.setPixelSize(20);
painter.setFont(font);
painter.drawText(rect, Qt::AlignCenter, tr("Pause"));
return;
}
auto boardTop = rect.bottom() - boardHeight * squareHeight();
for (int i = 0; i < boardHeight; ++i) {
for (int j = 0; j < boardWidth; ++j) {
auto fieldType =
board.fieldTypeAt(
static_cast<std::size_t>(j),
static_cast<std::size_t>(i));
drawField(painter, rect.left() + j * squareWidth(),
boardTop + i * squareHeight(), fieldType);
}
}
}
void SnakeBoard::keyPressEvent(QKeyEvent *event)
{
auto key = event->key();
if (key == Qt::Key_P) {
emit pause();
}
if (key == Qt::Key_Space) {
emit start();
}
else if (!isStarted || isGameOver || !snakeWasMoved) {
QFrame::keyPressEvent(event);
return;
}
switch (key) {
case Qt::Key_Left:
if (snakeDirection != SnakeDirection::right) {
snakeDirection = SnakeDirection::left;
snakeWasMoved = false;
}
break;
case Qt::Key_Right:
if (snakeDirection != SnakeDirection::left) {
snakeDirection = SnakeDirection::right;
snakeWasMoved = false;
}
break;
case Qt::Key_Down:
if (snakeDirection != SnakeDirection::up) {
snakeDirection = SnakeDirection::down;
snakeWasMoved = false;
}
break;
case Qt::Key_Up:
if (snakeDirection != SnakeDirection::down) {
snakeDirection = SnakeDirection::up;
snakeWasMoved = false;
}
break;
default:
QFrame::keyPressEvent(event);
}
}
void SnakeBoard::timerEvent(QTimerEvent *event)
{
if (isGameOver){
QFrame::timerEvent(event);
return;
}
if (event->timerId() == timer.timerId()) {
board.moveSnake(snakeDirection);
snakeWasMoved = true;
if (board.snakeHitFood()) {
board.eatFood();
board.growSnake();
board.updateSnakePosition();
board.placeFood();
score += points;
points += static_cast<double>(initDelay / delay) * initPoints;
delay -= 4;
emit scoreChanged(score);
emit delayChanged(delay);
}
else if (board.snakeHitWall() || board.snakeHitSnake()) {
emit gameOver();
}
else {
board.updateSnakePosition();
}
update();
timer.start(delay, this);
}
else {
QFrame::timerEvent(event);
}
}
int SnakeBoard::squareWidth()
{
return contentsRect().width() / boardWidth;
}
int SnakeBoard::squareHeight()
{
return contentsRect().height() / boardHeight;
}
void SnakeBoard::drawField(
QPainter& painter, int x, int y, snakeGame::FieldType fieldType)
{
switch(fieldType){
case FieldType::empty:
break;
case FieldType::wall:
drawWall(painter, x, y);
break;
case FieldType::food:
drawFood(painter, x, y);
break;
case FieldType::snakeHead:
drawSnakeHead(painter, x, y);
break;
case FieldType::snakeSegment:
drawSnakeSegment(painter, x, y);
break;
}
}
void SnakeBoard::drawWall(QPainter& painter, int x, int y)
{
constexpr auto colorBrown = 0xbf8040;
QColor color = QRgb{colorBrown};
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
color);
painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + 1);
}
void SnakeBoard::drawFood(QPainter& painter, int x, int y)
{
constexpr auto colorRed = 0xff0000;
QColor color = QRgb{colorRed};
painter.setPen(color.light());
painter.setBrush(QBrush{color});
painter.drawEllipse(x +1,y +1,squareWidth() -3, squareHeight() -3);
}
void SnakeBoard::drawSnakeHead(QPainter& painter, int x, int y)
{
constexpr auto colorDarkerLimeGreen = 0x00b300;
QColor color = QRgb{colorDarkerLimeGreen};
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
color);
painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + 1);
}
void SnakeBoard::drawSnakeSegment(QPainter& painter, int x, int y)
{
constexpr auto colorLimeGreen = 0x00e600;
QColor color = QRgb{colorLimeGreen};
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
color);
painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + 1);
}
</code></pre>
<h3>Board.h</h3>
<pre><code>#ifndef BOARD_H
#define BOARD_H
#include "Snake.h"
#include <vector>
#include <random>
#include <iosfwd>
namespace snakeGame {
enum class SnakeDirection;
enum class FieldType {
empty,
snakeSegment,
snakeHead,
wall,
food
};
enum class SnakeDirection {
up, right, down, left
};
class Board
{
public:
Board(std::size_t width, std::size_t height);
void reset();
void placeFood();
void updateSnakePosition();
bool snakeHitFood() const;
void eatFood();
void growSnake();
bool snakeHitWall() const;
bool snakeHitSnake() const;
void moveSnake(SnakeDirection snakeDirection);
void debugPrintSnakeCoordinates();
FieldType fieldTypeAt(std::size_t x, std::size_t y);
private:
std::vector<std::vector<FieldType>> initFieldWithWalls(
std::size_t width, std::size_t height);
void removeOldSnakePosition(const std::vector<SnakeSegment>& body);
void addNewSnakePosition(const std::vector<SnakeSegment>& body);
const std::size_t mWidth;
const std::size_t mHeight;
Snake mSnake;
std::vector<std::vector<FieldType>> mFields;
std::random_device mRandomDevice;
std::default_random_engine mGenerator;
std::uniform_int_distribution<std::size_t> mWidthDistribution;
std::uniform_int_distribution<std::size_t> mHeightDistribution;
friend std::wostream& operator<<(std::wostream& os, const Board& obj);
};
std::wostream& operator<<(std::wostream& os, const Board& obj);
}
#endif
</code></pre>
<h3>Board.cpp</h3>
<pre><code>#include "Board.h"
#include <algorithm>
#include <iostream>
namespace snakeGame {
Board::Board(std::size_t width, std::size_t height)
: mWidth{width},
mHeight{height},
mSnake{ width, height },
mFields{ initFieldWithWalls(width, height) },
mRandomDevice{},
mGenerator{ mRandomDevice() },
mWidthDistribution{ 2, width - 3 },
mHeightDistribution{ 2, height - 3 }
{
}
void Board::reset()
{
mFields = initFieldWithWalls(mWidth, mHeight);
mSnake = Snake{mWidth,mHeight};
}
void Board::placeFood()
{
for (;;) {
auto x = mWidthDistribution(mGenerator);
auto y = mHeightDistribution(mGenerator);
if(mFields.at(y).at(x) == FieldType::empty){
mFields.at(y).at(x) = FieldType::food;
return;
}
}
}
void Board::updateSnakePosition()
{
auto snakeBody = mSnake.getBody();
removeOldSnakePosition(snakeBody);
addNewSnakePosition(snakeBody);
}
bool Board::snakeHitFood() const
{
auto pos = mSnake.getBody().at(0).pos;
return mFields.at(pos.y).at(pos.x) == FieldType::food;
}
void Board::eatFood()
{
auto pos = mSnake.getBody()[0].pos;
mFields.at(pos.y).at(pos.x) = FieldType::empty;
}
void Board::growSnake()
{
mSnake.grow();
}
bool Board::snakeHitWall() const
{
auto pos = mSnake.getBody()[0].pos;
return mFields.at(pos.y).at(pos.x) == FieldType::wall;
}
bool Board::snakeHitSnake() const
{
auto pos = mSnake.getBody()[0].pos;
return mFields.at(pos.y).at(pos.x) == FieldType::snakeSegment;
}
void Board::moveSnake(SnakeDirection snakeDirection)
{
switch (snakeDirection) {
case SnakeDirection::right:
mSnake.moveRight();
break;
case SnakeDirection::down:
mSnake.moveDown();
break;
case SnakeDirection::left:
mSnake.moveLeft();
break;
case SnakeDirection::up:
mSnake.moveUp();
break;
}
}
void Board::debugPrintSnakeCoordinates()
{
auto body = mSnake.getBody();
for (std::size_t i = 0; i < body.size(); ++i) {
auto pos = body.at(i).pos;
std::wcout << "nr:" << i << "x:" << pos.x
<< "\t" << "y:" << pos.y << "\t";
auto field = mFields.at(pos.y).at(pos.x);
switch(field)
{
case FieldType::snakeHead:
std::wcout << L"Head\t";
[[fallthrough]];
case FieldType::snakeSegment:
std::wcout << L"Body\n";
[[fallthrough]];
default:
std::wcout << L" \n";
}
}
}
FieldType Board::fieldTypeAt(std::size_t x, std::size_t y)
{
return mFields.at(y).at(x);
}
std::vector<std::vector<FieldType>> Board::initFieldWithWalls(
std::size_t width, std::size_t height)
{
std::vector<FieldType> row(width, FieldType::empty);
std::vector<std::vector<FieldType>> field(height, row);
std::fill(field.at(0).begin(), field.at(0).end(), FieldType::wall);
std::fill(field.at(field.size() - 1).begin(),
field.at(field.size() - 1).end(), FieldType::wall);
for (auto it_row = field.begin() + 1;
it_row < field.end() - 1; ++it_row) {
(*it_row).at(0) = FieldType::wall;
(*it_row).at(it_row->size() - 1) = FieldType::wall;
}
return field;
}
void Board::removeOldSnakePosition(const std::vector<SnakeSegment>& body)
{
for (const auto& snakeSegment : body) {
auto prev = snakeSegment.prev;
mFields.at(prev.y).at(prev.x) = FieldType::empty;
}
}
void Board::addNewSnakePosition(const std::vector<SnakeSegment>& body)
{
auto first{ true };
for (const auto& snakeSegment : body) {
auto pos = snakeSegment.pos;
if (first) {
mFields.at(pos.y).at(pos.x) = FieldType::snakeHead;
first = false;
}
else {
mFields.at(pos.y).at(pos.x) = FieldType::snakeSegment;
}
}
}
std::wostream& operator<<(std::wostream& os, const Board& obj)
{
for (const auto& row : obj.mFields) {
for (const auto& element : row) {
switch(element){
case FieldType::empty:
os << L' ';
break;
case FieldType::wall:
os << L'#';
break;
case FieldType::food:
os << L'*';
break;
case FieldType::snakeHead:
os << L'@';
break;
case FieldType::snakeSegment:
os << L'o';
break;
}
}
os << '\n';
}
return os;
}
}
</code></pre>
<h3>Snake.h</h3>
<pre><code>#ifndef SNAKE_H
#define SNAKE_H
#include <vector>
#include <cstddef>
namespace snakeGame {
struct Point {
std::size_t x;
std::size_t y;
};
struct SnakeSegment
{
Point pos{ 0 , 0 };
Point prev{ pos };
};
class Snake
{
public:
Snake(std::size_t boardWidth, std::size_t boardHeight);
std::vector<SnakeSegment> getBody() const;
void moveRight();
void moveDown();
void moveLeft();
void moveUp();
void grow();
private:
void safeCurrentPosToLastOfFirstElement();
void moveRemainingElements();
std::vector<SnakeSegment> mBody;
};
std::vector<SnakeSegment> initSnake(
std::size_t fieldWidth, std::size_t fieldHeight);
}
#endif
</code></pre>
<h3>Snake.cpp</h3>
<pre><code>#include "Snake.h"
namespace snakeGame {
Snake::Snake(std::size_t fieldWidth, std::size_t fieldHeight)
:mBody{ initSnake(fieldWidth, fieldHeight) }
{
}
std::vector<SnakeSegment> Snake::getBody() const
{
return mBody;
}
void Snake::moveRight()
{
safeCurrentPosToLastOfFirstElement();
++mBody.at(0).pos.x;
moveRemainingElements();
}
void Snake::moveDown()
{
safeCurrentPosToLastOfFirstElement();
++mBody.at(0).pos.y;
moveRemainingElements();
}
void Snake::moveLeft()
{
safeCurrentPosToLastOfFirstElement();
--mBody.at(0).pos.x;
moveRemainingElements();
}
void Snake::moveUp()
{
safeCurrentPosToLastOfFirstElement();
--mBody.at(0).pos.y;
moveRemainingElements();
}
void Snake::grow()
{
mBody.push_back(SnakeSegment{
{mBody.at(mBody.size() - 1).prev.x,
mBody.at(mBody.size() - 1).prev.y}
});
}
void Snake::safeCurrentPosToLastOfFirstElement()
{
mBody.at(0).prev.x = mBody.at(0).pos.x;
mBody.at(0).prev.y = mBody.at(0).pos.y;
}
void Snake::moveRemainingElements()
{
for (std::size_t i = 1; i < mBody.size(); ++i) {
mBody.at(i).prev.x = mBody.at(i).pos.x;
mBody.at(i).prev.y = mBody.at(i).pos.y;
mBody.at(i).pos.x = mBody.at(i - 1).prev.x;
mBody.at(i).pos.y = mBody.at(i - 1).prev.y;
}
}
std::vector<SnakeSegment> initSnake(
std::size_t boardWidth, std::size_t boardHeight)
{
auto x = boardWidth / 2;
auto y = boardHeight / 2;
std::vector<SnakeSegment> body{
SnakeSegment{ {x, y} },
SnakeSegment{ {x - 1, y} },
};
return body;
}
}
</code></pre>
<h3>Snake_qt.pro</h3>
<pre><code>QT += widgets
CONFIG += c++17
SOURCES += \
Board.cpp \
Snake.cpp \
SnakeBoard.cpp \
SnakeWindow.cpp \
main.cpp
HEADERS += \
Board.h \
Snake.h \
SnakeBoard.h \
SnakeWindow.h
FORMS += \
SnakeWindow.ui
</code></pre>
<h3>SnakeWindow.ui</h3>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SnakeWindow</class>
<widget class="QWidget" name="SnakeWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>771</width>
<height>618</height>
</rect>
</property>
<property name="windowTitle">
<string>Snake</string>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="1" column="2" colspan="2">
<widget class="QLCDNumber" name="delayLcd">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(255, 255, 127);</string>
</property>
<property name="smallDecimalPoint">
<bool>false</bool>
</property>
<property name="digitCount">
<number>5</number>
</property>
<property name="mode">
<enum>QLCDNumber::Dec</enum>
</property>
<property name="segmentStyle">
<enum>QLCDNumber::Flat</enum>
</property>
</widget>
</item>
<item row="2" column="0" colspan="4">
<widget class="SnakeBoard" name="snakeBoard">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>8</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(255, 178, 102, 255), stop:0.55 rgba(235, 148, 61, 255), stop:0.98 rgba(0, 0, 0, 255), stop:1 rgba(0, 0, 0, 0));</string>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QPushButton" name="quitButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="styleSheet">
<string notr="true">
background-color: rgb(255, 170, 255);</string>
</property>
<property name="text">
<string>Quit</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="scoreLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
<weight>50</weight>
<bold>false</bold>
</font>
</property>
<property name="text">
<string>Score</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QLCDNumber" name="scoreLcd">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(255, 255, 127);</string>
</property>
<property name="smallDecimalPoint">
<bool>false</bool>
</property>
<property name="digitCount">
<number>10</number>
</property>
<property name="segmentStyle">
<enum>QLCDNumber::Flat</enum>
</property>
</widget>
</item>
<item row="0" column="2" colspan="2">
<widget class="QLabel" name="delayLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
<weight>50</weight>
<bold>false</bold>
</font>
</property>
<property name="text">
<string>Delay in ms</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="startButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(85, 255, 0);</string>
</property>
<property name="text">
<string>Start</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="pauseButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(170, 255, 0);</string>
</property>
<property name="text">
<string>Pause</string>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>SnakeBoard</class>
<extends>QFrame</extends>
<header location="global">SnakeBoard.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
</code></pre>
| [] | [
{
"body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use consistent formatting</h2>\n\n<p>It appears that your code uses tabs in some places and spaces in others, making the code appear badly formatted unless the settings in the reader's editor are set exactly the same as in yours. To prevent this, I recommend using spaces everywhere. It's a habit that may even <a href=\"https://stackoverflow.blog/2017/06/15/developers-use-spaces-make-money-use-tabs/\">earn you more money</a>!</p>\n\n<h2>Fix the bug</h2>\n\n<p>There is a subtle bug in the code. If the user crashes into the left wall, it's no longer possible to restart the game. </p>\n\n<h2>Don't store data unnecessary data</h2>\n\n<p>In the <code>Board</code> class, there is not any need to have the <code>mRandomDevice</code> stored as a member. Instead, initialize <code>mGenerator</code> like this:</p>\n\n<pre><code>mGenerator{ std::random_device{}() },\n</code></pre>\n\n<p>This creates, uses, and discards a <code>std::random_device</code> instance.</p>\n\n<h2>Carefully consider the use of data structures</h2>\n\n<p>In the <code>Board</code> class, the internal representation is a vector of vectors. However, since these are fixed size, it seems that perhaps <code>std::array</code> of <code>std::array</code> would be more appropriate. Alternatively, a single <code>std::array</code> could be used with helper routines to convert from, say, your <code>Point</code> class to the appropriate location in the data structure.</p>\n\n<h2>Avoid convoluted control flows</h2>\n\n<p>The <code>placeFood()</code> routine is currently like this:</p>\n\n<pre><code>void Board::placeFood()\n{\n for (;;) {\n auto x = mWidthDistribution(mGenerator);\n auto y = mHeightDistribution(mGenerator);\n\n if(mFields.at(y).at(x) == FieldType::empty){\n mFields.at(y).at(x) = FieldType::food;\n return;\n }\n }\n}\n</code></pre>\n\n<p>I think it could be made easier to read and understand if it's written like this:</p>\n\n<pre><code>void Board::placeFood()\n{\n auto [x, y] = randomEmptyLocation(); \n mFields.at(y).at(x) = FieldType::food;\n}\n</code></pre>\n\n<p>Note that this is using the C++17 <a href=\"https://en.cppreference.com/w/cpp/language/structured_binding\" rel=\"nofollow noreferrer\">structured binding declaration</a> for convenience. This also uses two helper functions:</p>\n\n<pre><code>std::tuple<std::size_t, std::size_t> Board::randomLocation() {\n return { mWidthDistribution(mGenerator), \n mHeightDistribution(mGenerator)};\n}\n\nstd::tuple<std::size_t, std::size_t> Board::randomEmptyLocation() {\n auto [x, y] = randomLocation(); \n while (fieldTypeAt(x, y) != FieldType::empty) {\n std::tie(x, y) = randomLocation();\n }\n return {x, y};\n}\n</code></pre>\n\n<p>Also, of course, <code>#include <tuple></code> is required to use this. Alternatively, instead of using individual <code>x</code> and <code>y</code>, the interface could be redesigned to more fully use the existing <code>Point</code> struct.</p>\n\n<h2>Avoid wasteful copies</h2>\n\n<p>The <code>Snake::getBody()</code> function duplicates and returns an entire vector. This is not really necessary since most places that call this function are only doing so to get the position of the head. For that reason, a better approach would be to provide <code>headloc()</code> function that would return the location of the head as either a <code>Point</code> or as a <code>std::tuple</code> as shown above.</p>\n\n<h2>Think about more efficient algorithms</h2>\n\n<p>The <code>updateSnakePosition()</code> code is not very efficient. As mentioned above, it makes a duplicate of the entire snake, but then it erases the entire snake from the board and then adds it back again in the new position. This is wholly unnecessary because the only updates required are the head, the segment just behind the head and the tail. It's not critical here, but it's useful to get into the habit of writing efficient code.</p>\n\n<h2>Think carefully about the user interface</h2>\n\n<p>Is there a purpose to the gradient on the field? It seems to me to be solely a distraction because it doesn't convey anything to the user and is, in my humble opinion, not aesthetically pleasing. </p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>Several of the functions could be <code>const</code> but are not, such as <code>SnakeBoard::squareHeight</code> and <code>Board::fieldTypeAt</code>. It would be better to declare them <code>const</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T07:17:01.357",
"Id": "426241",
"Score": "0",
"body": "thanks. many good suggestions. i give you sppecial credit for the space vs tab survey."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T16:57:41.900",
"Id": "426333",
"Score": "0",
"body": "i have one concern. If i switch the datastructure in class Board to `std::array for mFields` i need to know its size during compile time and cannot pass the size with the constructor argumenets `Board(std::size_t width, std::size_t height);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T17:03:11.933",
"Id": "426335",
"Score": "0",
"body": "@Sandro4912: that's true, but on the other hand, the `width` and `height` in the existing code are `constexpr`, so that's not much of a loss. If you want to allow a more dynamic sizing at runtime, then, yes, it would make sense to use a dynamically sized data structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T17:05:30.053",
"Id": "426336",
"Score": "0",
"body": "I guess you are right. After all we only want one board with the right size in all the game, not several different sized ones. Over engineering in this case i guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T17:17:40.110",
"Id": "426338",
"Score": "0",
"body": "As a practical matter, efficiency probably doesn't really matter much in this instance on modern computers. So if you think you *might* want to make it dynamic in the future, it may be better just to leave it as it is. Most of the time in the current program is taken up by deliberate delays between screen updates anyway, and unless the player is *very* good or the hardware *very* bad, I doubt anyone will notice much difference either way."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:34:30.673",
"Id": "220426",
"ParentId": "220147",
"Score": "4"
}
},
{
"body": "<p>Like hinted in the other answer there is a quite nasty bug which prevents the Game to restart after the Snake runs into the left wall.</p>\n\n<p>I hunted the bug und fixed it. Maybe its interesing whats the cause:</p>\n\n<p>After the crash with the left wall GameOver is still emitted in the timerEvent when the start Button is pressed. The Reason is the function \"snakeHitSnake()\" gives a false true here:</p>\n\n<pre><code>void SnakeBoard::timerEvent(QTimerEvent *event)\n{\n ...\n else if (board.snakeHitWall() || board.snakeHitSnake()) {\n emit gameOver();\n }\n ...\n}\n</code></pre>\n\n<p>To fix this issue we must realize that the start Button is faulty:</p>\n\n<pre><code>void SnakeBoard::start()\n{\n if (isGameOver) {\n isGameOver = false;\n board.reset();\n board.updateSnakePosition();\n board.placeFood();\n...\n}\n</code></pre>\n\n<p>In the if statement <code>board.reset()</code> is called:</p>\n\n<pre><code>void Board::reset()\n{\n mFields = initFieldWithWalls(mWidth, mHeight);\n mSnake = Snake{mWidth,mHeight};\n}\n</code></pre>\n\n<p>That already reinits all the field and makes a fresh new snake. So <code>board.updateSnakePosition();</code> after is not needed and causing the bug.</p>\n\n<p>Simply omiting it fixxes it:</p>\n\n<pre><code>void SnakeBoard::start()\n{\n if (isGameOver) {\n isGameOver = false;\n board.reset();\n board.placeFood();\n...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T09:08:44.403",
"Id": "220708",
"ParentId": "220147",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220426",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T18:38:09.120",
"Id": "220147",
"Score": "8",
"Tags": [
"c++",
"gui",
"c++17",
"snake-game",
"qt"
],
"Title": "C++ Snake game using Qt-framework"
} | 220147 |
<p>I tried in this project to apply what I learned from OOP, using classes and properties, please advise for any best practice or any improvement.</p>
<p>Conclusion:
I have a text file "ToDoList.txt" which has the following syntax <strong>Task,status</strong> for example:
<code>Shopping,0
cooking,1
pick up kids from school,2
do something,0</code> </p>
<p>And I have two classes:</p>
<ul>
<li><strong>TaskData</strong> class which only has properties and it will return the status in text(Completed or not completed)</li>
<li><strong>FilterData</strong> class which is going to filter the data according to the status</li>
</ul>
<p><strong>Main Program class:</strong></p>
<pre><code>namespace ExtractingDataFromTextFile
{
class Program
{
static void Main()
{
//Save Results of text data and declaring the text file to
//Read Data from.
TaskData textData = new TaskData();
string path = "ToDoList.txt";
//Create a string to read all data in file
string[] allData = File.ReadAllLines(path);
//Assign each data to TextData object properties
foreach (var task in allData)
{
PrintData(textData, task);
}
FilterData filterData = new FilterData();
//Filter to show Completed Tasks only
string[] completedTasks = filterData.ShowCompleted(allData);
Console.WriteLine("\nFilter only completed tasks:");
foreach (var task in completedTasks)
{
PrintData(textData, task);
}
//Filter to show uncompleted Taks only
string[] unCompletedTasks = filterData.ShowUnCompleted(allData);
Console.WriteLine("\nFilter only Un-completed tasks:");
foreach (var task in unCompletedTasks)
{
PrintData(textData, task);
}
Console.ReadLine();
}
//This method will print data to the console
private static void PrintData(TaskData textData, string task)
{
string[] lineData = task.Split(',');
textData.Name = lineData[0];
textData.Status = lineData[1];
Console.WriteLine($"Task: {textData.Name}, Status:[{textData.Status}]");
}
}
}
</code></pre>
<p><strong>TaskData class:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtractingDataFromTextFile
{
class TaskData
{
private string _status;
public string Name { get; set; }
public string Status
{
get {return _status; }
//The setter will convert status from number to text
//0 --> Not completed
//1 --> Completed
set
{
if (value == "0")
{
_status = "Not completed";
}
else if(value =="1")
{
_status = "Completed";
}
else
{
_status = "Unknown";
}
}
}
}
}
</code></pre>
<p><strong>FilterData class</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtractingDataFromTextFile
{
class FilterData
{
private List<string> _filterData = new List<string>();
//This function will filter the list to show only completed tasks
public string[] ShowCompleted(string[] allData)
{
_filterData = new List<string>(); //Recreate the list to delete old filter
foreach (var line in allData)
{
string[] lineData = line.Split(',');
if (lineData[1] == "1")
{
//Completed task
_filterData.Add($"{lineData[0]},{lineData[1]}");
}
}
return _filterData.ToArray();
}
//This function will filter the list to show only un-completed tasks
public string[] ShowUnCompleted(string[] allData)
{
_filterData = new List<string>(); //Recreate the list to deleted old filter
foreach (var line in allData)
{
string[] lineData = line.Split(',');
if (lineData[1] == "0")
{
//Un-Completed task
_filterData.Add($"{lineData[0]},{lineData[1]}");
}
}
return _filterData.ToArray();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T19:53:29.643",
"Id": "425540",
"Score": "0",
"body": "Please see [What to do when someone answers](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 5 → 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T20:03:24.083",
"Id": "425541",
"Score": "0",
"body": "@Mast Thank you, I followed the link and answered my question."
}
] | [
{
"body": "<p>In PrintData method you are assigning values to TaskData object but you don't seem to do anything with it besides just printing it out.</p>\n\n<p>I would parse the file into a List at the beginning and then work with this collection in later code.</p>\n\n<pre><code>private static List<TaskData> ParseTaskData(string[] allData)\n{\n var tasksData = new List<TaskData>();\n\n foreach (var task in allData)\n {\n string[] lineData = task.Split(',');\n\n tasksData.Add(new TaskData()\n {\n Name = lineData[0],\n // Before Enum: Status = lineData[1]\n Status = (Status)int.Parse(lineData[1].ToString())\n });\n };\n\n return tasksData;\n}\n</code></pre>\n\n<p>Also your filter methods can then work as one-liners with lambda. I would be tempted here to split property Status into <code>Status</code> and <code>StatusReadable</code>. Make <code>Status</code> an Enum for ease of filtering.</p>\n\n<pre><code>public List<TaskData> ShowUnCompletedFromList(List<TaskData> allData)\n{\n return allData.Where(w => w.Status == \"Not completed\").ToList();\n}\n</code></pre>\n\n<p>Enum solution (I changed the <code>ParseTaskData</code> above):</p>\n\n<pre><code>internal enum Status\n{\n NotCompleted = 0,\n Completed = 1\n}\n</code></pre>\n\n<p>And TaskData then becomes:</p>\n\n<pre><code>internal class TaskData\n{\n public string Name { get; set; }\n\n public Status Status { get; set; }\n\n public string StatusDescription\n {\n get\n {\n if (Status == Status.NotCompleted)\n {\n return \"Not completed\";\n }\n else if (Status == Status.Completed)\n {\n return \"Completed\";\n }\n else\n {\n return \"Unknown\";\n }\n }\n }\n}\n</code></pre>\n\n<p>Filtering is now based on Enum and not magic strings:</p>\n\n<pre><code>public List<TaskData> ShowUnCompletedFromList(List<TaskData> allData)\n{\n // With Magic string: return allData.Where(w => w.Status == \"Not completed\").ToList();\n return allData.Where(w => w.Status == Status.NotCompleted).ToList();\n}\n</code></pre>\n\n<p>Try it out with Enum solution:</p>\n\n<pre><code>// Parse all tasks to List.\nvar tasksData = ParseTaskData(allData);\n\n// Show items in List<>.\nConsole.WriteLine(\">> All tasks:\");\n\nforeach (var task in tasksData)\n{\n Console.WriteLine($\"Task: {task.Name} is {task.StatusDescription}.\");\n}\n\nConsole.WriteLine(\">> Uncompleted tasks:\");\nforeach (var uncompletedTask in filterData.ShowUnCompletedFromList(tasksData))\n{\n Console.WriteLine($\"Task: {uncompletedTask.Name} is {uncompletedTask.StatusDescription}.\");\n}\n\n// Actually no need for a filter method, this one-liner does it the same as above.\nConsole.WriteLine(\">> Uncompleted tasks short:\");\nfilterData.ShowUnCompletedFromList(tasksData).ForEach(e => Console.WriteLine($\"Task: {e.Name} is {e.StatusDescription}.\"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:53:08.333",
"Id": "425391",
"Score": "0",
"body": "Hi, thanks for reviewing, can your explain more about **Make Status an Enum for ease of filtering** how enum is easier to filter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T06:59:04.400",
"Id": "425392",
"Score": "0",
"body": "Also is it a good practice to make a method to print the filtered data from **FilterData** class instead of the Program Class? as following code `public void PrintCompleted(string[] FilteredData)\n{\n// code to print\n}`\nThis code will be called in Main method as such\n`filterData.PrintCompleted(filterData.ShowCompleted(allData));`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T10:41:18.563",
"Id": "425404",
"Score": "1",
"body": "@AMJ I'm on my phone, I'll get back to you regarding first comment when I get to a PC. Regarding your second comment - yes, if you would need to print the data often or perhaps 'prettify' it etc. then go for a separate method. The `Main` method will be cleaner and you would promote code reusage (DRY)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T17:57:53.773",
"Id": "425445",
"Score": "1",
"body": "@AMJ I changed to code to implement an Enum. Let me know if you have more questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T19:21:57.083",
"Id": "425454",
"Score": "1",
"body": "Wow thanks a lot, using enum really was a game changer made the code easier to understand! Also I used Task.Name instead of Task[0] which look better as well. Is it possible to post my reviewed code here ? i dont know if the rules allows that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T20:08:40.083",
"Id": "425456",
"Score": "1",
"body": "@AMJ I'm not sure about the rules for posting modified code. If you keep the original question as-is and edit your solution below that, it would probably be ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T18:56:25.343",
"Id": "425534",
"Score": "0",
"body": "Thank you, I edited my solution, didnt use the lambda expression though because i didnt understand how to use it yet, I see the tutorials and documentations always explain delegates first then anonymous method which made me confuse, do you have any recommended reference?idk if u will be able to post here or send me message. I will mark this thread as answered. EDIT: thanks a lot for the review it really helped me boost my confidence in using classes and objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:23:29.047",
"Id": "425632",
"Score": "0",
"body": "@Iztoksson For future reference: no, it's not. Please take a look at [this link](https://codereview.stackexchange.com/help/someone-answers)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T21:14:41.147",
"Id": "220154",
"ParentId": "220153",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220154",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T20:29:45.660",
"Id": "220153",
"Score": "2",
"Tags": [
"c#",
"beginner",
"console",
"to-do-list"
],
"Title": "To do list mini project"
} | 220153 |
<p>This is a C++17 Either implementation for error handling.</p>
<ul>
<li>First intent is I want to improve myself.</li>
<li>Second intent is I want to create a more expressive solution than variant for exception free error handling.</li>
<li>Third intent is same type handling without extra variable. </li>
</ul>
<p><strong>to_left(...)</strong> and <strong>to_right(...)</strong> helper functions for specified side if both types are same in <strong>Result</strong>.</p>
<p><strong>Left</strong> and <strong>Right</strong> are helper structs for avoid additional bool usage in <strong>Result</strong>.</p>
<p><strong>result.hpp</strong></p>
<pre><code>#include <type_traits>
#include <variant>
namespace marklar::result
{
// Helper
template<typename Type>
struct Left;
template<typename Type>
struct Right;
template<typename>
struct is_left : std::false_type {};
template<typename Type>
struct is_left<Left<Type>> : std::true_type {};
template<typename Type>
inline constexpr bool is_left_v = is_left<Type>::value;
template<typename>
struct is_right : std::false_type {};
template<typename Type>
struct is_right<Right<Type>> : std::true_type {};
template<typename Type>
inline constexpr bool is_right_v = is_right<Type>::value;
template<typename Type>
inline constexpr Left<Type>
to_left(Type const & value) {
return Left<Type>{ value };
}
template<typename Type, typename std::enable_if_t<std::is_move_constructible_v<Type>, bool> = true>
inline constexpr Left<Type>
to_left(Type && value) {
return Left<Type>{ std::forward<Type>(value) };
}
template<typename Type>
inline constexpr Right<Type>
to_right(Type const & value) {
return Right<Type>{ value };
}
template<typename Type, typename std::enable_if_t<std::is_move_constructible_v<Type>, bool> = true>
inline constexpr Right<Type>
to_right(Type && value) {
return Right<Type>{ std::forward<Type>(value) };
}
template<typename Type>
struct Left {
Type const value_;
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Left<Type>, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& std::is_convertible_v<ParamType &&, Type>
, bool> = true>
constexpr Left(ParamType && value)
: value_ { std::forward<ParamType>(value) }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Left<Type>, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& !std::is_convertible_v<ParamType &&, Type>
, bool> = false>
constexpr explicit Left(ParamType && value)
: value_ { std::forward<ParamType>(value) }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Type, ParamType>
&& std::is_constructible_v<Type, ParamType const &>
&& !std::is_convertible_v<ParamType const &, Type>
, bool> = false>
explicit constexpr Left(Left<ParamType> const & other)
: value_ { other.value_ }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Type, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& std::is_convertible_v<ParamType &&, Type>
, bool> = true>
constexpr Left(Left<ParamType> && other)
: value_ { std::move(other).value_ }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Type, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& !std::is_convertible_v<ParamType &&, Type>
, bool> = false>
explicit constexpr Left(Left<ParamType> && other)
: value_ { std::move(other).value_ }
{}
};
template<typename Type>
struct Right {
Type const value_;
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Right<Type>, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& std::is_convertible_v<ParamType &&, Type>
, bool> = true>
constexpr Right(ParamType && value)
: value_ { std::forward<ParamType>(value) }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Right<Type>, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& !std::is_convertible_v<ParamType &&, Type>
, bool> = false>
constexpr explicit Right(ParamType && value)
: value_ { std::forward<ParamType>(value) }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Type, ParamType>
&& std::is_constructible_v<Type, ParamType const &>
&& !std::is_convertible_v<ParamType const &, Type>
, bool> = false>
explicit constexpr Right(Right<ParamType> const & other)
: value_ { other.value_ }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Type, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& std::is_convertible_v<ParamType &&, Type>
, bool> = true>
constexpr Right(Right<ParamType> && other)
: value_ { std::move(other).value_ }
{}
template <typename ParamType = Type,
typename std::enable_if_t<
!std::is_same_v<Type, ParamType>
&& std::is_constructible_v<Type, ParamType &&>
&& !std::is_convertible_v<ParamType &&, Type>
, bool> = false>
explicit constexpr Right(Right<ParamType> && other)
: value_ { std::move(other).value_ }
{}
};
template<typename LeftType, typename RightType>
struct Result {
static_assert(!(std::is_reference_v<LeftType> || std::is_reference_v<RightType>)
, "Result must have no reference alternative");
static_assert(!(std::is_void_v<LeftType> || std::is_void_v<RightType>)
, "Result must have no void alternative");
using LeftValue = Left<LeftType>;
using RightValue = Right<RightType>;
static constexpr size_t index_left_ = 0;
static constexpr size_t index_right_ = 1;
const std::variant<const LeftValue, const RightValue> variant_;
constexpr explicit Result(Result<LeftType, RightType> && other)
: variant_ { std::forward<Result<LeftType, RightType>>( other ).variant_ }
{}
template<typename ParamType>
constexpr explicit Result(ParamType const & value)
: variant_ {
[]() -> auto {
if constexpr (std::is_same_v<LeftType, ParamType> || is_left_v<ParamType>) {
return std::in_place_index<index_left_>;
} else if constexpr (std::is_same_v<RightType, ParamType> || is_right_v<ParamType>) {
return std::in_place_index<index_right_>;
}
}()
, [](ParamType const & value) -> auto {
if constexpr (std::is_same_v<LeftType, ParamType>) {
return to_left(value);
} else if constexpr (std::is_same_v<RightType, ParamType>) {
return to_right(value);
} else if constexpr (is_left_v<ParamType> || is_right_v<ParamType>) {
return value;
}
}(value)
}
{
static_assert((is_left_v<ParamType> || is_right_v<ParamType> || std::is_same_v<LeftType, ParamType> || std::is_same_v<RightType, ParamType>)
, "Result only setted alternatives can use");
if constexpr (!(is_left_v<ParamType> || is_right_v<ParamType>)) {
static_assert(!std::is_same_v<LeftType, RightType>
, "Result must have distinguish between alternatives");
}
}
template<typename ParamType>
constexpr explicit Result(ParamType && value) noexcept
: variant_ {
[]() -> auto {
if constexpr (std::is_same_v<LeftType, ParamType> || is_left_v<ParamType>) {
return std::in_place_index<index_left_>;
} else if constexpr (std::is_same_v<RightType, ParamType> || is_right_v<ParamType>) {
return std::in_place_index<index_right_>;
}
}()
, [](ParamType && value) -> auto {
if constexpr (std::is_same_v<LeftType, ParamType>) {
return to_left(std::forward<ParamType>(value));
} else if constexpr (std::is_same_v<RightType, ParamType>) {
return to_right(std::forward<ParamType>(value));
} else if constexpr (is_left_v<ParamType> || is_right_v<ParamType>) {
return std::forward<ParamType>(value);
}
}(std::forward<ParamType>(value))
}
{
static_assert((is_left_v<ParamType> || is_right_v<ParamType> || std::is_same_v<LeftType, ParamType> || std::is_same_v<RightType, ParamType>)
, "Result only setted alternatives can use");
if constexpr (!(is_left_v<ParamType> || is_right_v<ParamType>)) {
static_assert(!std::is_same_v<LeftType, RightType>
, "Result must have distinguish between alternatives");
}
}
template<typename TempType = LeftType>
inline constexpr TempType const &
left() const &
{
static_assert(std::is_convertible_v<TempType, LeftType>);
return std::get<index_left_>(variant_).value_;
}
template<typename TempType = LeftType>
constexpr TempType &&
left() &&
{
static_assert(std::is_convertible_v<TempType &&, LeftType>);
return std::move(std::get<index_left_>(variant_).value_);
}
template<typename TempType = LeftType>
constexpr LeftType
left_or(TempType && substitute) const &
{
static_assert(std::is_convertible_v<TempType &&, LeftType>);
return std::holds_alternative<const LeftValue>(variant_)
? this->left()
: static_cast<LeftType>(std::forward<TempType>(substitute));
}
template<typename TempType = LeftType>
constexpr LeftType &&
left_or(TempType && substitute) &&
{
static_assert(std::is_convertible_v<TempType &&, LeftType>);
return std::holds_alternative<const LeftValue>(variant_)
? std::move(this->left())
: static_cast<LeftType>(std::forward<TempType>(substitute));
}
template<typename TempType = RightType>
inline constexpr TempType const &
right() const &
{
static_assert(std::is_convertible_v<TempType, RightType>);
return std::get<index_right_>(variant_).value_;
}
template<typename TempType = RightType>
constexpr TempType &&
right() &&
{
static_assert(std::is_convertible_v<TempType &&, RightType>);
return std::move(std::get<index_right_>(variant_).value_);
}
template<typename TempType = RightType>
constexpr RightType
right_or(TempType && substitute) const &
{
static_assert(std::is_convertible_v<TempType &&, RightType>);
return std::holds_alternative<const LeftValue>(variant_)
? static_cast<RightType>(std::forward<TempType>(substitute))
: this->right();
}
template<typename TempType = RightType>
constexpr RightType &&
right_or(TempType && substitute) &&
{
static_assert(std::is_convertible_v<TempType &&, RightType>);
return std::holds_alternative<const LeftValue>(variant_)
? static_cast<RightType>(std::forward<TempType>(substitute))
: std::move(this->right());
}
template<typename Function>
inline constexpr auto left_map(Function const & function) &&
-> Result<decltype(function(std::get<index_left_>(variant_).value_)), RightType>
{
return std::holds_alternative<const LeftValue>(variant_)
? Result{ to_left(function(this->left())) }
: Result{ std::get<index_right_>(variant_) };
}
template<typename Function>
inline constexpr auto
right_map(Function const & function) const
-> Result<LeftType, decltype(function(std::get<index_right_>(variant_).value_))>
{
return std::holds_alternative<const LeftValue>(variant_)
? Result{ std::get<index_left_>(variant_) }
: Result{ to_right(function(this->right())) };
}
template<typename LeftLocal = LeftType, typename RightLocal = RightType>
inline constexpr auto
join() const
-> std::common_type_t<const LeftLocal, const RightLocal>
{
return std::holds_alternative<const LeftValue>(variant_)
? this->left()
: this->right();
}
inline constexpr operator bool() const noexcept
{
return std::holds_alternative<const LeftValue>(variant_);
}
};
} // namespace marklar::result
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <string>
#include "result.hpp"
// Tester function
auto tester(int result) {
using R = marklar::result::Result<int, std::string>;
return
(result < 0)
? R( marklar::result::to_right<std::string>("It is a negative number") )
: R( marklar::result::to_left<int>(result) )
;
}
int main()
{
std::cout << std::boolalpha;
std::cout << "Positive test\n";
auto resOk = tester(42);
if(resOk) {
std::cout << "data : " << std::to_string(resOk.left()) << "\n";
} else {
std::cout << "error : " << resOk.right() << "\n";
}
std::cout << std::endl;
std::cout << "Negative test\n";
auto resErr = tester(-1);
if(resErr) {
std::cout << "data : " << std::to_string(resErr.left()) << "\n";
} else {
std::cout << "error : " << resErr.right() << "\n";
}
std::cout << std::endl;
std::cout << "Same type test - lef side\n";
marklar::result::Result<int, int> resSameLeft(marklar::result::to_left(42));
std::cout << "Is store left data? : " << static_cast<bool>(resSameLeft) << "\n";
std::cout << "data : " << std::to_string(resSameLeft.left()) << "\n";
std::cout << std::endl;
std::cout << "Same type test - right side\n";
marklar::result::Result<int, int> resSameRight(marklar::result::to_right(24));
std::cout << "Is store left data? : " << static_cast<bool>(resSameRight) << "\n";
std::cout << "data : " << std::to_string(resSameRight.right()) << "\n";
std::cout << std::endl;
return 0;
}
</code></pre>
<p><a href="http://coliru.stacked-crooked.com/a/1e762691bfbaf227" rel="nofollow noreferrer">An working example</a></p>
<p><strong>My questions:</strong></p>
<ul>
<li>Any suggestion for better implementation?</li>
<li>Is the perfect forwarding correctly used?</li>
<li>Can be improve the usability?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:35:34.680",
"Id": "425377",
"Score": "2",
"body": "Title says “Result”, question body says “Either”, which is it? And what is it supposed to do? A usage example would be useful, ideally in a `main` so we can run your code without making changes. You are also missing `#include` statements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T10:19:08.423",
"Id": "425402",
"Score": "1",
"body": "You code seems good, but what is the intent? In particular, what's wrong with `variant`? What's wrong with exceptions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T11:13:29.810",
"Id": "425409",
"Score": "0",
"body": "- First intent is I want to improve myself.\n- Second intent is I want to create a more expressive solution than variant for exception free error handling.\n- Third intent is same type handling without extra variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:52:30.743",
"Id": "425418",
"Score": "1",
"body": "You could significantly improve usability by foregoing a new type for `Result`, and making `Left` and `Right` more widely applicable. Simply use `std::variant` directly, and add a template encoding a statically chosen option from a `std::variant`. Perhaps a few convenience aliases and/or functions, and you are done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:59:25.857",
"Id": "425420",
"Score": "0",
"body": "Why do you think it is improve the usability? Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T07:00:35.667",
"Id": "425853",
"Score": "0",
"body": "He's asking about the intent of the code, not your intent (although that's important too, but it's already mentioned at the top of the question). What is the code supposed to do and does it do so to your satisfaction or not?"
}
] | [
{
"body": "<p>It seems to me that you go a very long and very complicated way to do exactly what <code>std::variant</code> does; since you're tagging your question with <code>reinvent-the-wheel</code> it could be perfectly legitimate, but then you can't use <code>std::variant</code> inside your code, because you can't use a wheel to reinvent it.</p>\n\n<p>What is the <code>Either</code> monad? It's not necessarily about error handling, even if it indeed is often used as beefed-up version of <code>Maybe</code>. It only is a type that can hold one of two arbitrary types. Generalizing it into a <code>AnyTypeOf</code> monad, it would become a type that can hold one of several arbitrary types. That is to say, a <code>std::variant</code>. At least conceptually, you rely on a more powerful type (<code>std::variant</code>) to implement a less powerful one (<code>Either</code>) and need 350 lines of very complex code to do it.</p>\n\n<p>Here's my version of the <code>Either</code> monad:</p>\n\n<pre><code>template <typename T, typename U>\nusing Either = std::variant<T, U>;\n</code></pre>\n\n<p>I confess that it is a bit rudimentary, but it isn't very difficult to derive the whole monadic interface from it. But let's precise the semantics a bit, since we're looking for exception-free error handling:</p>\n\n<pre><code>template <typename T>\nusing SafeType = Either<std::string, T>;\n</code></pre>\n\n<p>Note that the convention is for the right type to hold the correct value, and the left type the error. Now we can write simple constructors-like functions:</p>\n\n<pre><code>using SafeInteger = Either<std::string, int>; /\n\nSafeInteger left(std::string error_message) { return SafeInteger(error_message); }\nSafeInteger right(int i) { return SafeInteger(i); }\n</code></pre>\n\n<p>If the type of the error message and of the value are the same, it's just a few characters longer:</p>\n\n<pre><code>using SafeString = Either<std::string, std::string>;\n\nSafeString left(std::string error_message) { return SafeString(std::in_place_index_t<0>(), error_message); }\nSafeString right(std::string str) { return SafeString(std::in_place_index_t<1>(), std::move(str)); }\n</code></pre>\n\n<p>The monadic scaffolding is also just a few lines long (I implemented it around <code>return</code> and <code>bind</code>, but <code>join</code> wouldn't have been more complex):</p>\n\n<pre><code>auto monadic_return(std::string str) {\n return right(str);\n}\n\ntemplate <typename Function>\nauto monadic_bind(const SafeString& str, Function func) {\n if (std::get_if<0>(&str)) return str;\n return func(std::get<1>(str));\n}\n</code></pre>\n\n<p>Complete example here: <a href=\"https://wandbox.org/permlink/Sj61MC1jbEO20T5B\" rel=\"nofollow noreferrer\">https://wandbox.org/permlink/Sj61MC1jbEO20T5B</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T12:31:47.153",
"Id": "425502",
"Score": "0",
"body": "Thanks for the answer. Yes, the solution is somewhere bloated. I tried to put everything to a class/struct. In your solution always right side is the intended result. I tried also this part to generalize, but after rethink this was unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T12:34:21.653",
"Id": "425503",
"Score": "0",
"body": "Of course, `std::string` can throw an exception on assignment / initialisation, which might throw a spanner in the works of that example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T12:45:33.933",
"Id": "425505",
"Score": "0",
"body": "@Deduplicator: a spanner? / right, it'd be more sensible to allocate a buffer on the stack but I feel lazy."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T11:13:26.407",
"Id": "220227",
"ParentId": "220155",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220227",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T21:19:58.393",
"Id": "220155",
"Score": "6",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"monads",
"variant-type"
],
"Title": "C++17 Either implementation for error handling"
} | 220155 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.