body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm solving this simple challenge:</p>
<p>Given a vector A with N unique elements greater than 0 and lower or equal than N+1, find the missing element. Example:</p>
<p>A = [1,3,2,5] -> missing number 4</p>
<p>A = [1,3,5,4] -> missing number 2</p>
<p>I've come to the following solution. I'm interested in thoughts and ideas on how to write it as expressive as possible:</p>
<p>Option 1, compact but not very expressive:</p>
<pre><code>int solution_1(std::vector<int> &v) {
sort(v.begin(), v.end());
for (std::size_t i = 0; i < v.size(); ++i) {
if (v[i] != i+1) return i+1;
}
return v.size()+1;
}
</code></pre>
<p>Option 2</p>
<pre><code>int solution_2(std::vector<int> &v) {
sort(v.begin(), v.end());
auto missing_element = std::find_if(
v.begin(), v.end(),
[index=1](auto& element) mutable {
if (element != index++) {
return true;
} else {
return false;
}
});
if (missing_element == v.end()) {
return v.size() + 1;
} else {
return *missing_element - 1;
}
}
</code></pre>
<p>Any ideas on how to improve this or how to make it more expressive? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T01:52:09.173",
"Id": "461945",
"Score": "0",
"body": "https://www.geeksforgeeks.org/find-the-missing-number/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T06:19:46.747",
"Id": "461957",
"Score": "0",
"body": "Your examples do not comply with your task description. Input lenght Is 4 therefore it should contain elements lower than 5. But they contain element 5. But it seems more like the task description Is a contradiction on Its own So maybe you copied the description wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T07:42:20.973",
"Id": "461968",
"Score": "0",
"body": "Wrong task description, I meant lower or equal"
}
] |
[
{
"body": "<p>You dont need the sorting. The vector contains numbers 1 to (n + 1) with one number omitted. If it wasnt omitted it would sum up to <code>(n+ 1)*(n+ 2)/ 2</code>. Sum the vector, subtract it from the full sum And what Is left over Is the number that was omitted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T09:59:57.710",
"Id": "461987",
"Score": "0",
"body": "But be sure that `N` is small enough for the sum not to overflow, or take other measures!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T11:33:41.187",
"Id": "462001",
"Score": "0",
"body": "Might be worth pointing Blasco at `std::accumulate()` for the actual summing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:00:09.077",
"Id": "462041",
"Score": "5",
"body": "@phipsgabler, I've just thought about it a bit further; if we calculate using an unsigned type large enough to represent `N`, then overflow should just cancel out and not be a problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:27:59.647",
"Id": "462045",
"Score": "0",
"body": "Oh yeah, I have much too bad an intuition for number theory, but I realize it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:12:52.533",
"Id": "462054",
"Score": "2",
"body": "@phipsgabler, it does need some care, because of the division. We need to subtract twice the sum from twice the expected sum, and divide that by two, or be cleverer about computing the expected sum by halving one of the arguments before the multiplication."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T08:23:18.750",
"Id": "235943",
"ParentId": "235930",
"Score": "8"
}
},
{
"body": "<p>Ignoring the fact that there's a better algorithm based on the sum of all elements (albiet somewhat less efficient once the input is sorted), there's plenty to review in the implementation of the functions.</p>\n\n<hr>\n\n<p>It's rude to the caller to modify the function's argument. I suggest accepting <code>v</code> by value, and the caller can choose whether to <code>std::move()</code> into the argument or whether it needs to retain its own copy.</p>\n\n<hr>\n\n<p>This pattern:</p>\n\n<pre><code>if (condition)\n return true;\nelse\n return false;\n</code></pre>\n\n<p>can always be simplified to</p>\n\n<pre><code>return condition;\n</code></pre>\n\n<hr>\n\n<p>Solution 2 depends on the order of execution of the predicate. It might be best to make this explicit, by passing <strong><code>std::execution::seq</code></strong> as a first argument. However, I'm not convinced that this imposes the order that's required; <code>std::find_if()</code> just isn't going to work in a standards-guaranteed manner with a mutable predicate.</p>\n\n<hr>\n\n<p>Both solutions miss the useful library function <strong><code>std::adjacent_find()</code></strong>.</p>\n\n<p>In our case, we're looking for the first element that's not followed by an element that's one higher in value:</p>\n\n<pre><code>auto const predicate = [](int a, int b){ return a + 1 != b; }\nsort(v.begin(), v.end());\nif (v.empty() || v.front() != 0) { return 1; } // first element was missing\nauto it = std::adjacent_find(v.begin(), v.end(), predicate);\nif (it == v.end()) { --it; } // last element was missing\nreturn *it + 1;\n</code></pre>\n\n<p>We can safely use this <code>std::adjacent_find()</code> with a parallel execution policy if we want.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:28:52.883",
"Id": "235962",
"ParentId": "235930",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "235943",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-20T23:56:21.670",
"Id": "235930",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Find the missing element in vector"
}
|
235930
|
<h1>Preliminaries</h1>
<p>I am working on a software that controls CAEN digitizer. The current step is to provide an ability to save/load configuration to/from an external source (hereafter - "config file"). I decided config file to be a simple text file and consisting of lines like this one:</p>
<pre><code>PARAMETER VALUE
</code></pre>
<p>For example, this is how the trigger threshold might have been set:</p>
<pre><code>CH_THRESHOLD 100
</code></pre>
<p>To compile a configuration for a digitizer from a config file my program should process a config file line by line and extract a pair parameter-value from each line if it is possible.</p>
<h2>Some notes</h2>
<p>Here are some principles I was following when writing the code:</p>
<ul>
<li><p>First of all, performance is not the point. The parsing is not intended to be fast because it is a single operation, i.e. it is performed only once in a relative large time interval. I mainly refer it to the <code>find_first_*</code> function calls below (I believe it is expensive to search for a character in that <code>const string</code>).</p>
</li>
<li><p>The parsing of a config file is the first step in the loading of a config file. It is about <em>syntax not semantics</em>; that is why at this stage all the values are strings (though semantically they could be numbers).</p>
</li>
</ul>
<h1>Program</h1>
<h2>struct ConfigUnit</h2>
<p>This structure represents a single pair parameter-value, so called a <em>config unit</em>.</p>
<pre><code>struct ConfigUnit
{
std::string parameter;
std::string value;
void Print() const
{
std::cout << "Parameter: '" << parameter << "'" "\tValue: '" << value << "'" << std::endl;
}
};
</code></pre>
<h2>Algorithm</h2>
<p>This is actually a little bit more generic algorithm than I need because it searches for <em>all</em> words in a line.</p>
<pre><code>const std::string alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
ConfigUnit GetConfigUnit( const std::string &line )
{
ConfigUnit unit;
std::vector< std::string > words;
//Find all alphanumerical words in the line
for( size_t startWord = line.find_first_of( alphanumeric ); startWord != std::string::npos; )
{
std::size_t endWord = line.find_first_not_of( alphanumeric, startWord );
words.push_back( line.substr( startWord, (endWord - startWord) ) );
startWord = line.find_first_of( alphanumeric, endWord );
}
if( words.size() == 2 )
{
unit.parameter = words.at(0);
unit.value = words.at(1);
}
return unit;
}
</code></pre>
<h1>Test</h1>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <fstream>
struct ConfigUnit
{
std::string parameter;
std::string value;
void Print() const
{
std::cout << "Parameter: '" << parameter << "'" "\tValue: '" << value << "'" << std::endl;
}
};
const std::string alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
ConfigUnit GetConfigUnit( const std::string &line )
{
ConfigUnit unit;
std::vector< std::string > words;
//Find all alphanumerical words in the line
for( size_t startWord = line.find_first_of( alphanumeric ); startWord != std::string::npos; )
{
std::size_t endWord = line.find_first_not_of( alphanumeric, startWord );
words.push_back( line.substr( startWord, (endWord - startWord) ) );
startWord = line.find_first_of( alphanumeric, endWord );
}
if( words.size() == 2 )
{
unit.parameter = words.at(0);
unit.value = words.at(1);
}
return unit;
}
int main()
{
std::ifstream file;
file.exceptions( std::fstream::failbit | std::fstream::badbit );
try
{
file.open( "dummy.txt" );
std::string line;
while( std::getline( file, line ) )
{
ConfigUnit unit = GetConfigUnit( line );
unit.Print();
}
file.close();
}
catch( const std::ifstream::failure &e )
{
if( file.eof() )
{
std::cout << "SUCCESS!\n";
}
else
{
std::cerr << "FAILURE! " << e.what() << std::endl;
}
}
return 0;
}
</code></pre>
<hr />
<p>As always, please critique, suggest, correct.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T06:32:13.980",
"Id": "461958",
"Score": "0",
"body": "As always, please post the exact, complete code, including the `#include` lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T06:53:49.813",
"Id": "461961",
"Score": "0",
"body": "@RolandIllig, Section **Test** updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T07:53:13.353",
"Id": "461969",
"Score": "0",
"body": "What happens when this if conditions evaluates to false `if( words.size() == 2 )`? Seems to me you return a value initialized `ConfigUnit`. Is that acceptable? Have you tested it? Consider using `std::isalpha` https://en.cppreference.com/w/cpp/string/byte/isalpha and `std::isdigit` https://en.cppreference.com/w/cpp/string/byte/isdigit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T08:21:33.337",
"Id": "461971",
"Score": "0",
"body": "@OliverSchonrock, Sorry for not documenting the code. If that condition evaluates to false it means that the line is syntactically incorrect (for example it contains one or three words, or no word at all; the line may be empty I think and I should have checked it at the beginning of a function). Handling that condition is another thread. The simplest way is just doing nothing so the function returns \"empty\" `ConfigUnit`. Then I do not process empty units."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T08:35:06.757",
"Id": "461972",
"Score": "0",
"body": "@OliverSchonrock, yes I thought about `std::isalpha` and `std::isdigit` functions, but isn't a fact I should explicitly loop over each character in a string then? I think in this case the code grows. Is something wrong with my approach using that `const string`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T08:57:59.407",
"Id": "461974",
"Score": "0",
"body": "consider `std::optional` instead of default value initiliazed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T09:05:04.760",
"Id": "461975",
"Score": "0",
"body": "re std::is_alpha. Yes it's frustrating what you want is `std::find_if` which takes a predicate. You can rewrite it in terms of that, and that would be a good exercise. TBH I find this aspect of C++ frustrating. Simple string munging needs more utility functions. I carry this around, feel free to have a look: https://github.com/oschonrock/toolbelt/blob/master/os/str.hpp particularly `split()` is relevant here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T09:10:25.590",
"Id": "461976",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103527/discussion-between-lrdprdx-and-oliver-schonrock)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T11:31:29.023",
"Id": "461998",
"Score": "0",
"body": "You could make the test self-contained if you read from a `std::istringstream` instead of from a file. At present, it's fragile, and also missing the content."
}
] |
[
{
"body": "<h2>General</h2>\n\n<p>Please ensure code compiles when posting it here. Or state a specific justification why it doesn't. (e.g. <code>Print()</code> was missing a <code><<</code>)</p>\n\n<h2>Putting it all together</h2>\n\n<p>There are quite a few specific comments under your question, which I have incorporated and added a few more in a proposed alternative solution below. It is quite different in approach, technique and style. None of these are \"must have\", but you can take your pick.</p>\n\n<h2>Parsing - how flexible</h2>\n\n<p>The most challenging part of any parsing is the question, how flexible / tolerant does it have to be? How consistent is the file format?</p>\n\n<p>Probably the simplest way to parse anything in C++ is to use <code>std::getline</code>. You were already using it, but were you aware of the second version? \nIf your parsing requirements are not very pedantic or in need of lightspeed performance you could use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\">the overloaded version</a> of <code>std::getline</code> which accepts a delimiter. I have shown below how that can be used. </p>\n\n<p>It makes the code <em>much</em> simpler, but it's slightly less tolerant. e.g. double spaced gap is not good. </p>\n\n<h2>Printing</h2>\n\n<p>The common idiom for making objects \"printable\" in C++ is to implement the <code><<</code> operator. This is best done using a <code>friend</code> function inside the class as shown. </p>\n\n<p>You should almost always use <code>'\\n'</code> and not <code>std::endl</code>, because the latter flushes the stream buffer, and that is often not needed. The <code>'\\n'</code> line ending will also adapt to the local machine. </p>\n\n<h2>Return \"nothing\"</h2>\n\n<p>In case of parsing failures, you were previously returning an \"empty\" <code>ConfigUnit</code> (correct term is <a href=\"https://en.cppreference.com/w/cpp/language/value_initialization\" rel=\"nofollow noreferrer\">value initialized</a>). I have shown a, probably cleaner alternative, using C++17 <code>std::optional</code>. </p>\n\n<p>Note how in <code>main()</code> I call <code>get_config_unit()</code> assign it to <code>maybe_unit</code> (a common idiom to use <code>maybe_*</code>) then check for the <code>-> bool</code> conversion <em>in the same if statement parens</em>. This is using the <a href=\"https://en.cppreference.com/w/cpp/language/if\" rel=\"nofollow noreferrer\">C++17 if statement \"init-statement\"</a>. Then I \"dereference\" the <code>std::optional<config_unit> maybe_unit</code> using the <code>*</code> operator. </p>\n\n<p>This all makes for very terse syntax and stops variables and the \"maybeness\" leaking out. </p>\n\n<h2>Use of exceptions</h2>\n\n<p>We can have a long debate about exceptions, there are several schools of thought. However, something I think most people agree on is that exceptions shouldn't be thrown during the \"normal, expected case\". They should be, well... \"exceptional\". </p>\n\n<p>Your code was throwing and catching the <code>eof</code> flag. i.e. every invocation of the programme was throwing. This is probably bad. </p>\n\n<p>I double checked the \"file bits\" and they didn't seem very useful to me, e.g. <code>bad_bit</code> doesn't get set if file is not found (perhaps the most common mode of failure), only <code>fail_bit</code> gets set. But that also gets set for <code>eof</code>. So I did it differently without exceptions. </p>\n\n<h2>RAII</h2>\n\n<p>Look it up: \"Resource acquisition is initialisation\" (and what is not stated, is that when objects go out of scope they clean up after themselves). It is a key C++ feature. It means you don't have to call <code>file.close()</code>. When the object goes out of scope at end of function its destructor will be called, which will clean up. </p>\n\n<p>This also means we don't have to have \"one common exit point\". Maybe that's what you were trying to achieve with your <code>try .. catch</code> block? It's not required. The right stuff just happens (because the <code>std::</code> classes are well written). </p>\n\n<p>This was my test file \"music.txt\":</p>\n\n<pre><code>CH_THRESHOLD 100\nba pram 314\nSOME-PARAM2 3000\nToo_many_spaces 999\n</code></pre>\n\n<p>And here is the suggested code:</p>\n\n<pre><code>#include <fstream>\n#include <functional>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nstruct config_unit {\n std::string parameter;\n std::string value;\n\n friend std::ostream& operator<<(std::ostream& ostream, const config_unit& cu) {\n return ostream << \"Parameter: '\" << cu.parameter << \"'\\t\"\n << \"Value: '\" << cu.value << \"'\" << '\\n';\n }\n};\n\nstd::optional<config_unit> get_config_unit(const std::string& line) {\n std::istringstream ss(line);\n std::string field;\n std::vector<std::string> fields;\n while (getline(ss, field, ' ')) fields.push_back(field);\n if (fields.size() != 2) return std::nullopt;\n return config_unit{fields[0], fields[1]};\n}\n\nint main() {\n std::string filename{\"music.txt\"};\n std::ifstream fstream(filename);\n if (fstream.fail()) {\n std::cerr << \"couldn't open file '\" << filename << \"\\n\";\n return EXIT_FAILURE;\n }\n std::string line;\n while (std::getline(fstream, line)) {\n if (auto maybe_unit = get_config_unit(line); maybe_unit) {\n std::cout << *maybe_unit;\n }\n }\n return EXIT_SUCCESS;\n}\n\n</code></pre>\n\n<p>And here is the output produced given the above input:</p>\n\n<pre><code>Parameter: 'CH_THRESHOLD' Value: '100'\nParameter: 'SOME-PARAM2' Value: '3000'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:04:08.580",
"Id": "235964",
"ParentId": "235940",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T06:25:24.863",
"Id": "235940",
"Score": "1",
"Tags": [
"c++",
"strings",
"configuration"
],
"Title": "Finding all alphanumerical words in a text line using std::string"
}
|
235940
|
<p>I have made a small Python script that will generate some test sets for my project.</p>
<p>The script generates 2 datasets with the same dimensions <code>n*m</code>. One contains binary values 0,1 and the other contains floats.</p>
<p>The script runs fine and generates the output I need, but if I want to scale to many dimensions the for-loop in <code>pick_random()</code> slows down my computation time.
How can I get rid of it? Perhaps with some array comprehension using <code>numpy</code>?</p>
<p>What throws my reasoning off is the <code>if-stmt</code>. Because the sampling should occur with a probability.</p>
<pre><code># Probabilities must sum to 1
AMOUNT1 = {0.6 : get_10_20,
0.4 : get_20_30}
AMOUNT2 = {0.4 : get_10_20,
0.6 : get_20_30}
OUTCOMES = [AMOUNT1, AMOUNT2]
def pick_random(prob_dict):
'''
Given a probability dictionary, with the first argument being the probability,
Returns a random number given the probability dictionary
'''
r, s = random.random(), 0
for num in prob_dict:
s += num
if s >= r:
return prob_dict[num]()
def compute_trade_amount(action):
'''
Select with a probability, depending on the action.
'''
return pick_random(OUTCOMES[action])
ACTIONS = pd.DataFrame(np.random.randint(2, size=(n, m)))
AMOUNTS = ACTIONS.applymap(compute_trade_amount)
</code></pre>
|
[] |
[
{
"body": "<p>Logically you have two different forms of chance. The 'top level' to pick between <code>AMOUNT1</code> and <code>AMOUNT2</code> and then the second form to pick the function <code>get_10_20</code> or <code>get_20_30</code>. This requires you to generate <em>two</em> random numbers. A pretty expensive operation.</p>\n\n<p>Secondly you're performing a cumulative sum each and every time you're looping through either <code>AMOUNT</code>. This is just a waste when you can do it once. And so you should aim to normalize your input data.</p>\n\n<p>Your input format is pretty poor, what if I want a 50/50 chance, or a 1:1:1 chance. To do so a cumulative sum would work best. But lets get your input to work in a meh way.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>AMOUNTS = [\n {\n 0.6 : get_10_20,\n 0.4 : get_20_30,\n },\n {\n 0.4 : get_10_20,\n 0.6 : get_20_30,\n }\n]\n\ndef normalize_input(amounts):\n by_value = {}\n for chances in amounts:\n for chance, value in chances.items():\n by_value.setdefault(value, 0)\n by_value[value] += chance / len(amounts)\n\n total_chance = 0\n output = {}\n for value, chance in by_value.items():\n total_chance += chance\n output[total_chance] = value\n return output\n</code></pre>\n\n<p>This works hunkydory and returns:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>{\n 0.5: get_10_20,\n 1.0: get_20_30,\n}\n</code></pre>\n\n<p><sub><strong>Note</strong>: untested, provided purely as an example.</sub></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def pick_random(chances):\n def inner(chance):\n for c in chances:\n if c >= chance:\n return chances[c]()\n return inner\n\n\nCHANCES = pd.DataFrame(np.random.random(size=(n, m)))\nAMOUNTS = CHANCES.applymap(pick_random(normalize_input(OUTCOMES)))\n</code></pre>\n\n<hr>\n\n<p>But do you really need that <code>for</code> loop? From the looks of it no, not really.<br>\nYou could change your input to integers and provide your chances in <em>cumulative ratios</em> so you could have:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>{\n 1: foo,\n 2: bar,\n 4: baz,\n}\n</code></pre>\n\n<p>From this you can then normalize to an array, and just index the array. Using <code>np.random.randint</code> rather than <code>np.random.random</code>. The array would look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>[foo, bar, baz, baz]\n</code></pre>\n\n<p>Which would make <code>inner</code> super simple:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def inner(chance):\n return chances[chance]()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T10:20:58.997",
"Id": "235951",
"ParentId": "235942",
"Score": "5"
}
},
{
"body": "<p>There are already tools for choosing elements from a collection with some given probabilities. In the standard library there is <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"noreferrer\"><code>random.choices</code></a>, which takes the values, the probabilities and the number of items you want:</p>\n\n<pre><code>import random\n\nvalues = [\"get_10_20\", \"get_20_30\"]\n#p = [0.5 * 0.6 + 0.5 * 0.4, 0.5 * 0.4 + 0.5 * 0.6]\np = [0.5, 0.5]\n\nn = 10\nrandom.choices(values, weights=p, k=n)\n# ['get_10_20', 'get_10_20', 'get_10_20', 'get_10_20', 'get_10_20', 'get_20_30',\n# 'get_20_30', 'get_20_30', 'get_10_20', 'get_10_20']\n</code></pre>\n\n<p>The other possibility is to use <a href=\"https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.choice.html#numpy.random.choice\" rel=\"noreferrer\"><code>numpy.random.choice</code></a> for this, which allows you to directly generate multi-dimensional data:</p>\n\n<pre><code>values = [\"get_10_20\", \"get_20_30\"]\np = [0.5, 0.5]\n\nn, m = 2, 3\nnp.random.choice(values, p=p, size=(n, m))\n# array([['get_10_20', 'get_10_20', 'get_20_30'],\n# ['get_20_30', 'get_20_30', 'get_20_30']], dtype='<U9')\n</code></pre>\n\n<p>Both approaches assume that you can combine the probabilities to a total probability for each value. The <code>numpy</code> method enforces that they sum to one, while the standard library <code>random</code> does that for you, if necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:44:36.453",
"Id": "462039",
"Score": "3",
"body": "+1 TIL `random.choices` takes some weights :O"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T11:00:31.527",
"Id": "235953",
"ParentId": "235942",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T08:07:39.817",
"Id": "235942",
"Score": "10",
"Tags": [
"python",
"performance",
"numpy"
],
"Title": "Generating large testing datasets"
}
|
235942
|
<p><em>Note</em>: this code will be run using portable WinPython 3.7.6.0 (Python 3.7.6, package list <a href="https://github.com/winpython/winpython/blob/master/changelogs/WinPython-64bit-3.7.6.0.md" rel="noreferrer">here</a>) on Win10x64. Installing new packages or upgrading the Python version are not an option for this project.</p>
<p><em>Disclosure</em>: this code is heavily inspired by Janos' excellent answer <a href="https://codereview.stackexchange.com/a/64722/52915">here</a>.</p>
<hr>
<p>I've written a piece of crap that's going to grow a lot over time, so I thought I'd get the base reviewed instead of posting everything at once. After all, at this stage I can still easily scrap half of it without problems. Current version has already been a great help.</p>
<h3>Situation</h3>
<p>At work, we keep a lot of datasheets from the parts we use. The library of parts ever grows and the datasheets are updated by the manufacturer without notice. For some of our parts we're obliged to keep the documentation in order and to prevent accidentally missing relevant docs we keep the datasheets of everything even remotely electrical (including push-buttons, LEDs, etc.). Oh, and in 3 languages per part. Which means I'm talking about a couple thousand documents for some of our suppliers.</p>
<p>Directory structure looks like this:</p>
<pre class="lang-none prettyprint-override"><code>|> current lib
|> supplier1
part1_de.pdf
part1_en.pdf
part1_nl.pdf
part2_de.pdf
part2_en.pdf
part2_nl.pdf
|> supplier2
</code></pre>
<p>Etc.</p>
<p>So if we have a <a href="https://mall.industry.siemens.com/mall/gb/ww/Catalog/Product/6ES7132-6BF01-0BA0" rel="noreferrer">6ES7132-6BF01-0BA0</a> from Siemens, we have:</p>
<pre class="lang-none prettyprint-override"><code>|> current lib
|> Siemens
6ES7132-6BF01-0BA0_de.pdf
6ES7132-6BF01-0BA0_en.pdf
6ES7132-6BF01-0BA0_nl.pdf
</code></pre>
<p>There are a couple of things that can go wrong with this:</p>
<ul>
<li>Missing files (only <code>_de</code> available instead of all 3).</li>
<li>Files not signed (<code>6ES71326BF010BA0_de.pdf</code> instead of <code>6ES7132-6BF01-0BA0_de.pdf</code>).</li>
<li>Invalid language-separator signs (older files have the language separated by <code>-</code> instead of <code>_</code>).</li>
<li>Old language (older Dutch files are named <code>_ne</code> instead of <code>_nl</code>).</li>
<li>Incorrect language (we're not interested in <code>_it</code>).</li>
<li>Incorrect/missing extension (all files should be <code>.pdf</code>).</li>
<li>Outdated documents (the older it gets, the more likely the data has been adjusted).</li>
</ul>
<p>This comes pretty exact, since the files are externally referenced on an unfortunately hard-coded list. Back-ups are taken care of, so the directory only has to contain recent files without worrying about the archive.</p>
<p>I'm still working on the first 2 points of that list (I can check against a CSV containing all the items) but that's for next version. Those are out-of-scope for this question but perhaps something to keep in mind. The rest is covered in this one by explicitly white-listing the last couple of characters.</p>
<h3>Approach</h3>
<p>Set a couple of globals, create a white-list, iterate over the files and classify each file as either <code>'Correct'</code>, <code>'Invalid'</code> or <code>'OutOfDate'</code> (the latter based on time modified (mtime, creation date is unreliable). Return both the results and the total count of checked files. Print in a readable format.</p>
<p>Currently both <code>result</code> and <code>count</code> are used for manual reference, later the <code>result</code> will be passed to the next function. One supplier will be checked at a time. Current code considers files older than 90 days out-of-date. Actual list of suppliers is 20+ entries. I'm currently not automatically iterating over all suppliers because for some different standards apply. Those are exempt (come to think of it, perhaps I should put those on a blacklist and iterate over the list but that still seems risky). Current code works as expected for this revision.</p>
<h3>Code</h3>
<pre><code>import os
import pprint
import time
MAX_AGE = 90
# 60 seconds in a minute, 60 minutes in an hour, 24 hours in a day
MINUTES = 60
HOURS = 60*MINUTES
DAYS = 24*HOURS
PATH_TO_FILES = "path/to/local/copy/of/lib/"
EXT = ".pdf"
WHITELIST = ['_nl' + EXT, '_en' + EXT, '_de' + EXT]
SUPPLIERS = ['Siemens', 'IFM']
def classify_files(basedir, limit):
"""
Classify files in *basedir* not modified within *limit*
:param basedir: directory to search
:param limit: timelimit for treshold
Return result (dict) and count (int).
"""
report = {
'Correct' : [],
'Invalid' : [],
'OutOfDate': []
}
mod_time_limit = time.time() - limit
count = 0
for filename in os.listdir(basedir):
path = os.path.join(basedir, filename)
count += 1
if not filename[-7:] in WHITELIST:
report['Invalid'].append(filename)
elif os.path.getmtime(path) < mod_time_limit:
report['OutOfDate'].append(filename)
else:
report['Correct'].append(filename)
return report, count
def main():
for supplier in SUPPLIERS:
print("\n{}:".format(supplier))
result, count = classify_files(
PATH_TO_FILES + supplier,
MAX_AGE * DAYS
)
pprint.pprint(result)
print("{} files checked".format(count))
if __name__ == '__main__':
main()
</code></pre>
<h3>Issues</h3>
<p>One of the most glaring issues is the hardcoded <code>7</code> here:</p>
<pre><code>if not filename[-7:] in WHITELIST:
</code></pre>
<p>I'm not a fan of entire <code>if/else</code> structure. Feels off. And I should probably use a different method of returning the result. How I handle times feels hacky, but it's a lot more straight-forward than converting and messing-around with <code>datetime</code>. I should probably be using <code>Correct</code>/<code>Incorrect</code> or <code>Valid</code>/<code>Invalid</code> instead of the current <code>Correct</code>/<code>Invalid</code> combination, naming is hard. The count looks ugly (perhaps summing the length of the resulting lists would be better), and I'm not sure what validations and exception-handlers would make sense here.</p>
<p>I know the keys of <code>report</code> are probably not according to PEP8 and the extra white-space definitely isn't, but it looks better this way.</p>
<p>Speed is currently not a concern. Naming, maintainability, readability and extendability are priority. Currently configuration by globals is fine, when it's clear what the final thing is going to look like they will be replaced by either config-files or arguments.</p>
<p>Complicated one-liners are sub-optimal. My Python might be good enough to understand it, but it would be preferable if colleagues less proficient can follow it as well.</p>
|
[] |
[
{
"body": "<h3>Towards better functionality and data structures</h3>\n\n<ul>\n<li><p>prefer <code>f-string</code> formatting over multiple strings <code>+</code>- concatenation:</p>\n\n<pre><code>f'_nl{EXT}', f'_en{EXT}', f'_de{EXT}'\n</code></pre></li>\n<li><p>define constants <code>WHITELIST</code> and <code>SUPPLIERS</code> as immutable data structures to avoid potential/accidental compromising by subsequent callers. <br><strong>Furthermore</strong>, making <code>WHITELIST</code> a tuple helps solving the mentioned issue \"<code>filename[-7:] in WHITELIST</code>\" (see next points below)</p>\n\n<pre><code>WHITELIST = (f'_nl{EXT}', f'_en{EXT}', f'_de{EXT}')\nSUPPLIERS = ('Siemens', 'IFM')\n</code></pre></li>\n<li><p>consistent naming <code>Correct/Incorrect</code> or <code>Valid/Invalid</code> seems sound and perceivable. I would go with one of them</p></li>\n</ul>\n\n<hr>\n\n<p><strong><code>classify_files</code></strong> function:</p>\n\n<ul>\n<li><p>instead of hard-coded slicing in <code>if not filename[-7:] in WHITELIST</code> - use convenient <a href=\"https://docs.python.org/3/library/stdtypes.html#str.endswith\" rel=\"nofollow noreferrer\"><code>str.endswith</code></a> approach since we've already prepared the appropriate <code>WHITELIST</code> tuple:</p>\n\n<pre><code>...\nif not filename.endswith(WHITELIST):\n report['Incorrect'].append(filename)\n</code></pre></li>\n<li><p>replace redundant <code>count = 0</code> and subsequent increment <code>count += 1</code> with <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> feature starting from <code>1</code>:</p>\n\n<pre><code>for i, filename in enumerate(os.listdir(basedir), 1):\n ... \n</code></pre>\n\n<p>After the loop has completed the variable (counter) <code>i</code> will contain the number of iterated/checked files and can be easily used/referenced in <em>return</em> statement <code>return report, i</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T12:36:31.397",
"Id": "462020",
"Score": "0",
"body": "Ah, much better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T12:11:19.473",
"Id": "235957",
"ParentId": "235952",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Your code is small, but there's a lot going on that I find it hard to understand. Given that this is just the beginning, the complexity of the code will just increase as time goes on.</li>\n<li><p>I found the large amount of globals to hinder readability, as each time I came across another I had to scroll to the top of the code to find out what it is.</p>\n\n<p>Whilst I prefer not to have globals and hide them away in classes. I think there are two options when using a class:</p>\n\n<ul>\n<li>Make a <code>Classifier</code> class that just has those globals defined on the class as class variables.</li>\n<li>Make a <code>Classifier</code> class that is provided the values at instantiation. And utilize <code>typing</code> to convey what the values contain.</li>\n</ul></li>\n<li><p>Whilst I find a class helps reduce complexity. It should also increase general maintainability and readability. Currently your function is a bug/feature hotspot, and when you add more classifiers to the function the complexity will only increase.</p>\n\n<p>Splitting the different validation checks into their own methods, or functions, helps break down the function and make the code small palatable chunks. And so increases readability.</p>\n\n<p>It also increases maintainability as when you need to add additional functionality to the function, you instead have a small self-contained function. Which is simpler to re-learn, when coming back to the function after some time. In the changes I made the validation checks each became a method containing a single <code>if</code> and <code>return</code>.</p>\n\n<blockquote>\n <p>I'm currently not automatically iterating over all suppliers because for some different standards apply.</p>\n</blockquote>\n\n<p>This also increases customization, as you can easily define multiple classes with the different validation checks. Utilizing either inheritance or mixins to simplify the code.</p></li>\n<li><p>Since the <code>Classifier</code> class will have lots of functions that will be called in the same way, I would opt to make a <code>BaseClassifier</code> class that magically handles everything.</p>\n\n<ul>\n<li>Since I would pass values in at instantiation I would define the <code>__init__</code> and simply assign the value to the instance.</li>\n<li>Since we'll have lots of functions, to reduce the amount of WET I would automagically find the functions to run using <code>dir</code> and <code>getattr</code>.</li>\n<li>Since the functions will all be called in the same way, defining a simple <code>validate</code> function can reduce the amount of code to write on each classifier.</li>\n</ul></li>\n<li><p>I personally am not a fan of magic strings for your categories.</p>\n\n<p>Rather than magic strings you can use <code>enum.Enum</code> or <code>enum.IntFlag</code> to better categorize your paths.</p>\n\n<ul>\n<li><code>enum.Enum</code> can be used exactly as you are now. This means that you can only have one error per path.</li>\n<li><p><code>enum.IntFlag</code> allows you to report multiple errors at the same time.</p>\n\n<p>I have a personal distaste for programs that hide errors from me. It means that you have to run the checker multiple times fixing the previous errors to only then get more. Rather than stating all the problems and fixing everything in one swoop.</p></li>\n</ul></li>\n<li><p><code>os.path</code> is largely obsolete by <code>pathlib</code>. Changing your code to use <code>pathlib</code> increases readability of the validators as you can easily validate if the extension is correct using:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if path.suffix == EXT:\n</code></pre>\n\n<p>It also allows you to easily join paths using <code>path / str</code>.</p></li>\n<li><p>I would suggest using <code>logging</code> rather than <code>print</code>. This sets up your application to have correct and easily togglable debugging output. It also means that this can be turned off when in production when not debugging.</p></li>\n<li>I would prefer to have <code>WHITELIST</code> be a set. I see no need for it to be a list.</li>\n</ul>\n\n<p>Now, my solution is hands down more complex. It's adding <code>enum</code>, a <code>Classifier</code> class, a <code>BaseClassifier</code> class and is a significant increase in lines. And so it is susceptible to be an increase in maintainability costs. However in my opinion the benefits that I've described above outweigh the additional costs.</p>\n\n<blockquote>\n <p>Currently both result and count are used for manual reference, later the result will be passed to the next function.</p>\n</blockquote>\n\n<p>Given that you've not shown how the results are being used I have provided two <code>classify_files</code> functions. One that outputs the same as your currently expecting. And one that output all the paths grouped by all their errors.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import enum\nimport logging\nimport os\nimport pathlib\nimport pprint\nimport time\n\nfrom typing import Any, Callable, ClassVar, Dict, Generic, Iterator, List, Optional, Set, Tuple, TypeVar\n\nTItem = TypeVar('TItem')\nTFlag = TypeVar('TFlag')\n\n\nMAX_AGE = 90\n\n# 60 seconds in a minute, 60 minutes in an hour, 24 hours in a day\nMINUTES = 60\nHOURS = 60*MINUTES\nDAYS = 24*HOURS\n\nPATH_TO_FILES = pathlib.Path(\"./lib\")\nEXT = \".pdf\"\nLANGUAGES = {'_nl', '_en', '_de'}\nSUPPLIERS = ['Siemens', 'IFM']\n\n\nclass BaseClassifier(Generic[TItem, TFlag]):\n \"\"\"\n Classifier metaclass to ease classifying values.\n\n This is a fairly magical class that allows setting the required state.\n It also allows validating against all validators starting with `_valid_`,\n without having to manually call each of them.\n \"\"\"\n DEFAULT: ClassVar[TFlag]\n\n def __init__(self, **kwargs: Any):\n \"\"\"\n Initialize classifier state.\n\n Values must be passed as keywords so they can be set correctly\n on the instance. For each keyword provided an attribute with the\n same name is created and has the value set to the keywords value.\n\n For example we can set the attribute `foo` by passing it as a keyword.\n\n >>> bc = BaseClassifier(foo='bar')\n >>> bc.foo\n 'bar'\n \"\"\"\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n def _get_validators(self) -> List[Callable[[TItem], Optional[TFlag]]]:\n \"\"\"\n Get all validators on the instance.\n\n All validators must start `_valid_` and so we loop through all\n the names of the attributes on the instance, via `dir`, and\n filter to ones that start with `_valid_`. For each name that\n starts with `_valid_` we return the value of the attribute.\n\n For example `Classifier` has the following validators.\n Note that the test is for the function names, but it actually\n returns the full fat function. Just getting the test to work\n with the full fat functions is a PITA.\n\n >>> validators = Classifier()._get_validators()\n >>> [validator.__name__ for validator in validators]\n ['_valid_age', '_valid_extension', '_valid_language']\n \"\"\"\n return [\n getattr(self, name)\n for name in dir(self)\n if name.startswith('_valid_')\n ]\n\n def validate(self, items: Iterator[TItem]) -> Iterator[Tuple[TFlag, TItem]]:\n \"\"\"\n Validate input against the instance's validators.\n\n For each provided item we run all validators to build a complete \n picture of any problems with the item. Once all validators have\n ran we output the item as is, but with any statuses that the\n validators have assigned to it.\n\n For example the test below shows that 123_it.txt has both an\n invalid language and file type as it's flag is FileState.INVALID.\n\n >>> classifier = Classifier(\\\n ext=EXT,\\\n languages=LANGUAGES,\\\n time_limit=time.time() - (MAX_AGE * DAYS),\\\n )\n >>> list(classifier.validate([pathlib.Path('./lib/IFM/123_it.txt')]))\n [(<FileState.INVALID: 3>, WindowsPath('lib/IFM/123_it.txt'))]\n \"\"\"\n functions = self._get_validators()\n for item in items:\n ret = self.DEFAULT\n for function in functions:\n output = function(item)\n if output is not None:\n ret |= output\n yield ret, item\n\n\nclass FileState(enum.IntFlag):\n \"\"\"States that files can be in.\"\"\"\n CORRECT = 0\n EXTENSION = enum.auto()\n LANGUAGE = enum.auto()\n OUT_OF_DATE = enum.auto()\n\n # A convenience for your old categories.\n # only used in the backward-compatible `classify_paths`\n INVALID = EXTENSION | LANGUAGE\n\n\nclass Classifier(BaseClassifier[pathlib.Path, FileState]):\n \"\"\"Classifiers for files.\"\"\"\n __slots__ = ('ext', 'languages', 'time_limit')\n DEFAULT: ClassVar[FileState] = FileState.CORRECT\n\n ext: str\n languages: Set[str]\n time_limit: int\n\n def _valid_extension(self, path: pathlib.Path) -> Optional[FileState]:\n \"\"\"Validate if path has correct extension.\"\"\"\n if path.suffix != self.ext:\n return FileState.EXTENSION\n\n def _valid_language(self, path: pathlib.Path) -> Optional[FileState]:\n \"\"\"Validate if path has correct language.\"\"\"\n if path.stem[-3:] not in self.languages:\n return FileState.LANGUAGE\n\n def _valid_age(self, path: pathlib.Path) -> Optional[FileState]:\n \"\"\"Validate if file is out of date.\"\"\"\n if path.stat().st_mtime < self.time_limit:\n return FileState.OUT_OF_DATE\n\n\n# Simpler method of grouping categories\n# This utilizes the `enum` we defined earlier.\ndef classify_paths_simple(\n classifier: BaseClassifier,\n paths: Iterator[pathlib.Path],\n) -> Tuple[Dict[FileState, List[pathlib.Path]], int]:\n \"\"\"Group classifications.\"\"\"\n report: Dict[FileState, List[pathlib.Path]] = {}\n for count, (state, path) in enumerate(classifier.validate(paths)):\n report.setdefault(state, []).append(path)\n return report, count\n\n\n# Complex as I make the output exactly the same as the question.\ndef classify_paths(\n classifier: BaseClassifier,\n paths: Iterator[pathlib.Path],\n) -> Tuple[Dict[str, List[pathlib.Path]], int]:\n \"\"\"Group classifications into generic custom types.\"\"\"\n report: Dict[str, List[pathlib.Path]] = {\n 'Correct': [],\n 'Invalid': [],\n 'OutOfDate': [],\n }\n for count, (state, path) in enumerate(classifier.validate(paths)):\n if state == FileState.CORRECT:\n key = 'Correct'\n elif state & FileState.INVALID:\n key = 'Invalid'\n else:\n key = 'OutOfDate'\n report[key].append(path)\n return report, count\n\n\ndef main():\n classifier = Classifier(\n ext=EXT,\n languages=LANGUAGES,\n time_limit=time.time() - (MAX_AGE * DAYS),\n )\n for supplier in SUPPLIERS:\n logging.debug(supplier)\n # Also use classify_paths_simple to contrast the outputs\n result, count = classify_paths(\n classifier,\n (PATH_TO_FILES / supplier).iterdir()\n )\n pprint.pprint(result)\n logging.info(\"%s files checked\", count)\n\nif __name__ == '__main__':\n main()\n\n import doctest\n doctest.testmod()\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:35:48.473",
"Id": "235960",
"ParentId": "235952",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235960",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T10:57:11.970",
"Id": "235952",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "File classifier based on extension and date modified"
}
|
235952
|
<p>I've written up a key-value store that runs on SSTables in python. </p>
<pre><code>import json
import tempfile
import time
import uuid
from contextlib import contextmanager
import attr
from sortedcontainers import SortedDict
TOMBSTONE = str(uuid.uuid5(uuid.NAMESPACE_OID, 'TOMBSTONE')).encode('ascii')
def make_new_segment():
fd, path = tempfile.mkstemp(prefix=str(time.time()), suffix="txt")
return Segment(path=path, fd=fd)
def search_entry_in_segment(segment, key, offset):
with segment.open("r"):
entry = segment.search(key, offset)
if entry is not None:
return entry
return None
def chain_segments(s1, s2):
with s1.open("r"), s2.open("r"):
while not s1.reached_eof() and not s2.reached_eof():
if s1.peek_entry().key < s2.peek_entry().key:
yield s1.read_entry()
elif s1.peek_entry().key == s2.peek_entry().key:
yield s2.read_entry() # segment_2 was produced after segmented_i, so we take the more recent entry
s1.read_entry()
else:
yield s2.read_entry()
while not s1.reached_eof():
yield s1.read_entry()
while not s2.reached_eof():
yield s2.read_entry()
class UnsortedEntries(Exception):
def __init__(self, *args, **kwargs):
super(UnsortedEntries, self).__init__(args, kwargs)
class Segment:
"""
Segment represent a sorted string table (SST).
All k-v pairs will be sorted by key, with no duplicates
"""
def __init__(self, path, fd=None):
self.path = path
self.fd = fd
self.previous_entry_key = None
self.size = 0
def search(self, query, offset=0):
self.fd.seek(offset)
while not self.reached_eof():
entry = self.read_entry()
if entry.key == query:
return entry
return None
def __len__(self):
return self.size
def reached_eof(self):
cur_pos = self.fd.tell()
maybe_entry = self.fd.readline()
self.fd.seek(cur_pos)
return maybe_entry == ""
def peek_entry(self):
cur_pos = self.fd.tell()
entry = self.read_entry()
self.fd.seek(cur_pos)
return entry
def entries(self):
while not self.reached_eof():
entry = self.fd.readline()
yield SegmentEntry.from_dict(json.loads(entry))
def offsets_and_entries(self):
while not self.reached_eof():
offset = self.fd.tell()
entry = self.fd.readline()
yield offset, SegmentEntry.from_dict(json.loads(entry))
def add_entry(self, entry):
key = entry[0]
value = entry[1]
if not isinstance(value, str):
raise Exception("value needs to be a string, but {value} is not")
if self.previous_entry_key is not None and self.previous_entry_key > key:
raise UnsortedEntries(f"Tried to insert {key}, but previous entry {self.previous_entry_key} is bigger")
json_str = json.dumps({entry[0]: entry[1]})
self.previous_entry_key = key
pos = self.fd.tell()
self.fd.write(json_str)
self.fd.write("\n")
self.size += 1
return pos
def read_entry(self):
entry_dict = json.loads(self.fd.readline())
return SegmentEntry.from_dict(entry_dict)
def seek(self, pos):
self.fd.seek(pos)
@contextmanager
def open(self, mode):
try:
self.fd = open(self.path, mode)
yield self
finally:
self.fd.close()
self.previous_entry_key = None
@attr.s(frozen=True)
class KeyDirEntry:
offset = attr.ib()
segment = attr.ib()
@attr.s(frozen=True)
class SegmentEntry:
key = attr.ib()
value = attr.ib()
@classmethod
def from_dict(cls, d):
key, value = d.popitem()
return cls(key, value)
@classmethod
def from_pair(cls, pair):
key, value = pair
return cls(key, value)
def to_dict(self):
return {self.key: self.value}
def to_pair(self):
return self.key, self.value
def __getitem__(self, item):
if item == 0:
return self.key
elif item == 1:
return self.value
raise Exception("SegmentEntry can be indexed only by 0 (key) or 1 (value)")
class DB:
def __init__(self, max_inmemory_size=1000, sparse_offset=10, segment_size=10):
"""
:param max_inmemory_size: maximum number of entries to hold in memory.
:param sparse_offset: frequency of key offsets kept in memory. (Eg: if `sparse_offset=5`, one key offset is kept
in memory for every 5 entries.)
:param segment_size: maximum number of entries in a given segment.
"""
self._mem_table = MemTable(max_inmemory_size)
self.max_inmemory_size = max_inmemory_size
self._immutable_segments = []
self._sparse_memory_index = SortedDict()
self.sparse_offset = sparse_offset
self.segment_size = segment_size
def segment_count(self):
return len(self._immutable_segments)
def get(self, item):
if item in self._mem_table:
value = self._mem_table[item]
if value == TOMBSTONE:
return None
return value
closest_key = next(self._sparse_memory_index.irange(maximum=item, reverse=True))
segment, offset = self._sparse_memory_index[closest_key].segment, self._sparse_memory_index[closest_key].offset
entry = search_entry_in_segment(segment, item, offset)
if entry is not None:
return entry.value
segment_index = self._immutable_segments.index(segment)
for next_segment in self._immutable_segments[segment_index + 1:]:
entry = search_entry_in_segment(next_segment, item, offset)
return entry.value
return None
def __getitem__(self, item):
value = self.get(item)
if value is None:
raise RuntimeError(f"no value found for {item}")
return value
def __setitem__(self, key, value):
if self._mem_table.capacity_reached():
segment = self._write_to_segment()
self._immutable_segments.append(segment)
if len(self._immutable_segments) >= 2:
merged_segments = self.merge(*self._immutable_segments)
self._immutable_segments = merged_segments
self._sparse_memory_index.clear()
count = 0
for segment in self._immutable_segments:
with segment.open("r"):
for offset, entry in segment.offsets_and_entries():
if count % self.sparse_offset == 0:
self._sparse_memory_index[entry.key] = KeyDirEntry(offset=offset, segment=segment)
count += 1
self._mem_table.clear()
self._mem_table[key] = value
else:
self._mem_table[key] = value
def __delitem__(self, key):
if self.get(key) is not None:
self._mem_table[key] = TOMBSTONE
else:
raise Exception(f"{key} does not exist in the db; thus, cannot delete")
def __contains__(self, item):
return self.get(item) is not None
def merge(self, s1, s2):
merged_segments = []
def merge_into(new_segment, chain_gen):
count = 0
with new_segment.open("w+"):
for entry in chain_gen:
new_segment.add_entry(entry)
count += 1
if count == self.segment_size:
merge_into(make_new_segment(), chain_gen)
break
if len(new_segment) >= 1: # just in case the generator doesn't yield anything
merged_segments.append(new_segment)
merge_into(make_new_segment(), chain_segments(s1, s2))
return merged_segments[::-1]
def _write_to_segment(self):
segment = make_new_segment()
with segment.open("w") as segment:
count = 0
for (k, v) in self._mem_table:
if v != TOMBSTONE: # if a key was deleted, there's no need to put in the segment
offset = segment.add_entry((k, v))
if count % self.sparse_offset == 0:
self._sparse_memory_index[k] = KeyDirEntry(offset=offset, segment=segment)
count += 1
return segment
def load_from_data(self):
pass
class MemTable:
def __init__(self, max_size):
self._entries = SortedDict()
self.max_size = max_size
def __setitem__(self, key, value):
self._entries[key] = value
def __len__(self):
return len(self._entries)
def __getitem__(self, item):
return self._entries[item]
def clear(self):
self._entries.clear()
def __contains__(self, item):
return item in self._entries
def capacity_reached(self):
return len(self._entries) >= self.max_size
def __iter__(self):
for key, value in self._entries.items():
yield (key, value)
</code></pre>
<p>Some tests:</p>
<pre><code>from sst_engine.sst_engine import DB
import pytest
def test_simple_db_search():
db = DB(max_inmemory_size=10)
db["foo"] = "bar"
assert db["foo"] == "bar"
def test_deletion():
db = DB(max_inmemory_size=10)
db["foo"] = "bar"
del db["foo"]
with pytest.raises(Exception):
_ = db["foo"]
def test_db_search_with_exceeding_capacity():
db = DB(max_inmemory_size=2)
db["k1"] = "v1"
db["k2"] = "v2"
db["k3"] = "v3"
assert db["k1"] == "v1"
assert db["k2"] == "v2"
assert db["k3"] == "v3"
def test_db_search_with_multiple_segments():
db = DB(max_inmemory_size=2, segment_size=2, sparse_offset=5)
# all unique k-v pairs
kv_pairs = [("k" + str(i), "v" + str(i)) for i in range(5)]
for (k, v) in kv_pairs:
db[k] = v
assert db.segment_count() == 2
for (k, v) in kv_pairs:
assert db[k] == v
def test_db_search_with_single_merged_segment():
db = DB(max_inmemory_size=2, segment_size=2, sparse_offset=5)
kv_pairs = [("k1", "v1"), ("k2", "v2"), ("k1", "v1_1"), ("k2", "v2_2"), ("k3", "v3")]
for (k, v) in kv_pairs:
db[k] = v
assert db.segment_count() == 1
assert db["k1"] == "v1_1"
assert db["k2"] == "v2_2"
def test_db_search_for_for_deleted_key():
db = DB(max_inmemory_size=2, segment_size=2)
db["k1"] = "v1"
del db["k1"]
db["k2"] = "v2"
with pytest.raises(Exception):
_ = db["k1"]
def test_db_contains_key():
db = DB(max_inmemory_size=2, segment_size=2)
db["k1"] = "v1"
db["k2"] = "v2"
db["k3"] = "v3"
del db["k2"]
assert "k1" in db
assert "k2" not in db
def test_db_deletion_on_nonexistent_key():
db = DB(max_inmemory_size=2, segment_size=2)
with pytest.raises(Exception):
_ = db["k1"]
</code></pre>
<p>I'd love some pointers as to how I can make this more efficient and more idiomatic! </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T11:50:12.777",
"Id": "235956",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"database"
],
"Title": "Python database powered by SSTable"
}
|
235956
|
<p>This is a big script with a GUI basically. I have 4 page classes, that are children of the main Wizard class. I do most of the threading in <code>Step3</code> and the scripts are simple - creating a new user, editing reg files and installing chrome. Everything works perfectly here, until the main window is dragged - then the app lags a lot and needs to be re-launched.</p>
<p>Also I use some of my own written packages and if need be I can include them also.
So I believe the problem is with <code>tkinter</code> and <code>threading</code>, as is usual in these cases. I believe the problem is in the <code>class Step3</code></p>
<p>I would like some help with the lagging of the main window, or maybe entirely different but better options for doing stuff like this exists?</p>
<pre><code>import os
import json
import threading
import ctypes
import sys
import subprocess
import queue
import shutil
import elevate
import tkinter as tk
from tkinter import messagebox
from tkinter import font as tkfont
from tkinter import ttk
from PIL import Image, ImageTk
import webbrowser
from pack import newuser
from pack import alluserlist
from pack import switchuser
from pack import editreg
from pack import install
from pack import autologin
from pack import extension_editreg
class Wizard(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
data = {"COMPLETED": False, "STARTED": True, "USER CREATED": False, "AFTER RESTART": False}
print('starting')
if not os.path.exists('C:\\Users\\Public\\app'):
if getattr(sys, 'frozen', False):
# frozen
path_to_file = os.path.dirname(sys.executable)
else:
# unfrozen
path_to_file = os.path.dirname(os.path.realpath(__file__))
os.mkdir('C:\\Users\\Public\\app')
self.geometry("750x400+520+235")
self.maxsize(750, 500)
self.minsize(750, 500)
# fonts
self.font_big = tkfont.Font(family='Malgun Gothic', size=18, weight="bold")
self.font_small = tkfont.Font(family='Malgun Gothic', size=11)
self.font_smaller = tkfont.Font(family='Malgun Gothic', size=7)
self.title("setup")
try:
self.iconbitmap("icon.ico")
except:
self.iconbitmap("icon")
self.current_step = None
self.steps = [Step1(self, controller=self), Step2(self, controller=self), Step3(self, controller=self),
Step4(self, controller=self)]
self.button_frame = tk.Frame(self, bg="#cfcfcf", bd=1)
self.button_frame.place(width=750, height=60, x=0, y=440)
self.back_button = tk.Button(self.button_frame, text="<< Back", width=10, height=1, command=self.back)
self.next_button = tk.Button(self.button_frame, text="Next >>", width=10, height=1, command=self.next)
self.finish_button = tk.Button(self.button_frame, text="Finish", width=10, height=1, command=self.finish)
self.protocol("WM_DELETE_WINDOW", self.on_closing)
try:
with open("progress.json", 'r') as f:
data = json.loads(f.read())
for key, value in data.items():
if key == 'STARTED' and value:
self.current_step = 0
self.show_step(0)
elif key == "USER CREATED" and value:
current_step = self.steps[self.current_step]
current_step.pack_forget()
self.current_step = 0
self.show_step(2)
except FileNotFoundError:
with open("progress.json", 'w+') as f:
json.dump(data, f)
f.flush()
os.fsync(f)
self.show_step(0)
def back(self):
self.next_button.configure(state='active')
self.show_step(self.current_step - 1)
def next(self):
self.show_step(self.current_step + 1)
def finish(self):
sys.exit()
def show_step(self, step):
if self.current_step is not None:
# remove current step
current_step = self.steps[self.current_step]
current_step.pack_forget()
self.current_step = step
new_step = self.steps[step]
new_step.pack(fill="both", expand=True)
new_step.focus_set()
if step == 0:
# first step
self.back_button.pack_forget()
self.next_button.pack(side="right", padx=10)
self.finish_button.pack_forget()
elif step == len(self.steps) - 1:
# last step
self.finish_button.pack(side="right", padx=10)
self.back_button.pack_forget()
self.next_button.pack_forget()
elif step == 1:
self.back_button.pack(side="right", padx=15)
self.next_button.configure(state='disabled')
self.next_button.pack(side="right", padx=10)
self.finish_button.pack_forget()
elif step == 2:
self.back_button.pack_forget()
self.next_button.pack_forget()
self.finish_button.pack_forget()
else:
# all other steps
self.back_button.pack(side="right", padx=15)
self.next_button.pack(side="right", padx=10)
self.finish_button.pack_forget()
def on_closing(self):
if self.current_step == 3:
self.destroy()
else:
if messagebox.askyesno("Cancel", "Are you sure you want to cancel the setup?"):
self.destroy()
class Step1(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.pack(side="top", fill="both", expand=True)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
label_big = tk.Label(self, text="Welcome!", wraplength=450,
justify='left', font=controller.font_big)
label_big.place(x=250, y=16)
label1 = tk.Label(self, text="This will setup your windows machine as a kiosk.", wraplength=450,
justify='left', font=controller.font_small)
label1.place(x=250, y=130)
label2 = tk.Label(self,
text="A new user will be created, which will be used as the kiosk user. Next Google Chrome will be installed. Then Google Chrome will be setup so that it launches automatically and logs in every time the machine is launched.",
wraplength=450,
justify='left', font=controller.font_small)
label2.place(x=250, y=170)
label3 = tk.Label(self,
text="It is recommended you save your work as the setup will change the active user to the created one.",
wraplength=450,
justify='left', font=controller.font_small)
label3.place(x=250, y=270)
label3 = tk.Label(self,
text="Click Next to continue, or Cancel to exit the setup.",
wraplength=450,
justify='left', font=controller.font_small)
label3.place(x=250, y=400)
try:
load = Image.open("picture.jpg")
except:
load = Image.open("picture")
render = ImageTk.PhotoImage(load)
img = tk.Label(self, image=render, width=200, height=440)
img.image = render
img.place(x=0, y=0)
class Step2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.labels = []
self.controller = controller
self.pass_key = tk.IntVar()
self.auto_key = tk.IntVar(value=1)
self.controller = controller
self.header = tk.Label(self, text="Windows user creation", justify='left', font=controller.font_big)
self.header.place(x=25, y=15)
self.txt = tk.Label(self, text="You will need to create a new user for this machine.", wraplength=450,
justify='left', font=controller.font_small)
self.txt.place(x=25, y=50)
self.cb = tk.Checkbutton(self, text="No password", variable=self.pass_key, font=controller.font_small,
command=self.activatecheck_pass)
self.cb.place(x=25, y=320)
self.cbauto = tk.Checkbutton(self, text="Automatic login", variable=self.auto_key, font=controller.font_small)
self.cbauto.place(x=25, y=350)
self.name_text = tk.Label(self, text='Account name', font=controller.font_small)
self.name_text.place(x=25, y=175)
self.name_box = tk.Entry(self, width=50)
self.name_box.place(x=30, y=200)
self.name_text_info = tk.Label(self, text='The account name should be between 4 and 16 characters.',
font=controller.font_smaller)
self.name_text_info.place(x=25, y=220)
self.pass_text = tk.Label(self, text='Account password', font=controller.font_small)
self.pass_text.place(x=25, y=250)
self.pass_box = tk.Entry(self, width=50, show="*")
self.pass_box.place(x=30, y=275)
self.pass_text_info = tk.Label(self, text='The password should be between 4 and 16 characters.',
font=controller.font_smaller)
self.pass_text_info.place(x=25, y=295)
self.save_button = tk.Button(self, text="Save", width=10, height=1, command=self.save)
self.save_button.place(x=415, y=400)
self.information = tk.Label(self, text='For changes to take effect, please press the Save button',
font=self.controller.font_small)
self.information.place(x=25, y=400)
def save(self):
a = self.name_box.get()
if 16 >= len(a) >= 4:
self.print_good('namebox')
with open("progress.json", 'r') as f:
data = json.load(f)
data["USERNAME"] = a
data['PASSWORD'] = None
with open("progress.json", 'w') as f:
json.dump(data, f)
f.flush()
os.fsync(f)
# allow user to continue, enable next button
self.controller.next_button.configure(state='active')
else:
self.controller.next_button.configure(state='disabled')
self.print_bad('namebox')
if self.pass_box.cget('state') == 'normal':
b = self.pass_box.get()
if 16 >= len(b) >= 4:
self.print_good('passbox')
with open("progress.json", 'r') as f:
data = json.load(f)
data["PASSWORD"] = b
with open("progress.json", 'w') as f:
json.dump(data, f)
f.flush()
os.fsync(f)
else:
self.controller.next_button.configure(state='disabled')
self.print_bad('passbox')
# registry
self.registry = autologin.Reg(None, None)
if self.auto_key.get() == 1: # checked
val0, val1, val2 = self.registry.get_reg_val()
if val2 == '': val2 = None
with open("progress.json", 'r') as f:
data = json.load(f)
data["AutoAdminLogon"] = val0
data['DefaultUserName'] = val1
data['DefaultPassword'] = val2
with open("progress.json", 'w') as f:
json.dump(data, f)
f.flush()
os.fsync(f)
elif self.auto_key.get() == 0: # unchecked
with open("progress.json") as f:
data = json.load(f)
for element in list(data):
if 'AutoAdminLogon' in element:
del data['AutoAdminLogon']
if 'DefaultUserName' in element:
del data['DefaultUserName']
if 'DefaultPassword' in element:
del data['DefaultPassword']
with open("progress.json", 'w') as f:
json.dump(data, f)
f.flush()
os.fsync(f)
self.registry.close()
def print_good(self, n):
if n == 'namebox':
self.good_name = tk.Label(self, text=u'\u2713', font=self.controller.font_small)
self.good_name.place(x=340, y=195)
elif n == 'passbox':
self.good_pass = tk.Label(self, text=u'\u2713', font=self.controller.font_small)
self.good_pass.place(x=340, y=270)
self.labels.append(self.good_pass)
def print_bad(self, n):
if n == 'namebox':
self.bad_name = tk.Label(self, text=u'\u2717', font=self.controller.font_small)
self.bad_name.place(x=340, y=195)
elif n == 'passbox':
self.bad_pass = tk.Label(self, text=u'\u2717', font=self.controller.font_small)
self.bad_pass.place(x=340, y=270)
self.labels.append(self.bad_pass)
def activatecheck_pass(self):
if self.pass_key.get() == 0: # whenever unchecked
self.pass_box.config(state='normal')
elif self.pass_key.get() == 1: # whenever checked
for self.label in self.labels: self.label.destroy()
self.pass_box.delete(0, 'end')
self.pass_box.config(state='disabled')
with open("progress.json", 'r') as f:
data = json.load(f)
if 'PASSWORD' in data:
data['PASSWORD'] = None
with open("progress.json", 'w') as g:
json.dump(data, g)
g.flush()
os.fsync(g)
class Step3(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.things = []
self.controller = controller
ar = True # after restart
try:
with open("progress.json", 'r') as f:
data = json.load(f)
except FileNotFoundError:
ar = False
if not ar:
self.header = tk.Label(self,
text="Please wait until we complete the setup. Please note that the active user will be changed to the created one. The setup will continue automatically on startup.",
wraplength=710,
justify='left', font=controller.font_small)
elif ar:
self.header = tk.Label(self,
text="The setup will end shortly. When Google Chrome opens, please wait until a pop-up appears, then enable the virtual keyboard extension by pressing \"Enable extension\" on the upper right corner. After enabling the extension, please close Google Chrome",
wraplength=710,
justify='left', font=controller.font_small)
self.header.place(x=25, y=15)
self.p = ttk.Progressbar(self, orient='horizontal', length=500, takefocus=True, mode='indeterminate')
self.p.place(x=125, y=200)
t = threading.Thread(target=self.check, args=(self.things,))
t.setDaemon(True)
t.start()
def check(self, *options):
import time
thename = None
while True:
if self.winfo_ismapped():
break
self.p.start()
with open("progress.json", 'r') as f:
data = json.load(f)
if not data['AFTER RESTART']:
if not data['USER CREATED']:
# read required data from progress.json
self.read(self.things)
for needpass, username, *password in options:
thename = username
main = threading.Thread(target=newuser.CreateUserAndShare, args=(needpass, username, *password))
main.start()
userlist = alluserlist.listusers()
# while thename not in userlist:
# userlist = alluserlist.listusers()
with open("progress.json", 'w') as g:
data["USER CREATED"] = True
json.dump(data, g)
g.flush()
os.fsync(g)
# create thing to launch setup on startup of new user with the help of editreg.py
self.registry = editreg.Reg(None, 'C:\\Users\\Public\\app')
with open("progress.json", 'w') as g:
data['REG_VAL'] = self.registry.get_reg_val()
json.dump(data, g)
g.flush()
os.fsync(g)
self.registry.write_reg_val()
self.registry.close()
self.registry = editreg.Reg(None, None)
self.registry.disable_privacy_experience() # disable first startup privacy experience
self.registry.close()
self._registry = autologin.Reg(None, None)
if 'AutoAdminLogon' in data:
self._registry.write_reg_val(data['USERNAME'], data['PASSWORD'])
self._registry.close()
with open("progress.json", 'w') as g:
data['AFTER RESTART'] = True
json.dump(data, g)
g.flush()
os.fsync(g)
if getattr(sys, 'frozen', False):
# frozen
path_to_file = os.path.dirname(sys.executable)
else:
# unfrozen
path_to_file = os.path.dirname(os.path.realpath(__file__))
shutil.copytree(path_to_file, 'C:\\Users\\Public\\app', dirs_exist_ok=True)
# log out from the old user to be able to log in to the new
time.sleep(2)
switchuser.do()
# AFTER RESTART
else:
print('after')
if getattr(sys, 'frozen', False):
# frozen
path_to_file = os.path.dirname(sys.executable)
else:
# unfrozen
path_to_file = os.path.dirname(os.path.realpath(__file__))
self.registry = editreg.Reg(None, path_to_file)
reg_before = data['REG_VAL']
self.registry.del_reg_val(reg_before)
self.registry.close()
self.registry = editreg.Reg(None, None)
self.registry.enable_privacy_experience() # enable first startup privacy experience, simply delete key
self.registry.close()
# set sleep and power off to Never
subprocess.call("powercfg -change standby-timeout-ac 0 & powercfg -change -monitor-timeout-ac 0",
shell=True)
# install chrome
q = queue.Queue()
z = threading.Thread(target=install.run, args=(q,))
z.start()
z.join()
path = q.get()
# make chrome kiosk launch when windows launches
self.registry.write_chrome(path)
self.registry.close()
# install chrome virtual keyboard extension
self._registry = extension_editreg.Reg(None, None)
self._registry.write_reg_val()
self._registry.close()
# open chrome
subprocess.run(path)
self.p.stop()
self.controller.next()
def read(self, thelist):
with open("progress.json", 'r') as f:
data = json.load(f)
print(data)
if 'PASSWORD' in data:
thelist.append(True)
for key, value in data.items():
if key == 'USERNAME' or key == 'PASSWORD':
thelist.append(value)
else:
thelist.append(False)
for key, value in data.items():
if key == 'USERNAME':
thelist.append(value)
class Step4(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Setup complete!", font=self.controller.font_big)
label1.place(x=250, y=15)
load = Image.open("picture.jpg")
render = ImageTk.PhotoImage(load)
img = tk.Label(self, image=render, width=200, height=440)
img.image = render
img.place(x=0, y=0)
label2 = tk.Label(self, text="The setup has been successfully completed.", font=self.controller.font_small)
label2.place(x=250, y=70)
label3 = tk.Label(self, text="visit ",
font=self.controller.font_small)
label3.place(x=250, y=120)
link1 = tk.Label(self, text="here", fg="blue", cursor="hand2", font=self.controller.font_small)
link1.place(x=250, y=145)
link1.bind("<Button-1>", lambda e: self.callback("https://www.google.com"))
label4 = tk.Label(self, text="text", font=self.controller.font_small)
label4.place(x=373, y=145)
label5 = tk.Label(self,
text="it will launch after restart",
font=self.controller.font_small, wraplength=435,
justify='left')
label5.place(x=250, y=180)
label6 = tk.Label(self, text="Press Finish to restart your machine and run it as a kiosk! does not work yet",
font=self.controller.font_small)
label6.place(x=250, y=400)
t = threading.Thread(target=self.is_completed)
t.setDaemon(True)
t.start()
def check(self, *options):
import time
thename = None
while True:
if self.winfo_ismapped():
break
self.p.start()
def is_completed(self):
while True:
if self.winfo_ismapped():
break
try:
with open("progress.json", 'r') as f:
data = json.load(f)
with open("progress.json", 'w') as g:
data['COMPLETED'] = True
json.dump(data, g)
g.flush()
os.fsync(g)
except json.decoder.JSONDecodeError:
sys.exit()
print('removing json')
os.remove('progress.json')
def callback(self, url):
webbrowser.open_new(url)
if __name__ == "__main__":
elevate.elevate(show_console=False)
wiz = Wizard()
wiz.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T19:21:36.970",
"Id": "462094",
"Score": "1",
"body": "Does the code work? Does the main window appear? Code that is not working as expected is off-topic for code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T19:22:42.863",
"Id": "462095",
"Score": "2",
"body": "As I said, the code does work as intended. The problem is the lag when dragging"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:27:17.490",
"Id": "462102",
"Score": "0",
"body": "Suggest you simplify the above so that we don't need import pack. Or link to a repo where we can try it in full. Also, you can put hardcoded values on top as constants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T13:53:47.537",
"Id": "462202",
"Score": "1",
"body": "@Abdur-RahmaanJanhangeer Please don't suggest simplifications. On Code Review, we need to see the real deal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:44:34.860",
"Id": "462244",
"Score": "0",
"body": "@Mast we need to simplify else we are not able to test the project. Suggesting to remove pack here etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T20:06:43.447",
"Id": "462258",
"Score": "2",
"body": "@Abdur-RahmaanJanhangeer Removing is something else than simplifying. When in doubt, the original code is much preferred over a simplification. If a simplification is absolutely necessary, pleas keep [this](https://codereview.meta.stackexchange.com/a/7250/52915), [this](https://codereview.meta.stackexchange.com/a/5165/52915) and the [help/on-topic] in mind. Details matter! Daniel, I strongly recommend **against** modifying the code if what you've currently posted is how you're currently using it.You may just simplify the performance problem away if you take Abdur's advice.We've seen it happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T20:10:39.613",
"Id": "462259",
"Score": "0",
"body": "@Mast since it's not a big code base, i guess if people can run the code the OP can get better reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T12:15:05.750",
"Id": "462595",
"Score": "0",
"body": "@Abdur-RahmaanJanhangeer Sorry, that is against the policies of Code Review. If you want to argue otherwise, feel free to discuss on the Meta posts Mast just linked to. Do support your argument with full reasoning and evidence, since the current policies reflect the opinion of the majority of the members of the Code Review community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T18:55:57.367",
"Id": "462730",
"Score": "0",
"body": "@L. F. Thanks for clarifying"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T12:14:43.283",
"Id": "235958",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"multithreading",
"tkinter"
],
"Title": "Tkinter setup wizard-like application with threading"
}
|
235958
|
<p>I'm not an expert in authentication, so I want to make sure I have done everything right.</p>
<p>I am using <a href="https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options" rel="nofollow noreferrer"><code>crypto.createCipheriv</code> and <code>crypto.createDecipheriv</code></a> for authentication.</p>
<p>I will store the key in the database, and the initialization vector, IV, and encrypted data in cookies. When requested the server will try to decrypt encrypted data from cookies using the IV from the cookies and the key from the database. If the decryption is successful the request can proceed.</p>
<p>If the database is compromised, the hacker will not be able to use the database keys, because they will need the code to generate the IV and the data cookies. </p>
<p>The database key is the same for multiple sessions, only the IV and data are different.</p>
<p>Initial login conformation will be handled using external service, so I can focus on interacting with the cookies.</p>
<p>Are there problems with my solution?</p>
<pre><code>import crypto from 'crypto'
function encrypt(dataToEncrypt /*random data*/) {
let dbKey = crypto.randomBytes(32) //db
let userKey = crypto.randomBytes(16) //cookie
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(dbKey), userKey)
let encryptedData = cipher.update(JSON.stringify(dataToEncrypt))
encryptedData = Buffer.concat([encryptedData, cipher.final()])
return { userKey: userKey.toString('hex'), dbKey: dbKey.toString('hex'), encryptedData: encryptedData.toString('hex') }
}
function decrypt(userProvidedKey, dbKey, dataToDecrypt) {
let userKeyBuffer = Buffer.from(userProvidedKey, 'hex')
let dbKeyBuffer = Buffer.from(dbKey, 'hex')
let decryptedData = Buffer.from(dataToDecrypt, 'hex')
let decipher = crypto.createDecipheriv('aes-256-cbc', dbKeyBuffer, userKeyBuffer)
decryptedData = decipher.update(decryptedData)
decryptedData = Buffer.concat([decryptedData, decipher.final()])
return decryptedData.toString()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:30:53.990",
"Id": "462033",
"Score": "0",
"body": "\"Is my method correct?\" Did you test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:31:48.230",
"Id": "462034",
"Score": "0",
"body": "@Mast yes it's working and seems fine. It's more theory/implementation question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:32:56.353",
"Id": "462035",
"Score": "0",
"body": "Do you want the code reviewed or the theory reviewed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:34:58.120",
"Id": "462036",
"Score": "0",
"body": "@Mast both, or code at least."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:36:03.820",
"Id": "462037",
"Score": "1",
"body": "Good answer. If you'd wanted us to focus on the theory you'd be in the wrong place, so to avoid disappointment I'd to make sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:44:44.860",
"Id": "462047",
"Score": "1",
"body": "Hey! I've edited the wording of your post. I found it challenging to read and understand. I have attempted to make it easier for everyone else to also understand your question. Please could you read over my changes to ensure I've not messed up any of your intended meaning. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:50:10.793",
"Id": "462049",
"Score": "0",
"body": "@Peilonrayz thanks, English is not my native language so sorry for trouble ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:04:38.580",
"Id": "462051",
"Score": "1",
"body": "@RTW No problem, best of luck! :)"
}
] |
[
{
"body": "<blockquote>\n <p>I am using crypto.createCipheriv and crypto.createDecipheriv for authentication.</p>\n</blockquote>\n\n<p>Encryption is mainly used for providing <em>confidentiality</em>. You'd use a MAC (message authentication code) or <em>authenticated encryption</em> if you want authentication.</p>\n\n<p>Note that CTR decryption <em>always</em> succeeds, even if it <em>may</em> result in incorrect ciphertext. CBC decryption succeeds 1 out of 256 times if PKCS#7 compatible padding is used (and it is) if random ciphertext is fed to it. Besides that, CBC is vulnerable to padding oracle attacks. <em>Unauthenticated</em> ciphertext is always vulnerable to plaintext oracle attacks.</p>\n\n<p>Basically, you need a MAC (such as a HMAC over <strong>the IV</strong> and the ciphertext) or authenticated encryption.</p>\n\n<p>GCM mode is provided by CryptoJS, if I'm not mistaken. GCM already authenticates the IV - but make sure it <strong>does</strong> authenticate the tag!</p>\n\n<blockquote>\n <p>I will store the key in the database, and the initialization vector, IV, and encrypted data in cookies.</p>\n</blockquote>\n\n<p>I presume this is a textual error, as the initialization vector <strong>is</strong> the IV.</p>\n\n<blockquote>\n <p>If the database is compromised, the hacker will not be able to use the database keys, because they will need the code to generate the IV and the data cookies. </p>\n</blockquote>\n\n<p>The IV should never be considered a secret. The data may of course be considered secret, but the <em>algorithm to generate the data</em> should not act as a key either (see Kerckhoff's principle).</p>\n\n<blockquote>\n <p>The database key is the same for multiple sessions, only the IV and data are different.</p>\n</blockquote>\n\n<p>That's right, as long as you don't create millions of \"messages\" (in this case cookies). If you overextend the key you may want to create a different key (for instance using key derivation). Probably this is not a problem for you though.</p>\n\n<hr>\n\n<p>Let's move to the code (which we now know is not secure).</p>\n\n<pre><code>function encrypt(dataToEncrypt /*random data*/) {\n</code></pre>\n\n<p>Random has a very specific meaning in cryptography, so I'd try and avoid that adjective, and use \"any\" instead. I'd simply document your functions, and not put inline comments in the code.</p>\n\n<pre><code>let dbKey = crypto.randomBytes(32) //db\n</code></pre>\n\n<p>Fine, although I would use 256 / 8, preferably with a constant <code>KEY_SIZE = 256</code> for the key size.</p>\n\n<p>Don't use end-of-line comments either, as refactoring will make them disappear behind the right margin or trigger a nasty text wrap in editors.</p>\n\n<p>Where the key is stored is not within this method, so the comment should not be present in the <em>final</em> code.</p>\n\n<pre><code> let userKey = crypto.randomBytes(16) //cookie\n</code></pre>\n\n<p>No! An IV is not a key, and - even if it was - only the first block of ciphertext cannot be <em>decrypted without the IV</em> in CBC mode. Again, at least use a constant like <code>BLOCK_SIZE_BYTES = 16</code> or <code>IV_SIZE_BYTES = 16</code>.</p>\n\n<pre><code>let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(dbKey), userKey)\n</code></pre>\n\n<p>Wrong mode, but yeah.</p>\n\n<pre><code>let encryptedData = cipher.update(JSON.stringify(dataToEncrypt))\n</code></pre>\n\n<p>JSON-ify should be performed on a separate line. Now a significant operation is hidden inside another statement.</p>\n\n<pre><code>return { userKey: userKey.toString('hex'), dbKey: dbKey.toString('hex'), encryptedData: encryptedData.toString('hex') }\n</code></pre>\n\n<p>Ciphertext and keys are binary. I'd not stringify them unless strictly necessary. The IV and ciphertext may be concatenated and then converted to (URL-safe) base 64 to be more efficient than hex.</p>\n\n<hr>\n\n<p>Skipping some lines to the final part of the decryption:</p>\n\n<pre><code>return decryptedData.toString()\n</code></pre>\n\n<p>That's no good, first you JSON-ify the input, and then you don't do the reverse during decryption. These methods should be symmetric. Either you take it out of encryption or you add it to decryption (if that's possible).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T18:27:55.010",
"Id": "236246",
"ParentId": "235959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236246",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T13:26:40.680",
"Id": "235959",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"cryptography",
"authentication"
],
"Title": "Crypto createCipheriv and createDecipheriv for authentication"
}
|
235959
|
<p>The initial problem that led me to learn VBA is as follows:</p>
<p>You have a table that can be up to 10,000 rows (several hundred pages) long in a Word document. The table has a title in the form of a paragraph above the first row. This title is styled such that it links to a Table of Contents (<code>Style = "Caption"</code>). The table must be broken at the last row on each page, and the title must be inserted before the new table but in a different style that is not linked to the Table of Contents(<code>Style = "Caption Cont"</code>). </p>
<p>The first page will look like this:<a href="https://i.stack.imgur.com/uP27z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uP27z.png" alt="linked to the ToC"></a></p>
<p>The second page will look like this: <a href="https://i.stack.imgur.com/46wQp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/46wQp.png" alt="not linked to ToC"></a></p>
<p>My first solution was relatively hackey and not at all elegant. I've managed to put together the following solution that works quite well. However, the initial process of determining the row number at which the table crosses pages is pretty slow due to the use of <code>Range.Information</code>. I'm wondering if there's a faster way to determine the bottom row on the page. </p>
<p>Putting the document into <code>wdNormalView</code> shaves off about a second per page, even with <code>Application.ScreenUpdating = False</code>... </p>
<p>The program requires that your cursor is somewhere inside the table, which is fine and not a functionality I wish to remove.</p>
<p>It currently does about 120 pages per minute, with the majority of the time being spent on determining the row to split at (i.e. <code>splitNum</code>). I'm sure it can be much faster with a different method of determining <code>splitNum</code>.</p>
<p><strong>I CANNOT ADD AN ADDITIONAL ROW TO THE TABLE FOR THE PURPOSES OF USING "REPEAT HEADER ROWS".</strong>
It would violate regulations that are enforced in my industry, and a non-conforming document can be a huge hit to the company and future business. This code is meant as a standalone and should not require that users alter their workflow.</p>
<p>Code:</p>
<pre class="lang-vb prettyprint-override"><code>Sub tblSplit()
Dim timeCheck As Double
Application.ScreenUpdating = False
Application.ActiveWindow.View = wdNormalView
timeCheck = Time
On Error GoTo ErrH
Dim crossRef As Range, delRange As Range, tblR As Range, newTbl As Range
Dim tblNumField As Range, tblNum As String
Set tblNumField = Selection.Tables(1).Range
tblNumField.MoveStart wdParagraph, -1
tblNum = tblNumField.Words(2)
Set crossRef = Selection.Tables(1).Range
Set thisTbl = Selection.Tables(1).Rows(1).Range
Set tblR = Selection.Tables(1).Range
</code></pre>
<p>Insert cross-reference to title with style "Caption Cont"</p>
<pre class="lang-vb prettyprint-override"><code>crossRef.Move wdCharacter, -2
crossRef.InsertCrossReference ReferenceType:="Table", ReferenceKind:= _
wdOnlyCaptionText, ReferenceItem:=tblNum, InsertAsHyperlink:=True, _
IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
crossRef.Text = vbCr & " (Cont.)" & vbTab
crossRef.MoveStart wdCharacter, 1
crossRef.Style = "Caption Cont."
crossRef.Collapse wdCollapseStart
crossRef.InsertCrossReference ReferenceType:="Table", ReferenceKind:= _
wdOnlyLabelAndNumber, ReferenceItem:=tblNum, InsertAsHyperlink:=True, _
IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
crossRef.MoveEnd wdParagraph, 1
</code></pre>
<p>Delete duplicate title</p>
<pre class="lang-vb prettyprint-override"><code>Set delRange = crossRef.Duplicate
crossRef.MoveEnd wdParagraph, 1
crossRef.Copy
delRange.Text = vbNullString
</code></pre>
<p><strong>Find row at which table spans two pages</strong></p>
<pre class="lang-vb prettyprint-override"><code>Dim splitNum As Long, n As Long, i As Long, pageNum As Long
pageNum = tblR.Rows(1).Range.Information(wdActiveEndAdjustedPageNumber)
i = 15
Do
If tblR.Rows(i).Next.Range.Information(wdActiveEndAdjustedPageNumber) <> pageNum Then
splitNum = i
Exit Do
End If
i = i + 1
Loop Until i = 100 'arbitrary cap to prevent infinite loop
n = 1
</code></pre>
<p>Split and format</p>
<pre class="lang-vb prettyprint-override"><code>Do
DoEvents
'Split and format
tblR.Tables(n).Split (splitNum)
tblR.Tables(n).Rows.Last.Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
'Paste the stuff
Set newTbl = tblR.Tables(n + 1).Range
newTbl.Move wdParagraph, -2
newTbl.Paste
newTbl.MoveEnd wdParagraph, 1
'Clear excess
newTbl.Paragraphs.Last.Range.Text = vbNullString
'Next
n = n + 1
Loop Until tblR.Tables(n).Rows.Count < splitNum
</code></pre>
<p>Restore state, report time, safe-exit and error handler set-up for debugging</p>
<pre class="lang-vb prettyprint-override"><code>Application.ActiveWindow.View = wdPrintView
Application.ScreenUpdating = True
MsgBox "Pages completed: " & n & vbCr & _
"Time (sec): " & DateDiff("s", timeCheck, Time) & vbCr & _
"Seconds per page: " & CDbl(DateDiff("s", timeCheck, Time)) / CDbl(n) & vbCr & _
"Pages per minute: " & n / DateDiff("s", timeCheck, Time) * 60
Exit Sub
ErrH:
Application.ScreenUpdating = True
Err.Raise Err.Number
Stop
End Sub
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:19:08.840",
"Id": "235961",
"Score": "1",
"Tags": [
"vba",
"ms-word"
],
"Title": "What is the fastest way to determine if a table spans two pages?"
}
|
235961
|
<p>I was recently asked an interview question with regards to algorithm design. The challenge is as follows:</p>
<blockquote>
<p>Given a 6 or less digits positive integer (0 - 999999 inclusive), write a function <code>englishify(number: int)</code> that returns the full English equivalent of that number. Here are some samples of the structure you are expected to generate:</p>
<p>1 - One</p>
<p>222 - Two Hundred And Twenty two</p>
<p>1234 - One Thousand, Two Hundred and Thirty Four</p>
<p>31337 - Thirty One Thousand, Three Hundred And Thirty Seven</p>
<p>100100 - One Hundred Thousand And One Hundred</p>
<p>200111 - Two Hundred Thousand, One Hundred And Eleven</p>
</blockquote>
<p>As you may be able to see, there is a key requirement when it comes to formatting this:</p>
<blockquote>
<ol>
<li>There should be a comma, not 'And', after the thousands and before the hundreds, if <strong>both exist.</strong></li>
</ol>
</blockquote>
<p>I have attempted this challenge with the code below:</p>
<pre class="lang-py prettyprint-override"><code>def englishify(number):
#Numbers 0-19 (unique numbers)
OneToNine= 'One Two Three Four Five Six Seven Eight Nine'.split()
TenToNineteen = 'Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
ZeroToNineteen = [''] + OneToNine + TenToNineteen
#Numbers >= 20 at intervals of 10
Tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
#Additional function for ease of processing of numbers
def englishifyHundreds(number):
#Special case: Number = 0
if number == 0:
return 'Zero'
#1. Number from 1-19
if number < 20:
return ZeroToNineteen[number]
#2. Number from 20-99
if number >= 20 and number < 100:
result = Tens[int(number/10)-2] + ' ' + ZeroToNineteen[int(number%10)]
return result.rstrip()
#3. Number from 100-999
if number >= 100:
#Separating hundreds digit and tens digit
tens = number - ((number//100)*100)
#Accounting for edges = 0 (number = 100, 200, ...)
if number%100 == 0:
return ZeroToNineteen[int(number/100)] + ' Hundred'
else:
return ZeroToNineteen[int(number/100)] + ' Hundred And ' + englishifyHundreds(tens)
#Actual processing of number
if len(str(number)) <= 3:
return englishifyHundreds(number)
else:
#Splitting number into 'thousands' digits and 'hundreds' digits
thousands = int(str(number)[:-3])
hundreds = int(str(number)[-3:])
#Accounting for edges = 0 (thousands = 1000, 2000, ...)
if thousands % 1000 == 0:
return englishifyHundreds(thousands) + ' Thousand'
else:
#Accounting for if hundreds == 0:
if hundreds == 0:
return englishifyHundreds(thousands) + ' Thousand'
#Accounting for cases where comma is not necessary
elif hundreds % 100 == 0 or hundreds < 100:
return englishifyHundreds(thousands) + ' Thousand And ' + englishifyHundreds(hundreds)
#Remaining cases implementing comma
else:
return englishifyHundreds(thousands) + ' Thousand, ' + englishifyHundreds(hundreds)
</code></pre>
<p>I am currently trying to rack my brains thinking of ways to optimize this, but with my limited knowledge of recursions and algorithms this is the best I can churn out for now. Hopefully I can seek some opinions from some of the more experienced programmers around here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:56:46.930",
"Id": "462050",
"Score": "1",
"body": "Did you write `englishify(number)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:23:45.730",
"Id": "462117",
"Score": "1",
"body": "Sorry, I'm not quite sure what you meant. If you were asking whether I wrote this function `englishify(number)` myself, the answer is yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T09:55:59.620",
"Id": "462171",
"Score": "1",
"body": "RE this: `tens = number - ((number//100)*100)`, you can use `%100` to get the remainder, and I'm not sure that `tens` is the right name for a variable that represents the tens and units.\nAlso you should try to be a bit more consistent between using integer division(`number//100` for example) and fractional division cast to integer(`int(number/100)`). They give the same results so you should try to avoid mixing them to minimise potential confusion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:21:54.093",
"Id": "462173",
"Score": "0",
"body": "Ahh! Yes! The tens variable. Not quite sure what I was thinking there... must have messed up my operators in the midst of it. Will work on it. Nevertheless, thank you! Your points are deeply appreciated."
}
] |
[
{
"body": "<p>It's often best to write this kind of function along with its tests. Let's start with a simple test:</p>\n<pre><code>import doctest;\n\ndef englishify(number):\n """Format NUMBER into standard English form.\n NUMBER must be in range [0..999999]\n >>> englishify(0)\n 'Zero'\n """\n\n return 'Zero'\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n<p>Now, start adding more tests and make each one pass before moving on to the next.</p>\n<p>You'll find that when you reach the bigger numbers, there's a useful recursive property. We can split off the thousands and the hundreds, format each non-zero part separately, and then join using one of the techniques from <a href=\"//stackoverflow.com/q/44574485/4850040\"><em>Joining words together with a comma, and “and”</em></a>. For example, consider these inputs:</p>\n<ul>\n<li>123456 ⟶ 123 Thousand <code>,</code> 4 Hundred <code>and</code> 56</li>\n<li>123056 ⟶ 123 Thousand <code>and</code> 56</li>\n<li>123400 ⟶ 123 Thousand <code>and</code> 4 Hundred</li>\n</ul>\n<p>Now those individual numbers can be formatted into words (and the last case will have two "and"s in normal English: "One hundred <strong>and</strong> twenty-three thousand, four hundred <strong>and</strong> fifty-six.'</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>import doctest;\n\ndef englishify(number):\n """Format NUMBER into standard English form.\n NUMBER must be in range [0..999999]\n >>> englishify(0)\n 'Zero'\n >>> englishify(10)\n 'Ten'\n >>> englishify(20)\n 'Twenty'\n >>> englishify(99)\n 'Ninety Nine'\n >>> englishify(100)\n 'One Hundred'\n >>> englishify(101)\n 'One Hundred and One'\n >>> englishify(1001)\n 'One Thousand and One'\n >>> englishify(1201)\n 'One Thousand, Two Hundred and One'\n >>> englishify(123201)\n 'One Hundred and Twenty Three Thousand, Two Hundred and One'\n """\n\n Units = [None, 'One', 'Two', 'Three', 'Four', 'Five',\n 'Six', 'Seven', 'Eight', 'Nine',\n 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',\n 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n Tens = [None, None, 'Twenty', 'Thirty', 'Forty', 'Fifty',\n 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n\n if number < 20:\n return Units[number] or 'Zero'\n\n if number < 100:\n return ' '.join(filter(None, [Tens[number//10], Units[number%10]]))\n\n # Larger numbers - break down and englishify each part\n parts = list(filter(None,\n map(lambda quantity, number:\n englishify(number) + quantity if number else None,\n [' Thousand', ' Hundred', ''],\n [number // 1000, number // 100 % 10, number % 100])))\n\n if len(parts) == 1:\n return parts[0]\n return ' and '.join([', '.join(parts[:-1]), parts[-1]])\n\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n<p>The extension to support millions and more should now be obvious - just add the unit and its extraction to the list passed to <code>map()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:23:09.703",
"Id": "462116",
"Score": "0",
"body": "Yes! That was exactly the kind of approach I was going for. Hence the reason why I created the `englishifyHundreds` function to allow me to pass both `thousands` and `hundreds` through that function for separate processing, before adding in the **'And'** myself. Nevertheless, thank you for the useful tip regarding tests! Will try to implement them in future when I am trying to design other algorithms for interview/personal purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T09:02:01.303",
"Id": "462163",
"Score": "1",
"body": "I didn't explain myself very well, so I've added a worked example that simplifies the joining of the thousands, hundreds and units. The key is to filter out the empty components before joining the remaining ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:42:20.957",
"Id": "462178",
"Score": "0",
"body": "Wow, that is much neater indeed. Looks like I should brush up on my usage of lists and maps/filters. I also love that your solution is scalable to numbers in the millions/billions. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:50:52.027",
"Id": "235968",
"ParentId": "235963",
"Score": "3"
}
},
{
"body": "<p>The basic approach doesn't look bad.\nYou can optimize by working more with arrays that won't require any offset-handling.</p>\n\n<p>For example:</p>\n\n<ul>\n<li>You can combine <code>'Zero'</code> and the arrays <code>OneToTen</code> and <code>TenToNineteen</code>\nto one direct-initialized array. </li>\n<li>The array <code>Ten</code> could also have two empty values in the first two entries, making <code>'Twenty'</code> available at index 2.</li>\n<li>The Thousands, Millions, etc. could also be stored inside an array.</li>\n</ul>\n\n<p>This would look somewhat like this:</p>\n\n<pre><code> #Numbers 0-19 (unique numbers)\n ZeroToNineteen = [\n 'Zero',\n 'One',\n 'Two',\n 'Three',\n 'Four',\n 'Five',\n 'Six',\n 'Seven',\n 'Eight',\n 'Nine',\n 'Ten',\n 'Eleven',\n 'Twelve',\n 'Thirteen',\n 'Fourteen',\n 'Fifteen',\n 'Sixteen',\n 'Seventeen',\n 'Eighteen',\n 'Nineteen']\n\n #Numbers at intervals of 10\n Tens = [\n '',\n '',\n 'Twenty',\n 'Thirty',\n 'Forty',\n 'Fifty',\n 'Sixty',\n 'Seventy',\n 'Eighty',\n 'Ninety']\n\n #Numbers at intervals of 1000\n Thousands = [\n '',\n 'Thousand',\n 'Million',\n 'Billion',\n 'Trillion',\n 'Quadrillion',\n 'Quintillion',\n 'Sextillion',\n 'Septillion'\n ]\n</code></pre>\n\n<p>Doing so allows for a slightly shorter and simpler version of your <code>englishifyHundreds</code> function:</p>\n\n<pre><code> #Additional function for ease of processing of numbers\n def englishifyHundreds(number):\n #1. Number from 0-19\n if number < 20:\n return ZeroToNineteen[int(number)]\n #2. Number from 20-99\n elif number < 100:\n return Tens[int(number/10)] + ' ' + ZeroToNineteen[int(number%10)]\n #3. Number from 100-999\n else:\n #Accounting for edges = 0 (number = 100, 200, ...)\n remainder = int(number) % 100\n if remainder == 0:\n return ZeroToNineteen[int(number/100)] + ' Hundred'\n else:\n return ZeroToNineteen[int(number/100)] + ' Hundred And ' + englishifyHundreds(remainder)\n</code></pre>\n\n<p>The assembly can than be achieved by first splitting the number into number representing 3 digits each:</p>\n\n<pre><code> parts=[]\n iterations = int((len(str(number))-1)/3) + 1\n iteration = int(0)\n while iteration < iterations:\n part = int(number % 1000)\n number = int(number / 1000)\n parts.append(part)\n iteration += 1\n parts.reverse()\n</code></pre>\n\n<p>And then reassembling it according to your rules:</p>\n\n<pre><code> numberString=''\n for i, part in enumerate(parts):\n if part == 0:\n continue\n thousandsIndex = len(parts) - (i+1)\n separatorString = ('' if i == 0 else ' And ' if (part < 100 or part % 100 == 0) else ', ')\n partString = englishifyHundreds(part)\n thousandString = (' ' + Thousands[thousandsIndex]) if thousandsIndex > 0 else ''\n numberString += separatorString + partString + thousandString\n return numberString\n</code></pre>\n\n<hr>\n\n<p>I have tried the code using Repl.it (<a href=\"https://repl.it/repls/AdventurousMerryWamp\" rel=\"nofollow noreferrer\">Link</a>) with the following test cases:</p>\n\n<pre><code># Test cases\nprint(englishify(1)) # - One\nprint(englishify(222)) # - Two Hundred And Twenty two\nprint(englishify(1234)) # - One Thousand, Two Hundred and Thirty Four\nprint(englishify(31337)) # - Thirty One Thousand, Three Hundred And Thirty Seven\nprint(englishify(100100)) # - One Hundred Thousand And One Hundred\nprint(englishify(200111)) # - Two Hundred Thousand, One Hundred And Eleven\n\n# Custom\nprint(englishify(10000000025))\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>One\nTwo Hundred And Twenty Two\nOne Thousand, Two Hundred And Thirty Four\nThirty One Thousand, Three Hundred And Thirty Seven\nOne Hundred Thousand And One Hundred\nTwo Hundred Thousand, One Hundred And Eleven\nTen Billion And Twenty Five\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:58:16.597",
"Id": "462113",
"Score": "0",
"body": "The test case comment says the same as the block quote: `100100 - One Hundred Thousand And One Hundred`, the question claiming `There should be a comma, not 'And', after the thousands and before the hundreds, if both exist` a key requirement in the very next paragraph."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:18:59.233",
"Id": "462115",
"Score": "0",
"body": "I like the point on creating the empty values in my 'Ten' array, it would help a lot with keeping some of my indexing consistent. Also, even though it is true that one special case was left out (One Hundred Thousand **And** One Hundred instead of One Hundred Thousand, One Hundred), it seems like your approach could be used for values greater than 999999 as well. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T08:47:33.433",
"Id": "462160",
"Score": "1",
"body": "@greybeard Oh yes, I missed that one.\nCan be easily fixed by replacing `separatorString = ('' if i == 0 else ' And ' if part < 100 else ', ')` with `separatorString = ('' if i == 0 else ' And ' if (part < 100 or part % 100 == 0) else ', ')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T08:51:50.973",
"Id": "462161",
"Score": "0",
"body": "Adjusted the answer.\nThere are for sure some cases that don't quite work as expected, but I leave these for you to solve. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:48:25.010",
"Id": "462181",
"Score": "0",
"body": "Your answer is right on. The adjustment is much appreciated!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:25:43.123",
"Id": "235973",
"ParentId": "235963",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T14:36:00.927",
"Id": "235963",
"Score": "2",
"Tags": [
"python",
"algorithm",
"interview-questions"
],
"Title": "Convert integer to English words"
}
|
235963
|
<p>I'm trying to optimize the following function <code>f</code>, written in python.
It is a function of an integer <code>k</code>.
First it calls another function <code>G(k)</code>, which gives back a long list of certain objects. We want to manipulate this list as follows: two elements <code>a,b</code> are equivalent iff the function <code>H</code> (which is a given function that can take values 0 or 1) evalutated on them is one, <code>H(a,b)=1</code>; our function <code>f</code> should give back a list of equivalence classes of elements in <code>G(k)</code>. An element of the list should be of the form (representative element, number of elements in that class).</p>
<p>That's what my code below does, but I wonder if it can be optimized, considering that <code>G(k)</code> can be a very long list. For the moment I'd like to regard <code>G</code> and <code>H</code> as given.</p>
<pre><code>def f(k):
L = G(k)
y = len(L)
R = []
for i in range(y):
nomatch = 0
for j in range(len(R)):
if H(L[i],R[j][0]):
R[j][1] += 1
nomatch = 1
break
if nomatch == 0: R.append([L[i],1])
return R
</code></pre>
<p>Edit1: I do not care particularly about readability (it's 13 lines of code after all), just performance. You should regard G and H as black boxes, the first outputs a list of numbers (in first approximation), the second 1 or 0.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:43:47.590",
"Id": "462061",
"Score": "0",
"body": "Did you get this challenge from a website? If so please could you link to the site. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:46:19.737",
"Id": "462063",
"Score": "1",
"body": "What is `H` and what are the objects returned by `G`? Are they instances of a class which you can change? Can you convert this from a comparison function to a unique identifier method that returns the same for equivalent objects?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T16:22:46.567",
"Id": "462071",
"Score": "0",
"body": "Micro-review: the code would benefit from improved comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:09:42.940",
"Id": "462079",
"Score": "0",
"body": "@Peilonrayz No."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:10:27.197",
"Id": "462080",
"Score": "0",
"body": "@Graipher I cannot change H and G. I'd like to keep them as abstract as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:10:37.397",
"Id": "462081",
"Score": "0",
"body": "@TobySpeight What is unclear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:17:39.240",
"Id": "462083",
"Score": "2",
"body": "If the function itself were better named, and the variables too, then there wouldn't be so much need for comments. But this is lacking even a docstring, and `f` conveys nothing as a name. How is a future reader expected to pick up the necessary context?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:21:59.957",
"Id": "462084",
"Score": "0",
"body": "(While I'm comfortable with calling *categorisation* *sorting*, the caption of tag [tag:sorting] reads *Sorting is the process of applying some order to a collection of items.* which does *not* seem to apply here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:30:01.247",
"Id": "462175",
"Score": "0",
"body": "@Graipher You are right, I already did that, but in the end it reduces again to optimize 'sorting' of the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:30:20.080",
"Id": "462176",
"Score": "0",
"body": "@greybeard Sure, what would be more appropriate tag?"
}
] |
[
{
"body": "<p>Let me try and illustrate the difference <em>naming</em> and <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstrings</a> make -<br>\nah, well, iterating over sequences and <code>for…else</code>, as well:</p>\n\n<pre><code>def collatz_list(k, s=[]):\n \"\"\" append the list of collatz values starting from k to s. \"\"\"\n s.append(k)\n return s if k <= 1 else collatz_list(\n k//2 if 0 == k % 2 else k * 3 + 1, s)\n\n\ndef equivalent(l, r):\n \"\"\" return \"equivalent\" when congruent mod 42. \"\"\"\n return l % 42 == r % 42\n\n\ndef categorise(k, G, H):\n \"\"\" categorise the results of G(k) according to predicate H\"\"\"\n many_items = G(k)\n categories = []\n for item in many_items:\n for pair in categories:\n if H(item, pair[0]):\n pair[1] += 1\n break\n else:\n categories.append([item, 1])\n return categories\n\n\ndef g(k):\n \"\"\" return the list of collatz values starting from k. \"\"\"\n return collatz_list(k)\n\n\ndef h(l, r):\n \"\"\" return \"equivalent\" when congruent mod 42. \"\"\"\n return equivalent(l, r)\n\n\nif __name__ == \"__main__\":\n print(categorise(7, g, h))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T18:54:32.990",
"Id": "462093",
"Score": "0",
"body": "Had no luck trying to improve readability/elegance using `if (not any(map(lambda pair:…`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T18:09:03.217",
"Id": "235975",
"ParentId": "235967",
"Score": "2"
}
},
{
"body": "<p>Without knowing anything more about the nature of G or H, there isn't much to go on. This might not be <em>optimized</em>, but it is more readable. It takes as arguments the sequence output by <code>G(k)</code> and the function <code>H</code>.</p>\n\n<pre><code>from collections import defaultdict\n\ndef f(sequence, is_equivalent):\n \"\"\"returns the number items in each equivalence class in the input sequence\"\"\"\n counter = defaultdict(int)\n\n for item in sequence:\n # filter counter.keys() to find equivalents to item\n equivalent = (eq for eq in counter.keys() if is_equivalent(item, eq))\n\n # key is next equivalent or default to item if no equivalent\n key = next(equivalent, item)\n\n counter[key] += 1\n\n return list(counter.items())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:34:34.137",
"Id": "462121",
"Score": "0",
"body": "I see readability improved. In the question I do not see indication objects from `G` to be suitable as keys for dicts, let alone *un*suitable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T03:13:08.960",
"Id": "462133",
"Score": "0",
"body": "@greybeard True, the objects from `G` might not be suitable as keys. In that case, one could use their index in the sequence as keys."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T06:46:13.483",
"Id": "462143",
"Score": "0",
"body": "`use [index of non-hashable objects in an existing] sequence as keys` *nice*"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:59:46.910",
"Id": "235984",
"ParentId": "235967",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:42:02.123",
"Id": "235967",
"Score": "-1",
"Tags": [
"python",
"performance",
"sorting"
],
"Title": "sort a list with equivalence classes"
}
|
235967
|
<p>I want to use the android component autocomplete:</p>
<p><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView" rel="nofollow noreferrer">https://developer.android.com/reference/android/widget/AutoCompleteTextView</a></p>
<p>There are some possible values the user can select, but I also want that, the user starts typing and, if there is no match with any of the "possible" optionsm, then, the text the user wrote is also valid. So, to put an example, imagine we have an autocomplete to select favourite fruit, and the options are Banana, Apple, but the user types Pear, then, it should be fine.</p>
<p>For that, I did this:</p>
<pre><code>mAutocompleteTextView = findViewById(R.id.select_fruit_autoCompleteTextView)
mAutocompleteTextView.threshold = 1
val fruitListener = OnFruitSet()
// if the user clicks in one of the options
mAutocompleteTextView.onItemClickListener = fruitListener
// if the user writes a different option
mAutocompleteTextView.addTextChangedListener(fruitListener)
</code></pre>
<p>And then, my OnFruitSet private inner class:</p>
<pre><code>private inner class OnFruitSet: AdapterView.OnItemClickListener, TextWatcher {
private val textModified = AtomicBoolean(false)
// this is used to change focus if the user finishes (by clicking on one of the options, or in the go button, next, etc. but it isn't working very good)
private val goToNext = AtomicBoolean(false)
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
// this means that the fruit is an option
listeners.forEach{ it.onFruitSet(parent?.adapter?.getItem(position), true) }
}
override fun afterTextChanged(s: Editable?) {
if (textModified.get()) {
textModified.set(false)
goToNext.set(true)
// right now the user can add new lines, and I want to avoid it.
mAutocompleteTextView.setText(s?.replace("[\n]".toRegex(), ""))
} else {
goToNext.set(false)
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val name = if (s?.contains('\n') == true) {
textModified.set(true)
s.replace("[\n]".toRegex(), "")
} else {
s
}
if (!textModified.get()) {
val fruit = if (name.isNullOrEmpty() || name.isNullOrBlank()) {
null
} else {
s.toString()
}
listeners.forEach{ it.onFruitSet(fruit, goToNext.get()) }
}
}
}
</code></pre>
<p>There are some corner cases that don't work very good, specially with the \n, and when the user clicks on "Next".</p>
<p>Any hint on how to improve it? or is there any component already doing this?</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:02:35.413",
"Id": "462325",
"Score": "0",
"body": "Question, because I don't know everything about Android... \nwhen `s.replace(\"[\\n]\".toRegex(), \"\")` is called, it is the last thing that `onTextChanged` does (as `textModified` is set). Does `s.replace` change the `CharSequence` itself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:14:16.723",
"Id": "462359",
"Score": "0",
"body": "yes. It does. That's what I found the most problems"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:20:10.847",
"Id": "462366",
"Score": "0",
"body": "I searched further, and I believe it shouldn't: https://stackoverflow.com/a/6003815/3193776.\nIn afterTextChanged, you are doing the same operation. Guess that's where the value is updated. Updating means the value is changed, so the loop starts over."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T15:54:36.017",
"Id": "235969",
"Score": "1",
"Tags": [
"android",
"kotlin",
"autocomplete"
],
"Title": "Android Studio Autocomplete that creates a new entry if no entry selected"
}
|
235969
|
<p>I've a C# WinForms application that relies heavily on sending <code>HttpWebRequest</code>s. I've build an <code>HttpWebRequestBuilder</code>, and <code>WebRequestBodyBuilder</code>.</p>
<pre><code>public class HttpWebRequestBuilder
{
private HttpWebRequest _httpWebRequest; // The object that will be built.
public HttpWebRequestBuilder(string url) : this(url, Constants.FirefoxUserAgent) // Use firefox user-agent by default (Constants is a static class that has FirefoxUserAgent constant).
{
}
public HttpWebRequestBuilder(string url, string userAgent)
{
_httpWebRequest = WebRequest.CreateHttp(url); // Create an HttpWebRequest.
_httpWebRequest.UserAgent = userAgent; // Set the user-agent.
_httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // Set automatic decompression. I want this value for all requests.
}
public HttpWebRequestBuilder WithMethod(string method) // Set the method, "GET", "POST", etc. The default is "GET".
{
_httpWebRequest.Method = method;
return this;
}
public HttpWebRequestBuilder Accepts(string accept) // Set the "Accept" header.
{
_httpWebRequest.Accept = accept;
return this;
}
public HttpWebRequestBuilder WithContentType(string contentType) // Set the "Content-Type" header.
{
_httpWebRequest.ContentType = contentType;
return this;
}
public HttpWebRequestBuilder WithCookies(CookieContainer container) // Set a cookie container.
{
_httpWebRequest.CookieContainer = container;
return this;
}
public HttpWebRequestBuilder AllowAutoRedirect(bool allow) // Set AllowAutoRedirect
{
_httpWebRequest.AllowAutoRedirect = allow;
return this;
}
public HttpWebRequestBuilder WithReferer(string referer) // Set referer.
{
_httpWebRequest.Referer = referer;
return this;
}
public HttpWebRequestBuilder WithCustomHeader(string name, string value) // Add a custom header.
{
_httpWebRequest.Headers.Add(name, value);
return this;
}
public async Task<HttpWebRequestBuilder> PostAsync(WebRequestBodyBuilder bodyBuilder) // Takes an object of WebRequestBodyBuilder (which just makes a string like "param1=value1&param2=value2&...."
{
byte[] buffer = Encoding.UTF8.GetBytes(bodyBuilder.ToString());
using (var reqStrm = await _httpWebRequest.GetRequestStreamAsync()) // Write the body in the request stream.
{
reqStrm.Write(buffer, 0, buffer.Length);
}
return this;
}
public HttpWebRequest Build() // Returns the actual HttpWebRequest
{
return _httpWebRequest;
}
}
</code></pre>
<pre><code>public class WebRequestBodyBuilder
{
private StringBuilder _stringBuilder = new StringBuilder();
public WebRequestBodyBuilder SetKeyValuePair(string key, string value)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException($"Argument {nameof(key)} can't be null or whitespace."); // key can't be null, but value CAN!
if (!string.IsNullOrWhiteSpace(_stringBuilder.ToString()))
_stringBuilder.Append("&"); // First call shouldn't add "&" in the first.
_stringBuilder.Append($"{WebUtility.UrlEncode(key)}={WebUtility.UrlEncode(value)}");
return this;
}
public override string ToString()
{
return _stringBuilder.ToString(); // ToString is used in the HttpWebRequestBuilder, in the PostAsync method.
}
}
</code></pre>
<p>An example usage of these is like the following:</p>
<pre><code>var bodyBuilder = new WebRequestBodyBuilder()
.SetKeyValuePair("username", Account.Username)
.SetKeyValuePair("password", Account.Password)
.SetKeyValuePair("auth_token", _token);
HttpWebRequest req = (await (new HttpWebRequestBuilder() // The await is for PostAsync.
.WithMethod("POST")
.WithReferer("https://website.com/login")
.WithCookies(_cookies)
.Accepts("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.WithContentType("application/x-www-form-urlencoded")
.AllowAutoRedirect(false).PostAsync(bodyBuilder))).Build();
// Do something with req, like await req.GetResponseAsync()
</code></pre>
<p>I'm just starting learning design patterns, so I want to make sure that I'm not misusing them.</p>
<p><strong>I'm aware that docs recommends HttpClient over HttpWebRequest, but this is another story. My question is specific about applying the builder pattern in this case</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:15:48.757",
"Id": "462100",
"Score": "2",
"body": "Why do you need this builder at all when you can simply [initialize the properties](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer)? Part of learning design patterns is when NOT to use them because there are simpler alternatives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T06:45:48.187",
"Id": "462142",
"Score": "0",
"body": "@RolandIllig, The advantages I got are: • Having AutomaticDecompression and User-Agent set for all requests automatically. • The request body builder allows me for easier usage. • For me, it just looks easier, but I may be mistaken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:00:16.270",
"Id": "462339",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:03:34.300",
"Id": "462340",
"Score": "0",
"body": "@BCdotWEB, Does the new title look good to you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:22:45.947",
"Id": "462344",
"Score": "0",
"body": "@Youssef13 Like I said: the title should simply state the task accomplished by the code. Read the link I posted in my comment, which for instance contains this hint: **\"If your title contains a question, it is likely a bad title.\"**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:11:47.247",
"Id": "462358",
"Score": "0",
"body": "The code task is \"writing a builder for HttpWebRequest\" which is already stated."
}
] |
[
{
"body": "<p>Good implementation. Few minor bits:</p>\n\n<ol>\n<li><p>Mark <code>_httpWebRequest</code> as <code>readonly</code> as you're not assigning (nor want anyone to assign) to it outside of the constructor.</p></li>\n<li><p>Extract an interface (<code>IHttpRequestBuilder</code>) and have each method return that rather than the concrete class. This will allow for additional implementations or mocking for unit testing other parts of your system.</p>\n\n<p>2a. The same advice as above goes for <code>WebRequestBodyBuilder</code>.</p></li>\n<li><p><code>PostAsync</code> is already an <code>async</code> method, so continue using async implementations like <code>WriteAsync()</code> instead of <code>Write()</code>.</p></li>\n<li><p>Create constructors that take <code>Uri</code> parameters as well.</p></li>\n</ol>\n\n<p>Results:</p>\n\n<p><strong>IHttpRequestBuilder.cs</strong></p>\n\n<pre><code>public interface IHttpWebRequestBuilder\n{\n IHttpWebRequestBuilder WithMethod(string method); // Set the method, \"GET\", \"POST\", etc. The default is \"GET\".\n\n IHttpWebRequestBuilder Accepts(string accept); // Set the \"Accept\" header.\n\n IHttpWebRequestBuilder WithContentType(string contentType); // Set the \"Content-Type\" header.\n\n IHttpWebRequestBuilder WithCookies(CookieContainer container); // Set a cookie container.\n\n IHttpWebRequestBuilder AllowAutoRedirect(bool allow); // Set AllowAutoRedirect\n\n IHttpWebRequestBuilder WithReferer(string referer); // Set referer.\n\n IHttpWebRequestBuilder WithCustomHeader(string name, string value); // Add a custom header.\n\n Task<IHttpWebRequestBuilder> PostAsync(IWebRequestBodyBuilder bodyBuilder); // Takes an object of WebRequestBodyBuilder (which just makes a string like \"param1=value1&param2=value2&....\"\n\n HttpWebRequest Build(); // Returns the actual HttpWebRequest\n}\n</code></pre>\n\n<p><strong>HttpRequestBuilder.cs</strong></p>\n\n<pre><code>public class HttpWebRequestBuilder : IHttpWebRequestBuilder\n{\n private readonly HttpWebRequest _httpWebRequest; // The object that will be built.\n public HttpWebRequestBuilder(string url) : this(url, Constants.FirefoxUserAgent) // Use firefox user-agent by default (Constants is a static class that has FirefoxUserAgent constant).\n {\n }\n\n public HttpWebRequestBuilder(Uri uri) : this(uri, Constants.FirefoxUserAgent) // Use firefox user-agent by default (Constants is a static class that has FirefoxUserAgent constant).\n {\n }\n\n public HttpWebRequestBuilder(string url, string userAgent) : this(new Uri(url), userAgent)\n {\n }\n\n public HttpWebRequestBuilder(Uri uri, string userAgent)\n {\n _httpWebRequest = WebRequest.CreateHttp(uri); // Create an HttpWebRequest.\n _httpWebRequest.UserAgent = userAgent; // Set the user-agent.\n _httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // Set automatic decompression. I want this value for all requests.\n }\n\n public IHttpWebRequestBuilder WithMethod(string method) // Set the method, \"GET\", \"POST\", etc. The default is \"GET\".\n {\n _httpWebRequest.Method = method;\n return this;\n }\n\n public IHttpWebRequestBuilder Accepts(string accept) // Set the \"Accept\" header.\n {\n _httpWebRequest.Accept = accept;\n return this;\n }\n\n public IHttpWebRequestBuilder WithContentType(string contentType) // Set the \"Content-Type\" header.\n {\n _httpWebRequest.ContentType = contentType;\n return this;\n }\n\n public IHttpWebRequestBuilder WithCookies(CookieContainer container) // Set a cookie container.\n {\n _httpWebRequest.CookieContainer = container;\n return this;\n }\n\n public IHttpWebRequestBuilder AllowAutoRedirect(bool allow) // Set AllowAutoRedirect\n {\n _httpWebRequest.AllowAutoRedirect = allow;\n return this;\n }\n\n public IHttpWebRequestBuilder WithReferer(string referer) // Set referer.\n {\n _httpWebRequest.Referer = referer;\n return this;\n }\n\n public IHttpWebRequestBuilder WithCustomHeader(string name, string value) // Add a custom header.\n {\n _httpWebRequest.Headers.Add(name, value);\n return this;\n }\n\n public async Task<IHttpWebRequestBuilder> PostAsync(IWebRequestBodyBuilder bodyBuilder) // Takes an object of WebRequestBodyBuilder (which just makes a string like \"param1=value1&param2=value2&....\"\n {\n byte[] buffer = Encoding.UTF8.GetBytes(bodyBuilder.ToString());\n using (var reqStrm = await _httpWebRequest.GetRequestStreamAsync()) // Write the body in the request stream.\n {\n await reqStrm.WriteAsync(buffer, 0, buffer.Length);\n }\n return this;\n }\n\n public HttpWebRequest Build() // Returns the actual HttpWebRequest\n {\n return _httpWebRequest;\n }\n}\n</code></pre>\n\n<p><strong>IWebRequestBodyBuilder.cs</strong></p>\n\n<pre><code>public interface IWebRequestBodyBuilder\n{\n IWebRequestBodyBuilder SetKeyValuePair(string key, string value);\n}\n</code></pre>\n\n<p><strong>WebRequestBodyBuilder.cs</strong></p>\n\n<pre><code>public class WebRequestBodyBuilder : IWebRequestBodyBuilder\n{\n private readonly StringBuilder _stringBuilder = new StringBuilder();\n\n public IWebRequestBodyBuilder SetKeyValuePair(string key, string value)\n {\n if (string.IsNullOrWhiteSpace(key))\n throw new ArgumentException($\"Argument {nameof(key)} can't be null or whitespace.\"); // key can't be null, but value CAN!\n\n if (!string.IsNullOrWhiteSpace(_stringBuilder.ToString()))\n _stringBuilder.Append(\"&\"); // First call shouldn't add \"&\" in the first.\n _stringBuilder.Append($\"{WebUtility.UrlEncode(key)}={WebUtility.UrlEncode(value)}\");\n return this;\n }\n\n public override string ToString()\n {\n return _stringBuilder.ToString(); // ToString is used in the HttpWebRequestBuilder, in the PostAsync method.\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:16:42.893",
"Id": "462082",
"Score": "0",
"body": "Good points! I'm only wondering the usage of interface, why would I need it if I have only one class that implements it? There is no scenario in mind that will make me implement another class. Unfortunately, \"interfaces\" concept is always confuses me, especially, when I see that only one class implements it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:26:22.690",
"Id": "462085",
"Score": "0",
"body": "That's probably a secondary reason to my other justification: being able to mock the interface (using, for example, Moq) when writing unit tests that use this class. It fosters the I and D in SOLID development principles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:32:05.040",
"Id": "462086",
"Score": "1",
"body": "Why not use the concrete class for unit testing? I was told that mocking for unit tests is used when the class does some database operations, so I want to avoid making changes to a production database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:47:42.283",
"Id": "462087",
"Score": "1",
"body": "That's really a longer question with a longer answer, but the simple answer is: you mock ALL dependencies so ONLY the class/unit you're testing is being exercised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:10:57.600",
"Id": "462099",
"Score": "0",
"body": "Mock a URL builder? That would mean you also have to mock `String` and `int32`, if I understand the word _all_ correctly."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:06:01.623",
"Id": "235972",
"ParentId": "235970",
"Score": "4"
}
},
{
"body": "<p>I have modified yours, (not tested), but I want to share it just to give you some insights, not the best design, but I felt I need to share it. </p>\n\n<pre><code>//singleton class\npublic sealed class HttpRequestClient\n{\n internal enum MethodType\n {\n GET, POST, PUT, DELETE\n }\n\n internal enum RequestContentType { JSON, XML, x_www_form_urlencoded }\n\n private string Url;\n // for concurrent requests\n private static HttpWebRequest _request;\n\n private static HttpRequestClient _client;\n\n private HttpRequestHeaderBuilder HeaderBuilder;\n\n private HttpRequestMethodBuilder MethodBuilder;\n\n //body\n private StringBuilder _stringBuilder;\n\n public HttpRequestClient(string url)\n {\n if(string.IsNullOrEmpty(url)) { throw new ArgumentNullException(nameof(url)); }\n\n _client = _client ?? (_client = new HttpRequestClient(url));\n\n _request = _request = WebRequest.CreateHttp(new Uri(url)); // this will call the main method CreateHttp(Uri url) directly.\n\n _stringBuilder = new StringBuilder();\n }\n\n internal struct HttpRequestHeaderBuilder\n {\n internal HttpRequestHeaderBuilder Accepts(string accept) // Set the \"Accept\" header.\n {\n // do the same for the other methods, always validate the value beofre assign it.\n if (string.IsNullOrEmpty(accept)) { throw new ArgumentNullException(nameof(accept)); }\n\n _request.Accept = accept;\n\n return this;\n }\n\n internal HttpRequestHeaderBuilder ContentType(RequestContentType contentType) // Set the \"Content-Type\" header.\n {\n switch (contentType)\n {\n case RequestContentType.x_www_form_urlencoded:\n _request.ContentType = \"application/x-www-form-urlencoded\";\n break;\n case RequestContentType.XML:\n _request.ContentType = \"text/xml\";\n break;\n case RequestContentType.JSON:\n _request.ContentType = \"application/json\";\n break;\n default:\n _request.ContentType = \"application/x-www-form-urlencoded\";\n break;\n }\n\n return this;\n }\n\n internal HttpRequestHeaderBuilder Cookies(CookieContainer container) // Set a cookie container.\n {\n _request.CookieContainer = container;\n return this;\n }\n\n internal HttpRequestHeaderBuilder AutoRedirect(bool allow) // Set AllowAutoRedirect\n {\n _request.AllowAutoRedirect = allow;\n return this;\n }\n\n internal HttpRequestHeaderBuilder Referer(string referer) // Set referer.\n {\n _request.Referer = referer;\n return this;\n }\n\n internal HttpRequestHeaderBuilder UserAgent(string agent) // Set referer.\n {\n _request.UserAgent = agent;\n return this;\n }\n\n internal HttpRequestHeaderBuilder Custom(string name, string value) // Set referer.\n {\n _request.Headers.Add(name, value);\n return this;\n }\n\n\n\n internal HttpRequestClient AddBody(IDictionary<string, string> values) => _client.AddBody(values);\n\n internal HttpRequestHeaderBuilder AddHeader() => _client.AddHeader();\n\n internal async Task<HttpRequestClient> SendAsAsync(MethodType method) => await _client.MethodBuilder.SendAsync(method);\n\n }\n\n private struct HttpRequestMethodBuilder\n {\n\n internal async Task<HttpRequestClient> SendAsync(MethodType method)\n {\n switch (method)\n {\n case MethodType.GET:\n return await GetAsync().ConfigureAwait(false);\n case MethodType.POST:\n return await PostAsync().ConfigureAwait(false);\n default:\n return await GetAsync().ConfigureAwait(false);\n }\n }\n\n private async Task<HttpRequestClient> PostAsync() // Takes an object of WebRequestBodyBuilder (which just makes a string like \"param1=value1&param2=value2&....\"\n {\n byte[] buffer = Encoding.UTF8.GetBytes(_client._stringBuilder.ToString());\n\n using (var reqStrm = await _request.GetRequestStreamAsync().ConfigureAwait(false)) // Write the body in the request stream.\n {\n reqStrm.Write(buffer, 0, buffer.Length);\n }\n\n return _client;\n }\n\n private async Task<HttpRequestClient> GetAsync()\n {\n await _request.GetResponseAsync().ConfigureAwait(false);\n return _client;\n }\n }\n\n // Not sure why you're treating the body as QueryString, instead of object or plain string as a body could be attach in the url or the request body and both are totally different!\n // Consider serializations from (JSON, XML specifically)\n // you must have at least an overload of object or string to pass the serialized body. \n internal HttpRequestClient AddBody(IDictionary<string, string> values)\n {\n if (values is null) { throw new ArgumentNullException($\"Argument {nameof(values)} can't be null\"); }\n\n var _stringBuilder = new StringBuilder();\n\n foreach (var pair in values)\n {\n _stringBuilder\n .Append(WebUtility.UrlEncode(pair.Key))\n .Append('=')\n .Append(WebUtility.UrlEncode(pair.Value))\n .Append(\"&\");\n }\n\n _stringBuilder.Remove(_stringBuilder.ToString().Length - 1, 1); // remove the last &\n\n return this;\n }\n\n internal HttpRequestHeaderBuilder AddHeader() => HeaderBuilder;\n\n internal async Task<HttpRequestClient> SendAsAsync(MethodType method) => await MethodBuilder.SendAsync(method).ConfigureAwait(false);\n\n\n\n}\n</code></pre>\n\n<p>Usage : </p>\n\n<pre><code>var body = new Dictionary<string, string>\n{\n {\"SomeHeader\",\"SomeValue\" }\n};\n\nvar request = new HttpRequestClient(\"\")\n .AddHeader()\n .ContentType(HttpRequestClient.RequestContentType.x_www_form_urlencoded)\n .Accepts(\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\")\n .Referer(@\"https://website.com/login\")\n .AutoRedirect(false)\n .AddBody(body)\n .SendAsAsync(HttpRequestClient.MethodType.POST);\n</code></pre>\n\n<p>The <code>SendAsAsync</code> I made it as final call, so when you call it you can't add any header or body. The things that need to be add is to check the existing headers, and body, as you don't want to override the body twice ! you need only one body, so prevent that from happening. While the header is a dictionary, so the keys are unique, if any duplicates, will throw an error by default, so handle that as well. </p>\n\n<p>I used <code>Enum</code> to avoid rewriting the same strings (like content type). </p>\n\n<p>I'm sure there a lot of needed work on it, but as I said, it's just to give you some insights. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:55:34.967",
"Id": "236038",
"ParentId": "235970",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235972",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T16:20:44.343",
"Id": "235970",
"Score": "3",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Is it good to use the builder design pattern for HttpWebRequest?"
}
|
235970
|
<p>I'm looking for general feedback as how to improve my code. I wrote the program starting out with no functions, making it very difficult to adapt. When I separated the program into functions it became very repetitive.</p>
<p>How can I improve my code?</p>
<pre class="lang-py prettyprint-override"><code>"""
A program for comparrison of triangulation (wave or skipping stones, not sure what to call it?) to division by same limited known prime numbers
as how well they spot new ones
"""
from math import sin #only for wave
from math import pi #period and period displacement of wave
from math import sqrt #On the top of my head estimate of average overlapping multiplied waves. sin(pi/4) = sqrt(2)/2
from math import e
from statistics import mean
def Primer(number, numbers):#Generates primes by modulus for every prime in numbers
iteration = 0
while number % numbers[iteration] != 0: # as long as number modulus prime givesw remainder it keeps dividing
iteration +=1
if iteration == len(numbers):# Every former prime in list of primes hass been divided with remainder
return number
else:
pass
def Triangulation(numbers, x): #or skipping stone analogy. I dont understand this in combinatorics. prime 2 wave skips every other, prime every third and so on
wave = 1
for number in numbers:
wave *= abs(sin(x*pi/number)*2/sqrt(2)) # sqrt(2)/2 * 2/swrt(2) = 1 to keep the wave around zero
if wave > 1:
return wave, x
else:
return "","" #cant unpack None type
primes = [2,3]
exponent = 3
limit = int(10**exponent)
window = [0, limit]
triangulation = []
true = []
false = []
primes_for_triangulation = []
use_primes_up_to = e**(exponent)
primes_in_window = []
wave_amplitude = []
true_wave_amplitude = []
false_wave_amplitude = []
primes_by_limited_division = []
false_quotient = []
true_quotient = []
for number in range(len(primes)+2, limit, 1):
possibly_prime = Primer(number, primes)#feeds primer with numbers and past primes...
if type(possibly_prime) == int:
primes.append(possibly_prime)#when prime is found it gets put into cycles
for prime in primes:#creating a list from part of list
if prime < use_primes_up_to:
primes_for_triangulation.append(prime)
else:
pass
if prime >= window[0] and prime < window[1]:#remenant from when window was different than zero to limit
primes_in_window.append(prime)
else:
pass
for x in range(window[0], window[1], 1):# For every x down the number line the skipping stones hops over unkown primes diving into previous ones...
possibly_wave_amplitude, possibly_triangulated = (Triangulation(primes_for_triangulation, x))
if type(possibly_triangulated) == int: #... if its int theyre in the air
triangulation.append(possibly_triangulated)
wave_amplitude.append(possibly_wave_amplitude)
for tri in range(0, len(triangulation), 1):#seperating 2 list into 4 by true or false
if triangulation[tri] in primes:
true.append(tri)
true_wave_amplitude.append(wave_amplitude[tri])
else:
false.append(tri)
false_wave_amplitude.append(wave_amplitude[tri])
for number in range(4, limit, 1): #looking for primes...
limited_division = Primer(number, primes_for_triangulation)#...by limited prime list
if type(limited_division) == int:
primes_by_limited_division.append(limited_division)
for possibly_prime in primes_by_limited_division:#seperating a list into 2 by true or false
if possibly_prime in primes:
true_quotient.append(possibly_prime)
else:
false_quotient.append(possibly_prime)
#print out dosent handle zero
print("LIMITED DIVISION AND TRIANGULATION UP TO LIMIT", limit)
print("Primes up to ", use_primes_up_to, " were used to triangulate and to do limited division")
print("How many limited true divided ", len(true_quotient))
print("How many limited faulty divided ", len(false_quotient))
print("True per false ", len(true_quotient)/len(false_quotient))
print("Triangulate in window with lower bound being ", window[0], " and upper bound being limit ", window[1])
print("How many triangulated to be primes = ", len(triangulation))
print("Triangulated per window span = ", len(triangulation)/(window[1]-window[0]))
print("How many triangulated per primes in window ", len(triangulation)/len(primes_in_window)) #Zero division
print("How many Falesly triangulated ", len(false))
print("How many truely triangulated ", len(true))
print("True per false ", len(true)/len(false)) #Zero division
print("Mean of true wave amplitude ", mean(true_wave_amplitude))
print("Mean of false wave amplitude ", mean(false_wave_amplitude))
print("Largest true wave amplitude ", max(true_wave_amplitude))
print("Largest false wave amplitude ", max(false_wave_amplitude))
print("Smallest true wave amplitude ", min(true_wave_amplitude))
print("Smallest flase wave amplitude ", min(false_wave_amplitude))
print("\n Wave amplitude of falsely triangulated \n\n", false_wave_amplitude)
print("\n Wave amplitude of truely triangulated \n\n", true_wave_amplitude)
</code></pre>
<p>I would be specifically interested in:</p>
<ul>
<li><p>How to slim down code by handling lists in other ways than with the for statement.</p>
<pre class="lang-py prettyprint-override"><code>for tri in range(0, len(triangulation), 1):#seperating 2 list into 4 by true or false
if triangulation[tri] in primes:
true.append(tri)
true_wave_amplitude.append(wave_amplitude[tri])
else:
false.append(tri)
false_wave_amplitude.append(wave_amplitude[tri])
</code></pre></li>
<li><p>How to handle returning None and a tuple of two strings?</p>
<pre class="lang-py prettyprint-override"><code>def Triangulation(numbers, x): #or skipping stone analogy. I dont understand this in combinatorics. prime 2 wave skips every other, prime every third and so on
wave = 1
for number in numbers:
wave *= abs(sin(x*pi/number)*2/sqrt(2)) # sqrt(2)/2 * 2/swrt(2) = 1 to keep the wave around zero
if wave > 1:
return wave, x
else:
return "","" #cant unpack None type
</code></pre></li>
<li><p>How to not fill list with None type, or how to remove None type easily?</p>
<pre class="lang-py prettyprint-override"><code>for number in range(4, limit, 1): #looking for primes...
limited_division = Primer(number, primes_for_triangulation)#...by limited prime list
if type(limited_division) == int:
primes_by_limited_division.append(limited_division)
</code></pre></li>
</ul>
|
[] |
[
{
"body": "<p>Well, your biggest problem is the length of the scope of variables. You declare/define all the variables at the beginning before all the code. This is not required, nor is it any good. When I try to read the code I have no chance to find the usage of variables as I have to scan all(!) lines if it is altered somewhere. Such long scope is real evil. As you said the code is unreadable and thus unmaintainable. your variable names get long and longer to avoid name collisions. So we start to move the variable definitions down in the code to the place where they are needed first.</p>\n\n<pre><code># [...]\n\nprimes = [2,3]\nexponent = 3\nlimit = int(10**exponent)\nfor number in range(len(primes)+2, limit, 1):\n possibly_prime = Primer(number, primes) # feeds primer with numbers and past primes...\n if type(possibly_prime) == int:\n primes.append(possibly_prime) # when prime is found it gets put into cycles\n\nwindow = [0, limit]\nprimes_for_triangulation = []\nuse_primes_up_to = e**(exponent)\nprimes_in_window = []\nfor prime in primes:#creating a list from part of list\n if prime < use_primes_up_to:\n primes_for_triangulation.append(prime)\n else:\n pass\n if prime >= window[0] and prime < window[1]:#remenant from when window was different than zero to limit\n primes_in_window.append(prime)\n else:\n pass\n\ntriangulation = []\nwave_amplitude = []\nfor x in range(window[0], window[1], 1):# For every x down the number line the skipping stones hops over unkown primes diving into previous ones...\n possibly_wave_amplitude, possibly_triangulated = (Triangulation(primes_for_triangulation, x))\n if type(possibly_triangulated) == int: #... if its int theyre in the air\n triangulation.append(possibly_triangulated)\n wave_amplitude.append(possibly_wave_amplitude)\n\ntrue = []\nfalse = []\ntrue_wave_amplitude = []\nfalse_wave_amplitude = []\nfor tri in range(0, len(triangulation), 1): # seperating 2 list into 4 by true or false\n if triangulation[tri] in primes:\n true.append(tri)\n true_wave_amplitude.append(wave_amplitude[tri])\n else:\n false.append(tri)\n false_wave_amplitude.append(wave_amplitude[tri])\n\nprimes_by_limited_division = []\nfor number in range(4, limit, 1): # looking for primes...\n limited_division = Primer(number, primes_for_triangulation) # ...by limited prime list\n if type(limited_division) == int:\n primes_by_limited_division.append(limited_division)\n\nfalse_quotient = []\ntrue_quotient = []\nfor possibly_prime in primes_by_limited_division: # seperating a list into 2 by true or false\n if possibly_prime in primes:\n true_quotient.append(possibly_prime)\n else:\n false_quotient.append(possibly_prime)\n\n # [...]\n</code></pre>\n\n<p>much better now. Now we have the chance to extract functions. From</p>\n\n<pre><code>primes = [2,3]\nexponent = 3\nlimit = int(10**exponent)\nfor number in range(len(primes)+2, limit, 1):\n possibly_prime = Primer(number, primes) # feeds primer with numbers and past primes...\n if type(possibly_prime) == int:\n primes.append(possibly_prime) # when prime is found it gets put into cycles\n</code></pre>\n\n<p>we make</p>\n\n<pre><code>def get_primes(limit):\n primes = [2,3]\n for number in range(len(primes)+2, limit, 1):\n possibly_prime = Primer(number, primes) # feeds primer with numbers and past primes...\n if type(possibly_prime) == int:\n primes.append(possibly_prime) # when prime is found it gets put into cycles\n return primes\n\nexponent = 3\nlimit = int(10**exponent)\nprimes = get_primes(limit)\n</code></pre>\n\n<p>If you do that with all your first level loops (and move the function definitions before all the remaining (unintended) code, this remaing code at the bottom be much more readable. At least if you chose good function names. You also immediately see what parameters a function needs. At this point you can improve naming and refactor your functions.</p>\n\n<hr>\n\n<p>Now we also do this for the block</p>\n\n<pre><code>window = [0, limit]\nprimes_for_triangulation = []\nuse_primes_up_to = e**(exponent)\nprimes_in_window = []\nfor prime in primes:#creating a list from part of list\n if prime < use_primes_up_to:\n primes_for_triangulation.append(prime)\n else:\n pass\n if prime >= window[0] and prime < window[1]:#remenant from when window was different than zero to limit\n primes_in_window.append(prime)\n else:\n pass\n</code></pre>\n\n<p>We get</p>\n\n<pre><code>def get_primes_for_triangulation(primes, use_primes_up_to):\n primes_for_triangulation = []\n for prime in primes: # creating a list from part of list\n if prime < use_primes_up_to:\n primes_for_triangulation.append(prime)\n return primes_for_triangulation\n\ndef get_primes_in_window(primes, window):\n primes_in_window = []\n for prime in primes: # creating a list from part of list\n if prime >= window[0] and prime < window[1]: # remenant from when window was different than zero to limit\n primes_in_window.append(prime)\n return primes_in_window\n\nuse_primes_up_to = e**(exponent)\nprimes_for_triangulation = get_primes_for_triangulation(primes, use_primes_up_to)\n\nwindow = [0, limit]\nprimes_in_window = get_primes_in_window(primes, window)\n</code></pre>\n\n<p>As I said before we now have a chance to take a close look at the extracted functions. We notice that they are trivial and can be replaced by list comprehension.</p>\n\n<pre><code>def get_primes_for_triangulation(primes, use_primes_up_to):\n return [p for p in primes if p < use_primes_up_to]\n\ndef get_primes_in_window(primes, window):\n # remenant from when window was different than zero to limit\n return [p for p in primes if p >= window[0] and p < window[1]]\n</code></pre>\n\n<p>You may now inline the comprehensions directly in your main body as the comprehensions are trivial. Note: Sometimes it is desirable to keep the functions as the main code may be more readable and one has the chance to add docstrings to explain the algorithms inside the functions.</p>\n\n<hr>\n\n<p>Now let's have a look at <code>Primer</code>. We start with your function</p>\n\n<pre><code>def Primer(number, numbers): # Generates primes by modulus for every prime in numbers\n iteration = 0\n while number % numbers[iteration] != 0: # as long as number modulus prime givesw remainder it keeps dividing\n iteration +=1\n if iteration == len(numbers): # Every former prime in list of primes hass been divided with remainder\n return number\n else:\n pass\n</code></pre>\n\n<p>We immediately see there is a superfluous else branch that we remove</p>\n\n<pre><code>def Primer(number, numbers): # Generates primes by modulus for every prime in numbers\n iteration = 0\n while number % numbers[iteration] != 0: # as long as number modulus prime givesw remainder it keeps dividing\n iteration +=1\n if iteration == len(numbers): # Every former prime in list of primes hass been divided with remainder\n return number\n</code></pre>\n\n<p>If you iterate over a range or any other iterable (list, ...) you use a for loop. All the error prone fiddling with indices (off by one, ...) are gone. We rewrite to</p>\n\n<pre><code>def Primer(number, numbers): # Generates primes by modulus for every prime in numbers\n for n in numbers:\n if number % n == 0:\n return\n return number\n</code></pre>\n\n<p>Now we see a function that returns a single number that was passed as a parameter or it returns <code>None</code>. This smells like a boolean test. So the function</p>\n\n<ul>\n<li>shall return a boolean</li>\n<li>shall have a name starting with <code>is_</code> allowing it to be used in a readable test</li>\n</ul>\n\n<p>The caller now gets a bool which is no problem as he knows the number anyway. We get</p>\n\n<pre><code>def is_divisible(number, numbers): # Generates primes by modulus for every prime in numbers\n for n in numbers:\n if number % n == 0:\n return True\n return False\n</code></pre>\n\n<p>which we shorten with the help of <code>any</code> to</p>\n\n<pre><code>def is_divisible(number, numbers): # Generates primes by modulus for every prime in numbers\n return any(number % n == 0 for n in numbers)\n</code></pre>\n\n<p>which we now could easily inline as well.</p>\n\n<p>Now to the caller. Your function</p>\n\n<pre><code>def get_primes(limit):\n primes = [2,3]\n for number in range(len(primes)+2, limit, 1):\n possibly_prime = Primer(number, primes) # feeds primer with numbers and past primes...\n if type(possibly_prime) == int:\n primes.append(possibly_prime) # when prime is found it gets put into cycles\n return primes\n</code></pre>\n\n<p>has to use the new test like</p>\n\n<pre><code>def get_primes(limit):\n primes = [2,3]\n for number in range(len(primes)+2, limit, 1):\n if not is_divisible(number, primes):\n primes.append(number) # when prime is found it gets put into cycles\n return primes\n</code></pre>\n\n<p>we got rid of this type test and <code>possibly_prime</code> and have a nice readable function. No we do the inlining where we invert the logic to better fit the caller</p>\n\n<pre><code>def get_primes(limit):\n primes = [2,3]\n for number in range(len(primes)+2, limit, 1):\n if all(number % n != 0 for n in primes):\n primes.append(number) # when prime is found it gets put into cycles\n return primes\n</code></pre>\n\n<p>Nice and readable. So readable, that we immediately start doubting the algorithm. Especially the range is horrible. Why start at <code>len(primes)+2</code>? Why step <code>1</code>? Why test for the whole list of primes?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:13:35.513",
"Id": "462215",
"Score": "0",
"body": "Why are u so angry?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:17:45.957",
"Id": "462216",
"Score": "0",
"body": "As for the semi constructive inprovements (semi because it went over my head, obviuosly) I will look into your feedback \"Scan\"\n\"Functions in functions\"\n\"Overwrite variables and or lists\"\n\"Refactor functions meaning \"\n\"Ad docstrings in between functions in main\"\n\"Why is else pass superflous (whats else pass for)\"\n\"What is indices\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:20:20.730",
"Id": "462217",
"Score": "0",
"body": "Is theire a single question about how to check for primes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:20:57.063",
"Id": "462218",
"Score": "0",
"body": "A tag about how to check for primes? Are u even interested as to why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:22:07.043",
"Id": "462220",
"Score": "0",
"body": "Whos we that u are reffering to? It aint me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:29:52.370",
"Id": "462221",
"Score": "0",
"body": "Why isnt this sort of such distain bordering to hate shut down?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T00:13:07.713",
"Id": "462679",
"Score": "1",
"body": "@Progrmmingisfun I fail to see anything that is aggressive or hostile in the above post. To me the answer just reads as unemotional ways to improve your code. Given the large amount of comments you've left here, were you in a conversation with the answerer?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T18:42:40.580",
"Id": "235978",
"ParentId": "235974",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T17:32:51.340",
"Id": "235974",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings"
],
"Title": "Spotting prime numbers with use of limited prime numbers"
}
|
235974
|
<p>I have written this code that connects to a mysql database. The function should be able to be used as a context manager - via <code>with</code>. It is working, but I am not sure if this is a great way of doing it.</p>
<p><code>conect.py</code></p>
<pre><code>import os
import mysql.connector
from mysql.connector import errorcode
import contextlib
_CFG = {
'user': os.getenv("MYSQL_USER"),
'password': os.getenv("MYSQL_PASSWORD"),
'host': os.getenv("MYSQL_SERVER"),
'database': os.getenv("SENSOR_DB"),
'raise_on_warnings': True
}
@contextlib.contextmanager
def _connect(db=None):
if db:
_CFG["database"] = db
try:
print("{usr} connecting to {db} on {host}.".format(
usr=_CFG["user"],
db=_CFG["database"],
host=_CFG["host"]
)
)
connection = mysql.connector.connect(**_CFG)
yield connection
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
yield None
else:
connection.commit()
finally:
connection.close()
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>Obvious (dumb) point - I'd suggest using <code>logging</code> instead of <code>print</code></li>\n<li>I would have some kind of builder for <code>_CFG</code> so I could choose if I use environment variables for configuration or something else</li>\n<li>Instead of <code>str.format</code>, you may want to use fstring: <code>f\"{_CFG[\"user\"]} connecting to {_CFG[\"database\"]} on {_CFG[\"host\"]}.\"</code></li>\n<li>Instead of <code>yield None</code> you may want to reraise exception (from <a href=\"https://docs.python.org/3/library/contextlib.html\" rel=\"nofollow noreferrer\">the docs</a>, \"<em>If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception</em>\"). Otherwise, your code will fail with a funny exception.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T18:43:58.570",
"Id": "462729",
"Score": "0",
"body": "I was wondering even if the `_connect` function acts as context manger , should I just call it at module level instead of using `with` inside a function, then the connection object will be available at multiple functions ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:25:53.547",
"Id": "462805",
"Score": "0",
"body": "@Ciastopiekarz I think that if you want to have a shared connection in multiple functions, you would rather not use a context manager at all, but some other patterns to handle this. But why would you want this? I would not bother unless I am sure there's some significant performance impact, but I don't think there would be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:27:06.060",
"Id": "462806",
"Score": "0",
"body": "Ok, cool thanks I tried yesterday and didn’t find any significant benefit so switched back."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T17:28:04.987",
"Id": "236033",
"ParentId": "235980",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:10:05.800",
"Id": "235980",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"mysql"
],
"Title": "Connecting and getting mysql connection object"
}
|
235980
|
<p>I wanted to know is this the best way to handle a SegmentedControl using the e.NewValue? Base on the selected segment I hide and select different data?</p>
<p>XAML</p>
<pre><code><telerikInput:RadSegmentedControl.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Option One</x:String>
<x:String>Option Two</x:String>
<x:String>Favorites</x:String>
</x:Array>
</telerikInput:RadSegmentedControl.ItemsSource>
</code></pre>
<p>c#</p>
<pre><code>private void Show_SelectionChanged(object sender, ValueChangedEventArgs<int> e)
{
if (HomeListView.ItemsSource != null)
{
TilesViewModel gtvm = new TilesViewModel();
switch (e.NewValue)
{
case 0:
var selectoneItems = gtvm.ListItems.Where(x => x.IsProfessional).ToList();
HomeGuidelineListView.ItemsSource = selectoneItems ;
selecttwoTitle.IsVisible = false;
selectoneTitle.IsVisible = true;
FavOptionsGrid.IsVisible = false;
HomeOptionsGrid.IsVisible = true;
NoFavsMessage.IsVisible = false;
break;
case 1:
var selecttwoItems = gtvm.ListItems.Where(x => x.IsProfessional == false).ToList();
selecttwoTitle.IsVisible = true;
selectoneTitle.IsVisible = false;
FavOptionsGrid.IsVisible = false;
HomeOptionsGrid.IsVisible = true;
NoFavsMessage.IsVisible = false;
break;
case 2:
var favItems = gtvm.GuidelineListItems.Where(x => x.IsFavorite).ToList();
HomeGuidelineListView.ItemsSource = favItems;
HomeOptionsGrid.IsVisible = false;
FavOptionsGrid.IsVisible = true;
break;
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:25:27.503",
"Id": "235981",
"Score": "1",
"Tags": [
"c#",
"xamarin"
],
"Title": "xamarin SegmentedControl"
}
|
235981
|
<p>I made a very basic social network Java program. I was wondering if my design could be improved. I have 2 classes (+ 1 driver) : <code>Person</code> and <code>Graph</code>. I would like now to add a new method <code>hasAccount(Person person)</code> in the <code>Graph</code> class to check if a <code>Person</code> is on the graph. However, so far I don't have any data structure that stores every <code>Person</code> object added on the <code>Graph</code>. What would be the most efficient way to do it?</p>
<pre><code> public class Driver {
public static void main(String[] args) {
Graph facebook = new Graph();
Person sara = new Person("sara");
Person robert = new Person("robert");
Person alex = new Person("alex");
facebook.newFriendship(sara, robert);
facebook.newFriendship(alex, sara);
facebook.printFriends(sara);
facebook.removeFriendship(sara, alex);
facebook.printFriends(sara);
}
}
/*Class to represent friendships*/
public class Graph {
public void newFriendship(Person from, Person to) throws IllegalArgumentException{
if(from == null || to == null){
throw new IllegalArgumentException("One of the account does not exits");
}
from.addFriend(to);
to.addFriend(from);
}
public void removeFriendship(Person from, Person to) throws IllegalArgumentException{
if(from == null || to == null){
throw new IllegalArgumentException("One of the account does not exits");}
from.removeFriend(to);
to.removeFriend(from);
}
public void printFriends(Person user){
System.out.println(user.getFriendList());
}
}
/*Class to represent a User*/
public class Person {
private String name;
private List<Person> friends;
Person(String name){
this.name = name;
friends = new LinkedList();
}
public void addFriend(Person newFriend){
this.friends.add(newFriend);
}
public List getFriendList(){
List<String> friendList = new ArrayList<>();
for(Person friend : friends){
friendList.add(friend.name);
}
return friendList;
}
public void removeFriend(Person toremove){
friends.remove(toremove);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:08:53.590",
"Id": "462106",
"Score": "5",
"body": "We can review your current code if it works, with your feature in mind. But this is code review, we don't do feature-requests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:36:21.660",
"Id": "462108",
"Score": "2",
"body": "(`Graph` does *not* `represent friendships` - and what business would it have to? The \"driver\" seems to be using `Graph` as a go-between. There is no way to *add Person objects on the Graph*. Under what circumstances do you think storage of person related data anywhere else (than with the person) tolerable?)"
}
] |
[
{
"body": "<p><code>Graph</code> is a strange name for something designed to manipulate friendships. As indicated by @greybeard in the comments, it doesn't really represent anything at the moment.</p>\n\n<p><strong>print</strong></p>\n\n<p>I hate seeing methods like <code>printFriends</code> on classes. They very rarely belong. If you want to have the class provide a method/<code>toString</code> implementation that can be used by it's controller to write to the console / log / outputStream then that's one thing. However, hardcoding <code>System.out.println</code> into classes really does limit their usefulness.</p>\n\n<p><strong>control + error checking</strong></p>\n\n<p>Is it valid to call <code>addFriendShip</code> twice for the same friends? To Remove it twice? What are you expecting in this scenario:</p>\n\n<pre><code>facebook.newFriendship(sara, robert);\nfacebook.newFriendship(robert, sara);\n</code></pre>\n\n<p>Sara ends up with two friends, both of whom are Robert. This seems wrong.</p>\n\n<p><strong>Friendship is a two way street</strong></p>\n\n<p>This is nitpicky, but <code>newFriendShip</code> tells both supplied <code>Person</code>s that they have a new friend. Having the parameter names <code>from</code> and <code>to</code> suggests a one directional, rather than two way relationship.</p>\n\n<p><strong>List</strong></p>\n\n<p><code>getFriendList</code> returns a list of <code>String</code>s, unless there's a good reason not to, I'd set the return type appropriately, rather than just returning a basic <code>List</code>. You should also consider using the <code>Stream</code> libraries, they can make your code more concise:</p>\n\n<pre><code>public List<String> getFriendList(){\n return friends.stream().map(f->f.name).collect(Collectors.toList());\n}\n</code></pre>\n\n<p><strong>Graph</strong></p>\n\n<p>There are various structures that Graph could use to keep track of what <code>Person</code>s it knows about. However, there isn't really enough information at the moment to suggest the correct method. Some things to consider include, does Graph need to support adding and removing? If a Person is added, does the graph need to keep track of all that <code>Persons</code> friends as well? How about their friends and so on? What operations are you going to want <code>Graph</code> to support that will use the <code>Person</code>s it knows about?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T13:27:21.463",
"Id": "236021",
"ParentId": "235982",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:39:56.443",
"Id": "235982",
"Score": "-1",
"Tags": [
"java"
],
"Title": "Java basic Adjacency List"
}
|
235982
|
<p>I'm working on an audio player with a terminal interface. I'm designing it for eventual use on a Raspberry Pi with a 480x320px display. </p>
<p>I've broken the code into three main files with the intention of keeping the business logic (player.py) and graphics (view.py) separated and connected only through the main file. I've also included a configuration file where I'm storing future user options and text strings. </p>
<p>I have more functionality planned, so I'd like to make sure I have a solid foundation now while the complexity is low.</p>
<p>Any comments on the architecture, style, or efficacy of the code are welcome. The code is also available on on <a href="https://github.com/ReticulatedSpline/openDAP" rel="nofollow noreferrer">github</a>.</p>
<p><strong>main.py</strong></p>
<pre><code>import sys, os
from pynput import keyboard
from functools import partial
import cfg
from view import View
from player import Player
exit_signal: bool = False
def on_press(key: keyboard.KeyCode, view: View, player: Player):
"""Handle input"""
global exit_signal
key = str(key).strip('\'')
if str(key) == 'p':
view.notify('Playing...')
player.play()
elif key == 'a':
view.notify('Paused')
player.pause()
elif key == 'n':
view.notify('Skipping Forward...')
player.skip_forward()
elif key == 'l':
view.notify('Skipping Back...')
player.skip_back()
elif key == 'q':
view.notify('Exiting...')
exit_signal = True
del player
del view
return
view.update_ui(player.get_metadata())
def tick(view: View, player:Player):
"""For functions run periodically"""
metadata = player.get_metadata()
view.update_ui(metadata)
view = View()
player = Player()
view.notify("Ready!")
with keyboard.Listener(on_press=partial(on_press, view=view, player=player)) as listener:
while exit_signal == False:
tick(view, player)
listener.join() # merge to one thread
os.system('reset') # clean up the console
</code></pre>
<p><strong>player.py</strong></p>
<pre><code>import os
import vlc # swiss army knife of media players
import cfg
from mutagen.easyid3 import EasyID3 as ID3 # audio file metadata
music_path = os.path.abspath(os.path.join(__file__, '../../music'))
playlist_path = os.path.abspath(os.path.join(__file__, '../../playlists'))
class Player:
"""Track player state, wrap calls to the VLC plugin, and handle scanning for media."""
def __init__(self):
self.song_list = []
self.song_idx = 0
self.song_idx_max = 0
self.vlc = vlc.Instance()
self._scan_library()
self.player = self.vlc.media_player_new(self.song_list[self.song_idx])
self._update_song()
def __del__(self):
del self.vlc
return
def _scan_library(self):
for dirpath, _, files in os.walk(music_path):
for file in files:
filepath = os.path.join(dirpath, file)
_, ext = os.path.splitext(filepath)
if ext in cfg.file_types:
self.song_list.append(filepath)
self.song_idx_max += 1
def _get_id3(self, key: str):
metadata = ID3(self.song_list[self.song_idx])
return str(metadata[key]).strip('[\']')
def _update_song(self):
if self.song_list and self.song_idx < len(self.song_list):
self.media = self.vlc.media_new(self.song_list[self.song_idx])
self.media.get_mrl()
self.player.set_media(self.media)
def get_metadata(self):
"""Return a dictionary of title, artist, current runtime and total runtime."""
if (not self.song_list) or (self.song_idx < 0):
return None
else:
# default states when not playing a track are negative integers
curr_time = self.player.get_time() / 1000 # time returned in ms
if (curr_time < 0):
curr_time = 0
run_time = self.player.get_length() / 1000
if (run_time < 0):
run_time = 0
playing = False
else:
playing = True
info = {"playing": playing,
"title": self._get_id3('title'),
"artist": self._get_id3('artist'),
"curr_time": curr_time,
"run_time": run_time}
return info
def play(self):
"""Start playing the current track."""
self.player.play()
def pause(self):
"""Pause the current track. Position is preserved."""
self.player.pause()
def skip_forward(self):
"""Skip the the beginning of the next track and start playing."""
if (self.song_idx < self.song_idx_max):
self.song_idx += 1
self._update_song()
self.play()
def skip_back(self):
"""Skip to the beginning of the last track and start playing."""
if (self.song_idx > 0):
self.song_idx -= 1
self._update_song()
self.play()
</code></pre>
<p><strong>view.py</strong></p>
<pre><code>import cfg # settings
import curses # textual user interface
from datetime import timedelta
class View:
"""Wrap the python Curses library and handle all aspects of the TUI."""
def __init__(self):
self.screen = curses.initscr()
self.max_y_chars, self.max_x_chars = self.screen.getmaxyx()
self._draw_border()
self.line1 = self.max_y_chars - 4
self.line2 = self.max_y_chars - 3
self.line3 = self.max_y_chars - 2
self.screen.refresh()
def __del__(self):
"""Restore the previous state of the terminal"""
curses.endwin()
def _draw_border(self):
self.screen.border(0)
self.screen.addstr(0, (self.max_x_chars - len(cfg.title)) // 2, cfg.title)
def _set_cursor(self):
self.screen.move(2, len(cfg.prompt_en) + 2)
def _clear_line(self, line: int):
self.screen.move(line, 1)
self.screen.clrtoeol()
self._draw_border()
def _strfdelta(self, tdelta: timedelta):
"""Format a timedelta into a string"""
days = tdelta.days
hours, rem = divmod(tdelta.seconds, 3600)
minutes, seconds = divmod(rem, 60)
time_str = ''
if days > 0:
time_str += str(days) + ' days, '
if hours > 0:
time_str += str(hours) + ' hours '
time_str += str(minutes)
time_str += ':'
if (seconds < 10):
time_str += '0'
time_str += str(seconds)
return time_str
def _update_progress_info(self, metadata):
if metadata is None:
return
run_time = metadata["run_time"]
curr_time = metadata["curr_time"]
if run_time == 0:
return
percent = int((curr_time / run_time) * 100)
run_time_str = self._strfdelta(timedelta(seconds=run_time))
curr_time_str = self._strfdelta(timedelta(seconds=curr_time))
time_str = curr_time_str + cfg.time_sep_en + run_time_str + ' (' + str(percent) + '%)'
# two border characters
progress_bar_chars = self.max_x_chars - 2
fill_count = int(progress_bar_chars * curr_time / run_time)
progress_fill = cfg.prog_fill * fill_count
progress_void = ' ' * (progress_bar_chars - fill_count)
progress_bar = progress_fill + progress_void
self.screen.addstr(self.line2, 1, time_str)
self.screen.addstr(self.line3, 1, progress_bar)
def notify(self, string: str):
"""Add a string to the top of the window."""
self._clear_line(1)
self.screen.addstr(1, 1, string)
self._set_cursor()
self.screen.refresh()
def update_ui(self, metadata: dict):
"""Update track metadata and progress indicators."""
self._clear_line(self.line1)
self._clear_line(self.line2)
self._clear_line(self.line3)
if metadata is None:
return
else:
if metadata['playing']:
info_line = metadata['title'] + cfg.song_sep_en + metadata['artist']
self.screen.addstr(self.line1, 1, info_line)
self.screen.addstr(2, 1, cfg.prompt_en)
self._update_progress_info(metadata)
self._draw_border()
self._set_cursor()
self.screen.refresh()
</code></pre>
<p><strong>cfg.py</strong></p>
<pre><code># text strings
title = 'OpenDAP v0.0.0.1'
no_media_en = "Nothing is playing!"
no_load_en = "..."
no_progress_en = "Cannot display progress."
prompt_en = "[P]lay, P[a]use, [N]ext, [L]ast, [Q]uit ▶ "
song_sep_en = " by "
time_sep_en = " of "
# file types to scan for
file_types = {'.mp3', '.flac'}
# progress bar filler
prog_fill = '▒'
</code></pre>
<p>Thank you for your time.</p>
|
[] |
[
{
"body": "<p>Your code is pretty good.</p>\n\n<ul>\n<li><p>You have some Pythonic style problems like <code>on_press</code> should have two blank lines before it, mypy probably would complain about <code>exit_singal: bool = False</code> and un-Pythonic <code>if (...):</code> statements. And so I recommend that you run a linter or two on your code.</p></li>\n<li><p>Personally I don't like <code>view.notify('Playing...')</code> and then <code>player.play()</code>. Personally I would prefer if <code>view</code> and <code>player</code> had the same interface for signals. This would mean that you would have:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if key == 'p':\n view.play()\n player.play()\n</code></pre></li>\n<li><p>Personally I would prefer <code>raise SystemExit(0)</code> rather than <code>exit_signal</code>. This reduces the size of the global scope. You should be able to achieve the same results with a <code>try</code> <code>finally</code>.</p></li>\n<li><p>If you utilize <code>SystemExit</code> and make <code>view</code> and <code>player</code> have the same interface. Then you could convert <code>on_press</code> to be super simple, by using a dictionary:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>INTERFACE = {\n 'p': 'play',\n 'a': 'pause',\n 'n': 'skip_forward',\n 'l': 'skip_back',\n 'q': 'quit',\n}\n\ndef on_press(key: keyboard.KeyCode, view: View, player: Player):\n key = str(key).strip(\"'\")\n function = INTERFACE.get(key, None)\n if function is not None:\n getattr(view, function)()\n getattr(player, function)()\n view.update_ui(player.get_metadata())\n</code></pre></li>\n<li><p>I've found it to be very rare to need to use <code>del</code>, or ever define <code>__del__</code>. Maybe you <em>really</em> need it, maybe you don't?</p></li>\n<li>You can use <code>f'{minutes}:{seconds:0>2}'</code> so that the seconds are padded in <code>View._strfdelta</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T18:37:32.057",
"Id": "462401",
"Score": "0",
"body": "Thanks, there's a lot of great improvements in this answer. Marking it as the solution for now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T09:16:10.987",
"Id": "236017",
"ParentId": "235983",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T20:58:38.603",
"Id": "235983",
"Score": "5",
"Tags": [
"python",
"audio",
"curses"
],
"Title": "Terminal interface audio player based on VLC & Curses"
}
|
235983
|
<p>I am trying to make a very simple event system for learning purposes, after seeing some much more complicated code on the internet I was wondering if what I am doing is fine of if it has major issues. The code works but I am not sure if it is fast and safe.</p>
<p>The part that worries me is that in my test Listener class (KeyListener) I have to do a cast in order to get the correct Event, is this considered bad practice?</p>
<p>Thanks for your help!</p>
<p>Here is the code:</p>
<p>Event.h</p>
<pre><code> extern unsigned int NULL_EVENT;
extern unsigned int KEY_PRESSED_EVENT;
extern unsigned int EVENT_AMOUNT;
class Event
{
public:
Event();
Event(const Event&);
Event& operator=(const Event&);
virtual unsigned int getType() const;
};
</code></pre>
<p>Listener.h:</p>
<pre><code> class Listener
{
public:
Listener();
Listener(const Listener&);
Listener& operator=(const Listener&);
virtual unsigned int getEventType() const;
virtual void onEvent(Event*);
};
</code></pre>
<p>EventHandler.h:</p>
<pre><code> class EventHandler
{
private:
LinkedList<Listener*>* listeners;
void deleteData();
public:
EventHandler();
EventHandler(const EventHandler&);
EventHandler& operator=(const EventHandler&);
~EventHandler();
void registerListener(Listener*);
void onEvent(Event&);
};
</code></pre>
<p>EventHandler.cpp:</p>
<pre><code>EventHandler::EventHandler()
{
listeners = new LinkedList<Listener*>[EVENT_AMOUNT];
}
EventHandler::EventHandler(const EventHandler& handler)
{
listeners = new LinkedList<Listener*>[EVENT_AMOUNT];
for(unsigned int i=0;i<EVENT_AMOUNT;i++)
{
*(listeners + i) = *(handler.listeners + i);
}
}
EventHandler& EventHandler::operator=(const EventHandler& handler)
{
deleteData();
listeners = new LinkedList<Listener*>[EVENT_AMOUNT];
for(unsigned int i=0;i<EVENT_AMOUNT;i++)
{
*(listeners + i) = *(handler.listeners + i);
}
return *this;
}
EventHandler::~EventHandler()
{
deleteData();
}
void EventHandler::deleteData()
{
delete[] listeners;
}
void EventHandler::registerListener(Listener* listener)
{
unsigned int id = listener->getEventType();
assert(id < EVENT_AMOUNT && "Event type is out of bounds!");
if(!(listeners + id)->contains(listener))
{
std::cout << "registering listener of id: " << id << std::endl;
(listeners + id)->add(listener);
}
}
void EventHandler::onEvent(Event& event)
{
unsigned int id = event.getType();
assert(id < EVENT_AMOUNT && "Event type is out of bounds!");
LinkedListIterator<Listener*> itt = (listeners + id)->getIterator();
for(;itt.isValid();itt.next())
{
itt.getElement()->onEvent(&event);
}
}
</code></pre>
<p>Here is test Event and a test Listener:
KeyPressedEvent.h:</p>
<pre><code>class KeyPressedEvent : public Event
{
protected:
unsigned int keyCode;
public:
KeyPressedEvent(unsigned int);
KeyPressedEvent(const KeyPressedEvent&);
KeyPressedEvent& operator=(const KeyPressedEvent&);
unsigned int getKeyCode() const;
virtual unsigned int getType() const override;
};
</code></pre>
<p>KeyPressedEvent.cpp</p>
<pre><code>KeyPressedEvent::KeyPressedEvent(unsigned int keyCode)
{
this->keyCode = keyCode;
}
KeyPressedEvent::KeyPressedEvent(const KeyPressedEvent& event)
{
keyCode = event.keyCode;
}
KeyPressedEvent& KeyPressedEvent::operator=(const KeyPressedEvent& event)
{
keyCode = event.keyCode;
return *this;
}
unsigned int KeyPressedEvent::getKeyCode() const
{
return keyCode;
}
unsigned int KeyPressedEvent::getType() const
{
return KEY_PRESSED_EVENT;
}
</code></pre>
<p>KeyListener.h:</p>
<pre><code>class KeyListener : public Listener
{
public:
KeyListener();
virtual unsigned int getEventType() const override;
virtual void onEvent(Event*) override;
};
</code></pre>
<p>KeyListener.cpp:</p>
<pre><code>KeyListener::KeyListener()
{
}
unsigned int KeyListener::getEventType() const
{
return KEY_PRESSED_EVENT;
}
void KeyListener::onEvent(Event* e)
{
KeyPressedEvent* event = (KeyPressedEvent*)e; //Even though I am sure that this is the correct event type, can I do things like this or is this considered bad practice?
std::cout << "key pressed: " << event->getKeyCode() << std::endl;
}
</code></pre>
<p>main.cpp:</p>
<pre><code>EventHandler handler;
KeyListener listener;
handler.registerListener(&listener);
KeyPressedEvent event(5);
handler.onEvent(event);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:25:31.230",
"Id": "462107",
"Score": "0",
"body": "Welcome to CodeReview@SE. The indentation of the code presented looks inconsistent; two pieces of advice: 1) use blanks, only 2) bracket each code block with lines containing just `~~~` (and possibly a language hint) instead of prefixing each line with another 4 blanks."
}
] |
[
{
"body": "<blockquote>\n <p>I am trying to make a very simple event system for learning purposes,</p>\n</blockquote>\n\n<p>You've actually made a <strong>very</strong> complex event system. </p>\n\n<p>First, let's explore the requirements of an \"event system\". I am basing these off a rough examination of your code.</p>\n\n<ul>\n<li>Custom <code>Event</code>s can be defined</li>\n<li><code>Handler</code>s register <code>Listener</code>s</li>\n<li>Calls to <code>Handler::onEvent</code> get dispatched to all registered <code>Listener</code>s</li>\n</ul>\n\n<p>A system which satisfies these requirements could be implemented with a <code>std::vector</code> of <code>std::function</code>s. Instead of a <code>Listener</code> class, it would just be a field or perhaps a type alias. The event structure could be specified in the <code>std::function<></code> type. </p>\n\n<p>Let's use this concept as a reference.</p>\n\n<hr>\n\n<p><strong>Event.h</strong></p>\n\n<p>You are declaring every event type in this header essentially as a global variable. This means:</p>\n\n<ul>\n<li>Code can change the event values at runtime</li>\n<li>You need to modify at least two different files just to declare a new event type</li>\n<li>Events values may be important. Are two different types an alias of each other or not? You won't know until runtime.</li>\n<li>Every new event type created will trigger a rebuild of every dependency of Event.h</li>\n<li>Different runtime modules may disagree on the values of the event types due to this linkage</li>\n</ul>\n\n<p>The event class serves only to create a common base class for other event types. However, I don't see any utility for this. In the straw example I described, handlers must be coupled to their event types to some degree, but not to any base class. <strong>The implementation here requires every client of the system to be coupled to every other client.</strong> </p>\n\n<p>Prefer to use enums, and declare them as privately as possible.</p>\n\n<hr>\n\n<p><code>LinkedList</code> appears to be a learning-exercise utility. As a general rule, prefer <code>std::vector</code> when storing a collection of objects. They're very fast and canonically ubiquitous. Note that the algorithmic complexity of adding or removing from the collection is <strong>not</strong> a good reason by itself to use a linked list over a <code>std::vector</code>. In this case, the collection stores pointers which are very small, so there's a lot of overhead in each linked list node. Also, every time a linked list node is iterated over, it may induce a cache miss due to indirecting, which a <code>std::vector</code> is much less likely to do. </p>\n\n<hr>\n\n<p>As a learning exercise, I recommend trying to trim away at your code until it is at the bare bones of functionality. Do you really need a default constructor that does nothing? Do you need a copy constructor on a type with no data? These should be questions raised when trying to slim down your system.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:18:11.593",
"Id": "462237",
"Score": "0",
"body": "Thank you for your reply! I will try to implement what you said, hopefully I will end up with something decent. And when I said that I was making a simple event system I ment that the code was primitive, maybee I should have said basic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:25:59.433",
"Id": "462240",
"Score": "0",
"body": "Basic and primitive is sometimes what you want. A teapot is primitive in that it doesn't have many moving or complex parts, but it's intuitive and performs its job very well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T02:58:34.877",
"Id": "235997",
"ParentId": "235987",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235997",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:50:15.513",
"Id": "235987",
"Score": "1",
"Tags": [
"c++",
"event-handling"
],
"Title": "Creating a simple event system"
}
|
235987
|
<p>I'm working with thousands of large image files in a regularly updated library. The following script does the job (on average reduces my file size ~95%) but costs me around 25 seconds to compress one image. Obviously, I can just let the script run overnight, but it would be cool if I can shave some time off this process. I'm mostly looking for any unnecessary redundancies or overhead in the script that can be trimmed out to speed up the process. I'm still new to Python, so go easy on me.</p>
<pre><code>from PIL import Image
from pathlib import Path
import os, sys
import glob
root_dir = "/.../"
basewidth = 3500
for filename in glob.iglob(root_dir + '*.jpg', recursive=True):
p = Path(filename)
img = p.relative_to(root_dir)
new_name = (root_dir + 'compressed/' + str(img))
print(new_name)
im = Image.open(filename)
wpercent = (basewidth/float(im.size[0]))
hsize = int((float(im.size[1])*float(wpercent)))
im = im.resize((basewidth,hsize), Image.ANTIALIAS)
im.save(new_name, 'JPEG', quality=40)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:40:52.483",
"Id": "462109",
"Score": "0",
"body": "`basewidth = 3500` `quality=40` can you describe what visual effect you are aiming for (\"70%-80% is considered low quality\")? What is the expected lifetime of the images, the resolution of the viewports/output devices? Will zoom in be required?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:44:37.613",
"Id": "462112",
"Score": "0",
"body": "What version of python are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T00:47:29.960",
"Id": "462128",
"Score": "0",
"body": "@Linny I'm using Spyder 3.3 through Anaconda"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T00:51:10.327",
"Id": "462129",
"Score": "0",
"body": "@greybeard I'm using this compression to create a library of smaller jpegs that I can quickly index. All of the RAW files are kept and these compressed files maintain their names. That way I can easily find the photo I need in my compressed library instead of overloading my computer searching through the RAW files. This level of compression gets me to a very reasonable image quality given the enormous size of the originals"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T01:25:48.443",
"Id": "462130",
"Score": "0",
"body": "Well, I don't know about PIL (which doesn't seem active lately), but I'd give a lower width (1920 coming to mind) and a more common quality (default 75?) a try."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T07:34:30.447",
"Id": "462153",
"Score": "0",
"body": "What platform are you on? What dimensions are these images. 25s does sound awfully slow. Your python program doesn't look too difficult. Have you tried a couple of lines of shell/batch script calling ImageMagick? I suspect that will be a lot faster. Not the domain for python?"
}
] |
[
{
"body": "<p>I think what greybeard is getting at in the comments is that you could get away with squishing these images much more than you presently are. It sounds like you're basically using the reduced versions as thumbnails, but these \"thumbnails\" are almost twice the width (over three times the area) of a standard HD monitor. </p>\n\n<p>Dropping <code>basewidth</code> to 1920 (or possibly much lower still) seems like a good idea. Contrary to greybeard, I think your JPEG \"quality\" setting is fine, but you could play around with different variations of smaller-vs-larger and crisp-vs-compressed.</p>\n\n<p>A minute of googling suggests that PIL is in fact the normal choice for image handling. Maybe there's something better, but I'll suppose not. Given that the originals are large (50MB? more?), it may simply be that there's a lot of work to be done. That said, there are some things you can try.</p>\n\n<ul>\n<li>General hardware: Given that this is a heavy task, you may have some luck just running the same code on a fancier computer. This is an expensive option; even if you feel like throwing money at the problem still do plenty of research first.</li>\n<li>Storage hardware: One possible bottleneck is the hard drive you're reading from and writing to. If you can easily try the task against a different (faster or slower) harddrive while keeping everything else the same, that may be informative.</li>\n<li>Memory: Does you computer have a lot of RAM? Is that memory available for this python script to use? If you have a way of making half the currently available memory <em>unavaliable</em>, check if that makes the process twice as slow.</li>\n<li>Memory leaks: I see the line <code>im = Image.open(filename)</code>, and looking at the <a href=\"https://pillow.readthedocs.io/en/3.1.x/reference/Image.html\" rel=\"noreferrer\">docs</a> <em>suggests</em> that you should probably have a call to <code>load</code> or more likely <code>close</code> someplace. </li>\n<li>Parallelism: Your computer probably has multiple processor cores. It's hard to say if or how well this script is using all of those cores. If you try running your script twice at the same time (against non-overlapping target sets), how much slower is each concurrent process?</li>\n<li>It's not clear if <code>ANTIALIAS</code> is a valid option to the <code>resize</code> method in the 3.x version. Try <code>NEAREST</code>.</li>\n<li><a href=\"https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail\" rel=\"noreferrer\">Oh hey there's a <code>thumbnail</code> function that affects the way the file is read from disk!</a>. Playing around with the underlying <code>draft</code> function may also be helpful.</li>\n</ul>\n\n<p>And because this is code review:</p>\n\n<ul>\n<li>Move your format and quality constants up to the same place as <code>basewidth</code>. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T17:41:31.677",
"Id": "462400",
"Score": "0",
"body": "Thank you! You've left some really useful tips. I have a few followup questions:\n\n\n1) Is there any way you can think of to do this compression without read/write? The originals and compressed files are actually both stored on a cloud server, so I imagine that is causing a significant hindrance.\n\n\n2) I realized my code strips metadata. Do you have any suggestions on how it can be maintained?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:18:47.010",
"Id": "462405",
"Score": "0",
"body": "1) You can't work on data without reading it and you can't save your work without writing it. You could move the data locally for processing, or you could see if the cloud in question has some way for you to run your script on their machines. Or you could see if some permutation of `Image.[load | thumbnail | draft]` makes a difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:20:42.207",
"Id": "462406",
"Score": "0",
"body": "2) I don't. Searching in the PIL docs left me unclear if PIL has awareness of metadata (and could therefore help) or not. But am I right that what you really want is for the \"thumbnails\" to _be metadata of_ the originals?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:29:27.410",
"Id": "462425",
"Score": "0",
"body": "A few things. First of all, using NEAREST instead of ANTIALIAS helped immensely. I want to maintain as much resolution as possible to allow for maximum zoom on the compressed jpeg, so this has actually allowed me to bump UP my basewidth to ~5,000. Additionally, it's not clear in the PIL documentation but there is a very easy solution to copying exif data. I'm putting my new script as an answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T10:10:18.083",
"Id": "470397",
"Score": "0",
"body": "There are at least 3 alternatives to PIL as far as I am aware: Pillow, PIL2, Pillow2. Couldn't say which to prefer though."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T02:12:32.843",
"Id": "235995",
"ParentId": "235988",
"Score": "7"
}
},
{
"body": "<p>Here is my updated script. Notable changes include the use of NEAREST instead of ANTIALIAS, as well as the inclusion of an EXIF copy and paste. I think the major hang on the original script was the inefficiency of ANTIALIAS, as this script gives me around 95% compression in about 2 seconds per image.</p>\n\n<pre><code>from PIL import Image\nfrom pathlib import Path\nimport os, sys\nimport glob\n\nroot_dir = \"/.../\"\n\nbasewidth = 5504 #sets base width of new images\n\nfor filename in glob.iglob(root_dir + '*.jpg', recursive=True): #creates for loop to refeence all .jpg files in root directory\n p = Path(filename) #converts filename into Path object\n img = p.relative_to(root_dir) #uses Path function to parse out Path into components, then uses all components following that equal to the root_dir path name (in this case, our jpeg file names)\n new_name = (root_dir + 'compressed/' + str(img)) #creates new path to save compressed files to in subfolder \"compressed\" (note: must create subfolder before running)\n print(new_name)\n\n #resize and reduce\n im = Image.open(filename) #sets filename as object\n wpercent = (basewidth/float(im.size[0])) #uses the base width to establish aspect ratio\n hsize = int((float(im.size[1])*float(wpercent))) #scales image height using aspect ratio\n im = im.resize((basewidth,hsize), Image.NEAREST) #sets new resolution using basewidth and hsize\n exif = im.info['exif'] #copy EXIF data\n im.save(new_name, 'JPEG', exif = exif, quality=40)\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:33:10.377",
"Id": "236083",
"ParentId": "235988",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235995",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:59:18.467",
"Id": "235988",
"Score": "6",
"Tags": [
"python",
"performance",
"python-3.x",
"image",
"compression"
],
"Title": "Compressing large jpeg images"
}
|
235988
|
<p>After a conversation with my math teacher about a base algebra (base 43 using all the algebra symbols) and finding it more than the 30 min of work I was looking for, I decided to make this instead.</p>
<pre class="lang-py prettyprint-override"><code>import math
letters = ["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"]
def print_bases(base: int, num: int) -> None:
new_num = []
div = num
while div != 0:
if len(str(div % base)) > 1:
new_num.insert(0, letters[((div % base) - 10)])
else:
new_num.insert(0, str(div % base))
div = math.floor(div / base)
new_num = "".join(new_num)
print(f"{num} in base {base} is {new_num}")
while True:
while True:
try:
num = int(input("Please enter a number in base 10: "))
break
except (NameError, ValueError):
print("Please use numbers only")
for base in range(35):
print_bases(base + 2, num)
</code></pre>
<p>As this was made for fun I forgot to add any comments (doing that is still new for me), so I hope it makes sense. My main problem is I want to know if I can get rid of <code>letters</code>. Also <code>print_bases</code> seems messy and I wonder if that can be cleaned up. Any other small fixes would be appreciated.</p>
<p><a href="https://en.wikipedia.org/wiki/All_your_base_are_belong_to_us" rel="nofollow noreferrer">;)</a></p>
|
[] |
[
{
"body": "<ul>\n<li><p>Since <code>letters</code> is a list of characters (1 length strings) you logistically have made <code>letters</code> a string. And so you can simplify writing it as a string rather than a list of characters.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>letters = \"ABCDE...\"\n</code></pre></li>\n<li><p>You can remove the need to define <code>letters</code> by using <code>string.ascii_uppercase</code>.</p></li>\n<li>It's good to see some type hints. Good job!</li>\n<li>I would suggest changing your function to only take in the base and the number, and return a new number, rather than <code>print</code> it.</li>\n<li><p>You don't need to use <code>math.floor</code> you have a couple of alternate options:</p>\n\n<ul>\n<li>Use <code>int</code> - <code>int(div / base)</code>.</li>\n<li>Use the floordiv operator - <code>div // base</code>.</li>\n</ul></li>\n<li><p>Rather than using <code>div % base</code> and <code>math.floor(div / base)</code> you can use <code>divmod</code> to divide and get the modulo in <em>one</em> command.</p></li>\n<li><p>Rather than using <code>list.insert</code> I would recommend using <code>list.append</code> and then using <code>reversed</code>.</p>\n\n<p>This is because inserting at the start of a list in Python has to move every other item from the beginning of the list to the end of the list. Append on the other hand only needs to append to the end of the list and it doesn't have to touch the rest of the list.</p>\n\n<p>I also find it cleaner to just use <code>.append</code>.</p></li>\n<li>The check <code>len(str(div % base)) > 1</code> would be better described as <code>(div % base) >= 10</code>. This is as we're working with numbers - <code>/</code>, <code>%</code>, <code>divmod</code> - and so thinking of the value as a number is easier.</li>\n<li>If you change <code>letters</code> to <code>string.digits + string.ascii_uppercase</code> then you can remove the need for the <code>if</code>.</li>\n<li>I suggest you change the order of your function's arguments, so it's inline with other base conversion functions. <code>num</code> then <code>base</code>.</li>\n<li>It's Pythonic to have constants be <code>UPPER_SNAKE_CASE</code> and so <code>letters</code> should be all caps.</li>\n</ul>\n\n<p>There's a lot of points above, but for a beginner your code is good. Good job!</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import string\n\nLETTERS = string.digits + string.ascii_uppercase\n\n\ndef to_base(num: int, base: int) -> str:\n new_num = []\n while num != 0:\n num, mod = divmod(num, base)\n new_num.append(LETTERS[mod])\n return \"\".join(reversed(new_num))\n\n\nwhile True:\n while True:\n try:\n num = int(input(\"Please enter a number in base 10: \"))\n break\n except (NameError, ValueError):\n print(\"Please use numbers only\")\n for base in range(2, 37):\n new_num = to_base(num, base)\n print(f\"{int(new_num, base)} in base {base} is {new_num}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T08:43:36.260",
"Id": "236014",
"ParentId": "235989",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236014",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:00:58.370",
"Id": "235989",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Base 10 to Base 2-36 converter"
}
|
235989
|
<p>My mask translator is performing poorly in scenario where I have 30 masks and 10,000 ownerships. This is a <a href="https://en.wikipedia.org/wiki/Bit_field" rel="nofollow noreferrer">bit field</a> and similar to <a href="https://en.wikipedia.org/wiki/Mask_(computing)" rel="nofollow noreferrer">bit masks</a> such as <a href="https://docs.python.org/3/library/enum.html#enum.IntFlag" rel="nofollow noreferrer"><code>enum.IntFlag</code></a>.</p>
<p>I though about creating a list with all combinations of masked values and names (1 - alex, 2 - ben, 3 - alex/ben, 4 - clark, 5,... sum from 1 to 30 = 465) and then doing a simple lookup rather than evaluating the function for each ownership item. What do you think about this approach?</p>
<pre class="lang-py prettyprint-override"><code>def findbits(num,object):
for i in range(128):
if num & 1 << i:
y = "{0}".format(i + 1)
output.append([names[int(y)-1], object])
output = []
map = [['1','alex'],['2','ben'],['4','clark'],['8','dean'],['16','eric']]
mask = [row[0] for row in map] #['1', '2', '4', '8', '16']
names = [row[1] for row in map] #['alex', 'ben', 'clark', 'dean', 'eric']
ownership = [['radio','3'],['telly','31']]
for item in ownership:
findbits(int(item[1]),item[0])
print(output)
#[['alex', 'radio'], ['ben', 'radio'], ['alex', 'telly'], ['ben', 'telly'], ['clark', 'telly'], ['dean', 'telly'], ['eric', 'telly']]
</code></pre>
<p>In a nutshell: I have to find which names own which objects, that is to decompose masked number for each object (e.g. radio: 31 = 16 + 8 + 4 + 2 + 1) and look up values (names) for each sub-number (16 - eric, 8 - dean, ...).</p>
<p>And a large scale example:</p>
<pre class="lang-py prettyprint-override"><code>import random
import string
def get_ownerships(nbr):
for i in range(nbr):
objects = ''.join(random.choice(string.ascii_letters) for m in range(4))
ownership.append([objects,mask[i]])
return ownership
def findbits(num,object):
for i in range(int(num**0.5)+1): #roundup to nearest integer; this is crucia for performance. Shall be dependent on num,
#precisely the position of the highest subnumer. If num = 17, then 17 = 16 + 1 where 16 is 5th element (1 - 2 - 4 - 8 - 16),
#hence 5 elements = roundup(17^0.5). Could be improved though
if num & 1 << i:
y = "{0}".format(i + 1)
output.append([names[int(y)-1], object])
ownership = []
mask = [random.randrange(1, 32767) for _ in range(1000)]
get_ownerships(1000)
output = []
map = [['1','al'],['2','be'],['4','cl'],['8','de'],['16','er'],['32','fa'],['64','ga'],['128','ha'],['256','ia'],['512','ja'],['1024','ka'],['2048','la'],['4096','ma'],['8192','na'],['16384','oa']]
mask = [row[0] for row in map] #['1', '2', '4', '8', '16']
names = [row[1] for row in map] #['alex', 'ben', 'clark', 'dean', 'eric']
for item in ownership:
findbits(int(item[1]),item[0])
</code></pre>
|
[] |
[
{
"body": "<h1>Code block 1</h1>\n\n<ul>\n<li>Please don't use variable names like <code>object</code>, <code>i</code> or <code>y</code>.</li>\n<li>Standard indentation in Python is 4 spaces, not a mix between 2 and 4.</li>\n<li>Mutating values out of a functions scope isn't best practice. This is because it leads to confusing code.</li>\n<li><p>The following snippet is not needed. You can just use <code>names[i]</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>y = \"{0}\".format(i + 1)\nnames[int(y)-1]\n</code></pre></li>\n<li><p>Rather than <code>findbits</code> I would make a function <code>find_names</code>. Which will return the names that can use the object.</p></li>\n<li>Your bit mask, <code>num & 1 << i</code>, is good. But you can change it to use <code>while num:</code> to allow you to not waste any loops. Since the input you've provided us only goes to <code>1 << 4</code>, there's not much point in looping all the way to <code>128</code>. And so we can bitshift the other way.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def find_names(number, names):\n index = 0\n while number:\n if number & 1:\n yield names[index][1]\n number >>= 1\n index += 1\n\n\ndef main(map, ownership):\n output = []\n for obj, number in ownership:\n for name in find_names(int(number), map):\n output.append([name, obj])\n return output\n\n\nif __name__ == '__main__':\n print(main(\n [['1','alex'],['2','ben'],['4','clark'],['8','dean'],['16','eric']],\n [['radio','3'],['telly','31']],\n ))\n</code></pre>\n\n<p>Both my solution and your solution are similar, however my solution bitshifts <code>number</code> downwards, where yours shifts <code>i</code> upwards. This means that you're constantly making <code>1 << i</code> larger and comparing with <code>number</code>. This means on the first iteration <code>1 << i</code> is <span class=\"math-container\">\\$1\\$</span>, in binary form, where on the third iteration it's <span class=\"math-container\">\\$100\\$</span>, in binary form.</p>\n\n<p>Mine however works the opposite way checking the least significant bit, with <code>number & 1</code>. And so on the first iteration <code>number</code> would be something like <span class=\"math-container\">\\$10001001\\$</span>. Where on the third iteration it would be <span class=\"math-container\">\\$100010\\$</span>. This is as <code>>></code> discards the least significant bit.</p>\n\n<p>I find the following table to highlight the increase and decrease in size of the numbers to help. It's apparent that yours grows to match the bitlength of the original number, where mine shrinks until it reaches zero. The red highlights the bit that we're comparing with on each iteration.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{array}{l l r l}\n\\text{iteration} & \\text{matching bit} & \\text{Yours - 1 << i} & \\text{Mine - number} \\\\\n0 & 1000100\\color{red}{1} & \\color{red}{1} & 1000100\\color{red}{1}\\\\\n1 & 100010\\color{red}{0}1 & \\color{red}{1}0 & 100010\\color{red}{0} \\\\\n2 & 10001\\color{red}{0}01 & \\color{red}{1}00 & 10001\\color{red}{0} \\\\\n3 & 1000\\color{red}{1}001 & \\color{red}{1}000 & 1000\\color{red}{1} \\\\\n4 & 100\\color{red}{0}1001 & \\color{red}{1}0000 & 100\\color{red}{0} \\\\\n5 & 10\\color{red}{0}01001 & \\color{red}{1}00000 & 10\\color{red}{0} \\\\\n6 & 1\\color{red}{0}001001 & \\color{red}{1}000000 & 1\\color{red}{0} \\\\\n7 & \\color{red}{1}0001001 & \\color{red}{1}0000000 & \\color{red}{1} \\\\\n\\end{array}\n$$</span></p>\n\n<h1>Code block 2</h1>\n\n<ul>\n<li>We can transfer a lot of the changes from the above code block to the second.</li>\n<li>I would split the <code>objects</code> comprehension over multiple lines, as I find it helps with readability.</li>\n<li>The variable <code>m</code> is never used and so you can use the name <code>_</code> to denote that it is never used.</li>\n<li>I would move the <code>mask</code> iterator into <code>get_ownerships</code> and just generate one in the <code>for</code>. This allows you to generate both the name and the mask with ease.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport string\n\n\ndef generate_ownerships(amount, limit):\n for _ in range(amount):\n object_name = ''.join(\n random.choice(string.ascii_letters)\n for _ in range(4)\n )\n mask = random.randrange(1, limit)\n yield [object_name, mask]\n\n\ndef find_names(number, names):\n index = 0\n while number:\n if number & 1:\n yield names[index][1]\n number >>= 1\n index += 1\n\n\ndef main(map, ownership):\n output = []\n for obj, number in ownership:\n for name in find_names(int(number), map):\n output.append([name, obj])\n return output\n\n\nif __name__ == '__main__':\n main(\n [['1','al'],['2','be'],['4','cl'],['8','de'],['16','er'],['32','fa'],['64','ga'],['128','ha'],['256','ia'],['512','ja'],['1024','ka'],['2048','la'],['4096','ma'],['8192','na'],['16384','oa']],\n generate_ownerships(1000, 32767),\n )\n</code></pre>\n\n<h1>Further comments</h1>\n\n<ul>\n<li><p>The first value in <code>names</code> is never used. As only <code>names[index][1]</code> is used. This means you can change your input so that you only specify the names.</p>\n\n<p>If you would still like to specify the value in any order, <code>[['2', 'be'], ['1', 'al']]</code>, then you can normalize the names. This requires ordering the names by the first value.</p></li>\n<li><p>Since this is tagged <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a> you may be able to get a performance increase if you use an <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\">LRU cache from <code>functools</code></a>. This will store the <span class=\"math-container\">\\$n\\$</span> most recently used values to a function so you don't need to regenerate the output.</p>\n\n<p>This would require a small change to <code>find_names</code> to return an iterable rather than an iterator, and to only take hashables. For best performance it would only take <code>number</code>.</p>\n\n<p>It should be noted that this may not lead to a performance gain. The amount of performance gain you get may also change depending on the size of <span class=\"math-container\">\\$n\\$</span> and so you should test the performance on your data with different values.</p>\n\n<p>If you have both space and time constraints then you can utilize the <a href=\"https://en.wikipedia.org/wiki/Birthday_problem#Generalizations\" rel=\"nofollow noreferrer\">generalized birthday problem</a> to find a rough number to limit the cache to. As it's 50% chance for hits at a fraction the size of the maximum input is a good way to save on both. If this is needed then I will leave it to you to implement.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\n\ndef normalize_names(names):\n return [name for _, name in sorted(names, key=lambda i: int(i[0]))]\n\n\n@functools.lru_cache(maxsize=None)\ndef find_names(number):\n output = ()\n index = 0\n while number:\n if number & 1:\n output += (index,)\n number >>= 1\n index += 1\n return output\n\n\ndef main(map, ownership):\n output = []\n for obj, number in ownership:\n for index in find_names(int(number)):\n output.append([map[index], obj])\n return output\n\n\nif __name__ == '__main__':\n print(main(\n normalize_names(\n [['2','ben'],['1','alex'],['4','clark'],['8','dean'],['16','eric']],\n ),\n [['radio','3'],['telly','31']],\n ))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:10:42.057",
"Id": "462404",
"Score": "0",
"body": "Thank Peilonrayz for detailed answer, great food for thought. I will go through the code over the weekend, do some tests and come back (accept answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:05:29.510",
"Id": "462420",
"Score": "0",
"body": "I like the simplicity of your code. No need to hold in memory what is not needed. Will start practicing. Could you explain bit the while number part in find_names function (bitshifting)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:07:13.520",
"Id": "462421",
"Score": "0",
"body": "@regresss In a bit / tomorrow sure. Also which bit the `while number:` `if number & 1:`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:44:27.290",
"Id": "462426",
"Score": "0",
"body": "Yes, please also with `number >>= 1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T15:44:21.850",
"Id": "462526",
"Score": "1",
"body": "@regresss I have added some comments explaining how the bit-shifting work."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:54:08.477",
"Id": "236044",
"ParentId": "235990",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236044",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:11:19.250",
"Id": "235990",
"Score": "5",
"Tags": [
"python",
"performance",
"combinatorics"
],
"Title": "Performance of mask (1,2,4,8,16) convertor in python"
}
|
235990
|
<p>this is my first code review post :) So I wrote this Black Jack game as part of an online Python course and would love some feedback about my coding style and whether or not I have correctly used a 'Pythonic' style in terms of the OOP. </p>
<p>Any general comments are also extremely welcome because I am making a move towards Python as serious commitment and want to follow the standard conventions as closely as possible.</p>
<p>Here is my code. Many thanks</p>
<p><strong>Deck</strong> class:</p>
<pre><code>import random
from card import Card
class Deck:
'''
A class for creating a Deck of Cards.
A full deck of 52 cards is created and
can be accessed as a list or as as a string.
Deck exposes a <shuffle> method that will
pseudo-randomly reorganise the list of cards
'''
__card_values = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10,
}
__suits = ['Clubs', 'Spades', 'Hearts', 'Diamonds']
def __init__(self):
self.__deck = [Card(value + '-' + suit, self.__card_values[value])
for suit in self.__suits
for value in self.__card_values]
@property
def deck(self):
return self.__deck
@deck.setter
def deck(self, val):
self.__deck = val
def shuffle(self):
random.shuffle(self.__deck)
</code></pre>
<p><strong>Card</strong> class:</p>
<pre><code>class Card:
'''
A class for creating Card objects.
Each Card object has a <face_value>
which denotes the suit and its
value in the Deck. Each Card also
has a <value> which denotes how many
points the Card is worth in the game
'''
def __init__(self, face_value, value):
self.__face_value = face_value
self.__value = value
@property
def face_value(self):
return self.__face_value
@property
def value(self):
return self.__value
@value.setter
def value(self, val):
self.__value = val
def __str__(self):
return f'{self.face_value}'
</code></pre>
<p><strong>Hand</strong> class</p>
<pre><code>class Hand:
'''
A class for creating a Hand of Cards.
An instance of Hand takes a list of
Card objects as an argument which
becomes the players hand for a single
round. The <take_card> method adds a
new card to the hand
'''
def __init__(self, cards):
self.__cards = cards
def take_card(self, card):
self.__cards.append(card)
@property
def cards(self):
return self.__cards
def __str__(self):
card_string = ''
for card in self.cards:
card_string += card.face_value + '\n'
return card_string
</code></pre>
<p><strong>Actor</strong> class</p>
<pre><code>class Actor:
'''
Super class for creating game
participants, namely the Dealer and
the human Player. An Actor must have
a Hand and the human Actor must have
some chips in order to play. <chips>
is set to 0 by default so the Dealer
will not have any. This class has 2
abstract methods; <lose_bet> and
<win_bet>. Each method effects the
number of chips the Actor has. (For
the Dealer, these methods will simply
pass)
'''
def __init__(self, hand=None, chips=0, score=0):
self.__hand = hand
self.__chips = chips
self.__score = score
@property
def hand(self):
return self.__hand
@hand.setter
def hand(self, val):
self.__hand = val
@property
def chips(self):
return self.__chips
@chips.setter
def chips(self, val):
self.__chips = val
@property
def score(self):
return self.__score
@score.setter
def score(self, val):
self.__score = val
def lost_bet(self):
raise NotImplementedError("Subclass must inherit this abstract method")
def won_bet(self):
raise NotImplementedError("Subclass must inherit this abstract method")
class Dealer(Actor):
def lost_bet(self):
pass
def won_bet(self):
pass
class Player(Actor):
def lost_bet(self, val):
self.chips -= val
def won_bet(self, val):
self.chips += val
</code></pre>
<p><strong>black_jack.py</strong></p>
<pre><code>import random
import functools
from deck import Deck
from hand import Hand
from actor import Dealer, Player
def deal_cards(limit, max_cards):
cards = [random.randint(0, limit) for _ in range(0, max_cards)]
while True:
if len(set(cards)) != len(cards):
cards = [random.randint(0, limit) for _ in range(0, max_cards)]
else:
break
return cards
def remove_cards_from_deck(deck, cards):
cards.sort(reverse=True)
for i in cards:
deck.pop(i)
return deck
def calc_score(player, cards):
card_values = [card.value for card in cards]
score = functools.reduce(lambda x, y: x+y, card_values)
if score <= 11:
for value in card_values:
if value == 1 and (score + 10) <= 21:
score += 10
return score
def hit(deck, player):
cards = deal_cards(len(deck)-1, 1)
new_card = deck[cards[0]]
player.hand.take_card(new_card)
player.score = calc_score(player, player.hand.cards)
deck = remove_cards_from_deck(deck, cards)
return deck
def display_data(dealer, player, player_bet):
print('\nDealer\'s hand:')
print(dealer.hand.cards[0])
print('\nPlayers hand:')
print(player.hand)
print(f'Current bet: {player_bet}')
player.score = calc_score(player, player.hand.cards)
print(f'Player Score: {player.score}')
dealer.score = calc_score(dealer, dealer.hand.cards)
def has_won(dealer, player):
print('\nDealers Hand:')
print(dealer.hand)
print(f"Dealer score: {dealer.score}")
print(f"Player score: {player.score}")
if player.score > 21:
print('\nBust, you loose... boho')
return False
elif player.score <= 21 and player.score > dealer.score or (dealer.score > 21 and player.score <= 21):
print('\nCongrats Player, you won!!')
return True
else:
print('\nSorry Player, house wins... haha')
return False
def start_game(dealer, player, player_bet):
new_deck = Deck()
new_deck.shuffle()
cards = deal_cards(len(new_deck.deck)-1, 4)
dealer_hand = Hand([new_deck.deck[cards[1]],
new_deck.deck[cards[3]]])
player_hand = Hand([new_deck.deck[cards[0]],
new_deck.deck[cards[2]]])
new_deck.deck = remove_cards_from_deck(new_deck.deck, cards)
dealer.hand = dealer_hand
player.hand = player_hand
player.score = 0
dealer.score = 0
display_data(dealer, player, player_bet)
while player.score <= 21:
try:
choice = input('\nHit or Stick? (H/S) ')
if choice.lower() == 'h':
new_deck.deck = hit(new_deck.deck, player)
display_data(dealer, player, player_bet)
if choice.lower() == 's':
while dealer.score <= 17:
new_deck.deck = hit(new_deck.deck, dealer)
break
if dealer.score <= 17:
new_deck.deck = hit(new_deck.deck, dealer)
except Exception:
print('What are you playing at?')
if has_won(dealer, player):
player.won_bet(player_bet)
else:
player.lost_bet(player_bet)
def run():
print('\t\n==================== Welcome to the Black Jack Casino ====================\n')
print('Rules:')
print('''
1. Aces are worth 1 or 11
2. Numbered cards are worth their value
3. Picture cards are worth 10
4. The closest to 21 between you and the dealer is the winner
5. If you go over 21 you loose
6. You can only see one of the dealer's cards
7. 'Hit' to take another card
8. 'Stick' to keep what you have and compare with the dealer
9. If you and the dealer have the same score which is less than or equal to 21,
the house still wins
10. Good luck!!\n
''')
while True:
try:
player_chips = int(input('How many chips do you want to buy? '))
break
except Exception:
print('Don\'t muck me about...\n')
cash_out = False
dealer = Dealer()
player = Player()
player.chips = player_chips
aces = {'A-Clubs', 'A-Hearts', 'A-Diamonds', 'A-Spades'}
while not cash_out and player.chips > 0:
try:
print(f'Chips: {player.chips}')
player_bet = int(input('Place a bet: '))
if player_bet > player.chips:
print('You don\'t have the readies mate...\n')
else:
start_game(dealer, player, player_bet)
try:
if (player.chips != 0):
quit = input('\nYou want to continue? (Y/N) ')
if quit.lower() == 'n':
cash_out = True
else:
break
except Exception:
print('Don\'t talk rubbish...\n')
except Exception:
print('Don\'t waste my time...\n')
continue
try:
play_again = input('\nFancy another game? (Y/N) ')
if play_again.lower() == 'y':
run()
else:
print('Next time then sucker...')
return
except Exception:
print('Don\'t talk rubbish...')
run()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:13:03.607",
"Id": "462114",
"Score": "0",
"body": "Are `lost_bet` and `won_bet` for `Dealer` supposed to be `pass`, or have you not implemented that yet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:29:54.593",
"Id": "462118",
"Score": "0",
"body": "They are supposed to pass since the Dealer has no chips to lose or win. I wanted the Dealer to inherit from Actor as well so it would get a 'hand' and a 'score', but there is no need tor it to use these methods. Does that make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:34:22.030",
"Id": "462120",
"Score": "0",
"body": "Ah ok the whole class can just pass, I didn't know that. I have been studying a lot of Java where it is necessary to override methods in sub-classes, so I guess it's something I'll have to drop with Python. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:36:11.890",
"Id": "462122",
"Score": "0",
"body": "Please disregard my last comment, I didn't see the `NotImplementedError`. Coming from Java myself, it's understandable that you want subclasses to inherit all methods from a super class. This isn't always the case in Python. Since only one class actually uses these two methods, `Player` can have these methods in *that* class, instead of inheriting from `Actor`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:38:51.810",
"Id": "462123",
"Score": "0",
"body": "That makes sense. The Dealer class can just pass then still as it has no methods to implement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:48:33.860",
"Id": "462124",
"Score": "0",
"body": "Please refer to my answer, as I go more in-depth about this."
}
] |
[
{
"body": "<p>This answer is focused on one very specific part of this program.</p>\n\n<hr>\n\n<p>Let's take a look at the <code>Actor</code> class. Specifically, these two methods:</p>\n\n<pre><code>def lost_bet(self):\n raise NotImplementedError(\"Subclass must inherit this abstract method\")\n\ndef won_bet(self):\n raise NotImplementedError(\"Subclass must inherit this abstract method\")\n</code></pre>\n\n<p>Now lets list how many subclasses actually use this method:</p>\n\n<ul>\n<li><code>Player</code></li>\n<li>Wait, <em>just</em> player?</li>\n</ul>\n\n<p>Since <code>Dealer</code> is a subclass of <code>Actor</code>, I expected <code>Dealer</code> to utilize these methods as well. Not even <code>Actor</code> uses them in a meaningful way, except to make sure the subclasses write their own definition for them.</p>\n\n<p>From our conversation in the comments, you state you came from Java. Now I can clearly see why you used inheritance in this way. This is unnecessary for Python. <code>lost_bet</code> and <code>won_bet</code> should be standalone methods in the <code>Player</code> class, since that subclass is the only class that uses these two methods in a meaningful way.</p>\n\n<p>What I recommend is to keep <code>Player</code> exactly how it is. What I would change is the following:</p>\n\n<ul>\n<li>Remove <code>lost_bet</code> and <code>won_bet</code> from the <code>Actor</code> class.</li>\n<li>Set the <code>Dealer</code> class to <code>pass</code>.</li>\n</ul>\n\n<p>For the <code>Dealer</code> point, something like this:</p>\n\n<pre><code>class Dealer(Actor):\n pass\n</code></pre>\n\n<p>Now you have a way to clear distinguish a <code>Dealer</code> and <code>Actor</code> from each other, without the two unnecessary methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:54:36.100",
"Id": "462125",
"Score": "1",
"body": "Thanks a lot that's really useful to know and makes inheritance a lot simpler. Much appreciated"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:48:16.597",
"Id": "235994",
"ParentId": "235991",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235994",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T23:09:16.817",
"Id": "235991",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"game"
],
"Title": "I wrote a Black Jack game in Python and would love some feedback -"
}
|
235991
|
<p>So I am attempting to scrape a website of its staff roster (<a href="https://www.milb.com/greenville/ballpark/frontoffice" rel="nofollow noreferrer">https://www.milb.com/greenville/ballpark/frontoffice</a>) and I want the end product to be a dictionary in the format of {staff: position}. I am currently stuck with it returning every staff name and position as a separate string. It is hard to clearly post the output, but it essentially goes down the list of names, then the position. So for example the first name on the list is to be paired with the first position, and so on. The lowest I could get to the text I need by using the <code>class_</code> parameter was the individual <code>div</code> that the <code>p</code> is contained in. I am pretty sure that the way to accomplish this would be to use <code>zip</code> to put the elements in a dictionary, but I have tried several ways of getting there and nothing has worked so far. I am still inexperienced with python and new to web scraping, but I am relativity well versed with html and css, so help would be greatly appreciated. </p>
<pre class="lang-py prettyprint-override"><code># Simple script attempting to scrape
# the staff roster off of the
# Greenville Drive website
import requests
from bs4 import BeautifulSoup
URL = 'https://www.milb.com/greenville/ballpark/frontoffice'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
staff = soup.find_all('div', class_='l-grid__col l-grid__col--xs-12 l-grid__col--sm-4 l-grid__col--md-3 l-grid__col--lg-3 l-grid__col--xl-3')
for staff in staff:
data = staff.find('p')
if data:
print(data.text.strip())
position = soup.find_all('div', class_='l-grid__col l-grid__col--xs-12 l-grid__col--sm-4 l-grid__col--md-6 l-grid__col--lg-6 l-grid__col--xl-6')
for position in position:
data = position.find('p')
if data:
print(data.text.strip())
# This code so far provides the needed data, but need it in a dict()
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T02:26:33.547",
"Id": "235996",
"Score": "1",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Trouble returning web scraping output as python dictionary"
}
|
235996
|
<p>Hello guys i wrote this function code: </p>
<pre><code>function gematria(text){
var newText = text.toLowerCase(); // handle capital letters
var startValue=0; //initialize value to zero
for(let i=0 ; i<newText.length; i++){ // loop through every letter on the text
let currentCharValue = newText.charCodeAt(i) - 96; // get the distance from the 'a'
startValue +=currentCharValue;
}
return startValue
}
gematria("someText");
</code></pre>
<p>it works well but is there any way to do it more short? or better? how good is that code for doing the task?</p>
|
[] |
[
{
"body": "<p>Shorter:</p>\n\n<pre><code> const gematria = text => [...text].reduce((s, c) => s + c.toLowerCase().charCodeAt(0) - 96, 0);\n</code></pre>\n\n<p>Better: I don't know. Your code is totally fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:42:56.633",
"Id": "462134",
"Score": "0",
"body": "…and also different in its handling of multi-byte unicode characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:43:34.103",
"Id": "462135",
"Score": "0",
"body": "You have missed `toLowerCase` part"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:46:43.837",
"Id": "462136",
"Score": "1",
"body": "@yury whoops, fixed ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:47:57.857",
"Id": "462137",
"Score": "0",
"body": "why not `[...text.toLowerCase()]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:50:30.447",
"Id": "462138",
"Score": "0",
"body": "@nina I have no idea ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:52:27.110",
"Id": "462139",
"Score": "0",
"body": "@bergi oh, nice catch. Not sure if a +2000 years old technique needs to support emojis though ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:55:57.780",
"Id": "462140",
"Score": "0",
"body": "Oh, I had no idea what [gematria](https://en.wikipedia.org/wiki/Gematria) means… Yeah, hardly matters :-)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:41:09.897",
"Id": "235999",
"ParentId": "235998",
"Score": "-1"
}
},
{
"body": "<p>The shortest approach is to parse the character with a base of 36 and get the delta of <code>9</code> for summing.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function gematria(text) {\r\n return [...text].reduce((s, c) => s + parseInt(c, 36) - 9, 0);\r\n}\r\n\r\nconsole.log(gematria(\"someText\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:19:42.590",
"Id": "236000",
"ParentId": "235998",
"Score": "2"
}
},
{
"body": "<p>We can pre-compute a lookup table to make the function very fast, assuming that the accepted characters are known to be restricted to a range such as printable ASCII:</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 lut = Array.from(\n Array(128).keys(),\n index => String.fromCharCode(index).toLowerCase().charCodeAt(0) - 96\n);\n\nfunction gematria(text) {\n let startValue = 0;\n\n for (let i = 0; i < text.length; ++i) {\n startValue += lut[text.charCodeAt(i)];\n }\n\n return startValue;\n}\n\nconsole.log(gematria(\"someText\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Here's a <a href=\"https://jsperf.com/gematria-performance\" rel=\"nofollow noreferrer\">benchmark</a> comparing these three answers to the original implementation. On my Intel i7-9750H, running Windows 10, I get the following results:</p>\n\n<h3>Chrome 79.0.3945.117:</h3>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/236001/73672\">Mine</a>: 57,128,914 ops/sec (fastest)</li>\n<li><a href=\"https://codereview.stackexchange.com/q/235998/73672\">Original</a>: 37,709,334 ops/sec (34% slower)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/235999/73672\">Jonas Wilms</a>: 10,484,026 ops/sec (82% slower)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/236000/73672\">Nina Scholz</a>: 2,377,434 ops/sec (96% slower)</li>\n</ul>\n\n<h3>Firefox 72.0.2:</h3>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/q/235998/73672\">Original</a>: 65,230,557 ops/sec (fastest)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/236001/73672\">Mine</a>: 58,459,179 ops/sec (10% slower)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/235999/73672\">Jonas Wilms</a>: 3,964,879 ops/sec (94% slower)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/236000/73672\">Nina Scholz</a>: 2,892,339 ops/sec (96% slower)</li>\n</ul>\n\n<h3>Microsoft Edge 44.18362.449.0:</h3>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/236001/73672\">Mine</a>: 8,118,924 ops/sec (fastest)</li>\n<li><a href=\"https://codereview.stackexchange.com/q/235998/73672\">Original</a>: 5,840,381 ops/sec (29% slower)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/236000/73672\">Nina Scholz</a>: 470,844 ops/sec (94% slower)</li>\n<li><a href=\"https://codereview.stackexchange.com/a/235999/73672\">Jonas Wilms</a>: 422,330 ops/sec (95% slower)</li>\n</ul>\n\n<p>I did optimize this for V8, so I'm not surprised that SpiderMonkey turned out to favor the original answer, but best 2 out of 3 isn't bad in my opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T07:00:00.813",
"Id": "462145",
"Score": "0",
"body": "How about { a: 1, b: 2 ... } ... that could be faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T09:33:40.603",
"Id": "462166",
"Score": "0",
"body": "@JonasWilms it's not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T11:20:09.103",
"Id": "462187",
"Score": "0",
"body": "Does your measurement include building up the lut?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T12:16:31.700",
"Id": "462193",
"Score": "0",
"body": "@JonasWilms no, because that only needs to be done once. That's also why it doesn't include defining the functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T12:37:07.527",
"Id": "462195",
"Score": "0",
"body": "But if the function is only run once ... might be worth calculating runs = (other_time - lut_time) / run_time ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T13:12:30.420",
"Id": "462197",
"Score": "0",
"body": "@JonasWilms if the function is only run once then there's no point discussing performance at all. Feel free to calculate it yourself if you care, that's beyond the scope of the question, and my interest for that matter."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T22:47:55.967",
"Id": "236001",
"ParentId": "235998",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T21:38:07.260",
"Id": "235998",
"Score": "0",
"Tags": [
"javascript",
"performance"
],
"Title": "JS how to optimize function that finds the text value in gematria"
}
|
235998
|
<p>Helo everyone, I need to review on function <code>swapNode</code> in doubly linked list. It works but I want to make it clearer and better. Are there any errors like memory leak in my code?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
struct node;
struct list;
typedef struct node node;
typedef struct list list;
struct node
{
int point;
char name[30];
node *next;
node *prev;
};
struct list
{
node *head;
node *tail;
int count;
};
node *createNewNode(int point, char name[30], node *prev, node *next);
list *createList();
void insertHead(list *listNode, int point, char name[30]);
bool compareName(char a[30], char b[30]);
void swapNode(list *listNode, char nameA[30], char nameB[30]);
int main()
{
list *listNode = createList();
insertHead(listNode, 10, "abc def");
insertHead(listNode, 9, "qwe rty");
insertHead(listNode, 8, "ui op");
insertHead(listNode, 30, "fgh jkl");
insertHead(listNode, 1234, "akaka");
swapNode(listNode, "fgh jkl", "akaka");
node *temp = listNode->head;
while (temp != NULL)
{
printf("%-20s%d\n", temp->name, temp->point);
temp = temp->next;
}
return 0;
}
node *createNewNode(int point, char name[30], node *prev, node *next)
{
node *newNode = (node *)malloc(sizeof(node));
newNode->point = point;
strcpy(newNode->name, name);
newNode->next = next;
newNode->prev = prev;
return newNode;
}
list *createList()
{
list *listNode = (list *)malloc(sizeof(list));
listNode->count = 0;
listNode->head = NULL;
listNode->tail = NULL;
return listNode;
}
void insertHead(list *listNode, int point, char name[30])
{
node *newNode = allocateNewNode(point, name, NULL, listNode->head);
if (listNode->head)
listNode->head->prev = newNode;
listNode->head = newNode;
if (listNode->tail == NULL)
listNode->tail = newNode;
++listNode->count;
}
bool compareName(char a[30], char b[30])
{
for (int i = 0; i < 31; i++)
{
if (a[i] != b[i])
return false;
if (a[i] == '\0')
break;
}
return true;
}
void swapNode(list *listNode, char nameA[30], char nameB[30])
{
node *A = NULL, *B = NULL;
node *temp = listNode->head;
for (int i = 0; i < listNode->count; i++)
{
if (compareName(temp->name, nameA))
A = temp;
else if (compareName(temp->name, nameB))
B = temp;
temp = temp->next;
if (A && B)
break;
}
if (!A || !B)
return false;
else if (A == B)
return false;
node p=*A;
*A=*B;
*B=p;
B->next = A->next;
B->prev = A->prev;
A->next = p.next;
A->prev = p.prev;
}
</code></pre>
|
[] |
[
{
"body": "<h2>Don't Return Values from <code>void</code> Functions</h2>\n\n<pre><code> if (!A || !B)\n return false;\n else if (A == B)\n return false;\n</code></pre>\n\n<p>The function <code>void swapNode(List *listNode, char nameA[30], char nameB[30])</code> is declared void, which means it doesn't return a value, yet it attempts to return false in two places. Some compilers actually report this as an error. Rather than <code>return false;</code> it should just be <code>return;</code>. </p>\n\n<p>The two if statements above could be rewritten as one if statement</p>\n\n<pre><code> if ((!A || !B) || (A == B))\n {\n return;\n }\n</code></pre>\n\n<h1>Missing Error Checking</h1>\n\n<p>The C programming memory allocation functions <code>malloc(size_t size)</code>, <code>calloc(size_t count, size_t size)</code> and <code>realloc( void *ptr, size_t new_size)</code> may fail. If they do fail then they return NULL. Any time one of these functions are called, the result should be tested to see if it is NULL. Referencing fields through a NULL pointer yields unknown behavior and is generally a bug.</p>\n\n<pre><code>Node *safeMalloc(size_t size)\n{\n Node* newNode = malloc(size);\n if (newNode == NULL)\n {\n fprintf(stderr, \"Memory allocation failed in safeMalloc\\n\");\n exit(EXIT_FAILURE);\n }\n\n return newNode;\n}\n\nNode *createNewNode(int point, char name[30], Node *prev, Node *next)\n{\n Node *newNode = safeMalloc(sizeof(*newNode));\n newNode->point = point;\n strcpy(newNode->name, name);\n newNode->next = next;\n newNode->prev = prev;\n\n return newNode;\n}\n</code></pre>\n\n<h2>Declarations of Node Structs</h2>\n\n<p>It might have been easier to write the struct declarations as </p>\n\n<pre><code>typedef struct node\n{\n int point;\n char name[30];\n struct node *next;\n struct node *prev;\n} Node;\n\ntypedef struct list\n{\n Node *head;\n Node *tail;\n int count;\n} List;\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>The function <code>void swapNode(List *listNode, char nameA[30], char nameB[30])</code> can be simplified by breaking it into 2 functions, one that does the comparisons and then calls a swaping function as necessary:</p>\n\n<pre><code>void doSwap(Node *A, Node*B)\n{\n Node p=*A;\n *A=*B;\n *B=p;\n\n B->next = A->next;\n B->prev = A->prev;\n\n A->next = p.next;\n A->prev = p.prev;\n}\n\nvoid swapNode(List *listNode, char nameA[30], char nameB[30])\n{\n Node *A = NULL, *B = NULL;\n Node *temp = listNode->head;\n\n for (int i = 0; i < listNode->count; i++)\n {\n if (compareName(temp->name, nameA))\n {\n A = temp;\n }\n else if (compareName(temp->name, nameB))\n {\n B = temp;\n }\n temp = temp->next;\n if (A && B)\n {\n break;\n }\n }\n\n if ((A && B) && (A != B))\n {\n doSwap(A,B);\n }\n}\n</code></pre>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<h2>A Good Habit for Programming in C and C++</h2>\n\n<p>For readability and maintainability a good good habit (best practice) to get into is to always put the actions in <code>if</code> statements and loops into braces (<code>{</code> and <code>}</code>) as shown in the previous example. One of the major causes of bugs is to add a single line to the contents of an iff statement and to forget to add the necessary the necessary braces. This type of problem is very hard to track down when it doesn't result in a compiler error.</p>\n\n<h2>Leaks</h2>\n\n<blockquote>\n <p>Are there any errors like memory leak in my code? </p>\n</blockquote>\n\n<p>If the code was part of a larger project there would be memory leaks, the function <code>free(void *ToBeFreed)</code> is never called. It might be better if some linked list operations such as <code>deleteNode()</code> were added to the code. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:40:45.703",
"Id": "462224",
"Score": "0",
"body": "I think function `safeMalloc` is not necessary because as far as I concern, when we allocate a pointer by `malloc` `calloc` or `realloc` compiler will set some adjacent bytes in RAM so it can not be `NULL` pointer. Am I right? @pacmaninbw"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:58:28.920",
"Id": "462226",
"Score": "0",
"body": "No, you are absolutely wrong. Given current RAM sizes it is rare for malloc to fail, but if it does fail the return value is NULL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T16:04:27.380",
"Id": "462227",
"Score": "0",
"body": "so how do we know a pointer is failed to allocate memory, it is random or have a condition?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T16:04:34.997",
"Id": "462228",
"Score": "0",
"body": "@Becker in more modern languages such as C++, C# and Java memory allocation errors throw exceptions, the C programming languages is more of a high level assembler than most high level languages and memory allocation is just memory allocation and nothing else"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:15:18.560",
"Id": "462236",
"Score": "0",
"body": "@pacmaninbw [Rust is plenty modern, and it doesn't have exceptions](https://doc.rust-lang.org/book/ch09-00-error-handling.html). Also, C isn't anywhere near high level assembly, otherwise it wouldn't be possible to optimize it so much. Sure, JVM and .Net languages do far more to keep you from the metal, with all the advantages and disadvantages that implies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:14:16.253",
"Id": "462251",
"Score": "0",
"body": "\"One of the major causes of bugs is to add a single line to the contents of an iff statement and to forget to add the necessary the necessary braces.\" It's trivially fixed by just enforcing that brace-less `if` statements must only appear in one line: `if (condition) return;`. If that line gets too long, then you must use `{ }`, but never `if (condition) \\n return;`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:24:10.717",
"Id": "236026",
"ParentId": "236002",
"Score": "5"
}
},
{
"body": "<p>I get quite a lot of warnings when compiling with a reasonably picky compiler¹. Many are due to assigning string literals (<code>const char*</code>) to <code>char*</code> variables, which risks attempting invalid writes. For example:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>236002.c: In function ‘main’:\n236002.c:172:30: warning: passing argument 3 of ‘insertHead’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]\n 172 | insertHead(listNode, 10, \"abc def\");\n | ^~~~~~~~~\n236002.c:163:49: note: expected ‘char *’ but argument is of type ‘const char *’\n 163 | void insertHead(list *listNode, int point, char name[30]);\n | ~~~~~^~~~~~~~\n</code></pre>\n\n<p><code>main()</code> and <code>createList()</code> are declared as accepting <em>unspecified</em> arguments; it's good practice to declare them taking <em>no</em> arguments:</p>\n\n<pre><code>list *createList(void);\nint main(void);\n</code></pre>\n\n<p>We call <code>allocateNewNode()</code> which doesn't exist - perhaps that should be <code>createNewNode()</code>?</p>\n\n<p>There are <code>return</code> statements with a value, in a function declared to return <code>void</code>. That needs to be fixed.</p>\n\n<p>Once the code compiles, we can run it under Valgrind and see what it says:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>==2746238== HEAP SUMMARY:\n==2746238== in use at exit: 304 bytes in 6 blocks\n==2746238== total heap usage: 7 allocs, 1 frees, 1,328 bytes allocated\n==2746238== \n==2746238== 304 (24 direct, 280 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6\n==2746238== at 0x483677F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==2746238== by 0x1092B7: createList (236002.c:68)\n==2746238== by 0x109161: main (236002.c:36)\n==2746238== \n==2746238== LEAK SUMMARY:\n==2746238== definitely lost: 24 bytes in 1 blocks\n==2746238== indirectly lost: 280 bytes in 5 blocks\n==2746238== possibly lost: 0 bytes in 0 blocks\n==2746238== still reachable: 0 bytes in 0 blocks\n==2746238== suppressed: 0 bytes in 0 blocks\n</code></pre>\n\n<p>That's disappointing: we have failed to clean up the memory we allocated - some <code>malloc()</code> or similar is not matched with a corresponding <code>free()</code>.</p>\n\n<p>Looking in detail at the code, I see a function <code>compareName()</code> that seems to be mostly a reimplementation of <code>strncmp()</code> - do familiarise yourself with the Standard C Library, and use it to avoid reimplementing functions that have been written for you (generally more robustly and efficiently).</p>\n\n<p>The creation functions allocate memory, but always assume that <code>malloc()</code> was successful. That's a latent bug - it can return a null pointer if it fails. A minimal check could just bail out in that case:</p>\n\n<pre><code>node *newNode = malloc(sizeof *newNode);\nif (!newNode) {\n fputs(\"Memory allocation failure.\\n\", stderr);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>Note: <code>malloc()</code> returns a <code>void*</code>, which needs no cast to be assigned to any pointer variable. And we take the sizeof the pointed-to object, which is easier to check than having to look up its type.</p>\n\n<p>More library-orientated code will just return <code>NULL</code> early, to pass the error on to the caller to handle.</p>\n\n<p>The list structure is unusual - we don't normally use a count, but just let a sentinel pointer in <code>next</code> (either a null pointer, or a pointer back to a dummy head) indicate the end of the list. The code seems to use a mix of both, sometimes counting (e.g. in <code>swapNode()</code>) and sometimes chasing pointers (e.g. in <code>main()</code>).</p>\n\n<hr>\n\n<p>¹ <code>gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T03:51:54.913",
"Id": "462289",
"Score": "0",
"body": "could you please give me an e.g. about `Many are due to assigning string literals (const char*) to char* variables, which risks attempting invalid writes.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T08:50:21.933",
"Id": "462311",
"Score": "0",
"body": "I've edited to include the first of those warnings. HTH."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:30:16.940",
"Id": "462318",
"Score": "0",
"body": "my compiler does not show that warning. I have search for \"picky compiler\" but there is no tutorial to set up picky compiler. Could you show me how to set up it please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:45:49.433",
"Id": "462320",
"Score": "0",
"body": "Did you read the footnote showing my GCC options? Most reputable compilers have a similar set of warnings that you'd want to enable (just try searching for your compiler name with \"all warnings\" or similar)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:14:18.103",
"Id": "462328",
"Score": "0",
"body": "ok, I have just turn on some GCC options but when I compile code there is no warning. How to fix it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:24:19.480",
"Id": "462345",
"Score": "0",
"body": "That sounds like a good question for [so], rather than Code Review now."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T17:42:44.110",
"Id": "236034",
"ParentId": "236002",
"Score": "3"
}
},
{
"body": "<p>Swapping Nodes without changing the data</p>\n<pre><code>node* swapnodes(node* head,int x,int y)\n{\nnode* currx=NULL,*curry=NULL;\nnode* temp=head;\nwhile(temp)\n{\n if(temp->data==x||temp->data==y)\n {\n if(!currx)\n currx=temp;\n else\n {\n curry=temp;\n break;\n }\n }\n temp=temp->next;\n}\nif(currx->prev)\ncurrx->prev->next=curry;\nelse\nhead=curry;\nif(curry->next)\ncurry->next->prev=currx;\n\nif(currx->next==curry)//Adjacent Nodes\n{\n curry->prev=currx->prev;\n currx->next=curry->next;\n currx->prev=curry;\n curry->next=currx;\n return head;\n}\ncurry->prev->next=currx;\ncurrx->next->prev=curry;\nswap(currx->next,curry->next);\nswap(currx->prev,curry->prev);\nreturn head;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T11:22:26.367",
"Id": "478800",
"Score": "1",
"body": "Hey, welcome to Code Review! This answer could be improved by adding more explanation of *why* and *how* this is better than the code in the OP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T16:06:03.880",
"Id": "478836",
"Score": "1",
"body": "Welcome to the Code Review site where we review working code and provide suggestions on how to improve that code. While code only alternative solutions are acceptable on stack overflow, they are considered poor answers on Code Review and may be down voted or deleted. A good answer must contain one or more meaningful observations about the code, code can be used as examples."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:21:42.377",
"Id": "243907",
"ParentId": "236002",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "236026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T04:27:41.427",
"Id": "236002",
"Score": "6",
"Tags": [
"performance",
"c"
],
"Title": "function swap 2 nodes in doubly linked list"
}
|
236002
|
<p>Can anybody help me to minimize my hard coding? Also please give me any suggestions for improving my code for the future?</p>
<p>My Source Code:</p>
<pre><code> export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.border}>
<Image source={{uri:'https://images.unsplash.com/photo-1579551356536-e2d17fe1c7fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'}} style={styles.image}/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
padding: 8,
},
border:{
width: 200,
height: 300,
borderTopEndRadius: 50,
borderBottomStartRadius: 50,
borderRadius: 15,
backgroundColor: 'red',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 8,
},
image:{
width:'100%',
height: '100%',
borderTopEndRadius: 50,
borderBottomStartRadius: 50,
borderRadius: 15,
}
});
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>To clean the main <code>render</code>, we can extract the below JSX into a method and render that method into the main <code>render</code>.</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code><View style={styles.container}>\n <View style={styles.border}>\n <Image source={{uri: URI}} style={styles.image}/>\n </View>\n </View>)\n</code></pre>\n<ul>\n<li><p>For image url, instead of assigning it directly into the <code><Img ></code> tag, we can declare a <code>static</code> property or even in the <code>constructor</code> or <code>state</code>, then can use accordingly.</p>\n</li>\n<li><p>Further refactoring can be done by extracting the <code>StyleSheet</code> into a separate <code>Style.js</code>.</p>\n</li>\n<li><p>All the <code>colors</code> used can be used from a single file.</p>\n</li>\n</ul>\n<blockquote>\n<p>Modified Code:</p>\n</blockquote>\n<pre class=\"lang-js prettyprint-override\"><code> export default class App extends React.Component {\n static URI = 'https://images.unsplash.com/photo-1579551356536-e2d17fe1c7fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'\n\n defaultView = () => { \n return(\n <View style={styles.container}>\n <View style={styles.border}>\n <Image source={{uri: URI}} style={styles.image}/>\n </View>\n </View>)}\n\n render() {\n return (\n {this.defaultView()}\n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n justifyContent: 'center',\n alignItems: 'center',\n backgroundColor: '#fff',\n padding: 8,\n },\n border:{\n width: 200, \n height: 300,\n borderTopEndRadius: 50,\n borderBottomStartRadius: 50,\n borderRadius: 15, \n backgroundColor: 'red', \n shadowColor: '#000',\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.8,\n shadowRadius: 8, \n },\n image:{\n width:'100%', \n height: '100%', \n borderTopEndRadius: 50,\n borderBottomStartRadius: 50,\n borderRadius: 15, \n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:49:57.343",
"Id": "485933",
"Score": "1",
"body": "Could you please explain your code ? Is this an alternative solution or an improvement of the OP's approach ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:52:20.910",
"Id": "485935",
"Score": "1",
"body": "it's an improvement!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:53:59.513",
"Id": "485936",
"Score": "0",
"body": "It would be good if you explain what you improved"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:28:29.090",
"Id": "485943",
"Score": "0",
"body": "basically i cleaned the main `render` by exporting it to a method and fetched the images from a static variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:34:48.893",
"Id": "485946",
"Score": "1",
"body": "While this might be a great answer on Stack Overflow, code only alternate solutions are considered bad answers on Code Review. Good answers may not contain any code but they provide meaningful observations about the code. At the top of your answer please explain in detail why you think your code is better in terms of the original code posted."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:09:13.693",
"Id": "248133",
"ParentId": "236004",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T05:08:37.607",
"Id": "236004",
"Score": "3",
"Tags": [
"javascript",
"react.js",
"react-native"
],
"Title": "Minimize Hard Coding in React Native"
}
|
236004
|
<p>I know this code worked as I've tested it with the case tests commented below in the code, and even added a few of my own, but the developers who were testing me came back with the following critiques:</p>
<ol>
<li>All in one file, no attempt to modularise or separate out concerns</li>
<li>No tests at all. You could possibly forgive an entry level submission for 0% tests but seniors should be demonstrating their value</li>
<li>Everything is declared as let variables which suggests they can be overridden. I would assume most of them should be consts. Again, senior should demonstrate this</li>
<li>The submission can be difficult to read with the excessive comments and everything altogether</li>
</ol>
<p>I included their original tests, as well as three of my own, commented out within the code below. I'm not sure whether these were ignored or dismissed. Could anyone shed some light as to how this code could have been improved? If I get another coding test, I'd like to have some insight as to what is expected in terms of code formatting with respect to these sorts of comments.</p>
<blockquote>
<h1>Toy Robot Simulator</h1>
<h2>Description</h2>
<ul>
<li>The application is a simulation of a toy robot moving on a square tabletop, of dimensions 5 units x 5 units.</li>
<li>There are no other obstructions on the table surface.</li>
<li>The robot is free to roam around the surface of the table, but must be prevented from falling to destruction. Any movement that would
result in the robot falling from the table must be prevented,
however further valid movement commands must still be allowed.</li>
</ul>
<p>Create an application that can read in commands of the following form:</p>
<pre><code>PLACE X,Y,F
MOVE
LEFT
RIGHT
REPORT
</code></pre>
<ul>
<li>PLACE will put the toy robot on the table in position X,Y and facing NORTH, SOUTH, EAST or WEST.</li>
<li>The origin (0,0) can be considered to be the SOUTH WEST most corner.</li>
<li>The first valid command to the robot is a PLACE command, after that, any sequence of commands may be issued, in any order, including
another PLACE command. The application should discard all commands
in the sequence until a valid PLACE command has been executed.</li>
<li>MOVE will move the toy robot one unit forward in the direction it is currently facing.</li>
<li>LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot.</li>
<li><p>REPORT will announce the X,Y and F of the robot. This can be in any form, but standard output is sufficient.</p></li>
<li><p>A robot that is not on the table can choose the ignore the MOVE, LEFT, RIGHT and REPORT commands.</p></li>
<li>Input can be from a file, or from standard input, as the developer chooses.</li>
<li>Provide test data to exercise the application.</li>
</ul>
<h2>Constraints</h2>
<ul>
<li>The toy robot must not fall off the table during movement. This also includes the initial placement of the toy robot.</li>
<li>Any move that would cause the robot to fall must be ignored.</li>
</ul>
<h2>Example Input and Output</h2>
<h3>Example a</h3>
<pre><code>PLACE 0,0,NORTH
MOVE
REPORT
</code></pre>
<p>Expected output:</p>
<pre><code>0,1,NORTH
</code></pre>
<h3>Example b</h3>
<pre><code>PLACE 0,0,NORTH
LEFT
REPORT
</code></pre>
<p>Expected output:</p>
<pre><code>0,0,WEST
</code></pre>
<h3>Example c</h3>
<pre><code>PLACE 1,2,EAST
MOVE
MOVE
LEFT
MOVE
REPORT
</code></pre>
<p>Expected output</p>
<pre><code>3,3,NORTH
</code></pre>
<h2>Deliverables</h2>
<p>The Ruby source files, the test data and any test code.</p>
<p>It is not required to provide any graphical output showing the
movement of the toy robot.</p>
</blockquote>
<pre><code>// Toy Robot!
/* A few caveats for this solution
1) Input is said to be of a text format, we will make this an array with each element containing a command
e.g. ["PLACE 1,2,NORTH", "MOVE", "LEFT", "MOVE", "REPORT"]
2) I'm doing this in NodeJS (JavaScript)
3) To run this one could run this directly in the Node terminal, or copy and paste it into JSBin.com and execute it there;
or reference it in an HTML file; so in saying that, the executed input will be located at the bottom of the functional definition.
*/
/* CODE STARTS */
"use strict"
let Robot = function(aCommands) {
let iTableX = 5; // Width of Table
let iTableY = 5; // Height of Table
let aDir = ["NORTH","EAST","SOUTH","WEST"]; // Directions
let sRobotDir = 0; // Sets the default based off the above array
let aCommandSplit = [];
// Sets default setting for robot's coordinates X, Y
let iRobotX = 0;
let iRobotY = 0;
let bRobotPlaced = false; // Determines if the robot has been placed on the board...
let aTokens = []; // Sets up a basic array to hold our tokens
// Can I tell you I'm already enjoying programming this? :D
/* Let's set up some basic rules here
1) We split each element into a command and optional options (options only available with PLACE command)
2) We iterate through each array element, anything but a starting PLACE command is ignored.
3) As we proceed through each element, a switch command will assess the value of the command, and then takes an appropriate action.
*/
// Tokenizing engine
for(let iLoop = 0, iLen = aCommands.length; iLoop < iLen; iLoop++) {
aCommandSplit = aCommands[iLoop].toUpperCase().split(" "); // Initiates primary split, ensuring all commands are upper case
if(aCommandSplit.length == 2) {
aCommandSplit[1] = aCommandSplit[1].split(","); // split parameters
} else {
aCommandSplit[1] = []; // defafult
}
aTokens.push(aCommandSplit);
}
// Invalid Command
let invalidCommand = function(item) {
console.log(">> INVALID COMMAND: '"+item.join(" ")+"' IGNORED");
};
// Checks if value is below zero
let isBelowZero = (val) => (val < 0);
// Checks if value is equal to or above a certain limit
let isBeyondTableLimit = (val,limit) => (val >= limit);
// Checks if string represents a positive value
let isPosInteger = function (str) {
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
};
// Checks to see if the string is a direction in the direction array
let isDirection = (str) => !!~aDir.indexOf(str);
// Returns the index of the direction string
let whichDirection = (str) => aDir.indexOf(str);
// Validates the parameters for placement
let checkPlaceParams = (arr) => (
(arr != []) && // array isn't empty
(arr.length == 3) && // array contains three elements
isPosInteger(arr[0]) && // element 0 is a positive integer or zero
isPosInteger(arr[1]) && // element 1 is a positive integer or zero
(typeof(arr[2]) == "string") && // element 2 is a string
isDirection(arr[2]) && // element 2 is a direction
!isBelowZero(+arr[0]) && // element 0 is equal to zero or above
!isBelowZero(+arr[1]) && // element 1 is equal to zero or above
!isBeyondTableLimit(+arr[0], iTableX) && // element 0 is not bigger than the table size
!isBeyondTableLimit(+arr[1], iTableY) // element 1 is not bigger than the table size
);
// Sets the placement
let place = function(item) {
if(checkPlaceParams(item[1])) {
iRobotX = +item[1][0];
iRobotY = +item[1][1];
sRobotDir = whichDirection(item[1][2]);
bRobotPlaced = true;
}
};
// Rotates the robot left or right.
let rotate = function(turn) {
let newDir = (sRobotDir + ((turn=="LEFT")?3:1))%4;
sRobotDir = newDir;
};
// Checks to see if the robot can move in a certain direction
let canMove = function() {
switch(sRobotDir) {
case 0: // North
return (!isBeyondTableLimit(iRobotY+1, iTableY));
break;
case 1: // East
return (!isBeyondTableLimit(iRobotX+1, iTableX));
break;
case 2: // South
return (!isBelowZero(iRobotY-1));
break;
case 3: // West
return (!isBelowZero(iRobotX-1));
break;
}
}
// Moves the robot
let move = function() {
if(sRobotDir % 2 == 1) { // If east or west
if(sRobotDir == 1) { // if east
iRobotX++;
} else {
iRobotX--;
}
} else {
if(sRobotDir == 0) { // if north
iRobotY++;
} else {
iRobotY--;
}
}
};
// Reports position and direction facing
let report = function() {
console.log([iRobotX,iRobotY,aDir[sRobotDir]].join(","));
};
// Step through the tokens
aTokens.forEach(function(item, index) {
switch (item[0]) {
case "PLACE":
place(item);
break;
case "LEFT":
case "RIGHT":
bRobotPlaced ? rotate(item[0]) : invalidCommand(item);
break;
case "MOVE":
(bRobotPlaced && canMove()) ? move() : invalidCommand(item);
break;
case "REPORT":
bRobotPlaced ? report() : invalidCommand(item);
break;
default:
invalidCommand(item);
break;
}
});
};
/* CODE ENDS */
/* EXECUTE BLOCK STARTS */
// Original Test Cases
// Robot(["PLACE 0,0,NORTH","MOVE","REPORT"]); // 0,1,NORTH
// Robot(["PLACE 0,0,NORTH","LEFT","REPORT"]); // 0,0,WEST
// Robot(["PLACE 1,2,EAST","MOVE","MOVE","LEFT","MOVE","REPORT"]); // 3,3,NORTH
// My Test Cases
// Robot(["PLACE 1,2,NORTH", "MOVE", "LEFT", "MOVE", "REPORT"]); // Expected result: 0,3,WEST
// Robot(["MOVE","PLACE 0,3,WEST","MOVE","RIGHT","MOVE","MOVE","REPORT"]); // Expected result: 0,4,NORTH
/* NOTE: Robot should ignore first MOVE command because it hasn't been PLACE-d yet, and then ignore the second MOVE command because it can't go any further west, be able to move on the third MOVE command, but then ignore the last MOVE command because it can't go any further north. */
//Robot(["PLACE 2,2,NORTH","KEFT","NOVE","MOVE","REPORT"]);
/* Should ignore the "KEFT" command as it can't rotate "KEFT", then ignore the "NOVE" command, but obey the "MOVE" command.
Final result: 2,3,NORTH */
/* EXECUTE BLOCK ENDS */
</code></pre>
|
[] |
[
{
"body": "<p>Aside from the given critiques (which are all correct) I have following notes:</p>\n\n<ul>\n<li>Prefixing variable names with its type (Hungarian notation) is generally considered bad style. (BTW, what does the <code>s</code> in <code>sRobotDir</code> stand for?)</li>\n<li>Aside from using <code>let</code> instead of <code>const</code>, constants such as (<code>iTableX</code>, <code>iTableY</code> or <code>aDir</code> should be defined outside the main function (which would require modularization to avoid them becoming global variables). Also it would be worth considering making <code>iTableX</code> and <code>iTableY</code> configurable, so that different sized tables can be used at run-time.</li>\n<li>Tokenization is too fragile for my taste. It should either should be able to handle superfluous spaces, or be more strict on what it accepts and throw more/earlier errors if it finds something invalid.</li>\n<li>Having the helper functions in the middle of main function breaks the reading flow. I'd place them at the end or outside the function (again requiring modularization). Also using the conventional <code>function</code> statement instead of lambda notation would make them more readable.</li>\n<li>The function <code>place</code> only needs <code>item[1]</code> as its parameter, and <code>item</code> isn't a good variable name here.</li>\n<li>You have a few places where you use <code>==</code> instead of <code>===</code>.</li>\n<li>I'm not sure if <code>isBelowZero</code> and <code>isBeyondTableLimit</code> are a good idea. I'd go for something like:</li>\n</ul>\n\n\n\n<pre><code>function createLimitsCheck(min, max) {\n return value => value >= min && value < max;\n} \nconst checkLimitsX = createLimitsCheck(0, iTableX);\nconst checkLimitsY = createLimitsCheck(0, iTableY);\n</code></pre>\n\n<ul>\n<li><code>!!~</code> in <code>isDirection</code> is unnecessarily cryptic.</li>\n<li><code>isPosInteger</code> is over-engineered. Considering you'll need the integer value (for which you just the unary <code>+</code> operator anyway) and check it against the table limits later, I'd drop it altogether.</li>\n<li><code>checkPlaceParams</code> is also over-engineered with multiple unnecessary tests:\n\n<ul>\n<li><code>arr != []</code> can never return <code>false</code>, because it compares object references and not contents.</li>\n<li>I don't believe <code>arr[2]</code> can ever be anything else than a string. And even if it would be <code>isDirection</code> would then return false. (BTW, <code>typeof</code> is an operator not a function, so don't use brackets: <code>typeof arr[2]</code>.)</li>\n<li><code>isBelowZero</code> is unnecessery together with <code>isPosInteger</code> which already checked that.</li>\n<li>You repeat the conversion to numbers here and back in <code>place</code> again.</li>\n</ul></li>\n</ul>\n\n<p>Personnally I'd rewrite <code>checkPlaceParams</code> as follows:</p>\n\n<pre><code>function checkPlaceParams(params) {\n const x = +params[0];\n const y = +params[1];\n const dir = whichDirection(params[2]);\n if (checkLimitsX(x) && checkLimitsY(y) && dir > -1) {\n return [x, y, dir];\n }\n return; // undefined\n }\n</code></pre>\n\n<p>and <code>place</code> as</p>\n\n<pre><code>function place(params) { // only pass item[1]\n const validatedParams = checkPlaceParams(params || []) // avoid passing undefined\n if (validatedParams) {\n [iRobotX, iRobotY, sRobotDir] = validatedParams;\n bRobotPlaced = true;\n } else {\n console.log( ... );\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:33:23.490",
"Id": "462223",
"Score": "1",
"body": "_\"BTW, what does the s in sRobotDir stand for?\"_ This is presumably a remnant from when this contained the direction itself (`\"NORTH\"`) instead of its index in the array of directions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T23:58:07.240",
"Id": "462283",
"Score": "0",
"body": "You're right @Flater, I forgot all about that identifier..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T07:20:09.693",
"Id": "462307",
"Score": "0",
"body": "And that's one of the reasons not to use Hungarian notation. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T13:59:28.953",
"Id": "236023",
"ParentId": "236006",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T06:06:43.467",
"Id": "236006",
"Score": "6",
"Tags": [
"javascript",
"interview-questions",
"state-machine"
],
"Title": "Toy Robot Simulator"
}
|
236006
|
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/dynamic-array/problem" rel="nofollow noreferrer">Dynamic Array</a> problem on HackerRank:</p>
<blockquote>
<ul>
<li>Create a list, seqList, of N empty sequences, where each sequence is indexed from 0 to N-1. The elements within each of the N sequences also use 0-indexing.</li>
<li>Create an integer, lastAnswer, and initialize it to 0.</li>
<li>The 2 types of queries that can be performed on your list of sequences (seqList) are described below:
<ol>
<li>Query: 1 x y
<ol>
<li>Find the sequence, seq, at index ((x ^ lastAnswer) % N) in seqList.</li>
<li>Append integer y to sequence seq.</li>
</ol></li>
<li>Query: 2 x y
<ol>
<li>Find the sequence, seq, at index ((x ^ lastAnswer) % N) in seqList.</li>
<li>Find the value of element y % size in seq (where size is the size of seq) and assign it to lastAnswer.</li>
<li>Print the new value of lastAnswer on a new line.</li>
</ol></li>
</ol></li>
</ul>
</blockquote>
<p>However, I am getting a “time out error” for very large inputs. </p>
<p>Below is my code in Swift so far: </p>
<pre><code>func dynamicArray(n: Int, queries: [[Int]]) -> [Int] {
var sequences: [Int: [Int]] = [:]
var lastAnswer = 0
var answerlist = [Int]()
for query in queries {
let queryType = query[0]
let x = query[1]
let y = query[2]
switch queryType {
case 1:
let seq = (x ^ lastAnswer) % n
if var sequence = sequences[seq] {
sequence.append(y)
sequences[seq] = sequence
} else {
sequences[seq] = [y]
}
case 2:
let seq = (x ^ lastAnswer) % n
let index = y % (sequences[seq])!.count
lastAnswer = sequences[seq]![index]
answerlist.append(lastAnswer)
default: break
}
}
return answerlist
}
</code></pre>
<p>Can it be further optimised?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T07:22:01.747",
"Id": "462149",
"Score": "0",
"body": "For which input this code is being failed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T07:31:17.583",
"Id": "462151",
"Score": "0",
"body": "(PFB made me think you Canadian.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T07:34:30.657",
"Id": "462154",
"Score": "0",
"body": "Please block-quote the gist of the problem statement near the top of your question. Please describe how the code solves the problem - in the code, preferably."
}
] |
[
{
"body": "<p>You chose to represent the “list of sequences” as a dictionary</p>\n\n<blockquote>\n<pre><code>var sequences: [Int: [Int]] = [:]\n</code></pre>\n</blockquote>\n\n<p>and here you test if a sequence for the given index already exists, and then either append a new element or create the initial sequence for that index:</p>\n\n<blockquote>\n<pre><code>if var sequence = sequences[seq] {\n sequence.append(y)\n sequences[seq] = sequence\n} else {\n sequences[seq] = [y]\n}\n</code></pre>\n</blockquote>\n\n<p>That can be greatly simplified by using a subscript with a default value:</p>\n\n<pre><code>sequences[seq, default: []].append(y)\n</code></pre>\n\n<p>But actually, instead of representing the “list of sequences” as a dictionary I would represent it as an array (of arrays) instead:</p>\n\n<pre><code>var sequences: [[Int]] = Array(repeating: [], count: n)\n</code></pre>\n\n<p>The number of sequences is a-priori known, so that there is no advantage of using a dictionary. Appending a new element to a sequences (query type 1) then becomes</p>\n\n<pre><code>sequences[seq].append(y)\n</code></pre>\n\n<p>and for query type 2 we get</p>\n\n<pre><code>lastAnswer = sequences[seq][index]\nanswerlist.append(lastAnswer)\n</code></pre>\n\n<p>without the need of forced-unwrapping for the dictionary subscripting.</p>\n\n<p>This should also be more efficient, because (array) index lookups are faster than dictionary lookups.</p>\n\n<p>Some more remarks:</p>\n\n<ul>\n<li>The type of a variable should not be part of the variable name, e.g. <code>answers</code> instead of <code>answerList</code>.</li>\n<li><p>Multiple (related) assignments can be combined to a tuple assignment, e.g.</p>\n\n<pre><code>let (queryType, x, y) = (query[0], query[1], query[2])\n</code></pre></li>\n<li><p>We know that the query type can only be 1 or 2, but a <code>fatalError()</code> in the default case helps to find programming errors.</p></li>\n</ul>\n\n<p>Putting it together, the function could look like this:</p>\n\n<pre><code>func dynamicArray(n: Int, queries: [[Int]]) -> [Int] {\n var sequences: [[Int]] = Array(repeating: [], count: n)\n var lastAnswer = 0\n var answers = [Int]()\n for query in queries {\n let (queryType, x, y) = (query[0], query[1], query[2])\n switch queryType {\n case 1:\n let seq = (x ^ lastAnswer) % n\n sequences[seq].append(y)\n case 2:\n let seq = (x ^ lastAnswer) % n\n let index = y % sequences[seq].count\n lastAnswer = sequences[seq][index]\n answers.append(lastAnswer)\n default:\n fatalError(\"Bad query type\")\n }\n }\n return answers\n}\n</code></pre>\n\n<hr>\n\n<p>In addition, it seems that most of the time is spent while <em>reading the input data</em> into the <code>queries</code> array, done by the (HackerRank supplied template) code</p>\n\n<blockquote>\n<pre><code>guard let queriesRowTemp = readLine()?.replacingOccurrences(of: \"\\\\s+$\", with: \"\", options: .regularExpression) else { fatalError(\"Bad input\") }\n\nlet queriesRow: [Int] = queriesRowTemp.split(separator: \" \").map {\n if let queriesItem = Int($0) {\n return queriesItem\n } else { fatalError(\"Bad input\") }\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of removing trailing whitespace with a regular expression search we can split the input row and ignore empty components:</p>\n\n<pre><code>guard let queriesRowTemp = readLine() else { fatalError(\"Bad input\") }\nlet queriesRow: [Int] = queriesRowTemp.split(separator: \" \",\n omittingEmptySubsequences: true).map {\n if let queriesItem = Int($0) {\n return queriesItem\n } else { fatalError(\"Bad input\") }\n}\n</code></pre>\n\n<p>In my test that cut the time to read 100000 queries down from 3.7 to 1.7 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T09:22:42.923",
"Id": "462164",
"Score": "0",
"body": "I tried your code. However, the 6 out of 10 test cases are still failing. Your code seems to increase the readability but over all time complexity remained the same. So, the issue i faced is still persisting. Note: I also used 2-D array in my first attempt, but it couldn't help; then after i made sequences as dictionary as it as O(1) complexity in most of the cases. Please refer [link] (https://www.raywenderlich.com/1172-collection-data-structures-in-swift)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:07:00.067",
"Id": "462172",
"Score": "0",
"body": "@SiddharthKumar: See updated answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T10:34:32.200",
"Id": "462177",
"Score": "0",
"body": "Thanks Martin. The issue was with the hacker rank template code itself. Great work for pointing it out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T08:07:46.723",
"Id": "236012",
"ParentId": "236008",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236012",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T06:52:24.730",
"Id": "236008",
"Score": "2",
"Tags": [
"performance",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"swift"
],
"Title": "Dynamic Array Problem (Hacker rank)"
}
|
236008
|
<p>This is my JavaScript function to get a break time taken. I have two times (time_start and time_end). And with these two times, I have to get my break time. (break time hours are 12:00-13:00 and 17:45-18:15). The code below works but it contains a lot of nested <code>if</code> and <code>else</code>. Is there any method to reduce them?</p>
<pre><code>function timesheet(day,week_type,start_time,end_time){
this.day = day;
this.week_type = week_type;
this.start_time = convertTime(start_time);
this.start_time = (!isNaN(this.start_time)?this.start_time:0);
this.end_time = convertTime(end_time);
this.end_time = (!isNaN(this.end_time)?this.end_time:0);
this.work_start = convertTime("9:00");
this.work_end = convertTime("17:45");
this.break_1_start = convertTime("12:00");
this.break_1_end = convertTime("13:00");
this.break_2_end = convertTime("18:15");
//休憩時間を作業の開始時間と終業時間の次第で下の関数からゲットします。
this.break_time = function(){
/**
*この関数が取った休憩時間を渡します。
*/
if(this.start_time>this.end_time){
return 0;
}
else{
//if strart time is less than or equal to 12
if(this.start_time<=this.break_1_start){
if(this.end_time<=this.break_1_start){
return 0;
}
else if(this.end_time<this.break_1_end){
return (0+(this.end_time - this.break_1_start));
}
else{
if(this.end_time<this.work_end){
return 1;
}
else if(this.end_time<this.break_2_end){
return (1+(this.end_time - this.work_end));
}
else{
return 1.5;
}
}
}
else if(this.start_time<this.break_1_end){
if(this.end_time<this.break_1_end){
return (this.end_time - this.start_time);
}
else {
if(this.end_time<this.work_end){
return (this.break_1_end - this.start_time);
}
else if(this.end_time<this.break_2_end){
let break_one = this.break_1_end - this.start_time;
let break_two = this.end_time - this.work_end;
return (break_one+break_two);
}
else{
let break_one = this.break_1_end - this.start_time;
let break_two = this.break_2_end - this.work_end;
return (break_two+break_one);
}
}
}
else if(this.start_time<this.work_end){
if (this.end_time<this.work_end){
return 0;
}
else{
if (this.end_time<this.break_2_end){
return (this.end_time-this.work_end);
}
else{
return(0.5);
}
}
}
else{
if(this.start_time<this.break_2_end){
return (this.break_2_end-this.start_time);
}
else{
return 0;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T08:55:29.317",
"Id": "462162",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T08:05:48.410",
"Id": "236011",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Getting break time taken"
}
|
236011
|
<p>After a few weeks of searching and learning "php secure", I created a class Failedlogins. </p>
<ol>
<li><strong>record_failed_login</strong> -> recording the logins, if doesn't find the record, he create the new one. If he does find - will be updated.</li>
<li><strong>clear_failed_logins</strong> -> is similar like record failed login, if accept user then - set the count = 0.</li>
<li><strong>throttle_failed_logins</strong> -> returns the number of minutes to wait until logins are allowed again.</li>
</ol>
<p>I don't know how to inserting associative array into mysql table with prepared statement, that's why I used "<code>self::$database->escape_string</code>".</p>
<p><code>$this->sanitized_attributes();</code> comes from <code>class DatabaseObject</code> </p>
<pre><code>CREATE TABLE `failed_logins` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(255) NOT NULL,
`count_f` int(11) NOT NULL,
`last_time` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
<?php
class Failedlogins extends DatabaseObject {
static protected $table_name = "failed_logins";
static protected $db_columns = ['username', 'count_f', 'last_time'];
public $id;
public $username;
public $count_f;
public $last_time;
protected $failed_login;
static public function find_one_in_db($username) {
$sql = "SELECT * FROM " . self::$table_name . " ";
$sql .= "WHERE username='" . self::$database->escape_string($username) . "' ";
$sql .= "LIMIT 1";
$result = self::$database->query($sql);
$failed_logins = $result->fetch_assoc();
$result->free();
return $failed_logins;
}
protected function add_record_to_db($failed_login) {
// Insert record
foreach($failed_login as $key => $value){
$failed_login = [];
$failed_login['username'] = $value['username'];
$failed_login['count_f'] = $value['count_f'];
$failed_login['last_time'] = $value['last_time'];
$sql = "INSERT INTO " . self::$table_name . " (";
$sql .= join(', ', self::$db_columns);
$sql .= ") VALUES (";
$sql .= "'" . self::$database->escape_string($failed_login['username']) . "', ";
$sql .= "'" . self::$database->escape_string($failed_login['count_f']) . "', ";
$sql .= "'" . self::$database->escape_string($failed_login['last_time']). "'";
$sql .= ")";
}
$result = self::$database->query($sql);
if($result) {
$this->id = self::$database->insert_id;
}
return $result;
}
protected function update_record_in_db($failed_login) {
$attributes = $this->sanitized_attributes();
$attribute_pairs = [];
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= join(', ', $attribute_pairs);
$sql .= " WHERE username='" . self::$database->escape_string($this->username) . "' ";
$sql .= "LIMIT 1";
$result = self::$database->query($sql);
return $result;
}
public function record_failed_login($username) {
$failed_login = $this->find_one_in_db($username);
if(!isset($failed_login)) {
$failed_login[] = [
'username' => $username,
'count_f' => 1,
'last_time' => time()
];
$this->add_record_to_db($failed_login);
} else {
// existing failed_login record
$this->username = $failed_login['username'];
$this->count_f = $failed_login['count_f'] + 1;
$this->last_time = time();
$this->update_record_in_db($failed_login);
}
return true;
}
function clear_failed_logins($username) {
$failed_login = $this->find_one_in_db($username);
if(isset($failed_login)) {
$this->username = $failed_login['username'];
$this->count_f = $failed_login['count_f'] = 0;
$this->last_time = time();
$this->update_record_in_db($failed_login);
}
return true;
}
function throttle_failed_logins($username) {
$throttle_at = 5;
$delay_in_minutes = 10;
$delay = 60 * $delay_in_minutes;
$failed_login = $this->find_one_in_db($username);
if(isset($failed_login) && $failed_login['count_f'] >= $throttle_at) {
$remaining_delay = ($failed_login['last_time'] + $delay) - time();
$remaining_delay_in_minutes = ceil($remaining_delay / 60);
return $remaining_delay_in_minutes;
} else {
return 0;
}
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T19:54:00.130",
"Id": "462877",
"Score": "2",
"body": "I noticed is that you try to throttle based on an user name. That's not good enough. You will not throttle a brute force attack using the same password for many different user names. You left out the definition of you `DatabaseObject`. That is a real ommission since your `Failedlogins` class depends on it. You remarked that you're using \"php procedural style\" because you cannot use prepared statements. That doesn't make sense. You can use prepared statements with procedural style php. The two a not related."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T08:45:31.010",
"Id": "462927",
"Score": "0",
"body": "1. \"php procedural style\" the point is that I use self::$database->escape_string, I probably wrote it wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T08:55:36.457",
"Id": "462928",
"Score": "0",
"body": "2. I do not know how to use prepared statement to INSERT an array, I've never done this before. 3.\" using the same password for many different user names\" - you're right, i didn't think about that. 4. DatabaseObject with Failedlogins - I do not understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T13:42:15.000",
"Id": "462962",
"Score": "0",
"body": "The fact your having to add your own quotes to the escaped values indicates to me that something is wrong with your escape method as it should be returning a string that represents what you'd type in SQL for that value(so a null value would be `NULL`, the integer 4 would be `4`, but the string \"f'tang\" would be `'f''tang'`, etc). It shouldn't be returning something you have to quote or check the type of yourself when you decide you need to start passing null to the DB."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T12:36:35.137",
"Id": "236020",
"Score": "1",
"Tags": [
"php"
],
"Title": "Throttling - brute force attacks (security php)"
}
|
236020
|
<p>I'd like feedback on my solution to the outlined programming challenge. Is numpy a good candidate module for this? What might be a more efficient or Pythonic solution?</p>
<blockquote>
<p><a href="https://coderbyte.com/information/Closest%20Enemy%20II" rel="noreferrer">Closest Enemy II</a></p>
<p>Have the function ClosestEnemyII(strArr) read the matrix of numbers stored
in <code>strArr</code> which will be a 2D matrix that contains only the integers 1, 0,
or 2. Then from the position in the matrix where a 1 is, return the number
of spaces either left, right, down, or up you must move to reach an enemy
which is represented by a 2. You are able to wrap around one side of the
matrix to the other as well. For example: if <code>strArr</code> is
<code>["0000", "1000", "0002", "0002"]</code> then this looks like the following:</p>
<pre class="lang-none prettyprint-override"><code>0 0 0 0
1 0 0 0
0 0 0 2
0 0 0 2
</code></pre>
<p>For this input your program should return 2 because the closest enemy (2)
is 2 spaces away from the 1 by moving left to wrap to the other side and
then moving down once. The array will contain any number of 0's and 2's,
but only a single 1. It may not contain any 2's at all as well, where in
that case your program should return a 0.</p>
<pre class="lang-none prettyprint-override"><code>Examples
Input: ["000", "100", "200"]
Output: 1
Input: ["0000", "2010", "0000", "2002"]
Output: 2
</code></pre>
</blockquote>
<pre><code>import doctest
import numpy as np
from typing import List
def calc_closest_enemy(matrix: List[str]) -> int:
"""Calculate the minimum number of moves to reach an enemy
Moves allowed: left, right, up, down. All count as +1
Wrapping allowed: if current position is on an edge, a move
can be made to the opposite edge for the cost of 1 move.
>>> calc_closest_enemy(matrix=["000", "100", "200"])
1
>>> calc_closest_enemy(matrix=["0000", "2010", "0000", "2002"])
2
>>> calc_closest_enemy(matrix=["0000", "0010", "0000", "0000"])
0
>>> calc_closest_enemy(matrix=["0000", "0100", "0000", "0020"])
3
>>> calc_closest_enemy(matrix=["0000", "0100", "0000", "0000", "0020"])
3
>>> calc_closest_enemy(matrix=["0200", "0100", "0000", "0000", "0020"])
1
"""
grid = np.array([list(s) for s in matrix], dtype=np.int32)
# In case of no enemies
if 2 not in grid:
return 0
# format (y, x)
friendly_coords = tuple(int(i) for i in np.where(grid == 1))
assert len(friendly_coords) == 2, "Only one friendly is allowed"
# Create wrapped grid
# Wrap the y-axis then take the y-axis wrapped grid, transpose, and wrap the
# former x-axis (now y-axis after transposition)
for indx in friendly_coords:
height, _ = grid.shape
# These slices are appended to the appropriate grid ends to produce
# the wrapped grid
slice_to_friendly = grid[:indx]
slice_from_friendly = grid[indx+1:]
grid = np.insert(
arr=grid, values=slice_to_friendly, obj=height, axis=0)
grid = np.insert(
arr=grid, values=slice_from_friendly, obj=0, axis=0)
# Transpose to reuse code in for loop
grid = grid.T
# format (y, x)
friendly_coords = tuple(int(i) for i in np.where(grid == 1))
# Gather all enemy coords into a generator
enemy_locations = np.where(grid == 2)
enemy_locations = ((x, y) for y, x in zip(
enemy_locations[0], enemy_locations[1]))
# Calculate the moves required to travel from friendly to each enemy
# and return lowest
moves = [sum((abs(friendly_coords[1] - enemy[0]),
abs(friendly_coords[0] - enemy[1])))
for enemy in enemy_locations]
min_moves = min(moves)
return min_moves
if __name__ == "__main__":
doctest.testmod()
</code></pre>
|
[] |
[
{
"body": "<p>Here</p>\n\n<pre><code>enemy_locations = np.where(grid == 2)\nenemy_locations = ((x, y) for y, x in zip(\n enemy_locations[0], enemy_locations[1]))\n</code></pre>\n\n<p>the x/y-coordinates are swapped, and later the x-coordinate of each enemy is subtracted from the y-coordinate of the friend, and vice versa:</p>\n\n<pre><code>moves = [sum((abs(friendly_coords[1] - enemy[0]),\n abs(friendly_coords[0] - enemy[1])))\n for enemy in enemy_locations]\n</code></pre>\n\n<p>I find that confusing. If you don't swap the coordinates then the computation of the locations becomes simpler</p>\n\n<pre><code>enemy_locations = zip(*np.where(grid == 2))\n</code></pre>\n\n<p>and the distance computation becomes more logical:</p>\n\n<pre><code>moves = [sum((abs(friendly_coords[0] - enemy[0]),\n abs(friendly_coords[1] - enemy[1])))\n for enemy in enemy_locations]\n</code></pre>\n\n<p>Making <code>moves</code> a generator instead of a list would be sufficient.</p>\n\n<hr>\n\n<p>Here</p>\n\n<pre><code>friendly_coords = tuple(int(i) for i in np.where(grid == 1))\nassert len(friendly_coords) == 2, \"Only one friendly is allowed\"\n</code></pre>\n\n<p>you check if exactly one friend is given. But that check does not work: If there is zero or more than two <code>1</code> elements in the array then the <code>int(i)</code> conversion already fails with a</p>\n\n<pre><code>TypeError: only size-1 arrays can be converted to Python scalars\n</code></pre>\n\n<p>The error message is not appropriate if there is <em>no</em> friend.</p>\n\n<p>Also assertions are for finding programming errors. A grid with zero or more than 2 friends is a wrong parameter and a reason to raise a <a href=\"https://docs.python.org/3.7/library/exceptions.html#exceptions.ValueError\" rel=\"nofollow noreferrer\"><code>ValueError</code></a>:</p>\n\n<blockquote>\n <p>Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.</p>\n</blockquote>\n\n<p>My suggestion for that part would be</p>\n\n<pre><code>friendly_locations = list(zip(*np.where(grid == 1)))\nif len(friendly_locations) != 1:\n raise ValueError(\"There must be exactly one friend\")\nfriendly_coord = friendly_locations[0]\n</code></pre>\n\n<hr>\n\n<p>In order to compute the “wrapped distances” you augment the array by additional rows and columns. The dimensions of the array increase from <span class=\"math-container\">\\$ (m, n) \\$</span> to at most <span class=\"math-container\">\\$ (2m-1, 2n-1) \\$</span>, i.e. the number of elements is almost quadrupled if the friend is located at one of the corners.</p>\n\n<p>This can be completely avoided if the computation of the distance takes the wrapping into account:</p>\n\n<pre><code>def wrapped_distance(p1: Tuple[int, int], p2: Tuple[int, int], shape: Tuple[int, int]):\n \"\"\"Return the wrapped distance between two points.\n\n The Manhattan distance from p1 to p2 in a grid of the given shape\n is computed, taking wrapping around the edges of the grid into account.\n \"\"\"\n deltax = abs(p1[0] - p2[0])\n deltay = abs(p1[1] - p2[1])\n return min(deltax, shape[0] - deltax) + min(deltay, shape[1] - deltay)\n</code></pre>\n\n<p>And if the array is not modified then there is no need anymore to re-compute the friends's location. Also the pre-scan for the existence of enemies</p>\n\n<pre><code>if 2 not in grid:\n return 0\n</code></pre>\n\n<p>can now be replaced by calling <code>min()</code> with a default argument.</p>\n\n<p>The main function then becomes:</p>\n\n<pre><code>def calc_closest_enemy(matrix: List[str]) -> int:\n \"\"\"Calculate the minimum number of moves to reach an enemy.\n\n (... rest of your docstring omitted ...)\n \"\"\"\n grid = np.array([list(s) for s in matrix], dtype=np.int32)\n\n friendly_locations = list(zip(*np.where(grid == 1)))\n if len(friendly_locations) != 1:\n raise ValueError(\"There must be exactly one friend\")\n friendly_coord = friendly_locations[0]\n\n enemy_locations = zip(*np.where(grid == 2))\n distances = (wrapped_distance(friendly_coord, enemy, grid.shape)\n for enemy in enemy_locations)\n return min(distances, default = 0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T09:25:36.583",
"Id": "236053",
"ParentId": "236022",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>Is numpy a good candidate module for this?</p>\n</blockquote>\n\n<p>Using numpy is fine, but you can get by just fine without it.</p>\n\n<p>Borrowing Martin R's <code>wrapped_distance</code> function, you could solve the problem without any external libraries as follows:</p>\n\n<pre><code>def coordinates(matrix: List[str], subject: str) -> Iterable[Tuple[int, int]]:\n return ((r, c)\n for r, row in enumerate(matrix)\n for c, ch in enumerate(row)\n if ch == subject)\n\ndef calc_closest_enemy(matrix: List[str]) -> int:\n \"\"\"Calculate the minimum number of moves to reach an enemy\n\n (... rest of your docstring omitted ...)\n \"\"\"\n\n friendly_coord = next(coordinates(matrix, \"1\"))\n enemy_locations = coordinates(matrix, \"2\")\n shape = len(matrix), len(matrix[0])\n distances = (wrapped_distance(friendly_coord, enemy, shape) for enemy in enemy_locations)\n return min(distances, default=0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T18:41:26.793",
"Id": "236076",
"ParentId": "236022",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236053",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T13:49:57.553",
"Id": "236022",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"numpy",
"pathfinding"
],
"Title": "Find the closest enemy in a 2D grid with wrapping allowed"
}
|
236022
|
<p>I have two database tables UsersDownload, Non-UsersDownload. There is also two model object and two service that take in the object and insert the data into the correct table. Is this the best architecture for this? or is there a better way to handle this? Would it be better to use an interface?</p>
<pre><code>public class UserLog
{
public string CustomerId { get; set; }
public bool? IsMobile { get; set; }
public int? DeviceId { get; set; }
}
public class NonUserLog
{
public string DeviceId { get; set; }
public bool? IsMobile { get; set; }
public string AppType { get; set; }
}
</code></pre>
<p>insert using Store Procedure</p>
<pre><code> internal ResultStatus UsersDownload(UserLog userLog)
{
queryName = "usp_Insert_UserLog";
SQLHelper sql = new SQLHelper(conn);
ResultStatus rs = new ResultStatus();
SqlParameter[] parms = new SqlParameter[] {
new SqlParameter("@CustomerID", SqlDbType.NVarChar, 50),
new SqlParameter("@IsMobile", SqlDbType.Bit),
new SqlParameter("@DeviceId", SqlDbType.Int)
};
parms[0].Value = guidelineLog.CustomerId;
parms[1].Value = guidelineLog.IsMobile;
parms[2].Value = guidelineLog.DeviceId;
using (SqlDataReader dataReader = sql.ExecuteReaderStoreProcedure(queryName, parms))
{
rs.ResultCode = 1;
rs.ResultMessage = "Success";
dataReader.Close();
}
return rs;
}
internal ResultStatus NonUsersDownload(NonUserLog nonUserLog)
{
queryName = "usp_Insert_NonUserLog";
SQLHelper sql = new SQLHelper(conn);
ResultStatus rs = new ResultStatus();
SqlParameter[] parms = new SqlParameter[] {
new SqlParameter("@DeviceId", SqlDbType.NVarChar, 50),
new SqlParameter("@IsMobile", SqlDbType.Bit),
new SqlParameter("@AppType", SqlDbType.NVarChar)
};
parms[0].Value = guidelineLog.DeviceId;
parms[1].Value = guidelineLog.IsMobile;
parms[2].Value = guidelineLog.AppType;
using (SqlDataReader dataReader = sql.ExecuteReaderStoreProcedure(queryName, parms))
{
rs.ResultCode = 1;
rs.ResultMessage = "Success";
dataReader.Close();
}
return rs;
}
</code></pre>
<p>service</p>
<pre><code>public ResultStatus InsertUsersDownload(UserLog userLog)
{
return glDb.UsersDownload(userLog);
}
public ResultStatus InsertNonUsersDownload(NonUserLog nonUserLog)
{
return glDb.NonUsersDownload(nonUserLog);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T00:37:01.830",
"Id": "462457",
"Score": "0",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
}
] |
[
{
"body": "<p>It'll add more work if you use interface since your models are different, only one property (Mobile) is the common one, and you'll add Reflection to the equation as well. Even if you used a generic method, you'll add extra work to it. So, in your case, your best approach would be to use overloads (which you've already done) and keep it simple, but you've over-done it. Rather than just duplicating the method and change the model, you'll need to set a private base method, which is going to be used as call back. The other overloads will be set to each process respectively, then it'll callback the base method. </p>\n\n<pre><code>// UserLog overload\ninternal ResultStatus DownloadsLog(UserLog log)\n{\n var parameters = new SqlParameter[]\n {\n new SqlParameter { ParameterName = \"@CustomerID\", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = log.CustomerId },\n new SqlParameter { ParameterName = \"@IsMobile\", SqlDbType = SqlDbType.Bit, Value = log.IsMobile },\n new SqlParameter { ParameterName = \"@DeviceId\", SqlDbType = SqlDbType.Int, Value = log.DeviceId }\n };\n\n return DownloadsLog(\"usp_Insert_UserLog\", parameters);\n}\n\n// NonUserLog overload\ninternal ResultStatus DownloadsLog(NonUserLog log)\n{\n var parameters = new SqlParameter[]\n {\n new SqlParameter { ParameterName = \"@DeviceId\", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = log.DeviceId },\n new SqlParameter { ParameterName = \"@IsMobile\", SqlDbType = SqlDbType.Bit, Value = log.IsMobile },\n new SqlParameter { ParameterName = \"@AppType\", SqlDbType = SqlDbType.NVarChar, Value = log.AppType }\n };\n\n return DownloadsLog(\"usp_Insert_NonUserLog\", parameters);\n}\n\n// base\nprivate ResultStatus DownloadsLog(string procedureName, SqlParameter[] parameters)\n{\n using (var dataReader = new SQLHelper(conn).ExecuteReaderStoreProcedure(procedureName, parameters))\n {\n return new ResultStatus\n {\n ResultCode = 1,\n ResultMessage = \"Success\"\n };\n }\n}\n</code></pre>\n\n<p>as you can see, the <code>UserLog</code> and <code>NonUserLog</code> overloads are there just to set the parameters with the procedure name. Then, I just callback the base method. </p>\n\n<p><strong>Update</strong></p>\n\n<p>This is another approach where you define the parameters and the store procedure name in the model itself, kinda like gathering everything related into one box.</p>\n\n<pre><code>public interface ISqlDbLog\n{\n string GetSqlProcedureName();\n\n SqlParameter[] GetSqlParameters();\n}\n\npublic class UserLog : ISqlDbLog\n{\n public string CustomerId { get; set; }\n\n public bool? IsMobile { get; set; }\n\n public int? DeviceId { get; set; }\n\n public string GetSqlProcedureName() => \"usp_Insert_UserLog\";\n\n public SqlParameter[] GetSqlParameters()\n {\n return new SqlParameter[]\n {\n new SqlParameter { ParameterName = \"@CustomerID\", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = CustomerId },\n new SqlParameter { ParameterName = \"@IsMobile\", SqlDbType = SqlDbType.Bit, Value = IsMobile },\n new SqlParameter { ParameterName = \"@DeviceId\", SqlDbType = SqlDbType.Int, Value = DeviceId }\n };\n }\n}\n\npublic class NonUserLog : ISqlDbLog\n{\n public string DeviceId { get; set; }\n\n public bool? IsMobile { get; set; }\n\n public string AppType { get; set; }\n\n public string GetSqlProcedureName() => \"usp_Insert_NonUserLog\";\n\n public SqlParameter[] GetSqlParameters()\n {\n return new SqlParameter[]\n {\n new SqlParameter { ParameterName = \"@DeviceId\", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = DeviceId },\n new SqlParameter { ParameterName = \"@IsMobile\", SqlDbType = SqlDbType.Bit, Value = IsMobile },\n new SqlParameter { ParameterName = \"@AppType\", SqlDbType = SqlDbType.NVarChar, Value = AppType }\n };\n }\n}\n\nclass Program\n{\n internal static ResultStatus DownloadsLog(ISqlDbLog log)\n {\n return DownloadsLog(log.GetSqlProcedureName(), log.GetSqlParameters());\n }\n\n static void Main(string[] args)\n {\n var log = new UserLog\n {\n CustomerId = \"Test Customer\",\n DeviceId = 5,\n IsMobile = true\n };\n\n var result = DownloadsLog(log);\n\n }\n}\n</code></pre>\n\n<p>the advantage of this approach is that you have defined the data mapping within the model, which would be easier to navigate. The other thing, you're also defining the correct <code>SqlDbType</code> mapping. So, instead of using <code>AddWithValue</code>, you will pass the correct datatype, and it's already defined in the model. You can make a generic method where you use Reflection to auto-generate the SqlParameters, all you have to do is to change <code>GetSqlParameters()</code> to : </p>\n\n<pre><code>public SqlParameter[] GetSqlParameters()\n{\n return this.GetType()\n .GetProperties()\n .Where(x => x.GetValue(this, null) != null)\n .Select(x => new SqlParameter($\"@{x.Name}\", x.GetValue(this, null)))\n .ToArray();\n}\n</code></pre>\n\n<p>you can use it as an extension, if you have a wider usage (like applying it to other models as well). like this : </p>\n\n<pre><code>public static class SqlDbExtensions\n{\n public static SqlParameter[] ToSqlParameterArray<T>(this T model) where T : ISqlDbLog\n {\n return model.GetType()\n .GetProperties()\n .Where(x => x.GetValue(model, null) != null)\n .Select(x => new SqlParameter($\"@{x.Name}\", x.GetValue(model, null)))\n .ToArray();\n\n }\n}\n</code></pre>\n\n<p>This will be applied on all classes that implement <code>ISqlDbLog</code>. This is an insurance. So, with this, you will not need the <code>GetSqlParameter()</code> method in each class nor the <code>ISqlDbLog</code> interface. but you still need <code>ProcedureName</code>. </p>\n\n<p>I hope this would add more helpful thoughts to your work. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:53:44.987",
"Id": "462272",
"Score": "0",
"body": "So I would have to send the procedure name to the method is that something common that people do is sending the procedure name?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T22:01:16.360",
"Id": "462274",
"Score": "0",
"body": "@Jefferson yes, and don't worry about it, because it's private and will not be used outside this class scope, unless you expose it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:54:53.370",
"Id": "462350",
"Score": "0",
"body": "would it help if I have a flag in the NonUserLog model? Something like IsNonUser?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:38:56.460",
"Id": "462363",
"Score": "0",
"body": "Is there a way to have just one service?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:50:42.110",
"Id": "462450",
"Score": "0",
"body": "@Jefferson check the update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T00:26:11.180",
"Id": "462454",
"Score": "0",
"body": "Can I add the interface to the model? Can you please check the updated logic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T00:32:09.700",
"Id": "462455",
"Score": "0",
"body": "@Jefferson the updated interface would work also, you just need to add it to the models in order to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T00:42:11.003",
"Id": "462458",
"Score": "0",
"body": "@Jefferson yes should be fine, but you have to update your question with your modifications, so we know what modifications you've done, to help us determine what needs to be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T02:18:09.313",
"Id": "462461",
"Score": "0",
"body": "I posted the updated logic https://pastebin.com/JDK5XBmK"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T06:10:34.613",
"Id": "462471",
"Score": "0",
"body": "@Jefferson, I'm not sure why you're still forcing yourself to use `NonUsersDownloads` and `UsersDownload` overloads!. and why you have `public ResultStatus ProcessAppLogging(ILog objLog)` defined ? you don't need it, you only need it inside the models. so instead of doing `ProcessAppLogging(log)` , you'll only need to do `var result = log.ProcessAppLogging();` and that should do the work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T06:16:55.767",
"Id": "462472",
"Score": "0",
"body": "@Jefferson just saying, you're in a circle, where you try to do something, and you just recreate the same thing different ways! that's what makes your work redundant and your thoughts not clear enough. I suggest you give yourself a break, refresh air, then come back and work on it another time with a fresher mind!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T12:31:51.340",
"Id": "462505",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103649/discussion-between-jefferson-and-isr5)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:20:47.757",
"Id": "236043",
"ParentId": "236028",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236043",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T15:55:37.250",
"Id": "236028",
"Score": "4",
"Tags": [
"c#",
"interface"
],
"Title": "Architecture Logging"
}
|
236028
|
<h2>Overview</h2>
<p>I've just written a package in <strong>Python</strong> (which I've named <code>sibstructures</code>) whose purpose is to assist staff in managing a <strong>coldstore</strong>, which is a warehouse-sized refrigerator holding (in this case) boxes of potatoes.</p>
<p>The code below is one file taken from that package, the file which defines the centrepiece <code>Coldstore</code> class. It also defines a number of "helper" classes, i.e. small classes whose sole purpose is to facilitate something or other in <code>Coldstore</code>. The file then finishes with some unit tests.</p>
<p>I'm pretty much self-taught Python, so any remarks would be greatly appreciated, but I'd be particularly grateful for any guidance - or praise - regarding the way in which I've <strong>structured</strong> the file.</p>
<h2>The Code</h2>
<h3>Opening Lines</h3>
<p>This follows the proforma by which I begin almost all of my .py files.</p>
<pre class="lang-py prettyprint-override"><code>### This code defines a class, which models a potato coldstore.
# Imports.
import time
# Custom imports.
from sibstructures import sibconstants
from sibstructures import data_storage
from sibstructures import layer_colours
from sibstructures.box import Box
from sibstructures.spot import Spot
from sibstructures.numerals import to_roman, to_arabic
# Local constants.
max_tickets = 100
</code></pre>
<h3>Main Class</h3>
<p>There then follows the definition of the "main" class, which in this case models the coldstore itself.</p>
<p>A few features are worth explaining:</p>
<ul>
<li>The <code>data_storage</code> module allows access to a database, which (1) records what enters and exits the coldstore, (2) records where boxes are placed, and (3) stores plans for where boxes <em>should</em> be stored.</li>
<li>Scanners (using RFID) identify boxes as they enter and leave.</li>
<li>Using these scanners, the coldstore issues a recommendation to the storesman as to where to put a given box as it enters.</li>
<li>Upon receiving a recommendation, the storesman may either (1) follow the recommendation, (2) cancel the recommendation, or (3) override the recommendation (i.e. put the box somewhere else).</li>
</ul>
<pre class="lang-py prettyprint-override"><code>##############
# MAIN CLASS #
##############
# The class in question.
class Coldstore:
def __init__(self, code):
self.code = code
self.columns = None
self.headlands = None
self.ticket_machine = Ticket_Machine()
self.outstanding_recommendations = []
# Load a map of this coldstore (when empty) from plain text.
def load_floorplan_from_plain_text(self, plain_text):
lines = plain_text.split("\n")
no_of_columns = len(lines[0].split(" "))
sheet_columns = []
for i in range(no_of_columns):
max_layers_list = []
for line in lines:
max_layers = line.split(" ")
max_layers_list.append(int(max_layers[i]))
max_layers_tuple = tuple(max_layers_list)
sheet_columns.append(max_layers_tuple)
result = []
i = 0
for item in sheet_columns:
letter = chr(ord('a')+i)
column = Column(letter, item)
result.append(column)
self.columns = result
# Load the headlands of this coldstore from two integers.
def load_headlands_from_arguments(self, no_of_spots, max_layers):
result = []
for i in range(1, no_of_spots+1):
numeral = to_roman(i)
spot = Spot(numeral, max_layers)
result.append(spot)
self.headlands = result
# Load a coldstore's floorplan from the database.
def load_floorplan_from_db(self):
data = data_storage.fetch_local_specifics()
if data == None:
raise Exception("No local specifics to load.")
else:
floorplan = data["floorplan"]
headlands_spots = data["headlands_spots"]
headlands_maxlayers = data["headlands_maxlayers"]
self.load_floorplan_from_plain_text(floorplan)
self.load_headlands_from_arguments(headlands_spots,
headlands_maxlayers)
# Ronseal.
def select_column_by_letter(self, letter):
for column in self.columns:
if column.letter == letter:
return column
raise Exception("No column with letter="+letter+".")
# Executes the delivery of a box to a given column, and logs the same.
def execute_drop(self, epc, column_letter, row_numeral):
box = Box(epc, None)
column = self.select_column_by_letter(column_letter)
spot = column.select_spot_by_row(row_numeral)
if spot.add_one(box):
data_storage.commit_drop(epc, column_letter, spot.row_id,
int(time.time()))
else:
raise Exception("It should be impossible to add a box at column="+
column_letter+", row="+row_numeral+".")
# Take action upon detecting a given EPC entering this coldstore.
def execute_entry(self, epc, timestamp):
data_storage.add_entry_log(epc, timestamp)
self.issue_recommendation(epc)
# Take action upon detecting a given EPC leaving this coldstore.
def execute_exit(self, epc, timestamp):
data_storage.add_exit_log(epc, timestamp)
result = self.remove_box_by_epc(epc)
return result
# Add a recommendation to the list, given that a specific EPC was detected
# entering this coldstore.
def issue_recommendation(self, epc):
ticket = self.ticket_machine.issue_ticket()
permitted_columns = data_storage.fetch_permitted_columns(epc)
for letter in permitted_columns:
column = self.select_column_by_letter(letter)
for spot in column.spots:
if spot.has_room():
column_letter = letter
row_numeral = spot.row_id
recommendation = Recommendation(ticket, epc, column_letter,
row_numeral)
self.outstanding_recommendations.append(recommendation)
return
column_letter = None
row_numeral = None
recommendation = Recommendation(ticket, epc, column_letter, row_numeral)
self.outstanding_recommendations.append(recommendation)
# Remove a box with a given EPC from this coldstore, if possible.
def remove_box_by_epc(self, epc):
for column in self.columns:
for spot in column.spots:
if spot.remove_one(epc):
return True
return False
# Select a recommendation by its ticket.
def select_recommendation_by_ticket(self, ticket):
for rec in self.outstanding_recommendations:
if rec.ticket == ticket:
return rec
return None
# Follow up on an outstanding recommendation.
def follow_recommendation(self, ticket):
rec = self.select_recommendation_by_ticket(ticket)
if rec == None:
raise Exception("No outstanding recommendation with ticket="+
str(ticket)+".")
elif rec.column_letter == None:
raise Exception("Cannot follow a void recommendation.")
else:
self.execute_drop(rec.epc, rec.column_letter, rec.row_numeral)
self.outstanding_recommendations.remove(rec)
self.ticket_machine.return_ticket(ticket)
# Cancel a given outstanding recommendation.
def cancel_recommendation(self, ticket):
rec = self.select_recommendation_by_ticket(ticket)
self.outstanding_recommendations.remove(rec)
self.ticket_machine.return_ticket(ticket)
# Cancel a given outstanding recommendation, and do something else with
# that box.
def override_recommendation(self, ticket, column_letter, row_numeral):
rec = self.select_recommendation_by_ticket(ticket)
epc = rec.epc
self.cancel_recommendation(ticket)
self.execute_drop(epc, column_letter, row_numeral)
self.ticket_machine.return_ticket(ticket)
# Ronseal.
def print_me(self):
printer = Coldstore_Printer(self)
printer.print_me()
</code></pre>
<h3>Helper Classes</h3>
<p>A chocolate box of small, mostly self-explanatory classes.</p>
<pre class="lang-py prettyprint-override"><code>################################
# HELPER CLASSES AND FUNCTIONS #
################################
# A class which models a single column of a coldstore.
class Column:
def __init__(self, letter, max_layers_tuple):
self.letter = letter
self.spots = self.make_spots(max_layers_tuple)
# Add the column's spots, from a tuple of their max_layers.
def make_spots(self, max_layers_tuple):
i = 1
result = []
for max_layers in max_layers_tuple:
numeral = to_roman(i)
spot = Spot(numeral, max_layers)
result.append(spot)
i = i+1
return result
# Ronseal.
def select_spot_by_row(self, row_id):
for spot in self.spots:
if spot.row_id == row_id:
return spot
raise Exception("No spot with row_id="+row_id+".")
# A class which issues and recycles tickets, used to keep track of any
# recommendations issued.
class Ticket_Machine:
def __init__(self):
self.tickets = set()
for i in range(max_tickets):
ticket = i+1
self.tickets.add(ticket)
# Ronseal.
def issue_ticket(self):
result = self.tickets.pop()
return result
# Ronseal.
def return_ticket(self, ticket):
self.tickets.add(ticket)
# A bare-bones class to hold the properties of a recommmendation.
class Recommendation:
def __init__(self, ticket, epc, column_letter, row_numeral):
self.ticket = ticket
self.epc = epc
self.column_letter = column_letter
self.row_numeral = row_numeral
# A class which permits the printing of a coldstore to the screen.
class Coldstore_Printer:
def __init__(self, coldstore):
self.coldstore = coldstore
self.rows = self.make_rows()
# Rearrange the coldstore's columns into rows, which can be printed more
# easily, and extract the useful data from each spot.
def make_rows(self):
result = []
for i in range(len(self.coldstore.columns[0].spots)):
row = []
for column in self.coldstore.columns:
printed_spot = Printed_Spot(column.spots[i])
row.append(printed_spot)
result.append(row)
return result
# Makes the top row of the printout.
def get_top_row(self):
result = " "
for i in range(len(self.rows[0])):
result = result+" "+chr(ord('a')+i)+" "
return result
# Makes the tween rows of the printout.
def get_tween_row(self):
result = "+"
for _ in range(len(self.rows[0])):
result = result+"-----+"
return result
# Ronseal.
def print_me(self):
result = []
top_row = self.get_top_row()
tween_row = self.get_tween_row()
i = 1
result.append(top_row)
result.append(tween_row)
for row in self.rows:
printout_for_row = "|"
for spot in row:
printout_for_row = printout_for_row+" "+spot.get_printout()+" |"
printout_for_row = printout_for_row+" "+to_roman(i)
result.append(printout_for_row)
result.append(tween_row)
i = i+1
for item in result:
print(item)
# A class which is a component of the Coldstore_Printer class.
class Printed_Spot:
LAYER_COLOURS = (None, layer_colours.RED, layer_colours.ORANGE,
layer_colours.YELLOW, layer_colours.GREEN,
layer_colours.BLUE, layer_colours.INDIGO,
layer_colours.VIOLET)
MAXED_OUT_LAYER_COLOUR = layer_colours.VIOLET
RESET = layer_colours.RESET
def __init__(self, spot):
self.layers = spot.layers()
if spot.max_layers == 0:
self.is_void = True
else:
self.is_void = False
if self.layers == 0:
self.is_empty = True
else:
self.is_empty = False
if (self.is_void or self.is_empty):
self.top_display_code = None
else:
self.top_display_code = spot.boxes[-1].display_code
# Ronseal.
def get_printout(self):
if self.is_void:
result = "XXX"
elif self.is_empty:
result = " "
else:
colour = Printed_Spot.LAYER_COLOURS[self.layers]
result = colour+self.top_display_code+Printed_Spot.RESET
return result
</code></pre>
<h3>Testing</h3>
<p>Finally, there's some unit-testing. It's mostly unambitious: I try to make sure that the classes do what they're supposed to do, and don't try too hard to break them.</p>
<pre class="lang-py prettyprint-override"><code>###########
# TESTING #
###########
# Test the Column class.
def test_column():
column = Column('a', (0, 2, 3))
assert(column.letter == 'a')
assert(column.spots[0].max_layers == 0)
assert(column.spots[0].row_id == "i")
assert(column.spots[1].max_layers == 2)
assert(column.spots[1].row_id == "ii")
assert(column.spots[2].max_layers == 3)
assert(column.spots[2].row_id == "iii")
assert(len(column.spots[2].boxes) == 0)
# Test the Coldstore class.
def test_coldstore():
test_floorplans()
# These tests depend on agreeable data in the DB.
test_drops()
test_entry_and_exit()
test_recommendations()
#test_printing()
# Test the loading of floorplans by various means.
def test_floorplans():
plain_text = ("1 2 3\n"+
"4 5 6\n"+
"7 8 9")
coldstore = Coldstore("cs0")
coldstore.load_floorplan_from_plain_text(plain_text)
assert(len(coldstore.columns) == 3)
column_a = coldstore.columns[0]
assert(column_a.letter == 'a')
assert(len(column_a.spots) == 3)
spot_i = column_a.spots[0]
assert(spot_i.row_id == "i")
assert(spot_i.max_layers == 1)
spot_iii = column_a.spots[2]
assert(spot_iii.row_id == "iii")
assert(spot_iii.max_layers == 7)
# The remaining tests depend on agreeable data in the DB.
coldstore.load_floorplan_from_db()
assert(len(coldstore.columns) == 3)
column_a = coldstore.columns[0]
assert(column_a.letter == 'a')
assert(len(column_a.spots) == 3)
spot_i = column_a.spots[0]
assert(spot_i.row_id == "i")
assert(spot_i.max_layers == 1)
spot_iii = column_a.spots[2]
assert(spot_iii.row_id == "iii")
assert(spot_iii.max_layers == 7)
assert(len(coldstore.headlands) == 3)
assert(coldstore.headlands[0].max_layers == 7)
assert(coldstore.headlands[2].max_layers == 7)
# Test dropping boxes. Depends on agreeable data in DB.
def test_drops():
coldstore = Coldstore("cs0")
coldstore.load_floorplan_from_db()
coldstore.execute_drop("epc0", 'a', "i")
# Now check database.
# Test the entry and exit routines. Depends on agreeable data in DB.
def test_entry_and_exit():
coldstore = Coldstore("cs0")
coldstore.load_floorplan_from_db()
coldstore.execute_entry("epc0", int(time.time()))
assert(coldstore.execute_exit("epc0", int(time.time())) == False)
rec = coldstore.outstanding_recommendations[0]
assert(rec.epc == "epc0")
assert(rec.column_letter == 'a')
assert(rec.row_numeral == "i")
# Test the recommendation system. Depends on agreeable data in DB.
def test_recommendations():
coldstore = Coldstore("cs0")
coldstore.load_floorplan_from_db()
coldstore.execute_entry("epc0", int(time.time()))
assert(len(coldstore.ticket_machine.tickets) == max_tickets-1)
coldstore.follow_recommendation(
coldstore.outstanding_recommendations[0].ticket)
assert(coldstore.execute_exit("epc0", int(time.time())) == True)
assert(len(coldstore.ticket_machine.tickets) == max_tickets)
coldstore.execute_entry("epc0", int(time.time()))
coldstore.cancel_recommendation(
coldstore.outstanding_recommendations[0].ticket)
assert(len(coldstore.outstanding_recommendations) == 0)
coldstore.execute_entry("epc0", int(time.time()))
coldstore.override_recommendation(
coldstore.outstanding_recommendations[0].ticket, 'a', "i")
assert(len(coldstore.outstanding_recommendations) == 0)
assert(coldstore.execute_exit("epc0", int(time.time())) == True)
# A sub-function for "test_printing()".
def introduce_epc(coldstore, epc):
if len(coldstore.outstanding_recommendations) != 0:
raise Exception("Pre-existing outstanding recommendations.")
coldstore.execute_entry(epc, int(time.time()))
coldstore.follow_recommendation(
coldstore.outstanding_recommendations[0].ticket)
# Test the facilities used to print coldstores to the screen.
def test_printing():
coldstore = Coldstore("cs0")
coldstore.load_floorplan_from_db()
introduce_epc(coldstore, "epc0")
introduce_epc(coldstore, "epc1")
introduce_epc(coldstore, "epc2")
introduce_epc(coldstore, "epc3")
introduce_epc(coldstore, "epc4")
introduce_epc(coldstore, "epc5")
coldstore.print_me()
# Run the unit tests.
def test():
test_column()
test_coldstore()
print("Tests passed!")
</code></pre>
<h3>Wrapping Up</h3>
<p>I always put this at the end of my .py files, so I thought I'd check I've been doing the right thing!</p>
<pre class="lang-py prettyprint-override"><code>###################
# RUN AND WRAP UP #
###################
def run():
test()
if __name__ == "__main__":
run()
</code></pre>
<h2>Other Stuff</h2>
<p>A "review copy" of the whole package is available at <a href="https://github.com/tomhosker/sibstructures4review" rel="nofollow noreferrer">https://github.com/tomhosker/sibstructures4review</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:41:29.703",
"Id": "462243",
"Score": "0",
"body": "Are all of these one file? Whether or not they are could you provide the file structure that you're using, and highlight which file each code block is in. Currently I'm confused on how to copy this package and start working on it. In addition do you use something like `python sibstructures`, `cd sibstructures; python main.py`, `python -m sibstructures` or `pytest` to run your tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T22:49:24.620",
"Id": "462279",
"Score": "0",
"body": "@Peilonrayz Yes, all the code quoted in this question is from one file. Indeed, if you were to put all the snippets above into one file, in the order in which they appear above, you would have the whole file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T22:58:14.320",
"Id": "462280",
"Score": "0",
"body": "@Peilonrayz I need to use the structures I created in `sibstructures` in multiple, disparate places in the repository I'm working on, and so I concluded that the best solution would be to make `sibstructures` into a custom package by copying it into `~/.local/lib/python3.6` - that path being specific to Linux. (If you know of a better solution, I'd very much like to learn about it.) I can then run this file - named `coldstore.py` - by navigating into the appropriate directory and running `python3 coldstore.py`, and that's it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T23:03:51.210",
"Id": "462281",
"Score": "0",
"body": "@Peilonrayz My employer has asked me to work on this project in a private repository. However, since you've flattered me by taking an interest, and since it can't do any harm to share just this utilities package, I'll put it on GitHub so you can look at it properly. That said, I'm just about to go to bed, and so I'll do it in the morning (9am UK time). Hope you can wait till then!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T09:17:00.040",
"Id": "462312",
"Score": "0",
"body": "@Peilonrayz Okay, I've made the GitHub repository: https://github.com/tomhosker/sibstructures4review."
}
] |
[
{
"body": "<h1>Project Structure</h1>\n\n<ul>\n<li><blockquote>\n <p>I need to use the structures I created in sibstructures in multiple, disparate places in the repository I'm working on, and so I concluded that the best solution would be to make sibstructures into a custom package by copying it into ~/.local/lib/python3.6 - that path being specific to Linux. (If you know of a better solution, I'd very much like to learn about it.)</p>\n</blockquote>\n\n<p>This is good, you've correctly setup a Python package so that it runs correctly. You however have manually deployed the package. Now there's the motto \"if it ain't broke, don't fix it\", and I feel that can come into play here. If you're happy with this as a solution, you do you.</p>\n\n<p>However if you may want to create <a href=\"https://packaging.python.org/tutorials/packaging-projects/\" rel=\"nofollow noreferrer\">a setuptools package</a> to be able to deploy your script easier.</p>\n\n<ul>\n<li><p><strong>Solo</strong>: If you're a solo developer, then you won't see too many benefits from utilizing setuptools packages in their intended way. It does however allow you to use the following commands to install your package.</p>\n\n<pre><code>$ python -m pip install /path/to/sibstructures\n</code></pre></li>\n<li><p><strong>Team</strong>: Given how basic Python's packaging hosting infrastructure is, you can <a href=\"https://packaging.python.org/guides/hosting-your-own-index/\" rel=\"nofollow noreferrer\">host your own private PyPI repository</a>. And with a small change to <a href=\"https://pip.pypa.io/en/stable/user_guide/#config-file\" rel=\"nofollow noreferrer\">your pip config</a> changing <code>index-url</code> to your host. Then you can install using pip easily.</p>\n\n<pre><code>$ python -m pip install sibstructures\n</code></pre></li>\n</ul>\n\n<p>So again, if you're happy with what you have, you do you. But you may find changing to how the Python eco-system works easier. After the initial setup.</p></li>\n<li><p>You're method of testing isn't really standard. There's nothing wrong with this, but using tools like pytest or <code>unittest</code> give nicer output, and allow greater separation of your project.</p>\n\n<p>Since all of your tests start with <code>test_</code> and you're using <code>assert</code> to test your code, migrating to <a href=\"https://docs.pytest.org/en/latest/\" rel=\"nofollow noreferrer\">pytest</a> would be a doddle.</p>\n\n<p>I have previously written two answers highlighting how to utilize pytest. <a href=\"https://codereview.stackexchange.com/a/234109\">The first is a very basic method</a>, where <a href=\"https://codereview.stackexchange.com/a/229644\">the second utilizes tox</a>. I would highly recommend reading both, and utilizing tox where possible.</p></li>\n</ul>\n\n<p>I'm not bashing on you rolling your own package management or testing. The way you've done it is pretty decent. However I know I benefit from the above tools, and so I'm sure they will help you too.</p>\n\n<h1>Code Review</h1>\n\n<ul>\n<li><p>I suggest installing a linter, like <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a> or <a href=\"https://prospector.readthedocs.io/en/master/\" rel=\"nofollow noreferrer\">Prospector</a>. Your code is almost very Pythonic, but there are some minor aspects that are preventing you from being there.</p>\n\n<p>You may like a hinter, like <a href=\"https://black.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">black</a>, to automatically change your code to be more compliant. However I would recommend installing a linter even if you have a hinter as a hinter can't fix everything.</p></li>\n<li>With Python it's an industry standard to indent to 4 spaces. In all my time here it has been very rare for me to not see 4 spaces being used.</li>\n<li><p>Your comments before the classes or functions would be better as <a href=\"https://en.wikipedia.org/wiki/Docstring#Python\" rel=\"nofollow noreferrer\">docstrings</a>. This is because tools like <a href=\"https://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">Sphinx</a> can read them and convert them into documentation.</p>\n\n<p>Most programs in the Python ecosystem use Sphinx. Most of the above links to the different packages are websites that Sphinx created.</p></li>\n<li><p>For <code>load_floorplan_from_plain_text</code>:</p>\n\n<ul>\n<li>The function is fairly cluttered. you don't need <code>max_layers_tuple</code> when you could just use <code>sheet_columns.append(tuple(max_layers))</code> which is one character longer. This is a hindrance to the readability of your code.</li>\n<li>I have a personal distaste for <code>var_list</code> and <code>var_tuple</code>. If you have to specify the type then you're doing something wrong.</li>\n<li>After <code>i = 0</code>, <code>i</code> never changes. This means all your <code>Column</code>s have the same letter.</li>\n<li>You can better describe the function as three comprehensions.</li>\n</ul>\n\n<p></p>\n\n<pre><code>def load_floorplan_from_plain_text(self, plain_text):\n \"\"\"Load a map of this coldstore (when empty) from plain text.\"\"\"\n lines = plain_text.split(\"\\n\")\n no_of_columns = len(lines[0].split(\" \"))\n sheet_columns = [\n [\n int(line.split(\" \")[i])\n for line in lines\n ]\n for i in range(no_of_columns)\n ]\n self.columns = [\n Column('a', item)\n for item in sheet_columns\n ]\n</code></pre>\n\n<ul>\n<li>If you split <code>plain_text</code> so that it is a 2d array by default then you can simplify the creation of the columns.</li>\n<li>You can also merge the comprehensions for <code>sheet_columns</code> and <code>self.columns</code> as the content is the same.</li>\n</ul></li>\n<li><p>Since the function names in <code>load_floorplan_from_db</code> are rather long I would just enter the arguments on the next lines, rather than having people read the text on the other side of the monitor.</p></li>\n<li>In <code>execute_drop</code> I would use a guard to error so the happy path is always the outermost level it can be.</li>\n<li><code>remove_box_by_epc</code> could be better described as a comprehension and <code>any</code>.</li>\n<li>Always use <code>is</code> when comparing to <code>None</code>.</li>\n<li>You can use <code>enumerate</code> to get the current index and the item.</li>\n<li><p>You can use f-strings or <code>str.format</code> to format strings. Rather than using <code>+</code> and <code>str</code> manually.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> foo = 'foo'\n>>> f'{foo} bar'\n'foo bar'\n>>> f'{} bar'.format(foo)\n'foo bar'\n</code></pre></li>\n<li><p>Your class <code>Coldstore_Printer</code> should be a static class where you only have one public method <code>print</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> Coldstore_Printer.print(coldstore)\n...\n</code></pre></li>\n<li><p>You should merge <code>Printed_Spot</code> into <code>Coldstore_Printer</code> as it can be defined in less than ten lines in a function.</p></li>\n<li>The <code>spots</code> value of the <code>Column</code> class can just be a dictionary. Since you only want to look up by the spot id.</li>\n<li>You could make a class or function to more easily build spots.</li>\n<li><p>You should only instantiate <code>Coldstore</code> with all the data it needs. Delayed initialization is janky and can lead to some really crippling errors. To ensure your function is correctly setup you can utilize <code>classmethods</code> to run before <code>__init__</code>. Now to create the class you use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>coldstore = Coldstore.from_db(code, data_storage.fetch_local_specifics())\n</code></pre></li>\n<li><p>I think your code has some more problems, as I don't think you're using datatypes or classes in the best way. But I can't check and I've changed enough of your code.</p></li>\n</ul>\n\n<p><sub><strong>Note</strong>: Not tested, and only provided as an example.</sub></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>### This code defines a class, which models a potato coldstore.\n\n# Imports.\nimport time\n\n# Custom imports.\nfrom sibstructures import sibconstants\nfrom sibstructures import data_storage\nfrom sibstructures import layer_colours\nfrom sibstructures.box import Box\nfrom sibstructures.spot import Spot\nfrom sibstructures.numerals import to_roman, to_arabic\n\n# Local constants.\nmax_tickets = 100\n\n\nclass Coldstore:\n def __init__(self, code, columns, headlands):\n self.code = code\n self.columns = {column.letter: column for column in columns}\n self.headlands = headlands\n self.ticket_machine = Ticket_Machine()\n self.outstanding = {}\n self.outstanding_recommendations\n\n @classmethod\n def _load_floorplan(cls, plain_text):\n \"\"\"Load a map of this coldstore (when empty) from plain text.\"\"\"\n data = [\n row.split(\" \")\n for row in plain_text.split(\"\\n\")\n ]\n return [\n Column(\n 'a',\n [int(row[i]) for row in data]\n )\n for i in range(len(data[0]))\n ]\n\n @classmethod\n def _load_headlands(cls, no_of_spots, max_layers):\n \"\"\"Load the headlands of this coldstore from two integers.\"\"\"\n return spots_from_layers([max_layers] * no_of_spots)\n\n @classmethod\n def from_db(cls, code, data):\n \"\"\"Load a coldstore's floorplan from the database.\"\"\"\n if data is None:\n raise Exception(\"No local specifics to load.\")\n\n return cls(\n code,\n columns=cls._load_floorplan(\n data[\"floorplan\"],\n ),\n headlands=cls.load_headlands_from_arguments(\n data[\"headlands_spots\"],\n data[\"headlands_maxlayers\"],\n ),\n )\n\n def execute_drop(self, epc, column_letter, row_numeral):\n \"\"\"Executes the delivery of a box to a given column, and logs the same.\"\"\"\n box = Box(epc, None)\n column = self.columns[column_letter]\n spot = column.spots[row_numeral]\n if not spot.add_one(box):\n raise Exception(\n f\"It should be impossible to add a box at \"\n f\"column={column_letter}\"\n f\", row={row_numeral}.\"\n )\n data_storage.commit_drop(\n epc,\n column_letter,\n spot.row_id,\n int(time.time()),\n )\n\n def execute_entry(self, epc, timestamp):\n \"\"\"Take action upon detecting a given EPC entering this coldstore.\"\"\"\n data_storage.add_entry_log(epc, timestamp)\n self.issue_recommendation(epc)\n\n def execute_exit(self, epc, timestamp):\n \"\"\"Take action upon detecting a given EPC leaving this coldstore.\"\"\"\n data_storage.add_exit_log(epc, timestamp)\n return self.remove_box_by_epc(epc)\n\n def issue_recommendation(self, epc):\n \"\"\"\n Add a recommendation to the list, given that a specific EPC was detected\n entering this coldstore.\n \"\"\"\n rec = self._issue_recommendation(epc)\n self.outstanding[rec.ticket] = rec\n\n def _issue_recommendation(self, epc):\n ticket = self.ticket_machine.issue_ticket()\n for letter in data_storage.fetch_permitted_columns(epc):\n column = self.columns[letter]\n for spot in column.spots.values():\n if spot.has_room():\n return Recommendation(\n ticket,\n epc,\n letter,\n spot.row_id,\n )\n return Recommendation(\n ticket,\n epc,\n None,\n None,\n )\n\n def remove_box_by_epc(self, epc):\n \"\"\"Remove a box with a given EPC from this coldstore, if possible.\"\"\"\n return any(\n spot.remove_one(epc)\n for column in self.columns.values()\n for spot in column.spots.values()\n )\n\n def follow_recommendation(self, ticket):\n \"\"\"Follow up on an outstanding recommendation.\"\"\"\n rec = self.outstanding[ticket]\n if rec.column_letter is None:\n raise Exception(\"Cannot follow a void recommendation.\")\n\n self.execute_drop(rec.epc, rec.column_letter, rec.row_numeral)\n self.cancel_recommendation(ticket)\n\n def cancel_recommendation(self, ticket):\n \"\"\"Cancel a given outstanding recommendation.\"\"\"\n self.outstanding.pop(ticket)\n self.ticket_machine.return_ticket(ticket)\n\n def override_recommendation(self, ticket, column_letter, row_numeral):\n \"\"\"\n Cancel a given outstanding recommendation, and do something else with\n that box.\n \"\"\"\n rec = self.outstanding[ticket]\n epc = rec.epc\n self.execute_drop(epc, column_letter, row_numeral)\n self.cancel_recommendation(ticket)\n self.ticket_machine.return_ticket(ticket)\n\n def print_me(self):\n \"\"\"Ronseal.\"\"\"\n Printer.print(self)\n\n\n################################\n# HELPER CLASSES AND FUNCTIONS #\n################################\n\n\ndef spots_from_layers(layers):\n spots = (\n Spot(to_roman(i), layer)\n for i, layer in enumerate(layers, 1)\n )\n return {\n spot.row_id: spot\n for spot in spots\n }\n\n\nclass Column:\n \"\"\"A class which models a single column of a coldstore.\"\"\"\n def __init__(self, letter, layers):\n self.letter = letter\n self.spots = spots_from_layers(layers)\n\n\nclass Ticket_Machine:\n \"\"\"\n A class which issues and recycles tickets, used to keep track of any\n recommendations issued.\n \"\"\"\n def __init__(self):\n self.tickets = set(range(1, max_tickets+1))\n\n def issue_ticket(self):\n \"\"\"Ronseal.\"\"\"\n return self.tickets.pop()\n\n def return_ticket(self, ticket):\n \"\"\"Ronseal.\"\"\"\n self.tickets.add(ticket)\n\n\nclass Recommendation:\n \"\"\"A bare-bones class to hold the properties of a recommmendation.\"\"\"\n def __init__(self, ticket, epc, column_letter, row_numeral):\n self.ticket = ticket\n self.epc = epc\n self.column_letter = column_letter\n self.row_numeral = row_numeral\n\n\nclass Printer:\n \"\"\"Static class to print a ColdStore.\"\"\"\n LAYER_COLOURS = (\n None,\n layer_colours.RED,\n layer_colours.ORANGE,\n layer_colours.YELLOW,\n layer_colours.GREEN,\n layer_colours.BLUE,\n layer_colours.INDIGO,\n layer_colours.VIOLET,\n )\n MAXED_OUT_LAYER_COLOUR = layer_colours.VIOLET\n RESET = layer_colours.RESET\n\n @classmethod\n def print(cls, coldstore):\n print(\"\\n\".join(cls._print(coldstore)))\n\n @classmethod\n def _print(cls, coldstore):\n rows = self._make_rows(coldstore)\n yield self._get_top_row()\n TWEEN_ROW = self._get_tween_row()\n yield TWEEN_ROW\n for i, row in enumerate(rows):\n yield (\n \"|\"\n + \"\".join(\n f\" {cls._print_spot(spot)} |\"\n for spot in row\n )\n + \" \"\n + to_roman(i)\n )\n yield TWEEN_ROW\n\n @classmethod\n def _make_rows(cls, coldstore):\n \"\"\"\n Rearrange the coldstore's columns into rows, which can be printed more\n easily, and extract the useful data from each spot.\n \"\"\"\n return [\n [\n column.spots[i]\n for column in coldstore.columns\n ]\n for i in range(len(coldstore.columns[0].spots))\n ]\n\n @classmethod\n def _get_top_row(self, rows):\n \"\"\"Makes the top row of the printout.\"\"\"\n return ''.join(\n f\" {chr(ord('a')+i)} \"\n for i in range(len(rows[0]))\n )\n\n @classmethod\n def _get_tween_row(self, rows):\n \"\"\"Makes the tween rows of the printout.\"\"\"\n return \"+\" + ''.join(\n \"-----+\"\n for _ in range(len(rows[0]))\n )\n\n @classmethod\n def _print_spot(self, spot):\n if spot.max_layers == 0:\n return \"XXX\"\n if spot.layers == 0:\n return \" \"\n return (\n cls.LAYER_COLOURS[spot.layers]\n + spot.boxes[-1].display_code\n + cls.RESET\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:24:40.340",
"Id": "236059",
"ParentId": "236032",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236059",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T17:24:27.750",
"Id": "236032",
"Score": "6",
"Tags": [
"python",
"object-oriented",
"file-structure"
],
"Title": "Centrepiece Class from a Warehouse Management Package"
}
|
236032
|
<p>In effort to learn OCaml, I'm going through some easy LeetCode problems and attempting to implement them. I arrive at the correct answer, but I'm still developing an intuition for canonical OCaml code. I'd appreciate any feedback on my implementation.</p>
<p>As mentioned, this is <a href="https://leetcode.com/problems/two-sum/" rel="nofollow noreferrer">problem 1 on LeetCode</a>. A quick summary of the problem: given an array of integers, return the indices of the 2 numbers that sum to a given "target".</p>
<p>For example, given <code>nums: [2, 7, 11, 15]</code> and <code>target: 13</code>, the result should be <code>[0, 2]</code> (the integers at indices <code>0</code> and <code>2</code> sum to <code>13</code>).</p>
<p>Furthermore, we can assume a unique solution exists for the given array and target.</p>
<p>Here is my refined attempt at implementing this in OCaml:</p>
<pre class="lang-ml prettyprint-override"><code>let two_sum nums target =
let rec aux i j =
let n1 = List.nth nums i in
let n2 = List.nth nums j in
if n1 + n2 = target then [i; j]
else if j = (List.length nums) - 1 then aux (i + 1) (i + 2)
else aux i (j + 1)
in aux 0 1;;
</code></pre>
<p>I appreciate any feedback.</p>
|
[] |
[
{
"body": "<p>Since the task is about using arrays, I would suggest to use OCaml arrays and not list. Because of lists, you need to use <code>List.nth</code> and that is quite costly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:04:22.667",
"Id": "241085",
"ParentId": "236037",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T18:54:54.297",
"Id": "236037",
"Score": "2",
"Tags": [
"ocaml"
],
"Title": "Sum of two elements of a list equaling a target"
}
|
236037
|
<p><strong>EDIT</strong>: Refer <a href="https://codereview.stackexchange.com/a/236058/212940">this answer</a> for improved solution with incorporated feedback and extended functionality. eg Automatically <code>hexdump</code> both parts of a stack/heap obj like <code>std::string</code>. </p>
<hr>
<h2>Inspiration / Motivation</h2>
<p>Modern C++, certainly compared to C, provides a lot of abstractions which protects us from / hide from us the details of memory allocation and layout. Mostly "we don't care about the detail", or shouldn't. But sometimes we do for these reasons:</p>
<ul>
<li>New to C++: Should understand differences between stack & heap and have some simple appreciation about memory layout. Polymorphism? </li>
<li>Debug and inspect your application, especially if you're doing something a bit unusual. Getting a clear picture of "what is happening in memory" can be helpful. Yes the debugger can provide that, but the commands can be obscure and it's hard to get an overview. Also, I can compile the code below without <code>-g</code> and with <code>-O3</code> and it will not give me "optimized out" messages in the debugger. This is because the compiler "is aware of" the need to inspect the memory. (On the flip side we are changing what we are measuring here). </li>
<li>Advanced optimisations like <code>struct</code> packing, or CPU cache line optimisations. </li>
</ul>
<p>Before I go on: credit to <a href="https://codereview.stackexchange.com/q/165120/212940">this question</a> and particularly <a href="https://codereview.stackexchange.com/a/165162/212940">this answer</a>. They provided the idea and first cut of my code came from that answer. </p>
<h2><code>hd(adr, size)</code>: Show me the memory, quick!</h2>
<p>Rather than battle a debugger, which is yet another abstraction, the idea is just to dump/inspect with:</p>
<pre><code>std::cout << hd(&var, sizeof(var));
</code></pre>
<p>Sneak preview of the simple output (more interesting examples below):</p>
<pre><code>0x405000: -- -- -- -- 31 32 33 34 35 36 37 38 39 30 00 -- | ....1234567890.
</code></pre>
<ul>
<li>We get the address (is it stack/heap/.text ?)</li>
<li>The output is aligned to nearest 16 byte boundary => cache line? Padding between members or objects? (Most cache lines are 64 bytes, but that's too wide in terminal. Change one constant or make it a param is possibility). </li>
<li>Hex and (printable) ASCII. Nothing new here. </li>
</ul>
<p>The first 2 features are new over the related question / answer linked to above. In my opinion they broaden the use case significantly. <strong>Refer comments in <code>main()</code></strong>.</p>
<h2>The Code</h2>
<p><strong>Alert</strong>: Some of the code may hurt your eyes. I have tried to keep it C++'ish and tried (and failed) not to use too many <code>reinterpret_casts</code>. I have tried to avoid (too much) UB, and hopefully succeeded. But probably not. In the end, realistically, it's <code>C</code> really...?</p>
<p><strong>Some features</strong></p>
<ul>
<li><code>struct ostream_state</code> should be self explanatory and could be more generally useful. Tried to keep this generic => templated. </li>
<li>main function <code>hex_dump()</code> is a bit long, but has just 3 three (linked) stages. I decided not to split. </li>
<li>Using the "evil" <code>void*</code> was a choice suggested by previous answer and I decided to stick with it for this application. </li>
<li>Lots of pointer arithmetic and hence lots of <code>// NOLINT</code> to shut up <code>clang-tidy</code>. I have looked behind each of those, and I think they are all OK.</li>
<li><strong>Refer comments in main for demo of what I found interesting and useful in the output</strong></li>
<li>Caveat: Output will obviously differ per machine (incl the SBO limit). </li>
</ul>
<p><strong>Feedback wanted</strong>: </p>
<ul>
<li>I find this useful, but is it? </li>
<li>Usual trawl for bugs / UB (oh oh!) / cleaner techniques or structure</li>
</ul>
<p></p>
<pre><code>#include <bits/stdint-intn.h>
#include <iomanip>
#include <iostream>
#include <memory>
// utility: keeps states of an ostream, restores on destruction
template <typename T>
struct ostream_state {
explicit ostream_state(std::basic_ostream<T>& stream)
: stream_{stream}, flags_{stream.flags()}, fill_{stream.fill()}, width_{stream.width()} {}
ostream_state(const ostream_state& other) = delete;
ostream_state& operator=(const ostream_state& other) = delete;
ostream_state(ostream_state&& other) = delete;
ostream_state& operator=(ostream_state&& other) = delete;
~ostream_state() {
stream_.flags(flags_);
stream_.fill(fill_);
stream_.width(width_);
}
private:
std::basic_ostream<T>& stream_;
std::ios_base::fmtflags flags_;
typename std::basic_ostream<T>::char_type fill_;
std::streamsize width_;
};
inline std::ostream& print_ptr(std::ostream& os, const void* ptr) {
auto state = ostream_state(os);
return os << std::setw(19) << std::setfill(' ') << ptr; // NOLINT
}
inline std::ostream& print_byte(std::ostream& os, const unsigned char* ptr) {
auto state = ostream_state(os);
return os << std::setw(2) << std::setfill('0') << std::hex << static_cast<unsigned>(*ptr) << ' ';
}
inline std::ostream& hex_dump(std::ostream& os, const void* buffer, std::size_t bufsize) {
if (buffer == nullptr || bufsize == 0) return os;
constexpr std::size_t maxline{16};
// buffer for printable characters
unsigned char pbuf[maxline + 1]; // NOLINT
unsigned char* pbuf_curr{pbuf}; // NOLINT
const unsigned char* buf{reinterpret_cast<const unsigned char*>(buffer)}; // NOLINT
// pre-buffer area: floor(nearest maxline)
size_t offset = reinterpret_cast<size_t>(buffer) % maxline; // NOLINT
std::size_t linecount = maxline;
if (offset > 0) {
const void* prebuf = buf - offset; // NOLINT
print_ptr(os, prebuf) << ": ";
while (offset--) { // underflow OK NOLINT
os << "-- ";
*pbuf_curr++ = '.'; // NOLINT
--linecount;
}
}
// main buffer area
while (bufsize) { // NOLINT
if (pbuf_curr == pbuf) print_ptr(os, buf) << ": "; // NOLINT
print_byte(os, buf);
*pbuf_curr++ = std::isprint(*buf) ? *buf : '.'; // NOLINT
if (--linecount == 0) {
*pbuf_curr++ = '\0'; // NOLINT
os << " | " << pbuf << '\n'; // NOLINT
pbuf_curr = pbuf; // NOLINT
linecount = std::min(maxline, bufsize);
}
--bufsize;
++buf; // NOLINT
}
// post buffer area: finish incomplete line
if (pbuf_curr != pbuf) { // NOLINT
for (*pbuf_curr++ = '\0'; pbuf_curr != &pbuf[maxline + 1]; ++pbuf_curr) os << "-- "; // NOLINT
os << " | " << pbuf << '\n'; // NOLINT
}
return os;
}
struct hd {
const void* buffer;
std::size_t bufsize;
hd(const void* buf, std::size_t bufsz) : buffer{buf}, bufsize{bufsz} {}
friend std::ostream& operator<<(std::ostream& out, const hd& hd) {
return hex_dump(out, hd.buffer, hd.bufsize);
}
};
// start of demo/test
struct Dummy {
int16_t a = 0x1111; // forgive the ridiculous values, for easy spotting
int32_t b = 0x22222222;
int32_t c = 0x33333333;
void* ptr = (void*)0x8888888888888888; // crazy!
};
int main() {
// Note on UB:
// It's UB to access `+ 1`th byte of a sv or a str, but we know '\0'
// is there in all these cases. Tthe point of using the hd() utility is to
// examine these sorts of things during debugging so acceptably risky here?
auto sv1 = std::string_view{"1234567890"}; // in .text (ie code) segment => non-aligned
std::cout << hd(sv1.data(), sv1.size() + 1) << '\n';
auto sv2 = std::string_view{"Hello there this is a much longer string"};
std::cout << hd(sv2.data(), sv2.size() + 1) << '\n'; // starts on next byte after sv1
auto str1 = std::string{"123456789012345"}; // SBO on stack => non-aligned
std::cout << hd(str1.data(), str1.size() + 1) << '\n';
auto str2 = std::string{"1234567890123456"}; // too big for SBO => on heap => 16Byte aligned
std::cout << hd(str2.data(), str2.size() + 1) << '\n';
auto d1 = Dummy{}; // on stack with alignment gaps
std::cout << hd(&d1, sizeof(d1)) << '\n';
auto d2 = std::make_unique<Dummy>(); // on heap with alignment gaps
std::cout << hd(d2.get(), sizeof(*d2)) << '\n';
auto d3 = std::make_unique<Dummy[]>(4); // array on heap: odd/even alignment NOLINT
std::cout << hd(d3.get(), 4 * sizeof(d3[0])) << '\n';
</code></pre>
<p>Output:</p>
<pre><code> 0x405000: -- -- -- -- 31 32 33 34 35 36 37 38 39 30 00 -- | ....1234567890.
0x405000: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 48 | ...............H
0x405010: 65 6c 6c 6f 20 74 68 65 72 65 20 74 68 69 73 20 | ello there this
0x405020: 69 73 20 61 20 6d 75 63 68 20 6c 6f 6e 67 65 72 | is a much longer
0x405030: 20 73 74 72 69 6e 67 00 -- -- -- -- -- -- -- -- | string.
0x7ffe99b799f0: -- -- -- -- -- -- -- -- 31 32 33 34 35 36 37 38 | ........12345678
0x7ffe99b79a00: 39 30 31 32 33 34 35 00 -- -- -- -- -- -- -- -- | 9012345.
0x131bec0: 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 | 1234567890123456
0x131bed0: 00 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | .
0x7ffe99b79950: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....""""3333....
0x7ffe99b79960: 88 88 88 88 88 88 88 88 -- -- -- -- -- -- -- -- | ........
0x131bee0: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....""""3333....
0x131bef0: 88 88 88 88 88 88 88 88 -- -- -- -- -- -- -- -- | ........
0x131bf00: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....""""3333....
0x131bf10: 88 88 88 88 88 88 88 88 11 11 00 00 22 22 22 22 | ............""""
0x131bf20: 33 33 33 33 00 00 00 00 88 88 88 88 88 88 88 88 | 3333............
0x131bf30: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....""""3333....
0x131bf40: 88 88 88 88 88 88 88 88 11 11 00 00 22 22 22 22 | ............""""
0x131bf50: 33 33 33 33 00 00 00 00 88 88 88 88 88 88 88 88 | 3333............
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:12:43.777",
"Id": "462249",
"Score": "1",
"body": "Very related: https://codereview.stackexchange.com/questions/165120/printing-hex-dumps-for-diagnostics"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:14:16.163",
"Id": "462250",
"Score": "1",
"body": "Yes, exactly, I linked to it at top and hopefully gave appropriate credit. This is a further development of the idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:14:50.690",
"Id": "462252",
"Score": "0",
"body": "Just noticed after seeing what you linked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:09:11.567",
"Id": "462263",
"Score": "1",
"body": "Please stop editing your question. You have an answer now, and your edits may invalidate it. If any invalidation happens we will side with the answerer as posting a question prematurely is considered poor form. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:12:43.410",
"Id": "462264",
"Score": "0",
"body": "@Peilonrayz\nI have been over this with someone else already. As soon as I received the answer I acknowledged it by upvoting it and have stopped making any changes. I cannot see when someone \"starts to write a question\". So if your timeline shows that \"I edited question\" after answer received then I would ask you to consider that there such a thing as concurrent access ;-). And to be honest G.Sliepen, myself and a couple of others just play ping-pong around here. The rest is tumbleweed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:14:52.690",
"Id": "462265",
"Score": "0",
"body": "@Peilonrayz BTW I noticed you silently deleted our previous exchange. Nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:16:55.203",
"Id": "462266",
"Score": "1",
"body": "@OliverSchonrock I didn't delete any of your comments. I don't understand why you seem to accuse me of random things. But honestly I don't care. Bye."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:20:57.080",
"Id": "462268",
"Score": "0",
"body": "@Peilonrayz\nNot Random. They are gone for me. Please stop interfering . Thank you. Good bye."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T09:45:15.803",
"Id": "462315",
"Score": "0",
"body": "@Oliver, please don't make unfounded accusations. You have no idea who deleted comments (and if the comments were no longer needed, then deleting was the Right Thing; comments are ephemeral, and anything of long-term value needs to be in the question or in an answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:31:19.723",
"Id": "462319",
"Score": "0",
"body": "@TobySpeight Fair enough: Not proven You're right, could have been someone else. (although I would stand by my suspicion not being unfounded, there was a bit of history to that exchange). But it's over now and I don't mind at all. I do stand by my general point that this community is over-policed given the level of activity. All chiefs and no Indians -- all police and no protestors. You know what I mean. It just comes across as unwelcoming IMHO."
}
] |
[
{
"body": "<h1>Usefulness</h1>\n\n<p>Looks useful, although you could achieve something similar with a debugger, which in the end is much more powerful. See <a href=\"https://stackoverflow.com/questions/9233095/memory-dump-formatted-like-xxd-from-gdb\">this post</a> about making GDB give similar output.</p>\n\n<h1>Make a C++20 version</h1>\n\n<p>Because the code would be much cleaner if you could use <code>std::format()</code>. You can make it backwards compatible by detecting if C++20 support is present, otherwise falling back to <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">fmtlib</a>.</p>\n\n<h1>Consider making <code>hd()</code> take a reference</h1>\n\n<p>I think it would be much cleaner if <code>hd()</code> took a reference, and have the size default to the size of the type:</p>\n\n<pre><code>template<typename T>\nhd(const T &buf, std::size_t bufsz = sizeof(T)): buffer{...}, bufsize{...} {}\n</code></pre>\n\n<p>And then you could use it like:</p>\n\n<pre><code>auto d1 = Dummy{};\nstd::cout << hd(d1) << '\\n';\n</code></pre>\n\n<p>Of course, it gets a bit harder to use if you want to dump arbitrary memory, but it's a trade-off. I think it would benefit beginners, who may not know the size of types, or might easily make mistakes like writing <code>hd(some_pointer, sizeof(some_pointer))</code>. Maybe have two distinct classes, or have a version that takes only a reference and no size, and one that takes a void pointer and a size.</p>\n\n<h1>Avoid <code>void *</code> where possible</h1>\n\n<p>I think it's best if you cast to <code>unsigned char *</code> as soon as possible (in <code>hd</code>'s constructor), and stick with it. This avoids some casts in other parts of your code. The only time you want to cast it again is when printing the value of a pointer in <code>print_ptr()</code>.</p>\n\n<p>Even better, use <code>std::byte *</code>, and only convert a <code>std::byte</code> to <code>char</code> when needing to print it as a character directly.</p>\n\n<h1>Organizing the code</h1>\n\n<p>The function <code>hex_dump()</code> is a bit messy. It would be nicer if it was split into more functions, delegating more work to <code>print_*()</code> functions. In particular, have <code>print_bytes()</code> take a length so it prints a range of bytes in one go. Add a <code>print_ascii()</code> that prints a range of bytes as printable ASCII characters.</p>\n\n<p>You could move the handling of the pre- and post-buffer area to the <code>print_*()</code> functions, avoiding the special-casing in <code>hex_dump()</code> itself. For example:</p>\n\n<pre><code>constexpr std::size_t linesize{16};\nauto buf{buffer};\nsize_t pre = reinterpret_cast<size_t>(buffer) % maxline; // Size of pre-buffer area\nbuf -= pre; // Align buf and bufsize to start of pre-buffer area\nbufsize += pre;\n\nwhile (bufsize) {\n // Calculate the length of the post-buffer area on this line\n size_t post = bufsize < linesize ? linesize - bufsize : 0;\n\n // Print the line\n print_ptr(os, buf);\n os << \": \";\n print_bytes(os, buf, linesize, pre, post);\n os << \" | \";\n print_ascii(os, buf, linesize, pre, post);\n os << \"\\n\";\n\n buf += linesize;\n bufsize -= linesize - post; // Advance to next line, avoiding wrapping\n pre = 0; // No pre-buffer area after first line\n}\n</code></pre>\n\n<h1>About printing pointers</h1>\n\n<p>I can think of use cases where you'd want to see the pointers as decimal values, possibly even just offsets from the start of the data instead of absolute values. Perhaps this could be made configurable?</p>\n\n<h1>Make <code>bufsize_</code> <code>const</code></h1>\n\n<p>Just as <code>buffer_</code> is <code>const</code>, you can make <code>bufsize_</code> <code>const</code> as well.</p>\n\n<h1>Implications of using a class instead of a function</h1>\n\n<p>Using a class that has an <code>operator<<()</code> overload is a way to get relatively optimized output to an <code>std::ostream</code>, but there are some consequences. First, the class holds references to the data that is to be printed, and there is no guarantee that the data will be valid at the time you actually print it. For example, I could write:</p>\n\n<pre><code>hd bad_hd() {\n int i = 0xbad;\n return hd(&i, sizeof i);\n}\n...\nstd::cout << bad_hd(); // UB\n</code></pre>\n\n<p>This is a similar to how <code>std::span</code> behaves. While in the above it is rather obvious you are taking a reference of a local variable, it is harder to see if you have an overload that takes a reference of an arbitrary type. If you would use a function instead (basically <code>hex_dump()</code>, possibly with overloads), you would not have this issue.</p>\n\n<p>The second issue, which is very minor but might surprise someone, is that you can't use <code>hd()</code> to print an instance of itself using the reference template overload:</p>\n\n<pre><code>int foo = 0xf00;\nauto foo_hd = hd(foo);\nstd::cout << foo_hd; // OK\nstd::cout << hd(foo_hd); // Prints a copy of the above\nstd::cout << hd(&foo_hd, sizeof foo_hd); // Works\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:18:41.410",
"Id": "462267",
"Score": "0",
"body": "Great stuff as usual. 2 things. 1. I struggled to get anything much to work with std::byte (due to amount of weird recasting here). I will try again. and 2. That's a good link to gdb post. I suspected some \"scripting\" could do that. TBH I find gdb (and any debugger even the IDE ones) to be a pain. It takes me so long to get set up the way I want it, and I need to so rarely that in 99.9% of cases it's faster to \"print and think\". What do you find?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:42:32.930",
"Id": "462270",
"Score": "0",
"body": "It depends. Sure, it's easy to just add a print-statement here and there (and I do this too often myself), but then you need to recompile and rerun your program, and maybe you forgot to add a print-statement or made another mistake, and then you have to repeat the process, and in the end it would've been faster if you'd used the debugger from the beginning. It's definitely worth it to learn how to use one. Don't try too hard to get it to set it up the way you want it, learn how it works out of the box first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:52:09.487",
"Id": "462271",
"Score": "0",
"body": "Yeah. I do that. I am not too bad at gdb. I just find too many commands are required. Breakpoints, steps into out of, watches \"examines\" etc ...Oh now I need to recompile with `-O0` because the variable has been optimised out. By that stage I have solved it by thinking carefully about targeted prints and recompiling once. Mind you my compile times tend to be measured in seconds, not minutes. It's horses for course really. I find 99% I am in the print world."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:55:08.623",
"Id": "462273",
"Score": "0",
"body": "I really liked your \"use a reference\" idea so the type gets pushed through and we can template detect it. Tried to make it work. hmmmm.. sort of ...it never really detects the correct size. Like for none of the examples I gave. It gets the size of stack object. It would work for primitive types i think (bit boring), but that's about all. Am I doing something differently to what you had in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T22:14:25.300",
"Id": "462276",
"Score": "1",
"body": "About the \"correct\" size: it depends on what you want. If I have some POD class I want to dump exactly that, and then `sizeof(T)` is what you want. But if you want it to print the dynamically allocated parts of a container, then you'd have to specify the size and right pointer manually. Or... you could add some SFINAE overloads to make it detect if `T::data()` and `T::size()` exist and then use those?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T22:29:46.293",
"Id": "462278",
"Score": "0",
"body": "OK, yes. I will see if \"guestimating\" can work in a sufficient number of cases. Or is the very fact that you are looking at memory layout really asking that you understand which memory and how much of it, is sort of a prerequisite? ... Will think. Trying to refactor `hex_dump()` as suggest now. Second pair of eyes always useful. Thank you. ... You got me concerned about debuggers, but it appears I am not alone: https://lemire.me/blog/2016/06/21/i-do-not-use-a-debugger/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T00:05:10.210",
"Id": "462284",
"Score": "1",
"body": "refactor went well. thanks. On \"reference\": I am going down a double route. Keep the 2 param (ptr and size) approach as \"power tool\" and have a templated reference single param overload for which we have complete template specialisations for common non-trivial types, eg: `template <typename T>\n explicit hd(const T& buf) : buffer{&buf}, bufsize{sizeof(T)} {}`\n\n`template <>\n explicit hd(const std::string_view& buf) : buffer{buf.data()}, bufsize{buf.size() + 1} {}`\nThe unspecialiased version handles `int` etc. I am considering doing 2 dumps for std::string: stack part / heap part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:07:25.497",
"Id": "462327",
"Score": "0",
"body": "refactored version below incorporating your input and extending the concept of references for multi-part objects. Any feedback on the chaining of `hd` objects using `unique_ptr` appreciated. Wasn't 100% sure this is the best way, but could find a better one; `std::optional<std::reference_wrapper>` ??"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T21:04:00.710",
"Id": "236042",
"ParentId": "236039",
"Score": "6"
}
},
{
"body": "<p>A refactored improved version taking on board many of the points from <a href=\"https://codereview.stackexchange.com/a/236042/212940\">@G.Sliepen's answer</a> and then building on them:</p>\n\n<ul>\n<li>No more <code>void*</code> except for the general form <code>ctor</code> of <code>hd</code></li>\n<li>Main function <code>hex_dump()</code> totally refactored. Better. </li>\n<li><code>hd</code> ctor now has 2 overloads. </li>\n</ul>\n\n<p>There is a general form of hd ctor with <code>(adr, size)</code> and then a templated form which takes a reference. The general for of that template calls <code>sizeof()</code> and uses <code>&var</code> for the address. </p>\n\n<p>But there are also specialisations for <code>std::string_view</code> and <code>std::string</code> which:</p>\n\n<ol>\n<li>do the same as the general form (gives the stack part of the obj)</li>\n<li>Then chain a new instance of hd for the heap part of the object</li>\n</ol>\n\n<p>I am still validating this design. It seems to work fine. Feedback welcome. When bedded down, I should be able to extend it to say <code>std::vector</code>: Printing the stack and heaps parts of the container. It might even be able to recurse down multiple layers. </p>\n\n<p>New code and output below. </p>\n\n<p><strong>Small surprise</strong>: libstd++ uses 32bytes of stack for a heap allocated string? A <code>.data()</code> ptr a <code>size()</code> and another size which turns out to be the <code>.capacity()</code>. The remaining 8 bytes are alignment junk? Anyway we adjusted code to show the whole <code>capacity</code> of buffer which has been <code>reserved()</code>. Not just the current <code>size()</code>.</p>\n\n<pre><code>#include <bits/stdint-intn.h>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n\n// utility: keeps states of an ostream, restores on destruction\ntemplate <typename T>\nstruct ostream_state {\n explicit ostream_state(std::basic_ostream<T>& stream)\n : stream_{stream}, flags_{stream.flags()}, fill_{stream.fill()} {}\n\n ostream_state(const ostream_state& other) = delete;\n ostream_state& operator=(const ostream_state& other) = delete;\n\n ostream_state(ostream_state&& other) = delete;\n ostream_state& operator=(ostream_state&& other) = delete;\n\n ~ostream_state() {\n stream_.flags(flags_);\n stream_.fill(fill_);\n }\n\nprivate:\n std::basic_ostream<T>& stream_;\n std::ios_base::fmtflags flags_;\n typename std::basic_ostream<T>::char_type fill_;\n};\n\nnamespace detail {\ninline void print_adr(std::ostream& os, const std::byte* adr) {\n os << std::setw(19) << std::setfill(' ') << adr; // NOLINT\n}\n\ninline void print_fill_advance(std::ostream& os, const std::byte*& buf, std::size_t cnt,\n const std::string& str) {\n while (cnt-- != 0U) {\n ++buf; // NOTE: unusually this in passsed in by ref and we advance it. NOLINT\n os << str;\n }\n}\n\ninline void print_hex(std::ostream& os, const std::byte* buf, std::size_t linesize, std::size_t pre,\n std::size_t post) {\n print_fill_advance(os, buf, pre, \"-- \");\n {\n os << std::setfill('0') << std::hex;\n auto cnt = linesize - pre - post;\n while (cnt-- != 0U) os << std::setw(2) << static_cast<unsigned>(*buf++) << ' '; // NOLINT\n }\n print_fill_advance(os, buf, post, \"-- \");\n}\n\ninline void print_ascii(std::ostream& os, const std::byte* buf, std::size_t linesize,\n std::size_t pre, std::size_t post) {\n print_fill_advance(os, buf, pre, \".\");\n auto cnt = linesize - pre - post;\n while (cnt-- != 0U) {\n os << (std::isprint(static_cast<unsigned char>(*buf)) != 0 ? static_cast<char>(*buf) : '.');\n ++buf; // NOLINT\n }\n print_fill_advance(os, buf, post, \".\");\n}\n} // namespace detail\n\ninline std::ostream& hex_dump(std::ostream& os, const std::byte* buffer, std::size_t bufsize) {\n if (buffer == nullptr || bufsize == 0) return os;\n\n constexpr std::size_t linesize{16};\n const std::byte* buf{buffer};\n std::size_t pre =\n reinterpret_cast<std::size_t>(buffer) % linesize; // Size of pre-buffer area NOLINT\n bufsize += pre;\n buf -= pre; // NOLINT\n\n auto state = ostream_state{os}; // save stream setting and restore at end of scope\n while (bufsize != 0U) {\n std::size_t post = bufsize < linesize ? linesize - bufsize : 0;\n\n detail::print_adr(os, buf);\n os << \": \";\n detail::print_hex(os, buf, linesize, pre, post);\n os << \" | \";\n detail::print_ascii(os, buf, linesize, pre, post);\n os << \"\\n\";\n\n buf += linesize; // NOLINT\n bufsize -= linesize - post;\n pre = 0;\n }\n return os;\n}\n\nclass hd {\npublic:\n hd(const void* buf, std::size_t bufsz)\n : buffer_{reinterpret_cast<const std::byte*>(buf)}, bufsize_{bufsz} {}\n\n template <typename T>\n explicit hd(const T& buf)\n : buffer_{reinterpret_cast<const std::byte*>(&buf)}, bufsize_{sizeof(T)} {}\n\n // It's UB to access `+ 1`th byte of a string_view so we don't, despite most\n // targets of string_views (ie std::string or string literal) having '\\0'.\n template <>\n explicit hd(const std::string_view& buf)\n : buffer_{reinterpret_cast<const std::byte*>(&buf)}, bufsize_{sizeof(buf)} {\n child_ = std::make_unique<hd>(buf.data(), buf.size());\n child_label_ = \"string viewed\";\n }\n\n // There is some debate but we believe str[size()] is legal via [] or *\n // but UB via iterator. So here we DO show the '`0' terminator.\n template <>\n explicit hd(const std::string& buf)\n : buffer_{reinterpret_cast<const std::byte*>(&buf)}, bufsize_{sizeof(buf)} {\n auto data_byte_ptr = reinterpret_cast<const std::byte*>(buf.data());\n if (!(data_byte_ptr > buffer_ && data_byte_ptr < buffer_ + bufsize_)) {\n // not SBO, show the real string as well\n child_ = std::make_unique<hd>(buf.data(), buf.size() + 1);\n child_label_ = \"heap string\";\n }\n }\n\n friend std::ostream& operator<<(std::ostream& os, const hd& hd) {\n hex_dump(os, hd.buffer_, hd.bufsize_); // NOLINT\n if (hd.child_) os << std::setw(19) << hd.child_label_ << \":\\n\" << *(hd.child_);\n return os;\n }\n\nprivate:\n const std::byte* buffer_;\n std::size_t bufsize_;\n\n std::unique_ptr<hd> child_ = nullptr;\n std::string child_label_;\n};\n\n// start of demo/test\n\nstruct Dummy {\n int16_t a = 0x1111;\n int32_t b = 0x22222222;\n int32_t c = 0x33333333;\n void* end = (void*)0xffffffffffffffff; // NOLINT end of earth\n};\n\nint main() {\n auto i1 = int{0x12345678}; // 4 bytes int, 4-byte aligned\n std::cout << os::hd(i1) << '\\n';\n\n auto pi = 22/7.0; // 8bytes on stack\n std::cout << os::hd(pi) << '\\n';\n\n auto sv1 = std::string_view{\"1234567890\"}; // in .text (ie code) segment => non-aligned\n std::cout << os::hd(sv1) << '\\n';\n\n auto sv2 = std::string_view{\"This is a much longer string view onto a string literal\"};\n std::cout << os::hd(sv2) << '\\n'; // starts after sv1 with '\\0' gap\n\n auto i2 = short{0x1234}; // 2 bytes int, 4-byte aligned\n std::cout << os::hd(i2) << '\\n';\n\n auto str1 = std::string{\"123456789012345\"}; // SBO on stack => 16-byte aligned??\n std::cout << os::hd(str1) << '\\n';\n\n auto str2 = std::string{\"1234567890123456\"}; // too big for SBO => on heap => 16Byte aligned\n std::cout << os::hd(str2) << '\\n';\n\n auto d1 = Dummy{}; // on stack 8-byte aligned with padding gaps\n std::cout << os::hd(d1) << '\\n';\n\n auto d2 = std::make_unique<Dummy>(); // on heap 16byte aligned with padding gaps\n std::cout << os::hd(d2.get(), sizeof(*d2)) << '\\n';\n\n auto d3 = std::make_unique<Dummy[]>(4); // array on heap 8-byte aligned: odd/even NOLINT\n std::cout << os::hd(d3.get(), 4 * sizeof(d3[0])) << '\\n';\n}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code> 0x7ffcb8d3d350: -- -- -- -- 78 56 34 12 -- -- -- -- -- -- -- -- | ....xV4.........\n\n 0x7ffcb8d3d370: -- -- -- -- -- -- -- -- 49 92 24 49 92 24 09 40 | ........I.$I.$.@\n\n 0x7ffcb8d3d3a0: -- -- -- -- -- -- -- -- 0a 00 00 00 00 00 00 00 | ................\n 0x7ffcb8d3d3b0: 42 66 42 00 00 00 00 00 -- -- -- -- -- -- -- -- | BfB.............\n string viewed:\n 0x426640: -- -- 31 32 33 34 35 36 37 38 39 30 -- -- -- -- | ..1234567890....\n\n 0x7ffcb8d3d390: -- -- -- -- -- -- -- -- 37 00 00 00 00 00 00 00 | ........7.......\n 0x7ffcb8d3d3a0: 4d 66 42 00 00 00 00 00 -- -- -- -- -- -- -- -- | MfB.............\n string viewed:\n 0x426640: -- -- -- -- -- -- -- -- -- -- -- -- -- 54 68 69 | .............Thi\n 0x426650: 73 20 69 73 20 61 20 6d 75 63 68 20 6c 6f 6e 67 | s is a much long\n 0x426660: 65 72 20 73 74 72 69 6e 67 20 76 69 65 77 20 6f | er string view o\n 0x426670: 6e 74 6f 20 61 20 73 74 72 69 6e 67 20 6c 69 74 | nto a string lit\n 0x426680: 65 72 61 6c -- -- -- -- -- -- -- -- -- -- -- -- | eral............\n\n 0x7ffcb8d3d320: -- -- -- -- -- -- -- -- -- -- -- -- -- -- 34 12 | ..............4.\n\n 0x7ffcb8d3d330: 40 d3 d3 b8 fc 7f 00 00 0f 00 00 00 00 00 00 00 | @...............\n 0x7ffcb8d3d340: 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 00 | 123456789012345.\n\n 0x7ffcb8d3d350: -- -- -- -- -- -- -- -- 90 f8 e1 01 00 00 00 00 | ................\n 0x7ffcb8d3d360: 10 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 | ................\n 0x7ffcb8d3d370: 08 e0 04 eb 00 7f 00 00 -- -- -- -- -- -- -- -- | ................\n heap string:\n 0x1e1f890: 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 | 1234567890123456\n 0x1e1f8a0: 00 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ................\n\n 0x7ffcb8d3d380: 11 11 42 00 22 22 22 22 33 33 33 33 00 00 00 00 | ..B.\"\"\"\"3333....\n 0x7ffcb8d3d390: ff ff ff ff ff ff ff ff -- -- -- -- -- -- -- -- | ................\n\n 0x1e1f910: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....\"\"\"\"3333....\n 0x1e1f920: ff ff ff ff ff ff ff ff -- -- -- -- -- -- -- -- | ................\n\n 0x1e11eb0: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....\"\"\"\"3333....\n 0x1e11ec0: ff ff ff ff ff ff ff ff 11 11 00 00 22 22 22 22 | ............\"\"\"\"\n 0x1e11ed0: 33 33 33 33 00 00 00 00 ff ff ff ff ff ff ff ff | 3333............\n 0x1e11ee0: 11 11 00 00 22 22 22 22 33 33 33 33 00 00 00 00 | ....\"\"\"\"3333....\n 0x1e11ef0: ff ff ff ff ff ff ff ff 11 11 00 00 22 22 22 22 | ............\"\"\"\"\n 0x1e11f00: 33 33 33 33 00 00 00 00 ff ff ff ff ff ff ff ff | 3333............\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:04:31.550",
"Id": "462440",
"Score": "0",
"body": "Nice refactoring! I noticed you can `static_cast<>()` a `void *` to a `std::byte *` instead of using a `reinterpret_cast<>()`. Also, in the loop in `print_ascii()`, you could write `auto c = std::to_integer<char>(*buf++); os << (std::isprint(c) ? c : '.')` (you need to `#include <cstddef>`). Using `std::unique_ptr<hd> child_` is interesting, but why not just have two `buffer` and `bufsize` variables, and call `hex_dump()` twice in `operator<<()`? This avoids memory allocations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:42:25.353",
"Id": "462447",
"Score": "0",
"body": "@G.Sliepen\nThanks. Good call on static_cast (only for the general ctor though). And good call on std::to_integer. Wasn't aware of that. But is it correct? Not UB? I thought `isprint` needs `unsigned char` to be non-UB?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:42:41.750",
"Id": "462448",
"Score": "0",
"body": "@G.Sliepen On chaining: I agree the allocation is slightly irritating. I might go three levels though or even recursive so that the idea of a straight \"clone\" of the object \"and recurse\" (sort of, not quite yet) appealed to me. The only other solution I thought of was to give hd() a default ctor. Then \"empty - value initalialised\" could mean \"no child\" (with nullptr / zero), and then you popluate it if you need it...? That way we always get an extra (often uneeded) hd obj, but that's cheap? --- I have done a std::vector version too. These are quite trivial to add."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T23:16:52.927",
"Id": "462452",
"Score": "0",
"body": "@G.Sliepen Since you are the casting expert, do you have ideas on my `char*` struggles? https://codereview.stackexchange.com/questions/236073/c-wrapper-for-graphviz-library/236079 See comments under first answer for more details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T19:49:27.420",
"Id": "462550",
"Score": "0",
"body": "You're right apparently about `std::isprint()` needing an `unsigned char`, although in practice I've never seen any code casting a `char` to `unsigned char` before using any of the `ctype.h` functions. But better safe than sorry. You can't have a `hd` object directly embedded in `hd` itself, it always has to be a pointer, so then using `std::unique_ptr` is the right thing to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T19:54:39.040",
"Id": "462551",
"Score": "0",
"body": "Yeah the `unsigned char` thing is annoying. Especially since I don't even remotely understand why? You're right of course about `hd` having an `hd` member or even a `std::optional<hd>`. It can't work....incomplete object stuff. forgot :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T21:18:06.513",
"Id": "462556",
"Score": "0",
"body": "It's not only that it's incomplete, it's also because it would recurse infinitely!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T21:24:35.553",
"Id": "462558",
"Score": "0",
"body": "@G.Sliepen not the way I had it laid out in my head...but anyway it's a mute point. can't put \"self members\", the language just doesn't support without boost::container (or whatever that thing is called). The recursion stop challenge exists with the pointer too. I will cross that bridge when I get a real world example of 3+ layer object dumping."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:04:22.073",
"Id": "236058",
"ParentId": "236039",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236042",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:07:24.120",
"Id": "236039",
"Score": "8",
"Tags": [
"c++",
"memory-optimization"
],
"Title": "hexdump(): A memory layout utility to help debugging / understanding / optimising of C++ memory model"
}
|
236039
|
<p>I have a code to scrap data from webpage using selenium and python.
The code selects a URL the database and search it using selenium chrome driver and fetches the result and insert into a postgreSQL database.</p>
<p>Can anyone can review this code and let me know what I need to modify to make it better and organized.</p>
<p>The below code searches a URL in google , say example "<a href="https://www.google.com/search?&q=samung+galaxy+note+10" rel="nofollow noreferrer">https://www.google.com/search?&q=samung+galaxy+note+10</a>" , so there will be results shown in the google suggestions bar(adbar) from that fetching the <strong>Product Name, Company Name, Position, URL of product and Price</strong>.</p>
<p>Getting this in 5 lists and merge those results using ZIP function and the final result will be a TUPLE named "final_results", The contents of which need to be inserted to Database.</p>
<p>Note: the code is working fine now, But it is not Optimized and i would like to get recommendations on how to optimize this.
Also after certain searches google block the search displaying to select "Whether not a Robot" question and there after the script fails.Any other way to recover from that?</p>
<pre><code>from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import psycopg2
import os
import glob
import datetime
final_results=[]
positions=[]
option = webdriver.ChromeOptions()
option.add_argument("—-incognito")
browser = webdriver.Chrome(executable_path='/users/user_123/downloads/chrome_driver/chromedriver', chrome_options=option)
#def db_connect():
try:
#Database connection string
DSN = "dbname='postgres' user='postgres' host='localhost' password='postgres' port='5432'"
#DWH table to which data is ported
TABLE_NAME = 'staging.search_url'
#Connecting DB..
conn = psycopg2.connect(DSN)
print("Database connected...")
#conn.set_client_encoding('utf-8')
cur = conn.cursor()
cur.execute("SET datestyle='German'")
except (Exception, psycopg2.Error) as error:
print('database connection failed')
quit()
def get_products(url):
browser.get(url)
names = browser.find_elements_by_xpath("//span[@class='pymv4e']")
# simplified the filtering
# note that python objects have a "truth" value,
# and that empty strings and empty lists have a False value
#product = [x.text for x in names if x.text.strip()]
upd_product_name_list=list(filter(None, names))
product_name = [x.text for x in upd_product_name_list]
product = [x for x in product_name if len(x.strip()) > 2]
upd_product_name_list.clear()
product_name.clear()
return product
#print(product)
##################################
search_url_fetch="""select url_to_be_searched from staging.search_url where id in(65,66,67,68)"""
psql_cursor = conn.cursor()
psql_cursor.execute(search_url_fetch)
serach_url_list = psql_cursor.fetchall()
print('Fetched DB values')
##################################
for row in serach_url_list:
passed_url=''
passed_url=str(row)
passed_url=passed_url.replace(',)','')
passed_url=passed_url.replace('(','')
new_url=''
new_url=passed_url[1:len(passed_url)-1]
print('Passed URL :'+new_url)
print("\n")
filtered=[]
filtered.clear()
filtered = get_products(new_url)
if not filtered:
new_url=new_url+'+kaufen'
get_products(new_url)
print('Modified URL :'+new_url)
if filtered:
print(filtered)
positions.clear()
for x in range(1, len(filtered)+1):
positions.append(str(x))
gobal_position=0
gobal_position=len(positions)
print('global postion first: '+str(gobal_position))
print("\n")
company_name_list = browser.find_elements_by_xpath("//div[@class='LbUacb']")
# use list comprehension to get the actual repo titles and not the selenium objects.
company = []
company.clear()
company = [x.text for x in company_name_list]
# print out all the titles.
print('Company Name:')
print(company, '\n')
price_list = browser.find_elements_by_xpath("//div[@class='e10twf T4OwTb']")
# use list comprehension to get the actual repo titles and not the selenium objects.
price = []
price.clear()
price = [x.text for x in price_list]
print('Price:')
print(price)
print("\n")
urls=[]
urls.clear()
find_href = browser.find_elements_by_xpath("//a[@class='plantl pla-unit-single-clickable-target clickable-card']")
for my_href in find_href:
url_list=my_href.get_attribute("href")
urls.append(url_list)
#print(my_href.get_attribute("href"))
print('URLS:')
print(urls)
print("\n")
print('Final Result: ')
result = zip(positions,filtered, urls, company,price)
final_results.clear()
final_results.append(tuple(result))
print(final_results)
print("\n")
print('global postion end :'+str(gobal_position))
i=0
#try:
for d in final_results:
print( d[i])
while i <= gobal_position:
cur.execute("""INSERT into staging.pla_crawler_results(position, product_name, url,company,price) VALUES (%s, %s, %s,%s, %s)""", d[i])
print('Inserted succesfully')
conn.commit()
i=i+1
#except (Exception, psycopg2.Error) as error:
#pass
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:51:34.283",
"Id": "236040",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"selenium",
"google-chrome"
],
"Title": "Web scraping code using selenium and Python"
}
|
236040
|
<p>I am attempting to learn Python. It was suggested to me to try a web scraper, so I thought to get myself to look at multiple Nagios instances. I have not programmed in Python before, but learned from other code reviews to adapt my standards to PEP8. The online checker says the code passes.</p>
<pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup
import requests
from requests.auth import HTTPDigestAuth
from requests.auth import HTTPBasicAuth
import urllib.request
import time
allNagiosInfo = [
('http://example.com/nagios', 'user', 'password', 'Basic'),
('https://network2.example.com/nagios', 'user', 'password', 'Digest'),
('https://anothernetwork.example.com/nagios', 'user', 'password', 'Basic')]
for nagiosEntry in allNagiosInfo:
nagiosBaseURL = nagiosEntry[0]
nagiosUsername = nagiosEntry[1]
nagiosPassword = nagiosEntry[2]
nagiosAuthType = nagiosEntry[3]
# print("Current values: {}\t{}\t{}\t{}".format(
# nagiosBaseURL, nagiosUsername, nagiosPassword, nagiosAuthType))
if nagiosAuthType == "Basic":
response = requests.get(nagiosBaseURL + "/cgi-bin/status.cgi?host=all",
auth=HTTPBasicAuth(nagiosUsername,
nagiosPassword))
if nagiosAuthType == "Digest":
response = requests.get(nagiosBaseURL + "/cgi-bin/status.cgi?host=all",
auth=HTTPDigestAuth(nagiosUsername,
nagiosPassword))
html = BeautifulSoup(response.text, "html.parser")
for i, items in enumerate(html.select('td')):
if i == 3:
hostsAll = items.text.split('\n')
hostsUp = hostsAll[12]
hostsDown = hostsAll[13]
hostsUnreachable = hostsAll[14]
hostsPending = hostsAll[15]
hostsProblems = hostsAll[24]
hostsTypes = hostsAll[25]
if i == 12:
serviceAll = items.text.split('\n')
serviceOK = serviceAll[13]
serviceWarning = serviceAll[14]
serviceUnknown = serviceAll[15]
serviceCritical = serviceAll[16]
serviceProblems = serviceAll[26]
serviceTypes = serviceAll[27]
# print(i, items.text) ## To get the index and text
print("Nagios Server at {}@{}:".format(nagiosUsername, nagiosBaseURL))
print(" Hosts")
print("\tUp - {}".format(hostsUp))
print("\tDown - {}".format(hostsDown))
print("\tUnreachable - {}".format(hostsUnreachable))
print("\tPending - {}".format(hostsPending))
print("\tProblems - {}".format(hostsProblems))
print("\tTypes - {}".format(hostsTypes))
print(" Services")
print("\tOK - {}".format(serviceOK))
print("\tWarning - {}".format(serviceWarning))
print("\tUnknown - {}".format(serviceUnknown))
print("\tCritical - {}".format(serviceCritical))
print("\tProblems - {}".format(serviceProblems))
print("\tTypes - {}".format(serviceTypes))
# print("Request returned:\n\n{}".format(html.text))
# To get the full request
</code></pre>
<p>Currently, it outputs my three instances properly:</p>
<pre><code>Nagios Server at user@http://example.com/nagios:
Hosts
Up - 24
Down - 0
Unreachable - 0
Pending - 0
Problems - 0
Types - 24
Services
OK - 142
Warning - 0
Unknown - 0
Critical - 0
Problems - 0
Types - 142
Nagios Server at user@https://network2.example.com/nagios:
Hosts
Up - 3
Down - 0
Unreachable - 0
Pending - 0
Problems - 0
Types - 3
Services
OK - 28
Warning - 0
Unknown - 0
Critical - 0
Problems - 0
Types - 28
Nagios Server at user@https://anothernetwork.example.com/nagios:
Hosts
Up - 56
Down - 0
Unreachable - 0
Pending - 0
Problems - 0
Types - 56
Services
OK - 130
Warning - 0
Unknown - 0
Critical - 0
Problems - 0
Types - 130
</code></pre>
<p>I understand I do not have error checking (i.e. is the username/password correct? Auth Type correct? Server URL right?), so that will be my next thing to learn. I also understand I should not have variables (especially with passwords) hard-coded into the code, but I do not know what is the "proper" way of dealing with secure variables.</p>
|
[] |
[
{
"body": "<p>First of all, as per <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> I'd recommend you follow the best practices.</p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#id34\" rel=\"nofollow noreferrer\"><h2>Naming conventions</h2></a></p>\n\n<ul>\n<li><code>allNagiosInfo</code> -> this is most likely a constant, so: <code>ALL_NAGIOS_INFO</code></li>\n<li><code>nagiosEntry</code>, <code>nagiosBaseURL</code>, <code>nagiosUsername</code>, <code>nagiosPassword</code>, <code>nagiosAuthType</code> -> <code>nagios_entry</code>, <code>nagios_base_url</code>, <code>nagios_username</code>, <code>nagios_password</code>, <code>nagios_auth_type</code>.</li>\n</ul>\n\n<p>And so on with the naming, you got the idea. </p>\n\n<p><strong>Summary:</strong> </p>\n\n<blockquote>\n <p>Variable names should be lowercase, with words separated by\n underscores as necessary to improve readability.</p>\n</blockquote>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#id23\" rel=\"nofollow noreferrer\"><h2>Imports</h2></a></p>\n\n<blockquote>\n <p>Imports should be grouped in the following order:</p>\n \n <ul>\n <li>Standard library imports.</li>\n <li>Related third party imports.</li>\n <li>Local application/library specific imports.</li>\n <li>You should put a blank line between each group of imports.</li>\n </ul>\n</blockquote>\n\n<p>Also, don't import modules that you're not using (e.g: <code>time</code>, <code>urllib</code>).\nSo, that means you could rewrite your imports as follows:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import requests\nfrom requests.auth import HTTPBasicAuth, HTTPDigestAuth\nfrom bs4 import BeautifulSoup\n</code></pre>\n\n<hr>\n\n<p>This:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>nagios_base_url = nagios_entry[0]\nnagios_username = nagios_entry[1]\nnagios_password = nagios_entry[2]\nnagios_auth_type = nagios_entry[3]\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<p><code>nagios_base_url, nagios_username, nagios_password, nagios_auth_type = nagios_entry</code></p>\n\n<p>Since all the requests that you're doing are suffixed with the same url, I'd just define that before the <code>if</code>s:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># ...\nfor nagios_entry in ALL_NAGIOS_INFO:\n nagios_base_url, nagios_username, nagios_password, nagios_auth_type = nagios_entry\n full_url = \"{}/cgi-bin/status.cgi?host=all\".format(nagios_base_url)\n\n if nagios_auth_type == \"Basic\":\n response = requests.get(full_url, auth=HTTPBasicAuth(nagios_username, nagios_password))\n\n if nagios_auth_type == \"Digest\":\n response = requests.get(full_url, auth=HTTPDigestAuth(nagios_username, nagios_password))\n</code></pre>\n\n<p>You have way too many prints which can be rewritten as a single print:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"\"\"Nagios Server at {}@{}: \n\nHosts:\n\n Up - {}\n Down - {}\n Unreachable - {}\n Pending - {}\n Problems - {}\n Types - {}\n\nServices:\n\n OK - {}\n Warning - {}\n Unknown - {}\n Critical - {}\n Problems - {}\n Types - {}\n\"\"\".format(\n nagios_username, nagios_base_url, hosts_up, hosts_down, hosts_unreachable, hosts_pending,\n hosts_problems, hosts_types, service_ok, service_warning, service_unknown, service_critical,\n service_problems, service_types\n )\n)\n</code></pre>\n\n<p>You can also look at <a href=\"https://docs.python.org/2/library/textwrap.html#textwrap.dedent\" rel=\"nofollow noreferrer\"><code>textwrap.dedent</code></a> if you want to play around with the <code>\\t</code>s.</p>\n\n<hr>\n\n<h2>Security</h2>\n\n<p>As you said, it's not recommended to keep your passwords in the code. There's no perfect solution for this, but we can enumerate some of the most used ones:</p>\n\n<ul>\n<li>config files which have to be added to <code>.gitignore</code> so they get excluded from the repo</li>\n<li>environment variables (mostly used on Unix based distros)</li>\n<li>some powerful hashing technique to generate a master password (master password -> secure key-> encrypt data by the key)</li>\n</ul>\n\n<hr>\n\n<h2>Scraping</h2>\n\n<p>When scraping things, you can usualy go a specific element by using an <code>xpath</code> or a <code>selector</code>. I usually use the <code>lxml</code> module when I have to quickly put together something because it allows me to use xpaths (though bs might as well offer that - didn't actually play with that for a while now)</p>\n\n<p><strong>Example for lxml usage</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from lxml import html\nimport requests\n\nres = requests.get(some_url)\ntree = html.fromstring(res.content)\ntds = tree.xpath('//table//td[@class=\"plaintext\"]/text()[normalize-space()]')\n</code></pre>\n\n<hr>\n\n<p>Now, your code is not very portable and if you plan on adding more servers, you'll find yourself having a hard time integrating those as well. The first thing that I'd do is to find the proper data structure for my data. In your scenario, a dictionary looks like the best choice out there:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>NAGIOS_DATA = {\n 'http://example.com/nagios/cgi-bin/status.cgi?host=all': {\n 'user': 'user',\n 'password': 'password',\n 'auth_type': 'Basic'\n },\n 'https://network2.example.com/nagios/cgi-bin/status.cgi?host=all': {\n 'user': 'user',\n 'password': 'password',\n 'auth_type': 'Digest'\n },\n 'https://anothernetwork.example.com/nagios/cgi-bin/status.cgi?host=all': {\n 'user': 'user',\n 'password': 'password',\n 'auth_type': 'Basic'\n },\n}\n</code></pre>\n\n<p><em>INFO: don't forget that the <code>password</code> can be defined in a config file and imported here</em></p>\n\n<p>Now, that's debatable if it's the best structure that you can use because I don't know the entire logic of your app, but it'll do for now.</p>\n\n<p>Using the above, we can now do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import requests\nfrom requests.auth import HTTPBasicAuth, HTTPDigestAuth\nfrom bs4 import BeautifulSoup\n\n\nNAGIOS_DATA = {\n 'http://example.com/nagios/cgi-bin/status.cgi?host=all': {\n 'user': 'user',\n 'password': 'password',\n 'auth_type': 'Basic'\n },\n 'https://network2.example.com/nagios/cgi-bin/status.cgi?host=all': {\n 'user': 'user',\n 'password': 'password',\n 'auth_type': 'Digest'\n },\n 'https://anothernetwork.example.com/nagios/cgi-bin/status.cgi?host=all': {\n 'user': 'user',\n 'password': 'password',\n 'auth_type': 'Basic'\n },\n}\n\n\ndef get_url_response(url, user, password, auth_type):\n \"\"\"Get the response from a URL.\n\n Args:\n url (str): Nagios url\n user (str): Nagios username\n password (str): Nagios password\n auth_type (str): Nagios auth_type\n\n Returns: Response object\n \"\"\"\n\n if auth_type == \"Basic\":\n return requests.get(url, auth=HTTPBasicAuth(user, password)) \n return requests.get(url, auth=HTTPDigestAuth(user, password))\n\n\ndef main():\n \"\"\"\n Main entry to the program.\n \"\"\"\n\n for url, auth_data in NAGIOS_DATA.items():\n user, password, auth_type = auth_data[\"user\"], auth_data[\"password\"], auth_data[\"auth_type\"]\n response = get_url_response(url, user, password, auth_type)\n\n if response.status_code == 200:\n html = BeautifulSoup(response.text, \"html.parser\")\n # ... and so on\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I haven't finished the whole review because I want you to go ahead and do the rest. Some things that I've added to the program:</p>\n\n<ul>\n<li>functions: writing functions will let you reuse the functionality they contain at a later point + it's easier to test the code inside them. <em>Homework: could you think of a way of splitting them even further?</em></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>: having docstrings within a function will tell others (and most important, the future-you) what that function does.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:46:17.337",
"Id": "462335",
"Score": "2",
"body": "Note, many put spaces between the different import groups, due to `isort` - the industry standard import hinter. Also the big print would be nicer as an f-string or with explicit format names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T21:14:01.133",
"Id": "462430",
"Score": "0",
"body": "Thanks for the detailed review! I have it working with a couple new functions now, naming convention used, and the dictionary for variables. One question though, if I find out how to import settings from a config file, would the `NAGIOS_DATA` still be a constant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T13:58:01.237",
"Id": "462511",
"Score": "0",
"body": "@CanadianLuke Yep."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T18:44:05.970",
"Id": "462541",
"Score": "0",
"body": "Awesome, got a config file going now! Thanks! Should I post a new question for further review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T18:54:41.800",
"Id": "462542",
"Score": "0",
"body": "@CanadianLuke Yep"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T20:02:40.883",
"Id": "462553",
"Score": "0",
"body": "New question [here](https://codereview.stackexchange.com/q/236127/37991)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T08:04:01.843",
"Id": "236050",
"ParentId": "236045",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T22:56:38.273",
"Id": "236045",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"web-scraping"
],
"Title": "Beginner web scraper for Nagios"
}
|
236045
|
<p>I am learning to clean my code and make it more efficient, however I'm having trouble with my code, because most of the post about the subject are specified to a given code. The code below looks like a lot, but it's the same step for different sheets (the code below is for two sheets, there are five more sheets).</p>
<pre><code>Sub Formule_Code()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Compliance
Worksheets("WIP extract").Activate
Range("A1").Select
LastRow = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Range("A" & LastRow).Select
Range(ActiveCell, ActiveCell.End(xlDown).End(xlToRight)).Copy
Worksheets("Compliance").Activate
LastRowC = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Range("A" & LastRowC).Select
ActiveCell.PasteSpecial xlPasteAll
'Kolom G
LastRowSumG_C = Cells(Rows.Count, 7).End(xlUp).Offset(-1, 0).Row
LastRowFormG_C = Cells(Rows.Count, 7).End(xlUp).Row
Range("G" & LastRowFormG_C).Formula = "=SUM(G42:G" & LastRowSumG_C & ")"
Range("E8").Formula = "=SUM(G42:G" & LastRowSumG_C & ")"
'Kolom I
LastRowSumI_C = Cells(Rows.Count, 9).End(xlUp).Offset(-1, 0).Row
LastRowFormI_C = Cells(Rows.Count, 9).End(xlUp).Row
Range("I" & LastRowFormI_C).Formula = "=SUM(I42:I" & LastRowSumI_C & ")"
Range("F8").Formula = "=SUM(I42:I" & LastRowSumI_C & ")"
'Kolom K
LastRowSumK_C = Cells(Rows.Count, 11).End(xlUp).End(xlUp).Offset(-1, 0).Row
LastRowFormK_C = Cells(Rows.Count, 11).End(xlUp).End(xlUp).Row
Range("K" & LastRowFormK_C).Formula = "=SUM(K42:K" & LastRowSumK_C & ")"
Range("G8").Formula = "=SUM(K42:K" & LastRowSumK_C & ")"
'Kolom L
LastRowSumL_C = Cells(Rows.Count, 12).End(xlUp).End(xlUp).End(xlUp).Offset(-1, 0).Row
LastRowFormL_C = Cells(Rows.Count, 12).End(xlUp).End(xlUp).End(xlUp).Row
Range("L" & LastRowFormL_C).Formula = "=SUM(L42:L" & LastRowSumL_C & ")"
Range("H8").Formula = "=SUM(L42:L" & LastRowSumL_C & ")"
Range(Cells(Rows.Count, "L").End(xlUp).Offset(1), Cells(Rows.Count, "L")).EntireRow.Clear
Range("F11").Formula = "=SUM(H8 +- F12)"
Range("G11").Formula = "=SUM(H8 +- G12)"
LastRowStaff = Cells(Rows.Count, 4).End(xlUp).Offset().Row
LastRowExpense = Cells(Rows.Count, 12).End(xlUp).Offset(-5, 0).Row
Range("F12").Formula = "=SUMIF(D42:D" & LastRowStaff & ",""*Accrual*"", L42:L" & LastRowExpense & ")"
Range("G12").Formula = "=SUMIF(D42:D" & LastRowStaff & ",""*Accrual*"", L42:L" & LastRowExpense & ")"
Range("P42") = "Check"
Range("Q42") = "ID"
Range("P43").FormulaArray = "=IFERROR(INDEX(Lijst!$A$2:$A$247,MATCH(1,--(SEARCH(TRANSPOSE(Lijst!$A$2:$A$247),O43)>0),0),0),""Z"")"
Range("P43").Select
Selection.AutoFill Destination:=Range("P43:P1000")
Range("Q43").Formula = "=IF(P43<>P44,1,0)"
Range("Q43").Select
Selection.AutoFill Destination:=Range("Q43:Q1000")
Rows("42:42").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Compliance").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Compliance").AutoFilter.Sort.SortFields.Add2 Key:= _
Range("P42"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Compliance").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("P:Q").Select
Range("P25").Activate
Selection.EntireColumn.Hidden = True
Dim rngc As Range, rc As Long
Set rngc = Range("Q8:Q3276")
For rc = rngc.Count To 1 Step -1
If rngc(rc).Value = 1 Then
rngc(rc + 1).EntireRow.Insert
rngc(rc + 1).EntireRow.Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.599993896298105
.PatternTintAndShade = 0
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Range("A35").Select
End If
Next rc
Columns("R:R").Select
Range("R31").Activate
Range(Selection, Selection.End(xlToRight)).Select
Selection.Clear
Range("O31").Select
Application.Goto Reference:=Range("a1"), Scroll:=True
'-----------------------------
'Advies
Worksheets("WIP extract").Activate
Range("A" & LastRow).Select
Range(ActiveCell, ActiveCell.End(xlDown).End(xlToRight)).Copy
Worksheets("Advies").Activate
LastRowA = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Range("A" & LastRowA).Select
ActiveCell.PasteSpecial xlPasteAll
'Kolom G
LastRowSumG_A = Cells(Rows.Count, 7).End(xlUp).Offset(-1, 0).Row
LastRowFormG_A = Cells(Rows.Count, 7).End(xlUp).Row
Range("G" & LastRowFormG_A).Formula = "=SUM(G42:G" & LastRowSumG_A & ")"
Range("E8").Formula = "=SUM(G42:G" & LastRowSumG_A & ")"
'Kolom I
LastRowSumI_A = Cells(Rows.Count, 9).End(xlUp).Offset(-1, 0).Row
LastRowFormI_A = Cells(Rows.Count, 9).End(xlUp).Row
Range("I" & LastRowFormI_A).Formula = "=SUM(I42:I" & LastRowSumI_A & ")"
Range("F8").Formula = "=SUM(I42:I" & LastRowSumI_A & ")"
'Kolom K
LastRowSumK_A = Cells(Rows.Count, 11).End(xlUp).End(xlUp).Offset(-1, 0).Row
LastRowFormK_A = Cells(Rows.Count, 11).End(xlUp).End(xlUp).Row
Range("K" & LastRowFormK_A).Formula = "=SUM(K42:K" & LastRowSumK_A & ")"
Range("G8").Formula = "=SUM(K42:K" & LastRowSumK_A & ")"
'Kolom L
LastRowSumL_A = Cells(Rows.Count, 12).End(xlUp).End(xlUp).End(xlUp).Offset(-1, 0).Row
LastRowFormL_A = Cells(Rows.Count, 12).End(xlUp).End(xlUp).End(xlUp).Row
Range("L" & LastRowFormL_A).Formula = "=SUM(L42:L" & LastRowSumL_A & ")"
Range("H8").Formula = "=SUM(L42:L" & LastRowSumL_A & ")"
Range(Cells(Rows.Count, "L").End(xlUp).Offset(1), Cells(Rows.Count, "L")).EntireRow.Clear
Range("F11").Formula = "=SUM(H8 +- F12)"
Range("G11").Formula = "=SUM(H8 +- G12)"
LastRowStaff = Cells(Rows.Count, 4).End(xlUp).Offset().Row
LastRowExpense = Cells(Rows.Count, 12).End(xlUp).Offset(-5, 0).Row
Range("F12").Formula = "=SUMIF(D42:D" & LastRowStaff & ",""*Accrual*"", L42:L" & LastRowExpense & ")"
Range("G12").Formula = "=SUMIF(D42:D" & LastRowStaff & ",""*Accrual*"", L42:L" & LastRowExpense & ")"
Range("P42") = "Check"
Range("Q42") = "ID"
Range("P43").FormulaArray = "=IFERROR(INDEX(Lijst!$A$2:$A$247,MATCH(1,--(SEARCH(TRANSPOSE(Lijst!$A$2:$A$247),O43)>0),0),0),""Z"")"
Range("P43").Select
Selection.AutoFill Destination:=Range("P43:P1000")
Range("Q43").Formula = "=IF(P43<>P44,1,0)"
Range("Q43").Select
Selection.AutoFill Destination:=Range("Q43:Q1000")
Rows("42:42").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Advies").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Advies").AutoFilter.Sort.SortFields.Add2 Key:= _
Range("P42"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Advies").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("P:Q").Select
Range("P25").Activate
Selection.EntireColumn.Hidden = True
Dim rnga As Range, ra As Long
Set rnga = Range("Q8:Q3276")
For ra = rnga.Count To 1 Step -1
If rnga(ra).Value = 1 Then
rnga(ra + 1).EntireRow.Insert
rnga(ra + 1).EntireRow.Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.599993896298105
.PatternTintAndShade = 0
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Range("A35").Select
End If
Next ra
Columns("R:R").Select
Range("R31").Activate
Range(Selection, Selection.End(xlToRight)).Select
Selection.Clear
Range("O31").Select
Application.Goto Reference:=Range("a1"), Scroll:=True
</code></pre>
<p>Any suggestions / help is appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:50:13.973",
"Id": "462322",
"Score": "0",
"body": "Welcome to Code Review! Can you tell us more about what the code is doing and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:33:13.500",
"Id": "462348",
"Score": "0",
"body": "Time allowing, try to [get best value out of CodeReview@SE](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions?r=SearchResults&s=1|36.2985)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:59:20.133",
"Id": "462354",
"Score": "0",
"body": "See [this SO question](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba)... that's a good start. Also any time you have `Range` or `Cells` or `Rows` or `Columns`, etc., make sure they are qualified with the `Workbook` and `Worksheet` they are in/on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:32:52.353",
"Id": "462362",
"Score": "0",
"body": "Also, Activate, Select and \"Active-anything\" are things to avoid"
}
] |
[
{
"body": "<p>This review is going to be short, because it will cover ground that has been covered many times in Code Review. Searching previous articles should provide more information.</p>\n\n<ol>\n<li>Use <code>Option Explicit</code> at the top of modules every time. Always.\n<strong><em>Always</em></strong> (search: Option Explicit).</li>\n<li>Properly indent your code for readability and maintainability.\n(search: indent code)</li>\n<li>Avoid using select and activate unless you particularly want to draw\nsomething to the user's attention.\n(<a href=\"https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba\">https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba</a>\nis a good start as @BigBen noted).</li>\n<li>Always fully qualify any reference to Range or Cells. Using a\nqualified <code>With</code> block does count. (search: qualify ranges)</li>\n</ol>\n\n<p>Once the basics have been addressed, the code itself (as intended, not as currently presented) can then be reviewed. At the moment it is a bit too hard to read.</p>\n\n<p>Why do you have <code>.End</code> three times?</p>\n\n<pre><code>Cells(Rows.Count, 12).End(xlUp).End(xlUp).End(xlUp).Row\n</code></pre>\n\n<p>An additional hint is to declare and assign a <code>Workbook</code> and <code>Worksheet</code> object for the book/sheet(s) that you want to manipulate. When using the variable, the VBA IDE Intellisense will function and aid you in useful properties and methods. When not assigned to a variable, these commands (e.g. <code>ActiveWorkbook.Worksheets(\"WIP extract\")</code>) will return a generic Object and the Intellisense does not function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T09:59:10.810",
"Id": "462800",
"Score": "0",
"body": "Thanks for the comment @AJD"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T05:53:18.597",
"Id": "236101",
"ParentId": "236049",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236101",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T08:03:08.773",
"Id": "236049",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "Trying to optimize VBA code to create worksheets"
}
|
236049
|
<p>I have a few hundred mp4 files (thanks android =/) that I need to convert. I only want to convert videos that are too large (>= 1080p) and I do want to keep the exif Information so the timeline is not broken.</p>
<p>I hope someone can look over the script to point me to some grave mistakes or give some improvement.</p>
<p>Anything I am missing? Thanks in advance.</p>
<pre><code>resize() {
echo "Filename $1"
filename=$(basename -- "$1")
extension="${filename##*.}"
filename="${filename%.*}"
new_filename=${filename}.${timestamp}.${extension}
ffmpeg -v quiet -stats -i $1 -map_metadata 0 \
-vf scale=-1:720 -c:v libx264 -crf 23 \
-c:a copy $new_filename < /dev/null
exiftool -TagsFromFile $1 "-all:all>all:all" -overwrite_original $new_filename
}
if [[ -d $1 ]]; then
timestamp=$(date +%s)
echo "Finding Video Files ..."
exiftool $1/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' > /tmp/fl_$timestamp
echo "Processing Video Files ..."
while IFS= read -r line; do
resize $line
done < /tmp/fl_$timestamp
rm /tmp/fl_$timestamp
elif [[ -f $1 ]]; then
resize $1
else
echo "Argument missing"
exit 1
fi
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T11:20:41.670",
"Id": "462812",
"Score": "1",
"body": "I've rolled back your edit. Please do not edit the question with updated code. If you would like further improvements, please ask a new question."
}
] |
[
{
"body": "<h1>Consider portable shell</h1>\n<p>The only Bash feature we're using is <code>[[ ]]</code> for testing file properties. It's easy to replace <code>[[ -d $1 ]]</code> with <code>[ -d "$1" ]</code> and that allows us to stick with standard shell, which is more portable and lower overhead:</p>\n<pre><code>#!/bin/sh\n</code></pre>\n<h1>Careful with quoting</h1>\n<p>Most of shellcheck's output is due to failure to quote parameter expansions:</p>\n<pre class=\"lang-none prettyprint-override\"><code>236052.sh:9:31: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:9:50: error: Delete trailing spaces after \\ to break line (or use quotes for literal space). [SC1101]\n236052.sh:10:5: warning: This flag is used as a command name. Bad line break or missing [ .. ]? [SC2215]\n236052.sh:11:15: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:12:28: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:12:74: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:18:14: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:18:27: note: Expressions don't expand in single quotes, use double quotes for that. [SC2016]\n236052.sh:18:53: note: Expressions don't expand in single quotes, use double quotes for that. [SC2016]\n236052.sh:18:75: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:22:16: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:23:20: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:24:16: note: Double quote to prevent globbing and word splitting. [SC2086]\n236052.sh:26:12: note: Double quote to prevent globbing and word splitting. [SC2086]\n</code></pre>\n<p>Ironically, you do have quotes in some places they aren't strictly necessary, so it's unclear why you missed all these.</p>\n<h1>Errors go to standard output</h1>\n<blockquote>\n<pre><code>echo "Argument missing"\nexit 1\n</code></pre>\n</blockquote>\n<p>That should be:</p>\n<blockquote>\n<pre><code>echo >&2 "Argument missing"\nexit 1\n</code></pre>\n</blockquote>\n<p>The test here is slightly wrong: the argument may be present, but not the name of a plain file or directory. So I'd replace that with:</p>\n<pre><code>elif [ -e "$1" ]\n echo "$1: not a plain file or directory" >&2\n exit 1\nelif [ "$1" ]\n echo "$1: file not found" >&2\n exit 1\nelse\n echo "Argument missing" >&2\n exit 1\nfi\n</code></pre>\n<p>It may be worthwhile to move that testing into the <code>resize</code> function, because at present we assume that the contents found in directory arguments are plain files (that said, we're covering a tiny corner case with that, so I wouldn't sweat it - just let the commands there fail).</p>\n<h1>Don't assume previous commands succeeded</h1>\n<p>In <code>resize</code>, if <code>ffmpeg</code> fails, there's little point running <code>exiftool</code>, so connect them with <code>&&</code>. Also consider removing the file if it was created with errors (so we're not fooled by a partly-written output into thinking this file doesn't need conversion).</p>\n<h1>Avoid temporary files</h1>\n<p>There's no need for the file <code>/tmp/fl_$timestamp</code>: we could simply use a pipeline there.</p>\n<h1>Consider accepting more arguments</h1>\n<p>Instead of only allowing a single argument (and ignoring all but the first), let the user specify as many files as needed; it's easy to loop over them using <code>for</code>.</p>\n<h1>Handle directories using recursion</h1>\n<p>Instead of the <code>while</code> loop, we could invoke our script recursively using <code>xargs</code>. I'll make it a separate function for clarity:</p>\n<pre><code>resize_dir() {\n exiftool "$1"/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' |\n xargs -r -d '\\n' -- "$0" || status=false\n}\n</code></pre>\n<p>(<code>xargs -r</code> is a GNU extension to avoid running the command with no arguments. If this option isn't available, we'll need to modify the script so that passing no arguments isn't an error.)</p>\n<hr />\n<h1>Modified code</h1>\n<p>This is Shellcheck-clean, but I'm not able to test it (lacking the requisite directory of MPEG files).</p>\n<pre><code>#!/bin/sh\n\nset -eu\n\n\nstatus=true\nfail() {\n echo "$@" >&2\n status=false\n}\n\n# Resize a single file\nresize() {\n echo "Filename $1"\n filename=$(basename -- "$1")\n extension=${filename##*.}\n filename=${filename%.*}\n new_filename=${filename}.${timestamp}.${extension}\n if \n ffmpeg -v quiet -stats -i "$1" -map_metadata 0 \\\n -vf scale=-1:720 -c:v libx264 -crf 23 \\\n -c:a copy "$new_filename" < /dev/null &&\n exiftool -TagsFromFile "$1" '-all:all>all:all' \\\n -overwrite_original "$new_filename"\n then\n # success\n true\n else\n # failed; destroy the evidence\n rm -f "$new_filename" 2>/dev/null\n fail "Failed to convert $1"\n fi\n}\n\n# Resize all *.mp4 files in a single directory\n# N.B. only immediate contents; not recursive\nresize_dir() {\n # shellcheck disable=SC2016\n exiftool "$1"/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' |\n xargs -r -d '\\n' -- "$0" || status=false\n}\n\n[ $# -gt 0 ] || fail "Usage: $0 FILE FILE..."\n\ntimestamp=$(date +%s)\n\nfor arg\ndo\n if [ -d "$arg" ]\n then\n resize_dir "$arg"\n elif [ -f "$arg" ]\n then\n resize "$arg"\n elif [ -e "$arg" ]\n then\n fail "$arg: not a plain file or directory"\n else\n fail "$arg: file not found"\n fi\ndone\n\nexec $status # true or false\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:47:02.417",
"Id": "462321",
"Score": "0",
"body": "Processed about 100 Videos - so far works like a charm. Thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T20:13:02.833",
"Id": "462879",
"Score": "0",
"body": "Aren't `[[` a feature worth using more current shells for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T09:55:00.160",
"Id": "462935",
"Score": "0",
"body": "@chicks, that's very much a value judgement. For me, being able to omit quoting from those file tests isn't a feature worth sacrificing portability for. If we were using `[[` for regular expression matching (which doesn't have such a simple standard equivalent), then the trade-off might go the other way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T13:35:34.113",
"Id": "462960",
"Score": "0",
"body": "It doesn't have anything do with regular expressions. It has to do with making shell programming less confusing for folks coming from other languages. https://www.tothenew.com/blog/foolproof-your-bash-script-some-best-practices/ explains this in point 6. I'd consider `[[` a best practice that is worth moving to ksh or bash for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T13:38:07.527",
"Id": "462961",
"Score": "0",
"body": "That's a strange perspective - to me, it *adds* confusion because there's suddenly a context where quoting works differently."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T09:37:45.647",
"Id": "236054",
"ParentId": "236052",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236054",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T08:55:23.457",
"Id": "236052",
"Score": "5",
"Tags": [
"bash"
],
"Title": "ffmpeg batch script for video resizing"
}
|
236052
|
<p>Can you provide some advice on how I can simplify this code?</p>
<p>I am a beginner with Python, and I'm pretty sure that my code can be much simpler. I think the <code>check()</code> function is far too complex. But I have no idea how to simplify it, and still check which player has won the game.</p>
<pre><code>def check():
win = 0
if gameTable[0][0] == gameTable[0][1] == gameTable[0][2] == 'X':
who(1)
return True
elif gameTable[1][0] == gameTable[1][1] == gameTable[1][2] == 'X':
who(1)
return True
elif gameTable[2][0] == gameTable[2][1] == gameTable[2][2] == 'X':
who(1)
return True
elif gameTable[0][0] == gameTable[1][0] == gameTable[2][0] == 'X':
who(1)
return True
elif gameTable[0][1] == gameTable[1][1] == gameTable[2][1] == 'X':
who(1)
return True
elif gameTable[0][2] == gameTable[1][2] == gameTable[2][2] == 'X':
who(1)
return True
elif gameTable[0][0] == gameTable[1][1] == gameTable[2][2] == 'X':
who(1)
return True
elif gameTable[0][2] == gameTable[1][1] == gameTable[2][0] == 'X':
who(1)
return True
elif gameTable[0][0] == gameTable[0][1] == gameTable[0][2] == 'O':
who(2)
return True
elif gameTable[1][0] == gameTable[1][1] == gameTable[1][2] == 'O':
who(2)
return True
elif gameTable[2][0] == gameTable[2][1] == gameTable[2][2] == 'O':
who(2)
return True
elif gameTable[0][0] == gameTable[1][0] == gameTable[2][0] == 'O':
who(2)
return True
elif gameTable[0][1] == gameTable[1][1] == gameTable[2][1] == 'O':
who(2)
return True
elif gameTable[0][2] == gameTable[1][2] == gameTable[2][2] == 'O':
who(2)
return True
elif gameTable[0][0] == gameTable[1][1] == gameTable[2][2] == 'O':
who(2)
return True
elif gameTable[0][2] == gameTable[1][1] == gameTable[2][0] == 'O':
who(2)
return True
elif '-' not in gameTable[0] and '-' not in gameTable[1] and '-' not in gameTable[2]:
who(3)
return True
else:
return False
def who(win):
if win == 1:
print('\t---=== PLAYER 1 WINS ===---')
if win == 2:
print('\t---=== PLAYER 2 WINS ===---')
if win == 3:
print('\t---=== DRAW ===---')
else:
pass
def x_move():
while True:
x = input("Player {}\n Type coordinates of your move! (x, y):\n".format(p1))
tabx = x.split(',')
try:
tabx[0] = int(tabx[0])-1
tabx[1] = int(tabx[1])-1
except:
print("--==You've type invalid coordinates==--")
continue
try:
if gameTable[tabx[0]][tabx[1]] == '-':
gameTable[tabx[0]][tabx[1]] = 'X'
print('\t', gameTable[0], '\n\t', gameTable[1], '\n\t', gameTable[2])
break
else:
print("--==This place is already filled. Choose another.==--")
except:
print("--==You've type invalid coordinates==--")
continue
def y_move():
while True:
y = input("Player {}\n Type coordinates of your move! (x, y):\n".format(p2))
taby = y.split(',')
try:
taby[0] = int(taby[0])-1
taby[1] = int(taby[1])-1
except:
print("--==You've type invalid coordinates==--")
continue
try:
if gameTable[taby[0]][taby[1]] == '-':
gameTable[taby[0]][taby[1]] = 'O'
print('\t', gameTable[0], '\n\t', gameTable[1], '\n\t', gameTable[2])
break
else:
print("--==This place is already filled. Choose another.==--")
except:
print("--==You've type invalid coordinates==--")
continue
def game():
print('\t', gameTable[0], '\n\t', gameTable[1], '\n\t', gameTable[2])
while True:
x_move()
if check():
break
y_move()
if check():
break
p1 = input('First player name: ')
p2 = input('Second player name: ')
gameTable = [['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']]
game()
</code></pre>
<p>Ok, I changed that a little bit. I think now it looks better, but maybe is there anything more to make it simplier? </p>
<pre><code>def check():
win = 0
if gameTable[0][0] == gameTable[0][1] == gameTable[0][2] != '-':
who(1, gameTable[0][1])
return True
elif gameTable[1][0] == gameTable[1][1] == gameTable[1][2] != '-':
who(1, gameTable[1][1])
return True
elif gameTable[2][0] == gameTable[2][1] == gameTable[2][2] != '-':
who(1, gameTable[2][1])
return True
elif gameTable[0][0] == gameTable[1][0] == gameTable[2][0] != '-':
who(1, gameTable[1][0])
return True
elif gameTable[0][1] == gameTable[1][1] == gameTable[2][1] != '-':
who(1, gameTable[1][1])
return True
elif gameTable[0][2] == gameTable[1][2] == gameTable[2][2] != '-':
who(1, gameTable[1][2])
return True
elif gameTable[0][0] == gameTable[1][1] == gameTable[2][2] != '-':
who(1, gameTable[1][1])
return True
elif gameTable[0][2] == gameTable[1][1] == gameTable[2][0] != '-':
who(1, gameTable[1][1])
return True
elif '-' not in gameTable[0] and '-' not in gameTable[1] and '-' not in gameTable[2]:
who(2, '-')
return True
else:
return False
def who(win, cords):
if win == 1:
if cords == 'X':
print('---=== {} WINS A GAME ===---'.format(p1))
elif cords == 'O':
print('---=== {} WINS A GAME ===---'.format(p2))
elif win == 2:
print('\t---=== DRAW ===---')
else:
pass
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:58:44.550",
"Id": "462324",
"Score": "0",
"body": "Is there a reason at one point you have player 1 and 2 while at another you're referring to x_move and y_move?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:16:43.507",
"Id": "462330",
"Score": "0",
"body": "I used p1 and p2 variables just for displaying name of players, is that what you meant? I'm sorry, english isn't my first language and I could not get your question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:05:52.587",
"Id": "462342",
"Score": "0",
"body": "Yes, that's it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T12:39:15.347",
"Id": "462349",
"Score": "0",
"body": "There are different starting points for a quest for a simple solution. Starting from existing code, look for things that are the same between chunks (statements, sequences of statements, procedures, …), and for things that differ. Visualise execution and look for the same things; additionally, for chances missed to re-use results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:17:40.497",
"Id": "462365",
"Score": "0",
"body": "I'd edit post, what do you think about it now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T18:59:58.563",
"Id": "462402",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:00:32.377",
"Id": "462403",
"Score": "0",
"body": "If there are major improvements, you may want to post a follow-up question instead. You may also want to wait for a couple more hours, more answers may still be coming in."
}
] |
[
{
"body": "<p>Ok, so I'm also a beginner and some weeks ago I worked on a tic-tac-toe kind of game and learned a lot from it, here's what I think you could improve on.</p>\n\n<p>DRY (Don't Repeat Yourself): Whenever you see that you are having to copy and paste your code a lot, you can generally assume there's a shorter way to do the same thing you're trying to do, either by using lists, for-loops, while-loops, etc.</p>\n\n<p>One thing you can learn is using list comprehensions and the 'all' and 'any' operations, that's very useful when you are using lists.</p>\n\n<pre><code>players = ['X', 'O']\n\ngameRows = [[gameTable[0][0], gameTable[0][1], gameTable[0][2]],\n [gameTable[1][0], gameTable[1][1], gameTable[1][2]],\n [gameTable[2][0], gameTable[2][1], gameTable[2][2]]]\n\ndef check():\n # You don't need to repeat the same code for both players,\n # Just use a for loop for each of them\n for player in players:\n # You should iterate all the columns and diagonals of the table\n for row in gameRows:\n # Returns True if all of the tiles in the row are equal the player\n if all(i == player for i in row):\n who(1, player)\n return True\n\n # Here you can add the 'gameTable' into a list\n if '-' not in gameTable[0] + gameTable[1] + gameTable[2]:\n who(2, '-')\n return True\n\n\ndef who(win, cords):\n # Here it's pretty much the same, instead of printing 'p1'\n # you could just print 'cords'\n if win == 1:\n if cords == 'X':\n print('---=== {} WINS A GAME ===---'.format(p1))\n elif cords == 'O':\n print('---=== {} WINS A GAME ===---'.format(p2))\n elif win == 2:\n print('\\t---=== DRAW ===---')\n else:\n pass\n</code></pre>\n\n<p>You could have a 'gameColumns' and 'gameDiagonals' lists for you to iterate through them.\nIdk if this would actually work on your code, since you haven't provided all of it, but I think the general idea could be implemented. You could also check this link: <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a>\nIt's a style guide for writing code that is mostly accepted by all programmers, there's nothing wrong with using camelCase, it's just that people are generally used to other ways of casing variables.\nHope you understood everything. Good luck on learning python :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T17:26:54.140",
"Id": "462397",
"Score": "0",
"body": "Well. when I just copied and pasted your code , it keeps giving me a draw after first move. Second thing is that your logic is checking if there are same characters in a row, what isn't a point of tic tac toe, where you can win typing your chars diagonally"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T17:37:37.907",
"Id": "462399",
"Score": "0",
"body": "Yeah, for checking diagonals you should have a list of the tiles characters in the diagonals too, that way you check for rows, columns and diagonals. About the tie issue, I edited my code so that it fixes the problem"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:50:50.737",
"Id": "236074",
"ParentId": "236055",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T10:33:03.170",
"Id": "236055",
"Score": "5",
"Tags": [
"python",
"beginner",
"tic-tac-toe"
],
"Title": "TicTacToe Python"
}
|
236055
|
<p>The code below takes a directory of XML files and parses them into a CSV file.
Right now parsing around 60 XML files is fast and the output is a CSV file that is around 250MB.</p>
<p>That is a really big file and the reason is because columns are being repeated. I'm repeating the columns for the reason that every element should have all the information. In red is one of the cases where the ID Z048 had multiple lines of <code>setdata</code> so that is why the other columns in red had to be repeated.</p>
<p>I'm planning to increase the number of XML files to 5k, meaning that the CSV file will be relatively large.</p>
<p>Asking this question to maybe get any answer if the size of my CSV file can be lowered somehow. Even though I tried to code with the mindset that I want my code to be fast and produce not too big CSV files.</p>
<pre><code>from xml.etree import ElementTree as ET
from collections import defaultdict
import csv
from pathlib import Path
directory = 'path to a folder with xml files'
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
headers = ['id', 'service_code', 'rational', 'qualify', 'description_num', 'description_txt', 'set_data_xin', 'set_data_xax', 'set_data_value', 'set_data_x']
writer.writerow(headers)
xml_files_list = list(map(str, Path(directory).glob('**/*.xml')))
print(xml_files_list)
for xml_file in xml_files_list:
tree = ET.parse(xml_file)
root = tree.getroot()
start_nodes = root.findall('.//START')
for sn in start_nodes:
row = defaultdict(str)
repeated_values = dict()
for k,v in sn.attrib.items():
repeated_values[k] = v
for rn in sn.findall('.//Rational'):
repeated_values['rational'] = rn.text
for qu in sn.findall('.//Qualify'):
repeated_values['qualify'] = qu.text
for ds in sn.findall('.//Description'):
repeated_values['description_txt'] = ds.text
repeated_values['description_num'] = ds.attrib['num']
for st in sn.findall('.//SetData'):
for k,v in st.attrib.items():
row['set_data_'+ str(k)] = v
for key in repeated_values.keys():
row[key] = repeated_values[key]
row_data = [row[i] for i in headers]
writer.writerow(row_data)
row = defaultdict(str)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:52:59.287",
"Id": "462337",
"Score": "2",
"body": "This is a re-post of [this off-topic question, that you deleted](https://codereview.stackexchange.com/q/236036)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:57:51.733",
"Id": "462338",
"Score": "0",
"body": "@Peilonrayz, if you read the question you will see that it is not. The code works and not asking about long numbers. Really feeling the negativity that is coming across. I'm asking for advice I am not coming here with not a working code and then my post gets a downvote"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:06:52.573",
"Id": "462356",
"Score": "2",
"body": "@ebe: In any case, just to clarify, does the code posted here work correctly (i.e. did you fix the issue you had in your other question or does it not matter anymore)? Can you give us a (small) example XML file or explain more how you parse it, i.e. its structure? You might also want to [edit] your title to be more descriptive of the problem your code solves, rather than the issues you see with your current code. Otherwise we would get too many questions asking for \"improvement\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:10:47.767",
"Id": "462357",
"Score": "1",
"body": "Also, I removed the `pandas` tag, because it is not used anywhere in the code and fixed up some grammar. Feel free to further [edit] in case any of the changes changed your intention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:19:53.493",
"Id": "462360",
"Score": "0",
"body": "@Graipher, thank you for editing, all of it is fine. The code works, the problem I had before maybe was not suited because the code parses it right so I fixed it inside Excel. However I would really appreciate the help here. Also I would appreciate your suggestion on how I should rename the task"
}
] |
[
{
"body": "<p>At this point your code is starting to become hard to follow. If you add any more complicated logic, you will not be able to easily understand it yourself if you return to it a few weeks later.</p>\n\n<p>I would first of all separate out the parsing of an XML file so that you can change that independently of all the rest. You can make this a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a>, so it doesn't need to know what happens with the data it provides (being written to a CSV file, printed to the terminal, shucked into <code>/dev/null/</code>, ...).</p>\n\n<p>Using <code>findall</code> to find one element is not the right approach. Either there is exactly one e.g. <code>'.//Rational'</code> element, in which case you can just use <a href=\"https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements\" rel=\"nofollow noreferrer\"><code>find</code></a>, or there is not and you have to store all of them (or rethink your XML design).</p>\n\n<p>You can use a <a href=\"https://www.datacamp.com/community/tutorials/python-dictionary-comprehension\" rel=\"nofollow noreferrer\">dictionary comprehension</a> and the relatively new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code>s</a> to easily generate your row data (don't worry about missing keys here, we'll take care of them outside).</p>\n\n<pre><code>def parse_file(xml_file):\n tree = ET.parse(xml_file)\n for node in tree.getroot().findall('.//START'):\n repeated_values = dict(node.attrib)\n repeated_values['rational'] = node.find('.//Rational').text\n repeated_values['qualify'] = node.find('.//Qualify').text\n description = node.find('.//Description')\n repeated_values['description_txt'] = description.text\n repeated_values['description_num'] = description.get('num')\n\n for data in node.findall('.//SetData'):\n row = {f\"set_data_{key}\": value for key, value in data.attrib.items())}\n row.update(repeated_values)\n yield row\n</code></pre>\n\n<p>The <code>csv</code> module has a <code>DictReader</code> and, more importantly, a <a href=\"https://docs.python.org/3/library/csv.html#csv.DictWriter\" rel=\"nofollow noreferrer\"><code>DictWriter</code></a> class. These are a bit easier to use since you don't need to enforce the correct order in the parsing. It also has the <code>writerows</code> method (like all other <code>csv</code> writers) that can take an iterable of dictionaries to write. This is slightly faster than writing each row manually, and also more readable.</p>\n\n<pre><code>def join_xml_files(files, output_file, headers):\n with open(output_file, 'w') as f:\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n for xml_file in files:\n writer.writerows(parse_file(xml_file))\n</code></pre>\n\n<p>Note that <code>restvals=\"\"</code> is already set by default and replaces missing keys with an empty string, so no need for <code>collections.defaultdict(str)</code> anymore.</p>\n\n<p>You can then put the actual calling code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> which allows you to import from this script without running it:</p>\n\n<pre><code>if __name__ == \"__main__\":\n directory = 'path to a folder with xml files'\n xml_files = map(str, Path(directory).glob('**/*.xml'))\n headers = ['id', 'service_code', 'rational', 'qualify', 'description_num',\n 'description_txt', 'set_data_xin', 'set_data_xax', 'set_data_value',\n 'set_data_x']\n\n # actually call the function\n join_xml_files(xml_files, \"output.csv\", headers)\n</code></pre>\n\n<hr>\n\n<p>As to reducing the file size: that's not possible without removing information. You could zip up the resulting file (it would still be just as large in memory when unzipping it, though), or you can leave out the redundant information (but then all programs reading this file need to fill in the information when necessary).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:22:27.147",
"Id": "462367",
"Score": "0",
"body": "thank you for your answer, I understand that the size of the file can't be reduced. Really helpful the idea of breaking it down into smaller parts so later on they could be modified easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:44:57.717",
"Id": "462427",
"Score": "0",
"body": "can you give me any advice. Once the csv file is generated I try to read the csv file. I'am getting this error ```ParserError: Error tokenizing data. C error: Expected 1 fields in line 12, saw 2```."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:49:30.940",
"Id": "462496",
"Score": "0",
"body": "@ebe: That sounds like the CSV is malformed, you should take a look directly at the file in a text editor to see exactly what the problem is. Maybe it is newlines, maybe quoting, maybe the separator, it could be many things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:51:52.080",
"Id": "462865",
"Score": "0",
"body": "I'm getting an SyntaxError: invalid syntax at the line row = {f\"set_data_{key}\": value for key, value in data.attrib.items())}"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T09:43:30.663",
"Id": "462933",
"Score": "0",
"body": "@ebe: Which version of Python are you using? The `f-string` I used there is Python 3.6+. If you are on an older version, use `row = {\"set_data_{}\".format(key): value for key, value in data.attrib.items())}` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T13:43:31.347",
"Id": "462963",
"Score": "0",
"body": "I am using Python 3,7,4 on Anaconda"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T13:44:48.377",
"Id": "462964",
"Score": "0",
"body": "@ebe Nevermind, there is one closing parenthesis too many, it should be `row = {f\"set_data_{key}\": value for key, value in data.attrib.items()}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T17:24:27.457",
"Id": "463004",
"Score": "0",
"body": "I now seem to be getting the following error ```repeated_values['request'] = node.find('.//Request').text AttributeError: 'NoneType' object has no attribute 'text' ```"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:40:16.007",
"Id": "236065",
"ParentId": "236060",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T11:36:38.487",
"Id": "236060",
"Score": "1",
"Tags": [
"python",
"csv",
"xml"
],
"Title": "File size when parsing XML"
}
|
236060
|
<p>I decided to split the SQL Part away from <a href="https://codereview.stackexchange.com/questions/235919/sql-to-excel-then-to-csv-file-for-data-upload">This Question</a>.<br><br>
Before we get started I need to let you know a critical piece of information: Due to permissions within an offsite database I am NOT allowed to create tables even temporary ones within the database that I am getting the data from.</p>
<p>With that being said: All of the code below works as expected, but I would like a review of it because I know that there has to be a cleaner way of writing the SQL String.</p>
<pre><code>SELECT CONCAT(cfcif#,cfalta) AS Customer_Number,
cffna AS First_Name,
cfmna AS Middle_Name,
COALESCE(NULLIF(cflna,''),cfna1) AS Last_Name,
COALESCE(NULLIF(RTRIM(LTRIM(cfpfa1))|| ' '|| RTRIM(LTRIM(cfpfa2)),''),RTRIM(LTRIM(cfna2),'')|| ' ' || RTRIM(LTRIM(cfna3),'')) AS Street_Address,
COALESCE(NULLIF(cfpfcy,''),cfcity) AS Street_City,
COALESCE(NULLIF(cfpfst,''),cfstat) AS Street_State,
COALESCE(NULLIF(LEFT(cfpfzc, 5), 0), LEFT(cfzip, 5)) AS Street_Zip,
CONCAT(RTRIM(LTRIM(cfna2)),RTRIM(LTRIM(cfna3))) AS Mailing_Address,
cfcity AS Mailing_City,
cfstat AS Mailing_State,
LEFT(cfzip, 5) AS Mailing_Zip,
NULLIF(cfhpho,0) AS Home_Phone,
NULLIF(cfbpho,0) AS Business_Phone,
NULLIF(cfssno,0) AS TIN,
(CASE
WHEN cfindi = 'Y' THEN '1'
WHEN cfindi = 'N' THEN '2'
END) AS Customer_Type,
(CASE
WHEN cfdob7 = 0 THEN NULL
WHEN cfdob7 = 1800001 THEN NULL
ELSE cfdob7
END) AS Date_of_Birth,
cfeml1 AS Email_Address
FROM bhschlp8.jhadat842.cfmast cfmast
WHERE cfdead = 'N'
ORDER BY cfcif#
</code></pre>
|
[] |
[
{
"body": "<p>I can't see much wrong with it. Maybe use <code>BTRIM</code> if on Db2 11.1 or above rather than <code>RTRIM(LTRIM(</code> \nand maybe indent with fewer spaces (e.g. align the first column with the rest), but that is really a matter of style</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T15:54:12.043",
"Id": "462528",
"Score": "0",
"body": "unfortunately, i cant use `BTRIM`; I tried. Also thats how the editor I use formats the string and im not a fan of it. Thanks for taking a look at it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T21:03:58.077",
"Id": "236089",
"ParentId": "236063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:25:28.860",
"Id": "236063",
"Score": "2",
"Tags": [
"sql",
"db2"
],
"Title": "SQL String to get data from DB2"
}
|
236063
|
<p>I'm creating a parser, and I have just finished my lexer. I wanted to ask if there is anything I should change, add, or reconsider in my code! (I don't think the grammars matter much, since it is only a lexer)</p>
<p><strong>lexical_analyzer.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <iostream>
#include <string>
#include <vector>
// kinds of lexemes (i.e. tokens)
namespace la_enum
{
enum token
{
STRING // anything that isn't something below
, AND // +
, CHAR_REPEATED // *
, LEFT_PARENTHESIS // (
, RIGHT_PARENTHESIS // )
, ANY_CHAR // .
, COUNTER // {N}
, IGNORE_CASE // \I
, SINGLE_CAPTURE // \O{N}
};
}
class lexical_analyzer
{
public:
lexical_analyzer(std::string patternInput) :
pattern(patternInput)
{
addLexemes();
}
private:
void addLexemes(); // adds lexemes and tokens from the pattern to the vectors
bool isSingleSymbol(char); // checks if it is an operator with ONE symbol
void addString(); // is used to store strings (operands)
void addOperator(la_enum::token, std::string&, int, int); // is used to store operators
std::string pattern; // input pattern
std::string characterBuffer; // buffer for operators with more than one symbol
// 'lexemes' and 'tokens' have synched indexes
std::vector<std::string> lexemes; // stores lexemes
std::vector<la_enum::token> tokens; // stores tokens
};
</code></pre>
<p><strong>lexical_analyzer.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "lexical_analyzer.h"
// adds lexemes and tokens from the pattern to the vectors
void lexical_analyzer::addLexemes()
{
for (int i = 0; i != pattern.size(); i++)
{
// adds lexems and tokens from the char buffer (strings)
if (isSingleSymbol(pattern[i]))
addString();
switch (pattern[i])
{
case ('+') :
addOperator(la_enum::AND, pattern, i, 1);
break;
case ('*') :
addOperator(la_enum::CHAR_REPEATED, pattern, i, 1);
break;
case ('.') :
addOperator(la_enum::ANY_CHAR, pattern, i, 1);
break;
case ('(') :
addOperator(la_enum::LEFT_PARENTHESIS, pattern, i, 1);
break;
case (')') :
addOperator(la_enum::RIGHT_PARENTHESIS, pattern, i, 1);
break;
default :
if (pattern[i] == '{')
{
// checks if it's the right syntax '{N}'...
if (isdigit(pattern[i + 1]) && pattern[i + 2] == '}')
{
addString();
addOperator(la_enum::COUNTER, pattern, i, 3);
i += 2;
}
else
{ // ...otherwise it counts as a string and is added to the buffer
characterBuffer.push_back(pattern[i]);
}
}
else if (pattern[i] == '\\')
{
// checks if it's the right syntax '\I'...
if (pattern[i + 1] == 'I')
{
addString();
addOperator(la_enum::IGNORE_CASE, pattern, i, 2);
i++;
}
// checks if it's the right syntax '\O{N}'...
else if (pattern[i + 1] == 'O' && pattern[i + 2] == '{' && isdigit(pattern[i + 3]) && pattern[i + 4] == '}')
{
addString();
addOperator(la_enum::SINGLE_CAPTURE, pattern, i, 5);
i += 4;
}
else
{ // ...otherwise it counts as a string and is added to the buffer
characterBuffer.push_back(pattern[i]);
}
}
else // If the symbol isn't one of those above
// it counts as a string (operand) and is added to the buffer
{
characterBuffer.push_back(pattern[i]);
}
}
}
// check one last time if the buffer has content which is then added to the vectors
addString();
// prints tokens and lexemes
for (int i = 0; i != lexemes.size(); i++)
{
std::cout << "Token: \"" << tokens[i] << "\" Lexeme: \"" << lexemes[i] << "\"" << std::endl;
}
}
// checks if it is an operator with ONE symbol
bool lexical_analyzer::isSingleSymbol(char c)
{
if (c == '+' || c == '*' || c == '(' || c == ')' || c == '.')
return true;
else
return false;
}
// checks if the buffer has content
// which is then added as lexeme and token
void lexical_analyzer::addString()
{
if (!characterBuffer.empty())
{
lexemes.push_back(characterBuffer);
tokens.push_back(la_enum::STRING);
}
}
// adds an operator as a lexeme in the 'lexeme' vector, and token in 'tokens' vector
void lexical_analyzer::addOperator(la_enum::token tok, std::string& str, int pos, int sz)
{
lexemes.push_back(std::string(str, pos, sz));
tokens.push_back(tok);
characterBuffer.clear();
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "lexical_analyzer.h"
int main()
{
//std::string in;
//std::getline(std::cin, in);
//lexical_analyzer(std::move(in));
lexical_analyzer("Hell. (MY)\I n..e (is+was) Melwin.\O{0}");
return 0;
}
</code></pre>
<p>output:</p>
<pre class="lang-none prettyprint-override"><code>Token: "0" Lexeme: "Hell"
Token: "5" Lexeme: "."
Token: "0" Lexeme: " "
Token: "3" Lexeme: "("
Token: "0" Lexeme: "MY"
Token: "4" Lexeme: ")"
Token: "0" Lexeme: "I n"
Token: "5" Lexeme: "."
Token: "5" Lexeme: "."
Token: "0" Lexeme: "e "
Token: "3" Lexeme: "("
Token: "0" Lexeme: "is"
Token: "1" Lexeme: "+"
Token: "0" Lexeme: "was"
Token: "4" Lexeme: ")"
Token: "0" Lexeme: " Melwin"
Token: "5" Lexeme: "."
Token: "0" Lexeme: "O"
Token: "6" Lexeme: "{0}"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:14:04.930",
"Id": "462364",
"Score": "0",
"body": "you could use a scoped enum: https://en.cppreference.com/w/cpp/language/enum rather than namespaced. And maybe some form of `map` to get from `char` to `enum` rather than enum defined in one place and then a big switch statement. The map might be more sophisticated with lambda/callbacks or similar for a design which could scale to something more complex?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:34:27.803",
"Id": "462369",
"Score": "0",
"body": "@OliverSchonrock I had been thinking about using a map in this project, and you might be on to something there. I will see what I can find. But you're saying I could remove the switch statement altogether and use a map instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:52:06.433",
"Id": "462370",
"Score": "0",
"body": "I have not spent much time on the code, but yes, it look like all the simple - non-default - cases could be handled in one or 2 lines with a map. worth exploring. I agree with @ratchet freak that if the number of tokens will stay at this level you don't need a map. I depends on the future of this code. for 200 tokens a map would probably be more maintainable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T15:23:15.483",
"Id": "462373",
"Score": "0",
"body": "@OliverSchonrock I will explore it! thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T23:52:39.430",
"Id": "462891",
"Score": "0",
"body": "Lexer tools are already prevalent. Have you though about using \"Lex\"?"
}
] |
[
{
"body": "<p>You should clear <code>characterBuffer</code> at the end of <code>addString</code> instead of <code>addOperator</code>.</p>\n\n<p>There is no need for <code>characterBuffer</code> to be a member field. Instead make it a local in <code>addLexemes</code> and pass it (by ref) when needed.</p>\n\n<p>There is a very consistent patter that every time you call <code>addOperator</code> you call <code>addString</code> right before. Therefor you can put <code>addString</code> in <code>addOperator</code>.</p>\n\n<pre><code>// first adds the string in 'precedingStringBuffer' as string if not empty\n// then adds an operator as a lexeme in the 'lexeme' vector, and token in 'tokens' vector\nvoid lexical_analyzer::addOperator(std::string& precedingStringBuffer, la_enum::token tok, const std::string& str, int pos, int sz)\n{\n addString(characterBuffer);\n lexemes.push_back(std::string(str, pos, sz));\n tokens.push_back(tok);\n}\n</code></pre>\n\n<p>If that is the amount of tokens you will be using then the switch is fine. You are unlikely to get anything better than what the compiler can generate for the switch.</p>\n\n<p>For the single character tokens you could use the ascii value of the character as value for the token and values from 257 for the multi character values.</p>\n\n<p>The <code>COUNTER</code> and <code>SINGLE_CAPTURE</code> only allow for a single digit between the braces, this can be troublesome if you ever need something more than 9 in there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T15:19:22.543",
"Id": "462372",
"Score": "0",
"body": "Thank you, I will definitely add addString() in addOperator(), which let's me remove the isSingleSymbol() altogether. Clearing characterBuffer in addString makes sense! Changing characterBuffer to local variable, is better? (will look into it). \nAs for the last remark, I was planning on having a limit on 9 anyway so anything else becomes just a string ({97} becomes a string, for example).\nAND the ASCII characters I can change, also, could make things easier later!\nThanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T14:41:53.417",
"Id": "236066",
"ParentId": "236064",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T13:34:42.603",
"Id": "236064",
"Score": "3",
"Tags": [
"c++",
"lexical-analysis",
"lexer"
],
"Title": "A lexer in C++ for analysing regex-like text"
}
|
236064
|
<p>I'm using my own Action-based Event Manager for a while and looking for ways to improve it.</p>
<p>Mainly it's used in game development, where excessive garbage generation can lead to severe consequences. That's why I'm trying to avoid any boxing which normally exists in such managers.</p>
<p>There are different event types (dozens, but not hundreds), each event type holds several subscribers. Subscriptions happen not often, but some events can fire hundreds of times per second (it won't actually, but i'm considering the possibility while creating my manager).</p>
<p>There is my previous version which is works just fine, but asks for improvement:</p>
<pre><code>internal class EventManager: IEventManager
{
private readonly Dictionary<int, Action<object>?> events = new Dictionary<int, Action<object>?>();
public virtual void Subscribe(int incidentId, Action<object> action)
{
if (events.ContainsKey(incidentId)) events[incidentId] += action;
else events.Add(incidentId, action);
}
public virtual void Unsubscribe(int incidentId, Action<object> action)
{
if (!events.ContainsKey(incidentId)) return;
events[incidentId] -= action;
}
public virtual void Trigger(int incidentId, object args)
{
if (!events.ContainsKey(incidentId)) return;
events[incidentId]?.Invoke(args);
}
}
// Sender:
eventManager.Trigger(1, "1234");
// Receiver:
eventManager.Subscribe(1, a => Console.WriteLine($"Received string length: {(a as string)?.Length}"));
</code></pre>
<p>I'm actually wrapping <code>object</code> inside convenient struct, but it doesn't matter. Sender is boxing some data to <code>object</code>, receiver is unboxing it. That's behavior I would like to avoid. Creation of an <code>object</code> each time event is fired can be painful.</p>
<p>There is another version of event manager:</p>
<pre><code>internal class EventManager: IEventManager
{
private readonly Dictionary<int, Dictionary<Type, Delegate>> events = new Dictionary<int, Dictionary<Type, Delegate>>();
public virtual void Subscribe<T>(int incidentId, Action<T> action)
{
if (!events.ContainsKey(incidentId))
events[incidentId] = new Dictionary<Type, Delegate> {[typeof(T)] = action};
else if (!events[incidentId].ContainsKey(typeof(T)))
events[incidentId][typeof(T)] = action;
else
events[incidentId][typeof(T)] = Delegate.Combine(events[incidentId][typeof(T)], action);
}
public virtual void Unsubscribe<T>(int incidentId, Action<T> action)
{
if (!events.ContainsKey(incidentId) ||
!events[incidentId].ContainsKey(typeof(T))) return;
events[incidentId][typeof(T)] = Delegate.Remove(events[incidentId][typeof(T)], action);
}
public virtual void Trigger<T>(int incidentId, T args)
{
if (!events.ContainsKey(incidentId) ||
!events[incidentId].ContainsKey(typeof(T))) return;
var genericEvent = events[incidentId][typeof(T)] as Action<T>;
genericEvent?.Invoke(args);
}
}
// ...
// Sender:
eventManager.Trigger(1, "1234");
// Receiver:
eventManager.Subscribe<string>(1, a => Console.WriteLine($"Received string length: {a.Length}"));
</code></pre>
<p>That's much better! Events are still mapped with Ids, senders can send any data and subscribers would get it without need of unboxing. Even conflicting data types between sender and receiver are handled: receiver wouldn't get incorrect message type (in previous version I'd have to add null and default values handling).</p>
<p>But usage of generics leads to another collection of <code>Type</code> which stores generic Actions. I cannot just declare something like <code>Dictionary<int, Action<T>></code>.</p>
<p>Dictionary inside a dictionary?.. Is it normal? Are there hidden traps somewhere?</p>
<p>Or I'm missing some simple pattern which would allow to pass data via events <strong>and</strong> get rid of <code>object</code> boxing <strong>and</strong> support different Ids for different event types?</p>
<p><strong>P.S.</strong> Subscriptions are rare, so I'm not necessarily looking into micro-optimizations here. Event firing, on the other hand, could be extremely often.</p>
<p><strong>UPDATE:</strong> Clarification: I'd like to receive feedback on second implementation, potential improvements and possible problems in future. First example is just "standard" version: I'm wondering if I'd better to stick with it or use generics magic with second example.</p>
|
[] |
[
{
"body": "<p>I don't see any glaring issues with the generic EventManager. Yes Dictionary of Dictionary does happen and is sometimes needed. </p>\n\n<p>One thing to consider is this implementation violates the Liskov substitution principle of SOLID. Usually in a non generic version the code would take the object and do \"as\" their type and check if not null. While the that wouldn't be an option anymore with the generic. What if the handler wanted to listen to all events for an Id? with the non generic it would have that option. With the generic it couldn't unless it knew all the types that got register, not likely. Also with program growing might start with something like </p>\n\n<pre><code>public class FeatureEvent\n{\n public virtual string Title => \"Original Event\";\n}\n</code></pre>\n\n<p>then in phase 2 or 3 down the road need to expand to add more data. </p>\n\n<pre><code>public class ExtraFeatureEvent : FeatureEvent\n{\n public override string Title => \"Better Event\";\n public DateTime UseAfter { get; set; } = DateTime.Now;\n}\n\npublic class ExtraFeature2Event : FeatureEvent\n{\n public override string Title => \"Even Better Event\";\n public Guid Id { get; set; } = Guid.NewGuid();\n}\n</code></pre>\n\n<p>Since these both come from FeatureEvent but would be sending data as a different type only the specific types events would get triggered and not the handlers listening for the base event. </p>\n\n<p>You could expand the trigger to handle and check If with <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.type.isinstanceoftype?view=netframework-4.8\" rel=\"nofollow noreferrer\">IsInstanceOf</a> but then you have to handle casting the type and gets a bit more complex. Only you know if this is something that out weights the casting but it something I see a lot of people forget about when they switch to a generic scheme like this.</p>\n\n<p>Also a side note you might want to constrain the event data to come from a base abstract event class to make it clear this is event data and not send over bunch of data. Like MS does for their events that event data comes from a class that is based on EventArgs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:01:24.123",
"Id": "462478",
"Score": "0",
"body": "That's a lot of things to consider, thanks! _\"What if the handler wanted to listen to all events for an Id?\"_ - the opposite is also correct, isn't it? If a subscriber expects `bool` value it would be strange to receive something `\"0.001f\"` or `\"System.Collections.Generic.List\"`. What it supposed to do with it? I see the option to send `default` data to all subscribers of event if relevant data is not available, but this doesn't feel right. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T14:49:14.420",
"Id": "462515",
"Score": "2",
"body": "That's the trade off. If as a consume I know I'm getting an object then its up to the caller to cast it. What you are building is most commonly called an Event Aggregator. If you google it you will find lots of information on it and some mvvm projects like prism and Caliburn.Micro and you could check out their source code to see if how others have done it in the past."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:36:03.927",
"Id": "236084",
"ParentId": "236070",
"Score": "3"
}
},
{
"body": "<p>Generic is your call, as using generic would avoid casting objects. </p>\n\n<p>Would this version work with you ? : </p>\n\n<pre><code>internal class EventManager<T>\n{\n private readonly Dictionary<int, Action<T>> events = new Dictionary<int, Action<T>>();\n\n public virtual void Subscribe(int incidentId, Action<T> action)\n {\n if (events.ContainsKey(incidentId))\n {\n events[incidentId] = action;\n }\n else\n {\n events.Add(incidentId, action);\n }\n }\n\n public virtual void Unsubscribe(int incidentId, Action<T> action)\n {\n if (events.ContainsKey(incidentId))\n {\n events[incidentId] -= action;\n }\n }\n\n public virtual void Trigger(int incidentId, T args)\n {\n if (events.ContainsKey(incidentId))\n {\n events[incidentId]?.Invoke(args);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T07:52:38.920",
"Id": "462477",
"Score": "0",
"body": "Nice and straightforward solution. I've considered it: the problem is that for each argument type I want to send I'd have to create new event manager... But there is no actual reason **not* to create 5-6 event managers instead of one, just convenience. Although there would be a problem if some event will require triggering all its subscribers regardless of argument type (send `default` data to all subscribers of event)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:54:13.250",
"Id": "462498",
"Score": "0",
"body": "@Xamtouo if your logic required initiating one instance and use it for concurrent events, then it'll be easy to just make it a singleton class. if some event requires triggering all its subscribers, then you would need to create another method to handle the `default`, and just expose it. As, the dictionary has the events already, you can do whatever you need. If you see there is a certain logic needs a concrete handler, then implement the handler and call it back from this instance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T01:21:46.753",
"Id": "236096",
"ParentId": "236070",
"Score": "4"
}
},
{
"body": "<p>Do you necessarily want to have one Event-Manager only ?</p>\n\n<p>If you would have <code>EventManager<t></code>, instead of 3 generic methods, you would have one Eventmanager by Type. It's already resolved at compile time, which dictionary to access.</p>\n\n<p>Today, <code>Trigger<int></code> and <code>Trigger<string></code> put their things in the same dictionary, which you need to subdivide by type.</p>\n\n<p>If you have <code>EventManager<T></code>, a call to Trigger would just insert in the dictionary, other Types would have other dictionaries.</p>\n\n<p>Something else:</p>\n\n<p>If you have influence on how your incidentID is used, you could use a little registry for this, and generate continuous numbers, you just have to define, where this number is used the first time. Doing so, you can safe the top-dictionary also, it would be just a full-length indexed array - very easy to access, very performant.\nAs a side effect you can also attach a string, to the incidentID, this makes debugging messages and exceptions more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T12:48:58.107",
"Id": "236113",
"ParentId": "236070",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:13:42.040",
"Id": "236070",
"Score": "6",
"Tags": [
"c#",
"design-patterns",
"comparative-review",
"event-handling",
"unity3d"
],
"Title": "C# Event Manager without allocations"
}
|
236070
|
<p>I've a string as an input which is having some specific patterns and I'm trying to parse it into a desired json. Here is my code:</p>
<pre><code>const input = "status:all,applied_date:2019-04-15--to--2019-04-15,screen_status:SR|NS";
const output = { and: {} };
const dateSeparator = RegExp("--to--");
function parseStr(str) {
const arr = str.split(",");
for (let i=0; i<arr.length; i++) {
findPattern(arr[i]);
}
console.log(JSON.stringify(output));
}
function findPattern(subStr) {
const subArr = subStr.split(":");
const newKey = subArr[0].replace("_", ".");
output["and"][newKey] = {};
if(dateSeparator.test(subArr[1])) {
output["and"][newKey]["between"] = subArr[1].split("--to--");
} else if(subArr[1].split("|").length > 1) {
output["and"][newKey]["inq"] = subArr[1].split("|");
} else {
output["and"][newKey]["eq"] = subArr[1];
}
}
parseStr(input);
</code></pre>
<p>I think my approach is very naive and it's not good for complex strings(e.g. deep nesting) and also the logic I've written cannot identify if the given input conform the patterns and will fail if wrong input is provided. </p>
<p>Is there any efficient way to parse strings like these? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T08:47:03.537",
"Id": "462696",
"Score": "0",
"body": "Does the current code work the way it should?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T21:02:56.707",
"Id": "463033",
"Score": "0",
"body": "To add to Mast's question, could you provide and example of the expected output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T18:50:00.273",
"Id": "463167",
"Score": "0",
"body": "@Mast It is working for the given input above but it is a specific implementation rather than a generic one which also have a downside when properties are nested. Also, the solution cannot identify if the given input conform the patterns and will fail in case of a wrong input."
}
] |
[
{
"body": "<p>I could have criticized the most lines of the initial approach in terms of <em>naming, relations, structuring and performance</em>, but I believe it should be completely rewritten.</p>\n\n<hr>\n\n<p>The optimized approach:</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 input = \"status:all,applied_date:2019-04-15--to--2019-04-15,screen_status:SR|NS\";\nconst dateSep = /--to--/;\n\n/**\n * Parse input string to build JSON representing \n a rule-set of AND clauses for SQL query.\n * The return value is JSON output.\n * @param {string} str - input string\n * @param {string} [entry_sep] - entry separator, defaults to \",\"\n */\nfunction strToAndClause(str, entry_sep = \",\") {\n let entries = str.split(entry_sep);\n let output = { and: {} },\n and_clause = output.and;\n \n entries.forEach((entry) => {\n let [key, val] = entry.split(\":\"), rule = {};\n key = key.replace(\"_\", \".\");\n and_clause[key] = rule;\n \n if (dateSep.test(val)) {\n rule.between = val.split(dateSep);\n } else if (val.indexOf(\"|\") !== -1) {\n rule.inq = val.split(\"|\");\n } else {\n rule.eq = val;\n }\n });\n return JSON.stringify(output);\n}\n\nconsole.log(strToAndClause(input));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T18:53:06.953",
"Id": "236078",
"ParentId": "236072",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:25:42.500",
"Id": "236072",
"Score": "2",
"Tags": [
"javascript",
"strings",
"json"
],
"Title": "Parsing a string with specific pattern into json"
}
|
236072
|
<h2>Background</h2>
<p>The code below is (obviously minimally) ripped out of a current live project. The project does reasonably sized data extraction, cleaning, analysis, clustering and visualisation (on a budget, and that's why we are not using graphistry or similar for the visualisation part). </p>
<p>So for our sins, we are using <a href="https://www.graphviz.org/" rel="nofollow noreferrer">graphviz</a>'s very mature <code>neato</code> engine which implements the Kamada Kawai algorithm which has been shown to work well for our purpose (after researching many many algorithms), although it does not scale very well. We chose to interface with graphviz rather than use the <a href="https://www.boost.org/doc/libs/1_72_0/libs/graph/doc/kamada_kawai_spring_layout.html" rel="nofollow noreferrer">Boost Graph Library</a>. (possibly a mistake). </p>
<p>For this code review I am going to focus on a slim slice, which is the <code>C++</code> wrapper class of the graphviz lib. And specifically on one aspect of that. How to sanely and safely interface with the many many <code>char*</code> params which the C-API expects. </p>
<h2>Your friend the <code>char*</code></h2>
<p>I have included the (slimmed down) wrapper class below together with an improvised <code>main()</code> to show usage. The wrapper just does RAII and "method => function shoveling". </p>
<p>Most of graphviz's API uses <code>char*</code>. Are they <code>const</code> (i.e. are they modified when we call their API)? Who knows. They don't appear to get modified, but without reading all their source, we can't know for sure. </p>
<p>Do we want <code>const std::string&</code> or <code>std::string_view</code> or even, at worst <code>const char*</code> APIs? Yes we do.</p>
<p>We pass in a bunch of string (sorry <code>char*</code>) constants for attributes and colour names etc, small sample below. </p>
<p>The code as shown works fine. It's messy, I don't like it, because it uses a bunch of C-Style casts to cast away the <code>constness</code>. Yes I could use <code>static_cast</code> or <code>reinterpret_cast</code> or <code>const_cast</code> for some of these cases. Very painful syntax. In this encapsulated API I choose the C-style casts for terseness. </p>
<h2>Is it safe and correct?</h2>
<p>What's worse is that I believe the behaviour is not super well defined when using <code>std:string_view</code>. I have chosen <code>std::string_view</code> as my C++-end API type for all those mini-strings. There are several possible alternatives, I tried a few, but this seems reasonable given I need to store C++-end tables of, for example, colour constants (see short extract in code). -- <code>std::string</code> seems like heavy overkill here. </p>
<p>But <code>std::string_view</code> should not be passed to a <code>char*</code> because it is not guaranteed to terminate with <code>'\0'</code>. -- maybe that's not UB, but it's potentially bad! So does that eliminate the otherwise possibly best solution we have in modern C++?</p>
<p>As I said it works fine, because <em>I know</em> that all the strings end with <code>'\0'</code>, but it doesn't make me happy. </p>
<h2>Feedback wanted.</h2>
<ul>
<li>General on legacy C-API encapsulation class</li>
<li>Specifically on this option and alternatives for the <code>char*</code> API - Is my best option to deal with <code>[const] char*</code> in C++ too, rather than <code>std::string_view</code>?</li>
</ul>
<pre><code>#include <cgraph.h> // these 2 includes are the graphiz cgraph lib
#include <gvc.h>
#include <array>
using size_t = std::size_t;
class Graph {
public:
Graph() {
gvc_ = gvContext();
static const char* fargv[] = {"neato", "-Tsvg"}; // NOLINT
gvParseArgs(gvc_, 2, (char**)fargv); // NOLINT
graph_ = agopen((char*)"g", Agundirected, nullptr); // NOLINT
// clang-format off
set_graph_attr_def("splines", "none");
set_graph_attr_def("ratio", "1.25");
set_node_attr_def("tooltip", "");
set_node_attr_def("fillcolor", "grey");
set_node_attr_def("shape", "point");
set_node_attr_def("width", "0.05");
set_node_attr_def("penwidth", "0");
set_edge_attr_def("weight", "1");
// clang-format on
}
Graph(const Graph& other) = delete;
Graph& operator=(const Graph& other) = delete;
Graph(Graph&& other) = delete;
Graph& operator=(Graph&& other) = delete;
~Graph() {
if (graph_ != nullptr) {
if (gvc_ != nullptr) gvFreeLayout(gvc_, graph_);
agclose(graph_);
}
if (gvc_ != nullptr) gvFreeContext(gvc_);
}
void set_graph_attr_def(std::string_view name, std::string_view value) {
agattr(graph_, AGRAPH, (char*)name.data(), (char*)value.data()); // NOLINT
}
void set_node_attr_def(std::string_view name, std::string_view value) {
agattr(graph_, AGNODE, (char*)name.data(), (char*)value.data()); // NOLINT
}
void set_edge_attr_def(std::string_view name, std::string_view value) {
agattr(graph_, AGEDGE, (char*)name.data(), (char*)value.data()); // NOLINT
}
void set_node_attr(Agnode_t* node, std::string_view name, std::string_view value) { // NOLINT
agset(node, (char*)name.data(), (char*)value.data()); // NOLINT
}
void set_edge_attr(Agedge_t* edge, std::string_view name, std::string_view value) { // NOLINT
agset(edge, (char*)name.data(), (char*)value.data()); // NOLIN
}
Agedge_t* add_edge(Agnode_t* src, Agnode_t* dest, std::string_view weight_str) {
auto edge = agedge(graph_, src, dest, nullptr, 1);
set_edge_attr(edge, "weight", weight_str);
return edge;
}
Agnode_t* add_node(std::string_view node_name) {
auto node = agnode(graph_, (char*)node_name.data(), 1); // NOLINT
set_node_attr(node, "tooltip", node_name);
return node;
}
void layout() {
gvLayoutJobs(gvc_, graph_);
}
void render() {
gvRenderJobs(gvc_, graph_);
}
private:
Agraph_t* graph_ = nullptr;
GVC_t* gvc_ = nullptr;
};
static constexpr const size_t max_colours = 30;
static constexpr const std::array<std::string_view, max_colours> colours = {
"blue", "green", "red", "gold",
"black", "magenta", "brown", "pink",
"khaki", "cyan", "tan", "blueviolet",
"burlywood", "cadetblue", "chartreuse", "chocolate",
"coral", "darkgoldenrod", "darkgreen", "darkkhaki",
"darkolivegreen", "darkorange", "darkorchid", "darksalmon",
"darkseagreen", "dodgerblue", "lavender", "mediumpurple",
"plum", "yellow"};
int main() {
auto graph = Graph{}; // initializes instace of a graphviz graph
// build node list by loading data from a mongo database
auto node1 = graph.add_node("1");
auto node2 = graph.add_node("2");
// ... 10,000 + nodes (that's all neato can handle, we would like more)
// 2.3 is the "weight" and it's a double in our code but graphiz wants a string
// there is a reason that the Graph::add_edge API takes the string
// the double -> string conversion is quite expensive (we use Ryu)
// and we need it twice. Once for graphviz and once for the cluster
// both as a string
graph.add_edge(node1, node2, "2.3");
//... 2 - 25 million edges
// run clustering algorithm on separate thread
graph.layout(); // graphviz neato: slowest part of whole program
// clustering has finished by now, update the colours
graph.set_node_attr(node1, "fillcolor", colours[0]); // NOLINT
graph.set_node_attr(node1, "fillcolor", colours[1]); // NOLINT
// ...
graph.render(); // sends svg to stdout
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:55:59.303",
"Id": "462393",
"Score": "0",
"body": "Can you provide a link to where I can get the header files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T17:14:42.057",
"Id": "462394",
"Score": "0",
"body": "http://graphviz.org/download/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T13:07:49.847",
"Id": "462507",
"Score": "0",
"body": "The graph class is following a Facade Pattern, you can do real conversions within each function, up to and including char* = new char[type.size+];."
}
] |
[
{
"body": "<p>Basically the code is well thought out and written.</p>\n\n<p>A major observation about the code is that it is totally focused on performance/speed of execution, and not very flexible or extensible. A user of the graph class may want to add arguments to the <code>argv</code> through a call to a member function or an alternate version of the constructor that accepts a list of arguments. Hard coding the number of arguments in <code>arvg</code> (farvg) makes this impossible. It is very easy to calculate <code>argc</code> from <code>argv</code>:</p>\n\n<pre><code> gvParseArgs(gvc_, sizeof(fargv)/ sizeof(*fargv), (char**)fargv); // NOLINT\n</code></pre>\n\n<p>The variable <code>fargv</code> might be made into a class member variable to allow extensibility.</p>\n\n<p>The use of <code>std::array</code> over <code>std::vector</code> is another place where the code is not extensible. The use of <code>std::array</code> also forces the creation of a constant that is only used in the initialization of the array. I understand that the use of <code>std::vector</code> prevents the use of <code>constexpr</code> but I value extensibility over optimization. Some of us old school programs say that the first rule of optimization is <em>don't</em>. The real first rule is find the bottle necks before optimizing. </p>\n\n<h2>Minor Nit</h2>\n\n<p>I generally put the closing <code>};</code> of an std::array or std::vector initialization on a new line that is indented to the beginning of the array, it makes it a little more readable and easier to edit.</p>\n\n<pre><code>static const std::vector<std::string_view> colours = {\n \"blue\", \"green\", \"red\", \"gold\",\n \"black\", \"magenta\", \"brown\", \"pink\",\n \"khaki\", \"cyan\", \"tan\", \"blueviolet\",\n \"burlywood\", \"cadetblue\", \"chartreuse\", \"chocolate\",\n \"coral\", \"darkgoldenrod\", \"darkgreen\", \"darkkhaki\",\n \"darkolivegreen\", \"darkorange\", \"darkorchid\", \"darksalmon\",\n \"darkseagreen\", \"dodgerblue\", \"lavender\", \"mediumpurple\",\n \"plum\", \"yellow\"\n};\n</code></pre>\n\n<h2>Missing Header</h2>\n\n<p>Somehow <code>#include <string_view></code> seems to have been dropped from the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:23:57.547",
"Id": "462407",
"Score": "1",
"body": "Thanks for your feedback. Which `#include` is missing? Your points are well made. Clearly the `fargs` thing is almost a \"hack\". The `cgraph` lib is tightly coupled to their command line programmes (`dot`, `neato` etc). So the way you \"configure\" the main instance is you call `gvParseArgs`. I find it a bit weird..?! Anyway my wrapper is not designed to be run by the user with command line args etc. It's spawned from another process and the mongodb query is piped in json format, etc etc. the real `argv[]` is not for graphviz. But that's what the lib gives me. So I hacked it for what I need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:27:02.090",
"Id": "462409",
"Score": "0",
"body": "I actually wasn't focused on performance. Well I am, but only in the very inner loop, which creates edges (2-250million of them). So you are suggesting that I should store the 200+ little colour constants (above is just an extract) in a `std::vector<std::string>` ? As a static class member and then make the method APIs what? `std::string_view` or `const std::string&`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:27:23.667",
"Id": "462410",
"Score": "0",
"body": "many thanks for the #include...sorry about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:29:18.120",
"Id": "462411",
"Score": "0",
"body": "I would find it very difficult to count 200+ colors (us) and create a constant for them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:29:51.720",
"Id": "462412",
"Score": "0",
"body": "I can email you the list if you like....they exist... :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:33:50.783",
"Id": "462413",
"Score": "1",
"body": "Thanks, but that would be a bit much. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:34:30.243",
"Id": "462414",
"Score": "0",
"body": "But the main point is: What do we use? full `std::string` 's or `string literals` where appropriate. And how do we pass them to our C++ API: `std::string_view` `const std::string&` or `const char*`. Then how do we cast them to squeeze them into C's `char*`. What is the best \"cast\". Is it safe (null terminator, is it really `const` in the \"C\" lib etc). In my mind these are all, quite mundane and nit-picky questions, but they sort of matter. And they matter for anyone interfacing with \"C\". That's why I posted this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:39:24.670",
"Id": "462415",
"Score": "0",
"body": "If you pass const std::string& into the API you could use std::string.c_str() to get the const char *ptr. This would take care of the null termination as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:54:03.723",
"Id": "462416",
"Score": "0",
"body": "Yes, halfway. It requires instantiating a static vector of 200 colour constants - feels crazy, but you're right, it shouldn't maybe... then I pass eveything as std::string on C++ side and it enters Graph API as `const std::string&` (has to be this so it will accept a literal const rvalue ref). Then I call c_str() and it's `const` => need to cast it to `unconst`. You can call `.data()` which is `non-const` but it's only `non-const` if the std::string is `non-const`..except it is. so then we have this https://godbolt.org/z/MWmLHP and we still haven't solved it..without a potentially UB cast?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:58:28.257",
"Id": "462418",
"Score": "0",
"body": "OH, re the brace positon. I don't disagree... But I use .clang-format, have tuned it to \"close enough\"..and it does it's thing. I format very few things by hand. I am too old for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:58:38.023",
"Id": "462419",
"Score": "0",
"body": "I don't know what I can add but we can discuss it on https://chat.stackexchange.com/rooms/8595/the-2nd-monitor if you want."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:17:05.773",
"Id": "236079",
"ParentId": "236073",
"Score": "3"
}
},
{
"body": "<p>I see a few things that may help you improve your program.</p>\n\n<h2>Reconsider the tool</h2>\n\n<p>The <code>graphviz</code> package seems designed for more human-scale output graphics than your project is intending to use. The problem, as you have discovered, is that the layout does not scale linearly with the number of nodes, so your desire to process more than 10,000 nodes and millions of edges might not be a good match for <code>graphviz</code>, or for human consumption as a single diagram. Might GIS software such as GRASS or QGIS might be more appropriate for your use?</p>\n\n<h2>Use a different layout engine</h2>\n\n<p>The <code>neato</code> engine has limitations that the <code>sfdp</code> engine does not. If you change </p>\n\n<pre><code>static const char* fargv[] = {\"neato\", \"-Tsvg\"}; // NOLINT\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>static const char* fargv[] = {\"sfdp\", \"-Tsvg\"}; // NOLINT\n</code></pre>\n\n<p>the layout will be a bit different, but perhaps still acceptable and likely faster.</p>\n\n<h2>Check the fine print</h2>\n\n<p>You may already be aware, but in fact, the <code>dot</code> requires the <a href=\"http://graphviz.org/doc/info/attrs.html#d:weight\" rel=\"nofollow noreferrer\">weights to be integer values</a>. For the reasons mentioned in the comments of your code, you may not want to change anything anyway, but it's probably useful to be aware of it and maybe also insert a comment saying \"yes, I know\" if that's the case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:49:16.807",
"Id": "462669",
"Score": "0",
"body": "thanks! I tried `sfdp` it's much faster than `neato`, but the layout is next to useless for our purposes. I haven't tried \"geo type\" type software as this is not geo info, and I didn't make this link. This is company data, for researchers to spot clusters of companies. Not sure if that will fit, but I'll look into it. We looked at `open-ord`, which is very fast, but useless layout for us. Fruchterman-Reingold is good, but not faster than Kamada Kawai (neato)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:53:07.173",
"Id": "462670",
"Score": "0",
"body": "We can \"layout, cluster and render\" 10,000 nodes in a \"reasonable\" < 1min for the complete process. So what we do when we have more data, is we \"random sample it\" and then \"zoom in on interesting clusters\". I agree the docs say \"`dot` expects integers\" , but `neato` seems to work well with `float`s. Is there a possible performance gain with `int`s? I don't know, haven't tried that. But I am always open to new ideas for engines. The clustering algo we use is written in java and it is lightning fast. So we just call it with `pstream`. No point rewriting it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:54:02.440",
"Id": "462672",
"Score": "0",
"body": "This post here was mostly about the annoying `char*` interface. And I solved that after getting some ideas from SO: See comments under here: https://stackoverflow.com/questions/59902007/c-wrapper-for-c-api-exploring-best-options-for-passing-char/59903547#59903547"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T23:11:12.973",
"Id": "462673",
"Score": "1",
"body": "I tried it and noticed no difference with integers vs. float with `neato` in terms of either layout or performance, but I didn't look very closely. As for the suspected UB, it seemed to me that you have a usable answer. I'd consider re-implementing the Kamanda Kawai algorithm if performance is critical and `graphviz` is not delivering. Like you, I generally prefer to recycle rather than reimplement, but sometimes it's needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T23:15:43.027",
"Id": "462674",
"Score": "1",
"body": "Yes, many thanks for your time. I am currently looking into Boost graph who have a Kamada Kawei implementation. And there is some quite new research (from Asia I think) which seems to suggest that by chaining several of the historically known algorithms(tweaked a bit) you can get a 2 orders of magnitude gain. That would be great, but of course the whole thing is bascically O(n^2) so 2 orders is actually just 1, but still!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:36:27.203",
"Id": "236175",
"ParentId": "236073",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236175",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:35:58.257",
"Id": "236073",
"Score": "7",
"Tags": [
"c++",
"strings",
"api"
],
"Title": "C++ wrapper for graphviz library"
}
|
236073
|
<p>I'm relatively new to programming as I've just started university. My assignment was to develop a program (by using a function and a linked list with pointers with integer elements) which does the following:</p>
<ul>
<li>The function visits every element from the beginning. If the current element plus one is <= to the following element (e.g. if the first one is i and the second one is j, j>=i+1), you have to complete the list by adding all the values between i and j-1.</li>
<li>If the current element is followed by an element <=, it is to be removed by the list and added to an array declared in the formal parameters. You also have to put in the formal parameters a counter for the deleted elements.</li>
</ul>
<p>I had already asked a <a href="https://stackoverflow.com/questions/59787830/crash-with-0xc0000005-on-my-list-based-program">question</a> about this function since I couldn't get it to work, but using recursive functions I finally made it. I would now like to know how I might improve it! Sorry if I made any grammar mistakes, English is not my native language.</p>
<p>I left all the comments I made about how each function works.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
// list declaration
struct list {
int value;
struct list * next_ptr; };
// pre_insert function.
void pre_insert(struct list ** ptrptr, int value) {
struct list * tmp_ptr;
tmp_ptr = *ptrptr;
*ptrptr = malloc(sizeof(struct list));
(*ptrptr)->value = value;
(*ptrptr)->next_ptr = tmp_ptr;
}
// if the following item is bigger than the current one, a call to this function inserts all the items missing between the two values.
// the cost of this function is T(N) = c * (N-1) (because of the while loop).
void succ_value_bigger(struct list * ptr) {
while (ptr->value + 1 < ptr->next_ptr->value)
pre_insert(&ptr->next_ptr, ptr->next_ptr->value-1);
}
// if succ_value_smaller is called by complete_list_to_array, this function deletes the item following the one pointed by ptr.
// the function has linear cost as there are no iterations.
int delete_element (struct list * succ_ptr, int * V, int k) {
V[k] = succ_ptr->value;
free(succ_ptr);
return k;
}
// if i value is bigger than the following one, complete_list_to_array calls this function.
// the function deletes the following element using a call to delete_element function, then increases both count and k.
// the first one counts the deleted elements, the second one is an index for the array V collecting all the deleted elements.
// the function has a recursive behaviour, calling main function complete_list_to_array for the following element to be confronted with i.
// the function has cost T(N) = c1*N + c2 (since the else guard only works for the last item).
int succ_value_smaller(struct list * ptr, int * V, int * count, int k) {
struct list *succ_ptr = ptr->next_ptr;
// the guard sees if the current item isn't the last one. if so, it sends the flow to else, below.
// if it is not the case, it deletes the following element and increases the indexes.
if (succ_ptr->next_ptr != NULL)
{
ptr->next_ptr = succ_ptr->next_ptr;
delete_element(succ_ptr, V, k);
k++;
(*count)++;
// after doing so, it calls recursively to complete_list_to_array,
// so that the current item is confronted with its new following element.
// the returned value is *count.
(*count) = complete_list_to_array(ptr, V, count, k);
}
else {
// if the flow is sent here, it means the list has arrived at its last item, after the current one.
// the succ_ptr->next_ptr pointer will so point to NULL, indicating the list has reached its end.
// as above, the following item is deleted and count increased. The k index, though, has no need to
// as it's the last time an element will be inserted in the array V.
ptr->next_ptr = NULL;
delete_element(succ_ptr, V, k);
(*count)++;
}
return (*count);
}
// complete_list_to_array is the main recursive function of the program. Getting its data directly from main(),
// it uses while both as a loop and as a guard, checking each time if the list has reached its end or its last element.
// the function has cost T(N) = c1 if N == 2 || c1*N + T(N-1) if N > 2
int complete_list_to_array(struct list * ptr, int * V, int * count, int k) {
struct list * succ_ptr;
while (ptr != NULL)
{
if(ptr->next_ptr != NULL)
{
succ_ptr = ptr->next_ptr;
// if the following element is bigger than the current element plus one, it sends
// the flow to function succ_value_bigger and slides ptr to its following pointer.
if(ptr->value + 1 <= succ_ptr->value) {
succ_value_bigger(ptr);
ptr = ptr->next_ptr;
}
// if the following element is smaller than the current, it increases the index *count as return value
//and sends the flow to succ_value_smaller, then slides ptr to the following pointer.
else if (succ_ptr->value <= ptr->value)
{
(*count) = succ_value_smaller(ptr, V, count, k);
if (ptr->next_ptr != NULL)
ptr = ptr->next_ptr;
else
ptr->next_ptr = NULL;
}
}
// if the list only has one item, the flow is sent here. The break instruction sends the flow to the following
// instruction, and is widely used to change the flow in switch iterations.
else break;
}
return (*count);
}
// the following function creates the list which will then be used in the function. It uses two pointers, one to the
// first item, which is the return value (so that the main() function can begin its work from the first item), and
// a general pointer which is slid each time a value is inserted, according to the number N of items in the list.
struct list * create_list(int N) {
struct list * first_ptr, * ptr;
int i;
// if the list contains 0 elements (N == 0) the first pointer will point to NULL, contained in the memory.h library.
if(N == 0) {
first_ptr = NULL;
}
else {
first_ptr = malloc(sizeof(struct list));
printf("Insert the first value:\n");
scanf("%d", &first_ptr->value);
ptr = first_ptr;
for(i = 2; i <= N; i++) {
ptr->next_ptr = malloc(sizeof(struct list));
ptr = ptr->next_ptr;
printf("Insert element number %d:\n", i);
scanf("%d", &ptr->value);
}
ptr->next_ptr = NULL;
}
return(first_ptr);
}
// this simple function prints all the items contained in the list. It uses a while loop until the list
// has reached its last element.
void visit(struct list * ptr) {
int i = 1;
while(ptr != NULL) {
printf("Item number %d in the list has value %d.\n", i, ptr->value);
ptr = ptr->next_ptr;
i++;
}
}
// main function
int main(void) {
// variables declaration and dynamic allocation of the array.
struct list * first_ptr;
int N, k = 0;
int i;
int * V, count = 0;
V = (int *)malloc(sizeof(int)*count);
// choice of the dimension of the list.
printf("Insert the number of elements in the list.\n");
scanf("%d", &N);
// call to create_list function.
first_ptr = create_list(N);
printf("\n----------------------------\n\n");
// call to visit function in order to print the items initally contained in the list.
printf("At the beginning, the list contained the following items:\n\n");
visit(first_ptr);
printf("\n----------------------------\n\n");
// call to complete_list_to_array function, using first_ptr so that it begins from the first item
// and count's address, as the list requires in its formal parameters a pointer to int.
count = complete_list_to_array(first_ptr, V, &count, k);
// results after the flow returns from the function to main(). It first tells the user which and how many items
// have been removed (if count == 0 it skips the first step), then prints the modified list.
printf("After the function call, the following items have been removed from the list and put into the array:\n\n");
if(count == 0) {
printf("No item has been removed from the list.\n");
}
else {
for(i = 0; i < count; i++) {
printf("The value of V[%d] is: %d.\n", i, V[i]); }
printf("\nThe total number of removed elements is %d.\n", count);
}
// using function free(void *), the memory section occupied by array V, which was first allocated with
// library <stdlib.h>'s function malloc. This way, the allocated section for V is freed from the memory.
free(V);
printf("\n----------------------------\n\n");
printf("After the function call, the list contains the following items:\n\n");
visit(first_ptr);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>On my computer while the program runs and gives answers it still terminates with 0xC0000005 which means the memory problem is still there but it no longer stops the program.</p>\n\n<p>The type of recursion you are using, where 2 functions (<code>int succ_value_smaller(struct list * ptr, int * V, int * count, int k)</code> and <code>int complete_list_to_array(struct list * ptr, int * V, int * count, int k)</code>) call each other, is sometimes called Figure Eight recursion and was used in earlier forms of Fortran because Fortran did not support recursion directly. It is not something I would really recommend when programming in C, it is very difficult to program correctly, debug and maintain.</p>\n\n<h2>Self Documenting Code</h2>\n\n<p>Commenting code is ok, but it should be kept to a minimum. When comments are included in the code they need to be maintained as well as the code to keep the comments in sync with the code, this adds overhead to maintenance. Good comments provide very high level information about why something is done, and wouldn't comment at lower levels of the code. It's also not clear why the cost of each function is documented, but that may be required for a homework assignment. It is better to make the function names and variable names as clear as possible. </p>\n\n<p>It might be better to avoid abbreviations such as <code>succ_</code>, since it isn't quite clear what it means. It also isn't quite clear why the function <code>void pre_insert(struct list ** ptrptr, int value)</code> is called <code>pre_instert</code> since it is in fact doing the insertion.</p>\n\n<h2>Variable Declarations and Initialization</h2>\n\n<p>In the original version of the C programming language (sometimes referred to as K&R C) all variables needed to be declared at the top of the function, this is no longer true, it is better to declare variables as they are needed, for instance in main there is <code>int i;</code> at the top of the function but <code>i</code> is only used in a <code>for</code> loop at the end of <code>main()</code>. The variable <code>i</code> can be declared in the <code>for</code> loop itself: </p>\n\n<pre><code> for(int i = 0; i < count; i++) {\n printf(\"The value of V[%d] is: %d.\\n\", i, V[i]);\n }\n</code></pre>\n\n<p>The variable <code>k</code> can also be declared later in <code>main()</code></p>\n\n<pre><code> int k = 0;\n count = complete_list_to_array(first_ptr, V, &count, k);\n</code></pre>\n\n<p>The variable name <code>k</code> doesn't really indicate what k is used for, and it is never changed in the body of <code>main()</code>.</p>\n\n<p>When using the C programming language it is best to initialize all variables when they are declared. Some programming languages initialize variables to a default, such as setting an integer value to 0, the C programming language is not one of them and it is quite easy to use a variable without initializing it, which can lead to bugs. So rather than the following at the top of <code>main()</code></p>\n\n<pre><code>int main(void) {\n\n // variables declaration and dynamic allocation of the array.\n\n struct list * first_ptr;\n int N, k = 0;\n int i;\n int * V, count = 0;\n</code></pre>\n\n<p>It would be better to write the code this way</p>\n\n<pre><code>int main(void) {\n\n // variables declaration and dynamic allocation of the array.\n\n struct list * first_ptr = NULL;\n int N = 0;\n int *V = NULL;\n int count = 0;\n\n V = (int *)malloc(sizeof(int)*count);\n</code></pre>\n\n<p><em>This shows us the first bug in the program, since <code>count</code> is zero the call to <code>malloc(size_t size)</code> fails because <code>zero * sizeof(int)</code> is zero. It is probably what caused the 0xC0000005 problem.</em> </p>\n\n<h2>Bug</h2>\n\n<p>As pointed out above, the variable <code>V</code> is <code>NULL</code> and this leads to unknown behavior (bug). It might be better to use the variable <code>N</code> after the user has entered it.</p>\n\n<pre><code> printf(\"Insert the number of elements in the list.\\n\");\n scanf(\"%d\", &N);\n if (N > 0)\n {\n V = malloc(sizeof(int)*N);\n if (V == NULL)\n {\n fprintf(stderr, \"Failed to allocate the memory for the integer array V\\n\");\n return EXIT_FAILURE;\n }\n }\n else\n {\n fprintf(stderr, \"The number of elements in the list must be greater than 0.\\n\");\n return EXIT_FAILURE;\n }\n</code></pre>\n\n<h2>Error Checking and Preventing Bugs</h2>\n\n<p>There are 2 types of error checking that need to be implemented in this program. The first is to make sure user input is valid and the second is to make sure there are not memory allocation errors.</p>\n\n<p>The function <code>scanf()</code> can fail in a number of ways. <code>scanf()</code> returns an integer value that indicates the success or failure of the call, if the number is greater than zero then <code>scanf()</code> succeeded, if the number is <code>EOF</code> or zero than <code>scanf()</code> failed. The user can also enter an invalid value and that needs to be checked.</p>\n\n<p>The memory allocation functions <code>void *malloc(size_t size)</code>, <code>void *calloc(size_t count, size_t size)</code> and <code>void *realloc( void *ptr, size_t new_size )</code> can also fail for various reasons, although it is rare today do to the size of RAM on computers. If these functions fail they return <code>NULL</code>. Access through a null pointer yields unknown behavior, the easiest to see is the program crashing, data can also be corrupted which can be harder to detect. For this reason the return value of any of these functions should be tested to prevent invalid memory access (segmentation violation and other problems).</p>\n\n<p>Putting these 2 error checks together:</p>\n\n<pre><code>void scanf_failure()\n{\n fprintf(stderr, \"scanf() failed getting the number of elements in the list.\\n\");\n exit(EXIT_FAILURE);\n}\n\nint get_number_of_elements()\n{\n int element_count = 0;\n\n printf(\"Insert the number of elements in the list.\\n\");\n int test_tnput_count = scanf(\"%d\", &element_count);\n if (test_tnput_count != EOF && test_tnput_count > 0)\n {\n while (element_count <= 0)\n {\n fprintf(stderr, \"The number of elements must be greater than zero.\\n\");\n test_tnput_count = scanf(\"%d\", &element_count);\n if (test_tnput_count == EOF || test_tnput_count <= 0)\n {\n scanf_failure();\n }\n }\n }\n else\n {\n scanf_failure();\n }\n\n return element_count;\n}\n\nint main(void) {\n struct list * first_ptr = NULL;\n int N = 0;\n int *V = NULL;\n int count = 0;\n\n N = get_number_of_elements();\n V = malloc(sizeof(int)*N);\n if (V == NULL)\n {\n fprintf(stderr, \"Failed to allocate the memory for the integer array V\\n\");\n return EXIT_FAILURE;\n }\n\n ...\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The rest of this review is copied from my answer to your question on <a href=\"https://stackoverflow.com/questions/59787830/crash-with-0xc0000005-on-my-list-based-program/59792376#59792376\">Stack Overflow</a></p>\n\n<h2>Prefer <code>calloc</code> Over <code>malloc</code> for Arrays</h2>\n\n<p>There are 3 major allocation function in the C programming language, they are <code>void *malloc(size_t size_to_allocate)</code>, <a href=\"https://en.cppreference.com/w/c/memory/calloc\" rel=\"nofollow noreferrer\">void* calloc( size_t number_of_items, size_t item_size )</a> and <a href=\"https://en.cppreference.com/w/c/memory/realloc\" rel=\"nofollow noreferrer\">void *realloc( void *ptr, size_t new_size )</a>. The best for initially allocating arrays is <code>calloc</code> because it clearly shows that you are allocating an array, and because it zeros out the memory that is being allocated.</p>\n\n<h2>Functions Should Return Values</h2>\n\n<p>Rather than passing in a pointer to a pointer to get a new pointer value the <code>pre_insert(struct list * ptrptr, int value)</code> function should return the new pointer.</p>\n\n<pre><code>struct list* pre_insert(struct list * ptrptr, int value) {\n struct list * tmp_ptr;\n\n tmp_ptr = ptrptr;\n ptrptr = NewPtr(value);\n if (tmp_ptr)\n {\n ptrptr->next_ptr = tmp_ptr;\n }\n\n return ptrptr;\n}\n</code></pre>\n\n<h2>Missing Linked List Functions</h2>\n\n<p>There are a standard set of linked list functions that should be implemented, these are</p>\n\n<ul>\n<li>create Node (shown above as <code>*NewPtr(int value)</code>) </li>\n<li>Insert Node </li>\n<li>Append Node </li>\n<li>Delete Node </li>\n<li>Find Node </li>\n</ul>\n\n<p>Using these common linked list functions would make it much easier to implement the larger problem solution.</p>\n\n<h2>Complexity</h2>\n\n<p>If I was going to review this on code review, the first thing that I would suggest is that the function <code>int complete_list_array(struct list * ptr, int * V, int * count)</code> is too complex, this means it is doing too much in a single function. It would be easier for you to write/debug this if the contents of each of the internal if's was a function.</p>\n\n<p>There are 2 concepts to consider here, the first is top down design and the second is the Single Responsibility Principle. <a href=\"https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design\" rel=\"nofollow noreferrer\">Top down design</a> is where you keep breaking the problem into smaller and smaller pieces until each piece is very easy to implement. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T15:40:21.833",
"Id": "462616",
"Score": "1",
"body": "Thank you so much for such a detailed reply. Just wanted to clarify, regarding the name 'pre_insert', the long comments and the cost of the functions. For the first one, it was a function that our professor made us call \"pre_insert\" and won't accept anything else, even if, i know, it just inserts values. For the long comments and the functions' costs, yes, it was all homework stuff that i had to put in my code for my exam. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T17:58:06.433",
"Id": "236126",
"ParentId": "236077",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236126",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T18:51:15.837",
"Id": "236077",
"Score": "2",
"Tags": [
"beginner",
"c"
],
"Title": "Linked list: adding/deleting nodes according to value"
}
|
236077
|
<p>After discovering <a href="http://evanw.github.io/float-toy/" rel="nofollow noreferrer">Float Toy</a>, my goal was to create my own version using Python and Tkinter. The results of the endeavor is shown below. Most of the functionality is complete, but the <code>Equation</code> widget does not automatically update itself yet. Does anyone have any simple suggestions for updating its labels?</p>
<pre><code>#! /usr/bin/env python3
# http://evanw.github.io/float-toy/
import struct
import tkinter.ttk
from tkinter.constants import *
class FloatToy(tkinter.ttk.Frame):
@classmethod
def main(cls):
tkinter.NoDefaultRoot()
root = tkinter.Tk()
cls.create_styles(root)
root.title('Float Toy')
root.resizable(False, False)
toy = cls(root)
toy.grid()
root.mainloop()
@staticmethod
def create_styles(root):
style = tkinter.ttk.Style(root)
style.configure('S.TButton', background='#88F')
style.configure('E.TButton', background='#8F8')
style.configure('F.TButton', background='#F88')
style.configure('S.TLabel', background='#CCF')
style.configure('E.TLabel', background='#CFC')
style.configure('F.TLabel', background='#FCC')
def __init__(self, master=None, **kw):
super().__init__(master, **kw)
self.instructions = tkinter.ttk.Label(self)
self.example_32 = Example(32, self)
self.example_64 = Example(64, self)
self.configure_all()
self.grid_all()
def configure_all(self):
self.instructions['text'] = 'Click on a cell below to toggle bit ' \
'values. Use this to build intuition ' \
'for the IEEE float-point format.'
def grid_all(self):
self.instructions.grid(padx=5, pady=5, sticky=W)
self.example_32.grid(padx=5, pady=5, sticky=W)
self.example_64.grid(padx=5, pady=5, sticky=W)
class Example(tkinter.ttk.Labelframe):
def __init__(self, width, master=None, **kw):
kw['text'] = f'{width}-bit (float)'
super().__init__(master, **kw)
self.float = tkinter.DoubleVar(self)
self.bits = Bits(width, self.float, self)
self.equals = tkinter.ttk.Label(self)
self.equation = Equation(width, self.float, self)
self.configure_all()
self.grid_all()
def configure_all(self):
self.float.trace_add('write', self.update_equals)
self.float.set(1.0)
def update_equals(self, *_):
self.equals.configure(text=f' = {self.float.get()}')
def grid_all(self):
self.bits.grid(row=0, column=0, sticky=W)
self.equals.grid(row=0, column=1, sticky=W)
self.equation.grid(row=1, column=0, columnspan=2, sticky=W)
class Bits(tkinter.ttk.Frame):
STYLE_RULES = {
32: {
range(0, 1): 'S',
range(1, 9): 'E',
range(9, 33): 'F'
},
64: {
range(0, 1): 'S',
range(1, 12): 'E',
range(12, 65): 'F'
}
}
STRUCT_RULES = {
31: lambda bits: struct.unpack('>f', struct.pack('>L', bits))[0],
63: lambda bits: struct.unpack('>d', struct.pack('>Q', bits))[0]
}
def __init__(self, width, var, master=None, **kw):
super().__init__(master, **kw)
self.buttons = [tkinter.ttk.Button(self) for _ in range(width)]
self.var = var
self.configure_all()
self.grid_all()
def configure_all(self):
for column, button in enumerate(self.buttons):
button.configure(text='0', width=1, style=self.get_style(column),
command=self.get_command(column))
def get_style(self, column):
for key, value in self.STYLE_RULES[len(self.buttons)].items():
if column in key:
return f'{value}.TButton'
raise KeyError(f'column {column} has no style')
def get_command(self, column):
return lambda: self.toggle_bit(column)
def toggle_bit(self, column):
button = self.buttons[column]
button['text'] = int(not int(button['text']))
self.update_var()
def update_var(self):
bits = index = 0
for index, button in enumerate(reversed(self.buttons)):
bits |= int(button['text']) << index
self.var.set(self.STRUCT_RULES[index](bits))
def grid_all(self):
for column, button in enumerate(self.buttons):
button.grid(row=0, column=column)
class Equation(tkinter.ttk.Frame):
def __init__(self, width, var, master=None, **kw):
super().__init__(master, **kw)
self.width = width
self.var = var
self.sign = tkinter.ttk.Label(self)
self.times_1 = tkinter.ttk.Label(self)
self.exponent = tkinter.ttk.Label(self)
self.times_2 = tkinter.ttk.Label(self)
self.fraction = tkinter.ttk.Label(self)
self.configure_all()
self.grid_all()
def configure_all(self):
self.sign.configure(text='1', style='S.TLabel')
self.times_1.configure(text='×')
self.exponent.configure(text='2 ** 0', style='E.TLabel')
self.times_2.configure(text='×')
self.fraction.configure(text='1', style='F.TLabel')
def grid_all(self):
self.sign.grid(row=0, column=0, padx=5, pady=5)
self.times_1.grid(row=0, column=1, padx=5, pady=5)
self.exponent.grid(row=0, column=2, padx=5, pady=5)
self.times_2.grid(row=0, column=3, padx=5, pady=5)
self.fraction.grid(row=0, column=4, padx=5, pady=5)
if __name__ == '__main__':
FloatToy.main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T19:54:53.447",
"Id": "236081",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"tkinter",
"floating-point"
],
"Title": "Suggestions on how to update equation?"
}
|
236081
|
<h1>Problem</h1>
<p>I am trying to convert my synchronous code to an asynchronous implementation. Using <code>aiohttp</code> I was able to almost get where I want. My problem is how to deal with <em>synchronous</em> requests. I have 3 types of functions:</p>
<ol>
<li>Take argument, make <em>one</em> request (easy to turn async)</li>
<li>Take argument, make <em>multiple, independent</em> requests (easy to turn async as requests are independent)</li>
<li>Take argument, make <em>multiple, dependent</em> requests (problematic because I need to wait for the first response before making the second request)</li>
</ol>
<p>I managed to come up with something but I am uncertain whether the two requests in <code>async_file.f2</code> are done synchronously (that is the second has to wait for the first to yield a response). Also, further constructive criticism is always welcomed.</p>
<h1>Code</h1>
<p><code>Python 3.8.0 [MSC v.1916 64 bit (AMD64)] on win 32</code></p>
<p><strong>master</strong></p>
<pre class="lang-py prettyprint-override"><code>master = {
"f0": {
"a": {
"url": "https://example.com",
"method": "get"
}
},
"f1": {
"a": {
"url": ["https://example.com", "https://example.com"],
"method": ["get", "get"]
}
},
"f2": {
"a": {
"url": ["https://example.com", "https://example.com"],
"method": ["post", "get"]
}
}
}
</code></pre>
<p><strong>sync_file</strong></p>
<pre><code>import requests
from typing import List
from master import master
def f0(key: str) -> str:
method = master["f0"][key]["method"]
url = master["f0"][key]["url"]
return requests.request(method, url).text
def f1(key: str) -> List[str]:
method_0, method_1 = master["f1"][key]["method"]
url_0, url_1 = master["f1"][key]["url"]
return [requests.request(method_0, url_0).text, requests.request(method_1, url_1).text]
def f2(key: str) -> str:
method_0, method_1 = master["f2"][key]["method"]
url_0, url_1 = master["f2"][key]["url"]
response = requests.request(method_0, url_0)
return requests.request(method_1, url_1, data=response.text).text
def main(key: str):
res = []
for f in (f0, f1, f2):
res.append(f(key=key))
return res
if __name__ == '__main__':
test = main("a")
print(f"test: [{', '.join(type(_).__name__ for _ in test)}]")
# test: [str, list, str]
</code></pre>
<p><strong>async_file</strong></p>
<pre class="lang-py prettyprint-override"><code>import aiohttp
import asyncio
from typing import List
from master import master
async def f0(key: str) -> str:
method = master["f0"][key]["method"]
url = master["f0"][key]["url"]
session = aiohttp.ClientSession()
print('f0: request', flush=True)
async with session.request(method, url) as response:
text = await response.text()
print('f0: response', flush=True)
await session.close()
return text
async def f1(key: str) -> List[str]:
method_0, method_1 = master["f1"][key]["method"]
url_0, url_1 = master["f1"][key]["url"]
session = aiohttp.ClientSession()
print('f1: request', flush=True)
async with session.request(method_0, url_0) as response:
text_0 = await response.text()
print('f1: response', flush=True)
print('f1: request', flush=True)
async with session.request(method_1, url_1) as response:
text_1 = await response.text()
print('f1: response', flush=True)
await session.close()
return [text_0, text_1]
async def f2(key: str) -> str:
method_0, method_1 = master["f2"][key]["method"]
url_0, url_1 = master["f2"][key]["url"]
session = aiohttp.ClientSession()
print('f2: request', flush=True)
async with session.request(method_0, url_0) as response:
text_0 = await response.text()
print('f2: response', flush=True)
print('f2: request', flush=True)
async with session.request(method_1, url_1, data=text_0) as response:
text_1 = await response.text()
print('f2: response', flush=True)
await session.close()
return text_1
async def run(key: str):
tasks = []
for f in (f0, f1, f2):
task = asyncio.ensure_future(f(key))
tasks.append(task)
return await asyncio.gather(*tasks)
def main(key: str):
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(key))
return loop.run_until_complete(future)
if __name__ == '__main__':
test = main("a")
print(f"test: [{', '.join(type(_).__name__ for _ in test)}]")
# test: [str, list, str]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:24:52.410",
"Id": "462422",
"Score": "0",
"body": "Welcome, why `f0, f1, f2 ...` ? Is that pseudo-code, meaning that all reviewers are prevented (should ignore) from pointing to naming issues?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:28:42.697",
"Id": "462423",
"Score": "0",
"body": "Hi @RomanPerekhrest, yes, I used these generic names for simplicity - pointing to naming issues may be omitted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:29:16.040",
"Id": "462424",
"Score": "1",
"body": "What's your Python version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:23:47.627",
"Id": "462492",
"Score": "0",
"body": "@RomanPerekhrest I'm running `Python 3.8.0 on win 32`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:05:09.987",
"Id": "236082",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"asynchronous"
],
"Title": "Dealing Synchronous Request in Asynchronous Code"
}
|
236082
|
<p>This is my first Objective-C++ code, so I'm a bit lacking in the knowledge of methods.</p>
<p>I need to resolve a macOS alias and get its original location. I have access to the C string, which is the file path (in a human readable form). It also needs to be verified in this code itself that it is a true alias, and contains bookmark data. </p>
<pre><code>const char *class::resolveAliasFromURL(const char *filepath) const{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
char filepath[] = "/Users/me/alias"; /*you need to make an alias here*/
NSError *error = nil;
NSString *string = [[NSString alloc] initWithUTF8String:filepath];
NSURL *url = [NSURL fileURLWithPath:string];
NSData *bmdata = [NSURL bookmarkDataWithContentsOfURL:url error:&error];
if (!error) { /*needs better error catching*/
NSLog(@"Error: %@",error);
}
else {
NSLog(@"URL: %@",url); // Useless; sanity check
}
error = nil;
BOOL isstale = NO;
BOOL *isStalePointer = &isstale;
char ref[] = "";
NSString *relString = [[NSString alloc] initWithUTF8String:ref];
NSURL *relativeURL = [NSURL URLWithString:relString];
NSURLBookmarkResolutionOptions option = NSURLBookmarkResolutionWithoutUI;
NSURL *actual = [[NSURL alloc]
initByResolvingBookmarkData:bookmarkData
options:option
relativeToURL:relativeURL
bookmarkDataIsStale:isStalePointer
error:&error]; /*resolved NSURL object file://<some numbers>*/
char resolved[100]; /*resolved path in C; need to get length of the string, not arbitrarily 100 */
strcpy(resolved, [actual fileSystemRepresentation]);
printf(" %s\n",resolved);
/*Need to check if the resolved object is a file or a directory*/
[pool drain];
return tempPath;
}
</code></pre>
<p><a href="https://developer.apple.com/documentation/foundation/nsurl/1408344-bookmarkdatawithcontentsofurl?language=objc" rel="nofollow noreferrer"><code>bookmarkDataWithContentsOfURL</code></a>:</p>
<pre><code>+ (NSData *)bookmarkDataWithContentsOfURL:(NSURL *)bookmarkFileURL
error:(NSError * _Nullable *)error;
</code></pre>
<p><a href="https://developer.apple.com/documentation/foundation/nsurl/1413475-initbyresolvingbookmarkdata" rel="nofollow noreferrer"><code>initByResolvingBookmarkData</code></a></p>
<pre><code>- (instancetype)initByResolvingBookmarkData:(NSData *)bookmarkData
options:(NSURLBookmarkResolutionOptions)options
relativeToURL:(NSURL *)relativeURL
bookmarkDataIsStale:(BOOL *)isStale
error:(NSError * _Nullable *)error;
</code></pre>
<ul>
<li>Is there some improvements I can make given the goal and constraints? </li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T20:02:16.507",
"Id": "462552",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/103675/discussion-on-question-by-ankk-resolve-alias-original-item-using-bookmarkdata)."
}
] |
[
{
"body": "<h3>Memory management</h3>\n\n<p>The use of <code>NSAutoreleasePool</code> makes it apparent that this code is compiled <em>manual reference counting.</em> That is error-prone, as you'll see now: Here</p>\n\n<pre><code>NSString *string = [[NSString alloc] initWithUTF8String:filepath];\nNSString *relString = [[NSString alloc] initWithUTF8String:ref];\nNSURL *actual = [[NSURL alloc] initByResolvingBookmarkData ...];\n</code></pre>\n\n<p>are objects allocated but never released. That makes several memory leaks on each invocation of the method.</p>\n\n<p>The easiest fix would be to use <em>automatic reference counting (ARC)</em> instead. ARC is available since Mac OS 10.6, and there is no reason not to use it. You only have to adjust the compiler flags (i.e. do <em>not</em> pass <code>-fno-objc-arc</code> to the compiler) and replace (compare <a href=\"https://developer.apple.com/documentation/foundation/nsautoreleasepool\" rel=\"nofollow noreferrer\">this</a>)</p>\n\n<pre><code>NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n// ...\n[pool drain];\n</code></pre>\n\n<p>by </p>\n\n<pre><code>@autoreleasepool {\n // ...\n}\n</code></pre>\n\n<p>The compiler takes care of everything else and inserts <code>retain</code> and <code>release</code> calls where appropriate.</p>\n\n<p>If – for whatever reason – switching to ARC is not feasible then you have to fix the above-mentioned issues. You can add the needed release calls, e.g. </p>\n\n<pre><code>NSString *string = [[NSString alloc] initWithUTF8String:filepath];\n// ...\n[string release];\n</code></pre>\n\n<p>or (perhaps simpler) create autoreleased objects (which are released on return of the function, when the autorelease pool is drained):</p>\n\n<pre><code>NSString *string = [NSString stringWithUTF8String:filepath];\nNSURL *actual = [NSURL URLByResolvingBookmarkData ...];\n</code></pre>\n\n<p><code>string</code> can also more simply be created as a <a href=\"https://clang.llvm.org/docs/ObjectiveCLiterals.html#boxed-c-strings\" rel=\"nofollow noreferrer\">“boxed C string”</a>:</p>\n\n<pre><code>NSString *string = @(filepath);\n</code></pre>\n\n<p>Another error is here:</p>\n\n<pre><code>char resolved[100]; /*resolved path in C; need to get length of the string, not arbitrarily 100 */\nstrcpy(resolved, [actual fileSystemRepresentation]);\n// ...\nreturn tempPath;\n</code></pre>\n\n<p>because the function returns the address of a <em>local</em> variable, which is undefined behavior.</p>\n\n<p>You can make the character buffer static: That seems to be what similar functions in the blender project do. The disadvantage is that subsequent calls to the function overwrite the buffer.</p>\n\n<p>Or you can allocate a new string, and the caller has to release the memory eventually.</p>\n\n<h3>Error handling</h3>\n\n<p>The correct way to check for success or failure of Cocoa (Touch) methods is \ndocumented in\n<a href=\"https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-SW1\" rel=\"nofollow noreferrer\">\"Handling Error Objects Returned From Methods\"</a> in the \"Error Handling Programming Guide\":</p>\n\n<blockquote>\n <p><strong>Important:</strong> Success or failure is indicated by the return value of the\n method. Although Cocoa methods that indirectly return error objects in\n the Cocoa error domain are guaranteed to return such objects if the\n method indicates failure by directly returning nil or NO, you should\n always check that the return value is nil or NO before attempting to\n do anything with the NSError object.</p>\n</blockquote>\n\n<p>In your case, the correct way to check for the success of </p>\n\n<pre><code>NSData *bmdata = [NSURL bookmarkDataWithContentsOfURL:url error:&error];\n</code></pre>\n\n<p>would be</p>\n\n<pre><code>if (bmdata == nil) {\n NSLog(@\"Error: %@\",error);\n}\n</code></pre>\n\n<p>But <code>NSLog()</code>ing the error is not sufficient: You have to report the failure to the caller, e.g. by returning a <code>nullptr</code>:</p>\n\n<pre><code>if (bmdata == nil) {\n NSLog(@\"Error reading bookmark data for %@: %@\",url, error);\n [pool drain];\n return nullptr;\n}\n</code></pre>\n\n<p>Note that (if you keep the manual reference counting) you must take care that the autorelease pool is drained on any return from the function.</p>\n\n<p>The same error handling must be done when resolving the bookmark data, that is missing completely.</p>\n\n<h3>More remarks</h3>\n\n<ul>\n<li><code>relString</code> and <code>relativeURL</code> are not needed, you can simply pass <code>nil</code> to the <code>relativeToURL</code> argument.</li>\n<li><code>isStalePointer</code> is not needed, you can pass <code>&isstale</code> directly to the <code>bookmarkDataIsStale</code> argument. Or pass <code>nil</code> is you are not interested in the outcome (at present, the staleness is not evaluated in your code).</li>\n</ul>\n\n<h3>File system paths conversions</h3>\n\n<p>The conversion from an <code>NSURL</code> back to a C string with</p>\n\n<pre><code>char resolved[100];\nstrcpy(resolved, [actual fileSystemRepresentation]);\n</code></pre>\n\n<p>suggests that the C strings represent “file system paths” and in that case the correct counterpart for the conversion from the given <code>filepath</code> to an <code>NSURL</code> is </p>\n\n<pre><code>NSURL *url = [NSURL fileURLWithFileSystemRepresentation:filepath\n isDirectory:NO\n relativeToURL:nil];\n</code></pre>\n\n<p>But a buffer with 100 characters may be too short: Either determine the needed length dynamically, or use <code>MAXPATHLEN</code> from the system include files. Also <code>strcpy</code> does not check if the target buffer is large enough (potentially causing a memory corruption). Better use</p>\n\n<pre><code>static char resolved[MAXPATHLEN];\nif (![actual getFileSystemRepresentation:resolved maxLength:sizeof(resolved)]) {\n NSLog(@\"File system path too long for %@\", url);\n [pool drain];\n return nullptr;\n}\n</code></pre>\n\n<h3>Putting it together</h3>\n\n<p>Putting all the above suggestions together, the code (with manual reference counting) would be</p>\n\n<pre><code>const char *YourClass::resolveAlias(const char *filepath) const {\n\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n NSURL *url = [NSURL fileURLWithFileSystemRepresentation:filepath\n isDirectory:NO\n relativeToURL:nil];\n NSError *error = nil;\n NSData *bmdata = [NSURL bookmarkDataWithContentsOfURL:url error:&error];\n if (bmdata == nil) {\n NSLog(@\"Error reading bookmark data for %@: %@\",url, error);\n [pool drain];\n return nullptr;\n }\n NSURL *actual = [NSURL URLByResolvingBookmarkData:bmdata\n options:NSURLBookmarkResolutionWithoutUI\n relativeToURL:nil\n bookmarkDataIsStale:nil\n error:&error];\n if (actual == nil) {\n NSLog(@\"Error resolving bookmark data for %@: %@\", url, error);\n [pool drain];\n return nullptr;\n }\n\n static char resolved[MAXPATHLEN];\n if (![actual getFileSystemRepresentation:resolved maxLength:sizeof(resolved)]) {\n NSLog(@\"File system path too long for %@\", url);\n [pool drain];\n return nullptr;\n }\n\n [pool drain];\n return resolved;\n}\n</code></pre>\n\n<h3>Further simplification</h3>\n\n<p>As of macOS 10.10 the <code>NSURL</code> class has a </p>\n\n<pre><code>+ (instancetype)URLByResolvingAliasFileAtURL:(NSURL *)url \n options:(NSURLBookmarkResolutionOptions)options \n error:(NSError * _Nullable *)error;\n</code></pre>\n\n<p>initializer, which both reads and resolves the bookmark data. The function then simplifies to (now with automatic reference counting):</p>\n\n<pre><code>const char *YourClass::resolveAlias(const char *filepath) const {\n static char resolved[MAXPATHLEN];\n @autoreleasepool {\n\n NSURL *url = [NSURL fileURLWithFileSystemRepresentation:filepath\n isDirectory:NO\n relativeToURL:nil];\n NSError *error = nil;\n NSURL *resolvedURL = [NSURL URLByResolvingAliasFileAtURL:url\n options:NSURLBookmarkResolutionWithoutUI\n error:&error];\n if (![resolvedURL getFileSystemRepresentation:resolved maxLength:sizeof(resolved)]) {\n NSLog(@\"File system path too long for %@\", url);\n return nullptr;\n }\n }\n return resolved;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T18:15:31.743",
"Id": "462639",
"Score": "0",
"body": "I think we're going to keep it `void` and pass two pointers into it.. fits better with error catching and the rest of the code. Thanks for such an amazing review! https://nopaste.xyz/?850b0ee6b68d56f1#JpZYNesyRtC6Q7IHjvdu67hLl58TZ/G01X3DVP/4HqM= Will fix some little bits after integration"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T08:37:01.737",
"Id": "463273",
"Score": "0",
"body": "@ankk: Good idea, but better pass a destination pointer *and* the destination buffer size to the function. Also the function then should return a boolean to indicate success or failure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T21:05:04.513",
"Id": "236128",
"ParentId": "236085",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236128",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:47:00.393",
"Id": "236085",
"Score": "3",
"Tags": [
"strings",
"url"
],
"Title": "Resolve alias' original item using bookmarkData"
}
|
236085
|
<p>Here is the Question. Find the largest GCD of the input variable with the values of an array.</p>
<p>Inputs are as follows:- First-line contains two integers, N and Q.</p>
<p>Second-line contains N integers which form the arr[].</p>
<p>Next, Q lines contain an integer M, the time in seconds she wishes to go back.</p>
<pre><code>#include <stdio.h>
int main(){
int n,q;
scanf("%d %d", &n,&q);
int a[n];
int gcdn[n];
for (int i = 0;i < n; i++) {
scanf("%d",&a[i]); }
while (q>0){
q--;
int x;
int max = 0;
scanf("%d",&x);
max = gcd(a[0],x);
for(int i=0;i<n;i++) {
int t = gcd(a[i],x);
if(t > max)
max = t;
}
printf("%d \n",max);
}
}
int gcd (int a, int b) {
if (b==0)
return a;
else
return gcd(b, a%b);
}
</code></pre>
<p>How can I make this code better in terms of competitive programming? And what other languages can make this code better and more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:18:59.803",
"Id": "462443",
"Score": "0",
"body": "Rewrite your sentence about M. It doesn't make sense as is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:38:30.843",
"Id": "462446",
"Score": "1",
"body": "There is a good review of the code, however, this question might be listed as off-topic because the code would not compile using most compilers (item 3 in the answer)."
}
] |
[
{
"body": "<ol>\n<li><p>gcdn[] is unused. </p></li>\n<li><p>if n==0, you access a non-existent array element, and even if it isn't, you do the GCD with a[0] twice. </p></li>\n<li><p>gcd() is called before it is declared, which is bad style and can mess up optimization. </p></li>\n<li><p>you might think about whether the M or arr[] elements are likely to be larger. The order you pass values to gcd() can reduce by one loop if you guess right.</p></li>\n<li><p>The tail recursion on gcd() should be OK as long as you optimize.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:43:49.450",
"Id": "462449",
"Score": "0",
"body": "If you think the code won't compile you should flag the question and indicate that the code is broken. You gave a good answer, but since the code is broken it should not have been answered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T23:07:22.953",
"Id": "462451",
"Score": "3",
"body": "@pacmaninbw: No, this code compiles and runs. It gave what looked like correct results. Remember, unlike C++, C does allow implicit declaration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T06:52:18.437",
"Id": "462474",
"Score": "0",
"body": "Thanks, I was actually trying to optimize the code, earlier I used gcdn array to store all the gcds found and then to get the max, but later I decided to calculate max at the time it was being calculated but actually forgot to remove the gcdn declaration. can you please explain a bit about how can I better optimize my loops to make them shorter? Any advice on that will be really helpful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T14:16:31.220",
"Id": "462512",
"Score": "0",
"body": "@RajnishKaushik: The loops seem fine. You might consider `for (;q;q--)` or `while (q--)`, but neither one will speed up the optimized code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T22:18:19.097",
"Id": "236093",
"ParentId": "236087",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236093",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:59:47.010",
"Id": "236087",
"Score": "2",
"Tags": [
"performance",
"c",
"complexity"
],
"Title": "Find the maximum GCD of a number with respect to all the values in an array for competitive programming"
}
|
236087
|
<p>For testing purposes of a platform I'm working on, I must automate the process of initiating Dota 2, accepting an invite that shows on screen, choose the right spot for that player (team A or team B), wait until the game starts and then exit it.</p>
<p>All of that could be done with simple clicks on static coordinates but Steam is not concerned about people trying to automate tests. So a lot can go wrong from the moment the game is initiate until the user arrives in the lobby. Update requests may appear in the screen for example, also, sometimes a fullscreen advertising may appear blocking the view of everything else, and they are different from each other so I can't rely on a 'x' close button on a specific place to click.</p>
<p>So, after many tries, I came up with this script below.
I took several screenshots of every possible and obligatory step to do what I need, like a screenshot of the checkbox to "launch the game as soon as updated". Also, some coordinates are static and didn't need to be searched by an image reference.
The script uses an image search library to find all these images at their specific moments. For example, before searching for the main logo of Dota, I have to search for the mentioned update screen that may appear. But because the update screen may not appear (in case it is already updated), I have to search for the main logo alongside, so if the main logo appears it means the game is not going to update, so this step is concluded and we can move forward. </p>
<p>This kind of thing happens a lot of times, it is similar to the idea of a fluxogram that can have multiple nodes "active" at once (by active I mean that they are being executed alongside each other).</p>
<p>So, the classes <code>CoordNode</code> and <code>ImageSearchNode</code> holds specific methods for each of the processess (the process of simply clicking on a coordinate, or searching for an image, and maybe clicking on it). Also, it serves to save information about the state of that process (if it's concluded or not, so things don't get clicked twice).</p>
<p>The script works as I expected sucessfully, but I'm not satisfied with the implementation.</p>
<p>Besides being a little bit unreadable from the function <code>run_complete_flow</code>, every modification or increase in functionality that has to be made takes too long to be understood on <em>how</em> to be implemented alongside the rest of the script.</p>
<p>Being a not so specific situation to happen (automate a process that handles several obligatory and non-obligatory events), I wonder if there's already a better standard implementation of such a job. Or at least some recommendation on how to organize better the code.
Thank you. </p>
<pre><code>import traceback
import logging
import subprocess
from image_search.imagesearch import imagesearch_num_loop, click_image, imagesearch_region_loop, save_screenshot
import sys
from get_tag_value import get_coords, get_info
import pyautogui
import psycopg2
import time
from telegram_logs.bot import telegram_logger, send_photo
import ctypes
import os
from private_module import get_node_5
logging.basicConfig(level=logging.INFO)
# powerbutton topleft corner should be at 987, 8
X_REF_LOGO = 987
Y_REF_LOGO = 8
X_CORRECTION = None
Y_CORRECTION = None
def basic_log(msg):
telegram_logger(f"*{get_info('username')}*\n{str(msg)}")
def send_photolog():
save_screenshot(get_info('username'))
send_photo(f"*{get_info('username')}*", f"{get_info('username')}.png")
def run_game():
if os.path.exists("tags.json"):
os.remove("tags.json")
detached_process = 0x00000008
steam_username = get_info('username')
password = get_info('password')
print(steam_username, " : ", password)
subprocess.Popen([r"C:\Program Files (x86)\Steam\Steam.exe", "-login", f"{steam_username}", f"{password}",
"steam://rungameid/570"], creationflags=detached_process)
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
basic_log(f"Launched game!\n Screen res is: {screensize[0]}x{screensize[1]}")
return None
class Node:
def __init__(self, node_name, event_info, send_telegram_log):
self._node_name = node_name
self._event_info = event_info
self._send_telegram_log = send_telegram_log
self._finished = False
@property
def node_name(self):
return self._node_name
def _set_finished(self, value: bool):
self._finished = value
if self._send_telegram_log and value:
self._send_log()
@property
def finished(self):
return self._finished
@staticmethod
def _click_on_coords(latency, pos):
pyautogui.moveTo(pos[0], pos[1], latency)
pyautogui.click(button="left")
return pos
def _send_log(self):
basic_log(self.node_name)
def reset(self):
self._set_finished(False)
def execute(self, *args):
pass
class CoordNode(Node):
def __init__(self, node_name, coords, send_telegram_log=True):
super().__init__(node_name=node_name, event_info=coords, send_telegram_log=send_telegram_log)
try:
if not len(coords) == 2 \
or not type(coords[0]) == int \
or not type(coords[1]) == int:
raise ValueError("What kind of coordinates are you giving me?")
except Exception as exc:
logging.debug(str(exc))
raise exc
self._coords = coords
@property
def coords(self):
return self._coords
def click(self, latency=2):
if self.finished:
return True
self._set_finished(True)
return self._click_on_coords(latency, self.coords)
def execute(self, latency=2):
return self.click(latency)
class ImageSearchNode(Node):
def __init__(self, node_name, path: str, precision=0.8, send_telegram_log=True, clickable=False):
super().__init__(node_name=node_name, event_info=path, send_telegram_log=send_telegram_log)
try:
test_path = path
replaces = "_.\\/-:"
for char in replaces:
test_path = test_path.replace(char, '')
if not test_path.isalnum():
raise ValueError("What kind of image path are you trying to set?")
except Exception as exc:
logging.debug(str(exc))
raise exc
self._precision = precision
self._path = path
self.clickable = clickable
self._found = False
self._clicked = False
@property
def filename(self):
if len(self.path.split('\\')) == 1: # In case we're running on linux
return str(self.path.split('/')[-1])
else:
return str(self.path.split('\\')[-1])
@property
def found(self):
return self._found
@property
def clicked(self):
return self._clicked
@property
def path(self):
return self._path
def click(self, latency=2, frequency=None, duration=None):
if self.finished:
return True
pos = self.find(frequency, duration)
if not pos:
return False
click_image(image=self.path, pos=pos, action="left", timestamp=latency, offset=0)
self._set_finished(True)
return True
def find(self, frequency=2, duration=6*60*60, area_search=False, area_coords=None):
if self.finished:
return True
iterations = frequency * duration
period = 1 / frequency
if area_search:
try:
pos = imagesearch_region_loop(self.path, period, iterations,
area_coords[0],
area_coords[1],
area_coords[2],
area_coords[3],
self._precision,
self.filename)
if pos[0] != -1:
self._found = True
logging.debug("FOUND AT " + str(pos))
if not self.clickable:
self._set_finished(True)
return pos
else:
return None
except Exception as exc:
raise ValueError(f"Where are my area coords?? [x1, y1, x2, y2] \n {str(exc)}")
pos = imagesearch_num_loop(self.path, period, iterations, self._precision, self.filename)
if pos[0] != -1:
self._found = True
logging.debug("FOUND AT " + str(pos))
if not self.clickable:
self._set_finished(True)
return pos
else:
logging.info(self.filename + "Not found!")
return None
def execute(self, find=False, find_and_click=None, latency=0, frequency=None, duration=6*60*60):
if not find and not find_and_click:
raise ValueError("Well, I must either find or find and click!")
if find_and_click:
return self.click(latency=latency, frequency=frequency, duration=duration)
if find:
return self.find(frequency, duration)
def define_correction(main_logo_corner):
global X_CORRECTION
global Y_CORRECTION
X_CORRECTION = main_logo_corner[0] - X_REF_LOGO
Y_CORRECTION = main_logo_corner[1] - Y_REF_LOGO
def adjusted_coords(pos):
if not pos:
return pos
x_corr = pos[0] + X_CORRECTION
y_corr = pos[1] + Y_CORRECTION
return [x_corr, y_corr]
def run_complete_flow(oss="windows"):
windows_prefix = r"C:\Users\Administrator\Desktop\files_in_remote_ec2\python_scripts\images_to_search\\"
linux_prefix = r"/home/user/Desktop/images/"
if oss == "windows":
prefix = windows_prefix
else:
prefix = linux_prefix
# ~ : maybe will or maybe will not occur
# ^ : certainly will occur
# ^- : certainly will occur but condition has to be applied
# 1) ~ launch_as_soon_as_updated -> (find and click)
# 1.1) ~ restart steam -> (find and click)
# 1.1.5) ^- launch dota 2 again if steam restarted -> (execute dota)
# 1.2) ^ loading logo -> (find it)
# 2) ~ advertising -> (press esc)
# 3) ^ check if there is power button -> (find it)
# 3.1) ~ check if it was in a lobby before -> (find and click)
# 3.1.1) ^- if it was in a lobby, leave it -> (find and click)
# 4) ^ accept invite -> (find and click)
# 5) ^ in lobby get the correct slot and join it -> (click it)
# 6) ^ wait for about 3 minutes until match begins -> (wait)
# 7) ^- leave the match if you are radiant -> (nothing)
# 7.1) ^ click the arrow to go to dashboard -> (click it)
# 7.2) ^ leave game -> (click it)
# 7.3) ^ confirm leave game -> (click it)
# 7.4) ^ disconnect from match -> (click it)
# 8) ^- continue if you are dire -> (click it)
lasau = ImageSearchNode(node_name="Node 1: Launch as soon as updated",
path=prefix+"1_launch_game_update.png",
clickable=False,
precision=0.6, send_telegram_log=False)
resteam = ImageSearchNode(node_name="Node 1.1: Restart steam",
path=prefix+"restart_steam.png",
clickable=True,
precision=0.6)
# node_1_1_5 = "execute dota again"
mainlogo = ImageSearchNode(node_name="Node 1.2: Located loading logo",
path=prefix+"main_logo.png",
clickable=True,
precision=0.7)
# node_2 = "press esc if advertising (after logo appears and not powerbutton"
pwbttn = ImageSearchNode(node_name="Node 3: Found power button",
path=prefix+"3_power_button.png",
clickable=False,
precision=0.7)
wasinlbb = ImageSearchNode(node_name="Node 3.1: It was in a lobby!",
path=prefix+"back_to_lobby.png",
clickable=True,
precision=0.6)
lveprvslbb = ImageSearchNode(node_name="Node 3.1.1: leave the previous lobby",
path=prefix+"leave_this_lobby.png",
clickable=True,
precision=0.6)
accinv = ImageSearchNode(node_name="Node 4: Accept invite",
path=prefix+"4_accept_invite.png",
clickable=True,
precision=0.8)
# node_5 = "Defined later on"
# STEP 0: LAUNCH GAME
run_game()
# Non, begin the screenmonitor flow
# The logic must be:
# If an option is uncertain to occur, we try it alongside all the subsequent uncertain events
# Also, it must include at least the first obligatory event to occur and, if this event occurs, stop searching
# for the previous uncertain ones:
# in this case we only need to find the power button, not click it
start_time = time.time()
while not mainlogo.execute(find=True, frequency=2, duration=1):
if lasau.execute(find=True, frequency=2, duration=1):
# While it doesn't find the checked box, keep trying to click it
# sometimes the screen glitches and the checkbox isn't clicked
# the image is 145x15
# the checkbox itself is at (0,0) - (15,15)
# therefore, it must click (7,7) + chckbox_coords
# after a while, check if finds the checkbox full.. if not, click it again
count = 0
while not ImageSearchNode("Checkbox clicked?", path=prefix+"checked_box.png",
send_telegram_log=False).find(duration=1) and count < 5:
lasau.reset()
chckbox_coords = lasau.execute(find=True, frequency=2, duration=1)
print(str(chckbox_coords) + "Checkbox coordinates!")
if isinstance(chckbox_coords, tuple):
CoordNode("Clicking checkbox..", [chckbox_coords[0]+7, chckbox_coords[1]+7]).execute(latency=0)
count += 1
ImageSearchNode(node_name="Desperately clicking on play game", path=prefix+"play_game.png",
clickable=True, send_telegram_log=False, precision=0.5).execute(find_and_click=True,
frequency=2, duration=1)
if time.time()-start_time > int(get_info("timeout_photolog")):
start_time = time.time()
send_photolog()
if resteam.execute(find_and_click=True, frequency=2, duration=1):
# it clicked on restart steam, so load the game again
run_game()
while True:
# Found the logo!
# Now, look for the power button.. maybe be overridden by an advertising, so we click to close
reincident = False
while not (pwcoords:=pwbttn.execute(find=True, frequency=2, duration=1)):
mainlogo.reset()
if not mainlogo.execute(find=True, frequency=2, duration=1):
# well, the logo isn't there, but neither the power button. It must be an advertising
if reincident:
basic_log("Go check if the advertising has changed")
time.sleep(10)
if (advcoords:=ImageSearchNode(node_name="Advertising", path=prefix+"advertising.png").execute(find=True,
frequency=2,
duration=2)):
tl_adv = get_coords("advertising_coords")
CoordNode("Clicking advertising", [advcoords[0]+tl_adv[0],
advcoords[1]+tl_adv[1]]).execute()
reincident = True
###### COORDINATES NEEDS ADJUSTMENTS FROM HERE #######
# todo coordinates are not being correctly corrected. Sometimes the game screen tilts to another place
define_correction(pwcoords)
# Found power button! Just do a quick check on possible previous games
if wasinlbb.execute(find_and_click=True, frequency=4, duration=4):
lveprvslbb.execute(find_and_click=True, frequency=4, duration=5)
# Now we are ready to accept invites!
# Get the invitation!!
while not accinv.execute(find_and_click=True, frequency=2):
continue
# now we can set node_5:
coordinates, is_radiant = get_node_5()
coordinates = adjusted_coords(coordinates)
# Click the correct spot
node_5 = CoordNode(node_name="Node 5: found right spot",
coords=coordinates)
time.sleep(4) # just an assurance, we're running on slow computers
while not node_5.execute():
continue
# sleep for 4min = 240s
# node_6
sleep_time = int(get_info('sleep_time'))
logging.info(f"sleeping for {str(sleep_time)} seconds")
time.sleep(sleep_time)
if not is_radiant:
# if is_radiant we proceed to leave the match, and let dire win:
a_coords = get_coords('arrow_coords')
d_coords = get_coords('disconnect_coords')
l_coords = get_coords('leave_coords')
c_coords = get_coords('confirm_coords')
node_7_1 = CoordNode(node_name="Node 7.1 - clicked arrow", coords=adjusted_coords(a_coords))
node_7_1.execute(latency=2)
node_7_2 = CoordNode(node_name="Node 7.2 - clicked disconnect", coords=adjusted_coords(d_coords))
node_7_2.execute(latency=2)
node_7_3 = CoordNode(node_name="Node 7.3 - clicked leave", coords=adjusted_coords(l_coords))
node_7_3.execute(latency=2)
node_7_4 = CoordNode(node_name="Node 7.4 - clicked continue", coords=adjusted_coords(c_coords))
node_7_4.execute(latency=2)
else:
cont_coords = get_coords('continue_coords')
node_8 = CoordNode(node_name="Node 8 - clicked continue", coords=adjusted_coords(cont_coords))
node_8.execute(latency=2)
pwbttn.reset()
wasinlbb.reset()
lveprvslbb.reset()
accinv.reset()
if __name__ == "__main__":
if len(sys.argv) > 1:
run_complete_flow("linux")
else:
try:
run_complete_flow()
except Exception:
try:
username = get_info('username')
telegram_logger(f"*{username}* \n {str(traceback.format_exc())}")
except Exception as ee:
telegram_logger("\n\n second flaw \n\n" + str(ee))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:12:22.997",
"Id": "462648",
"Score": "0",
"body": "What version of python are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T17:29:30.093",
"Id": "462870",
"Score": "0",
"body": "@Linny, I'm using python 3.8"
}
] |
[
{
"body": "<p>Have you considered to split up your run_complete_flow() function? Personally I would prefer to put it in a class. The first part up to run_game would go into __init__(). Then I would try to split up the task into methods. E.g. you have a comment\n<code># in this case we only need to find the power button, not click it</code> - why not put that code in a method like find_power_buttom()? My goal would be, to make the flow easily understandable by reading the code of run_complete_flow() without comments, by \"hiding all the unnecessary stuff\" in well named methods. That should make it a lot easier to change the flow if needed, or identify where to look when a certain step makes problems.</p>\n\n<pre><code>def run_complete_flow(self):\n self.launch_as_soon_as_updated()\n self.advertising()\n self.check_power_button()\n self.accept_invite()\n self.in_lobby_get_slot_and_join()\n self.wait_for_match(time_out=180)\n radiant = self.check_radiant()\n if radiant:\n self.leave_match()\n else:\n # not sure, where to jump from here; consider puting whole \n # radiant/dire \"loop\" in one method continue_until_radiant\n self.continue_if_dire() \n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T17:29:09.303",
"Id": "462869",
"Score": "0",
"body": "Well, I haven't considered. It is a good start on organizing the code, but it doesn't actually solves my problem, since inside each of these functions there will still be the same block of code I would like to avoid or rebuild (the while's with confusing logic of when to break). But I will do this refactor for now, thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:42:50.587",
"Id": "236162",
"ParentId": "236088",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236162",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T21:02:59.340",
"Id": "236088",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"automation"
],
"Title": "Script to automate image searching and clicking on screen"
}
|
236088
|
<p>I have written this code and I wonder if there is a better way to do absolutely any of it. Also, if there is any way to optimise it or if there is a problem please also tell me preferably with fixed code as I am still sort of a beginner. It is one of my first school projects and I would like to show my teacher that I really now Python. What it is supposed to do is take an input which is a YouTube and give a response based on the input. I've heard of dictionary lookups but I don't really understand what they are so if anyone thinks that they maybe relevant and could show me how to impliment it that would be great! I am also thinking of using a switch statement (which might be the same as a dictionary lookup) that I know from my experience with JavaScript. The code is below:</p>
<pre class="lang-py prettyprint-override"><code>import random
def test():
youtuber = input('Enter your favourite youtuber: ')
youtuber = youtuber.lower()
favouriteYoutuber = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']
if youtuber == 'dr. phil':
print('You are an awesome lad!')
elif youtuber == 'james charles':
print('Errmm. Ok...')
elif youtuber == 'bloamz':
print('Ok then.')
elif youtuber == 'ali a':
print('I mean. Thats old but ok...')
elif youtuber == 'jacksepticeye':
print('Thats kinda cool')
elif youtuber == 'will smith':
print('Thats different. I rate that')
elif youtuber == 'jack black':
print('you have good taste')
elif youtuber == 'jack white':
print('I like him as well')
elif youtuber == 'dr. mike':
print('so you like learning then')
elif youtuber == 'morgz':
print('I mean just leave now')
else:
print('I dont know that one. Ill check them out')
print('my favourite youtuber is ' + random.choice(favouriteYoutuber))
def try_again():
again = True
while again:
test()
while True:
try:
print("")
print("Would you like to try again?")
maybe = input("Y/N ")
maybe = maybe.lower()
except ValueError:
print("That is not a valid option")
print("")
continue
if maybe in ('y','n'):
if maybe == "n":
print("")
again = False
elif maybe == "y":
print("")
break
else:
print("Thank you for using this app!")
try_again()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T21:05:25.187",
"Id": "236090",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Python3 output based on input"
}
|
236090
|
<p>I have written this code which provides advice based on user's favourite YouTuber. I wonder if there is a better way to do absolutely any of it. Also, if there is any way to optimise it or if there is a problem please also tell me preferably with fixed code as I am still sort of a beginner.
The code is below:</p>
<pre><code>import random
def test():
youtuber = input('Enter your favourite youtuber: ')
youtuber = youtuber.lower()
favouriteYoutuber = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']
if youtuber == 'dr. phil':
print('You are an awesome lad!')
elif youtuber == 'james charles':
print('Errmm. Ok...')
elif youtuber == 'bloamz':
print('Ok then.')
elif youtuber == 'ali a':
print('I mean. Thats old but ok...')
elif youtuber == 'jacksepticeye':
print('Thats kinda cool')
elif youtuber == 'will smith':
print('Thats different. I rate that')
elif youtuber == 'jack black':
print('you have good taste')
elif youtuber == 'jack white':
print('I like him as well')
elif youtuber == 'dr. mike':
print('so you like learning then')
elif youtuber == 'morgz':
print('I mean just leave now')
else:
print('I dont know that one. Ill check them out')
print('my favourite youtuber is ' + random.choice(favouriteYoutuber))
def try_again():
again = True
while again:
test()
while True:
try:
print("")
print("Would you like to try again?")
maybe = input("Y/N ")
maybe = maybe.lower()
except ValueError:
print("That is not a valid option")
print("")
continue
if maybe in ('y','n'):
if maybe == "n":
print("")
again = False
elif maybe == "y":
print("")
break
else:
print("Thank you for using this app!")
try_again()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:55:03.453",
"Id": "462466",
"Score": "1",
"body": "What's the purpose of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T21:26:04.267",
"Id": "462739",
"Score": "0",
"body": "At least half of these are not YouTubers..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T21:26:40.793",
"Id": "462740",
"Score": "0",
"body": "God, I feel old."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T07:46:34.133",
"Id": "462780",
"Score": "1",
"body": "I've rolled back your edit. Please do not edit the question with updated code. If you would like further improvements, please ask a new question."
}
] |
[
{
"body": "<blockquote>\n <p>I've heard of dictionary lookups but I don't really understand what they are so if anyone thinks that they maybe relevant and could show me how to implement it that would be great!</p>\n</blockquote>\n\n<p>Here you go!</p>\n\n<h1>Use Dictionaries!</h1>\n\n<p>The entire <code>if/elif/else</code> if yelling, if not screaming, to be put into a dictionary. This is a lot faster than your implementation because it's a simple key lookup, instead of multiple logical checks to test the user input.</p>\n\n<p>Here is your <code>test</code> function (now named <code>favorite_youtuber</code>):</p>\n\n<pre><code>def favorite_youtuber():\n\n youtube_response = {\n 'dr. phil': 'You are an awesome lad!',\n 'james charles': 'Errmm. Ok...',\n 'bloamz': 'Ok then.',\n 'ali a': 'I mean. Thats old but ok...',\n 'jacksepticeye': 'Thats kinda cool',\n 'will smith': 'Thats diferent. I rate that.',\n 'jack black': 'You have good taste.',\n 'jack white': 'I like him as well.',\n 'dr. mike': 'So you like learning then!',\n 'morgz': 'I mean just leave now.'\n }\n # Since some youtubers in the list below are not included in the dictionary, I left the list. #\n my_favorite_youtubers = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']\n\n youtuber = input('Enter your favourite youtuber: ').lower()\n\n if youtuber in youtube_response:\n print(youtube_response[youtuber])\n else:\n print('I dont know that one. Ill check them out.')\n\n print(f'My favourite youtuber is {random.choice(my_favorite_youtubers)}!')\n</code></pre>\n\n<p>A dictionary works by utilizing <code>keys</code> and <code>values</code>, like so:</p>\n\n<pre><code>my_dict = {\n \"key\": \"value of any type\",\n ...\n}\n</code></pre>\n\n<p>In this case, the <code>key</code> is the name of the youtuber that the user inputs, and the <code>value</code> is the response. This prevents you from having to have multiple print statements depending on what the user inputs. Now, all you have to do is make sure that the youtuber entered by the user is included in the dictionary's keys, utilizing this line:</p>\n\n<pre><code>if youtuber in youtube_response:\n</code></pre>\n\n<h1>Format Your Strings!</h1>\n\n<p>The era of <code>my_string = a + \" \" + b</code> is over. You can now format your strings to include your variables directly in them! Take a look:</p>\n\n<pre><code>print(f'My favourite youtuber is {random.choice(my_favorite_youtubers)}!')\n</code></pre>\n\n<p>Essentially, the value of the code within <code>{}</code> is placed in that position in the string.</p>\n\n<p>Another option is to use <a href=\"https://docs.python.org/3/library/string.html#string.Formatter.format\" rel=\"noreferrer\"><code>.format()</code></a>, which is a method called on a string. Take a look:</p>\n\n<pre><code>print('My favourite youtuber is {}'.format(random.choice(my_favorite_youtubers)))\n</code></pre>\n\n<p>They both do the same thing. It's up to you which one you want to use.</p>\n\n<h1><code>.lower()</code> utilization</h1>\n\n<p>Instead of</p>\n\n<pre><code>maybe = input(\"Y/N \")\nmaybe = maybe.lower()\n</code></pre>\n\n<p>do this</p>\n\n<pre><code>maybe = input(\"Y/N \").lower()\n</code></pre>\n\n<p>Since <code>input()</code> returns a string, <code>.lower()</code> applies to that string. This prevents you from having to write that extra line, and it makes your code a little nicer.</p>\n\n<h1><code>\\n</code></h1>\n\n<p>Instead of</p>\n\n<pre><code>print(\"That is not a valid option\")\nprint(\"\")\n</code></pre>\n\n<p>do this</p>\n\n<pre><code>print(\"That is not a valid option.\\n\")\n</code></pre>\n\n<p>It adds a newline character at the end of the string, doing exactly what you're doing but in a nicer way.</p>\n\n<h1>Repetitive User Input</h1>\n\n<p>Now let's talk about your <code>try_again</code> function.</p>\n\n<p>There's a lot to break down here. I find it easier to show you my improved version of your code, and walking you through what I did. Have a look:</p>\n\n<pre><code>def run_app():\n while True:\n favorite_youtuber()\n again = input(\"Play again? (Y/N)\").lower()\n while again not in \"yn\":\n print(\"Please enter Y/N!\")\n again = input(\"Play again? (Y/N)\").lower()\n if again == \"n\":\n break\n print(\"Thank you for using this app!\")\n</code></pre>\n\n<p>It's fairly self explanatory. The one thing I want to talk about is the nested <code>while</code> loop.</p>\n\n<p>Instead of checking if something is within a tuple <code>(\"y\", \"n\")</code>, you can check if something is within a string <code>\"yn\"</code>. It's easier to understand this way. The while loop keeps asking for input until the user enters a \"y\" or a \"n\". This is easier than having nested <code>while True:</code> loops, as those can get very messy very fast.</p>\n\n<p>Since you only want to see if they <em>don't</em> want to keep playing, you only need to check for the existence of an \"n\". Then, it's a simple <code>break</code> statement to print out the final goodbye.</p>\n\n<h1>Main Guard</h1>\n\n<p>Last thing I'm commenting on.</p>\n\n<p>You should use a main guard when running this program. Why?</p>\n\n<p>Let's say you want to import this module into another program, because you don't want to rewrite all this code in a different file. When you import the module, that spare <code>try_again</code> is going to run. That is not what you want. Containing this extra code in a main guard will prevent this from happening. It's a simple <code>if</code> statement:</p>\n\n<pre><code>if __name__ == \"__main__\":\n run_app()\n</code></pre>\n\n<p>I renamed your <code>try_again</code> to <code>run_app()</code>, since that name is more fitting of what the program is doing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T12:56:50.477",
"Id": "462506",
"Score": "0",
"body": "For `if youtuber in youtube_response.keys()`, don't you mean the simpler `if youtuber in youtube_response`? Also, by not following your own advice of applying `.lower()` after `input()` in your example, if `again` is `\"N\"` then the `if again == \"n\"` fails..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T18:38:13.943",
"Id": "462540",
"Score": "0",
"body": "@MatthieuM. Those are both great points, some things I overlooked while I was writing this review. I'll edit my answer accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T19:21:49.087",
"Id": "462544",
"Score": "0",
"body": "In `run_app` it could be `again = \"\" while again != \"n\":`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:05:39.053",
"Id": "462644",
"Score": "0",
"body": "@S.S.Anne True, but that doesn't provide the opportunity for the program to skip the while loop completely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:06:40.543",
"Id": "462645",
"Score": "0",
"body": "@Linny I don't see how it would make a difference except for code clarity."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T00:12:14.040",
"Id": "236094",
"ParentId": "236097",
"Score": "30"
}
},
{
"body": "<p>Your code has bad scaling, since with more youtubers, more code and more ifs are needed.\nThis can be solved by using a dict with each youtuber name as key and each message as value:</p>\n\n<pre><code>youtubers = {}\nyoutubers['dr. phil'] = 'You are an awesome lad!'\nyoutubers['james charles'] = 'Errmm. Ok...'\n# others entries here\n\n# querying\nprint(youtubers[youtuber])\n</code></pre>\n\n<p>This will reduce querying time since getting an item in a python dict uses constant time in average case.</p>\n\n<p>You can also create the dictionary using less code with comprehension dict, assuming you have a youtuber's names list and a message's list</p>\n\n<pre><code>youtuber_names = ['youtuber1', 'youtuber2']\nmessages = ['message1', 'message2']\n\n# this will create an equivalent dict \nyoutubers = {youtuber_names[i]: messages[i] for i in range(len(youtuber_names)}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:54:57.470",
"Id": "462468",
"Score": "4",
"body": "Better to define the constant all at once rather than build it up over one line per element."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:49:41.070",
"Id": "236098",
"ParentId": "236097",
"Score": "2"
}
},
{
"body": "<p>@Linny. First of all thanks for your solution. It's a real improvement and very good explained. This push me to try to enhance it even more. </p>\n\n<p>This new proposal is based on your solution, and it includes two additional changes. Both of them according to <a href=\"https://williamdurand.fr/2013/06/03/object-calisthenics/\" rel=\"nofollow noreferrer\">Jeff Bay's Object Calisthenics</a> (some basic rules to write better Object Oriented code): </p>\n\n<blockquote>\n <p>Rule 2: \"Don´t use the else keyword\". </p>\n</blockquote>\n\n<p>There's only one else. See below:</p>\n\n<pre><code> if youtuber in youtube_response:\n print(youtube_response[youtuber])\n else:\n print('I dont know that one. Ill check them out.')\n</code></pre>\n\n<p>Luckily, the whole 4 lines (if/else) can be replaced by one line:</p>\n\n<pre><code> print(youtube_response.get(youtuber, 'I dont know that one. Ill check them out.'))\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3/library/stdtypes.html\" rel=\"nofollow noreferrer\">Get behaviour</a> is the following: <code>get(key[, default])</code> return the value for key if key is in the dictionary, else default. </p>\n\n<blockquote>\n <p>Rule 1: \"Only One Level Of Indentation Per Method.\" </p>\n</blockquote>\n\n<p>Run_app function has two additional level of indentation:</p>\n\n<ul>\n<li>First line is considered as level 0 ´While True´</li>\n<li>Level 1 starts below first while</li>\n<li>And level 2 starts below second while </li>\n</ul>\n\n<pre><code>def run_app():\n while True:\n # Level 1\n favorite_youtuber()\n again = input(\"Play again? (Y/N)\").lower()\n while again not in \"yn\":\n # Level 2\n print(\"Please enter Y/N!\")\n again = input(\"Play again? (Y/N)\").lower()\n if again == \"n\":\n # Level 2\n break\n print(\"Thank you for using this app!\")\n</code></pre>\n\n<p>This function in fact has two responsibilities, <strong>run_app</strong> and check if <strong>play_again</strong>. My proposal is to extract this second responsibility to another function. This should improve code readability and lower its complexity:</p>\n\n<pre><code>def run_app():\n while True:\n favorite_youtuber()\n if not play_again():\n break\n print(\"Thank you for using this app!\")\n\n\ndef play_again():\n while (again := input(\"Play again? (Y/N)\").lower()) not in \"yn\":\n print(\"Please enter Y/N!\")\n return again == \"y\"\n</code></pre>\n\n<p>I hope this can be helpful</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T21:31:18.113",
"Id": "237189",
"ParentId": "236097",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T20:25:19.187",
"Id": "236097",
"Score": "18",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x"
],
"Title": "Providing advice based on user's favourite YouTuber"
}
|
236097
|
<p>Rust is one of my first forays on a <em>strongly typed</em> language, beginning to like it's strictness, and am looking to improve my comprehension.</p>
<h2>Rules</h2>
<p>Fizzbuzz is a programming challenge with the following rules for output;</p>
<ul>
<li><p><em><code>n</code></em> mod <code>3</code> => <em><code>"Fizz"</code></em></p></li>
<li><p><em><code>n</code></em> mod <code>5</code> => <em><code>"Buzz"</code></em></p></li>
<li><p><em><code>n</code></em> mod <code>3</code> && <em><code>n</code></em> mod <code>5</code> => <em><code>"Fizzbuzz"</code></em></p></li>
<li><p>else <em><code>n</code></em> => <em><code>n</code></em></p></li>
</ul>
<p>Examples;</p>
<ul>
<li><code>10</code> => <code>"Buzz"</code></li>
<li><code>11</code> => <code>"11"</code></li>
<li><code>12</code> => <code>"Fizz"</code></li>
<li><code>13</code> => <code>"13"</code></li>
<li><code>14</code> => <code>"14"</code></li>
<li><code>15</code> => <code>"Fizzbuzz"</code></li>
</ul>
<h2>Questions</h2>
<ul>
<li><p>Are there any mistakes that the compiler hasn't pestered my about?</p></li>
<li><p>The iterator increments or decrements, any other directions it should go?</p></li>
<li><p>It's not the shortest implementation, not my primary goal, but do any bits of code smell?</p></li>
<li><p>What other features would be good to add for the learning experience?</p></li>
</ul>
<hr>
<h2>Steps to Reproduce</h2>
<p><strong>Initialization</strong></p>
<pre><code>cargo init fizzbuzz
cd fizzbuzz
</code></pre>
<p><strong>Add <code>argparse</code> as dependency</strong> to <code>Cargo.toml</code> file</p>
<pre><code>[dependencies]
argparse = "0.2.2"
</code></pre>
<blockquote>
<p>See <strong><code>Source Code</code></strong> for contents of <code>src/main.rs</code> file.</p>
</blockquote>
<p><strong>Compiling and running</strong></p>
<pre><code>cargo build
./target/debug/fizzbuzz --begin 1 --end 26
./target/debug/fizzbuzz --begin 100 --end 74
</code></pre>
<hr>
<h2>Source Code</h2>
<p><strong><code>src/main.rs</code></strong></p>
<pre><code>extern crate argparse;
use argparse::{ArgumentParser, Store, StoreTrue};
/// **Licensing**
///
/// Rust Fizzbuzz
/// Copyright (C) 2020 S0AndS0
///
/// This program is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Affero General Public License as published
/// by the Free Software Foundation; version 3 of the License.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Affero General Public License for more details.
///
/// You should have received a copy of the GNU Affero General Public License
/// along with this program. If not, see <https://www.gnu.org/licenses/>.
/// Data structure for mutable states within `Game`
#[derive(Clone)]
struct State {
fizz: bool,
buzz: bool,
count: u32,
message: String
}
impl State {
/// Method for defaulting values other than `count`
fn new(count: Option<u32>) -> Self {
let count: u32 = match count {
Some(i) => { i },
None => { 1 }
};
return State {
fizz: false,
buzz: false,
count: count,
message: String::from(""),
}
}
}
/// Data structure of what `Game` is concerned with
struct Game {
state: State,
limit: u32,
}
impl Game {
/// Method for initializing game with counter and limit
fn new(count: Option<u32>, limit: Option<u32>) -> Self {
let limit: u32 = match limit {
Some(i) => { i },
None => { 16 }
};
Game { state: State::new(count), limit: limit }
}
}
impl Iterator for Game {
/// Return type of iterator
type Item = State;
/// Called implicitly by `for` loops
fn next(&mut self) -> Option<State> {
self.state.fizz = false;
self.state.buzz = false;
self.state.message = String::from("");
if self.state.count % 3 == 0 {
self.state.fizz = true;
self.state.message.push_str("fizz");
}
if self.state.count % 5 == 0 {
self.state.buzz = true;
self.state.message.push_str("buzz");
}
if self.state.message.is_empty() {
self.state.message = self.state.count.to_string();
} else if let Some(r) = self.state.message.get_mut(0..1) {
r.make_ascii_uppercase();
}
if self.state.count != self.limit {
if self.state.count < self.limit {
self.state.count += 1;
} else {
self.state.count -= 1;
}
Some(self.state.clone())
} else {
None
}
}
}
/// Called automatically by `cargo run` command or executing compiled binary
fn main() {
let mut begin: u32 = 1;
let mut end: u32 = 100;
let mut verbose = false;
// Limit borrowing scope for `ap.refer` methods.
{
let mut ap = ArgumentParser::new();
ap.set_description("Iterator based Fizzbuzz example writen in Rust");
ap.refer(&mut begin).add_option(
&["--begin", "--start"],
Store,
"Where iteration begins"
);
ap.refer(&mut end).add_option(
&["--end", "--stop"],
Store,
"Where iteration ends"
);
ap.refer(&mut verbose).add_option(
&["-v", "--verbose"],
StoreTrue,
"How _noisy_ to be"
);
ap.parse_args_or_exit();
}
if verbose {
println!("begin -> {}", begin);
println!("end -> {}", end);
}
let game: Game = Game::new(Some(begin), Some(end));
for state in game {
println!("{}", state.message);
}
}
</code></pre>
<hr>
<h2>Attribution</h2>
<ul>
<li><p><a href="https://doc.rust-lang.org/std/clone/trait.Clone.html" rel="nofollow noreferrer">Rust documentation -- <code>Clone</code></a></p></li>
<li><p><a href="https://doc.rust-lang.org/1.2.0/book/match.html" rel="nofollow noreferrer">Rust book <code>1.2.0</code> -- <code>match</code></a></p></li>
<li><p><a href="https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html" rel="nofollow noreferrer">Rust by Example -- <code>if</code> <code>let</code></a></p></li>
<li><p><a href="https://doc.rust-lang.org/stable/rust-by-example/trait/iter.html" rel="nofollow noreferrer">Rust by Example -- <code>iter</code></a></p></li>
<li><p><a href="https://stackoverflow.com/questions/38406793">StackOverflow -- Why is capitalizing the first letter of a string so convoluted in Rust</a></p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T02:25:51.130",
"Id": "462566",
"Score": "0",
"body": "Excellent suggestion! I've added a bit on how Fizzbuzz is usually described... though I seem to remember it being a drinking game too, so rules of output could differ."
}
] |
[
{
"body": "<p><code>extern crate argparse;</code> 2018 Rust edition doesn't require this, <a href=\"https://doc.rust-lang.org/stable/edition-guide/rust-2018/module-system/path-clarity.html?highlight=EXTERN#use-paths\" rel=\"nofollow noreferrer\">see</a>.</p>\n\n<hr>\n\n<pre class=\"lang-rust prettyprint-override\"><code>return State {\n fizz: false,\n buzz: false,\n count: count,\n message: String::from(\"\"),\n}\n</code></pre>\n\n<p>Here <code>return</code> is not idiomatic and you can omit <code>count:</code>, more info <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#needless_return\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Same thing <code>Game { state: State::new(count), limit: limit }</code>. Also, this time you did omit the return keyword, choice your style but you should be consistent.</p>\n\n<hr>\n\n<pre class=\"lang-rust prettyprint-override\"><code>self.state.fizz = false;\n\nif self.state.count % 3 == 0 {\n self.state.fizz = true;\n self.state.message.push_str(\"fizz\");\n}\n</code></pre>\n\n<p>This is also odd prefer use else branch:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>self.state.fizz = if self.state.count % 3 == 0 {\n self.state.message.push_str(\"fizz\");\n true\n}\nelse {\n false\n}; \n</code></pre>\n\n<hr>\n\n<p><code>self.state.message = String::from(\"\");</code> maybe prefer use <code>clean()</code> to reuse previous allocate memory.</p>\n\n<hr>\n\n<pre class=\"lang-rust prettyprint-override\"><code>if self.state.message.is_empty() {\n self.state.message = self.state.count.to_string();\n} else if let Some(r) = self.state.message.get_mut(0..1) {\n r.make_ascii_uppercase();\n}\n</code></pre>\n\n<p>As you already linked <a href=\"https://stackoverflow.com/a/38406885/7076153\">it</a>, but I think the best is to avoid situation where you need to capitalized first letter. That could be done using the fact that <code>n % 3 == 0</code> and <code>n % 5 == 0</code> is only true for <code>n % 15</code> so you could add a if condition in your algorithm to remove this issue.</p>\n\n<hr>\n\n<pre class=\"lang-rust prettyprint-override\"><code>if self.state.count != self.limit {\n if self.state.count < self.limit {\n self.state.count += 1;\n } else {\n self.state.count -= 1;\n }\n</code></pre>\n\n<p>You just reinvent <a href=\"https://doc.rust-lang.org/std/ops/struct.Range.html\" rel=\"nofollow noreferrer\">Range</a> feature, there is a much better way to do this in rust, see end example.</p>\n\n<hr>\n\n<p><code>Some(self.state.clone())</code>, you could return a <code>&str</code>, see <a href=\"https://stackoverflow.com/a/30423124/7076153\">this</a> answer for how to do it.</p>\n\n<hr>\n\n<p>I have not much to say about <code>argparse</code>.</p>\n\n<hr>\n\n<p><code>let mut begin: u32 = 1;</code>, <code>let mut end: u32 = 100;</code>, <code>let game: Game = Game::new(Some(begin), Some(end));</code>, this is not useful <em>let</em> rust infer your variable type in general.</p>\n\n<hr>\n\n<p>Also, a general critic about your algorithm, your <code>State</code> is odd, there is no point to keep it in your <code>Game</code> iterator. The only thing you need to keep is <code>count</code>, and State neither use <code>count</code> <code>fizz</code> or <code>buzz</code>, you only use the string. So State is basically just a String and contains <code>count</code> that should belong to <code>Game</code> and two useless variable that you don't use. See my end example to see a better way to manage it.</p>\n\n<hr>\n\n<p>The following is an example of what you could have do, removing your strange algorithm but trying to keep your way.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use argparse::{ArgumentParser, Store, StoreTrue};\n\n#[derive(Debug)]\nenum State {\n Fizz,\n Buzz,\n FizzBuzz,\n None(u32),\n}\n\nuse std::fmt;\n\nimpl fmt::Display for State {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match self {\n State::Fizz => write!(f, \"Fizz\"),\n State::Buzz => write!(f, \"Buzz\"),\n State::FizzBuzz => write!(f, \"FizzBuzz\"),\n State::None(n) => write!(f, \"{}\", n),\n }\n }\n}\n\nstruct Game<I> {\n inner: I,\n}\n\nuse std::iter::IntoIterator;\n\nimpl<I> Game<I>\nwhere\n I: Iterator,\n{\n fn new<U>(i: U) -> Self\n where\n U: IntoIterator<IntoIter = I, Item = I::Item>,\n {\n Game {\n inner: i.into_iter(),\n }\n }\n}\n\nimpl<I> Iterator for Game<I>\nwhere\n I: Iterator<Item = u32>,\n{\n type Item = State;\n\n fn next(&mut self) -> Option<State> {\n let n = self.inner.next()?;\n\n let state = if n % 15 == 0 {\n State::FizzBuzz\n } else if n % 3 == 0 {\n State::Fizz\n } else if n % 5 == 0 {\n State::Buzz\n } else {\n State::None(n)\n };\n\n Some(state)\n }\n}\n\nfn main() {\n let mut begin = 1;\n let mut end = 100;\n let mut verbose = false;\n\n {\n let mut ap = ArgumentParser::new();\n ap.set_description(\"Iterator based Fizzbuzz example writen in Rust\");\n\n ap.refer(&mut begin)\n .add_option(&[\"--begin\", \"--start\"], Store, \"Where iteration begins\");\n\n ap.refer(&mut end)\n .add_option(&[\"--end\", \"--stop\"], Store, \"Where iteration ends\");\n\n ap.refer(&mut verbose)\n .add_option(&[\"-v\", \"--verbose\"], StoreTrue, \"How _noisy_ to be\");\n\n ap.parse_args_or_exit();\n }\n\n if verbose {\n println!(\"begin -> {}\", begin);\n println!(\"end -> {}\", end);\n }\n\n let game = Game::new(begin..end);\n for state in game {\n println!(\"{}\", state);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T17:41:47.370",
"Id": "462534",
"Score": "0",
"body": "Thank you! Your way seems much cleaner than what I was writing, that range iterator trick is supper snazzy, and your use of `enum` is fantastic... I'll certainly have to spend more time with your code, and I'll be sure to mark this as the accepted answer if there are no other contenders by the end of the day."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T10:54:51.640",
"Id": "236109",
"ParentId": "236099",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236109",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T04:17:10.823",
"Id": "236099",
"Score": "4",
"Tags": [
"beginner",
"rust",
"fizzbuzz"
],
"Title": "Rust Iterator Fizzbuzz"
}
|
236099
|
<p><strong>This is a follow up to the code found here:</strong></p>
<p><a href="https://codereview.stackexchange.com/questions/235581/multithreaded-hd-image-processing-logistic-reg-classifier-visualization">Multithreaded HD Image Processing + Logistic reg. Classifier + Visualization</a></p>
<p><strong>Description:</strong></p>
<p>This code takes a label and a folder path of subfolders as input that have certain labels ex: trees, cats with each folder containing a list of HD photos corresponding to the folder name, then a multithreaded image processor converts data to .h5 format and classifies photos with the given label using logistic regression or a neural network.</p>
<p>The following link has the code below as well as the necessary .h5 files to make it work and demonstrate an example on classifying dog photos but feel free to test with your own image data and i'm awaiting your feedback for optimizations/improvements/reducing runtime...</p>
<ul>
<li><a href="https://drive.google.com/open?id=19FqVNsbm72dDP6WTDDXqIXv5ZoZbpHbr" rel="nofollow noreferrer">https://drive.google.com/open?id=19FqVNsbm72dDP6WTDDXqIXv5ZoZbpHbr</a></li>
</ul>
<p><strong>Updates:</strong></p>
<ul>
<li>Added a neural network implementation based on Andrew NG's Deep learning course</li>
<li>Wrapped everything into a class <code>ImageClassifier</code></li>
<li>Added some logging and more error checks.</li>
<li>Better organization of the code.</li>
<li>Added more training examples</li>
</ul>
<p>Running the code with <code>random_seed=151</code> should give the following results:</p>
<ul>
<li><strong>Initial sample:</strong></li>
</ul>
<p><a href="https://i.stack.imgur.com/tS3jy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tS3jy.png" alt="initial"></a></p>
<ul>
<li><strong>Sample of the results with 72% accuracy on the test set:</strong></li>
</ul>
<p><a href="https://i.stack.imgur.com/PnqYD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PnqYD.png" alt="res"></a></p>
<ul>
<li><strong>Learning curve(neural net) <code>max_iter=7000, learning_rate=0.015</code>:</strong></li>
</ul>
<p><a href="https://i.stack.imgur.com/Wtwbj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wtwbj.png" alt="lc"></a></p>
<p><strong>Code:</strong></p>
<pre><code>from concurrent.futures import ThreadPoolExecutor, as_completed
import matplotlib.pyplot as plt
from time import perf_counter
import pandas as pd
import numpy as np
import random
import shutil
import cv2
import os
class ImageClassifier:
"""
A tool for classifying and labeling HD images.
"""
def __init__(
self,
folder_path,
target_label,
new_image_size=(80, 80),
threads=5,
fig_size=(9, 9),
random_seed=None,
save_figs=False,
norm_value=255,
sample_dimensions=(2, 5),
display_progress=True,
log_file=None,
layer_dimensions=(20, 7, 5, 1),
initial_parameter_mode='he',
learning_rate=0.0005,
max_iter=2000,
display_nth_iteration=100,
test_size=0.2,
display_figs=None,
new_hdf=False,
show_figs=True,
):
"""
Initialize classification of a given folder.
Args:
folder_path: Path to folder containing labeled sub-folders of images.
target_label: One of the sub-folders name (label to classify).
new_image_size: Image resizing new dimensions.
threads: Number of image processing threads.
fig_size: Display figure dimensions.
random_seed: int representing a random seed.
save_figs: If True, all figures specified will be saved.
norm_value: Normalization value, in this case, 255 the maximum value of a pixel channel.
sample_dimensions: (n_rows, n_columns) dimensions of sample display subplots.
display_progress: If False, progress and results of the classification will not be displayed.
log_file: Path to .txt file name to log the classification progress and results
layer_dimensions: Neural network hidden layer dimensions.
initial_parameter_mode: Initial model parameter initialization mode:
'sq': Square root
'z': Zeros
learning_rate: The learning rate of the classifier.
max_iter: Maximum number of iterations for the optimization algorithm(gradient descent)
display_nth_iteration: Display current cost every n iterations.
'lr': logistic regression.
'nn': Neural network.
test_size: Percentage of the test set size.
display_figs: A list of figures to plot.
'i': If in list, initial sample will be displayed.
'lc': If in list, the learning curve will be displayed.
'r': If in list, the results correct sample will be displayed.
'e': If in list, the results false sample will be displayed.
new_hdf: If True, New .hdf file will be created for every sub-folder.
show_figs: If False, plotted figures will not be displayed.
"""
assert os.path.isdir(folder_path)
self.folder_path = folder_path
if target_label not in os.listdir(folder_path):
raise ValueError(
f'Invalid label: {target_label} Folder not found in {folder_path}'
)
self.target_label = target_label
self.new_image_size = new_image_size
self.threads = threads
self.fig_size = fig_size
if random_seed:
np.random.seed(random_seed)
self.random_seed = random_seed
self.save_figs = save_figs
self.norm_value = norm_value
self.sample_dimensions = sample_dimensions
self.display_progress = display_progress
self.log_file = log_file
self.layer_dimensions = layer_dimensions
self.initial_parameter_mode = initial_parameter_mode
self.learning_rate = learning_rate
self.max_iter = max_iter
self.display_nth_iteration = display_nth_iteration
assert isinstance(display_nth_iteration, int)
self.test_size = test_size
assert 0 <= test_size <= 1
self.display_figs = display_figs
self.new_hdf = new_hdf
self.flat_dimensions = []
self.show_figs = show_figs
def display_message(self, message):
"""
Print a message to the console and log to a .txt file.
Args:
message: Message to be printed.
Return:
None
"""
if self.display_progress:
print(message)
if self.log_file:
print(message, end='\n', file=open(self.log_file, 'a'))
def read_and_resize(self, image):
"""
Read and resize image.
Args:
image: Image path.
Return:
Resized Image.
"""
try:
image = cv2.imread(image)
return cv2.resize(image, self.new_image_size)
except cv2.error:
pass
def folder_to_hdf(self, folder_path):
"""
Save a folder images to hdf format.
Args:
folder_path: Path to folder containing images.
Return:
None
"""
label = folder_path.split('/')[-2]
data, resized = pd.DataFrame(), []
with ThreadPoolExecutor(max_workers=self.threads) as executor:
future_resized_images = {
executor.submit(self.read_and_resize, folder_path + img): img
for img in os.listdir(folder_path)
if img and img != '.DS_Store'
}
for future in as_completed(future_resized_images):
result = future.result()
resized.append(result)
self.display_message(
f'Processing ({label})-{future_resized_images[future]} ... done.'
)
del future_resized_images[future]
data['Images'] = resized
data['Label'] = label
data.to_hdf(folder_path + label + '.h5', label)
def folders_to_hdf(self, sub_folders=None):
"""
Convert image data(for every sub-folder self.folder_path) to .hdf format.
Args:
sub_folders: A list of sub_folder names to convert.
Return:
None
"""
if not sub_folders:
for folder_name in os.listdir(self.folder_path):
if folder_name != '.DS_Store':
path = ''.join([self.folder_path, folder_name, '/'])
self.folder_to_hdf(path)
if sub_folders:
for folder_name in sub_folders:
path = ''.join([self.folder_path, folder_name, '/'])
if folder_name not in os.listdir(self.folder_path):
raise FileNotFoundError(f'Folder {path}')
self.folder_to_hdf(path)
def clear_hdf(self, sub_folders=None):
"""
Delete every .h5 for every sub-folder in self.folder_path.
Args:
sub_folders: A list of sub_folder names to clear from .hdf files.
Return:
None
"""
if not sub_folders:
for folder_name in os.listdir(self.folder_path):
if folder_name != '.DS_Store':
try:
file_name = ''.join(
[self.folder_path, folder_name, '/', folder_name, '.h5']
)
os.remove(file_name)
self.display_message(f'Removed {file_name.split("/")[-1]}')
except FileNotFoundError:
pass
if sub_folders:
for folder_name in sub_folders:
file_name = ''.join(
[self.folder_path, folder_name, '/', folder_name, '.h5']
)
if folder_name not in os.listdir(self.folder_path):
raise FileNotFoundError(f'File not found {file_name}')
try:
os.remove(file_name)
self.display_message(f'Removed {file_name.split("/")[-1]}')
except FileNotFoundError:
pass
def load_hdf(self, sub_folders=None):
"""
Load classification data from .h5 files.
Args:
sub_folders: Sub-folders to load.
Return:
(x, y, frames).
"""
file_names = []
if not sub_folders:
file_names = [
''.join([self.folder_path, folder_name, '/', folder_name, '.h5'])
for folder_name in os.listdir(self.folder_path)
if folder_name != '.DS_Store'
]
if sub_folders:
for folder_name in sub_folders:
path = ''.join([self.folder_path, folder_name, '/', folder_name, '.h5'])
if folder_name not in os.listdir(self.folder_path):
raise FileNotFoundError(f'File not found {path}')
file_names = [
''.join([self.folder_path, folder_name, '/', folder_name, '.h5'])
for folder_name in sub_folders
]
frames = [pd.read_hdf(file_name) for file_name in file_names]
frames = pd.concat(frames).dropna()
frames['Classification'] = 0
frames.loc[frames['Label'] == self.target_label, 'Classification'] = 1
new_index = np.random.permutation(frames.index)
frames.index = new_index
frames.sort_index(inplace=True)
image_data, labels = (
np.array(list(frames['Images'])),
np.array(list(frames['Classification'])),
)
return image_data, labels, frames
def display_sample_images(self, title, image_data, labels=None):
"""
Plot and display a sample of size(self.sample_dimensions).
Args:
title: Title of the sample image.
image_data: numpy array of image data.
labels: numpy array of label data(0s and 1s).
Return:
None
"""
if not self.show_figs and not self.save_figs:
return
rows, columns = self.sample_dimensions
fig = plt.figure(figsize=self.fig_size)
plt.title(title)
for i in range(rows * columns):
img = image_data[i]
ax = fig.add_subplot(rows, columns, i + 1)
if isinstance(labels, np.ndarray):
ax.title.set_text(f'Prediction: {labels[i]}')
plt.imshow(img)
if self.save_figs:
plt.savefig(title + '.png')
if self.show_figs:
plt.show()
def pre_process(self, sub_folders=None):
"""
Split the data into train and test sets and prepare the data for further processing.
Args:
sub_folders: Sub-folders to load.
Return:
x_train, y_train, x_test, y_test, frames.
"""
image_data, labels, frames = self.load_hdf(sub_folders)
rows, columns = self.sample_dimensions
total_images = len(image_data)
title = (
f'Initial(before prediction) {rows} x {columns} '
f'data sample (Classification of {self.target_label})'
)
if self.display_figs and 'i' in self.display_figs:
self.display_sample_images(title, image_data)
image_data = image_data.reshape(total_images, -1) / self.norm_value
labels = labels.reshape(total_images, -1)
separation_index = int(self.test_size * total_images)
x_train = image_data[separation_index:].T
y_train = labels[separation_index:].T
x_test = image_data[:separation_index].T
y_test = labels[:separation_index].T
self.flat_dimensions.append(x_train.shape[0])
self.display_message(f'Total number of images: {total_images}')
self.display_message(f'x_train shape: {x_train.shape}')
self.display_message(f'y_train shape: {y_train.shape}')
self.display_message(f'x_test shape: {x_test.shape}')
self.display_message(f'y_test shape: {y_test.shape}')
return x_train, y_train, x_test, y_test, frames
def initialize_parameters(self):
"""
Initialize weights and bias for the given layer of the neural network dimensions.
Return:
A dictionary containing parameters [w1, w2, ... wn] and [b1, b2, ... bn].
"""
parameters = {}
self.flat_dimensions.extend(self.layer_dimensions)
layer_dimensions = self.flat_dimensions
for n in range(1, len(layer_dimensions)):
if self.initial_parameter_mode == 'he':
parameters['w' + str(n)] = np.random.randn(
layer_dimensions[n], layer_dimensions[n - 1]
) * (np.sqrt(2.0 / layer_dimensions[n - 1]))
parameters['b' + str(n)] = np.zeros((layer_dimensions[n], 1))
if self.initial_parameter_mode == 'sq':
parameters['w' + str(n)] = np.random.randn(
layer_dimensions[n], layer_dimensions[n - 1]
) / np.sqrt(layer_dimensions[n - 1])
parameters['b' + str(n)] = np.zeros((layer_dimensions[n], 1))
if self.initial_parameter_mode == 'z':
parameters['w' + str(n)] = np.zeros(
(layer_dimensions[n], layer_dimensions[n - 1])
)
parameters['b' + str(n)] = np.zeros((layer_dimensions[n], 1))
return parameters
@staticmethod
def sigmoid(x):
"""
Calculate sigmoid function(logistic regression).
Args:
x: Image data in the following shape(pixels * pixels * 3, number of images).
Return:
sigmoid(x).
"""
return 1 / (1 + np.exp(-x))
@staticmethod
def sigmoid_nn(x):
"""
Apply the sigmoid function(neural network).
Args:
x: numpy array of inputs.
Return:
a, x
a: Output of sigmoid.
"""
return 1 / (1 + np.exp(-x)), x
@staticmethod
def sigmoid_back(da, z):
"""
Back propagate a single Sigmoid unit(neural network).
Args:
da: Post activation gradient.
z: The output of the linear layer.
Return:
dz: gradient of the cost with respect to z.
"""
sig = 1 / (1 + np.exp(-z))
dz = da * sig * (1 - sig)
return dz
@staticmethod
def relu(z):
"""
Apply the RELU function(neural network).
Args:
z: The output of the linear layer.
Return:
a, z
a: Output of RELU.
"""
return np.maximum(0, z), z
@staticmethod
def relu_back(da, z):
"""
Back propagate a single RELU unit(neural network).
Args:
da: Post activation gradient.
z: The output of the linear layer.
Return:
dz: gradient of the cost with respect to z.
"""
dz = np.array(da, copy=True)
dz[z <= 0] = 0
return dz
def compute_cost(self, w, b, x, y):
"""
Compute cost function using forward and back propagation(logistic regression).
Args:
w: numpy array of weights(also called Theta).
b: Bias(int)
x: Image data in the following shape(pixels * pixels * 3, number of images)
y: Label numpy array of labels(0s and 1s)
Return:
Cost and gradient(dw and db).
"""
total_images = x.shape[1]
activation = self.sigmoid(np.dot(w.T, x) + b)
cost = (-1 / total_images) * (
np.sum(y * np.log(activation) + (1 - y) * np.log(1 - activation))
)
cost = np.squeeze(cost)
dw = (1 / total_images) * np.dot(x, (activation - y).T)
db = (1 / total_images) * np.sum(activation - y)
return cost, dw, db
@staticmethod
def compute_cost_nn(last_activation, y):
"""
Compute the cost function for the neural network using forward propagation.
Args:
last_activation: The last post-activation value.
y: numpy array of labels.
Return:
Cross-entropy cost.
"""
cost = -(
y * np.log(last_activation) + (1 - y) * np.log(1 - last_activation)
).mean()
return np.squeeze(cost)
@staticmethod
def linear_forward(a, w, b):
"""
Apply the linear part of a single layer's forward propagation.
Args:
a: Activations from previous layer(or inputs X)
w: numpy array of weights.
b: numpy array of bias.
Return:
z, a, w, b
z: The pre-activation parameter.
"""
z = np.dot(w, a) + b
return z, a, w, b
def linear_activation_forward(self, a_prev, a_func, w, b):
"""
Apply the forward propagation for the LINEAR->ACTIVATION layer.
Args:
a_prev: Activations from previous layer(or inputs X)
a_func: Activation function 's' for sigmoid or 'r' for RELU.
w: numpy array of weights.
b: numpy array of bias.
Return:
post_a, linear_cache, activation_cache.
"""
linear_cache, activation_cache, post_a = 0, 0, 0
if a_func == 's':
z, *linear_cache = self.linear_forward(a_prev, w, b)
post_a, activation_cache = self.sigmoid_nn(z)
if a_func == 'r':
z, *linear_cache = self.linear_forward(a_prev, w, b)
post_a, activation_cache = self.relu(z)
return post_a, linear_cache, activation_cache
def forward_prop(self, x, parameters):
"""
Apply forward propagation for the [LINEAR- > RELU] * (L-1) -> LINEAR -> SIGMOID computation
Args:
x: Image data in the following shape(pixels * pixels * 3, number of images).
parameters: A dictionary of initial parameters.
Return: last_activation, caches.
last_activation: The last post-activation value.
caches: A list of caches containing every cache of linear_activation_forward()
"""
caches = []
activation = x
layers = len(parameters) // 2
for layer in range(1, layers):
a_prev = activation
current_weights = parameters['w' + str(layer)]
current_bias = parameters['b' + str(layer)]
activation, *cache = self.linear_activation_forward(
a_prev, 'r', current_weights, current_bias
)
caches.append(cache)
last_weight = parameters['w' + str(layers)]
last_bias = parameters['b' + str(layers)]
last_activation, *cache = self.linear_activation_forward(
activation, 's', last_weight, last_bias
)
caches.append(cache)
return last_activation, caches
@staticmethod
def linear_back(dz, cache):
"""
Apply the linear part of a single neural network layer's back propagation.
Args:
dz: Gradient of the cost with respect to the linear output of current layer.
cache: A tuple containing current layer's forward propagation cache(a_prev, w, b).
Return:
da_prev, dw, db
da_prev: Gradient of the cost with respect to the activation(of previous layer)
dw: Gradient of the cost with respect to w
db: Gradient of the cost with respect to b
"""
a_prev, w, b = cache
m = a_prev.shape[1]
dw = np.dot(dz, a_prev.T) / m
db = np.sum(dz, axis=1, keepdims=True) / m
da_prev = np.dot(w.T, dz)
return da_prev, dw, db
def linear_activation_back(self, a_func, da, cache):
"""
Apply the back propagation for the LINEAR->ACTIVATION layer.
Args:
a_func: Activation function 's' for sigmoid or 'r' for RELU.
da: Post activation gradient for current layer.
cache: linear_cache, activation_cache from linear_activation_forward().
Return:
da_prev, dw, db
da_prev: Gradient of the cost with respect to the activation(of previous layer)
dw: Gradient of the cost with respect to w
db: Gradient of the cost with respect to b
"""
da_prev, dw, db = 0, 0, 0
linear_cache, activation_cache = cache
if a_func == 's':
dz = self.sigmoid_back(da, activation_cache)
da_prev, dw, db = self.linear_back(dz, linear_cache)
if a_func == 'r':
dz = self.relu_back(da, activation_cache)
da_prev, dw, db = self.linear_back(dz, linear_cache)
return da_prev, dw, db
def back_prop(self, last_activation, y, caches):
"""
Apply the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group.
Args:
last_activation: The last post-activation value.
y: numpy array of labels.
caches: A list of caches containing every cache of linear_activation_forward()
Return:
A dictionary of gradients.
"""
grads = {}
layers = len(caches)
y = y.reshape(last_activation.shape)
d_last_activation = -(
np.divide(y, last_activation) - np.divide(1 - y, 1 - last_activation)
)
current_cache = caches[layers - 1]
(
grads['da' + str(layers)],
grads['dw' + str(layers)],
grads['db' + str(layers)],
) = self.linear_activation_back('s', d_last_activation, current_cache)
for layer in reversed(range(layers - 1)):
current_cache = caches[layer]
da_prev_temp, dw_temp, db_temp = self.linear_activation_back(
'r', grads['da' + str(layer + 2)], current_cache
)
grads['da' + str(layer + 1)] = da_prev_temp
grads['dw' + str(layer + 1)] = dw_temp
grads['db' + str(layer + 1)] = db_temp
return grads
@staticmethod
def update_params(parameters, grads, learning_rate):
"""
Update parameters for gradient descent(neural network).
Args:
parameters: A dictionary of initial parameters.
grads: A dictionary of gradients.
learning_rate: The learning rate of gradient descent.
Return:
Updated parameters.
"""
layers = len(parameters) // 2
for layer in range(layers):
weight_decrease = learning_rate * grads['dw' + str(layer + 1)]
parameters['w' + str(layer + 1)] -= weight_decrease
bias_decrease = learning_rate * grads['db' + str(layer + 1)]
parameters['b' + str(layer + 1)] -= bias_decrease
return parameters
def g_descent(self, w, b, x, y):
"""
Optimize weights and bias using gradient descent algorithm(logistic regression).
Args:
w: numpy array of weights(also called Theta).
b: Bias(int)
x: Image data in the following shape(pixels * pixels * 3, number of images)
y: Label numpy array of labels(0s and 1s)
Return:
w, b, dw, db, costs
"""
dw, db, costs = 0, 0, []
for iteration in range(self.max_iter):
cost, dw, db = self.compute_cost(w, b, x, y)
w -= dw * self.learning_rate
b -= db * self.learning_rate
costs.append(cost)
if iteration % self.display_nth_iteration == 0:
self.display_message(
f'Iteration number: {iteration} out of {self.max_iter} iterations'
)
self.display_message(f'Current cost: {cost}\n')
return w, b, dw, db, costs
def g_descent_nn(self, x, y, parameters):
"""
Optimize weights and bias using gradient descent algorithm(neural network).
Args:
x: Image data in the following shape(pixels * pixels * 3, number of images)
y: Label numpy array of labels(0s and 1s)
parameters: A dictionary of initial parameters(weights/bias).
Return:
parameters, costs
"""
costs = []
for iteration in range(self.max_iter):
last_activation, caches = self.forward_prop(x, parameters)
current_cost = self.compute_cost_nn(last_activation, y)
costs.append(current_cost)
grads = self.back_prop(last_activation, y, caches)
parameters = self.update_params(parameters, grads, self.learning_rate)
if iteration % self.display_nth_iteration == 0:
self.display_message(
f'Iteration number: {iteration} out of {self.max_iter} iterations'
)
self.display_message(f'Current cost: {current_cost}\n')
return parameters, costs
def predict(self, w, b, x):
"""
Predict labels of x (logistic regression).
Args:
w: numpy array of weights(also called Theta).
b: Bias(int)
x: Image data in the following shape(pixels * pixels * 3, number of images)
Return:
Y^ numpy array of predictions.
"""
w = w.reshape(x.shape[0], 1)
activation = self.sigmoid(np.dot(w.T, x) + b)
activation[activation > 0.5] = 1
activation[activation <= 0.5] = 0
return activation
def predict_nn(self, x, parameters):
"""
Predict labels using a neural network.
Args:
x: Image data in the following shape(pixels * pixels * 3, number of images)
parameters: A dictionary of parameters of the trained model.
Return:
Y^ numpy array of predictions.
"""
last_activation, caches = self.forward_prop(x, parameters)
last_activation[last_activation > 0.5] = 1
last_activation[last_activation <= 0.5] = 0
return last_activation
def plot_figure(self, figure_type, frames=None, costs=None):
"""
Plot samples or learning curve.
Args:
figure_type: String indication of the figure to plot.
frames: pandas DataFrame with the image data.
costs: A list of costs for plotting the learning curve.
Return:
None
"""
rows, columns = self.sample_dimensions[0], self.sample_dimensions[1]
sample_size = rows * columns
if figure_type == 'lc':
plt.figure(figsize=self.fig_size)
plt.title('Learning curve')
plt.plot(range(self.max_iter), costs)
plt.xlabel('Iterations')
plt.ylabel('Cost')
if self.save_figs:
plt.savefig('Learning curve' + '.png')
if figure_type == 'r':
to_display = frames[frames['Accuracy'] == 1][
['Images', 'Predictions']
].head(sample_size)
images = np.array(list(to_display['Images']))
predictions = np.array(list(to_display['Predictions']))
title = f'Classification of {self.target_label} results sample'
self.display_sample_images(title, images, predictions)
if figure_type == 'e':
to_display = frames[frames['Accuracy'] == 0][
['Images', 'Predictions']
].head(sample_size)
images = np.array(list(to_display['Images']))
predictions = np.array(list(to_display['Predictions']))
title = f'Sample of the misclassified images'
self.display_sample_images(title, images, predictions)
def save_run_details(
self, path, alg, accuracy, total_time, image_size, x_train, x_test, frames
):
"""
Save run details to a .txt file.
Args:
path: Path to save the .txt file.
alg: Classification algorithm.
accuracy: Train and test accuracy.
total_time: Total time taken in seconds.
image_size: Image dimensions.
x_train: Training set.
x_test: Test set.
frames: pandas DataFrame with
Return:
None
"""
with open(path + '/' + 'run_details.txt', 'w') as details:
details.write(f'Algorithm: {alg}\n')
details.write(f'Iterations: {self.max_iter} iterations.\n')
details.write(f'Training accuracy: {accuracy[0]}%\n')
details.write(f'Test accuracy: {accuracy[1]}%\n')
details.write(f'Image size: {image_size} x {image_size}\n')
details.write(f'Learning rate: {self.learning_rate}\n')
details.write(f'Test sample: {self.test_size}\n')
details.write(f'Layer dimensions: {self.flat_dimensions}\n')
details.write(f'Data set size: {len(x_train) + len(x_test)}\n')
details.write(f'Training set size: {len(x_train)}\n')
details.write(f'Test set size: {len(x_test)}\n')
details.write(
f'Number of {self.target_label} examples: {len(frames[frames["Classification"] == 1])}\n'
)
details.write(
f'Number of non-{self.target_label} examples: {len(frames[frames["Classification"] == 0])}\n'
)
details.write(f'Total time: {total_time} seconds.')
def predict_folder(self, alg, sub_folders=None):
"""
Classify target label among specified folders.
Args:
alg: Algorithm to use for classification:
'lr': Logistic regression.
'nn': Neural network.
sub_folders: Sub_folders to load and process.
Return:
pandas DataFrame with the results.
"""
start_time = perf_counter()
if self.new_hdf:
self.clear_hdf(sub_folders)
self.folders_to_hdf(sub_folders)
x_train, y_train, x_test, y_test, frames = self.pre_process(sub_folders)
train_predictions, test_predictions, all_predictions, costs = (
None,
None,
None,
None,
)
if alg == 'lr':
w, b = np.zeros((len(x_train), 1)), 0
w, b, dw, db, costs = self.g_descent(w, b, x_train, y_train)
train_predictions = self.predict(w, b, x_train)
test_predictions = self.predict(w, b, x_test)
all_predictions = np.append(train_predictions, test_predictions)
if alg == 'nn':
initial_parameters = self.initialize_parameters()
parameters, costs = self.g_descent_nn(x_train, y_train, initial_parameters)
train_predictions = self.predict_nn(x_train, parameters)
test_predictions = self.predict_nn(x_test, parameters)
all_predictions = np.append(train_predictions, test_predictions)
training_accuracy = 100 - np.mean(np.abs(train_predictions - y_train)) * 100
test_accuracy = 100 - np.mean(np.abs(test_predictions - y_test)) * 100
frames['Predictions'] = all_predictions
frames['Accuracy'] = 0
frames.loc[frames['Predictions'] == frames['Classification'], 'Accuracy'] = 1
self.display_message(f'Training accuracy: {training_accuracy}%')
self.display_message(f'Test accuracy: {test_accuracy}%')
self.display_message(f'Train predictions: \n{train_predictions}')
self.display_message(f'Train actual: \n{y_train}')
self.display_message(f'Test predictions: \n{test_predictions}')
self.display_message(f'Test actual: \n{y_test}')
if self.display_figs and 'lc' in self.display_figs:
self.plot_figure('lc', costs=costs)
if self.display_figs and 'r' in self.display_figs:
self.plot_figure('r', frames)
if self.display_figs and 'e' in self.display_figs:
self.plot_figure('e', frames)
if self.show_figs:
plt.show()
end_time = perf_counter()
total_time = end_time - start_time
self.display_message(f'Time: {total_time} seconds.')
if self.log_file or self.save_figs:
new_folder_name = f'{alg}-{self.max_iter}-{self.learning_rate}-{random.randint(10 ** 6, 10 ** 7)}'
os.mkdir(new_folder_name)
img_size = np.sqrt(self.flat_dimensions[0] / 3)
self.save_run_details(
'./' + new_folder_name,
alg,
(training_accuracy, test_accuracy),
total_time,
img_size,
x_train,
x_test,
frames
)
for file_name in os.listdir('.'):
if file_name.endswith('.png') or file_name.endswith('.txt'):
shutil.move(file_name, new_folder_name)
return frames
if __name__ == '__main__':
clf = ImageClassifier(
'test_photos/',
'Dog',
display_figs=['i', 'lc', 'r', 'e'],
max_iter=7000,
learning_rate=0.0015,
show_figs=True,
save_figs=True,
log_file='log.txt',
random_seed=151
)
clf.predict_folder('nn')
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T05:22:34.963",
"Id": "236100",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"multithreading",
"machine-learning",
"neural-network"
],
"Title": "Multi-threaded HD Image classifier using a neural network"
}
|
236100
|
<p>I am working on struts 2 based web application, where an Action Class render 7000+ records in UI. The query which fetches the record is already been optimized by the DB developer, but instead it took around 7+ seconds to load UI it also freeze the UI for a moment,on deep inspection I have found there is something wrong with java code itself, but for more deep analysis, I would like my code to be review by community here.</p>
<p>In Action class, the fetched data collected and one by one putting into the <code>JSONObject</code> later on it then putting into in the <code>JSONArray</code>, it seems, such kind of implementation took time.</p>
<pre><code>public String execute() throws Exception {
logger.debug("---------Enter In HoldingMembersDataAction---------");
JSONObject obj = new JSONObject();
JSONObject obj1 = null;
ArrayList<JSONArray> extlist = new ArrayList<JSONArray>();
JSONArray arr = new JSONArray(extlist);
/* Field is use to store the session id */
int total = 0;
/* List is use to store the account details object */
List<Account> accountList = null;
try {
HttpServletRequest request = ServletActionContext.getRequest();
String holdingId = request.getParameter("holdingId");
CreditTrade creditTrade = new CreditTradeDAO();
logger.debug("Sort In Add Member" + getSort());
PagingInfo pageInfo= new PagingInfo(getStart(), getLimit(), getSort(), getDir());
pageInfo.setSearchText(getSearchText());
/* accountList = creditTrade.getAccountMemberList(holdingId,
getCoreProduct(), getSearchText().trim(), getMemberType(),
getMemberCountry(), getSort(), getDir());*/
accountList = creditTrade.getAccountMembersList(holdingId,
getCoreProduct(),getMemberType(),
getMemberCountry(),pageInfo);
/*
* Iterate account list and prepare JSONObject
*/
for (Account ac : accountList) {
String memberType=ac.getMemberType();
memberType=memberType.replaceAll(",", ", ");
obj1 = new JSONObject();
obj1.put("accountId", ac.getId());
obj1.put("externalReferenceID", ac.getExternalReferenceId());
obj1.put("name", ac.getName());
obj1.put("countryName", ac.getVisitingCountryName());
obj1.put("membercategory", memberType);
obj1.put("membershipId", ac.getMemberID());
obj1.put("isPartOfHolding", ac.getIsPartOfHolding());
obj1.put("isPartOfSameHolding", ac.getIsPartOfSameHolding());
arr.put(obj1);
}
//obj.put("totalCount", total);
//obj.put("data", arr);
/* Write JSONData into output stream */
writeJSONData(arr);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
</code></pre>
<p>I wanna ask if such usage of JSONObject and JSONArray is correct, or it can be furhter optimized to reduce time.</p>
<p><strong>Network Activity Log:</strong></p>
<p><a href="https://i.stack.imgur.com/92qal.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/92qal.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/cTIiy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cTIiy.png" alt="enter image description here"></a></p>
<p><strong>RENDER TIME:</strong></p>
<pre><code>TimeAnazer timeAna = new TimeAnazer();
timeAna.startMillSec();
accountList = creditTrade.getAccountMemberList(holdingId,
getCoreProduct(), getSearchText().trim(), getMemberType(),
getMemberCountry(), getSort(), getDir());
timeAna.endMillSec();
timeAna.showTimeTaken("HoldingMembersDataAction::getAccountMemberList");
timeAna.resetTime();
</code></pre>
<p><a href="https://i.stack.imgur.com/HX0ix.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HX0ix.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T07:11:07.063",
"Id": "462475",
"Score": "0",
"body": "Does it work? Is the output correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T07:20:33.000",
"Id": "462476",
"Score": "0",
"body": "Is there an actual measured timing problem? If you render 7000 objects in HTML your DOM becomes *huge* and it is no surprise that the application has poor response time. However, *measure* the time of your method to make sure that you find the correct place to \"optimize\". How long does it take from start to return? How long does the call to `creditTrade.getAccountMembersList()` take? Without this information, there's nothing you (or we) can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:53:06.473",
"Id": "462482",
"Score": "0",
"body": "output is correct and perfect, but it take lot of time to render"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:59:45.570",
"Id": "462483",
"Score": "0",
"body": "@mtj see my edits please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:22:25.027",
"Id": "462490",
"Score": "0",
"body": "@user9634982 Your measurement shows 1.5s for the backend call, which means, that from the 7+ seconds for rendering the page, at least 5.5 seconds are taken by the client. Furthermore, as I cannot see any long-runners in your method, you definitely need measurements on backend side, as stated in my first comment. Especially, as the conversion from one object type to another is usually small, I suspect that the main runtime will be taken by the call to `creditTrade.getAccountMembersList()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T10:04:02.083",
"Id": "462503",
"Score": "0",
"body": "Yeah you are correct, the measurement time is taken by `creditTrade.getAccountMembersList()`,it also hangs the grid for a second"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T10:48:19.163",
"Id": "462504",
"Score": "0",
"body": "Please see my edits"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T06:55:17.163",
"Id": "236102",
"Score": "1",
"Tags": [
"java",
"struts2"
],
"Title": "Is the usage of JSONObject and JSONArray is correct, as it take lot of time to render UI"
}
|
236102
|
<p>I am using the least_squares() function from the scipy.optimize module to calibrate a Canopy structural dynamic model (CSDM). The calibrated model is then used to predict leaf area index (lai) based on thermal time (tt) data. I tried two variants, the first did not use the "loss" parameter of the least_squares() function, while the second set this parameter to produce a robust model. Both models give me runtime warnings even though the optimization complete successfully.</p>
<p>With the simple least squares model I get these warnings: </p>
<pre class="lang-py prettyprint-override"><code>__main__:24: RuntimeWarning: overflow encountered in exp
__main__:24: RuntimeWarning: divide by zero encountered in true_divide
</code></pre>
<p>With the robust least squares model I get these warnings: </p>
<pre class="lang-py prettyprint-override"><code>__main__:24: RuntimeWarning: overflow encountered in exp
__main__:24: RuntimeWarning: overflow encountered in power
</code></pre>
<pre class="lang-py prettyprint-override"><code># Canopy structural dynamic model (CSDM) implementation using scipy.optimize
import numpy as np
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
#independent variable training data
tt_train = np.array([299.135, 408.143, 736.124, 1023.94, 1088.47, 1227.22,
1313.94, 1392.93, 1482.83, 1581.96, 2064.27, 2277.95, 2394.62, 2519.23])
#dependent variable training data
lai_train = np.array([0.0304313, 0.0833402, 0.682014, 0.973261, 2.54978,
4.93747, 5.31949, 6.25236, 6.64175, 7.3717, 3.61623, 2.96673, 1.72345, 0.803591])
# The CSDM formula (Duveiller et al. 2011. Retrieving wheat Green Area Index during the growing season...)
# LAI = k * (1 / ((1 + Exp(-a * (tt - T0 - Ta))) ^ c) - Exp(b * (tt - T0 - Tb)))
# initial estimates of parameters
To = 50 # plant emergence (x[0])
Ta = 1000 # midgrowth (x[1])
Tb = 2000 # end of cenescence (x[2])
k = 6 # scaling factor (arox. max LAI) (x[3])
a = 0.01 # rate of growth (x[4])
b = 0.01 # rate of senescence (x[5])
c = 1 # parameter allowing some plasticity to the shape of the curv (x[6])
x0 = np.array([To, Ta, Tb, k, a, b, c])
def model(x, tt):
return x[3] * (1 / ((1 + np.exp(-x[4] * (tt - x[0] - x[1]))) ** x[6]) - np.exp(x[5] * (tt - x[0] - x[2])))
#Define the function computing residuals for least-squares minimization
def fun(x, tt, lai):
return model(x, tt) - lai
#simple model
res_lsq = least_squares(fun, x0, args=(tt_train, lai_train))
#robust model
res_robust = least_squares(fun, x0, loss='soft_l1', f_scale=1, args=(tt_train, lai_train))
# termal time data for full season
tt_test = np.array([11.7584,22.1838,34.0008,47.7174,64.3092,81.1832,90.1728,101.494,116.125,127.732,140.229,
154.381,170.5,185.707,201.368,217.642,233.593,249.703,266.233,283.074,299.135,314.386,327.024,337.58,344.699,
354.328,367.247,379.627,391.51,400.93,408.143,414.941,423.678,433.2,442.072,448.923,454.699,462.479,471.187,
481.93,492.389,499.845,508.979,522.702,533.663,540.178,547.342,553.534,560.451,569.112,574.813,580.323,
589.95,597.542,601.937,606.161,609.48,613.321,615.876,619.44,623.754,630,636.784,640.978,643.625,646.384,
650.608,657.538,664.192,670.672,673.271,674.191,679.735,685.526,694.327,700.824,710.817,714.799,717.233,
718.539,718.669,718.669,718.669,719.985,726.038,736.124,740.441,745.865,751.463,757.85,761.474,763.216,
769.154,772.596,778.288,782.517,785.868,791.79,798.324,803.554,806.697,809.536,813.457,817.2,817.902,
817.902,817.902,817.902,817.902,820.271,824.126,826.609,826.668,827.619,827.619,827.629,827.629,827.629,
827.629,827.629,833.344,841.854,849.289,854.49,859.806,871.709,878.918,882.926,885.63,888.126,892.953,
898.661,899.547,900.031,903.327,906.253,909.183,912.358,917.222,921.757,925.36,927.341,927.819,929.745,
930.731,930.949,932.384,932.384,932.384,932.384,932.384,932.384,932.384,933.757,933.757,933.757,936.283,
940.396,945.01,952.758,961.418,973.865,986.804,999.508,1012.5,1023.94,1034.92,1048.68,1052.39,1052.39,
1052.8,1053.73,1053.73,1053.73,1054.09,1054.31,1056.48,1061.43,1068.88,1076.67,1088.47,1104.89,1119.38,
1130.99,1141.1,1155.06,1171.19,1185.48,1199.21,1213.17,1227.22,1242.87,1260.89,1277.97,1295.61,1313.94,
1331.04,1346.59,1359.13,1375.4,1392.93,1408.89,1424.56,1442.76,1461.92,1482.83,1502.78,1523.67,1544.39,
1563.29,1581.96,1599.23,1619.32,1637.81,1656.31,1678.33,1700.06,1721.59,1741.63,1761.09,1779.76,1799.04,
1818.54,1836.93,1855.25,1871.02,1890.62,1909.82,1928.01,1946.39,1966.27,1983.82,2003.26,2023.74,2043.92,
2064.27,2085.74,2107.14,2127.92,2148.44,2167.92,2188.01,2208.63,2231.33,2254.54,2277.95,2301.32,2323.56,
2347.52,2370.52,2394.62,2419.89,2442.6,2466.69,2492.51,2519.23,2540.78,2563.82,2585.14,2607.89,2628.95,
2652.57,2676.55,2700.73,2724,2742.09,2759.06,2778.77,2798.12,2815.01,2834.76,2855.37,2878.56])
# apply the two models to the full season data
lai_lsq = model(res_lsq.x, tt_test)
lai_robust = model(res_robust.x, tt_test)
# plot the two model fits
plt.plot(tt_train, lai_train, 'o', markersize=4, label='training data')
plt.plot(tt_test, lai_lsq, label='fitted lsq model')
plt.plot(tt_test, lai_robust, label='fitted robust model')
plt.xlabel("tt")
plt.ylabel("LAI")
plt.legend(loc='upper left')
plt.show()
</code></pre>
<p>Here is an image showing the fitted lines for the two models. The simple lsq model seems OK but this overflow warnings may indicate serious problem that compromise the algorithm (especially divide by zero). The robust model at the other hand is totally wrong.</p>
<p><a href="https://i.stack.imgur.com/cGFaO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cGFaO.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:22:39.700",
"Id": "462479",
"Score": "0",
"body": "Welcome to CodeReview@SE. I see your question close to the border between what is and isn't [on topic here](https://codereview.stackexchange.com/help/on-topic): please explicitly express one or more concerns about the code presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T13:48:16.503",
"Id": "462509",
"Score": "0",
"body": "An overflow in `np.exp(-x[4] * (tt - x[0] - x[1]))) ** x[6])` does not sound so unexpected, `x[6]` does not even need to be very large, depending on the other parameters, e.g. `np.exp(2**10) = inf`. And then `1./np.exp(-2**10)` is a divide by zero."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T14:37:18.133",
"Id": "462514",
"Score": "0",
"body": "@Graipher thanks for the explanation. This equation is popular in the literature in my field. I have had some success in finding the parameters with Excel Solver but using another data set. But implementation in Python seems to be quite difficult; or maybe impossible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T09:01:09.273",
"Id": "462790",
"Score": "0",
"body": "I found that there were no overflow and other warnings when constrain the model parameters to vary in certain bounds. I set the bounds parameter of least_squares like this: `bounds=([1, 500, 1500, 3, 0.001, 0.001, 0.5], [50, 2000, 3000, 9, 0.1, 0.1, 1.5])`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T09:40:14.420",
"Id": "462794",
"Score": "0",
"body": "Also, the data sets should be cast from float32 to float64."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T07:56:46.483",
"Id": "236103",
"Score": "1",
"Tags": [
"python",
"numpy",
"scipy"
],
"Title": "Python Implementation of Canopy Structural Dynamic Model using scipy.optimize.least_squares"
}
|
236103
|
<p>I have a system of 49 equations and 49 unknowns (<span class="math-container">\$x_{1},...,x_{49}\$</span>). All equations have the following form. </p>
<p><span class="math-container">\$x_{s}\sum_{r=1}^{R}\sum_{t=1}^{T}a_{s,t}b_{rs,t}=\sum_{r=1}^{R}\sum_{t=1}^{T}a_{r,t}b_{sr,t}x_{r}\$</span></p>
<p>where <span class="math-container">\$s = 1,...,49\$</span> with <span class="math-container">\$S = R = 50\$</span> and <span class="math-container">\$T = 30\$</span>. The <span class="math-container">\$a\$</span>'s, the <span class="math-container">\$b\$</span>'s and <span class="math-container">\$x_{50}\$</span> are known parameters. Since all equations have the same form, I believe that vectorizing the problem is possible. I appreciate any suggestions of how to do this. </p>
<hr>
<p>The code below solves a smaller system with <span class="math-container">\$S=R=T=3\$</span>. The code runs. I describe how the parameters are arranged beneath the code. </p>
<pre><code> %% Define parameters
T = 3; % Number of types (T)
S = 3; % Number of senders (S)
R = S; % Number of receivers (R), equals the number of senders
A = [.1 .1 .1 % Columns are senders (S), rows are types (T)
.3 .3 .6
.6 .6 .3];
B1 = [.9 .0 .1
.5 .1 .2
.8 .2 .1];
B2 = [.0 .7 .2
.2 .9 .0
.1 .8 .1];
B3 = [.1 .3 .7
.3 .0 .8
.1 .0 .8];
B = zeros(T,R,S); % Initialize
B(:,1,:) = B1; % Pages of B are receivers
B(:,2,:) = B2; % Rows of B are types
B(:,3,:) = B3; % Columns of B are senders
% Starting values
x0 = [36 26];
% Call functions
F = fsolve(@(x) myfun1(x,A,B),x0);
%% Define Functions
function F = myfun1(x,A,B)
F(1) = x(1)*(sum(A(:,1).*B(:,2,1)) + sum(A(:,1).*B(:,3,1))) ...
- x(2)*(sum(A(:,2).*B(:,1,2))) - (sum(A(:,3).*B(:,1,3)));
F(2) = x(2)*(sum(A(:,2).*B(:,1,2)) + sum(A(:,2).*B(:,3,2))) ...
- x(1)*(sum(A(:,1).*B(:,2,1))) - (sum(A(:,3).*B(:,2,3)));
end
</code></pre>
<ol>
<li>Is it possible to avoid the "sum"? Maybe by rearranging the
parameters? </li>
<li>Is it possible to vectorize the function itself to avoid writing F(1), F(2), ... , F(49)? I know it is possible, but for this particular problem I have difficulties understanding how to do it. </li>
</ol>
<p>A visualization of the B array: <a href="https://i.stack.imgur.com/cDkcl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cDkcl.png" alt="A visualization of the B array"></a>
In the example, the parameters are arranged as shown below. </p>
<p><span class="math-container">\$A:\$</span>
<span class="math-container">\begin{pmatrix} a_{1,1} & a_{2,1} & a_{3,1}\\ a_{1,2} & a_{2,2} & a_{3,2}\\ a_{1,3} & a_{2,3} & a_{3,3} \end{pmatrix}</span></p>
<p><span class="math-container">\$B1:\$</span>
<span class="math-container">\begin{pmatrix} b_{11,1} & b_{12,1} & b_{13,1}\\ b_{21,1} & b_{22,1} & b_{23,1}\\ b_{31,1} & b_{32,1} & b_{33,1} \end{pmatrix}</span></p>
<p><span class="math-container">\$B2:\$</span>
<span class="math-container">\begin{pmatrix} b_{11,2} & b_{12,2} & b_{13,2}\\ b_{21,2} & b_{22,2} & b_{23,2}\\ b_{31,2} & b_{32,2} & b_{33,2} \end{pmatrix}</span></p>
<p><span class="math-container">\$B3:\$</span>
<span class="math-container">\begin{pmatrix} b_{11,3} & b_{12,3} & b_{13,3}\\ b_{21,3} & b_{22,3} & b_{23,3}\\ b_{31,3} & b_{32,3} & b_{33,3} \end{pmatrix}</span> </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T23:19:53.387",
"Id": "463041",
"Score": "0",
"body": "I've spent a bit of time on this, but your inconsistent row/column indexing is making things confusing. For A you have a_{ij} for column i row j and for B you have b_{ijk} for row i column j slice k. Is this correct, a_{11}+a_{12}+a_{13}=1? And is x_50=1?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T07:15:40.713",
"Id": "463075",
"Score": "0",
"body": "Yes, sum(A) is a vector of ones, as is sum(B,2). Yes, x_50 = 1 (in the small example shown in the question, x_3 = 1). Sorry for the inconsistent indexing. I added an illustration of the B array."
}
] |
[
{
"body": "<p>Yes. You can simplify this code. I made two main changes. </p>\n\n<p>First, I forget that <span class=\"math-container\">\\$x_{50}\\$</span> is known and write an equation for it just like all the other variables, then I replace that equation by the equation <span class=\"math-container\">\\$x_{50}=1\\$</span>.</p>\n\n<p>Second, this is a system of linear equations. Notice that on both sides of the equation we have <span class=\"math-container\">\\$a_{ij}b_{kij}\\$</span> with <span class=\"math-container\">\\$\\{i,j,k\\}=\\{s,t,r\\}\\$</span> on the left and <span class=\"math-container\">\\$\\{i,j,k\\}=\\{r,t,s\\}\\$</span> on the right, and both are summed over <span class=\"math-container\">\\$t\\$</span> which corresponds to <span class=\"math-container\">\\$j\\$</span>. So first I find the matrix <span class=\"math-container\">\\$C_{ik}=\\sum_ja_{ij}b_{kij}\\$</span>, which requires quite some tweaking due to the messed up dimensions/slices. Now the equation reads</p>\n\n<p><span class=\"math-container\">\\$\\displaystyle x_{s}\\sum_{r=1}^R C_{sr} = \\sum_{r=1}^R C_{rs}x_r \\$</span></p>\n\n<p>for each <span class=\"math-container\">\\$s\\in1,2,\\ldots,S\\$</span>. The sum of the left is just <code>sum(C,2)</code> in Matlab, and the sum on the right is the matrix multiplication of <span class=\"math-container\">\\$C^t\\$</span> with the vector of unknowns <span class=\"math-container\">\\$\\vec x\\$</span>. We can write the equation in matrix form as</p>\n\n<p><span class=\"math-container\">\\$\\displaystyle \\vec c\\vec x-C\\vec x=0 \\$</span></p>\n\n<p>where <span class=\"math-container\">\\$[\\vec c]_s=\\sum_r C_{sr}\\$</span>. Written another way, we have</p>\n\n<p><span class=\"math-container\">\\$\\displaystyle \\left(\\mathrm{diag}(\\vec c)-C\\right)\\vec x=0. \\$</span></p>\n\n<p>Now since we know <span class=\"math-container\">\\$x_{50}=1\\$</span> just replace the last row of the matrix with <span class=\"math-container\">\\$[0,0,\\ldots,0,1]\\$</span>. Then if <span class=\"math-container\">\\$M=\\mathrm{diag}(\\vec c)-C\\$</span> our equation is <span class=\"math-container\">\\$M\\vec x=\\vec v\\$</span> where <span class=\"math-container\">\\$\\vec v=[0,0,\\ldots,0,1]^t\\$</span>. We can solve this system directly using <code>\\</code>.</p>\n\n<pre><code>%% Define parameters\nT = 3; % Number of types (T)\nS = 3; % Number of senders (S)\nR = S; % Number of receivers (R), equals the number of senders\nA = [.1 .1 .1 % Columns are senders (S), rows are types (T)\n .3 .3 .6\n .6 .6 .3]; \nB1 = [.9 .0 .1 \n .5 .1 .2 \n .8 .2 .1]; \nB2 = [.0 .7 .2 \n .2 .9 .0 \n .1 .8 .1]; \nB3 = [.1 .3 .7 \n .3 .0 .8 \n .1 .0 .8]; \n\nC = squeeze(sum(A.*cat(3,B1,B2,B3),1)).';\n\nM = diag(sum(C,1))-C; % matrix equations\nM(end,:) = [zeros(1,S-1) 1]; % replace the last equation\n\nv = [zeros(S-1,1);1]; % modify final RHS entry\n\nF = M\\v;\n</code></pre>\n\n<p>An additional benefit is that solving linear systems is much faster than solving nonlinear systems, so this code is much faster. I couldn't test with different <code>R</code>, <code>S</code>, or <code>T</code> so something might have to change, I'm not sure if it will just work, but I think it should.</p>\n\n<hr>\n\n<p>With the new method for generating the equations, we can make a few more simplifications to avoid having to concatenate the <code>Bi</code>'s explicitly, using a cell array:</p>\n\n<pre><code>T = 3; % Number of types (T)\nS = 3; % Number of senders (S)\nR = S; % Number of receivers (R), equals the number of senders\nA = [.1 .1 .1 % Columns are senders (S), rows are types (T)\n .3 .3 .6\n .6 .6 .3]; \nB{1} = [.9 .0 .1 \n .5 .1 .2 \n .8 .2 .1]; \nB{2} = [.0 .7 .2 \n .2 .9 .0 \n .1 .8 .1]; \nB{3} = [.1 .3 .7 \n .3 .0 .8 \n .1 .0 .8]; \n\nC = squeeze(sum(A.*cat(3,B{:}),1)).';\n\nM = diag(sum(C,1))-C;\nM(end,:) = [zeros(1,S-1) 1];\n\nv = [zeros(S-1,1);1];\n\nF = M\\v;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T04:58:15.227",
"Id": "237870",
"ParentId": "236105",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "237870",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:02:09.020",
"Id": "236105",
"Score": "2",
"Tags": [
"matlab",
"vectorization"
],
"Title": "Vectorizing equations for fsolve"
}
|
236105
|
<p>I do genetic programming. I have 5 parcours, the first on the left is the easiest parcour.</p>
<p><a href="https://i.stack.imgur.com/HWLOh.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HWLOh.jpg" alt="enter image description here"></a></p>
<p>The first parcour can be solved by place one belt in the middle pointing downwards to solve the problem. If placed in the middle downwards, the puzzle is solved because the iron-ore flows downwards to the robotic arm. The robotic arm grabs the iron-ore and place it into the wooden-box.</p>
<p>To solve the second parcour 3 belts have to be set.</p>
<p>This is the <strong>Brain</strong> of the <code>Thinker</code> to mutate:</p>
<pre><code>const int MAX_IDEAS=40000;
enum IdeaType {
MOVE_LEFT, MOVE_RIGHT, MOVE_UP, MOVE_DOWN, INC_MEM1_PTR, DEC_MEM1_PTR,
SET_MEM1_ZERO, INC_MEM1_BY_1, DEC_MEM1_BY_1, INC_MEM1_BY_10,
DEC_MEM1_BY_10, FLIP_MEM1_MEM2, GT_JMP, LT_JMP, EQ_JMP, NEQ_JMP,
LOOKUP_MEM1, STORE_MEM1, PLACE_BELT, GET_OBJECTIVE, ROTATE, FINISH,
FOLLOW_DIRECTION,
// the end
_COUNT
};
class Thinker {
private:
unsigned char memory[255];
unsigned char mem_pointer1, mem_pointer2;
unsigned char posX, posY;
public:
IdeaType ideas[MAX_IDEAS];
unsigned int execute(Playground *p, unsigned int maxExecs,
Objective *obj);
void randomize(int globalSeed);
Thinker* mutate(Thinker* spouse, int globalSeed);
void showIdeas();
};
</code></pre>
<p>This is the implementation of the steps to do:</p>
<pre><code>unsigned int Thinker::execute(Playground *p, unsigned int maxExecs,
Objective *obj) {
mem_pointer1 = 0;
mem_pointer2 = 0;
posX = 0;
posY = 0;
unsigned int steps = 0;
for (int ideaNr = 0; ideaNr < MAX_IDEAS; ++ideaNr) {
steps++;
if (ideaNr < 0)
ideaNr = 0;
if (ideaNr > MAX_IDEAS)
ideaNr = MAX_IDEAS - 1;
IdeaType i = ideas[ideaNr];
switch (i) {
case LOOKUP_MEM1:
memory[mem_pointer1] = p->getCell(posX, posY)->getBuilding();
break;
case STORE_MEM1:
memory[mem_pointer1] = mem_pointer1;
break;
case GT_JMP:
if (mem_pointer1 > mem_pointer2) {
ideaNr += (mem_pointer1 - mem_pointer2);
}
break;
case LT_JMP:
if (mem_pointer1 < mem_pointer2) {
ideaNr += (mem_pointer2 - mem_pointer1);
}
break;
case EQ_JMP:
if (mem_pointer1 == mem_pointer2) {
ideaNr += mem_pointer1;
}
break;
case NEQ_JMP:
if (mem_pointer1 != mem_pointer2) {
ideaNr += mem_pointer1;
}
break;
case INC_MEM1_PTR:
mem_pointer1++;
break;
case DEC_MEM1_PTR:
mem_pointer1--;
break;
case SET_MEM1_ZERO:
memory[mem_pointer1] = 0;
break;
case INC_MEM1_BY_1:
memory[mem_pointer1] += 1;
break;
case DEC_MEM1_BY_1:
memory[mem_pointer1] -= 1;
break;
case INC_MEM1_BY_10:
memory[mem_pointer1] += 10;
break;
case DEC_MEM1_BY_10:
memory[mem_pointer1] -= 10;
break;
case FLIP_MEM1_MEM2:
unsigned char l;
l = mem_pointer1;
mem_pointer1 = mem_pointer2;
mem_pointer2 = l;
break;
case PLACE_BELT:
if (p->getCell(posX, posY) == 0) {
return steps;
}
if (p->getCell(posX, posY)->isBuildingLocked()) {
return steps;
}
p->setCell(posX, posY, YELLOW_BELT, NOTHING, DOWN);
break;
case FINISH:
return steps;
case MOVE_UP:
if (posY == 0) {
return steps;
}
posY--;
break;
case MOVE_LEFT:
if (posX == 0) {
return steps;
}
posX--;
break;
case MOVE_RIGHT:
if (p->getCell(posX + 1, 0) == 0) {
return steps;
}
posX++;
break;
case FOLLOW_DIRECTION:
if (p->getCell(posX, posY) == 0) {
return steps;
}
Cell* c;
c = p->getCell(posX, posY);
if(c->getBuilding()==YELLOW_BELT) {
switch (c->getDirection()) {
case DOWN:
if(p->below(p->getCell(posX, posY))==0) {
return steps;
}
posY++;
break;
case UP:
if(posY==0) {
return steps;
}
posY--;
break;
case LEFT:
if(posX==0) {
return steps;
}
posX--;
break;
case RIGHT:
if(p->right(p->getCell(posX, posY))==0) {
return steps;
}
posX++;
break;
default:
break;
}
}
break;
case MOVE_DOWN:
if (p->getCell(0, posY + 1) == 0) {
return steps;
}
posY++;
break;
case GET_OBJECTIVE:
if (obj->row == posY && obj->cell == posX) {
memory[mem_pointer1] = obj->prospection;
} else {
memory[mem_pointer1] = 255;
}
break;
case ROTATE:
if (p->getCell(posX, posY) == 0) {
return steps;
}
if (p->getCell(posX, posY)->isBuildingLocked()) {
return steps;
}
p->getCell(posX, posY)->rotate();
break;
default:
cout << endl << "PROBLEM!!!!; VALUE OUT OF RANGE: " << (int) i
<< endl;
return steps;
break;
}
if (steps > maxExecs) {
cout << "Max ideas reached!" << endl;
break;
}
}
return steps;
}
</code></pre>
<p>Before mutation I initialize by this random method:</p>
<pre><code>void Thinker::randomize(int globalSeed) {
srand(globalSeed);
for (int ideaNr = 0; ideaNr < MAX_IDEAS; ++ideaNr) {
int r = rand() % _COUNT;
ideas[ideaNr] = static_cast<IdeaType>(r);
}
}
</code></pre>
<p>To mutate two thinker I use this method:</p>
<pre><code>Thinker* Thinker::mutate(Thinker *spouse, int globalSeed) {
Thinker *tt = new Thinker();
srand(globalSeed);
int from = rand() % MAX_IDEAS - 1;
int count = rand() % (MAX_IDEAS - from);
if (count == 0) {
count = 1;
}
int halfMaxIdeas = count / 2 + from;
for (int i = from; i < from + count; i++) {
if (i < halfMaxIdeas) {
tt->ideas[i] = ideas[i];
} else {
tt->ideas[i] = spouse->ideas[i];
}
}
return tt;
}
</code></pre>
<p>The rest is like this: There must be always 20,000 thinker. They do all try to solve the puzzle. Those winners are mutated.</p>
<p>Current results: </p>
<ol>
<li>From the first 20,000 candidates there where only 138 who could solve the maze successfully.</li>
<li>I do mutate all the 138 candidates up to 20,000 mutations of those candidates. Then I let them solve the second puzzle.</li>
<li>From the second puzzle there where only 2 winners.</li>
</ol>
<p>Only 2 winners is a bad result because they can be mutated but they are much too inbreeded for further healthy candidates.</p>
<p>What do I need a review for?</p>
<ul>
<li>Documentation style</li>
<li>Range check</li>
<li>Missing important IdeaTypes</li>
<li>Check if the mutation algorithm do a valid mutation.</li>
<li>Maybe optimizations</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:47:15.583",
"Id": "462480",
"Score": "2",
"body": "Is your code working? Are you looking for a review of your code? You question doesn't seem to reflect that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:51:36.787",
"Id": "462481",
"Score": "0",
"body": "@L.F. Code is working. I pointed out what a review I need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:09:36.347",
"Id": "462484",
"Score": "1",
"body": "From which programming-challenge is this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:15:18.127",
"Id": "462485",
"Score": "0",
"body": "@Mast No programming challange. I had the idea and I wrote all by myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:23:02.637",
"Id": "462491",
"Score": "1",
"body": "Then what is the picture from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:39:53.587",
"Id": "462495",
"Score": "1",
"body": "@Mast From Factorio."
}
] |
[
{
"body": "<p>I don't know anything about Factorio which your question also seems to be about, so I can't say anything about \"missing important IdeaTypes\", for instance.</p>\n\n<ol>\n<li><p>Since <code>MAX_IDEAS</code> is a compile-time constant, you might as well mark it as such by <code>constexpr</code> instead.</p></li>\n<li><p>Perhaps only nitpicking, but it seems clear that any type is... a type. So I think <code>Idea</code> is a better type name than <code>IdeaType</code>. I mean, it's <code>std::vector<T></code> and not <code>std::vector_type<T></code> for comparison.</p></li>\n<li><p>For <code>Thinker</code>: avoid C-style arrays. If you really do know 255 characters are sufficient, consider using e.g., <code>std::array</code> instead. You'll be able to enforce range checking much more easily, to name just one benefit. If you chose 255 just because it feels large enough, then use a dynamic data structure like a string or a vector.</p></li>\n<li><p>I don't see the reason <code>ideas</code> has to be a public array. Just rather make it a constant static array which is \"suitably global\", as per your needs.</p></li>\n<li><p>When you want to minimize the risk of leaking memory or doing something unintended, don't use pointers. You don't seem to need any dynamic memory management (for e.g., polymorphism), so just don't. It's <em>much</em> easier to reason about non-pointer types and references.</p></li>\n<li><p>In particular, <code>mutate</code> does not need to return a dynamically allocated object. Just return by value, modern C++ does guarantee copy elision and you don't take any hit by doing so. Also, the caller don't have to worry about managing the object lifetime (which you possibly might have neglected to do in your full code).</p></li>\n<li><p>The variable name <code>i</code> is quite surprising. Your instinct tells you it's probably a loop variable, but it's actually of type <code>IdeaType</code>. So I'd rename this to e.g., <code>idea</code>.</p></li>\n<li><p>The switch-case is quite a beast to parse and to understand. Here's a few pointers (no pun intended) for how you can make it more readable: note that <code>FLIP_MEM1_MEM2</code> is <code>std::(iter_)swap</code>; rely on standard implementations. All of <code>SET_MEM1_ZERO</code>, ..., <code>DEC_MEM1_BY_10</code> increment a location by a constant. So we could use an (unordered) map to store these values, where the key is <code>IdeaType</code>s. So if you are in one of these cases, reach into the map and increment by the corresponding value.</p></li>\n<li><p>Further, for the latter parts (dealing with movement it seems), you could consider delegating this work to helper functions to aid readability.</p></li>\n<li><p>Another example of a pointer you likely don't need is <code>Cell* c</code>. You don't show what this type is, but make <code>const Cell& c = p.getCell(posX, posY);</code> if you can, and just make is <code>Cell& c</code> if you can't. I'm also assuming here you pass by (constant) reference, and <em>not</em> by pointer (don't do that, unless you really know you want to).</p></li>\n<li><p>I think the <code>default</code> branch of your switch case shouldn't just print \"PROBLEM!!!!\", but rather fail hard. So you probably want to use an <code>assert</code> as this case (I assume) means the internal program logic is broken, i.e., we should never get here no matter what.</p></li>\n<li><p>Try to think about what constructors <code>Thinker</code> should have. Should it be the case that you pass it a <code>Playground</code>, <code>maxExecs</code>, and an <code>Objective</code> and it initializes suitably? Or should you be able to give the constructor a seed so that the candidate solution is built randomly? Think about the semantics here, the constructor helps you make your code more efficient and more readable; it also self-documents what a <code>Thinker</code> is.</p></li>\n<li><p>For <code>randomize</code>, read about how to use randomness more appropriately with the use of <code><random></code>. These facilities exist because of shortcomings of just using <code>rand()</code> and such. So you could do (untested!) something like:</p></li>\n</ol>\n\n<pre><code>void Thinker::randomize(int globalSeed) {\n std::random_device rnd_device;\n std::mt19937 engine {rnd_device()};\n std::uniform_int_distribution<int> dist{0, MAX_IDEAS};\n // It's so nice that ideas is an std::array so that we can use begin() and end()\n std::generate(ideas.begin(), ideas.end(), [&]() { return static_cast<IdeaType>(dist(engine)); });\n // Otherwise, we'd have to something more error prone like std::generate(ideas, ideas + 255, ...)\n</code></pre>\n\n<ol start=\"14\">\n<li><p>You can apply the same ideas for <code>mutate</code>. In short, don't return a pointer & use the modern random facilities. This also gives you the added benefit of <em>more control in an easy way</em>: what if you don't want a uniform distribution? You want to weight it in some exotic way? Much easier with <code><random></code> than doing it by hand!</p></li>\n<li><p>In general, it would help if you explained how the relevant concepts relate to the expected components of a genetic algorithm. For example, it seems that <code>Thinker</code> is a chromosome (i.e., a candidate solution), but it would be nice to see your fitness function as well, and so on. This helps in communicating ideas and in the (self-)documentation of your code.</p></li>\n<li><p>If you don't have a fitness function, your search essentially only progresses by mutation likely making it very inefficient as it explores the search space in random manner without any guidance.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T00:28:48.393",
"Id": "463239",
"Score": "0",
"body": "Genetic programming is a method that is not factorio-specific. But you are right, without knowledge of the playground you might not be able to identify good candidates for ideatypes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T05:52:08.107",
"Id": "463262",
"Score": "0",
"body": "@PeterRader I have a good amount of experience with GAs and other such metaheuristics. It would also help if you clearly described how each piece relates to the general framework, ie that a Thinker is a candidate solution (chromosome) etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T12:12:59.123",
"Id": "463298",
"Score": "0",
"body": "To 1, done after change dialect (`-std=c++11`). 2. A Idea is complex but IdeaType is atomic, anyway good catch I changed the name to IdeaStep. 3. 255 is the range of the `memory_pointer1` since char might have only 7 bits its max size might be 127 so I changed the range to `sizeof(mem_pointer1)`. 4. Good catch. 5. I got your point, since it depends on speed I feel like objects might allow better OOP what is bad for the performance. Am I right? 6. Mutate is not a constructor! I thought *copy elision* for copy and move constructors only!? 7. Good catch. Give me some time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T12:20:44.150",
"Id": "463300",
"Score": "0",
"body": "@PeterRader For (5.), there are surely much bigger things to worry about than the speed of pass-by-reference vs. pass-by-pointer in your design (and it's highly unclear whether passing by pointer would be any faster). For (6.), I see that it is not a constructor, it's a function that should return an object by value. [C++17 guarantees copy elision](http://www.cplusplus2017.info/c17-guaranted-copy-elision/)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T17:07:04.867",
"Id": "236363",
"ParentId": "236106",
"Score": "3"
}
},
{
"body": "<p>Your problem is difficult in trying for a genetic algorithm to create a long program for which the only outputs are a single binary ('problem is solved', 'problem is not solved') and that you are trying to find a single algorithm that solves all five problems, as seen by you promoting those that solve the first problem to the gene pool of the second.</p>\n\n<p>You might want to add a scoring function, e.g., how close the ore got to box with a huge bonus for getting to the box. You can then kill a reasonable number (say half) for each new level.</p>\n\n<p>You may find that this is not really a solvable problem, especially since your mutations are random op code swaps. You could experiment with swapping a random subsequence of the program instead.</p>\n\n<p>Otherwise, you are putting two frogs in a blender and hoping that 'Puree' creates one bigger frog.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T11:33:13.830",
"Id": "463292",
"Score": "0",
"body": "The bigger Frog is indeed my expectation. Mutation does not respect subsequences of ideas, otherwise it is not a real mutation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T15:31:45.230",
"Id": "463320",
"Score": "0",
"body": "Usually, one uses a combination of genetic swaps and random mutations. That is, a couple random gene flips for some survivors. I'm suggesting a 'gene' (idea) might be a different unit than an opcode."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T06:21:55.970",
"Id": "236395",
"ParentId": "236106",
"Score": "1"
}
},
{
"body": "<h2>Interpreting the problem as a path on a graph:</h2>\n\n<p>The problem can be interpreted as trying to find a path (from S to T) in a graph.</p>\n\n<p>E.g.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Mvh1s.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Mvh1s.jpg\" alt=\"enter image description here\"></a></p>\n\n<h2>Genetic Algorithm improvements</h2>\n\n<p>There are several techniques to mitigate your problems:</p>\n\n<ul>\n<li><strong>Divide the problem into two smaller ones</strong>, You could first find the path on the graph and then given a valid path, you can find the action that builds that path.</li>\n<li><a href=\"http://www.ijmlc.org/papers/146-C00572-005.pdf\" rel=\"nofollow noreferrer\">Blending Roulette Wheel Selection & Rank Selection</a>, basically it's a better way to select the population that tries to balance exploitation and exploration.</li>\n<li><strong>Add a heuristic to the fitness function</strong>, you could use the <a href=\"https://en.wikipedia.org/wiki/Taxicab_geometry\" rel=\"nofollow noreferrer\">L1 distance</a> from the current end of the path and the target square. This way you simulate the <a href=\"https://en.wikipedia.org/wiki/A*_search_algorithm\" rel=\"nofollow noreferrer\">A* algorithm</a>.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Genetic_algorithm#Elitism\" rel=\"nofollow noreferrer\">Elitism</a>, basically you keep untouched the best 5~10% of the population. This is meant to avoid regression.</li>\n</ul>\n\n<h2>Optimal Solution (No genetic algorithm)</h2>\n\n<p>This might be kind of offtopic, but if you don't need to use a Genetic Algorithm you can use Dynamic Programming to find the optimal solution.</p>\n\n<p>If we set a constant weight on all the edges we can use <a href=\"https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"nofollow noreferrer\">Dijkstra's algorithm</a> to find the solution that requires the least amount of belts.\n<a href=\"https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/\" rel=\"nofollow noreferrer\">Here a quite clear C++ implementation</a>.</p>\n\n<p>Once you have the optimal solution, it shouldn't be hard to build the sequence of actions that build that path.</p>\n\n<p>If the problem became <strong>really big</strong>, you could use <a href=\"https://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms\" rel=\"nofollow noreferrer\">Ant System</a>, which could be viewed as a hybrid between a pathfinding algorithm and a genetic algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T13:08:45.597",
"Id": "472695",
"Score": "0",
"body": "In Factorio, it would work to connect to T also from the left or the right."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T18:50:54.093",
"Id": "236548",
"ParentId": "236106",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:28:41.463",
"Id": "236106",
"Score": "7",
"Tags": [
"c++",
"genetic-algorithm"
],
"Title": "Genetic Programming - Pathfinding not enougth couples"
}
|
236106
|
<p>Currently my solution for calculating wages based on average weekly hours and any other wages field is very long and elaborate. I think it can be concised and make more readable but when I try to do it it creates some nasty bugs as it is based on field changed. Any elegant refactoring suggestion would be much appreciated!</p>
<pre><code>/**
* Executed on change of Hourly Wage.
* Calculates monthly and annual wage based on average weekly hours and hourly wage.
*
* @param {object} executionContext : provided by dynamics
* @returns {boolean} : returns true if calculation is done
*/
function onChangeHourlyWage(executionContext) {
const formContext = executionContext.getFormContext();
const {
AVERAGE_WEEKLY_HOURS,
HOURLY_WAGE,
MONTHLY_WAGE,
ANNUAL_WAGE
} = EMPLOYMENT_HISTORY_FIELDS;
const averageWeeklyHours = formContext
.getAttribute(AVERAGE_WEEKLY_HOURS)
.getValue();
const hourlyWage = formContext
.getAttribute(HOURLY_WAGE)
.getValue();
if (!averageWeeklyHours || !hourlyWage) return false;
annualWage = hourlyWage * averageWeeklyHours * WEEKS_IN_A_YEAR;
monthlyWage = annualWage / 12;
formContext.getAttribute(ANNUAL_WAGE).setValue(annualWage);
formContext.getAttribute(MONTHLY_WAGE).setValue(monthlyWage);
return true;
}
/**
* Executed on change of Monthly Wage.
* Calculates hourly and annual wage based on average weekly hours and monthly wage.
*
* @param {object} executionContext : provided by dynamics
* @returns {boolean} : returns true if calculation is done
*/
function onChangeMonthlyWage(executionContext) {
const formContext = executionContext.getFormContext();
const {
AVERAGE_WEEKLY_HOURS,
HOURLY_WAGE,
MONTHLY_WAGE,
ANNUAL_WAGE
} = EMPLOYMENT_HISTORY_FIELDS;
const averageWeeklyHours = formContext
.getAttribute(AVERAGE_WEEKLY_HOURS)
.getValue();
const monthlyWage = formContext
.getAttribute(MONTHLY_WAGE)
.getValue();
if (!averageWeeklyHours || !monthlyWage) return false;
annualWage = monthlyWage * 12;
hourlyWage = annualWage / (WEEKS_IN_A_YEAR * averageWeeklyHours);
formContext.getAttribute(ANNUAL_WAGE).setValue(annualWage);
formContext.getAttribute(HOURLY_WAGE).setValue(hourlyWage);
return true;
}
/**
* Executed on change of Annual Wage.
* Calculates hourly and monthly wage based on average weekly hours and annual wage.
*
* @param {object} executionContext : provided by dynamics
* @returns {boolean} : returns true if calculation is done
*/
function onChangeAnnualWage(executionContext) {
const formContext = executionContext.getFormContext();
const {
AVERAGE_WEEKLY_HOURS,
HOURLY_WAGE,
MONTHLY_WAGE,
ANNUAL_WAGE
} = EMPLOYMENT_HISTORY_FIELDS;
const averageWeeklyHours = formContext
.getAttribute(AVERAGE_WEEKLY_HOURS)
.getValue();
const annualWage = formContext
.getAttribute(ANNUAL_WAGE)
.getValue();
if (!averageWeeklyHours || !annualWage) return false;
hourlyWage = annualWage / (WEEKS_IN_A_YEAR * averageWeeklyHours);
monthlyWage = annualWage / 12;
formContext.getAttribute(HOURLY_WAGE).setValue(hourlyWage);
formContext.getAttribute(MONTHLY_WAGE).setValue(monthlyWage);
return true;
}
/**
* Executed on change of AverageWeeklyHours.
* Calculates hourly, monthly and annual wage if any three of a mentioned
* field and average weekly hours is filled.
*
* @param {object} executionContext : dynamics 365 execution context
*/
function onChangeAverageWeeklyHours(executionContext) {
if (onChangeHourlyWage(executionContext)) return;
if (onChangeMonthlyWage(executionContext)) return;
onChangeAnnualWage(executionContext);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:19:25.947",
"Id": "462488",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T08:52:35.903",
"Id": "236107",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Calculate hourly, weekly and annual wage"
}
|
236107
|
<p>Is this the best way to prefix all lines written by a Bash script to standard error?</p>
<pre><code>#! /bin/bash
exec 3>&2
exec 2> >(sed 's/^/ERROR: /' >&3)
echo stdout
echo stderr >&2
</code></pre>
<p>I am wondering, if I have to close file descriptor 3.</p>
|
[] |
[
{
"body": "<p>There's not a lot to review here. It's Valgrind clean, though that's not difficult to achieve.</p>\n\n<p>Certainly consider closing stream 3, unless you want to keep a means to emit unprefixed stderr messages.</p>\n\n<p>One shortcoming is that the shell won't wait for <code>sed</code> to finish when it terminates. If the last process's output is still being filtered at this point, then you may fail to capture it - I observed this (repeatably) when running the program in Emacs <code>compilation-mode</code>.</p>\n\n<p>One way you can improve on this if you're using GNU sed is by passing <code>-u</code> (\"unbuffered\") flag to sed. If you don't have GNU sed but do have GNU coreutils, then the <code>stdbuf</code> utility could make sed line-buffered for you:</p>\n\n<pre><code>stdbuf -oL -iL sed 's/^/ERROR: /'\n</code></pre>\n\n<p>With any sed, we could (and should) close stderr when we terminate and wait for sed to finish to be sure of catching all error output.</p>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<pre><code>#!/bin/bash\n\nexec 3>&2\nexec 2> >(sed -u 's/^/ERROR: /' >&3)\nexec 3>&-\n# shellcheck disable=SC2064\ntrap \"exec 2>&-; wait $!\" EXIT\n\necho stdout\necho stderr >&2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T13:28:55.270",
"Id": "463105",
"Score": "0",
"body": "It is possible to wait for the process substitution. The pid of the child process is in `$!` after the `exec`. In order to flush the output of the child process, it is sufficient to close the input fd, which is fd 2 of the parent. After that one can wait for the child pid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T17:11:24.210",
"Id": "463147",
"Score": "0",
"body": "Good suggestion; thanks @ceving. I've made the appropriate change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T17:12:31.200",
"Id": "463148",
"Score": "0",
"body": "That was a typo - `&1` where I meant `&-`. Sorry!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T13:11:00.790",
"Id": "236114",
"ParentId": "236110",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T11:02:54.493",
"Id": "236110",
"Score": "1",
"Tags": [
"bash"
],
"Title": "Prefix all lines on standard error"
}
|
236110
|
<p>I've created a tiny (723 bytes compressed + gzip) animation library. Is this a good way of animating arbitrary numbers?</p>
<pre><code>const map = (value, x1, x2, y1, y2) => (value - x1) * (y2 - y1) / (x2 - x1) + y1;
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
// Courtesy of @gre from https://gist.github.com/gre/1650294
const Easing = {
// no easing, no acceleration
linear: t => t,
// acceleration until halfway, then deceleration
easeInOutQuad: t => t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
};
function Animation(settings) {
if (typeof settings !== 'object' || (typeof settings === 'object' && settings instanceof Array)) {
throw new Error('The settings passed to Animation must be an object');
}
if (!settings.hasOwnProperty('duration')) {
throw new Error('The settings passed to Animation must have a "duration" property set');
}
if (!settings.hasOwnProperty('from')) {
throw new Error('The settings passed to Animation must have a "from" property set');
}
if (!settings.hasOwnProperty('to')) {
throw new Error('The settings passed to Animation must have a "to" property set');
}
if (settings.hasOwnProperty('easing') && typeof settings.easing !== 'function') {
throw new Error('Invalid easing function passed to settings. Easing function must be one of the functions provided in the Easing object, e.g. Easing.linear');
}
const duration = settings.duration;
const easing = settings.easing || Easing.linear;
const timestamps = {
start: 0,
finish: 0,
};
const value = {
from: settings.from,
to: settings.to,
};
let nextFrame, tickCallback;
const setTimestamps = currentTimestamp => {
timestamps.start = currentTimestamp;
timestamps.finish = currentTimestamp + duration;
};
const tick = () => {
nextFrame = requestAnimationFrame(tick);
const currentTimestamp = Date.now();
if (timestamps.start + timestamps.finish === 0) {
setTimestamps(currentTimestamp);
}
const normal = easing(map(currentTimestamp, timestamps.start, timestamps.finish, 0, 1));
const delta = clamp(normal, 0, 1);
tickCallback(map(delta, 0, 1, value.from, value.to));
if (delta === 1) {
cancelAnimationFrame(nextFrame);
}
};
this.animate = fn => {
if (typeof fn !== 'function') {
throw new Error('The given callback is not a function. A valid function callback must be provided');
}
nextFrame = requestAnimationFrame(tick);
tickCallback = fn;
};
return this;
}
</code></pre>
<p>Example of animating a number from -50 to 50 over 5000, starting slow and finishing slow:</p>
<pre><code>const animation = new Animation({
duration: 5000,
from: -50,
to: 50,
easing: Easing.easeInOutQuad,
});
animation.animate(value => {
document.body.innerText = String(Math.round(value));
});
</code></pre>
<p>I know there are many tiny animation libraries out there already, but I only need a small sub-set of their functionality.</p>
<p><a href="https://jsbin.com/fetoxapequ/edit?js,output" rel="nofollow noreferrer">Demo on JS Bin</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T11:13:33.427",
"Id": "236111",
"Score": "3",
"Tags": [
"javascript",
"animation"
],
"Title": "Tiny JavaScript Animation Library"
}
|
236111
|
<p>I've got such an input object, which I should modify in order to use it with some charts library.</p>
<pre><code>const input = {
foo: {
bar: 'biz',
},
statistic: {
"2019-11": {
A: 11,
B: 11,
C: 11,
D: 11,
E: 11,
},
"2019-12": {
A: 12,
B: 12,
C: 12,
D: 12,
E: 12,
},
....
}
};
</code></pre>
<p>My library expects an input like this:</p>
<pre><code>[
{ subject: 'A', '2019-11': 11, '2019-12': 12 },
{ subject: 'B', '2019-11': 11, '2019-12': 12 },
{ subject: 'C', '2019-11': 11, '2019-12': 12 },
{ subject: 'D', '2019-11': 11, '2019-12': 12 },
{ subject: 'E', '2019-11': 11, '2019-12': 12 }
]
</code></pre>
<p>And this is my current solution:</p>
<pre><code>const transform = arg => {
const keys = ['A', 'B', 'C', 'D', 'E'];
return _.map(keys, key => {
const data = _.reduce(arg.statistic, (result, value, k) => {
result[k] = value[key];
return result;
}, {});
return {
subject: key,
...data
}
});
}
</code></pre>
<p>Any improvements would be very welcome!</p>
|
[] |
[
{
"body": "<p>So you have five data series here right (A through E)? What happens when you have 4 or 6 data series? Do you really want to rewrite your code?</p>\n\n<p>Also, unless you have some reason to do so, lodash seems kind of unnecessary for these sort of simple data transforms these days. I am guessing using ES6 Array.map, Array.reduce and similar would do the same exact thing while also yielding a more fluent, readable style,</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T04:13:24.720",
"Id": "236135",
"ParentId": "236112",
"Score": "2"
}
},
{
"body": "<p>Using <code>reduce</code> to build a map object sounds wrong. By definition, the word reduce means \"to make smaller\", but you are using it here \"to make bigger\". A first step might be:</p>\n\n<pre><code>const data = {};\n_.foreach(arg.statistic, (key, value) => data[key] = value);\n</code></pre>\n\n<p>I don't know whether lodash actually has <code>foreach</code>, it's just to illustrate the idea.</p>\n\n<p>There's probably an even more elegant way to create this map out of the data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T09:09:45.350",
"Id": "463276",
"Score": "0",
"body": "You shouldn't limit yourself by reading too much into the name `reduce`. It's just one of many names for the same operation. Using it to \"reduce\" multiple values into a single value (even if that single value ends up being a \"larger\" object) is exactly what it is meant for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T05:38:26.060",
"Id": "236137",
"ParentId": "236112",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "236135",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T12:46:01.923",
"Id": "236112",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"lodash.js"
],
"Title": "Transform an object into another object structure"
}
|
236112
|
<p>I just got done coding this C program:</p>
<blockquote>
<p>Read the description of a deterministic finite automaton from standard input.</p>
<p>The first line of input is the number of states in the automaton, <em>n</em></p>
<p><em>n</em> lines follow, each one describing a state. Each line is composed of the name of the state, followed by its transitions, colon-separated. A transition is indicated like <code>(S,c)</code> and means that the automaton will move to state <em>S</em> upon reading the character <em>c</em>.</p>
<p>If the name of a state begins with <em>F</em>, it's a terminal state. For example, <code>F1;(A,b);(C,d)</code> is a terminal state and the automaton will move to state <em>A</em> upon reading characer <em>b</em>, and to state <em>C</em> upon reading character <em>d</em>. The name of a state can be 10 characters long at most.</p>
<p>After having read all the states, the program will read lines of text from standard input, until the line <code>STOP</code> is input. For every line, the automaton will determine if it belongs to the described language and, if it does, will echo it back.</p>
<p>Note: the program must not print anything but the recognized lines to standard output.</p>
</blockquote>
<p>I thought it was an interesting problem. A few notes:</p>
<ol>
<li><p>There are no error messages to handle ill-formed input. We were required by those who gave us the assignment to focus on solving the problem, rather than making it become an input-checking exercise. So I'll pretty much assume the input is well-formatted throughout the program</p>
</li>
<li><p>There are no prompt texts like <code>Number of states?</code> due to the program being corrected by an automatic platform that matches the exepcted output with the one from the program.</p>
</li>
</ol>
<p>My program passed the tests on that platform so it works. What I'm interested in is, what could I have done to improve the code? Thank you!</p>
<p>Code</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SNL 10 // maximum number of characters in a state's name
typedef struct transition {
char c;
char *newState;
struct transition *nextPtr;
} Transition;
typedef struct state {
char *sName;
Transition *tList;
} State;
int getNStates() { // gets the number of states in the automaton
int n;
if(scanf("%d", &n) != 1 || n <= 0) {
exit(1);
}
return n;
}
State *createNewState(char stateName[]) { // creates a new state with the specified name and returns it
State *newState = malloc(sizeof(State));
if(newState == NULL) exit(1);
newState->sName = malloc(sizeof(char) * SNL);
if(newState->sName == NULL) exit(1);
strcpy(newState->sName, stateName);
newState->tList = NULL;
return newState;
}
void appendTransition(Transition **tList, char *newS, char ch) { // appends a new transition to the existing list, recursively
if(*tList == NULL) {
*tList = malloc(sizeof(Transition));
if(tList == NULL) exit(1);
(*tList)->newState = malloc(sizeof(char) * strlen(newS)); // allocate memory for new state's name
if((*tList)->newState == NULL) exit(1);
strcpy((*tList)->newState, newS); // initialize new transition
(*tList)->c = ch;
(*tList)->nextPtr = NULL;
} else {
appendTransition(&((*tList)->nextPtr), newS, ch);
}
}
State *move(State **automaton, int nStates, State *currState, char ch) { // returns a state if transition is found, NULL is no transition is found
Transition *tList = currState->tList;
if(tList == NULL) return NULL;
while(tList != NULL) {
if(tList->c == ch) { // found correct transition
for(size_t i = 0; i < nStates; i++) {
if(!strcmp(automaton[i]->sName, tList->newState)) { // find the correct state in the table
return automaton[i];
}
}
}
tList = tList->nextPtr;
}
return NULL;
}
int evaluate(State **automaton, int nStates, char *line) {
if(*automaton == NULL) {
return 1;
}
State *st = automaton[0]; // initial state is the first state
for(size_t i = 0; i < strlen(line); i++) {
st = move(automaton, nStates, st, line[i]); // transition to the next state
if(st == NULL) {
return 0;
}
}
if(st->sName[0] == 'F') { // if state name begins with 'F', it's a terminal state
return 1;
}
return 0;
}
int main() {
int n = getNStates();
char stateName[SNL]; // used to store current state's name
char newState[SNL]; // used to store newState's name for every transition
char c; // used to store character that leads to newState for every transition
char line[100]; // used to store current line of text
State **automaton = malloc(n*sizeof(State)); // create the automaton table
if(automaton == NULL) exit(1);
while(getchar() != '\n'); // clear buffer
for(size_t i = 0; i < n; i++) { // get as many lines of text as there are states
scanf("%[^\n]", line);
automaton[i] = malloc(sizeof(State)); // allocate memory for new state
if(automaton[i] == NULL) exit(1);
char *token = strtok(line, ";"); // first token is the state name
automaton[i]->sName = malloc(sizeof(char) * (strlen(token) + 1)); // allocate memory for state name
if(automaton[i]->sName == NULL) exit(1);
strcpy(automaton[i]->sName, token); // copy state name into the table
automaton[i]->tList = NULL; // initialize current state transition table
while(token = strtok(NULL, ";")) { // keep reading as long as there are transitions
sscanf(token, "(%[^,],%c)", newState, &c);
appendTransition(&(automaton[i]->tList), newState, c); // append new transition to state's list
}
while(getchar() != '\n'); // clear buffer
}
scanf("%100s", line); // read a line
while(strcmp(line,"STOP")) { // keep reading lines until you encounter "STOP"
if(evaluate(automaton, n, line)) { // print the line of text if it's recognized by the automaton
puts(line);
}
scanf("%100s", line); // read a line
}
return 0;
}
</code></pre>
<p>Example inputs/outputs:</p>
<p>test case 1</p>
<pre><code>input:
5
A;(A,a);(B,c)
B;(A,a);(C,b);(B,c);(F2,k)
C;(F1,d);(A,a);(B,c)
F1;(C,b)
F2;
akcdbbbbc
cacack
cacbd
STOP
output:
cacack
cacbd
</code></pre>
<p>test case 2</p>
<pre><code>input:
3
S1;(S1,b);(S2,a)
S2;(S1,f);(F1,d);(S2,c)
F1;(S2,e);(F1,x)
bbafacccdedxxedx
x
bad
STOP
output:
bbafacccdedxxedx
bad
</code></pre>
<p>test case 3</p>
<pre><code>input:
1
F1;(F1,a)
a
aaa
bad
ab
STOP
output:
a
aaa
</code></pre>
|
[] |
[
{
"body": "<h1>About your notes</h1>\n\n<blockquote>\n <p>There are no error messages to handle ill-formed input. We were required by those who gave us the assignment to focus on solving the problem, rather than making it become an input-checking exercise. So I'll pretty much assume the input is well-formatted throughout the program</p>\n</blockquote>\n\n<p>It is a good excercise for yourself to add input checking. Invalid input is rather common, and if you don't check it, your program might crash (which is actually the best possible outcome), or worse: the program seems to run fine but you might get incorrect results.</p>\n\n<blockquote>\n <p>There are no prompt texts like Number of states? due to the program being corrected by an automatic platform that matches the exepcted output with the one from the program.</p>\n</blockquote>\n\n<p>That's actually a good thing, if it's more likely that someone will pipe a file to the program's standard input instead of typing in manually while the program is running.</p>\n\n<h1>Allocate a whole array in one go</h1>\n\n<p>You are creating an array of pointer to <code>State</code>s, and then while reading each line of input, you allocate the actual memory for each individual <code>State</code>. You can just as well allocate the memory for all <code>State</code>s in one go:</p>\n\n<pre><code>State *automaton = malloc(n * sizeof(*automaton));\n</code></pre>\n\n<p>Note that <code>sizeof(*automaton)</code> is equal to <code>sizeof(State)</code>, but prefer to use an actual variable to get the size of a type. The advantage of the former is that if you ever change the type of <code>automaton</code>, that you only have to do it in one place instead of multiple places.</p>\n\n<p>In the <code>for</code>-loop, you can now just use <code>.</code> instead of <code>-></code> to access the array members.</p>\n\n<h1>Prefer <code>strdup()</code> over manual allocation + copying of strings</h1>\n\n<p>While it's not part of the C standard, POSIX.1-2001-compliant C libraries provide a function named <code>strdup()</code> that will copy a string for you. So instead of doing a <code>malloc()</code> and <code>strcpy()</code>, you could write:</p>\n\n<pre><code>automaton[i].sName = strdup(token);\n</code></pre>\n\n<p>Note how you no longer have to check the length of the string manually. This would fix the bug in <code>appendTransition()</code>, where you forgot to add <code>+ 1</code> to the length of the string when calling <code>malloc()</code>.</p>\n\n<h1>Enable compiler warnings and fix all warnings it prints</h1>\n\n<p>Even if the warnings seem harmless, do fix them. It usually just ensures you keep your code clean (like getting rid of the unused <code>stateName</code> variable), but some warnings might actually point to potential bugs in your program.</p>\n\n<h1>Use <code>fgets()</code> to read lines</h1>\n\n<p>Instead of using <code>scanf()</code> and <code>getch()</code> to read lines, I recommend you use <code>fgets()</code> instead. It's designed to read in complete lines. The only issue that you have to deal with is that it stores the newline character (<code>\\n</code>) in the destination string as well. Also make sure that you pass the correct size of the buffer. For example:</p>\n\n<pre><code>fgets(line, sizeof(line), stdin); // Please do check the return value of fgets()!\nsize_t len = strlen(line);\nif (len && line[len - 1] == '\\n')\n line[len - 1] = '\\0'; // Removes trailing newline.\n</code></pre>\n\n<h1>Consider not hardcoding the check for terminal states in <code>evaluate()</code></h1>\n\n<p>It would make <code>evaluate()</code> simpler to maintain and more flexible if you didn't hardcode the knowledge that state names starting with <code>\"F\"</code> indicate terminal states. Instead, create another function to check this, and call that inside <code>evalute()</code> like so:</p>\n\n<pre><code>if(is_terminal(st))\n return 1;\n</code></pre>\n\n<p>Note that you don't need the comment anymore explaining what that <code>if</code>-statement does.\nThen you can decide how to implement <code>is_terminal()</code>. You can move the check for the name there:</p>\n\n<pre><code>bool is_terminal(const State *st) {\n return st->sName[0] == 'F';\n}\n</code></pre>\n\n<h1>Use <code>const</code> where appropriate</h1>\n\n<p>Whenever a variable is not supposed to be changed after being initialized, add <code>const</code> to its declaration. For example, if you use <code>strdup()</code> as mentioned above, you could make the strings stored in <code>Transition</code> and <code>State</code> <code>const</code>, like so:</p>\n\n<pre><code>typedef struct transition {\n char c;\n const char *newState;\n struct transition *nextPtr;\n} Transition;\n\ntypedef struct state {\n const char *sName;\n Transition *tList;\n} State;\n</code></pre>\n\n<p>And functions that take a string argument should be annotated as well, for example:</p>\n\n<pre><code>State *createNewState(const char *stateName) {\n ...\n newState->sName = strdup(stateName);\n ...\n}\n</code></pre>\n\n<p>Once you have parsed the state definitions from the input, the functions that evaluate the automaton should not modify them. So you should be able to write the following (assuming you allocated memory for states using a single <code>malloc()</code> call):</p>\n\n<pre><code>const State *move(const State *automaton, int nStates, const State *currState, char ch) {\n ...\n}\n\nint evaluate(const State *automaton, int nStates, const char *line) {\n ...\n}\n</code></pre>\n\n<p>The <code>const</code> annotation will allow the compiler produce better optimized code, and will generate errors when you accidentally do try to write to them.</p>\n\n<h1>Use <code>static</code> where appropriate</h1>\n\n<p>Functions and variables that are only used in the same <code>.c</code>-file where they are defined should be made <code>static</code>. This helps the compiler produce more optimized code, and prevents namespace pollution in larger projects. If you have everything in one <code>.c</code>-file, then every function and every global variable can be made <code>static</code>, except <code>main()</code> itself.</p>\n\n<h1>Improving performance</h1>\n\n<p>Your function <code>move()</code> is quite inefficient, it scales as O(S+T), where S is the number of states and T the number of possible transitions per state. It is possible to turn this into an O(1) operation. Instead of having a linked list of transitions, each storing the name, you could have an array of pointers to <code>State</code>s, indexed by the input character, like so:</p>\n\n<pre><code>typedef struct state {\n const char *sName;\n State *transitions[128]; // handle all 7-bit ASCII characters\n} State;\n</code></pre>\n\n<p>Assuming you fill in the <code>transitions</code> array correctly when parsing the state definitions, you can then change <code>move()</code> to:</p>\n\n<pre><code>const State *move(const State *automaton, int nStates, const State *currState, char ch) {\n return currState->transitions[ch];\n}\n</code></pre>\n\n<p>This solution is very fast, but it might waste quite a bit of memory if you only have a few valid transitions per state.</p>\n\n<p>Note that the above solution didn't require comparing state names. You could avoid that in your solution as well, by using <code>struct state *newState</code> in <code>Transition</code>, instead of storing the state name. Of course, the reason you went for this solution is that it simplifies parsing of the state definitions. However, it should be easy to modify the state definition parser to also handle previously unseen states after the first <code>;</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T18:04:10.810",
"Id": "462636",
"Score": "0",
"body": "Thank you for the advice! All useful tips. Only problem is with strdup(), as we were told we can only use standard functions in our programs. Will definitely look it up and see if I can use it in other programs where we don't have limitations on what libraries we can use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T18:41:37.350",
"Id": "462641",
"Score": "0",
"body": "Is strdup() in the standard yet, it didn't used to be portable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:05:32.783",
"Id": "462643",
"Score": "0",
"body": "It's going to be in [C2x](https://en.wikipedia.org/wiki/C2x)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T18:27:22.003",
"Id": "463356",
"Score": "0",
"body": "In this part ```if (len && end[len - 1] == '\\n')\n end[len - 1] = '\\0';``` you surely mean ```line``` instead of ```end```, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T23:09:59.777",
"Id": "463393",
"Score": "1",
"body": "I did indeed mean that. I've updated the answer, thanks for noticing."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:42:07.473",
"Id": "236161",
"ParentId": "236119",
"Score": "7"
}
},
{
"body": "<p>Overall good job, the code checks <code>malloc()</code> and sometimes checks <code>scanf()</code> for errors, generally braces wrap logic in <code>if</code> statements and loops. The functions generally adhere to the <code>Single Responsibility Principle</code>.</p>\n\n<p>It's not clear why the function <code>createNewState()</code> is unused since this would greatly simplify the <code>main()</code> function.</p>\n\n<p>There should be a function <code>createNewTransition()</code> that handles creating a transition, this would simplify the code in <code>void appendTransition(Transition **tList, char *newS, char ch)</code>.</p>\n\n<p>Recursion isn't necessary in <code>void appendTransition(Transition **tList, char *newS, char ch)</code>, it is very easy in a <code>while</code> loop to find the last transition in the list.</p>\n\n<h2>Readability</h2>\n\n<p>The structure/type names are good because they are descriptive.</p>\n\n<p>Since stdlib.h already has to be included for <code>malloc()</code>, it might be better to use <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> as the exit status.</p>\n\n<pre><code>int main() {\n\n...\n\n if(automaton == NULL) exit(EXIT_FAILURE);\n\n ...\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The variable name <code>n</code> isn't as descriptive as it could be, since the function to get the number of states is called <code>getNStates()</code> the variable could be called <code>nStates</code>.</p>\n\n<h2>Keep the User Informed</h2>\n\n<p>The program does not prompt the user for input even though it expects user intput, and the program does not report errors, it only quits when there are errors.</p>\n\n<p>The user should be prompted for input and error reporting should be added to error handling.</p>\n\n<pre><code>void reportErrorAndQuit(char *emsg)\n{\n fprintf(stderr, emsg);\n exit(EXIT_FAILURE);\n}\n\nint readNStates(){\n int nStates = 0;\n\n printf(\"Please enter the number of states in the automaton, the number of states must be greater than zero.\\n\");\n\n int scanfStatus = scanf(\"%d\", &nStates);\n if (scanfStatus < 1 || scanfStatus == EOF) {\n reportErrorAndQuit(\"Unable to read input, exiting program\\n\");\n }\n\n return nStates;\n}\n\nint getNStates() { // gets the number of states in the automaton\n int nStates = 0;\n\n while (nStates <= 0) {\n nStates = readNStates();\n }\n\n return nStates;\n}\n</code></pre>\n\n<h2>Calling <code>exit()</code></h2>\n\n<p>It is not necessary to call <code>exit(int exitStatus)</code> from <code>main()</code> a simple <code>return exitStatus;</code> is what is generally used. Call <code>exit()</code> from functions other than <code>main()</code> since the other functions don't return values to the operating system.</p>\n\n<h2>Reading a Line of Input From <code>stdin</code></h2>\n\n<p>The C library provides 2 functions for reading a line of input which might be better than using <code>scanf(\"%[^\\n]\", line);</code>. These functions are <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"nofollow noreferrer\">fgets(char *input_buffer, int max_buffer_size, FILE *stream)</a> and <code>gets(char *input_buffer)</code>. The function <code>fgets()</code> is considered safer since the buffer size is known and there will be no buffer overflow.</p>\n\n<pre><code> size_t charsRecieved = fgets(line, 100, stdin);\n if (size_t < 1) reportErrorAndQuit(\"Can't line read input from stdin\\n\");\n</code></pre>\n\n<p>There is a constant defined in stdio.h which is often used with <code>fgets()</code>, this constant is BUFSIZE and it is system dependent, generally the largest line that can be read.</p>\n\n<p>If the function <code>fgets()</code> is used then the code doesn't have to clear the input buffer after <code>scanf()</code>.</p>\n\n<h2>State *move(State **automaton, int nStates, State *currState, char ch)</h2>\n\n<p>In this function the line </p>\n\n<pre><code> if(tList == NULL) return NULL;\n</code></pre>\n\n<p>is not necessary, the condition in the while loop will handle this case, if <code>tList</code> is <code>NULL</code> it the code will not enter the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T18:01:29.477",
"Id": "462635",
"Score": "0",
"body": "Thank you for your input! As per the unused createNewState() function, I had initially written it because I though I would organize states in a linked list. Once I chose to use an array, I thought it wasn't needed anymore but I forgot to delete it. As per the \"keeping the user informed,\" I specified in my notes that the program mustn't print anything out. Neither error messages not prompt, due to it being automatically corrected by a program that matches the software's output with the expected output. Thank you for the advice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T21:55:31.187",
"Id": "462665",
"Score": "0",
"body": "What's the purpose of mentioning the obsolete `gets` function without saying \"never use it\"?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:51:48.163",
"Id": "236164",
"ParentId": "236119",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T15:45:30.277",
"Id": "236119",
"Score": "8",
"Tags": [
"performance",
"c",
"linked-list",
"pointers"
],
"Title": "C program that reads the description of a deterministic finite automaton and builds it"
}
|
236119
|
<p>I have been following along with a Udemy OOP basic course in Python. One of the sections prompted to make a banking system before watching the following videos. And so I have created a rudimentary banking system. I believe the system as is, is rather basic. I think there are some tweaks that can be made to it.</p>
<p>I have not use inheritance or any abstract base classes. Is there a possibility to utilize them in my solution? Are there ways to enhance the efficiency of my solution from an OOP point of standpoint?</p>
<p>My code continuously prompts the user for input on whether they are a new user or existing user. And does the following.</p>
<ul>
<li>A new user is allowed to create an account with an initial deposit.</li>
<li>An existing user is allowed to either deposit, withdraw or display their account information.</li>
<li>A few basic error checks, with more to come. I have checked:
<ul>
<li>Whether a user with the same name and account number exists, if so create a new account number.</li>
<li>Check whether a user's account is there, if not enter correct details.</li>
</ul></li>
</ul>
<p>For future code:</p>
<ul>
<li>Add in code so all transactions are saved and users can see a list of all deposits or withdrawals with dates.</li>
<li>More error checking.</li>
<li>A better menu system.</li>
</ul>
<pre><code>import pandas as pd
import os
import random
class Bank:
def __init__(self, name, acc_num):
self.name = name
self.acc_num = acc_num
def withdraw(self, amount):
self.amount = amount
self.column = name + "-" + str(self.acc_num)
self.accounts_df = pd.read_excel(os.getcwd() + "/accounts.xlsx")
self.accounts_df[self.column] = self.accounts_df[self.column].loc[0] - amount
self.accounts_df.to_excel(os.getcwd() + "/accounts.xlsx", index=False)
def deposit(self, amount):
self.amount = amount
self.column = name + "-" + str(self.acc_num)
self.accounts_df = pd.read_excel(os.getcwd() + "/accounts.xlsx")
self.accounts_df[self.column] = self.accounts_df[self.column].loc[0] + amount
self.accounts_df.to_excel(os.getcwd() + "/accounts.xlsx", index=False)
def display_balance(self):
self.column = self.name + "-" + str(self.acc_num)
self.accounts_df = pd.read_excel(os.getcwd() + "/accounts.xlsx")
print(self.accounts_df[self.column].loc[0])
class User():
def __init__(self, name):
self.name = name
def create_new_user(self, int_dep):
self.int_dep = int_dep
self.account_num = random.randint(10000, 99999)
if not os.path.exists(os.getcwd() + "/accounts.xlsx"):
data = {
self.name + "-" + str(self.account_num): [self.int_dep]
}
self.int_dep_df = pd.DataFrame(data)
else:
self.int_dep_df = pd.read_excel(os.getcwd() + "/accounts.xlsx", index=False)
print(self.account_num)
print('bfor')
while True:
if self.name + "-" + str(self.account_num) in self.int_dep_df.columns:
self.account_num = random.randint(10000, 99999)
else:
break
self.int_dep_df[self.name + "-" + str(self.account_num)] = self.int_dep
self.int_dep_df.to_excel(os.getcwd() + "/accounts.xlsx", index=False)
return 'Your account has been created you can now login with your name: ' + self.name + ' and account number: '\
+ str(self.account_num)
def existing_user(self, account_num):
self.account_num = account_num
ex_user_df = pd.read_excel(os.getcwd() + "/accounts.xlsx")
if self.name + "-" + str(self.account_num) in ex_user_df.columns:
return 'ok'
else:
return 'no user with these credentials, please enter again'
while True:
print('enter 1 if existing user')
print('enter 2 to new user')
user_input = int(input())
if user_input == 1:
while True:
name = input('Enter your name')
acc_number = int(input('Enter your account number'))
u = User(name)
check_ex_user = u.existing_user(acc_number)
if 'ok' in check_ex_user:
while True:
print('enter 4 to deposit')
print('enter 5 to withdraw')
print('enter 6 to display')
print('enter 7 to exit')
bank_actions = int(input())
bank_ob = Bank(name, acc_number)
if bank_actions == 4:
print('Enter amount to deposit')
dep = int(input())
bank_ob.deposit(dep)
elif bank_actions == 5:
print('Enter amount to withdraw')
withdraw_am = int(input())
bank_ob.withdraw(withdraw_am)
elif bank_actions == 6:
print('Your current balance is;')
bank_ob.display_balance()
elif bank_actions == 7:
break
break
else:
print(check_ex_user)
continue
elif user_input == 2:
name = input('Enter your name')
int_dep = int(input('Enter your initial deposit'))
u = User(name)
u.create_new_user(int_dep)
continue
</code></pre>
|
[] |
[
{
"body": "<p>Your code uses menu technology from the 1980s. It is not user-friendly at all.</p>\n\n<p>Instead of offering the user the choice of 1, 2, 3, 4, it is better to let the user choose the actions by naming them directly. As an example, see the following transcript, in which the lines starting with <code>></code> show the user input:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Bank manager version 2020.1\nType 'help' to see the available commands.\n\n> help\navailable commands:\nhelp\nregister account <name> <balance>\ndelete account <account number>\nlist accounts\ntransfer <amount> from <source> to <target>\nquit\n\n> register account\nusage: register account <name> <balance>\n\n> register account \"First Last\" 12345.05\ncreated account AC0001\n\n> transfer 1234.44 from AC0001 to AC0007\nerror: target account AC0007 does not exist\n\n> register account \"Family\" 0.00\ncreated account AC0002\n\n> transfer 1234.44 from AC0001 to AC0002\ntransferred\n</code></pre>\n\n<p>This kind of interaction is more natural to read than a sequence like 1, 3, 1, 5, 1, 1.</p>\n\n<p>Of course it's a bit more work to split the lines into meaningful pieces, especially with the spaces in the name and the quotes around it, but it has the benefit that you can save all these interactions in a file and apply that file automatically, which is useful for testing your code after any changes.</p>\n\n<p>Plus, the names of the actions are more stable than the menu item numbers. Whenever you change the structure of the menus, your users would have to re-learn the numbers and their associated actions.</p>\n\n<p>Regarding your data model:</p>\n\n<ul>\n<li>In normal life, a <code>Bank</code> is an institution that has <em>many</em> accounts. In your code, a bank is created whenever someone deposits or withdraws an amount. This wording is not correct. The bank should be a long-lived object. And it should be able to manage several accounts.</li>\n</ul>\n\n<p>Regarding your code:</p>\n\n<ul>\n<li><p>The variable <code>bank_actions</code> is wrong. The name must be <code>bank_action</code> since this variable only holds a single action.</p></li>\n<li><p>In <code>User.create_new_user</code> you make the account number a random integer. That is wrong since account numbers must be unique. Having only 90000 different account numbers will quickly generate collisions. A bank must manage money and accounts more reliably. In particular, it must not reuse existing account numbers.</p></li>\n</ul>\n\n<p>In summary, I suggest that you re-think the whole domain that you are modelling. Write down the possible actions in natural language and carefully check whether it makes sense to \"deposit money to a bank\", or whether it would be more appropriate to \"deposit money to an account, managed by a bank\". Be pedantic with each word, be as precise as possible.</p>\n\n<p>And after that, you will probably have to rewrite your code so that it matches your new domain model again.</p>\n\n<p>It's good to have an early prototype in code, but don't hesitate to throw it away. Usually the second attempt is much better than the first one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T23:32:38.733",
"Id": "462676",
"Score": "0",
"body": "This is really great info, and great detailing. I agree I think I have a problem with modelling projects like this in OOP, this is why I want to get better at, I guess I need to start thinking out the box a bit more, before I had just been working with data in pandas so a different type of modelling!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T23:33:17.063",
"Id": "462677",
"Score": "0",
"body": "Would you recommend for the menu code to create a class for that to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T06:56:16.243",
"Id": "462689",
"Score": "1",
"body": "No, I would not use a class immediately. I would first do the menu code using functions. And if it becomes clear later that there are several functions that belong together and share some data, I would put them in a class. But before that, I prefer simple functions, just because they are simpler."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:34:09.567",
"Id": "236160",
"ParentId": "236120",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236160",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T15:46:50.973",
"Id": "236120",
"Score": "5",
"Tags": [
"python",
"object-oriented"
],
"Title": "OOP banking system"
}
|
236120
|
<p>I was thinking of adding a very high-level implementation of the event/observer pattern to my project. The implementation would manage adding and removing observers as "needed". You can use an almost DLS-like API to define when an observer should be added or removed.</p>
<p>Here is an example of the API in use. We want to track mouse dragging along a path:</p>
<pre><code>public void registerMousePathTracker(
Mouse mouse,
Consumer<List<Point>> callback
)
{
final List<Point> points = new ArrayList<>();
observe(mouse)
.when(MouseDown.class)
.Do(evt -> {
points.clear();
points.add(evt.getPoint());
})
.once()
.laterWhen(MouseMove.class)
.Do(evt -> {
points.add(evt.getPoint());
})
.until(MouseUp.class)
.thenDo(evt -> {
points.add(evt.getPoint());
callback.accept(points);
})
.once()
.repeatIndefinitely()
;
}
</code></pre>
<p>This code defines 3 observers:</p>
<ul>
<li>when the mouse is pressed down we clear the points list and add the point where the mouse was pressed. Then we remove this observer from <em>mouse</em> and add the next observer.</li>
<li>every time the mouse is being moved we add a point to the points list.</li>
<li>when the mouse is released (no longer pressed) we remove the second observer and add the third. The third observer adds the current mouse position to the points list and calls the callback that was passed as a parameter. Afterwards the third observer removes itself from the mouse.</li>
<li>After the third observer was removed the first observer is added again to create a full circle.</li>
</ul>
<hr>
<p>The observe-Method is defined by the ObserverManager interface:</p>
<pre><code>public interface ObserverManager {
public DefineEventType observe(EventSrc eventSource);
@SuppressWarnings("unchecked")
public default <X extends Event> Consumer<X> nothing() {
return (Consumer<X>) DO_NOTHING;
}
public static final Consumer<Event> DO_NOTHING = e -> {};
public static interface DefineEventType {
public <X extends Event> DefineAction<X> when(Class<X> eventType);
}
public static interface DefineAction<X extends Event> {
public DefineCondition<X> Do(Consumer<X> action);
}
public static interface DefineCondition<X extends Event> {
public DefineChainedEvent once();
public void always();
public DefineChainedEvent While(Predicate<X> continueCondition);
public DefineChainedEvent until(Predicate<X> stopCondition);
public <Y extends Event> DefineFollowUpAction<Y> until(Class<Y> stopEventType);
}
public static interface DefineChainedEvent {
public <X extends Event> DefineAction<X> laterWhen(Class<X> event);
public void repeatIndefinitely();
}
public static interface DefineFollowUpAction<X extends Event> extends DefineChainedEvent {
public DefineCondition<X> thenDo(Consumer<X> action);
}
}
</code></pre>
<p>There is one implementation of this interface which could either be used as a <a href="https://en.wikipedia.org/wiki/Delegation_(object-oriented_programming)" rel="nofollow noreferrer">delegate</a> or as a super-class:</p>
<pre><code>public class ObserverManagerImpl implements ObserverManager {
@Override
public DefineEventType observe(EventSrc eventSource) {
return new ObserveBuilder(this, eventSource);
}
@SuppressWarnings("rawtypes")
static class ObserveBuilder implements DefineEventType, DefineChainedEvent, DefineAction, DefineFollowUpAction, DefineCondition {
private final ManagedObserver first;
private ManagedObserver latest;
private Class mostRecentStopEvent;
ObserveBuilder(ObserverManager source, EventSrc target) {
first = new ManagedObserver(source, target);
latest = first;
}
private void registerIfNeeded() {
if (latest == first) {
first.register();
}
}
@SuppressWarnings("unchecked") @Override
public <X extends Event> DefineAction<X> when(Class<X> event) {
latest.evtType = event;
return this;
}
@SuppressWarnings("unchecked") @Override
public <X extends Event> DefineAction<X> laterWhen(Class<X> event) {
ManagedObserver prev = latest;
latest = new ManagedObserver(prev.source, prev.target);
latest.evtType = event;
prev.followUp = latest;
return this;
}
@SuppressWarnings("unchecked") @Override
public DefineCondition Do(Consumer action) {
latest.action = action;
return this;
}
@SuppressWarnings("unchecked") @Override
public DefineCondition thenDo(Consumer action) {
ManagedObserver prev = latest;
latest = new ManagedObserver(prev.source, prev.target);
latest.evtType = mostRecentStopEvent;
prev.followUp = latest;
return Do(action);
}
@Override
public DefineChainedEvent once() {
Class<?> evtType = latest.evtType;
latest.unregisterCondition = evt -> evtType.isInstance(evt);
registerIfNeeded();
return this;
}
@Override
public void always() {
latest.unregisterCondition = null;
registerIfNeeded();
}
@Override
public DefineFollowUpAction until(Class stopEvent) {
mostRecentStopEvent = stopEvent;
latest.unregisterCondition = evt -> stopEvent.isInstance(evt);
registerIfNeeded();
return this;
}
@SuppressWarnings("unchecked") @Override
public DefineChainedEvent until(Predicate stopCondition) {
latest.unregisterCondition = evt -> stopCondition.test(evt);
registerIfNeeded();
return this;
}
@SuppressWarnings("unchecked") @Override
public DefineChainedEvent While(Predicate continueCondition) {
latest.unregisterCondition = evt -> !continueCondition.test(evt);
registerIfNeeded();
return this;
}
@Override
public void repeatIndefinitely() {
latest.followUp = first;
}
}
}
</code></pre>
<p>The ManagedObserver class looks like this:</p>
<pre><code>class ManagedObserver implements Observer {
final ObserverManager source;
final EventSrc target;
Class<? extends Event> evtType;
Consumer<Event> action;
Predicate<Event> unregisterCondition;
ManagedObserver followUp;
ManagedObserver(ObserverManager source, EventSrc target) {
this.source = source;
this.target = target;
}
@Override
public void onEvent(Event evt) {
if (evtType.isInstance(evt)) {
action.accept(evt);
}
if (unregisterCondition != null && unregisterCondition.test(evt)) {
unregister();
if (followUp != null) {
followUp.register();
followUp.onEvent(evt);
}
}
}
void register() {
target.addObserver(this);
}
private void unregister() {
target.removeObserver(this);
}
}
</code></pre>
<hr>
<p>My main concerns are:</p>
<ol>
<li>the naming of the methods in ObserverManager. The methods "Do" and "While" use capitalization in their names (because these words are java keywords) but in my opinion these names are the "perfect" fit for their purposes.</li>
<li>feature completeness. Will I be able to use this throughout my application or will this become a huge investment for little return because it lacks the features I will need.</li>
<li>I consider the ObserverManagerImpl class a rather "dirty" implementation. On the other hand, I also think that this may be okay in a situation like this where it is part of a closed system that is not supposed to be touched after it has been finished once.</li>
</ol>
<p>What are your thoughts and opinions? All feedback and suggestions for improvement are welcome.</p>
<hr>
<h2>Edit:</h2>
<p>I changed the ObserverManager interface & implementation in such a way to make sure both "until" methods work the same way. I guess it makes the implementation even more ugly. Advise is appreciated.</p>
|
[] |
[
{
"body": "<blockquote>\n <ol>\n <li>the naming of the methods in ObserverManager. The methods \"Do\" and \"While\" use capitalization in their names (because these words are java keywords) but in my opinion these names are the \"perfect\" fit for their purposes.</li>\n </ol>\n</blockquote>\n\n<p>Synonyms. What about <code>perform</code> instead of <code>Do</code> and <code>whilst</code> or <code>asLongAs</code> (for the non-Brits) for <code>while</code>?</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>feature completeness. Will I be able to use this throughout my application or will this become a huge investment for little return because it lacks the features I will need.</li>\n </ol>\n</blockquote>\n\n<p>I'm always very wary of generic functionality like this. You have to make sure that it is reasonably well behaved because if it needs redesign or if it had bugs, you may end up having to update all the applications and libraries that use it. Furthermore, you'll be the only person that fully understands what's going on.</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>I consider the ObserverManagerImpl class a rather \"dirty\" implementation. On the other hand, I also think that this may be okay in a situation like this where it is part of a closed system that is not supposed to be touched after it has been finished once.</li>\n </ol>\n</blockquote>\n\n<p>Sure, it won't harm here, but if it is deployed elsewhere then you need to test it, document it and make sure it is flexible enough.</p>\n\n<hr>\n\n<p>I'm slightly worried about the number of suppressed warnings - especially those for the generics. That's OK for some libraries if they are well designed, but it's a bit tricky for me to evaluate that.</p>\n\n<hr>\n\n<p>All in all, it looks well designed, but it is rather complex for what it tries to accomplish as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:41:21.047",
"Id": "238069",
"ParentId": "236122",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T16:00:09.073",
"Id": "236122",
"Score": "3",
"Tags": [
"java",
"api",
"event-handling",
"observer-pattern"
],
"Title": "High-Level Managed Observers"
}
|
236122
|
<p>Based on <a href="https://codereview.stackexchange.com/questions/235883/how-to-increase-the-efficiency-of-dla-algorithm/235901#235901">my answer</a> to another code review question I wrote my own python script for DLA (Diffusion Limited Aggregation).</p>
<p>The DLA algorithm task:</p>
<ul>
<li>Place seed at the center of the canvas.</li>
<li>Release a random walker from the edge.</li>
<li>Random walker sticks to the neighboring sites of the seed/previous points.</li>
<li>Repeat N(particles) times.</li>
</ul>
<p>Also, it was stated to use a 500x500 grid and simulate 50000 particles. And particles where not allowed to leave the area.</p>
<p>A brute force approach is very timeconsuming especially for increasing area size. Therefore I choose a different approach.</p>
<ul>
<li>Precalculate possible solutions when doing n steps in one go using multinomial distribution</li>
<li>calculate a distance_matrix for all positions in the area, with the max. allowed steps that make sure, we do not leave the area (by more than one step; thats needed, or border would become sticking position) and also do not collide with another particle. This also gives automatically information about all stick positions (value == 0; sticking particles get value == -1).</li>
<li>the distance matrix only has to be recalculated when a particle sticks (and also only a limited part of the whole area). While this is time consuming, it only happens N times (N=50000 particles)</li>
<li>when a particle does a step, I first check the max distance and then get the corresponding precalculated possible movements and use np.random to choose from that list</li>
</ul>
<p>This approach could solve the task in 45 minutes (the brute force approach was stated to take more than a day):</p>
<p><a href="https://i.stack.imgur.com/SdEIn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SdEIn.png" alt="enter image description here"></a></p>
<p>Note that 50000 particles seems to be too high a number for a 500x500 area, because in the end, particles are stopped at the border (but I wanted to reproduce the given task ^^).</p>
<p>For the precalculating, I used the module multiprocessing, for larger areas (200x200 and above) this improved the precalculating speed by a factor 6 with 6 cores on my test system. More than 95% of calculation time is spent in </p>
<pre><code>position_list[pos_y, pos_x] += rv.pmf([n_left, n_right, n_down, n_up])
</code></pre>
<p>In the end, the precalculation only took 3% of the total simulation time, so I guess I can not improve efficency here (beside maybe saving precalculated values in a file, which could be loaded again for later simulations).</p>
<p><strong>More than 1/3 of the total computation time is spent with DLASimulator.get_random_step()</strong></p>
<p>I have a feeling, that there is still a possibility for significant improvement.</p>
<p>Feedback to readability, efficency and general remarks are welcome.</p>
<pre><code>import bisect
from collections import defaultdict
from multiprocessing.pool import Pool
from multiprocessing.spawn import freeze_support
from typing import Optional, List
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import multinomial
def main():
np.random.seed(0)
dla_simulator = DLASimulator(area_size=(500, 500), max_steps=200) # max_steps is 167 for 500x500
dla_simulator.simulate(particles=50000)
dla_simulator.plot()
print("done")
class DLASimulator:
def __init__(self, area_size: tuple, max_steps: int, initial_particles_pos: Optional[List[tuple]] = None, max_factor=1.0):
self.area_size = area_size
if initial_particles_pos is None:
initial_particles_pos = [(area_size[0] // 2, area_size[1] // 2)]
self.initial_particles_pos = initial_particles_pos
self.distance_matrix = None # only to help code completion
self.init_distance_matrix()
self.is_first_particle = True
self.set_stick_particles(self.initial_particles_pos)
self.max_steps = min(max_steps, self.distance_matrix.max()) # no need to precalculate more than max distance
self.max_steps = max(int(self.max_steps*max_factor), 1) # no need to precalculate more than max distance
self.list_of_position_probability_dicts = generate_list_of_position_probability_dicts(self.max_steps)
def reset(self):
self.init_distance_matrix()
self.set_stick_particles(self.initial_particles_pos)
def simulate(self, particles: int = 1000, reset: bool = False):
print("start simulation")
if reset:
self.reset()
for _ in range(particles):
particle = self.get_new_particle()
self.simulate_particle(particle)
print(f"particle {_} sticked")
def simulate_particle(self, particle):
while True:
distance = self.distance_matrix[particle[1], particle[0]]
if distance == 0:
self.set_stick_particle(particle)
break
elif distance < 0:
# raise Exception("There is already a particle on This position")
break
else:
pos_x, pos_y = self.get_random_step(distance)
particle[0] = min(max(particle[0] + pos_x, 0), self.area_size[0]-1)
particle[1] = min(max(particle[1] + pos_y, 0), self.area_size[1]-1)
# calc distance to border for all positions (allowed number of steps in one go for each position)
def init_distance_matrix(self):
size_x, size_y = self.area_size
self.distance_matrix = np.zeros(self.area_size, np.int16)
for pos_x in range(size_x):
for pos_y in range(size_y):
self.distance_matrix[pos_y, pos_x] = min(pos_x + 1, pos_y + 1, size_x-pos_x, size_y - pos_y)
def set_stick_particles(self, particles):
for particle in particles:
self.set_stick_particle(particle)
def set_stick_particle(self, particle):
pos_x, pos_y = particle
self.distance_matrix[pos_y, pos_x] = -1 # no other particle allowed on this position
self.update_distance_positions(particle)
def update_distance_positions_in_rect(self, x_min, x_max, y_min, y_max, particle):
particle_x, particle_y = particle
for pos_x in range(x_min, x_max+1):
for pos_y in range(y_min, y_max + 1):
distance_to_stick = max(abs(pos_x - particle_x) + abs(pos_y - particle_y) - 1, 0)
self.distance_matrix[pos_y, pos_x] = min(self.distance_matrix[pos_y, pos_x], distance_to_stick)
def update_distance_positions(self, particle):
particle_x, particle_y = particle
x_min, y_min = 0, 0
x_max, y_max = self.area_size[0]-1, self.area_size[1]-1
# go in 4 directions; as soon as distance-value is smaller than distance from particle -> stop
for i in range(particle_x-1, -1, -1):
if self.distance_matrix[particle_y, i] <= particle_x - 1 - i:
x_min = i+1
break
for i in range(particle_y-1, -1, -1):
if self.distance_matrix[i, particle_x] <= particle_y - 1 - i:
y_min = i+1
break
for i in range(particle_x+1, self.area_size[0]):
if self.distance_matrix[particle_y, i] <= i - (particle_x + 1):
x_max = i-1
break
for i in range(particle_y+1, self.area_size[1]):
if self.distance_matrix[i, particle_x] <= i - (particle_y + 1):
y_max = i-1
break
self.update_distance_positions_in_rect(x_min, x_max, y_min, y_max, particle)
def get_new_particle(self) -> list:
random = np.random.randint(4)
if random == 0:
pos_x = 0
pos_y = np.random.randint(self.area_size[1])
elif random == 1:
pos_x = self.area_size[0] - 1
pos_y = np.random.randint(self.area_size[1])
elif random == 2:
pos_x = np.random.randint(self.area_size[0])
pos_y = 0
elif random == 3:
pos_x = np.random.randint(self.area_size[0])
pos_y = self.area_size[1] - 1
else:
raise Exception("Something went wrong in get_new_particle()")
return [pos_x, pos_y]
def get_random_step(self, distance):
n_step_dict = self.list_of_position_probability_dicts[min(distance, self.max_steps)]
random = np.random.random()
# search on numpy array seems to be slower then bisect on list
# index = np.searchsorted(n_step_dict["cumulative probability"], random)
index = bisect.bisect_left(n_step_dict["cumulative probability"], random)
pos_x = n_step_dict["pos_x"][index]
pos_y = n_step_dict["pos_y"][index]
return pos_x, pos_y
def plot(self):
canvas = np.zeros(self.area_size)
for x in range(self.area_size[0]):
for y in range(self.area_size[1]):
if self.distance_matrix[y, x] == -1:
canvas[y, x] = 1
plt.matshow(canvas)
plt.show()
plt.savefig("rand_walk_500particles.png", dpi=150)
def calc_symmetric_positions(position_list: dict) -> dict:
result = {}
for key, value in position_list.items():
pos_x = key[0]
pos_y = key[1]
result[-pos_x, pos_y] = position_list[(pos_x, pos_y)]
result[-pos_x, -pos_y] = position_list[(pos_x, pos_y)]
result[pos_x, -pos_y] = position_list[(pos_x, pos_y)]
result[pos_y, pos_x] = position_list[(pos_x, pos_y)]
result[-pos_y, pos_x] = position_list[(pos_x, pos_y)]
result[-pos_y, -pos_x] = position_list[(pos_x, pos_y)]
result[pos_y, -pos_x] = position_list[(pos_x, pos_y)]
return result
# no need for complete matrix, only list with actually reachable positions;
# creation is 1.055 times faster (compared to full matrix)
def calc_position_probability_list_symmetric(number_of_steps) -> dict:
result = {"cumulative probability": [], "pos_x": [], "pos_y": []}
# position_list = defaultdict(lambda:0.0) # multiprocessing needs to pickle -> can't have a lambda
position_list = defaultdict(float)
if number_of_steps == 0:
result["cumulative probability"].append(1)
result["pos_x"].append(0)
result["pos_y"].append(0)
return result
p_list = [0.25, 0.25, 0.25, 0.25] # all directions have same probability
rv = multinomial(number_of_steps, p_list)
# this loop finds all reachable positions
for n_right in range(number_of_steps + 1):
for n_left in range(number_of_steps - n_right + 1):
pos_x = n_right - n_left
if pos_x > 0: # due to symmetry
continue
for n_down in range(number_of_steps - n_left - n_right + 1):
n_up = number_of_steps - n_left - n_right - n_down
pos_y = n_up - n_down
# if pos_y > 0: # unnecessary; pos_x is already <=0
# continue
if pos_y > pos_x: # due to symmetry
continue
# this takes up >95% of computation time in calc_position_probability_list_symmetric!
# thus optimizing loop with impact on readability not helpful
# todo: check with pypy
position_list[pos_y, pos_x] += rv.pmf([n_left, n_right, n_down, n_up])
position_list.update(calc_symmetric_positions(position_list))
# create cummulative distribution values:
# todo: consider sorting before creating cumulative, to allow faster algorithm SLASimulator.in get_random_step()
sum=0
for key, value in position_list.items():
sum += value
result["cumulative probability"].append(sum)
result["pos_x"].append(key[0])
result["pos_y"].append(key[1])
# no speedup for bisect (np.array is even slower then list)
# result["cumulative probability"] = np.array(result["cumulative probability"])
# result["cumulative probability"] = tuple(result["cumulative probability"])
assert np.isclose(sum, 1.0)
return result
def generate_list_of_position_probability_dicts_single_process(max_number_of_steps: int) -> List[dict]:
result = []
for i in range(max_number_of_steps+1):
result.append(calc_position_probability_list_symmetric(i))
return result
def generate_list_of_position_probability_dicts(max_number_of_steps: int, multiprocessing=True) -> List[dict]:
if not multiprocessing:
return generate_list_of_position_probability_dicts_single_process(max_number_of_steps)
with Pool() as pool: # processes=None (or no argument given) -> number returned by os.cpu_count() is used.
result = pool.map(calc_position_probability_list_symmetric, range(max_number_of_steps+1))
return result
if __name__ == '__main__':
freeze_support() # needed for windows
main()
</code></pre>
<p>(the newest version can be found <a href="https://github.com/natter1/playground/blob/master/my_dla_optimization.py" rel="nofollow noreferrer">here</a>)</p>
|
[] |
[
{
"body": "<p>As I understand the code, it 1) determines a minimum number of steps (a \"radius\") before a particle could run into a sticky point or the edge and 2) randomly moves to a point based on a pre-calculated multinomial distribution for that number of steps. The selected point could be anywhere within the determined \"radius\".</p>\n\n<p>It seems that for a particle to reach a sticky point or the edge, it must first reach the circumference of the area defined by the radius. Therefore, for each step, it would suffice for the particle to jump to a randomly select point on the circumference of that area. And, because the area is symmetrical, it seems the points on the circumference are all equally probable.</p>\n\n<p>This would let the particle make large jumps when it is far away from anything and take small steps when it is near something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T15:26:39.167",
"Id": "462615",
"Score": "0",
"body": "Interesting approach. While this is not really following the algorithm (there is no random walk done; it would be impossible to draw the path of the particle), it might generate similar results. And it would be orders of magnitude faster. The question is, how to prove, that each point on the circumference has the same probability. That is not true for doing it in the least possible number of steps. For example, there is only one option to do 10 steps to the right, but there are allready 10 options for one up and 9 right. But intuitivly, when ignoring the step number, it should be true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:11:55.150",
"Id": "462647",
"Score": "0",
"body": "@natter1, Also, mapping from circumference to a grid coordinate may alter the probabilities. But the code already calculates the probabilities for every point that is upto *n* steps away. Just use the ones on the perimeter to calculate the cumulative distribution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:26:52.093",
"Id": "462649",
"Score": "0",
"body": "no need for mapping \"circumference\" to grid. The circumference is simply in dimond shape due to limiting the movement in 4 directions. Also, I don't think its a good idea to use the probabilities claculated with a fixed number of steps. I'm pretty sure, without limiting the number of steps, until reaching the circumverence, each position should have the same probability (so no precalculation; it would come down to a very simple function 1/(number of circumference positions)). The only question is, how to prof, that this is true (something like: if it is true for n, its true for n+1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:28:07.503",
"Id": "462650",
"Score": "0",
"body": "Maybe I will check with a brute force approach for small n values, if all positions have same probability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T08:15:47.423",
"Id": "462691",
"Score": "0",
"body": "Thinking about it a bit more, the number of paths to one side of the diamond circumference is just pascals triangle. One step = 1 1 (say for the upper right side of the diamond). For two steps the number of paths is 1 2 1, for three steps 1 3 3 1, and so on."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T00:46:09.667",
"Id": "236131",
"ParentId": "236124",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T16:13:00.323",
"Id": "236124",
"Score": "3",
"Tags": [
"python",
"algorithm",
"physics"
],
"Title": "Diffusion Limited Aggregation Simulator"
}
|
236124
|
<p>Version 1 - <a href="https://codereview.stackexchange.com/q/236045/37991">Beginner web scraper for Nagios</a></p>
<p>Current version changes:</p>
<ul>
<li>Moved <code>NAGIOS_DATA</code> dictionary to separate file (and added to .gitignore)</li>
<li>Used functions with DOCSTRINGS</li>
<li>Removed the multiple redundant <code>print()</code> statements</li>
<li>Actually <em>read</em> the PEP8 standards, and renamed variables to match the requirements</li>
</ul>
<p>Again, beginner Python programmer. I appreciate the feedback!</p>
<pre><code>import requests
from scraper import NAGIOS_DATA
from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
def get_url_response(url, user, password, auth_type):
"""Get the response from a URL.
Args:
url (str): Nagios base URL
user (str): Nagios username
password (str): Nagios password
auth_type (str): Nagios auth_type - Basic or Digest
Returns: Response object
"""
if auth_type == "Basic":
return requests.get(url, auth=HTTPBasicAuth(user, password))
return requests.get(url, auth=HTTPDigestAuth(user, password))
def main():
"""
Main entry to the program
"""
# for nagios_entry in ALL_NAGIOS_INFO:
for url, auth_data in NAGIOS_DATA.items():
user, password, auth_type = auth_data["user"], auth_data["password"], \
auth_data["auth_type"]
full_url = "{}/cgi-bin/status.cgi?host=all".format(url)
response = get_url_response(full_url, user, password, auth_type)
if response.status_code == 200:
html = BeautifulSoup(response.text, "html.parser")
for i, items in enumerate(html.select('td')):
if i == 3:
hostsAll = items.text.split('\n')
hosts_up = hostsAll[12]
hosts_down = hostsAll[13]
hosts_unreachable = hostsAll[14]
hosts_pending = hostsAll[15]
hosts_problems = hostsAll[24]
hosts_types = hostsAll[25]
if i == 12:
serviceAll = items.text.split('\n')
service_ok = serviceAll[13]
service_warning = serviceAll[14]
service_unknown = serviceAll[15]
service_critical = serviceAll[16]
service_problems = serviceAll[26]
service_types = serviceAll[27]
# print(i, items.text) ## To get the index and text
print_stats(
user, url, hosts_up, hosts_down, hosts_unreachable,
hosts_pending, hosts_problems, hosts_types, service_ok,
service_warning, service_unknown, service_critical,
service_problems, service_types)
# print("Request returned:\n\n{}".format(html.text))
# To get the full request
def print_stats(
user, url, hosts_up, hosts_down, hosts_unreachable, hosts_pending,
hosts_problems, hosts_types, service_ok, service_warning,
service_unknown, service_critical, service_problems, service_types):
print("""{}@{}:
Hosts
Up\tDown\tUnreachable\tPending\tProblems\tTypes
{}\t{}\t{}\t\t{}\t{}\t\t{}
Services
OK\tWarning\tUnknown\tCritical\tProblems\tTypes
{}\t{}\t{}\t{}\t\t{}\t\t{}""".format(
user, url, hosts_up, hosts_down, hosts_unreachable, hosts_pending,
hosts_problems, hosts_types, service_ok, service_warning,
service_unknown, service_critical, service_problems, service_types))
if __name__ == '__main__':
main()
</code></pre>
<p><code>scraper.py</code> source:</p>
<pre class="lang-py prettyprint-override"><code>NAGIOS_DATA = {
'http://192.168.0.5/nagios': {
'user': 'nagiosadmin',
'password': 'PasswordHere1',
'auth_type': 'Basic'
},
'https://www.example.com/nagios': {
'user': 'exampleuser',
'password': 'P@ssw0rd2',
'auth_type': 'Digest'
},
}
</code></pre>
|
[] |
[
{
"body": "<p>There are still a couple of rouge non-PEP8-compliant variable names: <code>serviceAll</code> and <code>hostsAll</code>.</p>\n\n<p>This is a minor detail, but to avoid too much nesting I would suggest inverting this condition <code>if response.status_code == 200:</code>. Then you can write it like this:</p>\n\n<pre><code>if response.status_code != 200:\n continue # or raise an exception\n\nhtml = BeautifulSoup(response.text, \"html.parser\")\n</code></pre>\n\n<p>IMO, such code is much easier to read. These kind of checks are also called guards (<a href=\"https://en.wikipedia.org/wiki/Guard_(computer_science)\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Guard_(computer_science)</a>).</p>\n\n<p>Instead of iterating through all the <code>td</code> tags, I would store them in a list and then extract the necessary elements with an index:</p>\n\n<pre><code>td_elements = list(html.select('td'))\nhosts_all = td_elements[3].text.split('\\n')\nservice_all = td_elements[12].text.split('\\n')\n</code></pre>\n\n<p>Next, I would like to focus on the <code>print_stats</code> function. It takes way to many parameters and has become tough to work with. I suggest storing all variables you extract from the HTML in a dictionary, which you can then pass to the <code>print_stats</code> function.</p>\n\n<pre><code>extracted_information = {\n 'hosts_up': hosts_all[12],\n 'hosts_down': hosts_all[13],\n 'hosts_unreachable': hosts_all[14],\n 'hosts_pending': hosts_all[15],\n 'hosts_problems': hosts_all[24],\n 'hosts_types': hosts_all[25],\n 'service_ok': service_all[13],\n 'service_warning': service_all[14],\n 'service_unknown': service_all[15],\n 'service_critical': service_all[16],\n 'service_problems': service_all[26],\n 'service_types': service_all[27],\n}\n</code></pre>\n\n<p>Then you would call the <code>print_stats</code> function like this: <code>print_stats(user, url, extracted_information)</code>.</p>\n\n<p>Of course, we now have to rewrite the print_stats function itself. The Python format function can also take named parameters. For example: <code>\"{param1} and {param2}\".format(param1=\"a\", param2=\"b\")</code> would return string <code>\"a and b\"</code>. Using this we can rewrite the template string and pass the \"unpacked\" <code>extracted_information</code> dictionary to the <code>format</code> function.</p>\n\n<pre><code>def print_stats(user, url, extracted_information):\n template = \"\"\"{user}@{url}:\n Hosts\n Up\\tDown\\tUnreachable\\tPending\\tProblems\\tTypes\n {hosts_up}\\t{hosts_down}\\t{hosts_unreachable}\\t\\t{hosts_pending}\\t{hosts_problems}\\t\\t{hosts_types}\n Services\n OK\\tWarning\\tUnknown\\tCritical\\tProblems\\tTypes\n {service_ok}\\t{service_warning}\\t{service_unknown}\\t{service_critical}\\t\\t{service_problems}\\t\\t{service_types}\"\"\"\n\n print(template.format(user=user, url=url, **extracted_information))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:33:36.077",
"Id": "236143",
"ParentId": "236127",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T20:02:25.093",
"Id": "236127",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Simple Nagios Scraper - version 2"
}
|
236127
|
<p>We start off we the following <code>Person</code> class:</p>
<pre><code>class Person:
def __init__(self):
self.moods = {
"happy": 5,
"angry": 5,
"sad": 5
}
def updateStates(self, stateUpdates: {}):
for mood, valChange in stateUpdates.items():
self.moods[mood] += valChange
</code></pre>
<p>From here I implemented a restriction on what the values <code>self.moods</code> can be.
I have implemented the restriction using descriptors. But I find it distasteful.</p>
<p>The following works. But I don't think it is worth it because now I have to append <code>.__get__(instance=self, owner=None)</code> to <code>self.moods[<mood>]</code> whenever I need to access a mood, or <code>.__set__(instance=self, value=<newVal>)</code> whenever I want to update one. This will quickly pollute my code and make it unreadable, which is why I am not a fan of this approach.</p>
<pre><code>class OneDigitNumericValue(): # descriptor class
def __set_name__(self, owner, name):
self.name = name
def __init__(self, defaultVal=5):
self.value = defaultVal
def __get__(self, instance, owner) -> object:
return self.value
def __set__(self, instance, value) -> None:
if not (0 < value < 9) or int(value) != int:
raise AttributeError("The value is invalid")
self.value = value
class Person:
moods = {
"happy": OneDigitNumericValue(),
"angry": OneDigitNumericValue(),
"sad": OneDigitNumericValue()
}
def updateStates(self, stateUpdates: {}):
for mood, valChange in stateUpdates.items():
oldVal = self.moods[mood].__get__(self, owner=None)
self.moods[mood].__set__(self, value=oldVal + valChange)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:53:46.137",
"Id": "462671",
"Score": "1",
"body": "This code can't ever work. Have you actually ran your provided code? `int(value) != int` is always true, you always error on any input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T12:17:34.390",
"Id": "462710",
"Score": "0",
"body": "Can you provide some examples on what input you expect this to work with. Because `Person().updateStates({'happy': 1})` doesn't work."
}
] |
[
{
"body": "<p>First of all, as per PEP8 I'd recommend you follow the <a href=\"https://www.python.org/dev/peps/pep-0008/#id34\" rel=\"nofollow noreferrer\">naming conventions</a>.</p>\n\n<p>A couple of examples:</p>\n\n<ul>\n<li><code>updateStates</code> -> <code>update_states</code> </li>\n<li><code>defaultValue</code> -> <code>default_value</code></li>\n</ul>\n\n<p>I think you were headed in the right direction, but instead of overriding the <code>__get__</code> and <code>__set__</code> methods, I would just override the <code>__add__</code> method, which would allow you to reuse the updateStates method from the first snippet. The <code>__add__</code> method allows you to override the behavior of the <code>+</code> operator (<a href=\"https://docs.python.org/3/reference/datamodel.html#object.__add__\" rel=\"nofollow noreferrer\">https://docs.python.org/3/reference/datamodel.html#object.<strong>add</strong></a>).</p>\n\n<p>Instead of <code>int(value) != int</code> to check whether <code>value</code> is an integer, you should use <code>isinstance</code>, which is the preferred way to check for the type of the variable in Python3.</p>\n\n<p>Below I wrote a snippet incorporating the suggestions. As you can see, I pretty much reused your code, just added the <code>__add__</code> method and the <code>isinstance</code> check.</p>\n\n<pre><code>class OneDigitNumericValue:\n def __init__(self, default_val=5):\n self.value = default_val\n\n def __add__(self, other_value):\n if not isinstance(other_value, int):\n raise AttributeError(\"The value is not an integer.\")\n\n new_value = self.value + other_value\n\n if not (0 < new_value < 9):\n raise AttributeError(\"The value is not between 0 and 9.\")\n\n return OneDigitNumericValue(new_value)\n\n\n def __repr__(self):\n return str(self.value)\n\nclass Person:\n moods = {\n \"happy\": OneDigitNumericValue(),\n \"angry\": OneDigitNumericValue(),\n \"sad\": OneDigitNumericValue()\n }\n\n def update_states(self, state_updates: {}):\n for mood, val_change in state_updates.items():\n self.moods[mood] += val_change\n\np = Person()\np.update_states({\"happy\": 1, \"angry\": 1})\nprint(p.moods)\np.update_states({\"happy\": 10, \"angry\": 1}) # error\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:51:48.980",
"Id": "462578",
"Score": "0",
"body": "Great idea, but **I don't think this a good approach**. Now, whenever you add an integer to `self.moods[mood]`, like +2, you are basically doing `self.moods[mood]+=2`. In other words, you get an unwanted (invisible) sideeffect that whenever you add an integer to `self.moods[mood]`, `self.moods[mood]` is also (invisibly) reassigned to that value. Meaning, your sixth last line `self.moods[mood] += val_change` can be rewritten as `self.moods[mood] + val_change`. This unwanted sideeffect might have consequences down the road; especially if coworkers unknowingly adds a value to `self.moods`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:54:00.977",
"Id": "462580",
"Score": "0",
"body": "If that is the case, instead of mutating `self.value` and returning `self` from the `__add__` method you can create a new object and return it: `return OneDigitNumericValue(new_value)`. I edited the solution, to reflect this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:06:07.403",
"Id": "462584",
"Score": "0",
"body": "Actually, instead of reassigning a value to `self.value` in `__add__` , you can just return the new_value like showed here: https://pastebin.com/PYEsiCYu. If you run the code in the pastebin, you'll see it has the desired result without the unwanted sideeffect mentioned in my first comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:10:39.677",
"Id": "462585",
"Score": "0",
"body": "Check my edited solution, I return a new object without modifying the original object. Also returning just the new_value variable, would mean that you would have integers as values in your moods dictionary, not OneDigitNumericValue objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T23:57:28.030",
"Id": "462678",
"Score": "0",
"body": "Mutating classvar's just won't end well with instances. Try making an second `Person` and you'll see that they have the exact same values _all the time_."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T08:43:47.723",
"Id": "236140",
"ParentId": "236129",
"Score": "1"
}
},
{
"body": "<h1>Your solution just doesn't work</h1>\n\n<ol>\n<li>Your validation check always fails. Yes <code>int(value) != int</code> is always true. I don't think an instance of a class will ever be the class that it's an instance of.</li>\n<li><p>Your mutating a class variable. The tool you're utilizing forces you to take instances, normally there's a pretty good reason.</p>\n\n<p>If we remove the previous error and run your code we can easily see, there's no point in having more than one instance of a <code>Player</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> a = Person()\n>>> b = Person()\n>>> a.moods['happy'].__set__(a, 8)\n>>> b.moods['happy'].__get__(b, None)\n8 # Ok, that's not right...\n</code></pre></li>\n</ol>\n\n<p>I don't believe you've actually tried to code you've provided. And honestly what's the point in a single-data non-singleton class? The provided code is just untested garbage.</p>\n\n<h1>You're using it wrong</h1>\n\n<p>If it's not evident enough that you're fighting a tool that is pure sugar. Then you're not doing it right. The instance has to keep the state of the instance, and the descriptor has to interact with a varying amount of instances to interact with <em>their</em> state correctly.</p>\n\n<p>If anything of the instance's leaks out into the descriptor, or vice versa. Then you're going to have a bad, bad time.</p>\n\n<p>Since descriptors are to be tied onto classes I'm making a <code>Mood</code> class. Since the descriptor needs to have a place to store data. We can define that in the <code>__init__</code> of <code>Mood</code>. To note, because you may not notice this by yourself. <code>self._values</code> can be mutated to bypass the validator. Using <code>self._values[mood] = value</code> is not how you update values, use <code>setattr(self, mood, value)</code>.</p>\n\n<p>In addition to fixing <code>OneDigitNumericValue</code>, you should make it take an argument that is the validator for the function. If you need another validator it'd be better and simpler to make a simple hard to mess-up function. Rather than making lots of potentially broken descriptors.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def single_digit(value):\n if 0 <= value <= 9:\n return\n raise ValueError(\"The value is invalid\")\n\n\nclass Validator:\n def __init__(self, validator):\n self.validator = validator\n self.name = None\n\n def __set_name__(self, owner, name):\n self.name = name\n\n def __get__(self, instance, owner) -> object:\n return instance._values[self.name]\n\n def __set__(self, instance, value) -> None:\n self.validator(value)\n instance._values[self.name] = value\n\n\nclass Mood:\n happy = Validator(single_digit)\n angry = Validator(single_digit)\n sad = Validator(single_digit)\n\n def __init__(self):\n self._values = {}\n self.happy = 5\n self.angry = 5\n self.sad = 5\n\n def update_states(self, states):\n for mood, value in states.items():\n setattr(self, mood, value + getattr(self, mood))\n</code></pre>\n\n<p>And it actually works:</p>\n\n<pre><code>>>> a = Mood()\n>>> b = Mood()\n>>> a.happy = 3\n>>> a.happy\n3\n>>> b.happy\n5\n>>> a.update_states({'happy': 3})\n>>> a.happy\n6\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T23:56:01.953",
"Id": "236177",
"ParentId": "236129",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T22:18:08.460",
"Id": "236129",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"design-patterns",
"properties"
],
"Title": "Descriptor to restrict input"
}
|
236129
|
<p>I was wondering what is the better way of writing? Having several variables to show the steps or rather do method chaining?</p>
<pre><code>function count(string) {
const array = string.split("");
return array.filter(element => element === "a").length
}
function count(string) {
return string
.split("")
.filter(element => element === "a")
.length
}
</code></pre>
<p>Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T15:47:13.187",
"Id": "462617",
"Score": "1",
"body": "To prevent your question from being closed, please read and follow https://codereview.stackexchange.com/help/how-to-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T07:23:42.050",
"Id": "462690",
"Score": "0",
"body": "Method chaining Is really painful to debug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T08:57:02.130",
"Id": "462697",
"Score": "0",
"body": "That's a terrible function name, `count`. What is it counting? Entries? Strings? Characters? From 1 to 10?"
}
] |
[
{
"body": "<p>Not everyone will agree, but I think the second option would most often be considered more readable and is probably the best option to use.</p>\n\n<p>But it's worth noting that some devs might prefer the first option because they find it easier to <code>console.log</code> when something goes wrong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:34:14.747",
"Id": "236148",
"ParentId": "236130",
"Score": "2"
}
},
{
"body": "<p>In this case I would clearly go with the more concise version 2.</p>\n\n<p>In general it can improve readability to assign complex expressions to variables with meaningful names and I would always prefer this to adding a comment. However, in this case there is neither the necessity to add a comment nor is the variable name <code>array</code> very meaningful. Just the opposite: You have to decode the second line by looking up <code>array</code> one line above if you want to understand what's going on.</p>\n\n<p>Personally I would shorten the code some more:</p>\n\n<pre><code>function count(string) {\n return string.split(\"\").filter(e => e === \"a\").length\n}\n</code></pre>\n\n<p>In my opinion, the name <code>element</code> doesn't add much information here, so you might as well write <code>e</code> or <code>x</code>. When variable scope is very short, these short names are fine. When you read this code, you will never wonder where the hell this variable <code>e</code> is coming from and what it means. It literally refers to something defined on the same line.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:34:25.770",
"Id": "236150",
"ParentId": "236130",
"Score": "4"
}
},
{
"body": "<p>I found the first one more readable and easy to understand. I know we shouldn’t declare a variable when we can return directly and I do the same usually but I think that return statement doing too many things in a single line.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T14:39:04.763",
"Id": "236157",
"ParentId": "236130",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T23:49:23.547",
"Id": "236130",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "What is good practise, more readable?"
}
|
236130
|
<p>I have a set of code that calculates how well a templates fits a users details. It's kind of long, so I've cut out all the code that does it's job well and only included the bottle neck and surrounding code. My target here is speed!</p>
<p>A couple of notes on the variables:</p>
<p><strong>Calculated at run time (changes each user):</strong></p>
<ul>
<li>TopSecHead - list of list of string - different sub list lengths</li>
<li>allSecScoreDicP1 - dict of list of float - always same length</li>
<li>allSecScoreDicP2 - dict of list of float - always same length</li>
<li>allSecReducerDicP1 - dict of list of float - always same length</li>
<li>allSecReducerDicP2 - dict of list of float - always same length</li>
</ul>
<p>The last 4 above are all the same dimentions as each other</p>
<p><strong>Calculated once and save/loaded (doesn't change per user):</strong></p>
<ul>
<li><p>docSecSizesFull - list of list of list of float - sub lists are not same length</p></li>
<li><p>shortSecSizesFull - list of list of list of float - sub lists are not same length</p></li>
<li><p>cutPointsFull - list of list of list of float - sub lists are not same length</p></li>
<li><p>tmplNumFull - list of list of list of float - sub lists are not same length</p></li>
<li><p>AllDocSplitsFull - list of list of list of float - sub lists are not same length</p></li>
</ul>
<p>All five above are same dimentions as each other.</p>
<pre><code>for x in range(4,8,1):
docSecSizes = docSecSizesFull[x-4]
shortSecSizes = shortSecSizesFull[x-4]
cutPoints = cutPointsFull[x-4]
tmpltNum = tmplNumFull[x-4]
layoutNums = 0
numTemps = len(docSecSizes)
tmpsplits = []
tmpsplits = [AllDocSplitsFull[x-4][z] for z in range(numTemps)]
alltmplIds = [tmplNumFull[x-4][z] for z in range(numTemps)]
for y in list(itertools.permutations(TopSecHead[x-4][1:])):
tmpHeadSec = []
tmpHeadSec.append('BasicInfo')
headingIDs = []
headingIDs.append(str(0))
for z in y:
tmpHeadSec.append(z)
headingIDs.append(str(headingLookups.index(z)))
SectionIDs = ','.join(headingIDs)
tmpvals = []
tmpArray = []
for key in allSecScoreDicP1:
tmpArray.append(allSecScoreDicP1[key])
nparr = np.array(tmpArray)
print(nparr.transpose())
for z in range(numTemps):
docScore = 0
docScoreReducer = 1
for q in range(len(shortSecSizes[z])):
if q < cutPoints[z]:
indexVal = shortSecSizes[z][q]
docScore+= allSecScoreDicP1[tmpHeadSec[q]][indexVal]
docScoreReducer *= allSecReducerDicP1[tmpHeadSec[q]][indexVal]
else:
indexVal = shortSecSizes[z][q]
docScore+= allSecScoreDicP2[tmpHeadSec[q]][indexVal]
docScoreReducer *= allSecReducerDicP2[tmpHeadSec[q]][indexVal]
docScore = docScore * docScoreReducer
tmpvals.append(docScore)
numTemplate = len(tmpvals)
totaldocs += numTemplate
sectionNum = [x] * numTemplate
layoutNumIterable = [layoutNums] * numTemplate
SectionIDsIterable = [SectionIDs] * numTemplate
scoredTemplates.append(pd.DataFrame(list(zip(sectionNum,alltmplIds,layoutNumIterable,tmpvals,SectionIDsIterable,tmpsplits)),columns = ['#Sections','TemplateID','LayoutID','Score','SectionIDs','Splits']))
layoutNums +=1
allScoredTemplates = pd.concat(scoredTemplates,ignore_index=True)
</code></pre>
<p>The problem code is this bit:</p>
<pre><code>for z in range(numTemps):
docScore = 0
docScoreReducer = 1
for q in range(len(shortSecSizes[z])):
if q < cutPoints[z]:
indexVal = shortSecSizes[z][q]
docScore+= allSecScoreDicP1[tmpHeadSec[q]][indexVal]
docScoreReducer *= allSecReducerDicP1[tmpHeadSec[q]][indexVal]
else:
indexVal = shortSecSizes[z][q]
docScore+= allSecScoreDicP2[tmpHeadSec[q]][indexVal]
docScoreReducer *= allSecReducerDicP2[tmpHeadSec[q]][indexVal]
docScore = docScore * docScoreReducer
tmpvals.append(docScore)
</code></pre>
<p>I've tried changing it to list comprehension but it was slower:</p>
<pre><code> docScore = [sum([allSecScoreDicP1[tmpHeadSec[q]][shortSecSizes[z][q]] if q < cutPoints[z] else allSecScoreDicP2[tmpHeadSec[q]][shortSecSizes[z][q]] for q in range(len(shortSecSizes[z]))]) for z in range(numTemps)]
docReducer = [np.prod([allSecReducerDicP1[tmpHeadSec[q]][shortSecSizes[z][q]] if q < cutPoints[z] else allSecReducerDicP2[tmpHeadSec[q]][shortSecSizes[z][q]] for q in range(len(shortSecSizes[z]))]) for z in range(numTemps)]
tmpvals = [docScore[x] * docReducer[x] for x in range(len(docScore))]
</code></pre>
<p>Any suggestions on optimisation methods would be massively appreciated. I have also attempted to convert the code to cython, I got it coverted and working, but it was about 10 times slower! </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T08:31:09.470",
"Id": "462576",
"Score": "0",
"body": "Welcome to CodeReview@SE. With performance concerns, it would be useful to include size of input and output as well as as many measurements as you see fit. A test input generator would help others gauge modifications. `I've cut out all the code that does it's job well and only included the bottle neck and surrounding code` fine if it did work out well, the ideal being *real code from real projects*. Can you provide a hyperlink to the full code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T18:28:56.893",
"Id": "462640",
"Score": "0",
"body": "@greybeard thanks for the input. I could provide the rest of the code, *but* the majority of the data is pulled from a mysql server so I can't really share that online (can I?). This is why I haven't shared the data, it's too big to be easily shareable and I can't create a simple function to replicate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T08:21:08.847",
"Id": "462692",
"Score": "1",
"body": "If you have improved code, please post a **new** question with that code. Again, don't vandalize the current post. Putting in links in both this and the new question pointing towards each other is fine. We have [a FAQ on how to handle iterative reviews indicating not to invalidate answers](https://codereview.meta.stackexchange.com/a/1765/52915)."
}
] |
[
{
"body": "<p>Probably the most important thing is to reduce the amount of nested loops. It looks like it's currently n^4, so for every 1,000 items it'll loop around 1,000,000,000,000 times. I solved a similar problem once by having an initial loop which mapped the data structure into a less deeply nested form, and then I didn't need to do as many nested loops.</p>\n\n<p>Also, as a side note, it would be good to name your variables rather than just using letters of the alphabet. Even just small changes like replacing <code>x</code> with <code>num</code> or <code>number</code> would improve the readability quite a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:23:53.567",
"Id": "236146",
"ParentId": "236133",
"Score": "3"
}
},
{
"body": "<p>If \"My target here is speed!\" (and assuming you mean speed of execution) then the best advice is to move it into a compiled language. There are many, many benefits to Python but execution speed is seldom one of them.</p>\n\n<p>The first step, as Andre O suggested, is to get a good algorithm. Python can be very helpful with that. The standard <code>profile</code> module can help you find where the code is spending its time and you can focus your optimization on that part of the code.</p>\n\n<p>As an intermediate step to a fully compiled language you can take a Python program and move it to Cython which compiles the Python to machine language.</p>\n\n<p>If your profiling finds certain portions are the most heavily used and slowest then you can code just that portion in C and call it from Python.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T07:55:31.463",
"Id": "236182",
"ParentId": "236133",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T01:16:44.530",
"Id": "236133",
"Score": "0",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Optimising code to calculate scores for a set of templates Python"
}
|
236133
|
<p>So I was coding Inversionless ECM using <em>Prime Numbers: A computational perspective</em> and when I finished and tried running my program it ran way, way slower than it is supposed to. I have no idea what I am doing wrong. The algorithm I'm coding is <a href="http://thales.doa.fmph.uniba.sk/macaj/skola/teoriapoli/primes.pdf" rel="nofollow noreferrer">here</a> and is algorithm 7.4.4(Ctrl-f it)</p>
<blockquote>
<ol>
<li>[Choose criteria]<br>
<em>B₁</em> = 10000; // Stage-one limit (must be even).<br>
<em>B₂</em> = 100 <em>B₁</em>; // Stage-two limit (must be even).<br>
<em>D</em> = 100; // Total memory is about 3 <em>D</em> size-<em>n</em> integers.</li>
<li>[Choose random curve <em>Eσ</em>]<br>
Choose random <em>σ</em>∈[6, <em>n</em>−1]; // Via Theorem 7.4.3.<br>
<em>u</em> = (σ²−5) mod <em>n</em>;<br>
<em>v</em> = 4σ mod <em>n</em>;<br>
<em>C</em> = ((v−u)³(3 <em>u</em>+<em>v</em>)/(4 <em>u</em>³<em>v</em>)−2) mod <em>n</em>;<br>
// Note: <em>C</em> determines curve <em>y²=x³+Cx²+x</em>,<br>
// yet, <em>C</em> can be kept in the form num/den.<br>
<em>Q</em> = [u³mod <em>n</em> : <em>v</em>³mod <em>n</em>]; // Initial point is represented [<em>X</em> : <em>Z</em>]. </li>
<li>[Perform stage one]<br>
for(1≤<em>i</em>≤<em>π</em>(<em>B₁</em>)) { // Loop over primes <em>p</em>i.<br>
Find largest integer <em>a</em> such that <em>pai</em>≤<em>B₁</em>;<br>
<em>Q</em> = [pai]<em>Q</em>; // Via Algorithm 7.2.7, and perhaps use FFT enhancements (see text following).<br>
}<br>
<em>g</em> = gcd(<em>Z</em>(<em>Q</em>), <em>n</em>); // Point has form <em>Q</em> = [<em>X</em>(<em>Q</em>) : <em>Z</em>(<em>Q</em>)].<br>
if(1<<em>g</em><<em>n</em>) return <em>g</em>; // Return a nontrivial factor of <em>n</em>. </li>
<li>[Enter stage two] // Inversion-free stage two.<br>
<em>S₁</em> = <em>doubleh</em>(<em>Q</em>);<br>
<em>S₂</em> = <em>doubleh</em>(<em>S₁</em>);<br>
for(<em>d</em>∈[1,<em>D</em>]) { // This loop computes <em>Sd</em>=[2 <em>d</em>]<em>Q</em>.<br>
if(<em>d</em>>2) <em>Sd</em> = <em>addh</em>(<em>Sd</em>−1,<em>S₁</em>,<em>Sd</em>−2);<br>
<em>βd</em> = <em>X</em>(<em>Sd</em>)<em>Z</em>(<em>Sd</em>)mod <em>n</em>; // Store the <em>XZ</em> products also.<br>
}<br>
<em>g</em> = 1;<br>
<em>B</em> = <em>B₁</em>−1; // <em>B</em> is odd.<br>
<em>T</em> = [<em>B</em>−2 <em>D</em>]<em>Q</em>; // Via Algorithm 7.2.7.<br>
<em>R</em> = [<em>B</em>]<em>Q</em>; // Via Algorithm 7.2.7.<br>
for(<em>r</em>=<em>B</em>; <em>r</em><<em>B₂</em>; <em>r=r</em>+2 <em>D</em>) {<br>
<em>α</em> = <em>X</em>(<em>R</em>)<em>Z</em>(<em>R</em>)mod <em>n</em>;<br>
for(prime <em>q</em>∈[<em>r</em>+2, <em>r</em>+2 <em>D</em>]) { //Loop over primes.<br>
<em>δ</em> = (<em>q−r</em>)/2; // Distance to next prime.<br>
// Note the next step admits of transform enhancement.<br>
<em>g = g</em>((<em>X</em>(<em>R</em>)−<em>X</em>(<em>Sδ</em>))(<em>Z</em>(<em>R</em>)+<em>Z</em>(<em>Sδ</em>))−<em>α</em>+<em>βδ</em>)mod <em>n</em>;<br>
}<br>
(<em>R</em>, <em>T</em>) = (<em>addh</em>(<em>R</em>, <em>SD</em>, <em>T</em>), <em>R</em>);<br>
}<br>
<em>g</em> = gcd(<em>g</em>, <em>n</em>);<br>
if(1<<em>g</em><<em>n</em>) return <em>g</em>; // Return a nontrivial factor of <em>n</em>. </li>
<li>[Failure]<br>
goto [Choose random curve...]; // Or increase B₁, B₂limits, etc.</li>
</ol>
</blockquote>
<p>Here is my code: </p>
<pre class="lang-py prettyprint-override"><code>from random import randrange
from primesieve import primes
from math import floor, log
def gcd(a, b):
if a == b: return a
while b > 0:
a, b = b, a % b
return a
def addh(xp, zp, xq, zq, x0, z0, n):
t = (xp - zp) * (xq + zq)
v = (xp + zp) * (xq - zq)
addx, addz = (t + v), (t - v)
addx, addz = addx * addx, addz * addz
addx, addz = addx * z0, addz * x0
if addx >= n:
addx = addx % n
if addz >= n:
addz = addz % n
return (addx, addz)
def doubleh(xp, zp, a24, n):
t, v = (xp + zp), (xp - zp)
t, v = t * t, v * v
u = t - v
addx = t * v
addz = u * (v + a24 * u)
if addx >= n:
addx = addx % n
if addz >= n:
addz = addz % n
return (addx, addz)
def montladder(n, X, Z, a24, r):
if n == 1:
return (X, Z)
if n == 2:
return doubleh(X, Z, a24, r)
U, V = X, Z
T, W = doubleh(X, Z, a24, r)
bk = bin(n)
for nj in bk[2:]:
if nj == 1:
U, V = addh(T, W, U, V, X, Z, r)
T, W = doubleh(T, W, a24, r)
else:
T, W = addh(U, V, T, W, X, Z, r)
U, V = doubleh(U, V, a24, r)
if bk[-1] == 1:
return addh(U, V, T, W, X, Z, r)
return doubleh(U, V, a24, r)
def fastECM(n, B1 = 10000, B2 = 100, D = 100):
# Criteria
B2 = B1 * B2
S = [0] * (D * 2 + 1)
be = [0] * (D+1)
# Choose random Curve Eo
g = 1
while g == n or g == 1:
o = randrange(6, n-1)
u = (o**2 - 5) % n
v = 4 * o % n
t1 = (v - u)**3
t2 = (3 * u + v)
t3 = 4 * (u**3) * v
C = ((t1 * t2 / t3) - 2) % n
a24 = (C+2) / 4
Q = (pow(u, 3, n), pow(v, 3, n))
# Perform Stage one
for pi in primes(B1):
a = int(log(B1, pi))
Q = montladder(pi**a, Q[0], Q[1], a24, n)
g = gcd(Q[1], n)
if g > 1 and g < n: return g
# Perform Stage two
S[1] = doubleh(Q[0], Q[1], a24, n)
S[2] = doubleh(S[1][0], S[1][1], a24, n)
be[1] = S[1][0] * S[1][1] % n
be[2] = S[2][0] * S[2][1] % n
for d in range(3, D+1):
S[d] = addh(S[d-1][0], S[d-1][1], S[1][0],S[1][1], S[d-2][0], S[d-2][1], n)
be[d] = (S[d][0] * S[d][1]) % n
g = 1
B = B1 - 1
T = montladder(B - 2 * D, Q[0], Q[1], a24, n)
R = montladder(B, Q[0], Q[1], a24, n)
r = B
for r in range(B1, B2, 2 * D):
alph = R[0] * R[1] % n
for q in primes(r + 2, r + 2 * D):
spec = (q - r) // 2
t1 = (R[0] - S[spec][0])
t2 = R[1] + S[spec][1]
g = (g * (t1 * t2 - alph + be[spec])) % n
R, T = addh(R[0], R[1], S[D][0], S[D][1], R[0], R[1], n), R
g = gcd(g, n)
return g
</code></pre>
<p>Basically this is taking minutes for 6 digit numbers and anything above my terminal just crashes. I'm not sure if this is the right place to ask this so if it isn't please tell me where I can.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T05:25:46.700",
"Id": "462569",
"Score": "1",
"body": "Please add some example code to your question that calls the interesting code. You should also describe \"it crashes\" more specifically, otherwise you can only expect \"then your code must be wrong\" as a comment, and that would make your question off-topic on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T05:26:50.330",
"Id": "462570",
"Score": "1",
"body": "Basically you have to convince us that \"the code works as intended according to the best of the author's knowledge\"."
}
] |
[
{
"body": "<p>Just some general thoughts since I am not familiar with the ECM algorithm you are using:</p>\n\n<p>The standard implementation of Python is interpreted. The Python executive is switched to for every line of your source. Thus idiomatic Python will use Numpy or other libraries to express the algorithm as calls to matrix routines or as operations on complex values or quaternions. Thus the interpreter is called less often and code spends more of its time running in compiled routines. In contrast your code looks more like Fortran.</p>\n\n<p>Other options are using Cython, which compiles Python to machine code, and writing compiled functions for routines that are called often inside loops.</p>\n\n<p>The standard module <code>profile</code> can tell you how often a line is executed and identify where your code is spending its time.</p>\n\n<p>You don't say which version of Python you are running with, but if you are using a 32 bit version of Python 2 you can get an immediate increase in speed and stability by upgrading to Python 3.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T06:00:24.513",
"Id": "236180",
"ParentId": "236136",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T04:18:21.487",
"Id": "236136",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"cryptography"
],
"Title": "Inversionless Lenstra ECM running way slower than it should"
}
|
236136
|
<p>Here is the code to a progress bar component. Is there anything that you feel I should improve to it?</p>
<p>If I state that the progress prop is required, is it ok NOT to check in the code that progress is not null?</p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
export default function ProgressBar({ progress, progressBarColor }) {
const percentage = progress > 1 ? 100 : progress * 100;
const commonStyles = 'rounded-50 h-13 lg:h-9 lgx:h-12 xl:h-13';
return (
<div className={`bg-grey-light relative overflow-hidden ${commonStyles}`}>
<div className={`${progressBarColor} ${commonStyles}`} style={{ width:`${percentage}%` }}>
&nbsp;
</div>
</div>
);
}
ProgressBar.propTypes = {
progress: PropTypes.number.isRequired,
progressBarColor: PropTypes.string
};
ProgressBar.defaultProps = {
progressBarColor: 'bg-gradient-b-turquoise-cyan'
};
</code></pre>
<p>I would use this progress bar to display the usage of some resource for example. Once that usage reaches a certain percentage, I would need to change the bar's color to orange for example and make it read if you have reached the limit/the maximum usage of the resource.</p>
<pre><code>render() {
let progressBarColor = 'bg-gradient-b-turquoise-cyan';
if (progress >= 1) {
progressBarColor = 'bg-red';
} else if (progress >= 0.8) {
progressBarColor = 'bg-orange';
}
return (
<div>
<ProgressBar
progress={progress}
progressBarColor={progressBarColor}
/>
</div>
);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:55:25.217",
"Id": "462582",
"Score": "0",
"body": "Don't hesitate to comment on why you are downgrading the question? I am looking forward to discussing about code with the community :) Maybe explain how would you ask the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T15:57:52.223",
"Id": "462618",
"Score": "1",
"body": "I can only guess at the downvoter's motivation by looking at the close votes. They say \"the description lacks context\". Maybe they wanted to see some code that actually uses this progress bar, and a little description of where you intend to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T20:19:43.527",
"Id": "462658",
"Score": "0",
"body": "I have now added the code that uses the progress bar and the little description explaining the usage."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T07:30:07.937",
"Id": "236139",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "Progress Bar React Component"
}
|
236139
|
<p><strong>Main Goal</strong></p>
<p>My goal is to create a chat app for my company (they are all software developers). I first make a console version and if it is working fine, I will make a GUI version. The program will run on an exchange drive, so using networking features is not neccessary.</p>
<p><strong>Project description</strong></p>
<p>The software will consist of three programs. One is for managing the users: create a new one, delete a user, and so on. The second program is for displaying messages. The third program is for write messages. Later when I make a GUI version, all programs get united to one.</p>
<p><strong>Current status</strong></p>
<p>I have finished the user management program. If you want to test it on your local machine, you have to create a ".save" folder in the same directory your class files are. Otherwise the program crashes.</p>
<p><strong>My Question</strong></p>
<p>Is the code acceptable in matters of readability and code quality?
Is there something to improve in matters of english grammar and writing?</p>
<p>(I dont want to implement high security features, because in my company we trust each other. Maybe I will write an Obfuscator class, that obfuscate the strings before they get stored on the disk, or something like that. But if you also have some hints in matters of security for me that are not to hard to implement, you can let me know.)</p>
<p><strong>User.java</strong></p>
<pre><code>import java.io.Serializable;
public class User implements Serializable {
private String name;
private String password;
public User(String name, String password) {
setName(name);
setPassword(password);
}
public String getName() {
return new String(name);
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
public boolean checkPassword(String password) {
return this.password.equals(password);
}
}
</code></pre>
<p><strong>UserManager.java</strong></p>
<pre><code>import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class UserManager implements Serializable {
private static final File SAVE_FILE = new File(".save/users");
private List<User> users;
public UserManager() {
if (SAVE_FILE.exists()) {
loadUsers();
} else {
users = new ArrayList<>();
saveUsers();
}
}
private void saveUsers() {
try (FileOutputStream fos = new FileOutputStream(SAVE_FILE);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(users);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void loadUsers() {
try (FileInputStream fis = new FileInputStream(SAVE_FILE);
ObjectInputStream ois = new ObjectInputStream(fis)) {
users = (ArrayList<User>) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public User retainUser(String name, String password) {
for (User user : users) {
if (user.getName().equals(name) && user.checkPassword(password)) {
return user;
}
}
return null;
}
// returns a success message or an error message
public String createUser(String name, String password) {
if (name.isEmpty()) {
return "Name can't be empty.";
}
if (password.isEmpty()) {
return "Password can't be empty";
}
// check if name already exits
for (User user : users) {
if (user.getName().equals(name)) {
return "A user with that name already exists.";
}
}
User user = new User(name, password);
users.add(user);
saveUsers();
return "The new user was created successfully.";
}
public List<String> retainUserNames() {
List<String> userNames = new ArrayList<>();
for (User user : users) {
userNames.add(user.getName());
}
return userNames;
}
// returns true if delete request was successful
public boolean deleteUser(String name, String password) {
for (User user : users) {
if (user.getName().equals(name) && user.checkPassword(password)) {
users.remove(user);
saveUsers();
return true;
}
}
return false;
}
}
</code></pre>
<p><strong>UserManagementProgram.java</strong></p>
<pre><code>import java.util.List;
import java.util.Scanner;
public class UserManagementProgram {
public static void main(String[] args) {
UserManagementProgram ump = new UserManagementProgram();
ump.mainLoop();
}
private Scanner scanner;
private UserManager userManager;
public UserManagementProgram() {
scanner = new Scanner(System.in);
userManager = new UserManager();
}
public void mainLoop() {
while (true) {
System.out.println("[1] Show all users");
System.out.println("[2] Create user");
System.out.println("[3] Delete user");
System.out.println("[4] Close");
System.out.print("Input: ");
String input = scanner.nextLine();
System.out.println();
switch (input) {
case "1":
printUsers();
break;
case "2":
createUser();
break;
case "3":
deleteUser();
break;
case "4":
return;
}
System.out.println();
}
}
private void printUsers() {
List<String> userNames = userManager.retainUserNames();
for (String name : userNames) {
System.out.println(name);
}
}
private void createUser() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
System.out.println(userManager.createUser(name, password));
}
private void deleteUser() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
if (userManager.deleteUser(name, password)) {
System.out.println("Success.");
} else {
System.out.println("Either name or password are incorrect.");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:04:13.740",
"Id": "462620",
"Score": "0",
"body": "Why do you want to create this app after all? There are several existing apps already. You could add that information to the first paragraph of your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:30:39.323",
"Id": "462622",
"Score": "0",
"body": "For the same reason some companies build cars even if other companies produce also cars already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T10:51:53.283",
"Id": "462700",
"Score": "0",
"body": "Even car companies won't reinvent every part of a car; they often buy some parts from other manufacturers. Similarly, even if you don't want to use an existing app, you could still use a framework which can handle creating/deleting a user for you. And then just make the other parts yourself. Not saying that you definitely should do this, just that in most cases it would be a good option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T05:42:03.490",
"Id": "462766",
"Score": "0",
"body": "Readability usability: your code lacks Javadoc comments. Six months from now you won't remember this stuff, and no one besides you knows what it does. Document it while you still have the design fresh in your mind."
}
] |
[
{
"body": "<p>I get that security isn't critical in this case, but it's probably still good to store the passwords in a hash. Some people may be using the same password for other websites and you don't want to compromise their security on those sites. There should be libraries to handle hashing passwords and it would be much better (and simpler) to use them than to try and create your own cryptography algorithm.</p>\n\n<p>I'm also not sure if calling a <code>User</code> method in a <code>User</code> class is the best approach, both for naming or as a way to initalise variables. But I don't usually program in Java so I'm not sure. Maybe someone else can give some advice on that. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T05:04:12.160",
"Id": "462765",
"Score": "1",
"body": "On the subject of hashing passwords in Java: https://www.baeldung.com/java-password-hashing"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:09:32.240",
"Id": "236145",
"ParentId": "236141",
"Score": "2"
}
},
{
"body": "<p>In your current implementation you are caching the users in <code>users</code> field in <code>UserManager</code>, but this has a chance of data loss if there are multiple instances of the application is run and new user are created there.</p>\n\n<p>Password should always be hashed. Though I understand it is an internal app, this is a good practice to ensure anyone's password is not accidentally exposed.</p>\n\n<p><code>getUserNames</code> is a more appropiate/simpler name instead of <code>retainUserNames</code>.</p>\n\n<p>In <code>UserManager.createUser</code> method, instead of returing exact error message return an enum or error code and then render the error message based on that in your CLI app. This makes handling/updating error messages or providing multilingual support easier later.</p>\n\n<p>Though not a high priority for a simple program such as this, I would recommend using a cli library for parsing command line arguments.</p>\n\n<p>There seems to be no way to update a user's password.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T04:48:54.497",
"Id": "236214",
"ParentId": "236141",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236214",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T08:58:51.577",
"Id": "236141",
"Score": "2",
"Tags": [
"java",
"serialization",
"chat"
],
"Title": "User Management Program"
}
|
236141
|
<p>Here is a function that formats a phone number and adds a country code prefix if it is not included in it.</p>
<p>So, as an in input value it could be, for example, '23581010' or '4923581010' and in output it would become via the formatNumber function '(02) 358 10 10'.</p>
<p>Is the positioning of the let assignment ok in this code ? If something else feels not ok can you tell me ?</p>
<pre><code>import { formatNumber } from 'libphonenumber-js';
export const formatGermanPhoneNumber = phoneNumber => {
if (!phoneNumber) {
return '';
}
const phoneNumberString = `${phoneNumber}`;
let prefix = '';
if (!phoneNumberString.startsWith('49')) {
prefix = '49';
}
return formatNumber(`+${prefix}${phoneNumberString}`, 'National');
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:54:34.783",
"Id": "462581",
"Score": "0",
"body": "Don't hesitate to comment on why you are downgrading the question? I am looking forward to discussing about code with the community :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:17:07.527",
"Id": "462587",
"Score": "1",
"body": "_@DDA_ This and your last question ask to review some (hypothetical?) stub code without giving any further context. You can check our [help] how to ask good questions. Also we cannot know what the agreed coding standards and guidelines are at your company. Your peer reviewer probably simply relies on these."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:18:54.340",
"Id": "462588",
"Score": "0",
"body": "Thank you. I have reformulated my question. I hope it is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:19:45.200",
"Id": "462589",
"Score": "0",
"body": "Well, it's still stub code presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:30:41.643",
"Id": "462590",
"Score": "1",
"body": "Sorry I don't know what 'stub code' means ? I have added the import line as well of the third party library being used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:35:18.007",
"Id": "462591",
"Score": "1",
"body": "Does [this](https://stackoverflow.com/questions/9777822/what-does-to-stub-mean-in-programming) help?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:00:51.860",
"Id": "462619",
"Score": "1",
"body": "This question is missing an exact description of which countries this code is intended to cover."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T20:05:37.390",
"Id": "462656",
"Score": "1",
"body": "Good point. I have renamed the function to \"formatGermanPhoneNumber()\" to be more specific."
}
] |
[
{
"body": "<p>I don't know of any coding standards or other reasons why you should have to move it higher. Generally it's just personal preference and whichever is more readable.</p>\n\n<p>As for the fact that you'd need to create a variable unnecessarily in some cases, creating a variable like this uses very little memory so it shouldn't be an issue unless the function is being looped over thousands of times. </p>\n\n<p>You could also consider another option, which is to use a ternary rather than mutating a variable:\n<code>let prefix = phoneNumberString.startsWith('49') ? '49' : ''</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:52:26.650",
"Id": "462579",
"Score": "1",
"body": "Thank you for your answer. My co-workers are a little allergic to the use of ternary. They think it makes the code less readable. I guess it is a question of preference there too :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T12:27:26.900",
"Id": "462596",
"Score": "3",
"body": "That `?:` is backwards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:47:09.447",
"Id": "236144",
"ParentId": "236142",
"Score": "3"
}
},
{
"body": "<p>While your coworkers may dislike <code>?:</code>, I would recommend putting the blank line before the declaration/initialization of prefix instead of after. This groups the setting of prefix together.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T20:07:02.867",
"Id": "462657",
"Score": "0",
"body": "Good point. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T12:24:21.373",
"Id": "236152",
"ParentId": "236142",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236144",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T09:32:16.457",
"Id": "236142",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Format a phone number function"
}
|
236142
|
<p>I'm using Flask along with Flask-SQLAlchemy and Flask-WTF.</p>
<p>I have a model:</p>
<pre class="lang-py prettyprint-override"><code>class Trip(db.Model):
id = db.Column(db.BigInteger, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True,
nullable=False)
name = db.Column(db.String(2000), nullable=False)
country_code = db.Column(db.String(2))
slug = db.Column(db.String(2000), nullable=False)
author = db.relationship('User',
backref=db.backref('trips',
order_by=lambda: Trip.name))
def __repr__(self):
return f"<Trip {self.id} author_id={self.author_id} slug={self.slug}>"
db.Index('idx_trip_author_slug', Trip.author_id, Trip.slug, unique=True)
</code></pre>
<p>To create and update trips, I use class-based views like this:</p>
<pre class="lang-py prettyprint-override"><code>class TripCUView(MethodView):
methods = ('GET', 'POST')
decorators = [user_required]
title = 'Trip action'
submit_text = 'Save'
def dispatch_request(self, *args, **kwargs):
self.model = self._instant_model()
return super().dispatch_request(*args, **kwargs)
def get(self):
self.form = self._build_form()
return self._default_render()
def post(self):
self.form = TripForm()
if self.form.validate():
try:
self.form.populate_obj(self.model)
db.session.add(self.model)
db.session.commit()
return redirect(url_for('.index'))
except IntegrityError as e:
db.session.rollback()
if (e.orig.pgcode == pgerrorcodes.UNIQUE_VIOLATION):
self.form.errors.setdefault('slug', [])
self.form.errors['slug'].append('Already exists')
return self._default_render()
else:
raise e
return self._default_render()
def _build_form(self):
raise NotImplementedError
def _instant_model(self) -> Trip:
raise NotImplementedError
def _default_render(self):
return render_template('form.html', form=self.form,
title=self.title,
submit_text=self.submit_text)
class CreateTripView(TripCUView):
title = 'Create trip'
def _build_form(self):
return TripForm()
def _instant_model(self):
return Trip(author=g.user)
class UpdateTripView(TripCUView):
@property
def title(self):
return f"Updating {self.model.name}"
def dispatch_request(self, slug):
self.slug = slug
return super().dispatch_request()
def _build_form(self):
return TripForm(obj=self.model)
def _instant_model(self):
return Trip.query\
.filter_by(slug=self.slug, author=g.user)\
.first_or_404()
trips.add_url_rule('/new', view_func=CreateTripView.as_view('new'))
trips.add_url_rule('/<slug>/update',
view_func=UpdateTripView.as_view('update'))
</code></pre>
<p>Basically, I override the <code>post</code> method on my <code>MethodView</code> subclass to check for integrity errors and translate them into form errors if they are indeed uniqueness violations.</p>
<p>Can it be done better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-31T04:14:42.510",
"Id": "463409",
"Score": "0",
"body": "I think Marshmallow could help you to validate any kind of input from the user using Model validation and normal input validation as well as output sanatization. [marshmallow](https://marshmallow.readthedocs.io/en/stable/)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T10:24:06.157",
"Id": "236147",
"Score": "3",
"Tags": [
"python",
"beginner",
"flask",
"sqlalchemy"
],
"Title": "Is this a good way to process SQLAlchemy's uniqueness constraint violation in Flask?"
}
|
236147
|
<p>I recently faced an interview question where you have to find minimum needed items from an array that can added together to generate <code>X</code> value.</p>
<p>For example giving:</p>
<p><code>[1, 9, 2, 5, 3, 10]</code> and the goal is: <code>13</code>, => it should be <code>[10, 3]</code></p>
<ul>
<li>You can't use any number out side of array.</li>
</ul>
<p>I have tried to sort items and take from the head one by one and some other stuff, but no lucks. Although, I have solved this by a not really performant solution and I will post it as an answer. I am looking for a more performant solution.</p>
<h1>Solution:</h1>
<p>First we have to find all subsets of the array:</p>
<pre><code>extension Array {
var allSubsets: [[Element]] {
guard count > 0 else { return [[]] }
let tail = Array(self[1..<endIndex])
let head = self[0]
let withoutHead = tail.allSubsets
let withHead = withoutHead.map { $0 + [head] }
return withHead + withoutHead
}
}
</code></pre>
<p>Then we can filter all subsets that their sum is equal to the goal like:</p>
<pre><code>subsets.filter { $0.reduce(0) { $0 + $1 } == goal }
</code></pre>
<p>And lastly, find the smallest subset by its count:</p>
<pre><code>func minimumElements(in array: [Int], goal: Int) -> [Int] {
let subsets = array.allSubsets
let validSubsets = subsets.filter { subset in
subset.reduce(0) { $0 + $1 } == goal
}
return validSubsets.reduce(array) { $0.count < $1.count ? $0 : $1 }
}
</code></pre>
<p><sub>This question was originally <a href="https://stackoverflow.com/q/59909672/5623035">asked</a> and <a href="https://stackoverflow.com/a/59909673/5623035">answered</a> in StackOverflow but moved here as suggestion.</sub></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T14:50:29.010",
"Id": "462605",
"Score": "0",
"body": "What is the intended result if there is *no* subset with the given sum?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T14:54:01.747",
"Id": "462607",
"Score": "0",
"body": "An empty array I think"
}
] |
[
{
"body": "<h3>Naming</h3>\n\n<p>Your function does not return “minimum elements,” but the shortest subset of an array with a given sum. I would suggest something like</p>\n\n<pre><code>func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]\n</code></pre>\n\n<h3>Handling exceptional cases</h3>\n\n<p>Your code returns the <em>entire</em> array if no subset with the given sum exists, which seems not sensible to me.</p>\n\n<p>In a comment you said that it should return an empty array in that case, but that would be ambiguous: an empty array is also the correct result for <code>goal = 0</code>.</p>\n\n<p>The Swift way would be to make the result an <em>optional</em> which is <code>nil</code> if no subset is found:</p>\n\n<pre><code>func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {\n let subsets = array.allSubsets\n\n let validSubsets = subsets.filter { subset in\n subset.reduce(0, +) == goal\n }\n\n if let firstValid = validSubsets.first {\n return validSubsets.dropFirst().reduce(firstValid) { $0.count < $1.count ? $0 : $1 }\n } else {\n return nil\n }\n}\n</code></pre>\n\n<p>Note also that the <code>+</code> operator can be passed directly to the closure parameter of <code>reduce()</code> which reduces(!) the code slightly.</p>\n\n<h3>Performance: avoid creation of intermediate arrays</h3>\n\n<p>The first performance problem is that a list with <em>all</em> subsets is generated first. For an array with <span class=\"math-container\">\\$ N \\$</span> elements that makes <span class=\"math-container\">\\$ 2^N \\$</span> subsets.</p>\n\n<p>A better approach would be to determine the shortest subset while enumerating the subsets, instead of putting all subsets into a list first. Here is a first attempt:</p>\n\n<pre><code>// Version A:\n\nfunc shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {\n // Terminating condition:\n guard let first = array.first else {\n return goal == 0 ? [] : nil\n }\n\n // Recursion:\n let tail = Array(array.dropFirst())\n let subsetWithout = shortestSubset(of: tail, withSum: goal)\n let subsetWith = shortestSubset(of: tail, withSum: goal - first)\n\n switch (subsetWithout, subsetWith) {\n case (let s1?, let s2?): return s1.count < s2.count + 1 ? s1 : [first] + s2\n case (let s1?, nil): return s1\n case (nil, let s2?): return [first] + s2\n case (nil, nil): return nil\n }\n}\n</code></pre>\n\n<p>In the recursion step, the shortest subsets which can be obtained by including or omitting the first array element are determined recursively. The switch-statement is used to handle the case where none, one, or both of these intermediate results are <code>nil</code>.</p>\n\n<p>This turned to be a bit faster in my tests, but there are still many intermediate array created at</p>\n\n<pre><code>let tail = Array(array.dropFirst())\n</code></pre>\n\n<p>If we modify the method to take a <em>collection</em> of integers instead of an array then we can pass the slice <code>array.dropFirst()</code> directly to the recursive call. Slices are “cheap” to create and share the storage with their origin (unless mutated):</p>\n\n<pre><code>// Version B:\n\nfunc shortestSubset<C: Collection>(of array: C, withSum goal: Int) -> [Int]? where C.Element == Int {\n // Terminating condition:\n guard let first = array.first else {\n return goal == 0 ? [] : nil\n }\n\n // Recursion:\n let subsetWithout = shortestSubset(of: array.dropFirst(), withSum: goal)\n let subsetWith = shortestSubset(of: array.dropFirst(), withSum: goal - first)\n switch (subsetWithout, subsetWith) {\n case (let s1?, let s2?):\n return s1.count < s2.count + 1 ? s1 : [first] + s2\n case (let s1?, nil):\n return s1\n case (nil, let s2?):\n return [first] + s2\n case (nil, nil):\n return nil\n }\n}\n</code></pre>\n\n<p>This turned out to be considerably faster in my test.</p>\n\n<h3>Performance: prune the search tree</h3>\n\n<p>A possible performance improvement is to stop the recursion if the goal cannot be reached with the remaining array elements, i.e. if the target sum is smaller than the smallest possible sum or larger than the largets possible sum of the array.</p>\n\n<p>Here it is useful to do the recursion in a helper function. The main function computes the smallest and largest sum once and passes it on to the helper function. The helper function can update those limits, without the need of computing them again.</p>\n\n<p>The helper function takes an array <em>slice</em> as argument, that is another way to void the creation of intermediate arrays.</p>\n\n<pre><code>// Version C:\n\nfunc shortestSubsetHelper(of array: ArraySlice<Int>, withSum goal: Int,\n min: Int, max: Int) -> [Int]? {\n guard let first = array.first else {\n return goal == 0 ? [] : nil\n }\n if goal < min || goal > max {\n return nil\n }\n let subsetWithout = shortestSubsetHelper(of: array.dropFirst(), withSum: goal,\n min: min, max: max)\n let subsetWith = first < 0 ?\n shortestSubsetHelper(of: array.dropFirst(), withSum: goal - first,\n min: min - first, max: max) :\n shortestSubsetHelper(of: array.dropFirst(), withSum: goal - first,\n min: min, max: max - first)\n switch (subsetWithout, subsetWith) {\n case (let s1?, let s2?):\n return s1.count < s2.count + 1 ? s1 : [first] + s2\n case (let s1?, nil):\n return s1\n case (nil, let s2?):\n return [first] + s2\n case (nil, nil):\n return nil\n }\n}\n\nfunc shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {\n\n let smallestSum = array.filter { $0 < 0 }.reduce(0, +)\n let largestSum = array.filter { $0 > 0 }.reduce(0, +)\n return shortestSubsetHelper(of: array[...], withSum: goal,\n min: smallestSum, max: largestSum)\n}\n</code></pre>\n\n<h3>Dynamic programming</h3>\n\n<p>What we have here is a variant of the <a href=\"https://en.wikipedia.org/wiki/Subset_sum_problem\" rel=\"nofollow noreferrer\">“subset sum problem”</a>, which has well-known solutions using dynamic programming. Instead of determining only if a subset with the given sum exists we also need the smallest subset with that sum.</p>\n\n<p>The following is motivated by the “Pseudo-polynomial time dynamic programming solution” from the above Wikipedia article. We maintain a dictionary which for every achievable sum stores the shortest subset with that sum that has been found so far. The given array is traversed once, and the dictionary updated accordingly for each array element.</p>\n\n<pre><code>// Version D:\n\nfunc shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {\n // Map each possible sum to the shortest subset found so far with that sum:\n var dp: [Int: [Int]] = [0: []]\n\n for elem in array {\n let upd = dp.map { (key, value) in (key + elem, value + [elem])}\n for (key, value) in upd {\n if let oldValue = dp[key] {\n if value.count < oldValue.count {\n dp[key] = value\n }\n } else {\n dp[key] = value\n }\n }\n }\n return dp[goal]\n}\n</code></pre>\n\n<p>This turned out to be faster for <em>large</em> arrays.</p>\n\n<h3>Benchmarks</h3>\n\n<p>The following (very simple) benchmark was done on a 3.5 GHz Quad-Core Intel Core i5 iMac running macOS 10.15, and </p>\n\n<pre><code>let array = [1, -2, 3, -4, 5, -6, 100, 100, 7, -8, 9, -10, 11, -12]\nlet goal = 20\n\nlet start = Date()\nlet result = shortestSubset(of: array, withSum: goal)\nlet end = Date()\nprint(result, end.timeIntervalSince(start) * 1000)\n</code></pre>\n\n<p>compiled with Xcode 11.3.1 in Release mode, i.e. with optimization.</p>\n\n<p>Results (approximately):</p>\n\n<ul>\n<li>Original code: 6 milliseconds.</li>\n<li>Version A: 3 milliseconds.</li>\n<li>Version B: 0.7 milliseconds.</li>\n<li>Version C: 0.2 milliseconds.</li>\n<li>Version D: 0.4 milliseconds.</li>\n</ul>\n\n<p>With the larger array</p>\n\n<pre><code>let array = [1, -2, 3, -4, 5, -6, 100, 100, 7, -8, 9, -10, 11, -12,\n 1, -2, 3, -4, 5, -6, 100, 100, 7, -8, 9, -10, 11, -12]\nlet goal = 20\n</code></pre>\n\n<p>we get the following results:</p>\n\n<ul>\n<li>Original code: ??? </li>\n<li>Version A: 37733 milliseconds.</li>\n<li>Version B: 6079 milliseconds.</li>\n<li>Version C: 548 milliseconds.</li>\n<li>Version D: 2.5 milliseconds.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T21:59:28.410",
"Id": "462667",
"Score": "0",
"body": "Nicely done. I suspect the difference in performance would be even more dramatic with hundreds or thousands of elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:37:03.977",
"Id": "462668",
"Score": "0",
"body": "@vacawama: I haven't tested hundreds or thousands, but yes, the difference becomes larger with larger arrays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T12:20:57.967",
"Id": "462711",
"Score": "0",
"body": "Thanks @MartinR . Let me investigate more on your solutions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T21:11:28.073",
"Id": "236173",
"ParentId": "236154",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236173",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T14:16:06.940",
"Id": "236154",
"Score": "4",
"Tags": [
"performance",
"algorithm",
"array",
"swift"
],
"Title": "Find minimum count of items where sum of them is X from an array"
}
|
236154
|
<p>I made my first open-source project and wonder if I could do it better.
I'll give briefly description, ask some questions and then post whole code.
Open to any opinons and suggestions, thank you.</p>
<p>So, Aiohttp is asynchronous HTTP Client for Python. You can find it's documentation <a href="https://docs.aiohttp.org/en/stable/" rel="nofollow noreferrer">here</a>. However all you need to know is that it have <code>ClientSession</code> class for making responses. This class is made in async-with approach.<br>
Developers suggest to use it like this:</p>
<pre class="lang-py prettyprint-override"><code>async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
</code></pre>
<p>I made an extension to aiohttp for retries. It's common idea to retry a request in case it failed.
I tried to save this async-with approach. So, here two classes: </p>
<ul>
<li><p><code>RetryClient</code> - client for retries<br>
It takes the same params as aiohttp ClientSession and do the same things. The only difference: methods like 'get' takes additional params like number of attemps.</p></li>
<li><p><code>_RequestContext</code> - async-with context for handling request<br>
Actually it contains all retry logic and tries to do requests. When it do request, it send it to aiohttp and then handle response in proper way.</p></li>
</ul>
<p>In my opinion the main problem here is huge usage of <code>**kwargs</code>. All params are stored here. I tested that it will be broken on wrong param, but smart IDE like Pycharm wouldn't suggest you anything. However, I don't know how to fix it.</p>
<p>You can find the whole project here:<br>
<a href="https://github.com/inyutin/aiohttp_retry" rel="nofollow noreferrer">https://github.com/inyutin/aiohttp_retry</a></p>
<p>The whole code:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
import logging
from aiohttp import ClientSession, ClientResponse
from typing import Any, Callable, Optional, Set, Type
# Options
_RETRY_ATTEMPTS = 3
_RETRY_START_TIMEOUT = 0.1
_RETRY_MAX_TIMEOUT = 30
_RETRY_FACTOR = 2
class _RequestContext:
def __init__(self, request: Callable[..., Any], # Request operation, like POST or GET
url: str, # Just url
retry_attempts: int = _RETRY_ATTEMPTS, # How many times we should retry
retry_start_timeout: float = _RETRY_START_TIMEOUT, # Base timeout time, then it exponentially grow
retry_max_timeout: float = _RETRY_MAX_TIMEOUT, # Max possible timeout between tries
retry_factor: float = _RETRY_FACTOR, # How much we increase timeout each time
retry_for_statuses: Optional[Set[int]] = None, # On which statuses we should retry
retry_exceptions: Optional[Set[Type]] = None, # On which exceptions we should retry
**kwargs: Any
) -> None:
self._request = request
self._url = url
self._retry_attempts = retry_attempts
self._retry_start_timeout = retry_start_timeout
self._retry_max_timeout = retry_max_timeout
self._retry_factor = retry_factor
if retry_for_statuses is None:
retry_for_statuses = set()
self._retry_for_statuses = retry_for_statuses
if retry_exceptions is None:
retry_exceptions = set()
self._retry_exceptions = retry_exceptions
self._kwargs = kwargs
self._current_attempt = 0
self._response: Optional[ClientResponse] = None
def _exponential_timeout(self) -> float:
timeout = self._retry_start_timeout * (self._retry_factor ** (self._current_attempt - 1))
return min(timeout, self._retry_max_timeout)
def _check_code(self, code: int) -> bool:
return 500 <= code <= 599 or code in self._retry_for_statuses
async def _do_request(self) -> ClientResponse:
try:
self._current_attempt += 1
response: ClientResponse = await self._request(self._url, **self._kwargs)
code = response.status
if self._current_attempt < self._retry_attempts and self._check_code(code):
retry_wait = self._exponential_timeout()
await asyncio.sleep(retry_wait)
return await self._do_request()
self._response = response
return response
except Exception as e:
retry_wait = self._exponential_timeout()
if self._current_attempt < self._retry_attempts:
for exc in self._retry_exceptions:
if isinstance(e, exc):
await asyncio.sleep(retry_wait)
return await self._do_request()
raise e
async def __aenter__(self) -> ClientResponse:
return await self._do_request()
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
if self._response is not None:
if not self._response.closed:
self._response.close()
class RetryClient:
def __init__(self, logger: Any = None, *args: Any, **kwargs: Any) -> None:
self._client = ClientSession(*args, **kwargs)
self._closed = False
if logger is None:
logger = logging.getLogger("aiohttp_retry")
self._logger = logger
def __del__(self) -> None:
if not self._closed:
self._logger.warning("Aiohttp retry client was not closed")
@staticmethod
def _request(request: Callable[..., Any], url: str, **kwargs: Any) -> _RequestContext:
return _RequestContext(request, url, **kwargs)
def get(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.get, url, **kwargs)
def options(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.options, url, **kwargs)
def head(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.head, url, **kwargs)
def post(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.post, url, **kwargs)
def put(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.put, url, **kwargs)
def patch(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.patch, url, **kwargs)
def delete(self, url: str, **kwargs: Any) -> _RequestContext:
return self._request(self._client.delete, url, **kwargs)
async def close(self) -> None:
await self._client.close()
self._closed = True
async def __aenter__(self) -> 'RetryClient':
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
await self.close()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>I think <code>RetryClient</code> is a bad name as it doesn't highlight that you're wrapping a session.</li>\n<li><p>Taking lots of <code>retry_*</code> parameters screams to me that you should make a class.</p>\n\n<p>For example popular libraries like <a href=\"https://stackoverflow.com/a/15431343\">requests</a> and <a href=\"https://urllib3.readthedocs.io/en/latest/user-guide.html#retrying-requests\" rel=\"nofollow noreferrer\">urllib3</a> use a <a href=\"https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry\" rel=\"nofollow noreferrer\">Retry class</a>.</p></li>\n<li><p>You can pass a tuple to <code>isinstance</code> to check against multiple types in one call.</p></li>\n<li>You use a tuple with <code>except</code> to filter to only those exceptions. Removing the need for <code>isinstance</code> at all.</li>\n<li>You can make <code>_exponential_timeout</code> a function that makes a full-fledged itarable.</li>\n<li><p>Making the <code>Retry</code> class take an iterable on how long each delay should be allows for easy customization from users.</p>\n\n<p>Want a 3 gap 20 times is easy:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>Retry(timeouts=[3] * 20)\n</code></pre>\n\n<p>Users can also make it so it retries infinitely.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class InfinateOnes:\n def __iter__(self):\n while True:\n yield 1\n</code></pre></li>\n<li><p>I would prefer to see an explicit <code>while True</code> and iteration over recursion.</p></li>\n<li><p>I would prefer if <code>Retry</code> was designed in a way in which it would work with any function that returns a <code>ClientResponse</code>.</p>\n\n<p>A part of me that likes to make things as generic as possible, would prefer changing statuses to a callback to check if the return is valid. However this doesn't make too much sense in a bespoke library.</p></li>\n</ul>\n\n<p>In all I think this drastically simplifies <code>_RequestContext</code>.<br>\n<sup><strong>Note</strong>: untested</sup></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import asyncio\nimport logging\nfrom aiohttp import ClientSession, ClientResponse\nfrom typing import Any, Callable, Optional, Set, Type, Iterable\n\n# Options\n_RETRY_ATTEMPTS = 3\n_RETRY_START_TIMEOUT = 0.1\n_RETRY_MAX_TIMEOUT = 30\n_RETRY_FACTOR = 2\n\n\ndef exponential(\n attempts: int = _RETRY_ATTEMPTS,\n start: int = _RETRY_START_TIMEOUT,\n maximum: int = _RETRY_MAX_TIMEOUT,\n factor: int = _RETRY_FACTOR,\n) -> Iterable[float]:\n return [\n min(maximum, start * (factor ** i))\n for i in range(attempts)\n ]\n\n\nclass Retry:\n def __init__(\n self,\n timeouts: Iterable[float] = exponential(),\n statuses: Optional[Set[int]] = None,\n exceptions: Optional[Tuple[Type]] = None,\n ) -> None:\n self._timeouts = timeouts\n self._statuses = statuses or set()\n self._exceptions = exceptions or ()\n\n def _is_retry_status(self, code):\n return 500 <= code <= 599 or code in self._statuses\n\n async def retry(\n self,\n callback: Callable[[...], ClientResponse],\n *args,\n **kwargs,\n ) -> ClientResponse:\n timeouts = iter(self.timeouts)\n while True:\n try:\n response = await self._request(*args, **kwargs)\n if not self._is_retry_status(response.status):\n return response\n try:\n retry_wait = next(timouts)\n except StopIteration:\n return response\n except self._retry_exceptions as e:\n try:\n retry_wait = next(timouts)\n except StopIteration:\n raise e from None\n await asyncio.sleep(retry_wait)\n\n\nclass _RequestContext:\n def __init__(\n self,\n request: Callable[..., Any],\n url: str,\n retry: Retry,\n **kwargs: Any\n ) -> None:\n self._request = request\n self._url = url\n self._kwargs = kwargs\n self._retry = retry\n\n async def __aenter__(self) -> ClientResponse:\n return await self._retry.retry(self._request, self._url, **self._kwargs)\n\n async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:\n if self._response is not None:\n if not self._response.closed:\n self._response.close()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T04:46:35.303",
"Id": "236330",
"ParentId": "236156",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236330",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T14:21:51.083",
"Id": "236156",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python aiohttp extension"
}
|
236156
|
<p>As an exercise to familiarise myself with smart pointers, I implemented a template linked list class in C++, closely following the very good tutorial at: <a href="https://solarianprogrammer.com/2019/02/22/cpp-17-implementing-singly-linked-list-smart-pointers/" rel="noreferrer">https://solarianprogrammer.com/2019/02/22/cpp-17-implementing-singly-linked-list-smart-pointers/</a>, which I duly acknowledge and from which I borrow freely.</p>
<p>The code seems to be working as expected, so far, and I feel that I have a better understanding of how to use unique_ptrs for ownership. However, I have taken a shortcut in my code for popping an element from the front of the list, which is also used in the clean() member function (see code below). In particular, when popping an element or iteratively deleting nodes, I have noticed that some people use an intermediary unique pointer to take ownership of the node to be deleted, as in the following:</p>
<pre><code>/**
* Pop the top element off the list
*
*/
template <typename T>
void LinkedList<T>::pop() {
if (ptrHead == nullptr) {
return;
}
// can we safely avoid the ptrDetached intermediary?
std::unique_ptr<Node> ptrDetached = std::move(ptrHead);
ptrHead = std::move(ptrDetached->ptrNext);
}
</code></pre>
<p>However, it appears to me that the allocation of a ptrDetached is unnecessary, and one can instead use:</p>
<pre><code>template <typename T>
void LinkedList<T>::pop() {
if (ptrHead == nullptr) {
return;
}
ptrHead = std::move(ptrHead->ptrNext);
}
</code></pre>
<p>This second version of the code seems to be working [Linux, g++ (Debian 9.2.1-22) 9.2.1 20200104], but I am concerned that I might be making some naive assumptions about unique_ptr's move constructor that might come back to bite me. Is there anything wrong with the second approach?</p>
<p>Can anyone offer some advice on best practice here? Is my short cut above generally safe? My header file for the complete LinkedList follows (it's a work in progress). Suggestions for improvement would be very welcome.</p>
<p>Thanks in advance and my apologies if there is something I have overlooked (this is my first post).</p>
<pre><code>/*
* File: LinkedList.h
*/
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <memory>
#include <exception>
template <typename T>
class LinkedList {
template <typename U>
friend std::ostream& operator<<(std::ostream&, const LinkedList<U>&);
public:
// default constructor
LinkedList() : ptrHead{nullptr} {}
// copy constructor: duplicate a list object
LinkedList(LinkedList&);
// move constructor
LinkedList(LinkedList&&);
// destructor
~LinkedList();
// TODO: Add overloaded assignment and move assignment operators
// For now, just delete them.
const LinkedList& operator=(const LinkedList&) = delete;
const LinkedList& operator=(const LinkedList&&) noexcept = delete;
// utility methods
void push(const T&);
void pop();
T peek() const;
void clean();
void print(std::ostream&) const;
private:
// basic node structure
struct Node {
// constructor
explicit Node(const T& data) : element{data}, ptrNext{nullptr} {}
// destructor (only for testing deallocation)
~Node() {
std::cout << "Destroying Node with data " << element << std::endl;
}
T element;
std::unique_ptr<Node> ptrNext;
};
std::unique_ptr<Node> ptrHead; // head of the list
};
/////////////////////////////////////////////////////////////////////////////
// Implementation of Linked List
/**
* Copy constructor
*
* @param list
*/
template <typename T>
LinkedList<T>::LinkedList(LinkedList& list) {
// the new head of list
std::unique_ptr<Node> ptrNewHead{nullptr};
// raw pointer cursor for traversing the new (copied) list
Node* ptrCurrNode{nullptr};
// raw pointer for traversing the list to be copied
Node* ptrCursor{list.ptrHead.get()};
while (ptrCursor) {
// allocate a new node, copying the element of the current node
std::unique_ptr<Node>
ptrTemp{std::make_unique<Node>(ptrCursor->element)};
// add it to the new list, as appropriate
if (ptrNewHead == nullptr) {
ptrNewHead = std::move(ptrTemp);
ptrCurrNode = ptrNewHead.get();
} else {
ptrCurrNode->ptrNext = std::move(ptrTemp);
ptrCurrNode = ptrCurrNode->ptrNext.get();
}
ptrCursor = ptrCursor->ptrNext.get();
}
ptrHead = std::move(ptrNewHead);
}
/**
* Copy move constructor
*
* @param list
*/
template <typename T>
LinkedList<T>::LinkedList(LinkedList&& list) {
ptrHead = std::move(list.ptrHead);
}
// TODO: Add overloaded assignment and move assignment operators
/**
* Destructor
*
*/
template <typename T>
LinkedList<T>::~LinkedList() {
clean();
}
/**
* Push a T value onto the list
*
* @param data
*/
template <typename T>
void LinkedList<T>::push(const T& data) {
std::unique_ptr<Node> ptrTemp{std::make_unique<Node>(data)};
ptrTemp->ptrNext = std::move(ptrHead);
ptrHead = std::move(ptrTemp);
}
/**
* Pop the top element off the list
*
*/
template <typename T>
void LinkedList<T>::pop() {
if (ptrHead == nullptr) {
return;
}
// can we safely avoid the ptrDetached intermediary?
// std::unique_ptr<Node> ptrDetached = std::move(ptrHead);
// ptrHead = std::move(ptrDetached->ptrNext);
ptrHead = std::move(ptrHead->ptrNext);
}
/**
* Peek at the value of the top element.
*
* Throws an exception if the list is empty.
*
* @return
*/
template <typename T>
T LinkedList<T>::peek() const {
if (ptrHead == nullptr) {
throw std::out_of_range{"Empty list: Attempt to dereference a NULL pointer"};
}
return ptrHead->element;
}
/**
* Clean the list
*
*/
template <typename T>
void LinkedList<T>::clean() {
while (ptrHead) {
// can we safely avoid the ptrDetached intermediary?
// std::unique_ptr<Node> ptrDetached = std::move(ptrHead);
// ptrHead = std::move(ptrDetached->ptrNext);
ptrHead = std::move(ptrHead->ptrNext);
}
}
/**
* Print the list on ostream os
*
* @param os
*/
template <typename T>
void LinkedList<T>::print(std::ostream& os) const {
Node* ptrCursor{ptrHead.get()}; // raw pointer for iteration
while(ptrCursor) {
os << ptrCursor->element << " -> ";
ptrCursor = ptrCursor->ptrNext.get();
}
os << "NULL" << std::endl;
}
/**
* Overloaded operator << for the LinkedList
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const LinkedList<T>& list) {
list.print(os);
return os;
}
#endif /* LINKEDLIST_H */
</code></pre>
|
[] |
[
{
"body": "<h2>Overall</h2>\n<p>Good.</p>\n<p>Personally I don't like building containers using smart pointers. Containers and smart pointers are the techniques we use to manage memory for objects (singular or plural respectively). As such they should both manage their own memories correctly.</p>\n<p>But other people do it (use smart pointers) so I don't see it as a big deal; but I think you will learn more from implementing the container as the class that handles memory management.</p>\n<h2>Overview</h2>\n<p>You should put your stuff inside its own namespace.</p>\n<h2>Code Review</h2>\n<p>Not very unique.</p>\n<pre><code>#ifndef LINKEDLIST_H\n#define LINKEDLIST_H\n</code></pre>\n<p>If you add your own namespace to that guard it may become unique.</p>\n<hr />\n<p>A friend template for a different type?</p>\n<pre><code>class LinkedList {\n template <typename U>\n friend std::ostream& operator<<(std::ostream&, const LinkedList<U>&);\n</code></pre>\n<p>You can simplify this to:</p>\n<pre><code>class LinkedList {\n friend std::ostream& operator<<(std::ostream&, LinkedList const&);\n</code></pre>\n<p>Even though <code>print()</code> is a public method and thus does not need a fiend to call it. I still would encourage this as a friend operator because it declares the tight coupling of the interface.</p>\n<hr />\n<p>Nice use of the initializer list here.</p>\n<pre><code> LinkedList() : ptrHead{nullptr} {}\n</code></pre>\n<p>Curious why you don't use it in the Copy Cosntrctor body!<br />\nI'll get to that below.</p>\n<hr />\n<p>Normally you would pass the list by const reference.</p>\n<pre><code> LinkedList(LinkedList&);\n</code></pre>\n<p>Here you could make a mistake in your copy constructor and accidently modify the input list.</p>\n<hr />\n<p>Move constructors are usually <code>noexcept</code> safe.</p>\n<pre><code> LinkedList(LinkedList&&);\n</code></pre>\n<p>This provides the standard library the opportunity to add optimizations when using its containers. If you can safely move objects without the chance of exception then the move constructor can be used. If the move constructor is not exception safe them you can not always provide the <code>Strong Exception Guarantee</code> and thus must use a technique that uses copying rather than moving. Thus if you can guarantee exception safe moves you should let the compiler know with <code>noexcept</code>.</p>\n<hr />\n<p>Seriously that comment does my no good.</p>\n<pre><code> // destructor\n ~LinkedList();\n</code></pre>\n<p>That is a bad comment. Because comments need to be maintained with the code (comments like code rote over time). So you be careful to avoid usless coments as they take effort to maintain (and people will put as little effort into maintenance as they can). As a result comments and code can drift apart over time and cause confusion.</p>\n<hr />\n<pre><code> // TODO: Add overloaded assignment and move assignment operators\n // For now, just delete them.\n const LinkedList& operator=(const LinkedList&) = delete;\n const LinkedList& operator=(const LinkedList&&) noexcept = delete;\n</code></pre>\n<p>These are both exceptionally easy to implement if you have a <code>swap() noexcept</code> method.</p>\n<p>Note 1: Assignment operators don't usually return const references.<br />\nNote 2: The move assignment operator does not take a const input. Moving the source into the destination will modify it.</p>\n<pre><code> LinkedList const& operator=(LinkedList const& input) {\n LinkedList copy(input);\n swap(copy);\n return *this;\n }\n LinkedList& operator=(LinkedList&& input) noexcept {\n clean();\n swap(input);\n return *this;\n }\n</code></pre>\n<hr />\n<p>You have a move constructor.<br />\nWhy don't you have a move <code>push()</code>?</p>\n<pre><code> void push(const T&); \n</code></pre>\n<hr />\n<p>Nice.</p>\n<pre><code> void pop();\n</code></pre>\n<p>Clea separation of the pop from the peek().</p>\n<hr />\n<p>Why are you returning by value?</p>\n<pre><code> T peek() const;\n</code></pre>\n<p>You should return a const reference to the object. This will prevent an extra copy (which is important if T is expensive to copy). But you can also provide a normal reference (if your class needs it) that would allow you to modify the object in place inside the list.</p>\n<pre><code> T const& peek() const;\n T& peek(); // Optional.\n</code></pre>\n<hr />\n<pre><code>template <typename T>\nLinkedList<T>::LinkedList(LinkedList& list) {\n</code></pre>\n<p>Why not use the initializer list to do this.</p>\n<pre><code> // the new head of list\n std::unique_ptr<Node> ptrNewHead{nullptr};\n</code></pre>\n<p>Which of course is the default action of the unique_ptr default constructor. So this operation is already done by this point in the constructor.</p>\n<hr />\n<p>I am going to mention comments again.</p>\n<pre><code> // raw pointer cursor for traversing the new (copied) list\n Node* ptrCurrNode{nullptr};\n\n // raw pointer for traversing the list to be copied\n Node* ptrCursor{list.ptrHead.get()};\n</code></pre>\n<p>These comments are not useful. They do not tell me more than I can already understand from simply reading the code. Infact your code could be made more readable by removing the comments and using better variable names.</p>\n<p>Comments should not be used for describing the code (the code does that very well). Also because of comment rote over time the code and comments can easily become disjoint. As such if a maintainer comes across code that has a comment that does not mach the comment do they fix the comment or do they fix the code. If they are good they have to do one which means they have to do research. It is better to write better "Self documenting code" so the code describes what it does.</p>\n<p>Your comments should describe WHY or an overall ALGORITHM or some particularly OBSCURE point that code can not describe. <strong>DO NOT</strong> simply convert your code into English and call it a comment.</p>\n<hr />\n<p>So above you ask why people assigned this to a temporary.</p>\n<pre><code>void LinkedList<T>::pop() {\n\n .... \n ptrHead = std::move(ptrHead->ptrNext);\n}\n</code></pre>\n<p>The question you have to ask yourself.</p>\n<p>Q: Does the <code>std::unique_ptr</code> assignment operator call the destruct on the object it contains before or after it assigns the new value?</p>\n<p>Let us imagine two different version of the assignment operator.</p>\n<pre><code> oldValue = internalPtr;\n internalPtr = newValue;\n delete oldValue;\n</code></pre>\n<p>or</p>\n<pre><code> delete internalValue;\n internalValue = newValue;\n</code></pre>\n<p>How do those different implementations affect your code?<br />\nWhat grantees does the standard provide?</p>\n<hr />\n<p>No need to use <code>std::endl</code> here.</p>\n<pre><code> os << "NULL" << std::endl;\n</code></pre>\n<p>Prefer to use <code>"\\n"</code>. This is exactly the same except it does not force a flush of the stream. The main problem with people timing C++ streams is that they always manually flush them (like this) then complain they are not as fast a C streams. If you don't manually flush them (especially since the stream knows when to flush itself very efficiently) the C++ streams are comparable to C streams.</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T09:44:00.333",
"Id": "462934",
"Score": "0",
"body": "thank you very much for the careful and informative review. All points you raise are valid and I shall take heed of them in the refactoring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T09:58:32.080",
"Id": "462936",
"Score": "0",
"body": "you mentioned memory management in your preamble. I have read your nice tutorial on dynamically resized vectors and learned much about memory management and placement new. Can you recommend a resource, web or otherwise, that does similar for lists?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T23:29:36.773",
"Id": "236262",
"ParentId": "236158",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236262",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T15:47:02.813",
"Id": "236158",
"Score": "6",
"Tags": [
"c++",
"linked-list",
"pointers"
],
"Title": "C++ Linked list implementation using smart pointers. Advice on move semantics"
}
|
236158
|
<p>So on my checkout page when I push final checkout I want to store my users address and shipping address into a database. I am wondering if this could be shorter. Currently, users have multiple options:</p>
<ol>
<li>Logged in where they use same or other shipping address.</li>
<li>Not logged in and they want to create account with same or different shipping address.</li>
<li>Not logged in where they create a guest account again with same or different address.</li>
</ol>
<p>I know I can put my <code>$_POST</code> values direct in the <code>$createlines</code> but its just for making it clear now as I am still coding it.</p>
<p>Just wondering if theres some sort of function to get all values and fields from my database.</p>
<pre><code>if (isset($_POST['final_checkout'])) {
$createuser = new User();
$createaddress = new Address();
$createshipping = new Shipping_address();
if (!empty($logged_in)) {
/*als same addres is aangevinkt bij ingelogde user*/
if ($_POST['shipping'] == 'same' ) {
$oldaddress = trim($_POST['oldaddress']);
$oldcity = trim($_POST['oldcity']);
$oldpostal = trim($_POST['oldpostal']);
$oldcountry = trim($_POST['oldcountry']);
$createshipping->user_id = $logged_in->id;
$createshipping->address = $oldaddress;
$createshipping->city = $oldcity;
$createshipping->postal = $oldpostal;
$createshipping->country = $oldcountry; //in tabel addresses nog kolom country maken en dan inputfield ook readonly stap 1
/*als different adres is aangevinkt bij ingelogde user*/
} else{
$othershippingaddress = trim($_POST['create_otheraddress']);
$othershippingcity = trim($_POST['create_othercity']);
$othershippingpostal = trim($_POST['create_otherpostal']);
$othershippingcountry = trim($_POST['create_othercountry']);
$createshipping->user_id = $logged_in->id;
$createshipping->address = $othershippingaddress;
$createshipping->city = $othershippingcity;
$createshipping->postal = $othershippingpostal;
$createshipping->country = $othershippingcountry;
}/*end else shippingaddress*/
/*if user is !logged in*/
}else{
/*create account*/
if ($_POST['optradio'] == 'create') {
/*variabelen maken van de post*/
$newusername = trim($_POST['create_username']);
$newpassword = trim($_POST['create_password']);
$newfirst = trim($_POST['create_first']);
$newlast = trim($_POST['create_last']);
$newmail = trim($_POST['create_mail']);
$newaddress = trim($_POST['create_address']);
$newcity = trim($_POST['create_city']);
$newpostal = trim($_POST['create_postal']);
$newcountry = trim($_POST['create_country']);
/*usertabel invullen*/
$createuser->username = $newusername;
$createuser->first_name = $newfirst;
$createuser->last_name = $newlast;
$createuser->password = $newpassword;
$createuser->user_mail = $newmail;
$createuser->user_image = 'guest';
$createuser->role_id = '4';
/*adresses tabel invullen*/
$createaddress->address = $newaddress;
$createaddress->postal = $newpostal;
$createaddress->city = $newcity;
$createaddress->country = $newcountry;
$createaddress->user_id = '';
/*shipping adres same or different in de create account*/
if ($_POST['shipping'] == 'same') {
/*als same addres is aangevinkt bij nieuwe user*/
$oldaddress = $newaddress;
$oldcity = $newcity;
$oldpostal = $newpostal;
$oldcountry = $newcountry;
/*shipping addres invoeren*/
$createshipping->user_id = $createuser->id;
$createshipping->address = $oldaddress;
$createshipping->city = $oldcity;
$createshipping->postal = $oldpostal;
$createshipping->country = $oldcountry; //in tabel addresses nog kolom country maken en dan inputfield ook readonly stap 1
} else{
/*als different adres is aangevinkt bij nieuwe user*/
$othershippingaddress = trim($_POST['create_otheraddress']);
$othershippingcity = trim($_POST['create_othercity']);
$othershippingpostal = trim($_POST['create_otherpostal']);
$othershippingcountry = trim($_POST['create_othercountry']);
/*shipping addres invoeren*/
$createshipping->user_id = $logged_in->id;
$createshipping->address = $othershippingaddress;
$createshipping->city = $othershippingcity;
$createshipping->postal = $othershippingpostal;
$createshipping->country = $othershippingcountry;
}/*end else different addres*/
}else{
/*als guestaccount is aangevinkt*/
$guestnumber = User::number_guest();
$newusername = 'guest' . $guestnumber;
$newpassword = '';
$newfirst = trim($_POST['create_first']);
$newlast = trim($_POST['create_last']);
$newmail = trim($_POST['create_mail']);
$newaddress = trim($_POST['create_address']);
$newcity = trim($_POST['create_city']);
$newpostal = trim($_POST['create_postal']);
$newcountry = trim($_POST['create_country']);
/*usertabel invullen*/
$createuser->username = $newusername;
$createuser->first_name = $newfirst;
$createuser->last_name = $newlast;
$createuser->password = $newpassword;
$createuser->user_mail = $newmail;
$createuser->user_image = 'guest';
$createuser->role_id = '4';
/*hier al saven om id te krijgen*/
/*adresses tabel invullen*/
$createaddress->address = $newaddress;
$createaddress->postal = $newpostal;
$createaddress->city = $newcity;
$createaddress->country = $newcountry;
$createaddress->user_id = '';
if ($_POST['shipping'] == 'same') {
/*als same addres is aangevinkt bij guest*/
$oldaddress = $newaddress;
$oldcity = $newcity;
$oldpostal = $newpostal;
$oldcountry = $newcountry;
/*shipping addres invoeren*/
$createshipping->user_id = $createuser->id;
$createshipping->address = $oldaddress;
$createshipping->city = $oldcity;
$createshipping->postal = $oldpostal;
$createshipping->country = $oldcountry; //in tabel addresses nog kolom country maken en dan inputfield ook readonly stap 1
} else{
/*als different adres is aangevinkt bij guest*/
$othershippingaddress = trim($_POST['create_otheraddress']);
$othershippingcity = trim($_POST['create_othercity']);
$othershippingpostal = trim($_POST['create_otherpostal']);
$othershippingcountry = trim($_POST['create_othercountry']);
/*shipping addres invoeren*/
$createshipping->user_id = $createuser->id;
$createshipping->address = $othershippingaddress;
$createshipping->city = $othershippingcity;
$createshipping->postal = $othershippingpostal;
$createshipping->country = $othershippingcountry;
}/*end elseif (guestaccount ->sameaddres)*/
}/*end else (guestaccount)*/
} /*end else (!logged in)*/
}/*end isset post*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:25:22.203",
"Id": "462621",
"Score": "0",
"body": "Your code indentation seems to be unbalanced (starting here: `if (!empty($logged_in)){`), can you fix that please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:36:41.577",
"Id": "462623",
"Score": "0",
"body": "just checked but indention seems ok to me the if ´(!empty($logged_in)){` is the start and everything is supposed to be in it or what u want me to do exactly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:40:33.800",
"Id": "462624",
"Score": "0",
"body": "reformatted with the help of php storm so should be good no thx for reply tho"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:48:30.170",
"Id": "462625",
"Score": "0",
"body": "There's still a hanging `}` as you can see. That should be aligned with the code formatted section. It's either one too much from a missing opening brace, or you missed the code balance correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:04:59.207",
"Id": "462626",
"Score": "0",
"body": "hope its ok now sorry to bother u"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:09:34.670",
"Id": "462627",
"Score": "0",
"body": "The `}` still hangs off there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:19:39.750",
"Id": "462628",
"Score": "0",
"body": "is there a way i can send u my php file so u can see in ur editor its not hanging off? when i debug using Xdebug everything works i just wanted to know if theres a way to shorten it out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:38:25.490",
"Id": "462630",
"Score": "0",
"body": "youre probably right im goin to rewrite the lot off it and then repost sorry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:38:27.400",
"Id": "462631",
"Score": "0",
"body": "I am just referring how your code posted renders here, you can blatantly see that `}` isn't rendered in the code section. Fix that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:44:47.437",
"Id": "462632",
"Score": "0",
"body": "Hint `if ($_POST['sameaddress'] == '1' || 'on') {` also lags indentation now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:56:25.287",
"Id": "462633",
"Score": "0",
"body": "u are def right just checked and i ave one to many at the bottom gonna fix it thx"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T18:13:15.717",
"Id": "462637",
"Score": "1",
"body": "You should implement methods to set a bulk of properties for the various instances you're populating."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:41:04.533",
"Id": "462653",
"Score": "0",
"body": "the indentation should be ok now as you will see i'm not yet including any save() its just written and testing out if i get all values i desire but just want to know how to write this shorter if it is possible"
}
] |
[
{
"body": "<p>In a sutuation when a block of code is present in both branches of an <code>if</code> statement, you can move this common part out of this statement. \nfor example,</p>\n\n<pre><code>if (some condition) {\n $a = $x;\n $b = $y;\n $a = $z;\n} else {\n $a = $x;\n $b = $y;\n $a = null;\n}\n</code></pre>\n\n<p>it can be rewritten to</p>\n\n<pre><code>$a = $x;\n$b = $y;\nif (some condition) {\n $a = $z;\n} else {\n $a = null;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T08:18:36.310",
"Id": "236217",
"ParentId": "236159",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:21:20.053",
"Id": "236159",
"Score": "-1",
"Tags": [
"php"
],
"Title": "Storing user and shipping addresses"
}
|
236159
|
<p>Utility to generate sequences of predetermined addenda that add up to a given number.
There is also a function for orderly printing and one for converting list of lists in sequence of sequences.</p>
<p>The answer that Gurkenglas gave invites me to specify the objective that I set myself by defining these functions. The field of applications that I had in mind is music theory. I teach my students elements of analysis and musical composition. A fundamental dimension of music is the duration of the sounds. A rhythm is a particular sequence of durations, which in music are sometimes expressed as numerical relationships, sometimes as absolute values (seconds). The durations of a piece of music are normally grouped into "measures", that is, into sequences whose total duration is equal to a predetermined duration. By changing the order in the sequence you can get totally different musical objects. As far as musical analysis is concerned, it is interesting to measure the variety of the rhythms used in relation to the possible rhythms obtained combinatorically starting from the basic durations used in the piece or in a part of it.</p>
<p>From the compositional point of view, the combinatorial generation can be a source of inspiration for unusual rhythms.</p>
<p>To come to what Gurkenglas explained, the function proposed by him does not produce the results of mine since the lists or sequences of addends do not take into account the constraint of the order.</p>
<p>For instance:</p>
<p>ex3 (addendumSequences 10 (toSeqs [[3,1],[7]]) (fromList [2,4,3])) produce:
[3,1,2,2,2]
[3,1,2,4]
[3,1,3,3]
[3,1,4,2]
[7,3]</p>
<p>Conversely knapsack 10 [2,4,3] [[3,1],[7]] produce:</p>
<p>[3,7]
[4,2,3,1]
[2,4,3,1]
[3,3,3,1]
[2,2,2,3,1]</p>
<p>In this case, not only the order of the elements is different, but the constraint that the sequences must start with [3,1] or [7], which is a request that has a musical sense, is absent.
Just this problem has induced me to prefer the Sequence type to List.</p>
<p>(About the signature: I only reported what GHCi deduced from the functions.)</p>
<pre><code>import Prelude hiding (null)
import Data.Sequence (Seq)
import Data.Sequence
import Data.Foldable (fold,toList)
import Data.Ratio -- library needed only for the example
-- The numbers must all be positive
addendumSequences :: (Ord a, Num a) => a -> Seq (Seq a) -> Seq a -> Seq (Seq a)
addendumSequences n bases addenda
| null bases && null addenda = empty
| null addenda = snd $ pruneAndStore n bases empty
| null bases = go n (fmap singleton addenda) addenda empty
| otherwise = go n bases addenda empty
where
go n bases addenda ok_bases
| null bases = ok_bases
| otherwise = let bases' = combinesBasesAndAddends bases addenda
(candidate_bases,ok_bases') = pruneAndStore n bases' ok_bases
in if null candidate_bases
then ok_bases'
else go n candidate_bases addenda ok_bases'
combinesBasesAndAddends
:: (Monoid (f (Seq a)), Foldable t, Functor f) =>
t (Seq a) -> f a -> f (Seq a)
combinesBasesAndAddends bases addenda =
fold $ foldr (\base acc -> acc |> fmap (base |>) addenda) empty bases
pruneAndStore
:: (Ord a, Foldable t1, Foldable t2, Num a) =>
a -> t1 (t2 a) -> Seq (t2 a) -> (Seq (t2 a), Seq (t2 a))
pruneAndStore n bases ok_bases =
foldr (\base (candidate_bases,ok_bases) ->
let tot = sum base
in if tot == n
then (candidate_bases, base <| ok_bases)
else if tot < n
then (base <| candidate_bases, ok_bases)
else (candidate_bases, ok_bases)
) (empty,ok_bases) bases
-- ============================== Utilities ==============================
toSeqs :: [[a]] -> Seq (Seq a)
toSeqs = fromList . fmap fromList
pPrint :: (Ord a, Num a, Show a) => Seq (Seq a) -> IO ()
pPrint = mapM_ print . toList . fmap toList . sort
-- ============================== Examples ==============================
ex1 = pPrint $ addendumSequences 8 empty (fromList [1,2,4,3])
ex2 = pPrint $ addendumSequences (1%1) empty (fromList [1%2,1%3,1%4,1%8])
ex3 = pPrint $ addendumSequences 10 (toSeqs [[3,1],[7]]) (fromList [2,4,3])
ex4 = pPrint $ addendumSequences 2.0 (toSeqs [[1.1],[0.85]]) (fromList [0.25,0.1])
</code></pre>
|
[] |
[
{
"body": "<p>Order of anything never seems to matter, so I will use <code>[]</code> instead of <code>Seq</code>.</p>\n\n<p><code>go</code> needs no <code>ok_bases</code> accumulator - see <code>foldl</code> vs <code>foldr</code>.</p>\n\n<p>The type signatures on your helper functions are needlessly general. In fact, I'd just localize the helpers.</p>\n\n<pre><code>knapsack :: (Ord a, Num a) => a -> [a] -> [[a]] -> [[a]]\nknapsack n addenda bases\n | null addenda = fst $ prune bases\n | null bases = go $ grow [[]]\n | otherwise = go bases\n where\n go [] = []\n go bases = let (yes, maybe) = prune $ grow bases\n in yes ++ go maybe\n grow = concatMap $ \\base -> map (:base) addenda\n prune = foldr partitioner (empty, empty)\n partitioner base = case compare n $ sum base of\n EQ -> first (base :)\n GT -> second (base :)\n LT -> id\n</code></pre>\n\n<p><code>| null bases = go $ grow [[]]</code> can go away once the user recognizes that an empty list of starting bases means no solutions, while he probably wants an empty starting base. (Are you sure we shouldn't prune the singletons?)</p>\n\n<p><code>| null addenda = fst $ prune bases</code> <- when there's nothing to put in, you check whether the starting bases are already enough and then give up. Shouldn't you then always check whether the starting bases are already enough before involving <code>addenda</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T11:51:21.910",
"Id": "236187",
"ParentId": "236163",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T16:51:09.263",
"Id": "236163",
"Score": "1",
"Tags": [
"haskell",
"music"
],
"Title": "Sequences of given addenda whose sum is equal to a given number"
}
|
236163
|
<p>This is my first working 2sum solver. It works by finding the difference for our <code>target</code> in <code>s</code> to determine if that 2sum exists.</p>
<p>Suppose our <code>target</code> is -5. I start with the first index in <code>s</code> and use subtraction, <strong>(-5-(-8) = 3)</strong>, and the result is 3. The code will check the difference in <code>s</code>. If the difference exists in the list <code>s</code> then the output is yes.</p>
<pre><code>s = [-8,3,5,1,3]
target = -5
for j in range(0, len(s)):
if target-int(s[j]) in s[j+1:len(s)]:
print('yes')
quit()
print('no')
</code></pre>
<p>I fixed a bug where a false yes was returned when <code>int(s[j])</code> was equal to <code>target-int(s[j])</code>. I did this by <code>s[j+1:len(s)]</code> An example would be our <code>target</code> would be 4, but our input for <strong>s</strong> was <code>[2]</code>. It would say yes because <code>int(s[j])</code> was equal to <code>target-int(s[j])</code>.</p>
<p>Is it possible to write this code all in one or two lines of code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:08:21.123",
"Id": "462646",
"Score": "0",
"body": "When mentioning about `target = 4` for `s = [2]` which gives you `yes`, did you describe the wrong case? Because your current approach will output `no` for that input case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:57:45.193",
"Id": "462655",
"Score": "0",
"body": "@RomanPerekhrest I'm stumped on it. I got writer's block. I'll figure out how I should best explain it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T02:14:18.947",
"Id": "462682",
"Score": "0",
"body": "Why the `int(...)` conversions if the inputs are already integers? Is the function meant to also work with non-integer inputs? If so, is the rounding behaviour of `int` really what you want?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T19:27:53.150",
"Id": "462732",
"Score": "2",
"body": "What is the reason you want to write it in one or two lines? I often see code that's really hard to understand just because the developer have prioritized few lines over readability. This causes bugs and maintenance problems. There are of course many good reasons to change the code to few lines, just make sure to not use few lines as a goal."
}
] |
[
{
"body": "<p>Translating your code directly into a one-liner:</p>\n\n<pre><code>s = [-8,3,5,1,3]\ntarget = -5\n\nis_2sum = any(target - s[j] in s[j+1:len(s)] for j in range(len(s)))\nprint(is_2sum)\n</code></pre>\n\n<p>A few notes:</p>\n\n<ul>\n<li><p>The loop is now translated into a generator expression: we record whether every difference is present in the remainder of the list and combine this with <code>any</code>, which will check if the resulting list contains a <code>True</code>.</p></li>\n<li><p>In particular, note that we do <em>not</em> construct a list by list comprehension inside the call to <code>any</code>. Indeed, by using a generator expression we allow for an early exit as soon as a <code>True</code> value is found, potentially speeding up quite a bit the execution on positive instances.</p></li>\n<li><p>Your approach runs in quadratic time. However, this algorithm can be further optimized to run in linear time (see e.g., a similar question on <a href=\"https://cs.stackexchange.com/a/13586/472\">CS.SE</a>).</p></li>\n</ul>\n\n<p>If you are fine with a quadratic time algorithm, another alternative is to brute-force every pair. It is straightforward to generalize such an algorithm to k-sum as well. So just for fun, we might also do:</p>\n\n<pre><code>from itertools import combinations \n\ns = [-8,3,5,1,3]\ntarget = -5\n\nis_2sum = any(sum(p) == target for p in combinations(s, 2))\nprint(is_2sum)\n</code></pre>\n\n<p>As stated, this is not highly scalable, but it should very easy for a beginner to read and to understand (if that matters).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T02:54:55.107",
"Id": "463255",
"Score": "0",
"body": "I was trying to make it a little faster than O(n^2) time by stopping one element short because of `s[j+1:len(s)]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T05:49:25.113",
"Id": "463261",
"Score": "0",
"body": "@TravisWells Such an approach runs in big Omega of n squared, so that won't help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:27:40.207",
"Id": "236167",
"ParentId": "236165",
"Score": "5"
}
},
{
"body": "<ul>\n<li>You should make this a function.</li>\n<li>You should use 4 spaces for indentation.</li>\n<li>If <code>s</code> becomes a count of numbers in a dictionary, then <code>in</code> becomes performs in <span class=\"math-container\">\\$O(1)\\$</span> time, where lists perform in <span class=\"math-container\">\\$O(n)\\$</span> time.</li>\n<li>Using <code>quit</code> isn't really idiomatic, and was added to make exiting the REPL easier.</li>\n<li>Rather than <code>for j in range(0, len(s))</code> you can use <code>for item in s</code>.</li>\n<li>Use better variable names, <code>s</code> and <code>j</code> are just meh.</li>\n<li>You can use a comprehension, with <code>any</code> to reduce noise.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\n\ndef has_two_sum(items, target):\n items = collections.Counter(map(int, items))\n for item in map(int, items):\n remainder = target - item\n if items.get(remainder, 0) >= (2 if item == remainder else 1):\n return True\n return False\n\n\nif has_two_sum(s, target):\n print('yes')\nelse:\n print('no')\n</code></pre>\n\n<p>Or you can write it in on of these one liners, which look like garbage:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>s=collections.Counter(map(int,s));print(['no','yes'][any(map(lambda i:s.get(t-i,0)>=1+(i==t-i),s))])\nf=set();print(['no','yes'][any(map(lambda i:(t-i in f,f.add(i))[0],s))])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T02:16:23.607",
"Id": "462683",
"Score": "0",
"body": "This will have the same bug that the OP described where a number plus itself can equal the target, giving a *\"false yes\"*. You can fix it by putting each number into the set after testing it, instead of putting them all in at the start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T05:15:45.343",
"Id": "462686",
"Score": "0",
"body": "Yes @kaya3, there is that bug indicating insufficient testing. On the other hand I like presenting code that is well formatted rather than golfed into a minimum number of lines. I do have one formatting quibble, I don't like simplistic if/else blocks. `print(f'{\"yes\" if has_two_sums(s,target) else \"no\"}')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T05:49:57.537",
"Id": "462688",
"Score": "1",
"body": "No need for a format string there - `print(\"yes\" if has_two_sums(s, target) else \"no\")` is equivalent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T12:13:51.867",
"Id": "462709",
"Score": "0",
"body": "@kaya3 Ah yes, my last 2 sum didn't have that characteristic. Simple fix."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:35:45.667",
"Id": "236168",
"ParentId": "236165",
"Score": "4"
}
},
{
"body": "<p>I believe this will solve your problem:</p>\n\n<pre><code># Using ternary operator to condense the print's\ntwo_sum = lambda s, target: print('yes') if any(map(lambda x: target-x in s and s.count(x)>1, s)) else print('no')\n\n# If s.count(x) is 1, it means the subtraction resulted in the same element took that time for the operation, which we don't want to happen. So the count must be greater then 1\n\ntwo_sum([-8, 3, 5, 1, 3], -5)\n# Output is \"yes\"\n\ntwo_sum([2], 4)\n# Output is \"no\"\n</code></pre>\n\n<p>So, we wrapped the function in a lambda, used another lambda in the map call and preserved all items in the list, checking if the output matches another element besides the one took in for the calculation.</p>\n\n<h2>Benchmark</h2>\n\n<p>I was wondering if @Juho's answer provided a faster function, so I benchmarked both.</p>\n\n<p>So:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>two_sum = lambda s, target: any(map(lambda x: target-x in s and s.count(x)>1, s))\n\nis_2sum = lambda s, target: any(target - s[j] in s[j+1:len(s)] for j in range(len(s)))\n\n# The print's aren't necessary for the benchmark.\n</code></pre>\n\n<p>Then, I ran both at Google Colab with the following code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>two_sum = lambda s, target: any(map(lambda x: target-x in s and s.count(x)>1, s))\n\nis_2sum = lambda s, target: any(target - s[j] in s[j+1:len(s)] for j in range(len(s)))\n\ntest_function = two_sum\n# test_function = is_2sum\n\nif __name__ == \"__main__\":\n import timeit\n setup = \"from __main__ import test_function\"\n average=0\n for i in range(0,100):\n average=average+timeit.timeit(\"test_function([-8, 3, 1, 5, 1, 3], -5)\", setup=setup, number=1000000)\n print(average/100)\n</code></pre>\n\n<p>The method <code>timeit.timeit()</code> will run each function 1.000.000 times, then I record the outputs of 100 iterations (so, we actually ran the function 100.000.000 times) and take the average.</p>\n\n<h3>Results:</h3>\n\n<p>For the function <code>two_sum</code>:<br>\nFirst run: <code>0.9409843384699957</code><br>\nSecond run: <code>0.948360692339993</code> </p>\n\n<p>For the function <code>is_2sum</code>:<br>\nFirst run: <code>0.9963176720300112</code><br>\nSecond run: <code>0.998327726480004</code> </p>\n\n<p>As you can see, there is an increase in performance for <code>two_sum</code> function, whether this comes from the use of <code>map()</code> and avoiding lists operations, I don't know, but it's a bit faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T01:58:34.890",
"Id": "236269",
"ParentId": "236165",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T17:08:02.773",
"Id": "236165",
"Score": "4",
"Tags": [
"python",
"2sum"
],
"Title": "Working 2sum solver"
}
|
236165
|
<p>I am writing a textual chat app for exercise purposes. All Chatters using my program have access to a network directory, and there my program is stored. This chat app consists of three programs. The user management program allows you to create and delete users. The messaging program allows you to write messages. The viewer program shows all messages.</p>
<p>Now I am about to find a strategy that is good for my viewer program. The code is not ordered yet, I just want to ask if the logic that is behind my code is suitable for a chat viewing program, or if there is a more sophisticated way to create such programs.</p>
<pre><code>import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.File;
public class MessageViewerProgram {
public static void main(String[] args) throws Exception {
String saveDir = ".save/messages/";
int fileName = 1;
File file = new File(saveDir + fileName);
while (true) {
Thread.sleep(50);
if (file.exists()) {
Thread.sleep(20);
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Message message = (Message) ois.readObject();
System.out.println(message.getSenderName() + ": " + message.getMessage());
fileName++;
file = new File(saveDir + fileName);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
</code></pre>
<p>And this here is my "MessageWriterProgram". It is not finished yet, but it works already. I just post it because maybe it is needed to understand the problem, but you dont have to review the following class:</p>
<pre><code>import java.util.Scanner;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class MessageWriterProgram {
public static void main(String[] args) {
MessageWriterProgram mwp = new MessageWriterProgram();
mwp.mainLoop();
}
private static final String SAVE_DIR_NAME = ".save/messages/";
private Scanner scanner = new Scanner(System.in);
private UserManager userManager;
private User identity;
public MessageWriterProgram() {
scanner = new Scanner(System.in);
userManager = new UserManager();
}
public void mainLoop() {
if (!login()) {
System.out.println("Login was not successful.");
return;
}
System.out.println(identity.getName());
while (true) {
System.out.print("> ");
String input = scanner.nextLine();
if (!input.isEmpty()) {
Message message = new Message(identity.getName(), input);
saveMessage(message);
}
}
}
public void saveMessage(Message message) {
// create file name that isn't used
int filename = 1;
while (true) {
File file = new File(SAVE_DIR_NAME + filename);
if (file.exists()) {
filename++;
} else {
break;
}
}
File file = new File(SAVE_DIR_NAME + filename);
// store message
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(message);
} catch (IOException e) {
e.printStackTrace();
}
}
// returns if login was successful
public boolean login() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
identity = userManager.retainUserIdentity(name, password);
return identity != null;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have some suggestions.</p>\n<h2>MessageViewerProgram</h2>\n<ol>\n<li>Instead of brute forcing all the messages in the directory, I suggest that you list them and iterate on them instead. You can use the method <code>java.io.File#listFiles()</code> for this.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>File file = new File(saveDir);\nFile[] files = file.listFiles();\n</code></pre>\n<p>This will give you an array of the files in the message folder, and you can iterate.</p>\n<pre class=\"lang-java prettyprint-override\"><code>File saveDir = new File(".save/messages/");\n\nfor (File currentMessageFile : saveDir.listFiles()) {\n try (FileInputStream fis = new FileInputStream(currentMessageFile);\n ObjectInputStream ois = new ObjectInputStream(fis)) {\n\n Message message = (Message) ois.readObject();\n System.out.println(message.getSenderName() + ": " + message.getMessage());\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n<h2>MessageWriterProgram</h2>\n<ol>\n<li>The initialization of the <code>MessageWriterProgram#scanner</code> variable outside the constructor is useless, it's created inside the constructor already.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private Scanner scanner;\n\npublic MessageWriterProgram() {\n scanner = new Scanner(System.in);\n}\n</code></pre>\n<ol start=\"2\">\n<li>I suggest that you rename the method <code>mainLoop</code> in <code>start</code> or <code>run</code> or even <code>execute</code>.</li>\n</ol>\n<h3><code>MessageWriterProgram#saveMessage</code> method</h3>\n<ol>\n<li><p>Rename the variable <code>filename</code> into <code>fileName</code></p>\n</li>\n<li><p>I suggest that you extract the logic of counting the next file name in a method.</p>\n</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>public void saveMessage(Message message) {\n // create file name that isn't used\n int fileName = getNextFilename();\n //[...]\n}\n\nprivate int getNextFilename() {\n int fileName = getNextFilename();\n\n while (true) {\n File file = new File(SAVE_DIR_NAME + fileName);\n if (file.exists()) {\n fileName++;\n } else {\n break;\n }\n }\n\n return fileName;\n}\n</code></pre>\n<ol start=\"3\">\n<li>Instead of counting the messages in the loop, you can use the <code>java.io.File#listFiles()</code> and check the number of files in the folder.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private int getNextFilename() {\n File messageDirectory = new File(SAVE_DIR_NAME);\n File[] files = messageDirectory.listFiles();\n\n if (files != null) {\n return files.length + 1;\n } else {\n return 1;\n }\n}\n</code></pre>\n<h3><code>MessageWriterProgram#login</code> method</h3>\n<p>In my opinion, this method is a bit useless and add confusion, since it does more than one thing.</p>\n<ul>\n<li>Check if the User is present.</li>\n<li>Update the <code>identity</code> variable.</li>\n</ul>\n<p>If you inline it, it will be more readable and you can convert the <code>identity</code> variable to a local variable.</p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.print("Name: ");\nString name = scanner.nextLine();\nSystem.out.print("Password: ");\nString password = scanner.nextLine();\n\nUser identity = userManager.retainUserIdentity(name, password);\n\nif (identity == null) {\n System.out.println("Login was not successful.");\n return;\n}\n</code></pre>\n<h3>Refactored <code>MessageWriterProgram</code> class</h3>\n<pre class=\"lang-java prettyprint-override\"><code>public class MessageWriterProgram {\n public static void main(String[] args) {\n MessageWriterProgram mwp = new MessageWriterProgram();\n mwp.mainLoop();\n }\n\n private static final String SAVE_DIR_NAME = ".save/messages/";\n\n private Scanner scanner;\n private UserManager userManager;\n\n public MessageWriterProgram() {\n scanner = new Scanner(System.in);\n userManager = new UserManager();\n }\n\n public void mainLoop() {\n System.out.print("Name: ");\n String name = scanner.nextLine();\n System.out.print("Password: ");\n String password = scanner.nextLine();\n\n User identity = userManager.retainUserIdentity(name, password);\n\n if (identity == null) {\n System.out.println("Login was not successful.");\n return;\n }\n\n System.out.println(identity.getName());\n\n while (true) {\n System.out.print("> ");\n String input = scanner.nextLine();\n\n if (!input.isEmpty()) {\n Message message = new Message(identity.getName(), input);\n saveMessage(message);\n }\n }\n }\n\n public void saveMessage(Message message) {\n // create file name that isn't used\n int fileName = getNextFilename();\n\n File file = new File(SAVE_DIR_NAME + fileName);\n\n // store message\n try (FileOutputStream fos = new FileOutputStream(file);\n ObjectOutputStream oos = new ObjectOutputStream(fos)) {\n oos.writeObject(message);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private int getNextFilename() {\n File messageDirectory = new File(SAVE_DIR_NAME);\n File[] files = messageDirectory.listFiles();\n\n if (files != null) {\n return files.length + 1;\n } else {\n return 1;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T17:38:32.377",
"Id": "463006",
"Score": "0",
"body": "That's an excellent code review, just wow!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T00:32:29.633",
"Id": "236178",
"ParentId": "236166",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T19:16:29.333",
"Id": "236166",
"Score": "3",
"Tags": [
"java",
"console",
"chat"
],
"Title": "Chat Viewer working with files"
}
|
236166
|
<p>I recently had to submit my 12th grade final project in C++, so I decided to make a game engine! That panned out just as you would expect (I am not touching OpenGL until they touch OOP), so I switched and ended up making a project on graph coloring instead!</p>
<p>For context, in the actual project this was used to calculate an exam schedule for a list of students read from a file, but I will not be including that since it would make things too long.</p>
<p>Did I follow good coding practices and make my teacher proud? Note that using STL was not the point of the project.</p>
<p>BTW, can anyone calculate the time complexity of this graph-coloring algorithm (in terms of the <span class="math-container">\$O(\ldots{})\$</span> notation)? I have no idea .</p>
<p>Here is some further context:</p>
<ol>
<li>There is a literal limit on how advanced this code can be. My board doesn't specify a version, so all teachers default to (shock, and horror! ⊂(゜Д゜⊂) ) <em>Turbo C++</em>. It is a miracle I could sneak in templates.</li>
<li>There are actually 40 other scripts where I had to make a <a href="/questions/tagged/linked-list" class="post-tag" title="show questions tagged 'linked-list'" rel="tag">linked-list</a> twice, so you know where I copied it from. The graph code is virgin fresh tho.</li>
<li>If you feel like it, compile it! Here is <a href="https://github.com/Uchiha-Senju/practicals/blob/master/xii/sir_practical_scripts/final_project/test.cpp" rel="nofollow noreferrer" title="Links to the final project's test script">some test code</a>(compiled with G++ 7.3.0) for a graph of integers. The repo also has the final project and the other scripts, so please do check them out too, if you are up to it!</li>
</ol>
<p><hr>
<strong>graph.h</strong></p>
<pre><code>#if !defined(VARAD_GRAPH_H_INCLUDED)
#define VARAD_GRAPH_H_INCLUDED
#include "list.h"
namespace graph_h {
// Add const to type if it is a pointer
template <class T>
struct AddConstToType {
typedef T type;
};
template <class T>
struct AddConstToType<T*> {
typedef const T* type;
};
template <class T>
class BinaryFunctor {
public :
virtual bool function(const typename AddConstToType<T>::type& a, const typename AddConstToType<T>::type& b) const = 0;
inline bool operator()(const typename AddConstToType<T>::type& a, const typename AddConstToType<T>::type& b) const {
return function(a, b);
}
};
}
template <class T>
class Graph {
public :
class Vertex {
public :
T data;
List<Vertex*> edges;
// Vertex Constructors
Vertex() : data(), edges() {}
// Weird cast of const T new_data to T so that it can be copied to data
Vertex(const typename graph_h::AddConstToType<T>::type& new_data) : data((T)new_data), edges() {}
Vertex(const typename graph_h::AddConstToType<T>::type& new_data, Vertex** edge_list, unsigned int edge_count)
: data((T)new_data), edges(edge_list, edge_count) {}
Vertex(const Vertex& old_vertex) : data(old_vertex.data), edges(old_vertex.edges) {}
// Equivalence checks are dependent on the Vertex data, not the edges
inline bool operator==(const Vertex& other_vertex) const {
return data == other_vertex.data;
}
inline bool operator!=(const Vertex& other_vertex) const {
return not (*this == other_vertex.data) ;
}
// Functions for edge management
bool isConnected() const {
return edges.len() != 0;
}
bool isConnectedWithVertex(const Vertex* const other_vertex) const {
if (other_vertex != nullptr and other_vertex != this)
return edges.includes(other_vertex) != -1;
return false;
}
bool isConnectedWithVertex(const Vertex& other_vertex) const {
return isConnectedWithVertex(&other_vertex);
}
void connectTo(const Vertex* const other_vertex) {
if (other_vertex != nullptr and other_vertex != this) {
if (edges.includes(other_vertex) == -1)
edges.append(other_vertex);
}
}
void disconnectFrom(const Vertex* const other_vertex) {
if (other_vertex != nullptr and other_vertex != this) {
int i = edges.includes(other_vertex);
if (i != -1)
edges.remove(i);
}
}
void connectTo(const Vertex& other_vertex) {
connectTo(&other_vertex);
}
void disconnectFrom(const Vertex& other_vertex) {
disconnectFrom(&other_vertex);
}
// Vertex Destructor
~Vertex() {
data.~T();
for (typename List<Vertex*>::Iterator connected_vertex(edges); not connected_vertex.hasEnded(); connected_vertex++)
connected_vertex()->disconnectFrom(this);
edges.~List();
}
};
List<Vertex> vertices;
Graph() : vertices() {}
Graph(Graph& old_graph) : vertices(old_graph.vertices) {}
void makeVertex(const typename graph_h::AddConstToType<T>::type& data) {
vertices.append(Vertex(data));
}
void removeVertex(unsigned int index) {
vertices.remove(index);
}
void connectVertices(unsigned int i_1, unsigned int i_2) {
Vertex* v_1 = &(vertices[i_1]);
Vertex* v_2 = &(vertices[i_2]);
if (v_1 == v_2 or v_1 == nullptr or v_2 == nullptr)
return;
v_1->connectTo(v_2);
v_2->connectTo(v_1);
}
void disconnectVertices(unsigned int i_1, unsigned int i_2) {
Vertex* v_1 = &(vertices[i_1]);
Vertex* v_2 = &(vertices[i_2]);
if (v_1 == v_2 or v_1 == nullptr or v_2 == nullptr)
return;
v_1->disconnectFrom(v_2);
v_2->disconnectFrom(v_1);
}
void makeConnections(const graph_h::BinaryFunctor<T>& func) {
// Cycle through each possible vertex pair and connect them
// if the given function returns true
for (typename List<Vertex>::Iterator i(vertices); not i.hasEnded(); i++)
for (typename List<Vertex>::Iterator j = i + 1; not j.hasEnded(); j++)
if (func(i().data, j().data)) {
i().connectTo(j());
j().connectTo(i());
}
}
List<List<Vertex*>> colorVertices() {
List<List<Vertex*>> color_list;
for (typename List<Vertex>::Iterator i(vertices); not i.hasEnded(); i++) {
typename List<List<Vertex*>>::Iterator color(color_list);
// Determine if vertex is connected to any other colored vertex
bool is_connected = true;
// Come out color-checking loop if colors have run out or
// the current vertex is not connected to any vertex of the given color
// Don't increment color if none are connected
for (; not (color.hasEnded() or not is_connected); is_connected ? color++ : color)
// Come out of vertex-connection-checking loop
// if there are no more vertices to check or
// the current vertex is connected to any vertex of the given color
for (typename List<Vertex*>::Iterator j( (is_connected = false, color()) ); not (j.hasEnded() or is_connected); ++j)
is_connected |= i().isConnectedWithVertex(j());
// If current vertex was not connected to any in the last color,
// switch back to it
if (color.hasEnded() and not is_connected)
color.last();
if (not color.hasEnded()) {
// Color the vertex if an unconnected color was found
color().append(&i());
} else {
// Make a new color if the vertex is connected to all the current colors
List<Vertex*> new_color;
new_color.append(&i());
color_list.append(new_color);
}
}
return color_list;
}
};
#endif
</code></pre>
<p><hr>
<strong>list.h</strong></p>
<pre class="lang-c++ prettyprint-override"><code>#if !defined(VARAD_LIST_H_INCLUDED)
#define VARAD_LIST_H_INCLUDED
namespace list_h {
const int check_num = 0x1234abcd;
// Make type const if it is a pointer
template <class T>
struct AddConstToType {
typedef T type;
};
template <class T>
struct AddConstToType<T*> {
typedef const T* type;
};
template <class T>
class BinaryFunctor {
public :
virtual bool function(const typename AddConstToType<T>::type& a, const typename AddConstToType<T>::type& b) const = 0;
inline bool operator()(const typename AddConstToType<T>::type& a, const typename AddConstToType<T>::type& b) const {
return function(a, b);
}
};
}
template <class T>
class List {
protected :
class Node {
public :
T data;
Node* next;
Node* previous;
const int check;
Node() : check(list_h::check_num) {}
// Weird cast of const T new_data to T so that it can be copied to data
Node(const typename list_h::AddConstToType<T>::type& new_data, Node* prev, Node* nxt = nullptr)
: check(list_h::check_num), data((T)new_data), previous(prev), next(nxt) {}
Node(Node* prev) : check(list_h::check_num), previous(prev), next(nullptr) {}
Node(const Node& old_node, Node* prev = nullptr) : Node(old_node.data, prev) {}
~Node() {
data.~T();
next = previous = nullptr;
}
bool isOk() const {
return check == list_h::check_num;
}
Node* makeNext(const typename list_h::AddConstToType<T>::type& new_data) {
Node* new_next = new Node(new_data, this);
if (new_next != nullptr) next = new_next;
return new_next;
}
Node* makeNext() {
Node* new_next = new Node(this);
if (new_next != nullptr) next = new_next;
return new_next;
}
};
Node* first;
Node* last;
unsigned int length;
Node* getNode(int index) const {
if (length == 0)
index = 0;
else if (index < 0)
index = index % length + length;
else
index = index % length;
Node* cur;
if (2 * index < length) {
cur = first;
for (int i = 1; i <=index; i++) {
cur = cur->next;
}
} else {
cur = last;
for (int i = length - 2; i >= index; i--) {
cur = cur->previous;
}
}
return cur;
}
void reCalculateLength() {
length = 0;
for(Node* read_head = first; read_head != nullptr; read_head = read_head->next, ++length);
}
public:
class Iterator {
friend class List;
const List& parent_list;
Node* current;
public :
int position;
private :
// Custom Constructor for exact copying
Iterator(const List& pops, Node* cur, int pos) : parent_list(pops), current(cur), position(pos) {}
public :
// Basic functions
void first() {
current = parent_list.first;
position = 0;
}
void last() {
current = parent_list.last;
position = parent_list.length - 1;
}
Iterator(const List& papa, bool start_at_first = true) : parent_list(papa) {
if (start_at_first)
first();
else
last();
};
// Constructors
Iterator(const Iterator& i) : parent_list(i.parent_list), current(i.current), position(i.position) {}
Iterator& operator=(const Iterator& i) {
if (&parent_list == &(i.parent_list)) {
current = i.current;
position = i.position;
}/* else {
~Iterator();
new(this) Iterator(i);
}*/
return *this;
}
bool hasEnded() const {
return current == nullptr or position >= parent_list.length or position < 0;
}
bool operator==(const Node* const node) const {
return current == node;
}
bool operator==(const Iterator& i) const {
return current == i.current;
}
bool operator!=(const Node* const node) const {
return not current == node;
}
bool operator!=(const Iterator& i) const {
return not current == i.current;
}
Iterator& operator++() {
if (current != nullptr) current = current->next;
++position;
return *this;
}
Iterator& operator++(int) {
return ++(*this);
}
inline Iterator& operator--() {
if (current != nullptr) current = current->previous;
--position;
return *this;
}
inline Iterator& operator--(int) {
return --(*this);
}
Iterator operator+(int index) {
Node* new_current = current;
if (index < 0)
for(int i = index; i < 0; i++) {
new_current = new_current->previous;
if (new_current == nullptr)
break;
}
else
for (int i = index; i > 0; i--) {
new_current = new_current->next;
if (new_current == nullptr)
break;
}
return Iterator(parent_list, new_current, position + index);
}
inline Iterator operator-(int i) {
return *this + (-i);
}
T& operator()() const {
return current->data;
}
};
// Basic Functions
inline unsigned int len() const {
return length;
}
T& operator[] (int index) const {
return getNode(index)->data;
}
bool append(const typename list_h::AddConstToType<T>::type& new_data) {
if (last == nullptr) {
last = new Node(new_data, nullptr);
first = last;
if (last == nullptr)
return false;
} else {
Node* new_last = last->makeNext(new_data);
if (new_last == nullptr) return false;
last = new_last;
}
++length;
return true;
}
bool prepend(const typename list_h::AddConstToType<T>::type& new_data) {
if (last == nullptr) {
first = last = new Node(new_data, nullptr);
if (first == nullptr)
return false;
} else {
Node* new_node = new Node(new_data, nullptr);
if (new_node == nullptr)
return false;
new_node->next = first;
first->previous = new_node;
first = new_node;
}
++length;
return true;
}
private :
void removeByPointer(Node* node) {
if (node == nullptr)
return;
// Neighbour management
if (node->next != nullptr) node->next->previous = node->previous;
if (node->previous != nullptr) node->previous->next = node->next;
// Boundary conditions
if (node == first)
first = node->next;
if (node == last)
last = node->previous;
// Guillotine
delete node;
--length;
}
public :
void remove(unsigned int index) {
removeByPointer(getNode(index));
}
void remove(Iterator iter) {
if (not iter.hasEnded())
removeByPointer(iter.current);
}
// Constructors
List() : first(nullptr), last(nullptr), length(0) {}
List(const T* const data_arr, unsigned int len) : List() {
for (int i = 0; i < len; ++i)
if (not append(data_arr[i]))
break;
}
List(unsigned int len) : List() {
length = len;
first = new Node(nullptr);
if (first == nullptr)
return;
last = first;
for (int i = 1; i < length; ++i) {
Node* new_last = last->makeNext();
if (new_last == nullptr)
i = length;
else
last = new_last;
}
}
List& operator=(const List& old_list) {
length = old_list.length;
if (length != 0) {
for (Iterator i(old_list); not i.hasEnded(); ++i)
if (not append(i()))
break;
} else {
first = last = nullptr;
}
return *this;
}
List(const List& old_list) : List() {
*this = old_list;
}
~List() {
if (length != 0) {
for (Iterator i(*this, false); not i.hasEnded(); ) {
Node* current = i.current;
--i;
delete current;
}
first = last = nullptr;
}
}
bool insert(unsigned int index, const typename list_h::AddConstToType<T>::type& new_data) {
if (index == length)
return append(new_data);
else if (index == 0)
return prepend(new_data);
Node* cur = getNode(index);
if (cur == nullptr)
return false;
Node* new_node = new Node(new_data, nullptr);
if (new_node == nullptr)
return false;
new_node->next = cur;
new_node->previous = cur->previous;
if (new_node->previous != nullptr) new_node->previous->next = new_node;
cur->previous = new_node;
++length;
}
void truncate(int end) {
// Domain folding
if (length == 0)
end = 0;
else if (end < 0)
end = end % length + length;
else
end = end % length;
Iterator i(*this);
for ( i.last(); not i.hasEnded() and i.position >= end; ) {
Node* current = i.current;
--i;
delete current;
}
// Loose ends management
last = i.current;
if (i.current != nullptr) i.current->next = nullptr;
length = end;
}
void slice(int start, int end, unsigned int step = 1) {
// Domain folding
if (length == 0)
end = 0;
else if (end < 0)
end = end % length + length;
else
end = end % length;
if (length == 0)
start = 0;
else if (start < 0)
start = start % length + length;
else
start = start % length;
if (start >= end)
return;
truncate(end);
Iterator i(*this);
for ( i.first(); not i.hasEnded() and i.position < start; ) {
Node* current = i.current;
++i;
delete current;
}
// Loose ends management
first = i.current;
if (i.current != nullptr) i.current->prev = nullptr;
length -= start;
// No iterators here because the list is dynamically changing
if (step != 1 or step != 0) {
for (int i = 0, offset = 0; i < length; ++i) {
if ((i + offset) % step != 0) {
remove(i);
++offset; --i;
}
}
reCalculateLength();
}
}
void swap(unsigned int i_1, unsigned int i_2) {
Node* temp;
// Ensure that i_1 <= i_2
if (i_1 > i_2) {
unsigned int temp = i_1;
i_1 = i_2;
i_2 = temp;
}
if (i_1 == i_2) return;
Node* node_1 = getNode(i_1);
Node* node_2 = getNode(i_2);
if (node_1 == nullptr or node_2 == nullptr)
return;
// Check if list markers need to be changed
if (i_1 == 0)
first = node_2;
else if (i_1 == length - 1)
last = node_2;
if (i_2 == 0)
first = node_1;
else if (i_2 == length - 1)
last = node_1;
// Alternate behaviour for adjacent swaps
if (i_1 + 1 == i_2) {
node_1->next = node_2->next;
node_2->previous = node_1->previous;
node_1->previous = node_2;
node_2->next = node_1;
if (node_1->next != nullptr) node_1->next->previous = node_1;
if (node_2->previous != nullptr) node_2->previous->next = node_2;
return;
}
// Standard swap behaviour
temp = node_1->previous;
node_1->previous = node_2->previous;
node_2->previous = temp;
temp = node_1->next;
node_1->next = node_2->next;
node_2->next = temp;
// Correct neighbours addresses
if (node_1->next != nullptr) node_1->next->previous = node_1;
if (node_1->previous != nullptr) node_1->previous->next = node_1;
if (node_2->next != nullptr) node_2->next->previous = node_2;
if (node_2->previous != nullptr) node_2->previous->next = node_2;
}
void sort(const list_h::BinaryFunctor<T>& func) {
class Dummy {
public :
void quickSort(List& arr, unsigned int start, unsigned int end, const list_h::BinaryFunctor<T>& func) {
if (end - start <= 1)
return;
int pivotIndex = start;
for (int i = start; i < end - 1; ++i) {
if (func(arr[i], arr[end - 1])) {
arr.swap(i, pivotIndex);
++pivotIndex;
}
}
arr.swap(pivotIndex, end - 1);
quickSort(arr, start, pivotIndex, func);
quickSort(arr, pivotIndex + 1, end, func);
}
} dummy_dum_dum;
dummy_dum_dum.quickSort(*this, 0, length, func);
}
int includes(const typename list_h::AddConstToType<T>::type& search_data) const {
for (Iterator i(*this); not i.hasEnded(); i++)
if (i() == search_data and i.position < length)
return i.position;
return -1;
}
};
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T21:47:20.000",
"Id": "462664",
"Score": "5",
"body": "Maybe it makes your teacher proud, but frankly it is a bit annoying that students are still asked to reimplement standard library functions. The result is almost always poor, and that's not because of a fault of yours, but because you are being asked to reimplement something from scratch in just a week or two what lots of standard library developers have been working on for decades. It would be better if you could have two separate reviews: one for your `List`, and one for a `Graph` implementation that uses `std::list`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T10:36:07.557",
"Id": "462699",
"Score": "0",
"body": "@G.Sliepen I must confess I don't actually know STL as of yet (●﹏●)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T03:13:26.930",
"Id": "462762",
"Score": "1",
"body": "Hi Varad, welcome to Code Review! 1) Please always remember to tag the main language tag (`c++`) in addition to the specific version `c++11`. This is because tags are used for searching and many other related mechanisms. For example, people who follow the `c++` tag may miss your question if you tag `c++11` only. (I should have updated my watch list to `c++*`!) 2) Did *you* compile your code using Turbo-C++ or a modern compiler? Please clarify in your question. 3) Your github link gives me Page not found ... Make sure you've made your project public."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T09:56:08.337",
"Id": "462798",
"Score": "0",
"body": "@L.F. Forgot about the repository being private "
}
] |
[
{
"body": "<p>That's a <em>lot</em> of code. Consider just using STL? ;)</p>\n\n<p>Seriously, though, you wrote an entire <code>List</code> utility class, almost 500 lines of code, and:</p>\n\n<ul>\n<li><p>It doesn't work anything like <code>std::list</code>, so any coworker of yours (e.g., me) can't use their existing knowledge base to understand it.</p></li>\n<li><p>Your own code doesn't use half of the functionality you implemented (e.g., <code>slice</code> and <code>sort</code>). So those bits were wasted effort.</p></li>\n<li><p>Since you don't use that code, <em>and</em> I'm assuming you wrote no unit tests for it, the code probably doesn't work at all. Code that is unused and untested should be ripped out. Code that is <em>used</em> but untested... should be tested!</p></li>\n</ul>\n\n<p>To expand on that first point, the unfamiliar API: It looks like the way you iterate over a <code>list_h::List<T></code> is like this—</p>\n\n<pre><code>Iterator i(myList);\nfor (i.first(); not i.hasEnded(); ++i) {\n const T& elt = i.current->data;\n do_something_with(elt);\n}\n</code></pre>\n\n<p>Compare this to the way we iterate over a <em>standard</em> container:</p>\n\n<pre><code>for (const T& elt : myList) {\n do_something_with(elt);\n}\n</code></pre>\n\n<p>The standard containers can all be used with range-<code>for</code>-loops because they implement iterators with the standard interface: initialized with the return values of <code>myList.begin()</code> and <code>myList.end()</code>, compared with <code>==</code>, dereferenced with <code>*</code>, and incremented with <code>++</code>. Of that checklist, the only part you successfully copied was \"incremented with <code>++</code>.\"</p>\n\n<hr>\n\n<p>Serious bug: Your destructors are all wrong. This indicates strongly to me that you have never tested this code.</p>\n\n<pre><code>~Node() {\n data.~T();\n next = previous = nullptr;\n}\n</code></pre>\n\n<p>If you construct and then destroy a <code>Node<std::unique_ptr<int>></code>, you'll find that the allocation is deleted twice (that's a \"double-free bug\"). Your hand-written destructor does not need to manually destroy the members (or base classes) of <code>Node</code>, any more than you ever need to manually destroy the local variables in the stack frame of a function.</p>\n\n<blockquote>\n <p>Rule of thumb for 12th-graders: never, ever write <code>foo.~Bar()</code>. (Okay, let me revise that to allow for experimentation. Never write <code>foo.~Bar()</code> and expect the code to actually work correctly!)</p>\n</blockquote>\n\n<p>You don't need to set <code>next = previous = nullptr;</code> either. It doesn't matter what value those members have, given that they're going to be destroyed either way.</p>\n\n<hr>\n\n<p>Your namespaces are weird. Did your teacher tell you that <code>list.h</code> should put everything in <code>namespace list_h</code>, and <code>graph.h</code> should put everything in <code>namespace graph_h</code>? In the real world, we'd do something more like</p>\n\n<pre><code>// varad_list.h\nnamespace varad {\n template<class T> class List { ... };\n}\n\n// varad_graph.h\nnamespace varad {\n template<class T> class Graph { ... };\n}\n</code></pre>\n\n<p><a href=\"https://quuxplusone.github.io/blog/2020/01/07/namespaces-are-for-preventing-name-collisions/\" rel=\"noreferrer\">Namespaces are for preventing name collisions.</a> When I see a repetitive redundant repetitive name like <code>graph_h::Graph</code>, I know something's wrong. On the other hand, the name <code>varad::Graph</code> actually tells me something in C++ese. \"It's a <code>Graph</code> class. Whose <code>Graph</code> class? The <code>Graph</code> class that belongs to <code>varad</code>.\"</p>\n\n<hr>\n\n<p>Again showing that you never compiled this code:</p>\n\n<pre><code> bool operator!=(const Node* const node) const {\n return not current == node;\n }\n</code></pre>\n\n<p>Suppose <code>current</code> is <code>(Node*)0x12345678</code>. Then what is <code>not current</code>?— Right, it's the boolean <code>false</code>. Can you compare a <code>bool</code> with a pointer? Nope.</p>\n\n<hr>\n\n<p>Finally (although there's much much more to unpack here), I want to talk about <code>BinaryFunctor</code>.</p>\n\n<pre><code>// Make type const if it is a pointer\ntemplate <class T>\nstruct AddConstToType {\n typedef T type;\n};\ntemplate <class T>\nstruct AddConstToType<T*> {\n typedef const T* type;\n};\n\ntemplate <class T>\nclass BinaryFunctor {\n public :\n virtual bool function(const typename AddConstToType<T>::type& a, const typename AddConstToType<T>::type& b) const = 0;\n inline bool operator()(const typename AddConstToType<T>::type& a, const typename AddConstToType<T>::type& b) const {\n return function(a, b);\n }\n};\n\nvoid sort(const list_h::BinaryFunctor<T>& func) {\n [...]\n}\n</code></pre>\n\n<p>Your <code>AddConstToType</code> doesn't do anything except break your code for non-const-qualified pointers. (Again, you never compiled this code to test it.) If I make a <code>List<int*></code> and then try to <code>.sort</code> it, I'll just get a bunch of errors about how an lvalue of type <code>int*</code> cannot be bound to a reference of type <code>const int*&</code>.</p>\n\n<p>Your <code>BinaryFunctor</code> uses something kind of like the Non-Virtual Interface Idiom, which is cool; but to get all the way there, you should make <code>virtual bool function</code> a <code>private</code> method. Nobody should ever be calling it directly, right? They should be going via the public <code>operator()</code>. And derived classes don't need access to <code>virtual bool function</code> either — they can override a private method just as easily as they can override a public one.</p>\n\n<p>But really you shouldn't have <code>BinaryFunctor</code> at all. C++ already has first-class \"function objects\" — lambdas, and pointers to functions, and <code>std::function<bool(const T&)></code> objects, and so on and so forth. You seem to want a <code>List<T>::sort(F)</code> that can accept <em>any kind of</em> predicate type <code>F</code>, just like <code>List<T></code> can accept <em>any kind of</em> object type <code>T</code>. You already know how to express that in C++. Use a template!</p>\n\n<pre><code>template<class F>\nvoid sort(const F& func) {\n [...]\n}\n</code></pre>\n\n<p>And then don't reinvent <code>quickSort</code>. (I guarantee that your implementation is wrong. I don't know how, but I'm confident that if you write a bunch of unit tests, you'll find out pretty quick.) Just use <code>std::sort</code>.</p>\n\n<p>Or, as I implied at the beginning of this review: just delete the entire <code>sort</code> function. You never use it! And code that is unused and untested <em>never works.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T11:14:26.697",
"Id": "462703",
"Score": "0",
"body": "Thanks for answering! I do agree with all that you have said (the `operator!=(`~`Node`~ `Iterator)` was embarrassing TBH), but I do have a couple of nitpicks : 1) Intended interface for `Iterator` is `Iterator i(MyList); typeof(T) == typeof(i())`. `current` is private, it's just that `List` is a friend. 2) `AddConstToType` explicitly exists to allow for `const&` to pointer types. [Link to source](https://stackoverflow.com/questions/16150738/c-passing-a-const-pointer-by-const-reference). (1/2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T11:15:55.300",
"Id": "462704",
"Score": "0",
"body": "3) Sure, maybe no one _needs_ to access `BinaryFunctor::function`, but surely no harm could be incurred by leaving it there, right? _Right?_ (2/2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T11:26:28.687",
"Id": "462705",
"Score": "0",
"body": "Comment Edit: Maybe I should add a cast to `T` for `List<T>::Iterator`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T16:16:09.043",
"Id": "462720",
"Score": "1",
"body": "2) Huh! Today I learned that C++ apparently lets you type-pun between pointer types that differ only in `const`, as long as you promise not to modify the type-punned object. That's a little scary. https://godbolt.org/z/-pY_OD 3) Unused and untested source code is _always_ \"harm.\" Not only do I have to read and think about it, I might also be tempted to use it (and then find out later that it doesn't work). The smaller your codebase, the easier it is to work with."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:03:33.270",
"Id": "236174",
"ParentId": "236170",
"Score": "11"
}
},
{
"body": "<p>A few notes to add to the existing answer(s):</p>\n\n<ul>\n<li><p>It is not wrong use <code>not</code> in place of <code>!</code> but I'd like to claim that most programmers will find it odd. Shorthand operators are much more common and likely make parsing the code faster for most readers.</p></li>\n<li><p>It appears that your algorithm is not exact (i.e., it is not guaranteed to find an optimal coloring for every possible input). Rather, it looks to be the well-known greedy heuristic that goes through the vertices in some order, and always assigns to each vertex the lowest available color. As such, in principle, it can be implemented to run in linear time but I'm not certain what the complexity of all your <code>List</code> methods for example are.</p></li>\n<li><p>Your internal storage for a graph is definitely not optimal. That is, your lists rely on pointers and there is no guarantee consecutive elements would be stored consecutively in memory (i.e., we should expect cache misses when accessing elements in your list). Storing and processing large graphs with your implementation will likely be slow. If you are curious about a faster implementation, you can have a look at <a href=\"https://codereview.stackexchange.com/a/219748/40063\">my earlier graph related answer here</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T11:06:50.417",
"Id": "236185",
"ParentId": "236170",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T20:34:45.880",
"Id": "236170",
"Score": "10",
"Tags": [
"c++",
"c++11",
"linked-list",
"reinventing-the-wheel",
"graph"
],
"Title": "Graph coloring project in C++"
}
|
236170
|
<p>I have an interface under development using an object-based approach. Objects should be statically allocated by the application writer (Dynamic memory allocation is not allowed). I want to obfuscate the object data so the application writer can only access the struct members using the provided methods. So I came to this</p>
<pre><code>typedef struct{ /*this its the object private data*/
uint32_t Parameter;
uint8_t Value;
void *owner
size_t length;
}__xObject_Private_data_t;
typedef struct{ /*this is the object definition*/
uint8_t xPrivateData[ sizeof(__xObject_Private_data_t) ]; /*data masked with a raw memory block*/
}xObject_t;
</code></pre>
<p>object methods follow this pattern:</p>
<pre><code>void xObject_SetValue( xObject_t *obj, uint8_t newvalue ){
__xObject_Private_data_t *handler;
if( NULL != obj ){
handler = (__xObject_Private_data_t*)obj->xPrivateData;
handler->Value = newvalue;
}
}
</code></pre>
<p>I deep analyze this implementation keeping this in mind: - Portability - Data padding and alignment - Strict aliasing rules</p>
<p>So far, I consider that everything meets my requirements, however, I would like to have some final concept in case I am missing something before consolidating my solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T02:42:17.997",
"Id": "462684",
"Score": "0",
"body": "Is `__xObject_Private_data_t` defined in the same header as `xObject_t`? If so, the application writer can do the same thing you are to get at the data. If not, how do you intend to keep the actual struct and the data block that is supposed to store it from getting out of sync with their sizes?"
}
] |
[
{
"body": "<p>1201ProgramAlarm rightly comments:</p>\n\n<blockquote>\n <p>Is <code>__xObject_Private_data_t</code> defined in the same header as <code>xObject_t</code>? If so, the application writer can do the same thing you are to get at the data.</p>\n</blockquote>\n\n<p>In other words, your chosen approach is no solution at all.</p>\n\n<p><em>Besides</em>, your chosen approach is buggy! A C data type consists of more than its <code>sizeof</code>. You also have to consider <em>alignment</em>.</p>\n\n<pre><code>struct Bad {\n char pad;\n xObject_t x;\n};\nstruct Good {\n char pad;\n __xObject_Private_data_t x;\n};\n</code></pre>\n\n<p><code>struct Bad</code>'s alignment is <code>1</code>, which means that after your cast to <code>__xObject_Private_data_t</code> you'll find you're getting a lot of misaligned loads and stores (or, on ARM and PowerPC, plain old bus errors).</p>\n\n<p>You seem to be under the impression that double-underscoring an identifier makes it a \"private implementation detail.\" If you trust your users to follow that convention, then you can use a much simpler solution:</p>\n\n<pre><code>typedef struct {\n uint32_t __Private_parameter;\n uint8_t __Private_value;\n void *__Private_owner;\n size_t __Private_length;\n} xObject_t;\n</code></pre>\n\n<p>(Obligatory note that in both C and C++, technically, it's not valid to use double-underscored names if you're not the compiler vendor. Use a single underscore followed by a lowercase letter — <code>_private0_parameter</code> — and you'll be okay.)</p>\n\n<p>To help ensure that your clients don't go poking at <code>_private0_parameter</code>, you can just change its name to <code>_private1_parameter</code> in your next minor release. And then <code>_prviate2_parameter</code> in the release after that. (Heck, keep the misspelling! That will <em>really</em> ensure that nobody wants to touch those data members.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T04:01:35.150",
"Id": "236179",
"ParentId": "236176",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236179",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T22:58:38.550",
"Id": "236176",
"Score": "2",
"Tags": [
"object-oriented",
"c"
],
"Title": "Struct data masking"
}
|
236176
|
<p>I am very confuse what is better approach to display child view and subscribe to its event on ReactiveUI WPF, so far I have 2 implementation that somehow works for my case:</p>
<p><strong>Implementation 1:</strong></p>
<pre><code>public class ChildWindowView
{
public event EventHandler<Exception> Error;
public event EventHandler<bool> Closed;
internal void ShowSomeChild()
{
var vm = new SomeChildViewModel();
var view = new SomeChildView { DataContext = vm };
ChildWindowManager.Instance.Show(view, "Child Title");
Observable.FromEventPattern<Exception>
(h => vm.Error += h, h => vm.Error -= h)
.Subscribe(p => Error?.Invoke(p.Sender, p.EventArgs));
Observable.FromEventPattern<bool>
(h => vm.Close += h, h => vm.Close -= h)
.Subscribe(p => Close?.Invoke(p.Sender, p.EventArgs));
}
internal void ShowOtherChild() { /* Code committed */}
internal void ShowAnotherChild() { /* Code committed */}
}
</code></pre>
<pre><code>public class MainViewModel
{
private readonly ChildWindowView child = new ChildWindowView();
public MainViewModel()
{
// this commmand executed several times during runtime
ShowSomeChild = ReactiveCommand.Create(() => child.ShowSomeChild());
// this commmand executed several times during runtime
ShowOtherChild = ReactiveCommand.Create(() => child.ShowOtherChild());
// this commmand executed several times during runtime
ShowAnotherChild = ReactiveCommand.Create(() => child.ShowAnotherChild());
// handle child view error message
Observable.FromEventPattern<Exception>
(h => child.Error += h, h => child.Error -= h)
.Subscribe(e => /* Error Handling */);
// do something when child closed
Observable.FromEventPattern<bool>
(h => child.Close += h, h => child.Close -= h)
.Subscribe(e => /* Do Something */);
}
}
</code></pre>
<p>As you see, on the first implementation <code>ChildWindowView</code> subscribe to an event on the <code>ChildViewModel</code> before invoking his own Event, this event then subscribed by <code>MainViewModel</code>.</p>
<p>The advantage in this implementation is <code>MainViewModel</code> only need to subscribe to child event once for any child, although <code>ChildWindowView</code> will subscribe to <code>ChildViewModel</code> every time <code>ShowSomeChild()</code> is called.</p>
<p><strong>Implementation 2:</strong></p>
<pre><code>public class ChildWindowView
{
public event EventHandler<Exception> Error;
public event EventHandler<bool> Closed;
internal void ShowSomeChild(SomeChildViewModel vm)
{
var view = new SomeChildView { DataContext = vm };
ChildWindowManager.Instance.Show(view, "Child Title");
}
internal void ShowOtherChild(OtherChildViewModel vm)
{
var view = new OtherChildView { DataContext = vm };
ChildWindowManager.Instance.Show(view, "Child Title");
}
internal void ShowAnotherChild(AnotherChildViewModel vm)
{
var view = new AnotherChildView { DataContext = vm };
ChildWindowManager.Instance.Show(view, "Child Title");
}
}
</code></pre>
<pre><code>public class MainViewModel
{
private readonly ChildWindowView child = new ChildWindowView();
public MainViewModel()
{
// this commmand executed several times during runtime
ShowSomeChild = ReactiveCommand.Create(() =>
{
var vm = new SomeChildViewModel();
// handle child view error message
Observable.FromEventPattern<Exception>
(h => vm.Error += h, h => vm.Error -= h)
.Subscribe(e => /* Error Handling */);
// do something when child closed
Observable.FromEventPattern<bool>
(h => vm.Close += h, h => vm.Close -= h)
.Subscribe(e => /* Do Something */);
child.ShowSomeChild(vm)
});
// this commmand executed several times during runtime
ShowOtherChild = ReactiveCommand.Create(() =>
{
var vm = new OtherChildViewModel();
// handle child view error message
Observable.FromEventPattern<Exception>
(h => vm.Error += h, h => vm.Error -= h)
.Subscribe(e => /* Error Handling */);
// do something when child closed
Observable.FromEventPattern<bool>
(h => vm.Close += h, h => vm.Close -= h)
.Subscribe(e => /* Do Something */);
child.ShowOtherChild(vm)
});
// this commmand executed several times during runtime
ShowAnotherChild = ReactiveCommand.Create(() =>
{
var vm = new AnotherChildViewModel();
// handle child view error message
Observable.FromEventPattern<Exception>
(h => vm.Error += h, h => vm.Error -= h)
.Subscribe(e => /* Error Handling */);
// do something when child closed
Observable.FromEventPattern<bool>
(h => vm.Close += h, h => vm.Close -= h)
.Subscribe(e => /* Do Something */);
child.ShowAnotherChild(vm)
});
}
}
</code></pre>
<p>On the second implementation, I move child vm creation and event subscribtion to MainViewModel, but I lose central subscribtion that can handle all close event from any child.</p>
<p>And here is the <code>ChildWindowManager</code> that used to display child view on both implementation</p>
<pre><code>public class ChildWindowManager : ReactiveObject
{
public static ChildWindowManager Instance { get { return lazy.Value; } }
private static readonly Lazy<ChildWindowManager> lazy =
new Lazy<ChildWindowManager>(() => new ChildWindowManager());
[Reactive] public string Title { get; set; }
[Reactive] public bool IsOpen { get; set; }
[Reactive] public FrameworkElement XmlContent { get; set; }
ChildWindowManager ()
{
XmlContent = null;
}
public void Show(FrameworkElement content, string title)
{
XmlContent = content;
Title = title;
IsOpen = true;
}
public async void Close()
{
IsOpen = false;
XmlContent = null;
}
}
</code></pre>
<p>Or maybe someone have better solutions.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T09:41:34.493",
"Id": "236183",
"Score": "6",
"Tags": [
"c#",
"system.reactive"
],
"Title": "Display Child View and Subscribe to its event on ReactiveUI"
}
|
236183
|
<p>I am learning C and therefore decided to build my own, little shell. Currently I am concerned with input parsing. I want to split a line of text into tokens with delimiters. But it should be possible to escape the delimiter.</p>
<p>A simple example would be:</p>
<pre class="lang-none prettyprint-override"><code>Input: "echo Hello World"
Output: [echo, Hello, World] with n=3 tokens
Input: "echo "Hello World""
Output: [echo, "Hello World"] with n=2 tokens
</code></pre>
<p>My current solution seems to work. But because I am coming from Python I fear to miss something out (e.g. memory leak or pointer error).</p>
<p>I appreciate any sorts of feedback (style, comments, performance, etc).</p>
<p><strong>NOTE</strong>: The methods <code>str_list_cat</code> and <code>print_2D</code> are only debugging methods. I am mainly concerned about <code>tokenize</code>.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 2
#define NEWLINE '\n'
/**
* Read user input from STDIN.
*
* Stores the input into a self growing buffer.
*/
char *read_line()
{
int buf_size = BUF_SIZE;
int cur_index = 0;
char cur_char;
char *buffer = malloc(buf_size * sizeof(char));
/* Could not allocate enough memory */
if (buffer == NULL)
{
return NULL;
}
/* Store the input char by char */
while (1)
{
cur_char = (char) getchar();
/* Line end reached. Store tailing 0x0 byte and break */
if (cur_char == EOF || cur_char == NEWLINE)
{
buffer[cur_index] = '\0';
return buffer;
}
buffer[cur_index++] = cur_char;
/* Reallocate memory if the buffer is full */
if (cur_index >= buf_size)
{
buf_size += BUF_SIZE;
buffer = realloc(buffer, buf_size);
if (buffer == NULL)
{
return NULL;
}
}
}
}
/**
* Copy of Python's input() method.
* Asks the user for input with a variable question.
*/
char *input(const char *q)
{
printf("%s", q);
char *input = read_line();
return input;
}
/**
* Concat a list of strings to a single string and place a delimiter between each substring.
*/
char *str_list_cat(char **strings, char delimiter)
{
int buf_size = BUF_SIZE;
int cur = 0;
int pos;
int total = 0;
char cur_chr;
char *str;
char *string = malloc(buf_size * sizeof(char));
/* Memory error */
if (string == NULL)
{
return NULL;
}
/* Iterate over string char by char */
while ((str = strings[cur++]) != NULL)
{
pos = 0;
while (1)
{
cur_chr = str[pos++];
/* Place the delimiter between the strings*/
if (cur_chr == '\0')
{
string[total++] = delimiter;
break;
}
/* Store the current char */
string[total++] = cur_chr;
if (total >= buf_size)
{
buf_size += BUF_SIZE;
string = realloc(string, buf_size * sizeof(char));
if (string == NULL)
{
return NULL;
}
}
}
}
/* Override the previous char to remove a tailing delimiter. */
string[--total] = '\0';
return string;
}
/**
* Tokenize a line of text.
* Supported delimiters: Space (' ') and Tab ('\t')
* Escape character: Quote (")
*
* Return: A 2D array of tokens, each with variable width.
*/
char **tokenize(const char *line)
{
/* Buffer sizes for both the current token and the list of tokens */
int token_buf_siz = BUF_SIZE;
int tokens_buf_size = BUF_SIZE;
/* Variables for iterating over line */
char cur_chr;
int cur = 0, escaped = 0;
/* Number of chars in current token */
int tok_pos = 0;
/* Total number of token */
int tot_tok_num = 0;
/* Buffers */
char *token = malloc(token_buf_siz * sizeof(char));
char **tokens = malloc(tokens_buf_size * sizeof(char *));
if (tokens == NULL || token == NULL)
{
return NULL;
}
/* Iterate over line char by char */
while ((cur_chr = line[cur++]) != '\0')
{
/* Check for unescaped delimiters */
if ((cur_chr == ' ' || cur_chr == '\t') && !escaped)
{
if (tok_pos == 0)
{
/* Skip duplicate delimiters */
continue;
}
/* Store the token and grow buffer if necessary */
tokens[tot_tok_num++] = token;
if (tot_tok_num >= tokens_buf_size)
{
tokens_buf_size += BUF_SIZE;
tokens = realloc(tokens, tokens_buf_size * sizeof(char *));
if (tokens == NULL)
{
return NULL;
}
}
/* Reset the token vars and allocate new space */
token[tok_pos] = '\0';
tok_pos = 0;
token_buf_siz = BUF_SIZE;
token = malloc(token_buf_siz * sizeof(char)); // IMPORTANT: Don't forget to free the old tokens later on
if (token == NULL)
{
return NULL;
}
continue;
}
if (cur_chr == '\"')
{
/* Enter/Leave escape mode */
escaped = 1 - escaped;
}
/* Store the char and grow buffer if necessary */
token[tok_pos++] = cur_chr;
if (tok_pos >= token_buf_siz)
{
token_buf_siz += BUF_SIZE;
token = realloc(token, token_buf_siz * sizeof(char));
if (token == NULL)
{
return NULL;
}
}
}
if (tok_pos)
{
if (escaped)
{
/* Catch unclosed escape sequence */
token[tok_pos] = '\0';
}
/* Copy the last token if it exists */
tokens[tot_tok_num++] = token;
if (tot_tok_num >= tokens_buf_size)
{
tokens_buf_size += BUF_SIZE;
tokens = realloc(tokens, tokens_buf_size * sizeof(char *));
if (tokens == NULL)
{
return NULL;
}
}
}
tokens[tot_tok_num] = NULL;
return tokens;
}
/**
* Free a 2D array of strings
*/
void free_2D(char **arr)
{
char *s;
int cur = 0;
while ((s = arr[cur++]) != NULL)
{
free(s);
}
free(arr);
}
void print_2D(char **tokens)
{
printf("%s\n", str_list_cat(tokens, ','));
free_2D(tokens);
}
int main()
{
/* Test */
print_2D(tokenize("echo Hello World"));
print_2D(tokenize("echo \"Hello World\""));
print_2D(tokenize("echo \"Hello World\" "));
print_2D(tokenize(""));
print_2D(tokenize("\"\""));
print_2D(tokenize(" "));
print_2D(tokenize("echo 1 äöü "));
print_2D(tokenize("\"touch index.html;"));
print_2D(tokenize("\ttttttttt sdf \t"));
print_2D(tokenize("cat text.xml | grep foo.bar"));
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T18:24:59.410",
"Id": "462728",
"Score": "3",
"body": "C is not a good languages to express lexemes with. Might be an idea to look at \"Lex\" as a language. You can probably express these rules with about 3 lines of \"Lex\" code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:33:57.697",
"Id": "462810",
"Score": "2",
"body": "Welcome to Code Review! I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>For future reference:</p>\n\n<ol>\n<li><p>Debug code should be embedded in </p>\n\n<pre><code>#ifdef DEBUG\n#endif\n</code></pre></li>\n<li><p>Having live debug code in the program means the code is not ready for code review.</p></li>\n<li><p>Having unused functions such as <code>char *input(const char *q)</code> means the code is not ready for code review.</p></li>\n</ol>\n\n<h2>Performance</h2>\n\n<p>Shells provide the user interface for the operating system; they need to be very fast, therefore character by character input and multiple memory reallocations are not the best way to achieve good performance in shells. The functions <code>malloc()</code> and <code>realloc()</code> are slow because they make system calls to allocate the memory; programs making system calls can be swapped out during the system call depending on system resources and usage. These calls should be minimized when speed is important. Single character input is also slow; reading the full input buffer is much faster, and string manipulation is much faster than input as well.</p>\n\n<p>The C library provides an excellent function to get a line of input from the terminal; this function is <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"nofollow noreferrer\"><code>fgets(char* buffer, size_t buffer_size, FILE *stream)</code></a>. The function <code>fgets()</code> could basically replace the function <code>char *read_line()</code>. The standard include file <code><stdio.h></code> provides a symbolic constant for input buffer sizes; this constant is <code>BUFSIZ</code> and it is defined as the most optimal size for getting input on your operating system. So to replace <code>read_line()</code> properly:</p>\n\n<pre><code>char *input(const char *q)\n{\n printf(\"%s\", q);\n char input_buffer[BUFSIZ];\n int number_of_chars_read = fgets(input_buffer, BUFSIZ, stdin);\n if (number_of_chars_read > 0)\n {\n return strdup(input_buffer);\n }\n\n return NULL;\n}\n</code></pre>\n\n<p>Prior to May 2019, <code>strdup(char *str)</code> was not totally portable, but in May of 2019 it was added to the C programming standard.</p>\n\n<p>The function <code>fgets()</code> properly handles <code>EOF</code> and newlines.</p>\n\n<h2>Complexity</h2>\n\n<p>Functions the size and complexity of <code>char **tokenize(const char *line)</code> are very hard to read, write, debug and maintain. I've had managers that considered any function larger than 10 lines of code to be too big, but I don't quite agree with that; any function that is more than one screen in an editor should be considered too big and too complex. There are a couple of programming principles that apply here: the Single Responsibility Principle and the KISS principle.</p>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a> principle is \"Keep It Simple\", and applies to more than just software development.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</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, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>Following this principle, the function <code>char **tokenize(const char *line)</code> should call multiple functions to implement the tokenization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T20:55:46.317",
"Id": "462738",
"Score": "1",
"body": "I disagree with \"malloc and realloc are slow because they make system calls\". They usually use more intelligent algorithms than just a simple mmap per allocation. For example, on NetBSD, calling `malloc(100)` a million times results in only 117 `mmap` system calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T01:48:27.397",
"Id": "462754",
"Score": "0",
"body": "There's no point in `char *input = strdup(input_buffer); return input;`; just `return strdup(input_buffer);`. Also, any C standard past C11 has not been standardized yet and probably won't even be fully implemented until two years past its standardization date."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T01:49:48.730",
"Id": "462755",
"Score": "0",
"body": "`BUFSIZ` is meant to notify how many characters are available in the buffers of a `FILE *` stream, not as a user buffer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:27:06.380",
"Id": "462807",
"Score": "0",
"body": "I updated my question and implemented some of your suggestions. I knew that there are already functions for reading fromm stdin. But I felt like, I'd be robbing myself the opportunity to learn something, if I used them. I use them now anyway. But only because I know their principles and how they work internally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:09:36.580",
"Id": "462814",
"Score": "2",
"body": "@Leonleon1 You should always use library functions if you can instead of reimplementing them yourself. That's what they're for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:16:24.937",
"Id": "462816",
"Score": "0",
"body": "C11 quote: `BUFSIZ` *expands to an integer constant expression that is the size of the buffer used by the `setbuf` function*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T17:09:37.887",
"Id": "463003",
"Score": "1",
"body": "It's an exaggeration to say that \"*programs making system calls are swapped out during the system call*\"; that's unlikely on a modern platform that has demand paging and/or enough RAM to keep its processes in memory. I'd change that \"*are*\" to \"*could be*\", at most."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T18:40:45.640",
"Id": "463012",
"Score": "0",
"body": "@TobySpeight Is this better? When I started programming in C getting swapped out was not a question, computer resources were very limited."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T16:03:38.437",
"Id": "236193",
"ParentId": "236188",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T12:23:47.233",
"Id": "236188",
"Score": "10",
"Tags": [
"c",
"strings",
"parsing"
],
"Title": "Tokenize a string with escaping"
}
|
236188
|
<p>I have a piece of python code doing fuzzy matching which works very well and is pretty fast. For reference, it uses the following files:</p>
<p><a href="https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv" rel="noreferrer">https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv</a>
<a href="https://raw.githubusercontent.com/nlintz/pyBros/master/sp500/sp500.csv" rel="noreferrer">https://raw.githubusercontent.com/nlintz/pyBros/master/sp500/sp500.csv</a></p>
<pre><code>import csv
from fuzzywuzzy import process
def csv_reader(file, key):
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
return [row[key] for row in reader]
const_data = csv_reader("constituents.csv", "Name")
target_data = csv_reader("sp500.csv", "company")
with open('results_python.csv', 'w', newline='') as csvfile:
fieldnames = ["name", "match_name", "match_score"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in const_data:
match = process.extractOne(row, target_data)
writer.writerow({'name': row, 'match_name': match[0], 'match_score': match[1]})
</code></pre>
<p>This is how it performs:</p>
<pre><code>$ time ./fuzzy.py
./fuzzy.py 19,90s user 0,13s system 97% cpu 20,444 total
</code></pre>
<p>However, my surprise came when I did a pretty similar code in Golang using a port of the <code>fuzzywuzzy</code> library. I want to understand if the slowness of it is related to the way I structure my code, or some deeper reason within the matching library. </p>
<pre><code>package main
import (
"encoding/csv"
"os"
"strconv"
"github.com/paul-mannino/go-fuzzywuzzy"
)
func readCsv(file string) [][]string {
csvFile, _ := os.Open(file)
defer csvFile.Close()
r := csv.NewReader(csvFile)
records, _ := r.ReadAll()
return records
}
func main() {
original:= readCsv("constituents.csv")
target:= readCsv("sp500.csv")
csvOut, _ := os.Create("results_go.csv")
csvwriter := csv.NewWriter(csvOut)
var targetData []string
for _, line := range target[1:] {
targetData = append(targetData, line[1])
}
csvwriter.Write([]string{"name", "match_name", "match_score"})
for _, line := range original[1:] {
match, _ := fuzzy.ExtractOne(line[1], targetData)
csvwriter.Write([]string{line[1], match.Match, strconv.Itoa(match.Score)})
}
}
</code></pre>
<p>This is how the Go version performs:</p>
<pre><code>$ time ./fuzzy
./fuzzy 75,04s user 1,28s system 98% cpu 1:17,51 total
</code></pre>
<p>Are there any possible bad steps that I took in my Go code that made this comparison slow? Are there any improvements you could suggest to make it perform at the very least to a similar speed as the python code? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T16:30:54.020",
"Id": "462723",
"Score": "0",
"body": "Do you want a review of the Python code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T16:35:28.887",
"Id": "462724",
"Score": "0",
"body": "I was hoping more for a review of the Go version, but if you have some comments about the Python version too, I would also appreciate them."
}
] |
[
{
"body": "<p><strong>Review I - package <code>go-fuzzywuzzy</code></strong></p>\n\n<hr>\n\n<p>After a quick read of your Go code, the Go code for package <code>go-fuzzywuzzy</code>, and the Go documentation, it is reasonable to hope for at least a 60% to 95% improvement in Go performance.</p>\n\n<hr>\n\n<p>For example, </p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m55.183s\nuser 0m58.858s\nsys 0m0.944s\n$\n</code></pre>\n\n<p>After moving one line in package <code>go-fuzzywuzzy</code>,</p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m6.321s\nuser 0m7.211s\nsys 0m0.188s\n$\n</code></pre>\n\n<p>The line to move:</p>\n\n<pre><code>r := regexp.MustCompile(\"[^\\\\p{L}\\\\p{N}]\")\n</code></pre>\n\n<p>A diff of package <code>go-fuzzywuzzy</code>:</p>\n\n<pre><code>diff --git a/stringutility.go b/stringutility.go\nindex 935f6e1..95441cc 100644\n--- a/stringutility.go\n+++ b/stringutility.go\n@@ -5,6 +5,8 @@ import (\n \"strings\"\n )\n\n+var rxCleanse = regexp.MustCompile(\"[^\\\\p{L}\\\\p{N}]\")\n+\n func Cleanse(s string, forceAscii bool) string {\n s = strings.TrimSpace(s)\n s = strings.ToLower(s)\n@@ -12,8 +14,7 @@ func Cleanse(s string, forceAscii bool) string {\n s = ASCIIOnly(s)\n }\n\n- r := regexp.MustCompile(\"[^\\\\p{L}\\\\p{N}]\")\n- s = r.ReplaceAllString(s, \" \")\n+ s = rxCleanse.ReplaceAllString(s, \" \")\n return s\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><a href=\"https://golang.org/pkg/regexp/\" rel=\"nofollow noreferrer\">Package regexp</a></p>\n\n<pre><code> import \"regexp\"\n</code></pre>\n \n <p><a href=\"https://golang.org/pkg/regexp/#MustCompile\" rel=\"nofollow noreferrer\">func MustCompile</a></p>\n\n<pre><code>func MustCompile(str string) *Regexp\n</code></pre>\n \n <p>MustCompile is like Compile but panics if the expression cannot be\n parsed. It simplifies safe initialization of global variables holding\n compiled regular expressions.</p>\n</blockquote>\n\n<p>The documentation clearly says <strong>global</strong> variables.</p>\n\n<hr>\n\n<p>If I spent more time reading the code, I would expect further performance improvements.</p>\n\n<hr>\n\n<hr>\n\n<p>After more reading, package <code>go-fuzzywuzzy</code> is written in \"PyGo.\" Writing the package in Go yields efficiencies.</p>\n\n<p>For example, completely rewriting the <code>go-fuzzywuzzy</code> file <code>stringutility.go</code> in Go.</p>\n\n<p>Before:</p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m55.183s\nuser 0m58.858s\nsys 0m0.944s\n$\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m5.735s\nuser 0m6.601s\nsys 0m0.193s\n$\n</code></pre>\n\n<p><code>stringutility.go</code>:</p>\n\n<pre><code>package fuzzy\n\nimport (\n \"strings\"\n \"unicode\"\n)\n\nfunc Cleanse(s string, forceAscii bool) string {\n if forceAscii {\n s = ASCIIOnly(s)\n }\n s = strings.TrimSpace(s)\n rs := make([]rune, 0, len(s))\n for _, r := range s {\n if !unicode.IsLetter(r) && !unicode.IsNumber(r) {\n r = ' '\n }\n rs = append(rs, r)\n }\n return strings.ToLower(string(rs))\n}\n\nfunc ASCIIOnly(s string) string {\n b := make([]byte, 0, len(s))\n for _, r := range s {\n if r <= unicode.MaxASCII {\n b = append(b, byte(r))\n }\n }\n return string(b)\n}\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>UPDATE:</p>\n\n<p>The package <code>go-fuzzywuzzy</code> author adopted the suggested <code>stringutility.go</code> changes:</p>\n\n<pre><code>[Fixes #4] Stop reinitializing costly regex in stringutility\nhttps://github.com/paul-mannino/go-fuzzywuzzy/commit/f14294bf5858c8a7fa51b026a9ee9a2802c816bf\n\nWas using regexp.MustCompile within a frequently invoked\nmethod Cleanse. Since go does not cache these calls, it was\nincurring a costly regex compilation each time Cleanse was\ncalled. The other changes made in the stackoverflow post that\ncaught this issue seem to further improve performance by\nabout 10% on top of the massive gains from fixing this issue,\nso incorporating those as well.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T20:44:15.797",
"Id": "462736",
"Score": "0",
"body": "You summarized the issues really well! I am just confused about something: What is PyGo?... Couldn't find any reference to it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T20:46:12.277",
"Id": "462737",
"Score": "2",
"body": "I [reported the bad performance](https://github.com/paul-mannino/go-fuzzywuzzy/issues/4) to the author of go-fuzzywuzzy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T23:10:51.493",
"Id": "462746",
"Score": "3",
"body": "And, only 2 hours later, it's fixed, so after updating to the latest go-fuzzywuzzy, the original code should run quite fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:51:34.157",
"Id": "462864",
"Score": "0",
"body": "@telex-wap: \"PyGo\" is a hybrid language used when converting Python code, with minimal changes, to compile as Go code. It is often unreadable and unmaintainable, and it often performs poorly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T17:30:01.337",
"Id": "236196",
"ParentId": "236189",
"Score": "11"
}
},
{
"body": "<p><strong>Review II - your <code>fuzzy.go</code> code</strong></p>\n\n<hr>\n\n<p>After a quick read of your Go code, the Go code for package <code>go-fuzzywuzzy</code>, and the Go documentation, it is reasonable to hope for at least a 60% to 95% improvement in Go performance.</p>\n\n<hr>\n\n<p>Review I, package <code>go-fuzzywuzzy</code>, completely rewrote the package <code>go-fuzzywuzzy</code> file <code>stringutility.go</code> in Go for a significant improvement in performance.</p>\n\n<p>Before:</p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m55.183s\nuser 0m58.858s\nsys 0m0.944s\n$\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m5.735s\nuser 0m6.601s\nsys 0m0.193s\n$\n</code></pre>\n\n<p>The package <code>go-fuzzywuzzy</code> author adopted the suggested <code>stringutility.go</code> changes:</p>\n\n<pre><code>[Fixes #4] Stop reinitializing costly regex in stringutility\nhttps://github.com/paul-mannino/go-fuzzywuzzy/commit/f14294bf5858c8a7fa51b026a9ee9a2802c816bf\n\nWas using regexp.MustCompile within a frequently invoked\nmethod Cleanse. Since go does not cache these calls, it was\nincurring a costly regex compilation each time Cleanse was\ncalled. The other changes made in the stackoverflow post that\ncaught this issue seem to further improve performance by\nabout 10% on top of the massive gains from fixing this issue,\nso incorporating those as well.\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>Now that poor package <code>go-fuzzywuzzy</code> performance is no longer muffling your code performance, let's review your code (<code>fuzzy.go</code>).</p>\n\n<p>Fix obvious problems: check for errors, check for indices in range, flush buffers, close files, and so on.</p>\n\n<p>Your fuzzy search algorithm performance appears to be quadratic - O(original x target). For many cases (exact lowercase match), replace your quadratic algorithm with a linear algorithm - O(original x 1).</p>\n\n<pre><code>for _, line := range original {\n // ...\n name, data := line[1], targetData\n if target, ok := targetMap[strings.ToLower(name)]; ok {\n data = []string{target}\n }\n match, err := fuzzy.ExtractOne(name, data)\n // ...\n}\n</code></pre>\n\n<p>Performance:</p>\n\n<pre><code>$ go build fuzzy.go && time ./fuzzy\nreal 0m5.370s\nuser 0m6.228s\nsys 0m0.175s\n$\n\n$ go build peter.go && time ./peter\nreal 0m2.372s\nuser 0m2.785s\nsys 0m0.070s\n$\n</code></pre>\n\n<p>Also, <code>peter.go</code> appears to be much faster than your Python implementation (<code>fuzzy.py</code>).</p>\n\n<p>As promised, the Go user time has been improved by over 95%: original telex-wap 0m58.858s; peterSO 0m2.785s; user -95.27%.</p>\n\n<p><code>peter.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"encoding/csv\"\n \"fmt\"\n \"os\"\n \"strconv\"\n \"strings\"\n\n fuzzy \"github.com/paul-mannino/go-fuzzywuzzy\"\n)\n\nfunc readCsv(file string) ([][]string, error) {\n csvFile, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n defer csvFile.Close()\n r := csv.NewReader(csvFile)\n records, err := r.ReadAll()\n if err != nil {\n return nil, err\n }\n return records, nil\n}\n\nfunc matchNames() error {\n target, err := readCsv(\"sp500.csv\")\n if err != nil {\n return err\n }\n if len(target) > 1 {\n target = target[1:]\n }\n var targetData []string\n var targetMap = make(map[string]string, len(target))\n for _, line := range target {\n if len(line) <= 1 {\n continue\n }\n name := strings.TrimSpace(line[1])\n targetData = append(targetData, name)\n targetMap[strings.ToLower(name)] = name\n }\n\n original, err := readCsv(\"constituents.csv\")\n if err != nil {\n return err\n }\n if len(original) > 1 {\n original = original[1:]\n }\n\n csvOut, err := os.Create(\"results_go.csv\")\n if err != nil {\n return err\n }\n csvWriter := csv.NewWriter(csvOut)\n err = csvWriter.Write([]string{\"name\", \"match_name\", \"match_score\"})\n if err != nil {\n return err\n }\n\n for _, line := range original {\n if len(line) <= 1 {\n continue\n }\n name, data := strings.TrimSpace(line[1]), targetData\n if target, ok := targetMap[strings.ToLower(name)]; ok {\n data = []string{target}\n }\n match, err := fuzzy.ExtractOne(name, data)\n if err != nil {\n return err\n }\n err = csvWriter.Write([]string{name, match.Match, strconv.Itoa(match.Score)})\n if err != nil {\n return err\n }\n }\n\n csvWriter.Flush()\n err = csvWriter.Error()\n if err != nil {\n return err\n }\n err = csvOut.Close()\n if err != nil {\n return err\n }\n return nil\n}\n\nfunc main() {\n err := matchNames()\n if err != nil {\n fmt.Fprintln(os.Stderr, err)\n os.Exit(1)\n }\n}\n</code></pre>\n\n<p><code>fuzzy.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"encoding/csv\"\n \"github.com/paul-mannino/go-fuzzywuzzy\"\n \"os\"\n \"strconv\"\n)\n\nfunc readCsv(file string) [][]string {\n csvFile, _ := os.Open(file)\n defer csvFile.Close()\n r := csv.NewReader(csvFile)\n records, _ := r.ReadAll()\n return records\n}\n\nfunc main() {\n\n original := readCsv(\"constituents.csv\")\n target := readCsv(\"sp500.csv\")\n csvOut, _ := os.Create(\"results_go.csv\")\n csvwriter := csv.NewWriter(csvOut)\n\n var targetData []string\n\n for _, line := range target[1:] {\n targetData = append(targetData, line[1])\n }\n csvwriter.Write([]string{\"name\", \"match_name\", \"match_score\"})\n for _, line := range original[1:] {\n match, _ := fuzzy.ExtractOne(line[1], targetData)\n csvwriter.Write([]string{line[1], match.Match, strconv.Itoa(match.Score)})\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T19:22:16.373",
"Id": "463017",
"Score": "0",
"body": "Thanks for this! It was very useful to read. I specially found interesting the detail with the quadratic algorithm. This is a task that I perform now and then, so this advice will help my future fuzzy coding style significantly!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:34:40.583",
"Id": "236240",
"ParentId": "236189",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T12:57:27.700",
"Id": "236189",
"Score": "9",
"Tags": [
"python",
"performance",
"csv",
"go"
],
"Title": "Are there ways to speed up this string fuzzy matching in Golang?"
}
|
236189
|
<p>I have written some code for calculating a count of common factors. Please help me remove anything unnecessary and shorten it.</p>
<p>Please tell me if any function in Python 3 can calculate common factors directly!</p>
<pre><code># a string of 2 numbers
# is input e.g. '10 15'
a,b=str(input()).split(' ')
a,b=int(a),int(b)
n=0
if a>=b:
lim=a
else:
lim=b
for num in range(1,lim):
if a%num==0 and b%num==0:
n+=1
print(n)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T14:26:41.650",
"Id": "462718",
"Score": "2",
"body": "Why does this have a VTC for lacking a description. Do you, the closer, not know what common factors are?"
}
] |
[
{
"body": "<p>Basically you only need to iterate up to sqrt(a) because the inverse of every factor <= sqrt(a) gives you the one which is greater than sqrt(a).</p>\n\n<p>See the following code example:</p>\n\n<pre><code>import math\n\n\ndef factors(a):\n ans = set()\n for i in range(1, int(math.sqrt(a)) + 1):\n if a % i == 0:\n ans.add(i)\n ans.add(a // i)\n return ans\n\n\ndef find_common_factors(a, b):\n factors_a = factors(a)\n factors_b = factors(b)\n return factors_a.intersection(factors_b)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T08:23:56.757",
"Id": "462787",
"Score": "0",
"body": "I might be wrong, but there seems to be a problem with your solution. `find_common_factors(10, 25)` returns an empty list, but there are two common factors (1, 5)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T08:30:55.200",
"Id": "462788",
"Score": "0",
"body": "Another example: 720 and 24 have 8 common factors, not 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:31:11.460",
"Id": "462808",
"Score": "0",
"body": "you're right, max_prime should be int(max(math.sqrt(a), math.sqrt(b))). By the way, 1 is not considered a factor (it is implicit for all n)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:42:14.097",
"Id": "462811",
"Score": "0",
"body": "1 is not a *prime factor* of n, but is *is* a common factor of a and b (and the original code counts it as well). Btw, your `find_common_factors(720, 24)` misses the common factor 24."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:09:46.327",
"Id": "462815",
"Score": "0",
"body": "Another problem: `factors(20, ...)` does not find the factor 4. `factors(78, ...)` does not find the factor 6."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:52:31.210",
"Id": "462821",
"Score": "0",
"body": "Edited the code which should fix that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:01:48.037",
"Id": "462825",
"Score": "0",
"body": "Did you check it for (78, 78)? The factor 6 seems still to be missing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:44:09.360",
"Id": "462832",
"Score": "0",
"body": "you're right, just took a very simple approach which should work now."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T12:28:23.547",
"Id": "236191",
"ParentId": "236190",
"Score": "1"
}
},
{
"body": "<p>So there's couple of things you can improve:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>a,b=str(input()).split(' ')\na,b=int(a),int(b)\n\ncdiv=[] #list to store common divisors\nnum=2\nif(max(a,b)%min(a,b)==0): \n c=min(a,b)\n for i in range(2,int(c**0.5)+1):\n while(c%i==0):\n cdiv.append(i)\n c/=i\n if(c>1): cdiv.append(c)\nelse:\n while(num<=min(a,b)//2):\n while(a % num==0)&(b % num==0):\n cdiv.append(num)\n a/=num\n b/=num\n num+=1\n</code></pre>\n\n<p>(1) you indeed should focus on prime divisors.</p>\n\n<p>(2) maximal potential divisor of any number <code>x</code> is <code>x//2</code> (floor from half of <code>x</code>), so it's enough to look for divisors until <code>min(a,b)//2</code> (cause we are looking only for common divisors).</p>\n\n<p>(3) some of the prime divisors could be multiple times divisors - so also you should look for these.</p>\n\n<p>(4) after confirming single number being divisor you can divide both numbers by it - by decreasing the numbers you make it easier to take modulo from it next time (you could probably also do it if divisor is just divisor for one of the numbers, but then you would have to check both numbers separately, which I'm not sure is worth doing in terms of computational overhead).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T07:57:45.490",
"Id": "462782",
"Score": "0",
"body": "You only have to iterate up to sqrt(min(a,b)) because if a or b is dividable by a number greater than its sqrt there also has to be a divider smaller than its sqrt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T08:55:58.783",
"Id": "462789",
"Score": "1",
"body": "@WernerAltewischer: That is not correct, see also my comment at your answer. 10 and 25 have the common factor 5, which is larger than sqrt(min(10, 25))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:05:02.160",
"Id": "462803",
"Score": "0",
"body": "@Werner Altewischer - you're right in terms of finding divisors for a single number, but if we're talking about common divisors - you might be interested only in exactly this higher divisor. (10, 25) is a very good counter-example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T10:22:27.273",
"Id": "462804",
"Score": "1",
"body": "@GrzegorzSkibinski: Your solution seems to be problematic as well: 720 and 24 have the 8 common factors 1, 2, 3, 4, 6, 8, 12, 24, but your code produces `[2, 2, 2]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:48:48.237",
"Id": "462819",
"Score": "0",
"body": "Thanks @Martin R I tweaked my answer - it's for the case when ```b%a==0```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:58:25.793",
"Id": "462824",
"Score": "0",
"body": "Did you check it for (720, 24)? Your result is now `[2, 2, 2, 3]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T15:16:07.780",
"Id": "462844",
"Score": "0",
"body": "Yes, this is correct, I have only prime divisors there - so ```24=2*2*2*3```"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T14:38:39.413",
"Id": "236192",
"ParentId": "236190",
"Score": "2"
}
},
{
"body": "<h3>Coding style</h3>\n\n<p>There is a well-established coding style for Python, the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 coding style</a>, and conformance to that style can be checked online at <a href=\"http://pep8online.com\" rel=\"nofollow noreferrer\">PEP8 online</a>.</p>\n\n<p>In your case it reports “missing space around operator” in almost every\ncode line. Fixing those issues increases the legibility of your code.</p>\n\n<h3>Program structure</h3>\n\n<p>It is better to separate the I/O from the actual computation. With a <em>function</em> to compute the number of common divisors you make your code more readable and reusable. In addition you can <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><em>document</em></a> each function and add <a href=\"https://docs.python.org/3.7/library/doctest.html\" rel=\"nofollow noreferrer\"><em>test cases</em></a> easily.</p>\n\n<p>A <a href=\"https://docs.python.org/3.7/library/__main__.html\" rel=\"nofollow noreferrer\"><em>check for main</em></a> allows to run the script directly, or import it as a module.</p>\n\n<p>So the overall program structure should be</p>\n\n<pre><code>def num_common_factors(a, b):\n \"\"\" Return the number of common factors of a and b. \"\"\"\n # ... TODO ...\n\n\nif __name__ == \"__main__\":\n a, b = map(int, input().split())\n print(num_common_factors(a, b))\n</code></pre>\n\n<p>Note also that reading the input line and the mapping to integers can be combined into a single statement.</p>\n\n<h3>Simplify (and fix) your code</h3>\n\n<p>Your solution is the “brute-force” approach: Test every possible number (in a suitable range) if it is a divisor of both numbers. That can be improved considerably (see below), but let's first discuss how your solution can simplified. First, the limit can be computed using the built-in <code>min()</code> function:</p>\n\n<pre><code>lim = min(a, b)\n</code></pre>\n\n<p>Then note that a <code>range()</code> <em>excludes</em> the upper bound, so you probably want</p>\n\n<pre><code>for num in range(1, lim + 1):\n</code></pre>\n\n<p>I would also avoid abbreviations, i.e. <code>limit</code> instead of <code>lim</code>. Finally the code can be written more concisely by summing a <em>generator expression:</em></p>\n\n<pre><code>def num_common_factors(a, b):\n \"\"\" Return the number of common factors of a and b. \"\"\"\n limit = min(a, b)\n return sum(1 for i in range(1, limit + 1) if a % i == 0 and b % i == 0)\n</code></pre>\n\n<h3>Mathematics helps!</h3>\n\n<p>The problem can be solved more efficiently using some maths. Every common divisor of <code>a</code> and <code>b</code> is a divisor of the <a href=\"https://en.wikipedia.org/wiki/Greatest_common_divisor\" rel=\"nofollow noreferrer\">“greatest common divisor”</a> of <code>a</code> and <code>b</code>, and vice versa. So the task can be split into two separate problems:</p>\n\n<ul>\n<li>Determine the greatest common divisor <span class=\"math-container\">\\$ g = \\gcd(a, b) \\$</span>. This can be done efficiently using the <a href=\"https://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow noreferrer\">Euclidian algorithm</a>, but even better, Python has a built-in function <a href=\"https://docs.python.org/3.7/library/math.html#math.gcd\" rel=\"nofollow noreferrer\">math.gcd</a> for that.</li>\n<li>Count the number of divisors of <span class=\"math-container\">\\$ g \\$</span>.</li>\n</ul>\n\n<p>So our function would be</p>\n\n<pre><code>from math import gcd\n\n\ndef num_common_factors(a, b):\n \"\"\" Return the number of common factors of a and b.\n\n Example 1: 10 and 25 have the 2 common factors 1, 5.\n >>> num_common_factors(10, 25)\n 2\n\n Example 2: 720 and 24 have the 8 common factors 1, 2, 3, 4, 6, 8, 12, 24.\n >>> num_common_factors(720, 24)\n 8\n \"\"\"\n g = gcd(a, b)\n return num_divisors(g)\n</code></pre>\n\n<p>where I also have added two test cases as examples.</p>\n\n<p>Now we are left with the second task: counting the number of divisors. A simple implementation would be</p>\n\n<pre><code>def num_divisors(n):\n \"\"\"Return the number of divisors of n.\"\"\"\n\n count = 0\n for i in range(1, n+1):\n if n % i == 0:\n count += 1\n return count\n</code></pre>\n\n<p>which again can be done by summing a generator expression:</p>\n\n<pre><code>def num_divisors(n):\n \"\"\"Return the number of divisors of n.\"\"\"\n\n return sum(1 for i in range(1, n+1) if n % i == 0)\n</code></pre>\n\n<p>But this can be done far more efficiently using the prime number factorization: If\n<span class=\"math-container\">$$\n n = p_1^{e_1} \\, p_2^{e_2} \\cdots p_k^{e_k}\n$$</span>\nis the factorization of <span class=\"math-container\">\\$ n \\$</span> into prime numbers <span class=\"math-container\">\\$ p_i \\$</span>\nwith exponents <span class=\"math-container\">\\$ e_i \\$</span>, then \n<span class=\"math-container\">$$\n \\sigma_0(n) = (e_1+1)(e_2+1) \\cdots (e_k+1)\n$$</span>\nis the number of divisors of <span class=\"math-container\">\\$ n \\$</span>, see for example\n<a href=\"https://en.wikipedia.org/wiki/Divisor_function\" rel=\"nofollow noreferrer\">Wikipedia: Divisor function</a>. Example:\n<span class=\"math-container\">$$\n 720 = 2^4 \\cdot 3^2 \\cdot 5^1 \\Longrightarrow\n \\sigma_0(720) = (4+1)(2+1)(1+1) = 30 \\, .\n$$</span></p>\n\n<p>Here is a possible implementation (translated from the JavaScript <a href=\"https://codereview.stackexchange.com/a/120646/35991\">here</a> to Python):</p>\n\n<pre><code>def num_divisors(n):\n \"\"\"Return the number of divisors of n.\"\"\"\n\n count = 1 # Number of divisors\n factor = 2 # Candidate for prime factor of n\n\n # If n is not a prime number then it must have one factor\n # which is <= sqrt(n), so we try these first:\n while factor * factor <= n:\n if n % factor == 0:\n # factor is a prime factor of n, determine the exponent:\n exponent = 1\n n /= factor\n while n % factor == 0:\n exponent += 1\n n /= factor\n\n # factor^exponent is one term in the prime factorization of n,\n # this contributes as factor exponent + 1:\n count *= exponent + 1\n\n # Next possible prime factor:\n factor = 3 if factor == 2 else factor + 2\n\n # Now n is either 1 or a prime number. In the latter case,\n # it contributes a factor 2:\n if n > 1:\n count *= 2\n\n return count\n</code></pre>\n\n<h3>Testing</h3>\n\n<p>As already mentioned above, test cases can be added to each function, and verified with the <a href=\"https://docs.python.org/3.7/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module. Running the tests after each modification of the code helps to find programming errors.</p>\n\n<p>We already added two test cases to the <code>num_common_factors()</code> function. Now we'll do this for the <code>num_divisors()</code> divisors function, which is essential to the program, and where a programming error can easily lead to wrong results.</p>\n\n<p>One option is to compute a bunch of values using an alternative program and use the results as test cases. I chose <a href=\"https://pari.math.u-bordeaux.fr/gp.html\" rel=\"nofollow noreferrer\">PARI/GP</a> to compute the number of divisors of <span class=\"math-container\">\\$ 1, \\ldots, 20 \\$</span>, <span class=\"math-container\">\\$ 100, \\ldots, 119\\$</span>, and <span class=\"math-container\">\\$ 10000, \\ldots, 10019 \\$</span>:</p>\n\n<pre><code>? vector(20, n, numdiv(n))\n%1 = [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6]\n? vector(20, n, numdiv(99+n))\n%2 = [9, 2, 8, 2, 8, 8, 4, 2, 12, 2, 8, 4, 10, 2, 8, 4, 6, 6, 4, 4]\n? vector(20, n, numdiv(9999+n))\n%3 = [25, 4, 8, 4, 12, 16, 4, 2, 24, 2, 32, 8, 6, 8, 8, 4, 12, 16, 4, 4]\n</code></pre>\n\n<p>and added these as test cases to the <code>num_divisors()</code> function:</p>\n\n<pre><code>def num_divisors(n):\n \"\"\"Return the number of divisors of n.\n\n >>> [num_divisors(n) for n in range(1, 21)]\n [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6]\n\n >>> [num_divisors(n) for n in range(100, 120)]\n [9, 2, 8, 2, 8, 8, 4, 2, 12, 2, 8, 4, 10, 2, 8, 4, 6, 6, 4, 4]\n\n >>> [num_divisors(n) for n in range(10000, 10020)]\n [25, 4, 8, 4, 12, 16, 4, 2, 24, 2, 32, 8, 6, 8, 8, 4, 12, 16, 4, 4]\n \"\"\"\n ... remaining function omitted ...\n</code></pre>\n\n<p>Testing is done by running </p>\n\n<pre><code>python -m doctest -v countcommonfactors.py \n</code></pre>\n\n<p>on the command line (assuming that “countcommonfactors.py” is the name of your Python script).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T12:52:32.213",
"Id": "462822",
"Score": "0",
"body": "Please tell me a bit about the map() function that you used in : a, b = map(int, input().split())"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:04:14.077",
"Id": "462826",
"Score": "0",
"body": "@UtkarshSharma: The first argument is a function, which is applied to every item in the second argument (which is an iterable). Documented here: https://docs.python.org/3/library/functions.html#map."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:09:18.013",
"Id": "462827",
"Score": "0",
"body": "@UtkarshSharma: ... The result is an iterable, which is unpacked into a and b."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T14:29:50.697",
"Id": "462973",
"Score": "0",
"body": "Out of curiosity; is there a reason you don't remove `if n % factor == 0:` and the first `n /= factor`, and change `exponent = 1` to `exponent = 0`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T14:39:38.090",
"Id": "462974",
"Score": "0",
"body": "@Peilonrayz: Then a multiplication `count *= exponent + 1` would also be done if `factor` is not a divisor. That would work because `exponent = 0` in that case. (The real reason is that I translated this back from a JavaScript with a repeat-while loop :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T07:43:25.313",
"Id": "236216",
"ParentId": "236190",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236216",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T11:43:53.763",
"Id": "236190",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "Count common factors"
}
|
236190
|
<p>Hello I made this calculator in Python, I know it's pretty basic but I want your opinions if I made it well or not, and if you find any mistakes or not.<br>
P.S ( I know I could do another better than this one if I looked in internet but I want to evolve that's why I'm here )</p>
<pre><code>#Commands
print("Operations that you can use:")
print("Addition: +")
print("Subtraction: -")
print("Multiplication: *")
print("Division: /")
print("Exponentiation: **")
print("Radicalization: **(1/")
print("\n")
#Variables
x = None
y = None
z = None
ce = 0
while ce < 1:
# Inputs
x = float(input("First Value: "))
y = input("Operation: ")
z = float(input("Second Value: "))
# If
if '+' == y:
add = float(x) + float(z)
print(add)
elif '-' == y:
sub = float(x) - float(z)
print(sub)
elif '/' == y:
div = float(x) / float(z)
print(div)
elif "**(1/" == y:
rad = float(x) **(1/float(z))
print(rad)
elif "**" == y:
exp = float(x) ** float(z)
print(exp)
elif '*' == y:
mul = float(x) * float(z)
print(mul)
print("Continue or Exit?")
ce = int(input(" 0 or 1 : "))
</code></pre>
|
[] |
[
{
"body": "<p>Let me offer the following rewrite of your program and then let's walk through it:</p>\n\n<pre><code>names = {'Addition' : '+',\n 'Subtraction' : '-',\n 'Division' : '/',\n 'Exponentation': '**',\n 'Radicalization': '**(1/'\n }\n\nprint(\"Operations that you can use:\")\nfor op in names:\n print(op, names[op])\n\nops = {\n '+' : (lambda x, y: x + y),\n '-' : (lambda x, y: x - y),\n '*' : (lambda x, y: x * y),\n '/' : (lambda x, y: x / y),\n '**' : (lambda x, y: x ** y),\n '**(1/' : (lambda x, y: x ** 1.0 / y),\n 'na' : (lambda x, y: 'Unknown binary operator')\n }\n\nce = 0\nwhile ce != 1:\n x = float(input(\"First Value: \"))\n y = input(\"Operation: \")\n z = float(input(\"Second Value: \"))\n\n op = ops.get(y, 'na')\n print(ops[op](x, z))\n\n print(\"Continue or Exit?\")\n ce = int(input(\" 0 or 1 : \"))\n</code></pre>\n\n<ul>\n<li><p>It seems unnecessary to define <code>x</code>, <code>y</code> and <code>z</code> to be <code>None</code> so we just define them inside the main loop.</p></li>\n<li><p>The <code>ops</code> dictionary stores a symbol of the operator and the actual implementation in a lambda function. It also stores a special <code>'na'</code> value to represent any unknown operator; this is useful in the main loop where we return that key if we don't find what the user gave us as input.</p></li>\n<li><p>The key difference and main idea here is a <em>data-driven solution</em>. That is, notice how we've put the supported operators into data structures. This way it's easier to make changes and to maintain the program, e.g., when you add a new binary operator, you don't have to touch the logic of your calculator, just add a new element into your data structure.</p></li>\n<li><p>There's no explicit if-elif chain anymore, yay! Such chains are often annoying to write and it's always a potential code smell. No matter how experienced you are, it's one of those things where it's easy to make a human error and write something you didn't mean to, but it can be tough to discover the bug.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T19:09:59.680",
"Id": "236201",
"ParentId": "236195",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T16:33:19.313",
"Id": "236195",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "Python Basic Calculator"
}
|
236195
|
<p>I'm a beginner programmer and I was hoping someone would be able to review my program. Everything has been tested for user validation, error-checking and conforms to the specification with a few slight additions of my own. I want to know what I've done well, what I haven't done well, improvements I can make e.g. how can I can make code structure more efficient. Are there any parts of my program which can be simplified i.e. have I over-thought / over-complicated any parts of my program and if I have is there an easier way? I'll be absolutely grateful to anyone who does! There are five parts to my program, a struct "specification" and "implementation" for both "Item" (singular) and "Items" (plural), and the "Main.cpp". I've based my program on the following scenario... </p>
<blockquote>
<p>A system that allows one to enter the items that they are
selling, the quantity sold, the price of each of the items. They would
like the program to be able to create suggestions based on the data
provided.</p>
<p>Input:</p>
<p>Item name</p>
<p>Sale price</p>
<p>Quantity sold</p>
<p>Output:</p>
<p>Quantity of items sold</p>
<p>Total price of items sold</p>
<p>Most sold item</p>
<p>Least sold item</p>
<p>The difference in sales between the most and least sold items</p>
<p>Estimated operational cost (50% of sales)</p>
<p>Tax paid (20% of sales)</p>
<p>Profit (Total after tax and operational costs)</p>
<p>If any number of products constitutes less than 5% of sales
individually, a warning should be displayed</p>
<p>Your program will also need to work within the following constraint:</p>
<p>There must be at least 5 products that can be entered</p>
</blockquote>
<p>Sales System.cpp : This file contains the 'main' function. Program execution begins and ends there.</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include "Item.hpp"
#include "Items.hpp"
//When called this asks the user how many items they would like to add and the item number has to be greater than 5.
//Through the parameter is passed a vector of items.
//The ContinueOptions() procedure is there to allow people to decide when they want to go back to the menu.
void ContinueOptions()
{
bool bValid = false;
char cInputCommandPrompt = 0;
do{
std::cout << "Press ""y"" to continue: ";
bValid = bool( std::cin >> cInputCommandPrompt );
if (bValid)
{
cInputCommandPrompt = std::toupper(static_cast<unsigned char>(cInputCommandPrompt));
bValid = cInputCommandPrompt == 'Y';
}
if (!bValid)
{
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "Please try again.\n";
}
} while(!bValid );
std::cout << "\n";
}
void DisplayMenu()
{
std::cout << "What would you like to do?\nChoose a number from the Menu...\n";
std::cout << "\t1. Add another item\n";
std::cout << "\t2. Display items\n";
std::cout << "\t3. Total quantity of items sold\n";
std::cout << "\t4. Total price of items sold\n";
std::cout << "\t5. Most sold item\n";
std::cout << "\t6. Least sold item\n";
std::cout << "\t7. Difference in sales between the most and least sold items\n";
std::cout << "\t8. Estimated operational cost (50% of sales)\n";
std::cout << "\t9. Show Tax paid (20% of sales)\n";
std::cout << "\t10.Profit (Total after tax and operational costs)\n";
std::cout << "\t11. Show additional options\n";
std::cout << "\t0. Quit.\n";
std::cout << "\n";
}
void DisplayAdditionalMenu()
{
std::cout << "What would you like to do?\nChoose a number from the Additional Menu...\n";
std::cout << "\t1. Delete an item\n";
std::cout << "\t2. Search for specific item\n";
std::cout << "\t0. Back to main menu\n";
std::cout << "\n";
}
void AdditionalMenu(Items &Items)
{
bool bExitAdditionalMenu = false;
do
{
DisplayAdditionalMenu();
int iAdditionalMenuSelection = 0;
std::cout << "Enter a number from the additional menu: ";
std::cin >> iAdditionalMenuSelection;
if(std::cin.good())
{
switch(iAdditionalMenuSelection)
{
case 1:
Items.DeleteAnItem();
ContinueOptions();
break;
case 0:
bExitAdditionalMenu = true;
default:
std::cout << "Invalid input. Try again!\n";
continue;
}
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Sorry, invalid input input. Try again!";
std::cout << "\n";
ContinueOptions();
}
}while(bExitAdditionalMenu == false);
}
int main()
{
Items Items;
bool bExitProgram = false;
int iMenuSelection = 0;
int iIndexOfMostSoldItem = 0;
int iIndexOfLeastSoldItem = 0;
//If this variable is greater than 1 (which will increment within the do / while) then a continue option will display.
int iNumber = 1;
std::cout << "===================================\n";
std::cout << "\t\tSales System\n";
std::cout << "===================================\n";
Items.GetItemInformation();
Items.DisplayWarning();
do{
iNumber++;
if (iNumber > 1)
{
ContinueOptions();
}
DisplayMenu();
std::cout << "Enter a number from the menu: ";
std::cin >> iMenuSelection;
if(std::cin.good())
{
std::cout << "\n";
switch (iMenuSelection)
{
case 1:
std::cout << "You've chosen option 1.\n";
std::cin.ignore();
Items.AddNewItem();
break;
case 2:
std::cout << "You've chosen option 2.\n";
Items.PrintItems();
break;
case 3:
std::cout << "You've chosen option 3.\n";
std::cout << "The total quantity sold is: " << Items.CalculateQuantitySold() << ".\n";
break;
case 4:
std::cout << "You've chosen option 4.\n";
std::cout << "Total Amount of Items Sold: £" << Items.CalculateTotalSales() << "\n";
break;
case 5:
std::cout << "You've chosen option 5.\n";
std::cout << "Displaying most sold item...\n";
iIndexOfMostSoldItem = Items.MostSoldItem();
Items.DisplayVectorOfItemsAtIndex(iIndexOfMostSoldItem);
break;
case 6:
std::cout << "You've chosen option 6.\n";
std::cout << "Displaying least sold item...\n";
iIndexOfLeastSoldItem = Items.LeastSoldItem();
Items.DisplayVectorOfItemsAtIndex(iIndexOfLeastSoldItem);
break;
case 7:
std::cout << "You've chosen option 7.\n";
std::cout << "The difference between the most and least is by: ";
std::cout << Items.CalculateDifferenceBetweenLeastAndMostSold() << ".\n";
break;
case 8:
std::cout << "You've chosen option 8.\n";
std::cout << "Estimated operational cost (50% of sales): ";
std::cout << Items.CalculateEstimatedOperationalCost() << ".\n";
break;
case 9:
std::cout << "You've chosen option 9.\n";
std::cout << "Tax paid (20% of sales): ";
std::cout << Items.CalculateTaxPaid() << ".\n";
break;
case 10:
std::cout << "You've chosen option 10.\n";
std::cout << "Profit (Total after tax and operational costs): ";
std::cout << Items.CalculateProfit() << ".\n";
case 11:
AdditionalMenu(Items);
break;
case 0:
std::cout << "You have exited the program.\n";
bExitProgram = true;
break;
default:
std::cout << "Invalid command prompt. Try again!\n";
continue;
}
}
//This will essentially clear the invalid characters the user entered and will prompt them to try again by re-looping back to the start.
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Sorry, invalid input input. Try again!";
std::cout << "\n";
ContinueOptions();
}
}while(bExitProgram == false);
std::cout << "\n";
}
</code></pre>
<p>Item.hpp
Sale System</p>
<pre><code>#ifndef Item_hpp
#define Item_hpp
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <stdio.h>
//This struct models as a basic item which includes its name, price and quantity sold.
struct Item{
private:
std::string sItemName;
double dSalePrice;
int iQuantitySold;
public:
Item(std::string s, double d, int i);
std::string GetItemName()const;
double GetItemSalePrice()const;
int GetItemQuantity()const;
double GetItemSale();
};
#endif /* Item_hpp */
</code></pre>
<p>Item.cpp
Sale System</p>
<pre><code>#include "Item.hpp"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
Item::Item(std::string s, double d, int i):sItemName(s),dSalePrice(d),iQuantitySold(i){
}
std::string Item::GetItemName()const{return sItemName;}
double Item::GetItemSalePrice()const{return dSalePrice;}
int Item::GetItemQuantity()const{return iQuantitySold;}
double Item::GetItemSale()
{
return dSalePrice * iQuantitySold;
}
</code></pre>
<p>Items.hpp
Sale System
This is the specification of the "Items" (plural) struct</p>
<pre><code>#ifndef Items_hpp
#define Items_hpp
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include "Item.hpp"
struct Items{
//The vector<Items>ItemsVec is private so only member functions/procedures have access to it.
private:
std::vector<Item>ItemsVec;
public:
//The ContinueOptions() procedure is there to allow people to decide when they want to go back to the menu.
//Memeber functions/procedures of Items prototypes ()
bool CheckIfItemExists(std::string sInputName);
void AddNewItem(); //PROTOTYPE of procedure that adds a new item to the vecto
void GetItemInformation();//PROTOTYPE that allows user to enter in the amount of items (and number of how many will be the amount of times the for loop iterates to add desired number of items through means of push_back)
int CalculateQuantitySold();//PROTOTYPE of function that calculates the total quantity sold for all items
int MostSoldItem(); //PROTOTYPE of function that calculates most item using a For Loop.
int LeastSoldItem(); //PROTOTYPE of function that calculates least item using a For Loop.
void DisplayVectorOfItemsAtIndex(int iIndex); //PROTOTYPE that expects iIndex as a parameter to ascertain which index to display in vector.
double CalculateDifferenceBetweenLeastAndMostSold();//PROTOTYPE for calculating difference between the least amount sold and the highest.
double CalculateTotalSales(); //PROTOTYPE for calculating the total sales
double CalculateEstimatedOperationalCost(); //PROTOTYPE for calculating the estimated operational cost
double CalculateTaxPaid(); //PROTOTYPE for calculating amount of tax paid.
double CalculateProfit(); //PROTOTYPE for calculating total profit
bool PrintItems()const; //PROTOTYPE for printing items in vector
void DisplayWarning(); //PROTOTYPE for displaying a warning
bool DeleteAnItem(); //PROTOTYPE for deleting an item from the vector
};
#endif /* Items_hpp */
</code></pre>
<p>Items.cpp
Sale System</p>
<pre><code>#include "Items.hpp"
#include "Item.hpp"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
//This procedure allows the user to type in the name of the item, and if the item exists, will subseqently be deleted.
bool Items::DeleteAnItem()
{
std::string sNameOfItemToBeDeleted;
std::cout << "Input name of item that you wish to delete: ";
std::cin.ignore(); //This ignores anything that is in the cin buffer.
std::getline(std::cin,sNameOfItemToBeDeleted);
for (int iCount = 0; iCount < ItemsVec.size();iCount++)
{
if (ItemsVec.at(iCount).GetItemName() == sNameOfItemToBeDeleted)
{
ItemsVec.erase(ItemsVec.begin() + iCount);
std::cout << sNameOfItemToBeDeleted << " has been deleted.\n";
std::cin.clear();
return true;
}
}
std::cout << "We couldn't find the item you're trying to delete\n";
return false;
}
bool Items::CheckIfItemExists(std::string sInputName)
{
for(int iCount = 0; iCount < ItemsVec.size();iCount++)
{
if (ItemsVec.at(iCount).GetItemName() == sInputName)
{
std::cout << "Try again! There's already an item with that name.\n";
return false;
}
}
return true;
}
void Items::AddNewItem()
{
bool bValid = false;
std::string sInputName;
double dInputSalePrice = 0;
int iInputQuantity = 0;
do{
std::cout << "Enter information for new item..." << std::endl;
std::cout << "\tName: ";
std::cin.clear();
std::getline(std::cin,sInputName);
bValid = CheckIfItemExists(sInputName);
}while(bValid == false);
bool bSalePriceValid = false;
do{
std::cout << "\tSale price: £";
std::cin >> dInputSalePrice;
if(!std::cin)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "\n";
std::cout << "Sorry, invalid input input. Try again!\n";
std::cout << "\n";
}
else
{
bSalePriceValid = true;
}
}while(bSalePriceValid == false);
bool bQuantityValid = false;
do{
std::cout << "\tQuantity sold: ";
std::cin >> iInputQuantity;
if(!std::cin)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "\n";
std::cout << "Sorry, invalid input input. Try again!\n";
std::cout << "\n";
}
else
{
bQuantityValid = true;
}
}while(bQuantityValid == false);
Item NewItem(sInputName, dInputSalePrice, iInputQuantity);
ItemsVec.push_back(NewItem);
std::cout << "=======================================================================\n";
std::cout << "You've succesfully added a " << "'" << sInputName << "' as an item.\n";
std::cout << "=======================================================================\n";
}
void Items::GetItemInformation()
{
bool bValid = false;
int iInputItemSize = 0;
std::string sItem;
do{
std::cout << "How many items would you like to add?: ";
std::cin >> iInputItemSize;
if(std::cin.good())
{
if(iInputItemSize < 5)
{
std::cout << "\n";
std::cout << "Try again, number must be greater than 5!\n";
}
else
{
bValid = true;
}
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Sorry, invalid input input. Try again!";
std::cout << "\n";
}
} while(bValid == false);
for (int iCount = 0; iCount < iInputItemSize;iCount++)
{
std::cin.ignore();
AddNewItem();
std::cout << "\n";
}
std::cout << "You've successfully added " << iInputItemSize <<" items\n";
}
int Items::CalculateQuantitySold(){
int iTotalQuantitySold = 0;
for (int iCount = 0; iCount < ItemsVec.size();iCount++){
iTotalQuantitySold += ItemsVec.at(iCount).GetItemQuantity();
}
return iTotalQuantitySold;
}
int Items::MostSoldItem()
{
Item MostSoldItem("",0,0);
int iIndexOfMostSoldItem = 0;
for (int iCount = 0; iCount < ItemsVec.size();iCount++)
{
if ( ItemsVec.at(iCount).GetItemQuantity() > MostSoldItem.GetItemQuantity() )
{
MostSoldItem = ItemsVec.at(iCount);
iIndexOfMostSoldItem = iCount;
}
}
return iIndexOfMostSoldItem;
}
int Items::LeastSoldItem()
{
Item LeastSoldItem("",0,0);
int iIndexOfLeastSoldItem = 0;
for (int iCount = 0; iCount < ItemsVec.size();iCount++)
{
if (ItemsVec.at(iCount).GetItemQuantity() < LeastSoldItem.GetItemQuantity())
{
LeastSoldItem = ItemsVec.at(iCount);
iIndexOfLeastSoldItem = iCount;
}
}
return iIndexOfLeastSoldItem;
}
void Items::DisplayVectorOfItemsAtIndex(int iIndex)
{
std::cout << "==========================================\n";
std::cout <<"\tName: " << ItemsVec.at(iIndex).GetItemName() << "\n";
std::cout <<"\tSale Price: £" << ItemsVec.at(iIndex).GetItemSalePrice() << "\n";
std::cout <<"\tQuantity Sold: " << ItemsVec.at(iIndex).GetItemQuantity() << "\n";
std::cout << "==========================================\n";
std::cout << "\n";
}
double Items::CalculateDifferenceBetweenLeastAndMostSold()
{
int iDifferenceBetweenMostLeast = 0;
int iMostSoldIndex = MostSoldItem();
int iLeastSoldIndex = LeastSoldItem();
iDifferenceBetweenMostLeast = ItemsVec.at(iMostSoldIndex).GetItemQuantity() - ItemsVec.at(iLeastSoldIndex).GetItemQuantity();
return iDifferenceBetweenMostLeast;
}
double Items::CalculateTotalSales()
{
double dTotalSales = 0;
for (auto Item : ItemsVec)
{
dTotalSales += Item.GetItemSale();
}
return dTotalSales;
}
double Items::CalculateEstimatedOperationalCost()
{
double dTotalSales = CalculateTotalSales();
double dEstimatedOperationalCost = dTotalSales * 0.5;
return dEstimatedOperationalCost;
}
double Items::CalculateTaxPaid()
{
double dTaxPaid = CalculateTotalSales() * 0.2;
return dTaxPaid;
}
double Items::CalculateProfit()
{
double dTotalProfit = 0;
double dTotalSales = CalculateTotalSales();
dTotalProfit = dTotalSales - CalculateTaxPaid() - CalculateEstimatedOperationalCost();
return dTotalProfit;
}
bool Items::PrintItems()const
{
int iCountNumber = 1;
if (ItemsVec.size() == 0)
{
std::cout << "There are no items to display.\n";
return false;
}
else
{
for (const auto &Item : ItemsVec)
{
std::cout << "Displaying information for item " << iCountNumber++ << "...\n";
std::cout << "==========================================\n";
std::cout << "\tName: " << Item.GetItemName() << "\n";
std::cout << "\tSale Price: £" << Item.GetItemSalePrice() << "\n";
std::cout << "\tQuantity Sold: " << Item.GetItemQuantity() << "\n";
std::cout << "==========================================\n";
std::cout << "\n";
}
}
return true;
}
void Items::DisplayWarning()
{
double dTotalSales = CalculateTotalSales();
double FivePercentOfTotalSales = dTotalSales * 0.05;
bool bWarning = false;
for (int iCount = 0; iCount < ItemsVec.size();iCount++)
{
if (ItemsVec.at(iCount).GetItemSale() <= FivePercentOfTotalSales)
{
bWarning = true;
}
else
{
bWarning = false;
}
}
if (bWarning == true)
{
std::cout << "Warning! You have products that constitutes less than 5% of sales individually.\n";
}
else
{
std::cout << "Well done! All your products constitutes to more than 5% of sales individually.\n";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T21:42:21.577",
"Id": "462741",
"Score": "1",
"body": "Which specific version of the language are you targeting? You should specify at most one of the C++11, C++14, and C++17 tags. The contents of a review may vary depending on which language spec you're using."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T22:11:19.163",
"Id": "462742",
"Score": "0",
"body": "C++11 I think..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T04:56:18.310",
"Id": "468534",
"Score": "0",
"body": "Hello, please don't edit your question to include feedback from answers. This makes answers nonsensical because the points they address no longer exist in the question. See [What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<p>To get you started:</p>\n\n<hr>\n\n<h1>Naming</h1>\n\n<p>Hungarian notation (e.g., <code>bValid</code>) is not generally used in C++. C++ is a statically typed language, so the compiler will do type checking. Also, the common naming scheme in C++ is:</p>\n\n<ul>\n<li><p><code>snake_case</code> for variables and functions;</p></li>\n<li><p><code>CamelCase</code> (or <code>Like_this</code>) for classes; and</p></li>\n<li><p><code>ALL_CAPS</code> for macros.</p></li>\n</ul>\n\n<p>You can come up with your own naming scheme if you have a good reason, but sticking to the common one is better in general.</p>\n\n<p>Macro names are not subject to scopes, so avoid common names like <code>Item_hpp</code> (or <code>ITEM_HPP</code>). You can append a <a href=\"https://www.random.org/strings/?num=1&len=10&digits=on&upperalpha=on&loweralpha=on&format=plain\" rel=\"nofollow noreferrer\">random string</a>: <code>ITEM_HPP_h0hCHfEa5Y</code>.</p>\n\n<p><code>Item</code> and <code>Items</code> are way too similar. Consider using a distinctive name such as <code>Collection</code> instead of <code>Items</code> for clarity.</p>\n\n<hr>\n\n<h1><code>ContinueOptions</code></h1>\n\n<p>This function should be named <code>confirm_continue</code> because it simply forces the user to press <code>Y</code> and then continue. If the user chooses not to continue, the system says \"Please try again.\" (<em>sad face</em>)</p>\n\n<blockquote>\n<pre><code>//When called this asks the user how many items they would like to add and the item number has to be greater than 5.\n//Through the parameter is passed a vector of items.\n</code></pre>\n</blockquote>\n\n<p>??? Not sure what that means ...</p>\n\n<p><code>cInputCommandPrompt</code> is not a good name because it stores the input rather than the prompt (which is what you show to the user). <code>input</code> is enough.</p>\n\n<p>This is a bit scary:</p>\n\n<blockquote>\n<pre><code>std::toupper(static_cast<unsigned char>(cInputCommandPrompt))\n</code></pre>\n</blockquote>\n\n<p>Technically yes, this prevents UB. I never saw that before (and never wrote that), but it's right the more I think about it. You can declare the variable as <code>unsigned char</code> in the first place. Or just use <code>char</code> ...</p>\n\n<p><code>\"Press \"\"y\"\" to continue: \"</code> is equivalent to <code>\"Press y to continue\"</code>. You are concatenating three string literals.</p>\n\n<p><code>#include <cctype></code> is missing for <code>std::toupper</code>. Also, <code>std::tolower</code> is more commonly used for case-insensitive comparison.</p>\n\n<p>Also, the logic is a bit convoluted. Here's an attempt at simplification:</p>\n\n<pre><code>// requires '#include <limits>'\nconstexpr auto stream_max = std::numeric_limits<std::streamsize>::max();\n\ntemplate <typename T>\nauto& input(std::string_view prompt, T& value) // requires '#include <string_view>'\n{\n std::cout << prompt;\n return std::cin >> value;\n}\n\nvoid confirm_continue()\n{\n char ch{};\n while (!input(\"Press 'y' to continue: \", ch) && std::tolower(ch) == 'y') {\n std::cin.clear();\n std::cin.ignore(stream_max, '\\n'); // has special meaning\n std::cout << \"Please try again.\\n\";\n }\n}\n</code></pre>\n\n<p>This is arguably clearer. See <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/ignore\" rel=\"nofollow noreferrer\">cppreference</a> for the use of <code>stream_max</code>.</p>\n\n<hr>\n\n<h1><code>AdditionalMenu</code></h1>\n\n<p>The advertised <code>2. Search for specific item</code> functionality results in <code>Invalid input. Try again!</code>. At least use something like <code>Coming soon ...</code>.</p>\n\n<p>The two kinds of invalid input can be unified somehow.</p>\n\n<p>Similar simplification:</p>\n\n<pre><code>void additional_menu(Items& items)\n{\n while (true) {\n int option{};\n if (input(\"Enter a number from the additional menu: \", option)) {\n switch (option) {\n case 0:\n return; // exit additional menu\n case 1:\n items.DeleteAnItem();\n confirm_continue();\n continue;\n case 2:\n std::cout << \"Coming soon ...\\n\\n\";\n continue;\n }\n } else {\n std::cin.clear();\n std::cin.ignore(stream_max, '\\n');\n }\n std::cout << \"Invalid input. Try again!\\n\";\n }\n}\n</code></pre>\n\n<p>The <code>main</code> function can be simplified analogously.</p>\n\n<hr>\n\n<p><code>Item</code></p>\n\n<p>Only <code>#include</code> necessary headers. You only need <code><string></code>.</p>\n\n<p>The <code>Item</code> class doesn't maintain any class invariant, so use an <a href=\"https://en.cppreference.com/w/cpp/language/aggregate_initialization\" rel=\"nofollow noreferrer\">aggregate</a> (which is basically an all-public class) to get rid of the constructor and observer functions:</p>\n\n<pre><code>#include <string>\n\nstruct Item {\n std::string name;\n double price;\n int quantity_sold;\n\n const double sale() const noexcept\n {\n return price * quantity_sold;\n }\n};\n</code></pre>\n\n<p>Now the <code>Item.cpp</code> file can be removed.</p>\n\n<hr>\n\n<h1><code>Items</code></h1>\n\n<p>As I said before, rename to <code>Collection</code> or something like that.\nAnd rename <code>ItemsVec</code> to <code>items</code>.</p>\n\n<p>Comments like <code>//The vector<Items>ItemsVec is private so only member functions/procedures have access to it.</code> are unnecessary because competent programmers are familiar with the basic language constructs.</p>\n\n<p>Now the individual functions:</p>\n\n<h2>Delete an item</h2>\n\n<p><code>std::cin.ignore();</code> ignores <strong>one character</strong>, not \"anything that is left\" ;)\nUse <code>std::cin >> std::ws</code> instead. Consider handling invalid input?</p>\n\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/algorithm/find\" rel=\"nofollow noreferrer\"><code>std::find_if</code></a> (requires <code>#include <algorithm></code>) + <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"nofollow noreferrer\">lambda</a> to find the item:</p>\n\n<pre><code>bool Items::delete_item()\n{\n std::string name;\n std::cout << \"Input name of item that you wish to delete: \";\n getline(std::cin >> std::ws, name);\n\n auto it = std::find_if(items.begin(), items.end(),\n [&](const Item& item) { return item.name == name; });\n if (it == items.end()) { // not found\n std::cout << \"We couldn't find the item you're trying to delete\\n\";\n return false;\n } else {\n items.erase(it);\n std::cout << name << \" has been deleted.\\n\";\n return true; \n }\n}\n</code></pre>\n\n<h2>Check for existence</h2>\n\n<p>It should be <code>ensure_nonexistent</code> based on the return value.</p>\n\n<p>Similarly:</p>\n\n<pre><code>bool Items::ensure_nonexistent(std::string name)\n{\n auto it = std::find_if(items.begin(), items.end(),\n [&](const Item& item) { return item.name == name; });\n if (it == items.end()) {\n return true;\n } else {\n std::cout << \"Try again! There's already an item with that name.\\n\";\n return false;\n }\n}\n</code></pre>\n\n<h2>Add new item</h2>\n\n<p>The function can be simplified analogously, but note that this:</p>\n\n<pre><code>Item NewItem(sInputName, dInputSalePrice, iInputQuantity);\nItemsVec.push_back(NewItem);\n</code></pre>\n\n<p>introduces overhead by copying the item. Use move semantics:</p>\n\n<pre><code>Item item{/* ... */};\nitems.push_back(std::move(item)); // #include <utility>\n</code></pre>\n\n<p>or simply:</p>\n\n<pre><code>items.push_back(Item{name, price, quantity});\n</code></pre>\n\n<h2><code>GetItemInformation</code></h2>\n\n<p>The name is deceptive! It's actually <code>add_items</code>.</p>\n\n<h2>Calculate total quantity</h2>\n\n<p>Make the function <code>const</code>. Use <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a>: (<code>#include <numeric></code>)</p>\n\n<pre><code>int Items::total_quantity_sold() const noexcept\n{\n return std::accumulate(items.begin(), items.end(), 0,\n [](int sum, const Item& item) { return sum + item.quantity_sold; });\n}\n</code></pre>\n\n<p>Similarly for <code>CalculateTotalSales</code>.</p>\n\n<h2>Most / least sold item</h2>\n\n<p>Similarly, use <a href=\"https://en.cppreference.com/w/cpp/algorithm/max_element\" rel=\"nofollow noreferrer\"><code>max_element</code></a> and <a href=\"https://en.cppreference.com/w/cpp/algorithm/mix_element\" rel=\"nofollow noreferrer\"><code>min_element</code></a>:</p>\n\n<pre><code>int Items::most_sold_index() const noexcept\n{\n auto it = std::max_element(items.begin(), items.end(),\n [](const Item& lhs, const Item& rhs)\n {\n return lhs.quantity_sold < rhs.quantity_sold;\n });\n return it - items.begin();\n}\nint Items::least_sold_index() const noexcept\n{\n auto it = std::min_element(items.begin(), items.end(),\n [](const Item& lhs, const Item& rhs)\n {\n return lhs.quantity_sold < rhs.quantity_sold;\n });\n return it - items.begin();\n}\n</code></pre>\n\n<p><code>int</code> is actually not the correct type for indexes. It doesn't matter in this case, but <code>std::vector<Items>::size_type</code> is better. Or <code>std::vector<Items>::const_iterator::difference_type</code> ...</p>\n\n<h1>Other calculations</h1>\n\n<p>Instead of the verbose</p>\n\n<blockquote>\n<pre><code>double Items::CalculateEstimatedOperationalCost()\n{\n double dTotalSales = CalculateTotalSales();\n double dEstimatedOperationalCost = dTotalSales * 0.5;\n return dEstimatedOperationalCost;\n}\ndouble Items::CalculateTaxPaid()\n{\n double dTaxPaid = CalculateTotalSales() * 0.2;\n return dTaxPaid;\n}\ndouble Items::CalculateProfit()\n{\n double dTotalProfit = 0;\n double dTotalSales = CalculateTotalSales();\n dTotalProfit = dTotalSales - CalculateTaxPaid() - CalculateEstimatedOperationalCost();\n return dTotalProfit;\n}\n</code></pre>\n</blockquote>\n\n<p>Do</p>\n\n<pre><code>double Items::estimated_operational_cost() const\n{\n return total_sales() * 0.5;\n}\ndouble Items::tax() const\n{\n return total_sales() * 0.2;\n}\ndouble Items::profit()\n{\n return total_sales() - tax() - estimated_operational_cost();\n}\n</code></pre>\n\n<p>This is a <em>lot</em> better.</p>\n\n<hr>\n\n<h1>Miscellaneous</h1>\n\n<p>Sort <code>#include</code> directives in alphabetical order to ease navigation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:07:38.910",
"Id": "462853",
"Score": "0",
"body": "First of all can I just say how thankful I am that you've taken the time to review my program and give me feedback on it as well fantastic solutions and simplifications. I'm truly indebted to you. I do have a slight problem with: auto it = std::find(items.begin(), items.end(),\n [&](const Item& item) { return item.name == name; }); I've added #include <algorithm> however it gives me a compiler error I'm not familiar with. What was that you said about + lamba?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:19:56.140",
"Id": "462858",
"Score": "0",
"body": "What does this mean? No matching function for call to object of type '(lambda at /Applications/Practice.cpp/Practice.cpp/Practice/doodle/Sale System/Sale System/Items.cpp:159:28)'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T18:55:34.490",
"Id": "462875",
"Score": "0",
"body": "I'm having problems implementing \"Delete an item\", \"Check for existence\", \"Calculate total quantity\", and \"Most / least sold item\". It's something to do with \"lambda\". Do you know the cause of this problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T05:17:27.753",
"Id": "462904",
"Score": "0",
"body": "@GeorgeAustinBradley Sorry, I made a mistake. The two `std::find`s should be `std::find_if`. And the argument to `std::accumulate` is wrong. Hopefully the interface of STL will get easier to use with the C++20 Ranges library!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:39:39.843",
"Id": "236231",
"ParentId": "236197",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236231",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T17:49:26.067",
"Id": "236197",
"Score": "2",
"Tags": [
"c++",
"beginner",
"c++11"
],
"Title": "Sales System Calculator"
}
|
236197
|
<p>I made the looks of asteroids using <code>pygame</code>. I still need to implement collisions but since it is running incredibly slow with 'amount' anything above 10. Please rip my code to shreds and explain why it is bad so that I can improve. :)</p>
<pre><code>import pygame
import pygame.locals
import numpy
import random
asteroids = []
paused = False
delta_angle = 0.01
amount = 5 # Anything above 5 makes it run much slower, above 10 makes it run really slow.
maxVelocity = 10
screen = (1600, 1200)
left_down, right_down = False, False
boost = False
pygame.init()
display = pygame.display.set_mode(screen, pygame.RESIZABLE)
background = pygame.Surface(screen)
clock = pygame.time.Clock()
class Boid:
def __init__(self):
self.position = numpy.array([0, 0])
self.velocity = numpy.array([0, 0])
self.acceleration = numpy.array([0, 0])
self.angle = 0
self.size = 1
def update(self):
self.position += self.velocity
self.velocity += self.acceleration
self.acceleration = 0
def rotation(angle):
rotation = numpy.array([[numpy.cos(angle), -numpy.sin(angle)], [numpy.sin(angle), numpy.cos(angle)]])
return rotation
def Ship(angle):
offset1 = numpy.array([[0.0, -15.0], [-10.0, 15.0], [0.0, 10.0], [10.0, 15.0], [-5.0, 12.5], [0.0, 20.0], [5.0, 12.5]])
ship = []
for i in range(len(offset1)):
offset1[i] = rotation(angle).dot(offset1[i])
ship.append(offset1[i])
return ship
def Asteroids(angle):
offset2 = numpy.array([[-10.0, 0.0], [-8.0, -5.0], [-5.0, -8.0], [0.0, -10.0], [6.0, -8.0], [9.0, -4.0], [4.0, -2.0], [10.0, 0.0], [7.0, 7.5], [2.5, 4.0], [0.0, 10.0], [-6.0, 8.0], [-9.0, 3.0], [-4.0, 0.0]])
asteroid = []
for i in range(len(offset2)):
offset2[i] = rotation(angle).dot(offset2[i])
asteroid.append(offset2[i])
return asteroid
def player_creator():
boid = Boid()
vec = numpy.random.random_sample(2) - numpy.array([0.5, 0.5])
boid.position = numpy.array([screen[0] / 2, screen[1] / 2])
boid.velocity = vec / numpy.linalg.norm(vec) * 5
boid.acceleration = numpy.array([0.0, 0.0])
if vec[0] < 0 and vec[1] > 0 or vec[0] < 0 and vec[1] < 0:
boid.angle = numpy.arctan((vec[1]) / (vec[0])) + numpy.pi
elif vec[0] > 0 and vec[1] < 0:
boid.angle = numpy.arctan((vec[1]) / (vec[0])) + 2 * numpy.pi
else:
boid.angle = numpy.arctan((vec[1]) / (vec[0]))
return boid
def drawing_player_creator():
vertices = player.position + player.velocity + numpy.array([Ship(angle)[0], Ship(angle)[1], Ship(angle)[2], Ship(angle)[3]])
pygame.draw.polygon(display, (0, 0, 0), (vertices), 0)
pygame.draw.polygon(display, (255, 255, 255), (vertices), 2)
player.update()
def drawing_booster_flames():
vertices = player.position + numpy.array([Ship(angle)[2], Ship(angle)[4], Ship(angle)[5], Ship(angle)[6]])
pygame.draw.polygon(display, (0, 0, 0), (vertices), 0)
pygame.draw.polygon(display, (255, 255, 255), (vertices), 2)
def asteroid_creator(amount):
for asteroid in range(amount):
asteroid = Boid()
vec = numpy.random.random_sample(2) - numpy.array([0.5, 0.5])
asteroid.position = numpy.random.random_sample(2) * screen
asteroid.velocity = vec / numpy.linalg.norm(vec)
asteroid.acceleration = numpy.array([0.0, 0.0])
asteroid.angle = numpy.random.random_sample(1)[0] * 2 * numpy.pi
asteroid.size = numpy.random.randint(2, 8)
asteroids.append(asteroid)
def drawing_asteroid_creator(amount):
for n in range(amount):
#pygame.draw.circle(display, (255 - (n / amount * 255), 255 - (n / amount * 255), 255 - (n / amount * 255)), (int(asteroids[n].position[0]), int(asteroids[n].position[1])), 21)
#pygame.draw.circle(display, (n / amount * 255, n / amount * 255, n / amount * 255), (int(asteroids[n].position[0]), int(asteroids[n].position[1])), 19)
asteroid_angle = asteroids[n].angle
vertices = asteroids[n].position + asteroids[n].size * numpy.array([(Asteroids(asteroid_angle)[0]), (Asteroids(asteroid_angle)[1]), (Asteroids(asteroid_angle)[2]), (Asteroids(asteroid_angle)[3]), (Asteroids(asteroid_angle)[4]), (Asteroids(asteroid_angle)[5]), (Asteroids(asteroid_angle)[6]), (Asteroids(asteroid_angle)[7]), (Asteroids(asteroid_angle)[8]), (Asteroids(asteroid_angle)[9]), (Asteroids(asteroid_angle)[10]), (Asteroids(asteroid_angle)[11]), (Asteroids(asteroid_angle)[12]), (Asteroids(asteroid_angle)[13])])
pygame.draw.polygon(display, (0, 0, 0), (vertices), 0)
pygame.draw.polygon(display, (255, 255, 255), (vertices), 2)
asteroids[n].update()
asteroid_creator(amount)
player = player_creator()
angle = player.angle + numpy.pi / 2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
if paused == False:
paused = True
elif paused == True:
paused = False
if event.key == pygame.K_LEFT:
left_down = True
if event.key == pygame.K_RIGHT:
right_down = True
if event.key == pygame.K_SPACE:
boost = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
left_down = False
if event.key == pygame.K_RIGHT:
right_down = False
if event.key == pygame.K_SPACE:
boost = False
if event.type == pygame.VIDEORESIZE:
screen = (event.w, event.h)
display = pygame.display.set_mode((screen), pygame.RESIZABLE)
background = pygame.Surface(screen)
if paused == False:
display.blit(background, (0, 0))
drawing_asteroid_creator(amount)
drawing_player_creator()
if left_down == True:
angle -= delta_angle * 2 * numpy.pi
#player.velocity = rotation(-delta_angle * 2 * numpy.pi).dot(player.velocity)
if right_down == True:
angle += delta_angle * 2 * numpy.pi
#player.velocity = rotation(delta_angle * 2 * numpy.pi).dot(player.velocity)
if boost == True:
drawing_booster_flames()
player.velocity += rotation(-numpy.pi / 2).dot(numpy.array([numpy.cos(angle), numpy.sin(angle)]) / 10)
if maxVelocity < numpy.linalg.norm(player.velocity):
player.velocity = maxVelocity * player.velocity / numpy.linalg.norm(player.velocity)
if player.position[0] > screen[0] + 15:
player.position[0] = 0
if player.position[0] < 0 - 15:
player.position[0] = screen[0]
if player.position[1] > screen[1] + 15:
player.position[1] = 0 - 15
if player.position[1] < 0 - 15:
player.position[1] = screen[1] + 15
for n in range(amount):
if asteroids[n].position[0] > screen[0] + asteroids[n].size * 15:
asteroids[n].position[0] = 0 - asteroids[n].size * 15
if asteroids[n].position[0] < 0 - asteroids[n].size * 15:
asteroids[n].position[0] = screen[0] + asteroids[n].size * 15
if asteroids[n].position[1] > screen[1] + asteroids[n].size * 15:
asteroids[n].position[1] = 0 - asteroids[n].size * 15
if asteroids[n].position[1] < 0 - asteroids[n].size * 15:
asteroids[n].position[1] = screen[1] + asteroids[n].size * 15
clock.tick(120)
pygame.display.update()
</code></pre>
|
[] |
[
{
"body": "<p>I'll focus mostly on the performance issue and only hint at a few design ones at the end.</p>\n\n<p>For this use-case, I'd say stay away from <code>numpy</code>. <code>numpy</code> has some pretty high overhead, which you tend to amortize by faster computations at a \"massive\" scale. Which is not the case here.</p>\n\n<p>You use <code>numpy</code> for vector addition and for trigonometric functions. In the latter case, you can see that using numpy is the wrong approach. A quick benchmark:</p>\n\n<pre><code>In [5]: import numpy as np \n\nIn [6]: %timeit np.cos(0.6) \n630 ns ± 19.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [7]: import math \n\nIn [8]: %timeit math.cos(0.6) \n70.7 ns ± 1.47 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [9]: from math import cos \n\nIn [10]: %timeit cos(0.6) \n44.1 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\n</code></pre>\n\n<p><code>numpy</code> is ~10x slower than pure Python, and importing the function locally which gives you an extra bump.</p>\n\n<p>For vectors of length 2, probably the overhead of using it is way higher than the computational wins. That's even more when you apply a trigonometric function to a single value (scalar). </p>\n\n<p>If you still want to go on with <code>numpy</code> you'd most likely want to focus on the <code>rotation</code> function.</p>\n\n<pre><code>def rotation(angle):\n rotation = numpy.array([[numpy.cos(angle), -numpy.sin(angle)], [numpy.sin(angle), numpy.cos(angle)]])\n return rotation\n</code></pre>\n\n<p>Here you calculate twice each trigonometric function used. you could just calculate each once and reuse it</p>\n\n<pre><code>def rotation_reuse(angle):\n c, s = numpy.cos(angle), numpy.sin(angle)\n return numpy.array(((c,-s), (s, c)))\n</code></pre>\n\n<p>Again, benchmarking this change</p>\n\n<pre><code>In [17] %timeit rotation(0.6) \n4.3 µs ± 252 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [18]: %timeit rotation_reuse(0.6) \n2.68 µs ± 30.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n\n<p>You can see that it takes basically half the time, as you could expect by doing half the amount of operations.</p>\n\n<p>And if we continue with what we learned already</p>\n\n<pre><code>In [20]: def new_rotation(angle): \n ...: c, s = cos(angle), sin(angle) \n ...: return numpy.array(((c,-s), (s, c))) \n ...: \n\nIn [21]: %timeit new_rotation(0.6) \n1.22 µs ± 18.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<p>Another 2x improvement, while keeping a <code>numpy</code> array as return value. This won't break the rest of your operations with the positions and velocities. You'd have to check if doing a manual loop to do those is faster or not than using <code>numpy</code>.</p>\n\n<p>Furthermore, on a more \"design\" level, you have a lot of duplicated code between the <code>Ship</code> and <code>Asteroid</code> functions. Here, you most likely should try to have a class and then create instances, and thus reducing the amount of duplication. </p>\n\n<p>Also, in Python, people tend to write class definitions with the first letter uppercase and functions all lowercase. You have <code>Ship</code> and <code>Asteroid</code> as functions. This ties with the previous paragraph, maybe you already kinda realized that those things are proper entities that deserve a more substantial modeling. </p>\n\n<p>Moreover, improve the doctrings of the functions. As it is now, it's rather hard for a casual reader to understand what's happening.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T14:31:02.337",
"Id": "462834",
"Score": "0",
"body": "Thanks for the feedback! I implemented the single vertices calculator but i think i made a mistake because all the objects now spin like crazy. Do you know why that might be?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T14:32:07.250",
"Id": "462835",
"Score": "0",
"body": "Probably you're applying the rotation action onto the objects at every tick of the game clock now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T14:36:50.907",
"Id": "462836",
"Score": "0",
"body": "I don't know where i am applying it again and again. :S I can't find it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T14:53:07.387",
"Id": "462838",
"Score": "0",
"body": "That's beyond what I can help with. Undo your changes and start again carefully."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T15:11:31.593",
"Id": "462843",
"Score": "0",
"body": "I did, thank you. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:58:04.280",
"Id": "236233",
"ParentId": "236198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T18:31:25.017",
"Id": "236198",
"Score": "2",
"Tags": [
"python",
"performance",
"numpy",
"pygame"
],
"Title": "Asteroids using pygame"
}
|
236198
|
<p>all!</p>
<p>I am developing a web "app" with JavaScript and jQuery with the help of a couple of other libraries for ease of use. </p>
<p>Its purpose is to collect user ID's and to build a list of "attackable" targets for the game at <a href="https://torn.com" rel="nofollow noreferrer">https://torn.com</a></p>
<p>Details for the API can be found at <a href="https://api.torn.com" rel="nofollow noreferrer">https://api.torn.com</a>, although I'm pretty sure it requires an account to do anything with it (needs an API Key, and I don't want to provide mine for security purposes)</p>
<p>The entirety of the site is on my <a href="https://git.ggez.me/kmorton1988/murdr.us-torn-hitlist" rel="nofollow noreferrer">gitlab instance</a></p>
<p>My biggest concern is whether or not I have created effective and efficient code to accomplish the purpose of the app. Specifically, the API call and data handling is what I am most concerned with here. </p>
<pre><code>
$.get( url, function( data ) {
var username = data.name;
var userlevel = data.level;
var userstatus = data.status.description;
var liuser = $('<li/>')
.addClass('userLevel')
.text(userlevel)
.appendTo(`ul.userListItem${value}`)
var liname = $('<li/>')
.addClass('userName')
.text(username)
.appendTo(`ul.userListItem${value}`);
var listatus = $('<li/>')
.addClass('userStatus')
.text(userstatus)
.appendTo(`ul.userListItem${value}`);
var liattack = $('<li/>')
.addClass('userAttack')
.html(`<a href="https://www.torn.com/loader.php?sid=attack&user2ID=${value}" class="button" target="_blank">Attack!</a>`)
.appendTo(`ul.userListItem${value}`);
var liremove = $('<li/>')
.addClass('userRemove')
.html(`<a href="javascript:removeUser(${value})" type="button" class="button" id='removeuser${id}'>x</a>`)
.appendTo(`ul.userListItem${value}`);
});
</code></pre>
<p>This feels like a <em>lot</em> of work to do within a single API call. It works, and can be demo'd on the site it currently lives on: <a href="https://murdr.us" rel="nofollow noreferrer">https://murdr.us</a></p>
<p>I'm also looking for a better input validation that can check for empty state or non-numbers entered and return an on-screen alert (rather than a browser alert as it currently shows). </p>
<p>here's the current validation method used: </p>
<pre><code>function empty() {
var x = $('input#useridValue').val();
if (x == "") {
alert("Enter a Valid User ID");
return false;
};
}
</code></pre>
<p>and the button that calls it: </p>
<pre><code>$("button#submitUser").click(function() {
if (empty() !== false ) {
var tempid = parseInt($('input#useridValue').val());
console.log(tempid)
addID(tempid);
$('input#useridValue').val("");
}
});
</code></pre>
<p>I greatly appreciate your time, folks. Hopefully, some insight and optimization techniques may be devised from this. </p>
<p>Thanks, all. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T18:38:24.757",
"Id": "236199",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"validation"
],
"Title": "App that Builds a list of \"targets\" for a Text-Based RPG using the games' API"
}
|
236199
|
<p>I made a program (C#, .NET) that calculates time for XML and CSV export and please I have a question for improving my knowledge in programming. Do you think that I can improve the structure of the program? Or what do you think about code refactoring? Way of solve... Is it good? I uploaded the project to github.
Thanks for your comments.</p>
<pre><code> t.SetupWriteStart(TestType.String); //that inicialize collection, stringreader, stringstringwriter
Time = CalculateTime(t.TestWriteString);
t.SetupWriteEnd(TestType.String); //delete this collection, close stringreader and writer
</code></pre>
<p><a href="https://github.com/Argellius/CalculateXMLCSV" rel="nofollow noreferrer">Github link</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T07:36:55.923",
"Id": "462778",
"Score": "3",
"body": "That's a very small piece of code you shared, we can't meaningfully review that. If you want the code on GitHub reviewed, please include the major parts of it in the question itself. We can't review code that's behind a link."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T19:07:17.077",
"Id": "236200",
"Score": "1",
"Tags": [
"c#",
".net"
],
"Title": "calculate time in data processing into XML and CSV"
}
|
236200
|
<h2>Problem</h2>
<p>HackerRank <a href="https://www.hackerrank.com/contests/source-code-series-1/challenges/sub-array-sum-range-query" rel="nofollow noreferrer">Range query</a>:</p>
<blockquote>
<p>You are given an array <code>A</code> of <code>n</code> integers. You have to perform <code>m</code>
queries on the array. The queries are of two types:</p>
<ol>
<li><p>Modify the <code>i</code>th element of the array.</p></li>
<li><p>Given <code>x</code>, <code>y</code>, print <code>min{Ai + Ai+1 +…+ Aj | x ≤ i ≤ j ≤ y}</code>.</p></li>
</ol>
<p><strong>Note:</strong> A brute force solution may not work; Try using an efficient data structure. Use fast I/O to avoid TLE.</p>
<h3>Input Format</h3>
<p>The first line contains an integer <code>t</code> denoting the number of test
cases.</p>
<p>The next line consists of an integer <code>n</code>.</p>
<p>The following line contains <code>n</code> integers representing the array <code>A</code>.</p>
<p>The next line contains an integer <code>m</code> denoting the number of queries.</p>
<p>The following <code>m</code> lines contain integers of the form given below.</p>
<ul>
<li><code>0 x y</code>: modify <code>Ax</code> into <code>y</code> </li>
<li><code>1 x y</code>: print <code>min{Ai + Ai+1 +…+ Aj | x ≤ i ≤ j ≤ y}</code></li>
</ul>
<h3>Constraints</h3>
<blockquote>
<p>1 ≤ t ≤ 100</p>
<p>1 ≤ n ≤ 50000</p>
<p>-10000 ≤ Ai ≤ 10000</p>
<p>0 ≤ m ≤ 50000</p>
</blockquote>
<h3>Output Format</h3>
<p>For each query print the output as specified.</p>
</blockquote>
<h2>My Solution</h2>
<h3>Algorithm</h3>
<ol>
<li>Calculate prefix sums <code>prefix_sums</code> for the given array.</li>
<li>For the given interval, move from left to right and keep track of the largest encountered value <code>max_prefix_sum</code> of <code>prefix_sums</code> and the minimum subsum <code>min_subsum</code> (<code>min_subsum = min(prefix_sums[i] - max_prefix_sum)</code> for <code>left=<i<=right</code>). In the end, <code>min_subsum</code> is the answer.</li>
<li>If some value of the initial array is updated then <code>prefix_sums</code> must be updated accordingly.</li>
</ol>
<p>The overall time complexity of the algorithm is O(n<sup>2</sup>). The space complexity is O(n). I know that for a O(n<sup>2</sup>) time complexity solution I don't need any additional array and there's a more elegant solution for this based on <a href="https://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="nofollow noreferrer">Maximum Subarray Problem</a>. However, it feels like with prefix sums I have a better chance of having a O(nlogn) or O(n<sup>1.5</sup>) time complexity solution.</p>
<h3>Code</h3>
<pre><code>import itertools
class MinSumRangeQuery:
prefix_sums = None
def __init__(self, array):
self.prefix_sums = list(itertools.accumulate(array))
def update(self, index, value):
diff = value - array[index]
for i in range(index, len(self.prefix_sums)):
self.prefix_sums[i] += diff
def min_subarray_sum(self, left, right):
if left == right:
return self.prefix_sums[left]
min_subsum = 99999999
max_prefix_sum = self.prefix_sums[left - 1]
for i in range(left, right + 1):
current_subsum = self.prefix_sums[i] - max_prefix_sum
if min_subsum > current_subsum:
min_subsum = current_subsum
if max_prefix_sum <= self.prefix_sums[i]:
max_prefix_sum = self.prefix_sums[i]
return min_subsum
for _ in range(int(input())):
n = int(input())
array = [int(i) for i in input().split()]
array.insert(0, 0)
minSumRangeQuery = MinSumRangeQuery(array)
for _ in range(int(input())):
a, x, y = [int(i) for i in input().split()]
if a == 1:
print(minSumRangeQuery.min_subarray_sum(x, y))
elif a == 0:
if array[x] != y:
minSumRangeQuery.update(x, y)
</code></pre>
<h2>Question</h2>
<p>Given the constraints above, the code times out for all but a default test case. What's a more efficient way to solve the problem?</p>
|
[] |
[
{
"body": "<h1>Introduction</h1>\n<p>I have come up with a more efficient solution in terms of the time complexity, although it's still not passing all the test cases. Nevertheless, I decided to post the solution, because it may help someone with a similar problem in the future.</p>\n<h1>Explanation</h1>\n<p>The idea is to divide an initial array into segments of size √n, and for each segment to pre-calculate <code>4</code> helper arrays - sum of elements, minimum sum of elements, minimum prefix sum (minimum sum starting from the first element of the bucket) and minimum suffix sum (minimum sum ending at the last element of the bucket).</p>\n<p>In such case, there are <code>3</code> possible use cases when calculating the min sum:</p>\n<ol>\n<li><p>Sum range is within the same bucket. Then, to calculate the minimum subsum there, do it brute force.</p>\n</li>\n<li><p>Sum range starts in one bucket and ends in a neighbouring bucket. Again, do brute force.</p>\n</li>\n<li><p>Sum range covers more than <code>2</code> buckets. That's the hardest case, and that's what for all the additional arrays are built. The minimum sum in the range can happen to be a minimum subsum in some bucket, or a minimum prefix, or a suffix, or a sum of the min suffix and prefix (both buckets are in the range), or a sum of all elements in the current bucket and "special" sum from previous matching buckets. The "special" sum is either a min suffix from the preceding matching bucket or sum of elements starting from some min suffix. Please see the code for more details.</p>\n</li>\n</ol>\n<p>When a value is updated, all <code>4</code> helper arrays have to be updated too, and that is done in O(√n) time.</p>\n<h1>Code</h1>\n<pre><code>import math\nimport sys\n\nclass MinSumRangeQuery:\n size = None\n array = None\n\n bucket_size = None\n bucket_sums = None\n min_prefix_sums = None\n min_suffix_sums = None\n min_subarray_sums = None\n\n def __init__(self, array):\n self.size = len(array)\n self.array = array\n\n self.bucket_size = int(math.sqrt(self.size))\n self.bucket_sums = [None] * (self.bucket_size)\n self.min_prefix_sums = [None] * (self.bucket_size)\n self.min_suffix_sums = [None] * (self.bucket_size)\n self.min_subarray_sums = [None] * (self.bucket_size)\n\n left = 0\n for i in range(self.bucket_size):\n right = left + self.bucket_size\n\n # sum of elements in a bucket\n self.bucket_sums[i] = sum(self.array[left:right])\n # calculate a min sum starting from the left position\n self.min_prefix_sums[i] = self.find_min_prefix(left, right)\n # calculate a min sum ending at the right position\n self.min_suffix_sums[i] = self.find_min_suffix(left, right)\n # calculate a min sum within the bucket\n self.min_subarray_sums[i] = self.find_min_subsum(left, right)\n left += self.bucket_size\n\n def find_min_prefix(self, left, right):\n min_prefix = self.array[left]\n current_prefix = min_prefix\n for i in range(left + 1, right):\n current_prefix += self.array[i]\n if current_prefix < min_prefix:\n min_prefix = current_prefix\n\n return min_prefix\n\n def find_min_suffix(self, left, right):\n min_suffix = self.array[right - 1]\n current_suffix = min_suffix\n for i in range(right - 2, left - 1, -1):\n current_suffix += self.array[i]\n if current_suffix < min_suffix:\n min_suffix = current_suffix\n\n return min_suffix\n\n def find_min_subsum(self, left, right):\n current_min_subsum = 0\n min_subsum = sys.maxsize\n\n for i in range(left, right):\n current_min_subsum = min(current_min_subsum + self.array[i],\n self.array[i])\n if current_min_subsum < min_subsum:\n min_subsum = current_min_subsum\n\n return min_subsum\n\n def find_min_in_range(self, left, right):\n current_bucket_id = int(left / self.bucket_size)\n end_bucket_id = int(right / self.bucket_size)\n current_right = min((current_bucket_id + 1) * self.bucket_size, right)\n\n current_min_subsum = self.find_min_suffix(left, current_right)\n min_sum = self.find_min_subsum(left, current_right)\n\n current_bucket_id += 1\n while current_bucket_id < end_bucket_id:\n min_prefix = self.min_prefix_sums[current_bucket_id]\n min_subsum = self.min_subarray_sums[current_bucket_id]\n min_suffix = self.min_suffix_sums[current_bucket_id]\n\n min_sum = min(min_sum, min_prefix + current_min_subsum)\n min_sum = min(min_subsum, min_sum)\n\n current_min_subsum = min(current_min_subsum + self.bucket_sums[current_bucket_id],\n min_suffix)\n min_sum = min(current_min_subsum, min_sum)\n\n current_bucket_id += 1\n\n current_left = current_bucket_id * self.bucket_size\n #if current_left < right:\n min_prefix = self.find_min_prefix(current_left, right)\n min_sum = min(current_min_subsum + min_prefix, min_sum)\n min_sum = min(self.find_min_subsum(current_left, right), min_sum)\n\n return min_sum\n\n def update(self, index, value):\n bucket_index = int(index / self.bucket_size)\n if bucket_index < self.bucket_size:\n self.bucket_sums[bucket_index] += (value - self.array[index])\n self.array[index] = value\n if bucket_index < self.bucket_size:\n left = bucket_index * self.bucket_size\n right = left + self.bucket_size\n self.min_suffix_sums[bucket_index] = self.find_min_suffix(left, right)\n self.min_prefix_sums[bucket_index] = self.find_min_prefix(left, right)\n self.min_subarray_sums[bucket_index] = self.find_min_subsum(left, right)\n\ntests = int(input())\n\nfor i in range(tests):\n size = int(input())\n\n array = [int(i) for i in input().split()]\n\n minSumRangeQuery = MinSumRangeQuery(array)\n\n queries = int(input())\n\n for _ in range(queries):\n a, x, y = [int(i) for i in input().split()]\n x -= 1\n\n if a == 1:\n print(minSumRangeQuery.find_min_in_range(x, y))\n elif a == 0 and array[x] != y:\n minSumRangeQuery.update(x, y) \n</code></pre>\n<h1>Algorithm Complexity</h1>\n<p>Time complexity of the algorithm is O(n√n), and space complexity is O(√n) because <code>4</code> arrays for each bucket have to be maintained.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-28T23:20:31.010",
"Id": "258821",
"ParentId": "236202",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T20:14:37.153",
"Id": "236202",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Given an integer array A and a range, find a subarray within the range with a minimum sum"
}
|
236202
|
<p>I'm trying to learn Python, so I started with a program to convert length units, mixing imperial and metric. First I wrote a bunch of small simple functions, but then I wanted to solve the issue of having an intuitive way of calling one function with some easy to remember parameter values in order to convert from any unit to any other unit, as opposed to having to call a bunch of different function names.</p>
<p>Does each instance of Convert remain in memory when I am using <code>__new__</code> and not actually returning an instance of the class? For example, since only a float is stored in 'x' at the end, is the instance of convert that was created destroyed?</p>
<p>Is this approach valid overall? It feels like I've done something a little strange here.</p>
<p><strong>Note</strong>: The code works on both Python 3 and 2.</p>
<pre><code>class Convert(object):
def __new__(self, val, unit_in, unit_out):
convertString = '%s_to_%s' % (unit_in, unit_out)
try:
convertFunction = getattr(self, convertString)
except:
return None
return convertFunction(self, val)
def mm_to_cm(self, millimeters):
return millimeters / 10.0
def mm_to_in(self, millimeters):
return ((millimeters / 1000.0) / 0.9144) * 36.0
def mm_to_ft(self, millimeters):
return ((millimeters / 1000.0) / 0.9144) * 3.0
def mm_to_m(self, millimeters):
return millimeters / 1000.0
def cm_to_mm(self, centimeters):
return centimeters * 10.0
def cm_to_in(self, centimeters):
return ((centimeters / 100.0) / 0.9144) * 36.0
def cm_to_ft(self, centimeters):
return ((centimeters / 100.0) / 0.9144) * 3.0
def cm_to_m(self, centimeters):
return centimeters / 100.0
def in_to_mm(self, inches):
return (((inches / 12.0) / 3.0) / (1.0 / 0.9144)) * 1000.0
def in_to_cm(self, inches):
return (((inches / 12.0) / 3.0) / (1.0 / 0.9144)) * 100.0
def in_to_ft(self, inches):
return inches / 12.0
def in_to_m(self, inches):
return (((inches / 12.0) / 3.0) / (1.0 / 0.9144))
def ft_to_mm(self, feet):
return (feet / 3.0) / (1.0 / 0.9144) * 1000.0
def ft_to_cm(self, feet):
return (feet / 3.0) / (1.0 / 0.9144) * 100.0
def ft_to_in(self, feet):
return feet * 12.0
def ft_to_m(self, feet):
return (feet / 3.0) / (1.0 / 0.9144)
def m_to_mm(self, meters):
return meters * 1000.0
def m_to_cm(self, meters):
return meters * 100.0
def m_to_in(self, meters):
return (meters / 0.9144) * 36.0
def m_to_ft(self, meters):
return (meters / 0.9144) * 3.0
print(Convert( 1.0, 'ft', 'in'))
print(Convert(12.0, 'in', 'ft'))
print(Convert( 0.3048, 'm', 'ft'))
x = Convert(3, 'ft', 'm')
print(x)
exit()
output:
12.0
1.0
1.0
0.9144
</code></pre>
|
[] |
[
{
"body": "<p>I think that it's a bit weird to use classes as a way to return values, I don't know if that's common in python, but anyways. The problem with your code, in my opinion, is that if you are converting a unit to another, ex: cm to in, you don't need to create a class that will store information about other units, like: inches to m. That ends up happening in your code whenever you do <code>print(Convert(val, unit_in, unit_out))</code>.\nHere's my solution:</p>\n\n<pre><code>class LengthUnit():\n # This class stores the unit's ratio to all the others\n def __init__(self, to_mm, to_cm, to_m, to_in, to_ft):\n self.to_mm = to_mm\n self.to_cm = to_cm\n self.to_m = to_m\n self.to_in = to_in\n self.to_ft = to_ft\n\n# This function returns the conversion of the value\n# The value is divided by the first number in the ratio,\n# and multiplied by the second number (it's a tuple).\ndef convert_unit(val, unit_in, unit_out):\n unit_out = 'to_{}'.format(unit_out)\n try:\n return val / getattr(unit_in, unit_out)[0] * getattr(unit_in, unit_out)[1]\n except AttributeError:\n return 'Invalid Units'\n\nif __name__ == '__main__':\n # In this dictionary, you store all the unit classes\n length_units = {'mm' : LengthUnit(to_mm= (1.0, 1.0), to_cm= (0.1, 1.0), to_m= (0.001, 1.0), to_in= (25.4, 1), to_ft= (305, 1)),\n 'cm' : LengthUnit(to_mm= (1.0, 10), to_cm= (1.0, 1.0), to_m= (100.0, 1.0), to_in= (2.54, 1), to_ft=(30.48, 1.0)),\n 'm' : LengthUnit(to_mm= (1.0, 1000), to_cm= (1.0, 100.0), to_m= (1.0, 1.0), to_in= (1.0, 39.37), to_ft=(1.0, 3.281)),\n 'in' : LengthUnit(to_mm= (1.0, 25.4), to_cm= (1.0, 2.54), to_m= (39.37, 1.0), to_in=(1.0, 1.0), to_ft= (12.0, 1)),\n 'ft' : LengthUnit(to_mm= (1.0, 305), to_cm= (1.0, 30.48), to_m= (3.281, 1.0), to_in= (1, 12.0), to_ft= (1.0, 1.0))\n }\n\n print(convert_unit(5, length_units['cm'], 'm'))\n print(convert_unit(10, length_units['ft'], 'mm'))\n print(convert_unit(23, length_units['in'], 'm'))\n # If a non-defined unit is parsed, a error message is printed.\n print(convert_unit(5, length_units['mm'], 'miles'))\n</code></pre>\n\n<p>This is all a rough sketch, you can adjust the values if you want them to be more exact, or change the function if you want it to print the values instead of returning them.\nHope it was helpful! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:33:46.243",
"Id": "464413",
"Score": "0",
"body": "Re classes, this thread https://stackoverflow.com/questions/35988/c-like-structures-in-python is the origin of my (work in progress!) approach in aiming to use classes like structs. Thank you for the ideas!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T02:19:51.417",
"Id": "236213",
"ParentId": "236203",
"Score": "6"
}
},
{
"body": "<p>Firstly as <a href=\"https://codereview.stackexchange.com/a/236213\">highlighted by Tlomoloko</a> using a class for this is <em>really</em> strange.</p>\n\n<p>However I think the both of your are missing something rather important. If you wanted to hand write every <a href=\"https://en.wikipedia.org/wiki/International_System_of_Units#Prefixes\" rel=\"noreferrer\">SI prefix</a> for metres alone then you'll rack up an unmaintainable amount of code. The table contains 21 prefixes, such as no prefix - m, centi - cm, and kilo - km. Whilst I'm sure many conversions you'll think are ridiculous. Who needs to convert from yoctometres to yottametres? But what's the harm in supporting it, if you allow something reasonable like zetta to yotta?</p>\n\n<p>To write the conversions for all SI prefixes would require only <span class=\"math-container\">\\$\\binom{21+1}{2}\\$</span> or 231 bespoke functions. Which would be absolutely ridiculous to write by hand.</p>\n\n<p>And so the solution to this is to have an intermarry value that you always convert to or from. And since all of your existing functions are nice simple multiplications or divisions we can simply assign a single value for each unit.</p>\n\n<p>This may be a bit hard to visualize, and so we'll run through some examples.</p>\n\n<h3>Example</h3>\n\n<ul>\n<li><p>1 cm to mm</p>\n\n<p>1 cm = 0.01 m<br>\n1 mm = 0.001 m</p>\n\n<p>First we convert 1 cm to metres. This is as simple as <span class=\"math-container\">\\$1 \\times 0.01\\$</span>. Afterwards we convert from metres to millimetres simply as <span class=\"math-container\">\\$\\frac{1 \\times 0.01}{0.001}\\$</span>.</p>\n\n<p>Which results in 10.</p></li>\n<li><p>1' to inches</p>\n\n<p>1' = 0.3048 m<br>\n1\" = 0.0254 m</p>\n\n<p>First we convert 1' to meters. This is as simple as <span class=\"math-container\">\\$1 \\times 0.3048\\$</span>. Afterwards we convert from metres to foot simply as <span class=\"math-container\">\\$\\frac{1 \\times 0.3048}{0.0254}\\$</span>.</p>\n\n<p>Which results in 12.</p></li>\n</ul>\n\n<h3>Code</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>CONVERSIONS = {\n 'm': 1,\n 'cm': 0.01,\n 'mm': 0.001,\n 'in': 0.0254,\n 'ft': 0.3048,\n}\n\ndef convert(value, unit_in, unit_out):\n return value * CONVERSIONS[unit_in] / CONVERSIONS[unit_out]\n\n\nprint(convert( 1.0, 'ft', 'in'))\nprint(convert(12.0, 'in', 'ft'))\nprint(convert(0.3048, 'm', 'ft'))\nprint(convert(3, 'ft', 'm' ))\n</code></pre>\n\n<p>Now the code's not perfect. If you run it you should instantly notice that it outputs some ugly 12.000000000000002 rather than 12.0. Yuck.</p>\n\n<p>And so we can convert your code to use <code>fractions.Fraction</code>. However this will print 1143/1250 rather than 0.9144. Since I dislike getting 12.0 rather than 12, we can fix these at the same time.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Dict, Union\nfrom fractions import Fraction\n\nNumber = Union[int, float]\nCONVERSIONS: Dict[str, Fraction] = {\n 'm': Fraction('1'),\n 'cm': Fraction('0.01'),\n 'mm': Fraction('0.001'),\n 'in': Fraction('0.0254'),\n 'ft': Fraction('0.3048'),\n}\n\n\ndef to_number(value: Fraction) -> Number:\n if value % 1:\n return float(value)\n else:\n return int(value)\n\n\ndef convert(value: Number, unit_in: str, unit_out: str) -> Number:\n return to_number(value * (CONVERSIONS[unit_in] / CONVERSIONS[unit_out]))\n\n\nif __name__ == '__main__':\n print(convert( 1.0, 'ft', 'in'))\n print(convert(12.0, 'in', 'ft'))\n print(convert( 0.3048, 'm', 'ft'))\n print(convert( 3, 'ft', 'm'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:04:44.887",
"Id": "464407",
"Score": "0",
"body": "I was using a class as sort of a stand-in for a struct. My posted code did not entirely reflect my intent as I was still studying the notion of \"data classes\" https://docs.python.org/3/library/dataclasses.html I appreciate your criticisms and approach and will study the fractions module."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:35:30.350",
"Id": "464487",
"Score": "0",
"body": "@AlanK I don't think using any of a class, a dataclass, or a named tuple would be beneficial here. Please understand that any deception in a question can lead to drastically different answers. In the future please post your finished code verbatim for the best experience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:08:50.960",
"Id": "464667",
"Score": "0",
"body": "Deception? I think you should choose another word. I said my code did not entirely reflect my intent because I was still studying data classes. To put it another way, I didn't understand data classes yet, so my example code did not reflect the correct implementation of one. That is not \"deception\". Deception suggests an _intent_ to mislead, and I certainly had no such intent. I don't know if English is your first language or not, but in common parlance, to call someone \"deceptive\" is about the same as calling them a liar. Harsh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:44:35.617",
"Id": "464674",
"Score": "0",
"body": "@AlanK At no point did I call you deceptive or a liar."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T19:15:03.900",
"Id": "236311",
"ParentId": "236203",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "236311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T20:24:03.070",
"Id": "236203",
"Score": "7",
"Tags": [
"python",
"unit-conversion"
],
"Title": "Pythonic attempt at conversion of length"
}
|
236203
|
<p>I've wrote a simulation of Langton's Ant in Java, and hope you have some suggestions to improve the code.</p>
<p>The class <strong>Control.java</strong> contains just the <code>main</code>:</p>
<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
public class Control {
static boolean exit = false;
public static void main(String[] args) throws InterruptedException, IOException {
LangtonsAnt langtonsAnt = new LangtonsAnt(71, 71);
Gui gui = new Gui(langtonsAnt);
gui.setVisible(true);
while(!exit) {
gui.render();
Thread.sleep(10);
}
}
}
</code></pre>
<p>The class <strong>Gui.java</strong> has the task to create and run the GUI:</p>
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Gui extends JFrame {
LangtonsAnt langtonsAnt;
JPanel panel;
JButton button;
private final int BOX_DIM = 10;
public Gui(LangtonsAnt langtonsAnt) {
this.langtonsAnt = langtonsAnt;
setSize(830, 740);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
JPanel subPanel = new JPanel();
subPanel.setLayout(new java.awt.GridLayout(3, 1));
panel.setPreferredSize(new Dimension(710, 710));
button = new JButton("Start / Stop");
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
onButtonClick();
}
});
JButton button2 = new JButton("Faster");
button2.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
langtonsAnt.faster();
}
});
JButton button3 = new JButton("Slower");
button3.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
langtonsAnt.slower();
}
});
add(panel, BorderLayout.WEST);
subPanel.add(button);
subPanel.add(button2);
subPanel.add(button3);
add(subPanel, BorderLayout.EAST);
setVisible(true);
}
private void onClose() {
Control.exit = true;
}
private void onButtonClick() {
isRunning = !isRunning;
}
private int countedFrames = 1;
boolean isRunning = false;
public void render() {
countedFrames++;
if(isRunning && countedFrames % langtonsAnt.speed == 0) {
langtonsAnt.tick();
countedFrames = 1;
}
Graphics graphic = panel.getGraphics();
for (int i = 0; i < langtonsAnt.getWidth(); i++) {
for (int j = 0; j < langtonsAnt.getHeight(); j++) {
if(langtonsAnt.get(i, j) == 0) {
graphic.setColor(Color.WHITE);
}
else if(langtonsAnt.get(i, j) == 1) {
graphic.setColor(Color.BLACK);
}
else if(langtonsAnt.get(i, j) == 2) {
graphic.setColor(Color.RED);
}
else if(langtonsAnt.get(i, j) == 3) {
graphic.setColor(Color.GREEN);
}
graphic.fillRect(i * BOX_DIM, j * BOX_DIM, BOX_DIM, BOX_DIM);
}
}
}
public static void antDied() {
JOptionPane.showMessageDialog(null,"Ant died.");
}
}
</code></pre>
<p>And finally, the class <strong>LangtonsAnt.java</strong> is responsible for the logic:</p>
<pre class="lang-java prettyprint-override"><code>public class LangtonsAnt {
private int[][] world;
private int width;
private int height;
public int speed = 10;
public LangtonsAnt(int width, int height) {
this.width = width;
this.height = height;
world = new int[width][height];
//Field edge is getting filled up with '2'
for(int i = 0; i < world.length; i++){
for(int j = 0; j < world.length; j++){
world[i][j] = 2;
}
}
//Field gets filled up with '0' = white cells; '1' will be used for black cells; '3' for the ant
for(int i = 1; i < world.length - 1; i++){
for(int j = 1; j < world.length - 1; j++){
world[i][j] = 0;
}
}
world[35][35] = 3;
}
public void tick() {
applyRules();
}
public int get(int x, int y) {
return world[x][y];
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void clear() {
for(int i = 1; i < world.length - 1; i++){
for(int j = 1; j < world.length - 1; j++){
world[i][j] = 0;
}
}
}
public void faster() {
if(speed - 5 > 0) {
speed = speed - 5;
}
}
public void slower() {
speed = speed + 5;
}
private String color = "WHITE";
private String direction = "DOWN";
private void applyRules() {
int length = world.length;
int x = 0;
int y = 0;
for(int i = 0; i < length; i++) {
for(int j = 0; j < length; j++) {
if(world[i][j] == 3) {
x = i;
y = j;
}
}
}
if(color.equals("BLACK")) {
if(direction.equals("UP")) {
direction = "LEFT";
}
else if(direction.equals("DOWN")) {
direction = "RIGHT";
}
else if(direction.equals("RIGHT")) {
direction = "UP";
}
else if(direction.equals("LEFT")) {
direction = "DOWN";
}
}
else if(color.equals("WHITE")) {
if(direction.equals("UP")) {
direction = "RIGHT";
}
else if(direction.equals("DOWN")) {
direction = "LEFT";
}
else if(direction.equals("RIGHT")) {
direction = "DOWN";
}
else if(direction.equals("LEFT")) {
direction = "UP";
}
}
int xDirection = 0;
int yDirection = 0;
if(direction.equals("UP")) {
xDirection = 0;
yDirection = -1;
}
else if(direction.equals("DOWN")) {
xDirection = 0;
yDirection = 1;
}
else if(direction.equals("RIGHT")) {
xDirection = 1;
yDirection = 0;
}
else if(direction.equals("LEFT")) {
xDirection = -1;
yDirection = 0;
}
if(color.equals("WHITE")) {
world[x][y] = 1;
}
else if(color.equals("BLACK")) {
world[x][y] = 0;
}
if(x + xDirection < 69 && y + yDirection < 69) {
if(world[x + xDirection][y + yDirection] == 0) {
color = "WHITE";
}
else if(world[x + xDirection][y + yDirection] == 1) {
color = "BLACK";
}
world[x + xDirection][y + yDirection] = 3;
}
else {
Gui.antDied();
world[x][y] = 1;
Control.exit = true;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I reviewed <code>LangtonsAnt.java</code> only.</p>\n\n<h2>Observe Separation of concerns</h2>\n\n<p>The class violates this <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">principle</a> . The class is responsible for both applying Langton's Ant rules, and implementing the world as two dimension array. these are two separate topics that may have multiple implementations. the rules engine should be concerned with deciding where is the next position of the ant and possibly color change of one or more cells. the world can be implemented as array, some collection or something else (even a <code>String</code> is viable, as it have indices of its characters) and it knows how to represent state and movement, it knows to get current position of the ant (possibly multiple ants?), and perhaps other features (undo?)</p>\n\n<h2>Avoid magic numbers and String literals</h2>\n\n<p>instead of explaining the possible values a cell can have in comments, make constants:<br>\n<code>public static final int WHITE_CELL = 0;</code><br>\nor better yet - if a variable can hold a finite predefined set of values - make it an enum. this is especially useful for the direction literals. this way you get the compiler to check for typos.</p>\n\n<p>another added bonus of enum is that it supports conversion of String value from/to int (ordinal). so you do not need to ask on the String value when populating the matrix with int values.</p>\n\n<h2>Express the state machine in map</h2>\n\n<p>applying the rules of Langton's Ant is implemented as a set of if statements. this is error prone and cumbersome. a better way is to implement the rules as set of key-value pairs that can be put in a map. you can concatenate the key factors (color + direction) and get the desired direction. this way you can read the rules from file as String key value pairs and support different set of rules! (and have it in one <code>RuleEngine</code> class that is responsible for that only!)</p>\n\n<h2>Duplicated Code</h2>\n\n<p>The constructor fills the world with zeros. but this is exactly what's done in <code>clear()</code></p>\n\n<h2>Fill array with zeros</h2>\n\n<p>while on the subject, Java 8 added <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#setAll-int:A-java.util.function.IntUnaryOperator-\" rel=\"nofollow noreferrer\"><code>setAll()</code></a> to Arrays class. it works on one dimensional array, so it saves the inner loop. However, it so happens that <code>0</code> is the default value for uninitialized int, so declaring a new (one dimension) array gives you the desired result. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T08:20:08.937",
"Id": "236218",
"ParentId": "236204",
"Score": "2"
}
},
{
"body": "<h2>The GUI</h2>\n\n<p>Usually, in the \"view\" side, you can decompose your frames in many components, this <strong>smart and dumb components</strong> pattern is a simple one that give a better structure to your code.</p>\n\n<p>You can extract one class for the buttons and another for the grid. You can also create a subclass of <code>JButton</code> for all of your buttons and use the fancy lambdas notations for a concise syntax :</p>\n\n<pre><code>public Gui(LangtonsAnt langtonsAnt) {\n this.simulation = langtonsAnt;\n\n worldGrid = new WorldGrid(simulation);\n\n JPanel buttons = new VerticalStackPanel( // Your Jpanel with GridLayout\n new ActionButton(\"Start / Stop\", this::onStartStop),\n new ActionButton(\"Faster\", langtonsAnt::increaseSpeed),\n new ActionButton(\"Slower\", langtonsAnt::decreaseSpeed)\n );\n\n add(worldGrid, BorderLayout.CENTER);\n add(buttons, BorderLayout.EAST);\n\n setSize(\n worldGrid.getWidth() + BUTTONS_WIDTH + ARBITRARY_SPACE,\n worldGrid.getHeight() + ARBITRARY_SPACE);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n // duplicated setVisible(true) removed, alrdeay called in your Control.\n}\n</code></pre>\n\n<h2>The core, LangtonsAnt</h2>\n\n<p>Your code contains some <strong>magic numbers</strong>, you can replace them by constants to reduce the cognitive load and improve the readability. </p>\n\n<p>You have a <code>speed</code> field that is accessible from all classes. However it is subject to some rules. So it is better to <strong>encapsulate</strong> it under a getter so that other classes cannot change it, they have to use your method to increase and decrease it. It can also be a good improvement to rename your <code>slower</code> and <code>faster</code> method to <code>decraseSpeed</code> and <code>increaseSpeed</code> so that the relation between those two methods and the <code>getSpeed</code> accessor is clear.</p>\n\n<p>In your system, the speed is part of the GUI so it may be better to move it to the GUI or remove it form the <code>LangtonsAnt</code> class to improve the <strong>separation of concerns</strong>. For the same goal you could also find a way to remove the static call to <code>Gui.antDied()</code> and <code>Control.exit = true</code> because it add two useless and non explicit dependencies. </p>\n\n<p>It looks like there is a bit of repetition in your rules. The proposal of @sharon is a good idea. However it don't use the power of OOP, I believe it would be a good exercise because there are a lot of possibles implementations. </p>\n\n<p>To have an idea, mine will have one class that represent the map, encapsulate the two dimensional array and provide a <code>Cell</code> abstraction. One <code>Ant</code> that hold the state of the system (current cell and direction) and produce movements that can be executed to mutate the map.</p>\n\n<pre><code>class WorldMap {\n private static final int WHITE_CELL = 1;\n private static final int BLACK_CELL = 0;\n\n private final int[][] map;\n\n // ..\n\n public Cell getCellAt(int x, int y)\n\n public void execute(Movement movement)\n\n class Cell {\n final int x, y;\n\n private void toggle() {\n world.map[y][x] ^= 1;\n }\n\n public boolean isWhite() {\n return get() == WHITE_CELL;\n }\n\n public Direction change(Direction direction) {\n return isWhite()\n ?direction.turnLeft()\n :direction.turnRight();\n }\n\n // ...\n } \n}\n\nclass Ant {\n\n private Direction direction = new Direction(Direction.UP);\n private Cell position;\n\n // ...\n\n class Direction {\n private static final int ROTATION = 90;\n private static final int UP = 0;\n private static final int RIGHT = UP + ROTATION;\n private static final int DOWN = RIGHT + ROTATION;\n private static final int LEFT = DOWN + ROTATION;\n private final int angle;\n\n Direction(int angle) {\n this.angle = angle;\n }\n\n public Direction turnRight() {\n return new Direction((angle + ROTATION) % 360);\n }\n }\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T09:39:09.907",
"Id": "236221",
"ParentId": "236204",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T21:42:26.740",
"Id": "236204",
"Score": "2",
"Tags": [
"java",
"swing",
"gui"
],
"Title": "Langton's Ant in Java"
}
|
236204
|
<p>When I am developing in Bootstrap, I need to make sure that what is on the screen looks good. Bootstrap have various cutoff points where the flow can change. So to help with the visual debugging, I have created this tool that just shows what the current screen is according to Bootstrap. </p>
<pre><code><cfscript>
sizes = [
{ "styleClass" : "d-block d-sm-none", "name" : "Extra small", "look" : "warning"},
{ "styleClass" : "d-none d-sm-block d-md-none", "name" : "Small", "look" : "info"},
{ "styleClass" : "d-none d-md-block d-lg-none", "name" : "Medium", "look" : "success"},
{ "styleClass" : "d-none d-lg-block d-xl-none", "name" : "Large", "look" : "primary"},
{ "styleClass" : "d-none d-xl-block", "name" : "Extra large", "look" : "dark"}
];
sizes.each(function(item){
writeoutput("<p class='#item.styleClass#'><span class='badge badge-#item.look#'>#item.name#</span></p>");
})
</cfscript>
</code></pre>
<p>Is there additional information that can/should be shown.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T21:42:56.147",
"Id": "236205",
"Score": "1",
"Tags": [
"twitter-bootstrap",
"coldfusion"
],
"Title": "Generates HTML to show current Bootstrap screen size"
}
|
236205
|
<p>This is a function for checking if the checksum provided by <code>card[]</code> is valid. <code>card[]</code> contains six pairs of characters. The first five pairs make up a hexadecimal number, and the last pair contains the checksum. The checksum is valid if it is equal to XOR of the first five pairs.</p>
<p>It is working fine, but the code is awful. I was trying to use a nested loop, but it wasn't working. Now I'm getting pairs from <code>card[]</code>, converting them into numbers and checking whether the checksum is valid.</p>
<pre><code>bool checksum(char card[])
{
int a=0;
char character0[2];
char character1[2];
char character2[2];
char character3[2];
char character4[2];
char character5[2];
long n0,n1,n2,n3,n4,n5;
char card_number;
for(int i=0;i<2;i++)
{
for(a=0;a<2;a++)
{
character0[a]=card[i];
}
}
for(int i=2;i<4;i++)
{
for(a=0;a<2;a++)
{
character1[a]=card[i];
}
}
for(int i=4;i<6;i++)
{
for(a=0;a<2;a++)
{
character2[a]=card[i];
}
}
for(int i=6;i<8;i++)
{
for(a=0;a<2;a++)
{
character3[a]=card[i];
}
}
for(int i=8;i<10;i++)
{
for(a=0;a<2;a++)
{
character4[a]=card[i];
}
}
for(int i=10;i<12;i++)
{
for(a=0;a<2;a++)
{
character5[a]=card[i];
}
}
n0 = strtol(character0, NULL, 16);
n1 = strtol(character1, NULL, 16);
n2 = strtol(character2, NULL, 16);
n3 = strtol(character3, NULL, 16);
n4 = strtol(character4, NULL, 16);
n5 = strtol(character5, NULL, 16);
if(n0^n1^n2^n3^n4==n5) return true;
else return false;
}
</code></pre>
<p>The input for the example is "1E00EDE5E5F3", so 1E^00^ED^E5^E5 should be F3.</p>
<p>And something is wrong with this code. I see it now, because</p>
<pre><code>if(n0^n1^n2^n3^n4==n5) return true;
else return false;
</code></pre>
<p>is working good, but</p>
<pre><code>if((n0^n1^n2^n3^n4)==n5)) return true;
else return false;
</code></pre>
<p>is not working at all.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T09:11:24.203",
"Id": "463083",
"Score": "3",
"body": "Obvious nitpick here, but your aim shouldn't be to make it \"shorter\". It should be to make it \"better\". I know that's what you mean, but it's always worth pointing out that the two are not necessarily equivalent."
}
] |
[
{
"body": "<p>The most obvious issue is that you create excessive double loops for the same type of array initialisations.</p>\n\n<h2>Convert similar loops into one</h2>\n\n<p>Instead of creating <code>6</code> separate double loops for each <code>character</code> array, set each array in the same double loop:</p>\n\n<pre><code>...\nfor(int i=0;i<2;i++) {\n for(a=0;a<2;a++) {\n character0[a]=card[i];\n character1[a]=card[i + 2];\n character2[a]=card[i + 4];\n character3[a]=card[i + 6];\n character4[a]=card[i + 8];\n character5[a]=card[i + 10];\n }\n}\n...\n</code></pre>\n\n<p>This change alone will make your code much shorter and more readable already. IT can be simplified even further - check the answer from @Craig Estey.</p>\n\n<h2>Minor improvements</h2>\n\n<ul>\n<li>Your <code>char card_number;</code> is never used so you can simply remove it.</li>\n<li>Declaring <code>a</code> outside of your loops is not necessary. You can create it within a <code>for</code> loop as <code>for(int a=0; a<2; a++)</code>.</li>\n<li>Maybe <code>n1</code> or <code>n2</code> and so on could have better names but I fail to come up with any. </li>\n<li><p>As mentioned by @PeterMortensen, indentation in your code should be more consistent. For example, in your loop your <code>character</code> array is indented as:</p>\n\n<pre><code>for(a=0;a<2;a++)\n{\ncharacter0[a]=card[i];\n}\n</code></pre>\n\n<p>But then in another <code>for</code> loop as:</p>\n\n<pre><code>for(a=0;a<2;a++)\n{\n character4[a]=card[i];\n}\n</code></pre>\n\n<p>Also, indentation for local variables declaration and <code>return</code> statements is different from that of the <code>for</code> loops.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T22:42:52.870",
"Id": "236210",
"ParentId": "236206",
"Score": "8"
}
},
{
"body": "<p>Use a 2D array instead of 6 1D arrays (vs. <code>character0</code>, <code>character1</code>, ...)</p>\n\n<p>Use a 1D array for <code>n</code> instead of (<code>n0</code>, <code>n1</code>, ...)</p>\n\n<p>Add EOS termination to the string that gets passed to <code>strtol</code></p>\n\n<p>Here's a refactored version:</p>\n\n<pre><code>bool\nchecksum(char card[])\n{\n char chars[6][3];\n long nx[6];\n\n for (int col = 0; col < 6; ++col) {\n int lo = col << 1;\n int hi = lo + 2;\n for (int i = lo; i < hi; ++i)\n chars[col][i - lo] = card[i];\n }\n\n for (int i = 0; i < 6; ++i) {\n char *ptr = chars[i];\n ptr[2] = 0;\n nx[i] = strtol(ptr,NULL,16);\n }\n\n if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5])\n return true;\n else\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Here's a cleaner/simpler version:</p>\n\n<pre><code>bool\nchecksum(char card[])\n{\n char tmp[3];\n long nx[6];\n\n tmp[2] = 0;\n for (int col = 0; col < 6; ++col) {\n int lo = col << 1;\n\n tmp[0] = card[lo + 0];\n tmp[1] = card[lo + 1];\n\n nx[col] = strtol(tmp,NULL,16);\n }\n\n if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5])\n return true;\n else\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #2:</strong></p>\n\n<p>Here's an even simpler version:</p>\n\n<pre><code>bool\nchecksum(char card[])\n{\n char tmp[3];\n long nx;\n\n tmp[2] = 0;\n nx = 0;\n for (int idx = 0; idx < 12; idx += 2) {\n tmp[0] = card[idx + 0];\n tmp[1] = card[idx + 1];\n\n nx ^= strtol(tmp,NULL,16);\n }\n\n if (nx == 0)\n return true;\n else\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #3:</strong></p>\n\n<p>Based on some feedback ...</p>\n\n<p>The first two examples above, were to eliminate \"parallel scalar\" variables (e.g.) <code>v0, v1, v2, ... vN</code> in favor of an array: <code>v[N+1]</code>. This allowed replicated code to be replaced with loops. OP's code had two such instances for <code>character*</code> and <code>n*</code> variables, so I converted both to arrays.</p>\n\n<p>When starting out [as a programmer], when to use an array isn't always obvious [particularly for small numbers]. In the above case, <code>N</code> was 6. So, the code could be built up by cut-and-paste.</p>\n\n<p>If, however, <code>N</code> had been a much larger number, say, 1000, the original code would then not <em>scale</em> well. And, the array solution would have become [more] obvious.</p>\n\n<p>OP's code was trying to copy two bytes from the buffer into different <code>char</code> arrays of the form <code>character*</code> in the first code block [to add an EOS char to allow <code>strtol</code> to work]. This still had a bug because there was no space for the EOS.</p>\n\n<p>OP's second block would use <code>strtol</code> on the intermediate <code>character*</code> variables to produce <code>n*</code> variables.</p>\n\n<p>My first example [in my <em>original</em> post], did the conversion from separate scalar variables to arrays.</p>\n\n<p>My second example [in my first update], combined both blocks/loops into one, so that <code>character*</code> [which I had replaced with the 2D <code>chars</code> array], could be eliminated with a single <code>tmp</code> array.</p>\n\n<p>When I did my example in update #2, I assumed that OP's algorithm was correct. I didn't realize that:</p>\n\n<pre><code>if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5])\n</code></pre>\n\n<p>was being interpreted [by the compiler, based on precedence] as:</p>\n\n<pre><code>if (nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ (nx[4] == nx[5]))\n</code></pre>\n\n<p>I assumed it was grouped as:</p>\n\n<pre><code>if ((nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4]) == nx[5])\n</code></pre>\n\n<p>Because that's what made sense for the CRC calculations [and I assumed OP had done it correctly].</p>\n\n<p>My refinement [to eliminate the <code>nx</code> <em>array</em> in favor of a running CRC], was based on the following identity:</p>\n\n<pre><code>(x == y) === ((x ^ y) == 0)\n</code></pre>\n\n<p>So, XORing all values (including the checksum), if the message was correct/intact, would produce a final value of zero. So, by doing this, I fixed OP's second bug, based on some serendipity.</p>\n\n<p>Others have pointed out that:</p>\n\n<pre><code>if (nx == 0)\n return true;\nelse\n return false;\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>return (nx == 0);\n</code></pre>\n\n<p>I had debated doing that, but decided that the example was already far afield from OP's original and that it would be clearer to leave the <code>return</code> sequence as it was. And, the optimizer would [probably] produce the same exact code for both.</p>\n\n<p>At that point, I had debated coming up with a <code>hex</code> function that decoded a single hex char as others have suggested, calling it twice and eliminating the copy to <code>tmp</code> and call to <code>strtol</code>, but, again, felt I was getting far enough away from the original code.</p>\n\n<p>But, just for the sake of completeness, here is my final/best example, generalized to allow an arbitrary buffer size:</p>\n\n<pre><code>unsigned int\nhex(unsigned int chr)\n{\n\n // NOTE: hopefully, this function gets inlined ...\n\n do {\n if ((chr >= '0') && (chr <= '9')) {\n chr -= '0';\n break;\n }\n\n chr = tolower(chr);\n\n if ((chr >= 'a') && (chr <= 'f')) {\n chr -= 'a';\n chr += 10;\n break;\n }\n\n // should blow up here (but there was no error checking in original)\n chr = 0;\n } while (0);\n\n return chr;\n}\n\nbool\nchecksum(const char *card,size_t len)\n{\n unsigned int cur;\n unsigned int crc = 0;\n\n for (size_t idx = 0; idx < len; idx += 2) {\n cur = hex(card[idx + 0]);\n cur <<= 4;\n\n cur |= hex(card[idx + 1]);\n\n crc ^= cur;\n }\n\n return (crc == 0);\n}\n</code></pre>\n\n<p>Note that even this could be tweaked a bit more for speed with some careful benchmarking ...</p>\n\n<hr>\n\n<p><strong>UPDATE #4:</strong></p>\n\n<p>Eliminating the call to <code>hex</code> in favor of a [single] table lookup may be faster and provide some error checking:</p>\n\n<pre><code>int\nchecksum(const char *card,size_t len)\n{\n static unsigned char hex[256] = { ['0'] = 0xFF };\n unsigned int chr;\n unsigned int cur;\n unsigned int crc = 0;\n\n // one time init of translation table\n if (hex['0'] == 0xFF) {\n for (chr = 0x00; chr <= 0xFF; ++chr)\n hex[chr] = 0xFF;\n\n for (chr = 0; chr <= 9; ++chr)\n hex[chr + '0'] = chr;\n\n for (chr = 0x00; chr <= 0x05; ++chr) {\n hex[chr + 'a'] = chr + 0x0A;\n hex[chr + 'A'] = chr + 0x0A;\n }\n }\n\n for (size_t idx = 0; idx < len; idx += 2) {\n chr = hex[card[idx + 0]];\n#ifdef ABORT_ON_ERROR\n if (chr == 0xFF)\n return -1;\n#endif\n cur = chr;\n cur <<= 4;\n\n chr = hex[card[idx + 1]];\n#ifdef ABORT_ON_ERROR\n if (chr == 0xFF)\n return -1;\n#endif\n cur |= chr;\n\n crc ^= cur;\n }\n\n return (crc == 0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T06:10:08.630",
"Id": "462769",
"Score": "43",
"body": "In your last code snippet, you can simply `return nx == 0` instead of the `if` statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T17:16:34.937",
"Id": "462868",
"Score": "9",
"body": "If I read the [operator precedence chart](https://en.cppreference.com/w/c/language/operator_precedence) correctly, `==` has precedence over `^` so that `nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] == nx[5]` amounts to `nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ (nx[4] == nx[5])`. (The OP suspected as much already.) It is recommended to bracket the more obscure and seldomly used operators. Of course that judgement is in the eye of the beholder: Too many brackets again obscure the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T16:23:17.040",
"Id": "462993",
"Score": "0",
"body": "I really like the explanation since it teaches a lot of the mindset of a C programmer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T16:25:58.313",
"Id": "462994",
"Score": "0",
"body": "In your update #3, you made the typical mistake of passing an illegal value to `tolower`. You must not cast from `char` directly to `unsigned int`, but take the intermediate step of casting from `char` to `unsigned char`. Also you are assuming that the letters `abcdef` are adjacent in the execution character set, which is not guaranteed. ASCII and EBCDIC behave that way, but you can never know. Therefore the `strtol` from the original code was better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T18:59:41.240",
"Id": "463014",
"Score": "0",
"body": "Update 4 feels like a lot of speculative code for a \"may be faster\" with no benchmarking. If I wrote that and then stepped back to look at it, I think I'd stash it away and then test the original to see whether any speedup is required. And if it is, I'd then test this version to see if it was a real improvement ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T01:13:29.310",
"Id": "463045",
"Score": "0",
"body": "@Useless Yes, to decide between the two, benchmarking would be helpful. From the previous update, I said: _Note that even this could be tweaked a bit more for speed with some careful benchmarking ..._ If the prior example, _inlines_ the `hex` call, it _might_ be faster. But, it's still several instructions per call. The final version, after getting the `hex` _array_ into the cache, is two memory fetches [from cache], so I suspect it would go faster because it's just the two fetches, whereas the `hex` func version has some `if` against the ranges in addition to to the fetch for `tolower`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T01:24:33.510",
"Id": "463046",
"Score": "0",
"body": "@RolandIllig Yes, it is possible that a system is non-ascii (i.e. non-contiguous), but that would be _rare_. I've yet to encounter one (even EBCDIC usually gets translated at the \"outer edge\"). If it were _truly_ a concern, one could add a diagnostic test at program start to compare both `hex` against `strtol` for all [256] possible combinations, selecting `hex` if it works and fallback to `strtol` if it fails. But, again, this would be rare. I've often written such startup code [sometimes in a utility that is called during the `make` to compile the best algorithm via `#ifdef`]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T02:25:07.513",
"Id": "463047",
"Score": "0",
"body": "And nothing about the indentation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T05:20:12.867",
"Id": "463064",
"Score": "0",
"body": "@PeterMortensen By that I presume you mean OP's original indentation? That could be an artefact of the code block. But, except for readability here, I don't worry about indentation. For example, before I refactor code here [or on SO], I run the source through a wrapper script that invokes GNU `indent` and it reformats the code, according to _my_ :-) style guide. Indentation and coding style [enforcement] should be automated. So, in a way, I did comment on the indent/style by reformatting it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T09:49:32.583",
"Id": "463087",
"Score": "0",
"body": "You misunderstand me. I'm saying there is no point writing #4 in the first place, _unless_ you already tested the simple version and found it too slow. You can spend all day coming up with alternative implementations that might be faster, but generally shouldn't unless you have a specific requirement."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T00:17:03.940",
"Id": "236211",
"ParentId": "236206",
"Score": "20"
}
},
{
"body": "<p>As <code>x ^ x == 0</code> on can do a homogeneous:</p>\n\n<pre><code>return nx[0] ^ nx[1] ^ nx[2] ^ nx[3] ^ nx[4] ^ nx[5] == 0;\n</code></pre>\n\n<p>A char, a hex digit represent a nibble, 4 bits. As XORing does not influence other positions (like ADDing), one can do the checksum separately on the two nibbles:</p>\n\n<pre><code>int\nhex(char ch)\n{\n // For ASCII\n return ch <= '9' ? (int) ch - '0' : (ch & 0xF) + 9;\n}\n</code></pre>\n\n<p>The hex function should give a number 0 <= x < 16 for characters 0-9A-Fa-f, for ASCII based character encodings.</p>\n\n<p><strong><em>After feedback to the non-validating hex function:</em></strong></p>\n\n<pre><code>int\nhex(char ch)\n{\n char* digits = \"0123456789ABCDEFabcdef\";\n char* p = strchr(digits, ch);\n if (!p) {\n return -1;\n }\n int digit = p - digits;\n return digit < 16 ? digit : digit - 6;\n}\n</code></pre>\n\n<p>One might do more than returning -1. Or check it at the call site.</p>\n\n<pre><code>bool\nchecksum_valid(char* card)\n{\n if (strlen(card) != 6*2) {\n return false;\n }\n int crc0 = 0;\n int crc1 = 0;\n while (*card) {\n crc0 ^= hex(*card++);\n crc1 ^= hex(*card++);\n }\n return crc0 == 0 && crc1 == 0;\n}\n</code></pre>\n\n<p>Using <code>0 ^ x == x</code> and <code>x ^ x == 0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:16:42.140",
"Id": "462828",
"Score": "2",
"body": "While your answer isn't code only, it doesn't really review the original posters code. Good answers on code review review the code and don't necessarily provide an alternate solution at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T13:22:50.893",
"Id": "462829",
"Score": "0",
"body": "@pacmaninbw thanks, that explains to me not receiving points ;). After the review of the return statement of the OP, \"making the answer shorter\" went to an entire removal of the extra array and so on. I leave the answer for who it wants to use,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T15:52:01.613",
"Id": "462848",
"Score": "0",
"body": "Letters are not guaranteed by the standard to be contiguous. You'll probably have to use a lookup table for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T15:59:40.513",
"Id": "462851",
"Score": "0",
"body": "@S.S.Anne yes EBCDIC is such a case. I assumed ASCII however. A `strchr` or such is nicer though. And allows to validate that the characters are valid hex digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:09:58.120",
"Id": "462854",
"Score": "0",
"body": "`ch <= '9'` will do bad stuff for `ch < '0'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:13:10.810",
"Id": "462855",
"Score": "0",
"body": "@S.S.Anne no validation. I'll rewite the hex function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T16:28:55.457",
"Id": "462860",
"Score": "0",
"body": "Nice `strchr` solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T00:16:09.283",
"Id": "462894",
"Score": "1",
"body": "`strchr(digits, tolower(ch))` would be better, especially as the sample input from the OP uses upper case."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T11:37:28.507",
"Id": "236223",
"ParentId": "236206",
"Score": "1"
}
},
{
"body": "<p>It would be interesting to eliminate the loops; I suspect the optimizer will deal with the hard coded indexes and optimize the code.</p>\n\n<pre><code>character0[0]=card[0];\ncharacter1[0]=card[2];\ncharacter2[0]=card[4];\ncharacter3[0]=card[6];\ncharacter4[0]=card[8];\ncharacter5[0]=card[10];\ncharacter0[0]=card[1];\ncharacter1[0]=card[3];\ncharacter2[0]=card[5];\ncharacter3[0]=card[7];\ncharacter4[0]=card[9];\ncharacter5[0]=card[11];\ncharacter0[1]=card[0];\ncharacter1[1]=card[2];\ncharacter2[1]=card[4];\ncharacter3[1]=card[6];\ncharacter4[1]=card[8];\ncharacter5[1]=card[10];\ncharacter0[1]=card[1];\ncharacter1[1]=card[3];\ncharacter2[1]=card[5];\ncharacter3[1]=card[7];\ncharacter4[1]=card[9];\ncharacter5[1]=card[11];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T15:53:12.677",
"Id": "462849",
"Score": "0",
"body": "The compiler will likely leave it. Even though it's ugly, this type of code is performant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T18:51:12.933",
"Id": "462874",
"Score": "0",
"body": "I find this version to be easier to read, reason about, and debug as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T03:09:16.657",
"Id": "462896",
"Score": "2",
"body": "This does exactly what the largest part of the original program does (up to the first strtol). Now observe that you can delete lines 1-6 and lines 13-18 without changing the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T11:41:56.113",
"Id": "462941",
"Score": "1",
"body": "What's up with all the re-assignment nonsense? (e.g., `character0[0]=card[0];` on line 1, and then `character0[0]=card[1];` on line 7?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T14:26:28.907",
"Id": "462972",
"Score": "0",
"body": "@will I agree, After taking a look at the entire code rather than focusing on the loops this code could get rid of reassignments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T10:00:47.880",
"Id": "463088",
"Score": "2",
"body": "Since a decent compiler is perfectly capable of unrolling constant loops itself, I'm not sure what this answer is trying to achieve. Anyway, manual unrolling is pretty much never used to make the code _better_, but to make it worse-and-faster where that tradeoff is justified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T20:51:19.343",
"Id": "464065",
"Score": "1",
"body": "@Useless by unrolling the code manually it's easier to see that half of the assignments are useless and can be removed. After that, the loops can be added again."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T14:53:35.727",
"Id": "236237",
"ParentId": "236206",
"Score": "3"
}
},
{
"body": "<p>I have a recommendation. But first a critique.</p>\n\n<p>The main problem with the program is that it's very badly broken.\nYou have six loops, none of which is working correctly.</p>\n\n<p>First, if you were to actually write down the steps of your first loop and what part of <code>card</code> is copied to <code>character0</code> at each step, you should find at the end that the last thing written to <code>character[0]</code> is <code>card[1]</code> and the last thing written to <code>character[1]</code> is <code>card[1]</code>. In other words, <code>character0</code> ends up containing two copies of <code>card[1]</code>, and <code>card[0]</code> ends up being ignored.\nLikewise <code>card[2]</code>, <code>card[4]</code>, <code>card[6]</code>, <code>card[8]</code>, and <code>card[10]</code> all will be ignored in your final calculations.</p>\n\n<p>A second serious defect is that you pass a string to <code>strtol</code> without putting a null terminator at the end of the string. Therefore you are telling <code>strtol</code> to parse the two characters you gave it plus whatever is after them in memory. \"Whatever is after\" <em>might</em> be a null character, which will give you the result you want, or it might be some other non-hexadecimal character, which also will give you the result you want, or it might be one or more hexadecimal characters, which usually will give you a wrong result.\nWhen I tried running your code in an online compiler and gave it the input 112233445566, and inserted <code>printf(\"n = %x %x %x %x %x %x\\n\", n0, n1, n2, n3, n4, n5);</code> near the end to see what six numbers it got, the output was</p>\n\n<p>11 2211 332211 44332211 44332211 44332211</p>\n\n<p>This tells me something about how that particular compiler laid out the twelve bytes of memory for <code>character0</code> through <code>character5</code>.\nIt also tells me you were asking for undefined behavior when you called your <code>strtol</code> functions.\nThis is basic test and debugging that you should have done before posting here.</p>\n\n<p>There is a third defect, that <code>n0^n1^n2^n3^n4==n5</code> does not work the way you meant it to, but you already have realized that this needs to be looked into.</p>\n\n<hr>\n\n<p>Now my recommendation. My main recommendation is to write smaller functions.\nYou <em>could</em> do the whole thing very compactly in one function via loops,\nbut I recommend smaller functions because small functions force you to think about\nwhat each one is doing by itself: what are the inputs, exactly, what is the output,\nwhat is the task the function has to perform.\nIf you name your function well, it will even make the code more self-documenting.</p>\n\n<p>A smaller function that seems obvious to me is:</p>\n\n<blockquote>\n <p>Take two characters from <code>card</code>. Parse them as a hexadecimal number, turning them into an integer in the range 0 to 255, and return that integer.</p>\n</blockquote>\n\n<p>It's also fairly obvious that you'll end up calling the function six times, due to the way the larger function's specification is written:</p>\n\n<blockquote>\n <p><code>card[]</code> contains six pairs of characters. The first five pairs make up a hexadecimal number, the last pair contains the checksum.</p>\n</blockquote>\n\n<p>Now you just need to figure out how to pass each pair of characters to your function.\nFor example, if you name the function <code>convertCharacterPairToNumber</code> you might pass the second pair like this:</p>\n\n<pre><code>convertCharacterPairToNumber(card[2], card[3])\n</code></pre>\n\n<p>Or you might decide to make your function aware of <code>card</code> but tell it which two characters to use: </p>\n\n<pre><code>convertCharacterPairToNumber(card, 2, 3)\n</code></pre>\n\n<p>Or you might realize that the second character is always right after the first one, so you just need to tell your function where the first character is:</p>\n\n<pre><code>convertCharacterPairToNumber(card, 2)\n</code></pre>\n\n<p>Or you might decide that a pointer into the string, pointing at the first of the two characters in the pair, is enough:</p>\n\n<pre><code>convertCharacterPairToNumber(&card[2])\n</code></pre>\n\n<p>Then you just need to write the function's implementation and test it before you put it into the larger function.\nYou could solve two of the three major defects in your program this way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T12:59:51.150",
"Id": "236290",
"ParentId": "236206",
"Score": "5"
}
},
{
"body": "<p>Instead of calling <code>strtol</code> repeatedly, you could also call it once to extract a 64-bit integer, and then do some calculations on that integer.</p>\n\n<p>The basic idea is:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>bool checksum(const char *card) {\n\n unsigned long long int num = strtoull(card, NULL, 16);\n\n unsigned long long int xored = 0;\n\n xored ^= num >> 40;\n xored ^= num >> 32;\n xored ^= num >> 24;\n xored ^= num >> 16;\n xored ^= num >> 8;\n xored ^= num;\n\n return (xored & 0xFF) == 0;\n}\n</code></pre>\n\n<p>The above code works by looking at a small \"window\" of the number in each line. One after another, the digit pairs are shifted into that \"window\" and xored to form the final result. It basically looks like this:</p>\n\n<pre><code>AABBCCDDEEFF <- the number\n00AABBCCDDEE <- the number, shifted by 8 bits to the right\n 00AA <- the number, shifted by 40 bits to the right\n\n **\n AABBCCDDEEFF 40 bits\n AABBCCDDEEFF 32 bits\n AABBCCDDEEFF 24 bits\n AABBCCDDEEFF 16 bits\n AABBCCDDEEFF 8 bits\nAABBCCDDEEFF 0 bits\n **\n</code></pre>\n\n<p>The small part between the asterisks is the interesting part of the \"window\", which will form the final result. Outside this window, the bits also take part in the computation, but they will be ignored. The nice thing about xor is that the outside bits cannot influence the inside bits. This is different from the usual integer addition or subtraction.</p>\n\n<p>After xoring all the shifted numbers, the interesting part of the window is extracted using <code>& 0xFF</code>. In the first attempt I used an <code>unsigned char xored</code>, but then I realized that it might be larger than 8 bits. It seemed clever at first but really wasn't. I could have used <code>uint8_t</code>, which would have worked as well. Which one is better depends on the generated machine code. When you have learned assembler, you can look at the generated code and compare them.</p>\n\n<p>What's left now is some error checking. Your code silently assumes that it will only be passed valid data, that is a 12-digit hex number. It's not that difficult to add the missing error handling:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <ctype.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n\nbool checksum(const char *card) {\n if (strlen(card) != 12) {\n return false;\n }\n\n // Make sure that the whole card number looks like a hex number.\n char *end;\n unsigned long long int num = strtoull(card, &end, 16);\n if (end != card + 12) {\n return false;\n }\n\n // Make sure the first character is not a space or hyphen or plus,\n // which would be accepted by strtoull.\n if (!isxdigit((unsigned char)card[0])) {\n return false;\n }\n\n // Make sure the second character is not an x, since 0x would be\n // interpreted as \"hex\" by strtoull.\n if (!isxdigit((unsigned char)card[1])) {\n return false;\n }\n\n unsigned long long int xored = 0;\n\n xored ^= num >> 40;\n xored ^= num >> 32;\n xored ^= num >> 24;\n xored ^= num >> 16;\n xored ^= num >> 8;\n xored ^= num;\n\n return (xored & 0xFF) == 0;\n}\n</code></pre>\n\n<p>To be sure that the above code is correct, you must think of a whole bunch of test cases. One test case is definitely not enough since a simple <code>return true</code> would have made that test succeed.</p>\n\n<p>A few test cases I came up with are:</p>\n\n<pre><code>#include <assert.h>\n\nint main(void) {\n assert(checksum(\"\") == false);\n assert(checksum(\"00000000000\") == false); // 11 digits are too short\n assert(checksum(\"000000000000\") == true);\n assert(checksum(\"0000000000000\") == false); // 13 digits are too long\n assert(checksum(\"000000000001\") == false);\n assert(checksum(\"000000000101\") == true);\n assert(checksum(\"000000010001\") == true);\n assert(checksum(\"000001000001\") == true);\n assert(checksum(\"000100000001\") == true);\n assert(checksum(\"010000000001\") == true);\n assert(checksum(\"FF01020408F0\") == true);\n assert(checksum(\"123456563412\") == true);\n assert(checksum(\"123456654321\") == false);\n assert(checksum(\"abcdefABCDEF\") == true);\n assert(checksum(\"abcdefABCDEF\") == true);\n assert(checksum(\"abcdegABCDEF\") == false); // invalid character in the middle\n assert(checksum(\"-00000000000\") == false); // invalid character at the beginning\n assert(checksum(\" 0\") == false); // invalid character at the beginning\n assert(checksum(\"+00000000000\") == false); // invalid character at the beginning\n assert(checksum(\"0x0000000000\") == false); // don't let strtoull trick us with hex\n\n assert(checksum(\"1E00EDE5E5F3\") == true);\n}\n</code></pre>\n\n<p>I intentionally used the <code>== true</code> and <code>== false</code> here to keep the beginnings of the lines the same, to make them clearly stick out as a block of code. If I had used the often recommended form of omitting the <code>== true</code> and replacing <code>x == false</code> with <code>!x</code>, the visual code layout would have been much more chaotic.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T17:26:27.923",
"Id": "236305",
"ParentId": "236206",
"Score": "5"
}
},
{
"body": "<p>You have several answers showing alternative solutions, or describing what's wrong with your existing code. I'm going to try to show how I'd get from <em>here</em> (your current code) to something I'd actually be happy using.</p>\n\n<h2>1. The Declaration</h2>\n\n<pre><code>bool checksum(char card[])\n</code></pre>\n\n<p>is already kind of a problem. There's no way to communicate to the caller that conversion failed. This might be OK if it's only used inside a module that already guarantees our pre-requisites, but we should at least say very clearly what they are.</p>\n\n<p>The function name actually isn't great either, because a <em>checksum</em> is a noun, which means this function sounds like it should calculate and return one of those.</p>\n\n<p>I'm using Doxygen markdown just to get in the mood of writing real code.</p>\n\n<pre><code>/**\n * Validate a checksummed card number.\n * The format is 12 hex digits, with the last two representing\n * a single-octet checksum of the first 10 chars/5 octets.\n *\n * @param card must contain 12 hex digits.\n *\n * @note This function will not check for short (or NULL)\n * arguments and will not gracefully handle invalid digits.\n *\n * @return true if the input is valid\n */\nbool validate_checksum(const char *card)\n</code></pre>\n\n<h2>2. The Repetition</h2>\n\n<p>You have five identical loops populating five variables with numbers in their names - this should always <em>always</em> be factored out somehow. Variables with numbers in their names (ordinal numbers, rather than say <code>point3d</code>) are a particular red flag - they should either be an array, or a loop.</p>\n\n<p>Even when we know we should move the repeated code into a function, it isn't always obvious how best to structure it. One approach is to work backwards from the desired result, and see how to get <em>there</em>.</p>\n\n<h2>2.a The End Result</h2>\n\n<p>We want something equivalent to the expression</p>\n\n<pre><code>return (b0 ^ b1 ^ b2 ^ b3 ^ b4 ^ b5) == 0;\n</code></pre>\n\n<p>(note that if <code>b0 ^ ... ^ b4 == b5</code> then <code>b0 ^ ... ^ b4 ^ b5</code> must be zero, and grouping all the input values together makes it easy to naturally avoid the operator precedence problem in your original code)</p>\n\n<p>... but ideally without those numbered variables I called out earlier. We don't really need to keep all six values around at one time either, so we could write</p>\n\n<pre><code>unsigned long result = 0;\n/* 5 is NUM_OCTETS_IN_CARD or similar */\nfor (int octnum = 0; octnum < 6; ++octnum)\n{\n result ^= hex_octet(card);\n card += 2;\n /* 2 is CHARS_PER_OCTET */\n}\nreturn result == 0;\n</code></pre>\n\n<p>I made a note of things that should probably be clearly-defined constants instead of magic numbers, but I'm not writing the whole program here.</p>\n\n<h2>2.b The Repetition pt.2</h2>\n\n<p>Now we know what we want the interface to our factored-out code to look like, it's easier to write:</p>\n\n<pre><code>/**\n * Convert two hexadecimal characters to an integer.\n * The parameter must point to a string with at least two valid\n * hex characters.\n */\nunsigned long hex_octet(const char *o)\n{\n char tmp[3] = { o[0], o[1], 0 };\n return strtoul(tmp, NULL, 16);\n}\n</code></pre>\n\n<p>Note that the only reason for using <code>unsigned long</code> above was to avoid extra work converting from <code>strtoul</code> - otherwise we could have just used <code>uint8_t</code> for the octet values.</p>\n\n<p>Writing our own hex conversion is certainly feasible, but not immediately necessary. If lots of (well, six) calls to <code>strtoul</code> look expensive during profiling, it might be less work to replace them with a single call to <code>strtoull</code> returning all six octets in a single <code>unsigned long long</code>, and then work on the low six bytes of that (the minimum allowed size for <code>unsigned long</code> is 32 bits or 4 bytes, which isn't enough).</p>\n\n<p>After all that, we should have something that works up to the constraints we imposed on the input.</p>\n\n<h2>3. Interface Improvements</h2>\n\n<p>We could actually check our pre-requisites, either just with</p>\n\n<pre><code>assert(isxdigit(c)==0)\n</code></pre>\n\n<p>for every character, or perhaps with</p>\n\n<pre><code>char *end;\nunsigned long long whole = strtoull(card, &end, 16);\nassert(end == card+12);\n</code></pre>\n\n<p>if <code>card</code> is guaranteed to be null-terminated.</p>\n\n<p>Either way, if we don't want to just abort (in debug builds, and continue blithely on in release builds), we need a different interface to tell the caller about errors. With all those constants I mentioned earlier, and proper error-checking, we might end up with</p>\n\n<pre><code>/**\n * Validate a checksummed card number.\n * The format is 12 hex digits, representing 6 octets.\n * The last octet is a checksum for the first five.\n *\n * @param card must contain 12 hex digits. If it is not null-terminated, only the\n * first 12 digits are used.\n *\n * @return 0 (zero) if the checksum is correct, or\n * a positive integer if the checksum is incorrect\n * a negative integer if the input format is invalid\n */\nint validate_checksum(const char *card)\n{\n static const int BITS_PER_OCTET = 8;\n static const unsigned long long LOW_OCTET_MASK = 0xFF;\n static const int CHARS_PER_OCTET = 2;\n static const int EXPECTED_OCTETS = 6;\n static const int EXPECTED_CHARS = EXPECTED_OCTETS * CHARS_PER_OCTET;\n\n char tmp[EXPECTED_CHARS + 1];\n memcpy(tmp, card, EXPECTED_CHARS);\n tmp[EXPECTED_CHARS] = 0;\n\n char *end;\n unsigned long long value = strtoull(tmp, &end, 16);\n if (end != tmp + EXPECTED_CHARS)\n {\n /* error: got (end-tmp) hex digits instead of EXPECTED_CHARS */\n return -1; \n }\n\n uint8_t octet = 0;\n for (int i = 0; i < EXPECTED_OCTETS; ++i)\n {\n octet ^= (uint8_t)(value & LOW_OCTET_MASK);\n value >>= BITS_PER_OCTET;\n }\n\n return octet; /* zero is correct, non-zero must be +ve */\n}\n</code></pre>\n\n<p>Things like <code>BITS_PER_OCTET</code> are probably overkill when \"octet\" literally means \"eight bits\", but I decided to eliminate magic numbers from the code almost entirely. Conversely, the integer constant <code>0xFF</code> could have been written <code>(1 << BITS_PER_OCTET) - 1</code>, but I'm used to reading this sort of value in hex - YMMV.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:46:28.760",
"Id": "464081",
"Score": "0",
"body": "Fixed the off-by-one. The low octet mask is already addressed in the text, and the `CHARS_PER_OCTET` change really suggests _another_ constant, `BITS_PER_CHAR = 4` or something. I generally prefer masking explicitly, it's easier to reason about in general."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T18:28:51.073",
"Id": "236309",
"ParentId": "236206",
"Score": "3"
}
},
{
"body": "<p>The majority of your function consists of parsing a string of 12 characters into six numbers, expecting that each number is represented as a two-digit hexadecimal value in the input string. This is unfortunate, since it obfuscates the core of this function - the algorithm by which the checksum is computed!</p>\n\n<p>Luckily, this kind of parsing is so common that there's a ready-made function in the standard library for this task, called <a href=\"http://www.cplusplus.com/reference/cstdio/sscanf/\" rel=\"nofollow noreferrer\"><code>sscanf</code></a>. Reusing <code>sscanf</code> instead of doing your own parsing also does away with any bugs you may have introduced, so your perfectly reasonable expectation of</p>\n\n<pre><code>if((n0^n1^n2^n3^n4)==n5)) return true; \nelse return false;\n</code></pre>\n\n<p>working should be met.</p>\n\n<p>Lastly, you might like to consider a stylistic adjustment and eliminate the unneeded <code>if</code> statement, given that for some expression <code>e</code>, the code</p>\n\n<pre><code>if (e) return true;\nelse return false;\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>return e;\n</code></pre>\n\n<p>Thus, you could shorten your function to</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>bool checksum(char card[])\n{\n unsigned n0, n1, n2, n3, n4, n5;\n int num_fields_converted;\n\n num_fields_converted = sscanf(card, \"%02X%02X%02X%02X%02X%02X\", &n0, &n1, &n2, &n3, &n4, &n5);\n\n assert(num_fields_converted == 6 || !\"Input string malformed\");\n\n return (n0 ^ n1 ^ n2 ^ n3 ^ n4) == n5;\n}\n</code></pre>\n\n<p>This nicely emphasises the actual way by which the <code>checksum</code> function computes its output value: it XOR's the first five bytes and then verifies that this equals the sixth byte.</p>\n\n<p>Note that this assumes (by checking the <code>sscanf</code> return value) that the input string is well-formed before bothering to verify the checksum. Instead of using an <code>assert</code>, some other behaviour might be more convenient in your use case (e.g. returning <code>false</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T18:18:33.620",
"Id": "463157",
"Score": "2",
"body": "Of course, when using `scanf()` family of functions, we always check the return value. Don't we?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T08:34:10.343",
"Id": "463272",
"Score": "0",
"body": "@TobySpeight It depends: in case `sscanf` fails, how should `checksum` behave? After all, it cannot even compute the checksum, so how could it test if the checksum matches. You could set e.g. a global error code, but it's not far-fetched to just document the function as being undefined for malformed inputs. Partial functions are tricky though, a good fix might be to have some `assert`ions or maybe a dedicated type (instead of `char*`) which expresses the preconditions explicitly (and moves the input validation to the caller)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-30T16:23:47.967",
"Id": "463336",
"Score": "1",
"body": "That's a good question, and when I'm writing code that's a time to go back to the customer and ask what they want to happen. Most likely, we should return `false` if we can't read or can't parse the string; other possibilities include changing the functions return type to be able to express more than boolean (e.g. use an int or enum)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T20:55:22.200",
"Id": "464066",
"Score": "0",
"body": "I think what Toby wanted to say politely is: We expect _every_ answer on Code Review to either _use and check_ the return value of `scanf`, or alternatively give a very good reason why the return value does not need to be checked. Silently ignoring the return value is questionable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:52:39.520",
"Id": "464124",
"Score": "0",
"body": "@RolandIllig That makes perfect sense; I now added `assert`ions to express the preconditions of the function (not satisfying them renders the behaviour undefined)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T07:39:46.233",
"Id": "236338",
"ParentId": "236206",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T22:09:25.157",
"Id": "236206",
"Score": "12",
"Tags": [
"c"
],
"Title": "How can I make this C code for checking checksum shorter?"
}
|
236206
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.