body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have a system for going back to a previously-visited page in a Python console application; it works well enough, but I feel that there could be a <em>prettier</em> way of doing it. Does anyone have any suggestions to improve what I have below?</p>
<pre><code>def main():
try:
while True:
print('Main Menu\n')
option = input('page 1, page 2, quit\n')
if option in ['1', 'one']:
menu_stack.append(0)
page_one()
elif option in ['2', 'two']:
menu_stack.append(0)
page_two()
elif option in ['q', 'quit']:
quit()
else:
print('Invalid input, please try again\n')
sleep(1)
except KeyboardInterrupt:
quit()
</code></pre>
<p>Very similar to the main menu page, below is page 1:</p>
<pre><code>def page_one():
while True:
clear_terminal()
print('Page One\n')
option = input('Page 2, back\n')
if option in ['2', 'two']:
menu_stack.append(1)
page_two()
elif option in ['b', 'back']:
menu_checker()
else:
print('Invalid input, please try again\n')
sleep(1)
</code></pre>
<p><code>menu_checker()</code> calls the other pages based on what pops from the stack:</p>
<pre><code>def menu_checker():
page = menu_stack.pop()
if page == 1:
page_one()
elif page == 2:
page_two()
elif page == 0:
main()
else:
print('Error')
</code></pre>
<p>Does anyone have any better ideas/solutions? Even though it doesn't cause any issues (as far as I am aware), I feel what I have is kind of clunky and could be improved.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T12:44:05.847",
"Id": "504835",
"Score": "0",
"body": "Welcome to the Code Review Community where we review code that is working as expected and make suggestions on how to improve that code. This part of the question is off-topic for code review `An idea I had was to stack function calls; so the popped values of menu_stack() would be functions, not integers. The issue with this is that I don't know how to do that, or even if it can be done.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T12:49:07.613",
"Id": "504836",
"Score": "0",
"body": "No problem removing, but why is it *off-topic*? I am new to this forum, but I thought it would be OK to share an idea I had."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T12:51:44.390",
"Id": "504838",
"Score": "0",
"body": "It is asking about code not yet written, which means it doesn't belong in a code review. We don't answer how to questions on code review, that is what stack overflow is for. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T16:53:51.390",
"Id": "504863",
"Score": "0",
"body": "Well, I wasn't asking how to do that per se, just that it was an idea I had, help give an insight to what my application is trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:46:45.237",
"Id": "504964",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles. At the moment it's uninformative - a console app which does **what?**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T14:32:16.177",
"Id": "504971",
"Score": "0",
"body": "Why does it matter what my app does? Anyone who wants to build a multi-page console application but is struggling to implement it can come here to this post. If you are curious about what it does, it is (or should I say *will*) be used to implement OpenDota's API, not that it makes any difference."
}
] |
[
{
"body": "<p>I'm thinking there are a few different approaches you could take here.</p>\n<h2>The stack was inside you all along</h2>\n<p>It may not be the most flexible of approaches, but the way things are right now, your pages are just functions. And guess what? Your program already has a stack of functions -- you navigate it by calling functions and <code>return</code>ing from them! You don't get a whole lot of information about where you'll end up if you return, but if that's not a problem, you might be able to just get rid of <code>menu_checker</code> and <code>menu_stack</code> altogether -- if the user wants to go back, you just <code>return</code>.</p>\n<p>For example, your <code>page_one</code> could simply look like</p>\n<pre><code>def page_one():\n while True:\n clear_terminal()\n\n print('Page One\\n')\n\n option = input('Page 2, back\\n')\n\n if option in ['2', 'two']:\n page_two()\n elif option in ['b', 'back']:\n return\n else:\n print('Invalid input, please try again\\n')\n sleep(1)\n</code></pre>\n<p>It's not the fanciest-looking perhaps, but it's easy to implement, easy to understand and does the job just fine.</p>\n<h2>Where do you want to go?</h2>\n<p>But maybe that isn't good enough. It might be nice if the "back" option could say something like "Back (to page 1)" depending on what the stack looks like, for example. Or maybe you'd like to also have a "forward" option in case the user accidentally presses "back" too many times. Or maybe there's another reason you don't want to use the call stack for this. That's fine too.</p>\n<p>Another option could be to move the navigation logic from the individual menus into a single core loop. Each menu then returns which menu it thinks you should go to next.</p>\n<p>For example, we might be looking at something like this:</p>\n<pre><code>def main():\n menu_stack = [main_menu]\n\n while menu_stack:\n current_menu = menu_stack[-1]\n\n next = current_menu(option)\n\n if next:\n menu_stack.append(next)\n else:\n menu_stack.pop()\n</code></pre>\n<p>With menus looking a lot like the previous ones, but instead of calling the next menu like <code>page_two()</code> they return it like <code>return page_two</code>. Or perhaps <code>return None</code> if we should go back.</p>\n<h2>Classy</h2>\n<p>Personally, though, I think there are some tasks (like asking for input) that should be the responsiblity of the app itself rather than the menus. The menu can know what it looks like and how to navigate based on input, but the core loop asks it for help and then handles those things on its own terms.</p>\n<pre><code>def main():\n menu_stack = [main_menu]\n\n while menu_stack:\n current_menu = menu_stack[-1]\n\n clear_terminal()\n\n print(current_menu.text)\n\n option = input(current_menu.prompt)\n\n try:\n next = current_menu.get_next_menu(option)\n\n if next:\n menu_stack.append(next)\n else:\n menu_stack.pop()\n except ValueError as e:\n print("Invalid input, please try again")\n sleep(1)\n</code></pre>\n<p>Defining a nice Menu class is left as an exercise for the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T11:24:27.037",
"Id": "504943",
"Score": "0",
"body": "Wow, thanks, Sara! Really cool stuff :p This is exactly what I was looking for and more. I really appreciate the help. Stay safe :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T02:17:39.160",
"Id": "255833",
"ParentId": "255801",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255833",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T12:19:56.930",
"Id": "255801",
"Score": "3",
"Tags": [
"python",
"stack"
],
"Title": "Python Console App | Is there a better way to go back a page?"
}
|
255801
|
<p>Here are the items:</p>
<pre><code>
var item = ['a', 'b', 'c', 'd'];
</code></pre>
<p>Desired output:</p>
<pre><code>
[
[ ['a'],['b'],['c'],['d'] ],
[ ['a'],['b','c'],['d'] ],
[ ['a'],['b'],['c','d'] ],
[ ['a'],['b','c','d'] ],
[ ['a'],['c'],['b','d'] ],....
]
</code></pre>
<p>The code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getCombinations(items) {
var res = [];
for (var i = 0; i < items.length; i++) {
for (var j = i + 1; j <= items.length; j++) {
var temp = items.slice(i, j);
var remained = items.slice(0, i).concat(items.slice(j, items.length));
if (remained.length > 0) {
var combinations = getCombinations(remained);
combinations.forEach(combination => {
res.push([temp].concat(combination));
});
} else {
res.push([temp]);
}
}
}
return res;
}
var item = ['a', 'b', 'c', 'd'];
console.log(getCombinations(item));</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T06:25:05.123",
"Id": "504923",
"Score": "0",
"body": "You output for `['a', 'b', 'c', 'd']` doesn't contain `[['a', 'c'], ['b', 'd']]` which may be incorrect. Also, your output contain duplicate `[['a'], ['b'], ['c'], ['d']]`, `[['a'], ['b'], ['d'], ['c']]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T06:46:49.783",
"Id": "504924",
"Score": "0",
"body": "The number of partitions is known as [Bell number](https://en.wikipedia.org/wiki/Partition_of_a_set#Counting_partitions), which may be quite large when there are more items in the input. As a result, any valid solution won't be much fast due to the fact of output size."
}
] |
[
{
"body": "<p>I see the <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a> tag added to this post. Did you intend to have answers address performance in terms of time, space or other aspects?</p>\n<p>If you are looking to optimize performance in terms of time then I must restrain myself from suggesting changing the outer <code>for</code> loop to a <code>for of</code> loop. However I do see there is a <code>forEach</code> loop inside the nested <code>for</code> loop. If you really want to optimize for performance, then consider using a <code>for</code> loop instead of that <code>.forEach</code> method. Also consider whether the same result can be achieved by iterating backwards through the loops - this would allow for fewer operations<sup><a href=\"https://www.freecodecamp.org/news/how-to-optimize-your-javascript-apps-using-loops-d5eade9ba89f/#optimizations\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n<p>Given that an arrow function is used in the <code>.forEach()</code> callback, other <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features can be used - e.g. <code>const</code> and <code>let</code> instead of <code>var</code>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> instead of calling <code>.concat()</code>, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T16:55:52.900",
"Id": "255807",
"ParentId": "255802",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T13:18:17.363",
"Id": "255802",
"Score": "5",
"Tags": [
"javascript",
"performance",
"array",
"ecmascript-6"
],
"Title": "Generate all partitions of a set of items"
}
|
255802
|
<p>I was wondering if there is a better way to solve this issue.</p>
<p>I have a list like this:</p>
<pre><code>imp_list=["aa","daa","ab","as","aem",
"aum","aw","aa","acm","at",
"ar","aa_imp","daa_imp","ab_imp",
"as_imp"]
</code></pre>
<p>I want to select all the strings that have the <strong><code>_imp</code> suffix</strong>, plus all the the strings that have no <code>_imp</code> partner.</p>
<p>That's because <code>aa_imp</code> it's just a modified version of <code>aa</code>, and for me, in a large sense, it's a replica.
So I created this function:</p>
<pre><code>def imputed_handler(my_list):
imp=[x for x in my_list if "imp" in x]
cleaned_imp=set(map(lambda x: x.replace("_imp",""),imp))
not_imp=[x for x in my_list if "imp" not in x]
set_list=set(my_list)
no_replica=list(set_list-cleaned_imp)
print(no_replica)
return no_replica
</code></pre>
<p>Running the code as described above</p>
<pre><code>test=imputed_handler(imp_list)
</code></pre>
<p>I get the following output:</p>
<pre><code>['at', 'acm', 'aw', 'ar', 'daa_imp', 'aem', 'as_imp', 'ab_imp', 'aa_imp', 'aum']
</code></pre>
<p>Do better solutions exist? Thanks for your time, and let me know if something is not clear :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T16:00:43.927",
"Id": "504859",
"Score": "2",
"body": "\"Do better solutions exist?\" - Yes, for example the one that doesn't compute `not_imp` and then never uses it :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T16:10:58.347",
"Id": "504861",
"Score": "0",
"body": "@KellyBundy lol you are right and you make my day :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T18:51:09.360",
"Id": "504882",
"Score": "1",
"body": "What's with the function _name_, would you like to have it reviewed? Or is this a no-touch constraint?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T10:49:37.010",
"Id": "504940",
"Score": "0",
"body": "@hc_dev yep it can be reviewed! I am self-taught so if there is something wrong I really appreciate it! <3"
}
] |
[
{
"body": "<p>First off, since you're looking for strings that end with <code>_imp</code>, <code>x.endswith("_imp")</code> is probably more reliable than <code>"imp" in x</code>.</p>\n<p>Second, since we only want to remove <code>_imp</code> when it's a suffix, and since we know how long it is, we can use string slicing to remove the last 4 characters. That means we don't accidentally turn <code>x_impabc_imp</code> into <code>xabc</code> instead of <code>x_impabc</code> or something. Assuming that's not what we want to do. Maybe it is, maybe it isn't, maybe we'll never get an input like that so it won't matter either way, I have no idea.</p>\n<p>I'm also thinking it might be nice to pass the suffix as a parameter. Maybe it might change at some point in the future. Maybe another part of the program uses a different suffix in a similar way. Doesn't hurt to be prepared.</p>\n<p>In general, though, your approach is good. You find the <code>_imp</code> ones, you figure out what they are replacing, you remove the ones that have been replaced.</p>\n<p>The neat thing is, you can do the first two steps all at once in a single pass through the input list. For example, you can do this:</p>\n<pre><code>def imputed_handler(my_list, suffix="_imp"):\n my_set = set(my_list)\n cleaned_imp = set(item[:-len(suffix)] for item in my_set if item.endswith(suffix))\n\n return list(my_set - cleaned_imp)\n</code></pre>\n<p>Though a loop might be clearer at that point:</p>\n<pre><code>def imputed_handler(my_list, suffix="_imp"):\n my_set = set(my_list)\n\n for item in my_list:\n if item.endswith(suffix):\n my_set.discard(item[:-len(suffix)])\n\n return list(my_set)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T18:01:02.547",
"Id": "504872",
"Score": "5",
"body": "Since Python 3.9 you can also use `item.removesuffix(suffix)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T18:03:21.923",
"Id": "504873",
"Score": "1",
"body": "@KellyBundy Oh, neat. I didn't find that since I'm still on 3.8.5 for some reason, but that's good to know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:27:09.400",
"Id": "511255",
"Score": "1",
"body": "If I recall correctly, the line `cleaned_imp = set(item[:-len(suffix)] for item in my_set if item.endswith(suffix))` will call `len(suffix)` and calculate `-len(suffix)` for every item. So it's usually better to calculate it once and use it as a variable inside the generator expression."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T17:57:50.383",
"Id": "255816",
"ParentId": "255805",
"Score": "10"
}
},
{
"body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> lists several conventions Python programs should follow. Things like:</p>\n<ul>\n<li>spaces around binary operators (<code>imp = [...]</code> and <code>set_list = set(my_list)</code>).</li>\n<li>spaces after comma (eg, <code>""), imp))</code></li>\n</ul>\n<h1>Side Effects</h1>\n<p>You are returning a result from <code>imputed_hander</code>; shouldn't print from inside it.</p>\n<h1>Type Hints and Doc Strings</h1>\n<p>What is <code>def imputed_handler(my_list)</code>? What does it do? What is <code>my_list</code> a list of? What is returned?</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List\n\ndef imputed_handler(my_list: List[str]) -> List[str]: \n """\n Filter a list of strings, removing `"xyz"` if `"xyz_imp"` is found.\n Return the filtered list.\n """\n</code></pre>\n<p>Now we have a (poor) description, and can see the argument & return types.</p>\n<h1>Improved code</h1>\n<p>As mentioned in <a href=\"https://codereview.stackexchange.com/a/255816/100620\">Sara J's answer</a>, <code>.endswith()</code> is preferable to simply checking if the search string is contained anywhere inside the original.</p>\n<p>Converting the list into a set, and then back into a list ruins the original lists order. Here is a possible improvement on Sara's solution:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List\n\ndef imputed_handler(my_list: List[str], suffix: str = "_imp") -> List[str]:\n """\n A good description here.\n """\n\n unwanted = {item.removesuffix(suffix) for item in my_list if item.endswith(suffix)}\n return [item for item in my_list if item not in unwanted]\n</code></pre>\n<p>A <code>set</code> is only constructed from the prefix of items which end in <code>_imp</code>. This should result in a smaller memory footprint, that <code>set(my_list) - cleaned_imp</code>. Since it is a <code>set</code>, the <code>in</code> operator is <span class=\"math-container\">\\$O(1)\\$</span>, filtering the list is fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T05:12:21.803",
"Id": "504918",
"Score": "2",
"body": "Note, [`typing.List` is now deprecated](https://www.python.org/dev/peps/pep-0585/#implementation) you can just use `list[str]` in Python 3.9+ or import annotations from PEP 563 - \"Importing those from `typing` is deprecated. Due to [PEP 563](https://www.python.org/dev/peps/pep-0563) and the intention to minimize the runtime impact of typing, this deprecation will not generate DeprecationWarnings.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:47:08.800",
"Id": "504987",
"Score": "0",
"body": "One more possible tweak is instead of taking \"foo_imp\" and generating \"foo\" to discard, is to ask for each \"foo\" whether \"foo_imp\" is in the set. `my_set = set(my_list); return [s for s in my_list if s + suffix not in my_set]`. Need to be careful whether it's equivalent for chains such as `imputed_handler([\"aa\", \"aa_imp\", \"aa_imp_imp\"])` but I think it is... This also matches your description \"removing `\"xyz\"` if `\"xyz_imp\"` is found\" which is the clearest definition I can think of."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T23:48:23.997",
"Id": "255831",
"ParentId": "255805",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "255816",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T15:50:14.053",
"Id": "255805",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"set"
],
"Title": "Filtering a List based on a Suffix and avoid duplicates"
}
|
255805
|
<p>I'm comparing performance of two sorting algorithms applied to sort integers using google benchmark.</p>
<p>I'm quite surprised by the results so wanted to ask if you see some mistakes in the way I measure the performance. I would expect performance of my naive radix sort to be much worse that <code>std::sort</code> because it is supposed to be bandwidth bound.</p>
<pre><code>#include <benchmark/benchmark.h>
#include <random>
#include <vector>
#include <array>
#include <algorithm>
#define TEST_SIZE DenseRange(50000, 1000000, 50000)
class SortingBmk : public benchmark::Fixture
{
public:
using T = int32_t;
std::vector<T> m_vals;
void SetUp(const ::benchmark::State& state)
{
const auto n = state.range(0);
m_vals.resize(n);
std::iota(m_vals.begin(), m_vals.end(), 0);
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(m_vals.begin(), m_vals.end(), g);
}
void TearDown(const ::benchmark::State& state) {}
};
BENCHMARK_DEFINE_F(SortingBmk, StdSort)(benchmark::State& state)
{
const auto n = state.range(0);
std::vector<T> values(m_vals.size());
for (auto _ : state)
{
std::copy(m_vals.begin(), m_vals.end(), values.begin());
std::sort(values.begin(), values.end());
benchmark::DoNotOptimize(values);
benchmark::ClobberMemory();
}
}
BENCHMARK_REGISTER_F(SortingBmk, StdSort)->Unit(benchmark::kMicrosecond)->TEST_SIZE;
inline int getBits(SortingBmk::T v, SortingBmk::T i) { return (v >> i)&0b11; }
void radixSort_count(std::vector<SortingBmk::T>& data, std::vector<SortingBmk::T>& buf) {
const int n = data.size();
std::array<int, 8> psum = {0};
constexpr auto sz = sizeof(SortingBmk::T) * 8 - 2;
for (SortingBmk::T i = 0; i < sz; i += 2) {
//count sort
for (int v : data) {
auto bits = getBits(v, i);
++psum[bits];
}
for (int i = 1; i < 8; ++i)
psum[i] += psum[i-1];
for (int j = n - 1; j>= 0; --j) {
auto bits = getBits(data[j], i);
--psum[bits];
assert(psum[bits] < buf.size());
buf[ psum[bits] ] = data[j];
}
swap(buf, data);
psum = {0};
}
}
BENCHMARK_DEFINE_F(SortingBmk, NaiveRadixSort)(benchmark::State& state)
{
const auto n = state.range(0);
std::vector<T> values(m_vals.size());
std::vector<T> buffer(m_vals.size());
for (auto _ : state)
{
std::copy(m_vals.begin(), m_vals.end(), values.begin());
radixSort_count(values, buffer);
for (int i = 1; i < values.size(); ++i)
assert(values[i-1] < values[i]);
benchmark::DoNotOptimize(values);
benchmark::ClobberMemory();
}
}
BENCHMARK_REGISTER_F(SortingBmk, NaiveRadixSort)->Unit(benchmark::kMicrosecond)->TEST_SIZE;
BENCHMARK_MAIN();
</code></pre>
<p>UPD: X-axis is number of elements in the array, Y-axis is time spend on computations in average for all the times I run the code within <code>for</code> loop. It is in kMicrosecond.</p>
<p><a href="https://i.stack.imgur.com/2pSbd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2pSbd.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T17:21:02.443",
"Id": "504867",
"Score": "0",
"body": "I added text regarding axis labels."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T17:21:35.733",
"Id": "504868",
"Score": "3",
"body": "Thanks for that. Is `kMicrosecond` a new word for millisecond?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T02:52:19.670",
"Id": "505095",
"Score": "0",
"body": "I didn't look too close at the code, but don't you just pick all elements in range [0,n) and randomly shuffle them? How would `std::sort` be more efficient at sorting such a range compared to a radix sort? These are the perfect conditions ever for radix sorting. If your numbers were random arbitrary values then things would be different - also if they were a bizarre set of floating points - then radix sort would perform quite bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:26:37.403",
"Id": "505118",
"Score": "0",
"body": "Probably you are right regarding choosing numbers."
}
] |
[
{
"body": "<p>I'm not too surprised to see the radix sort being faster in this use case, 32 bits is very short for a key.\nYou may want to look at this <a href=\"https://erik.gorset.no/2011/04/radix-sort-is-faster-than-quicksort.html\" rel=\"nofollow noreferrer\">comparison</a> as well as at the last paragraph of this <a href=\"https://en.wikipedia.org/wiki/Radix_sort#History\" rel=\"nofollow noreferrer\">History</a> section.</p>\n<p>About the bench method, I would:</p>\n<ul>\n<li>Try with values already sorted.</li>\n<li>Try with values sorted in reverse.</li>\n<li>Try with multiple sets of random values, each set identified by its seed (so no random seed).</li>\n<li>Try with the same as above but with the first half filled with random values and the second half being a copy of the first half.</li>\n</ul>\n<p>I would also test the end result, of course.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:28:05.127",
"Id": "505119",
"Score": "0",
"body": "I think I will make a separate repo for benchmarking sorting algorithms. It might be interesting for a broad audience for educational purposes as well as to make provide a guidance which sorting algorithm to choose depending on the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T14:33:40.733",
"Id": "514255",
"Score": "0",
"body": "I've added this repo, comments are welcomed. See https://github.com/KirillLykov/int-sort-bmk"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T15:27:39.203",
"Id": "255847",
"ParentId": "255809",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255847",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T17:10:10.397",
"Id": "255809",
"Score": "3",
"Tags": [
"c++",
"sorting",
"benchmarking"
],
"Title": "benchmarking sorting algorithms: std::sort vs my naive radix"
}
|
255809
|
<p>I have a DB2 SQL view created with below statement:</p>
<p>The problem I am facing is kind of strange. When we do a select * on this view, it runs slow for the first few times every new session. But then after 2 to 3 executions, the speed improves drastically and execution time reduces to 2 seconds from the initial 40 seconds.</p>
<p>Can someone guide on any possible optimizations:</p>
<pre><code>-- Generate SQL
-- Version: V7R4M0 190621
-- Generated on: 02/09/21 10:26:37
-- Relational Database: BIGBLUE
-- Standards Option: Db2 for i
CREATE VIEW IESQAFILE.PSINPROGVW (
AS
WITH INPROGRESS AS
(
SELECT
DIODR#
, DIDISP
, DIUNIT
, DIETAD
, DIDR1
, DIETAT
FROM
IESQAFILE.LOAD
WHERE
DIETAD = 0
AND DIETAT = '0000'
ORDER BY
1
)
, STOPGROUP AS
(
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
, MAX(SOAPTM) APPTMADE
FROM
IESQAFILE.STOPOFF
INNER JOIN
INPROGRESS
ON
DIODR# = SOORD
WHERE
SOARDT = 0
GROUP BY
SOORD
ORDER BY
1
)
, STOPAPPTS AS
(
SELECT
SOORD APPTORDER
, SOCUST STOPCUST
, SOEDA ETADATE
, SOETA ETATIME
, SOADT1 EARLYDATE
, SOATM1 EARLYTIME
, SOADT2 LATEDATE
, SOATM2 LATETIME
, SOCTYC NEXTCITY
, SOSTP# APPTSTOP
, SOST NEXTSTATE
FROM
IESQAFILE.STOPOFF
INNER JOIN
STOPGROUP
ON
STOPORDER = SOORD
AND NEXTSTOP = SOSTP#
)
SELECT
ORDER_NUMBER
, SHIPPER_ID
, SHIPPER_NAME
, SHIPPER_ADDRESS_1
, SHIPPER_ADDRESS_2
, SHIPPER_CITY
, SHIPPER_ST
, SHIPPER_ZIP
, SHIPPER_ZIP_EXT
, LOAD_AT_ID
, LOAD_AT_NAME
, LOAD_AT_ADDRESS_1
, LOAD_AT_ADDRESS_2
, LOAD_AT_CITY
, LOAD_AT_ST
, LOAD_AT_ZIP
, LOAD_AT_ZIP_EXT
, LOAD_AT_LATITUDE
, LOAD_AT_LONGITUDE
, EARLY_PU_DATE_TIME
, LATE_PU_DATE_TIME
, EARLY_DELV_DATE_TIME
, EST_REVENUE
, ORDER_DIV
, CONSIGNEE_ID
, CONSIGNEE_NAME
, CONSIGNEE_ADDRESS_1
, CONSIGNEE_ADDRESS_2
, CONSIGNEE_CITY
, CONSIGNEE_ST
, CONSIGNEE_ZIP
, CONSIGNEE_ZIP_EXT
, CONSIGNEE_LATITUDE
, CONSIGNEE_LONGITUDE
, TRAILER_TYPE
, ORDER_MESSAGE
, ADDITIONAL_STOPS
, CMDTY_CODE
, CMDTY_DESCRIPTION
, ORDER_MILES
, ORDER_WGT
, ORIGIN_CITY_CODE
, ORIGIN_CITY
, ORIGIN_ST
, DEST_CITY_CODE
, DEST_CITY_NAME
, DEST_ST
, PICK_UP_AREA
, PLAN_INFO
, NUMBER_LDS
, NUMBER_DISP
, SHIP_DATE_TIME
, NEW_PICKUP_AREA
, EQUIPMENT_NUMBER
, APPT_REQ
, APPT_MADE
, PRE_T_SEQ
, PRE_T_AREA
, LOAD_DISPATCHED
,
CUST_SERV_REP,
NEGOTIATIONS,
(
CASE
WHEN UNUNIT IS NOT NULL
THEN UNUNIT
ELSE ' '
END
)
UNIT_DISPATCHED
,
(
CASE
WHEN UNSUPR IS NOT NULL
THEN UNSUPR
ELSE ' '
END
)
DRIVER_MGR_CODE
, COALESCE(SUPNAM,' ') DRIVER_MGR_NAME
,
(
CASE
WHEN UNFMGR IS NOT NULL
THEN UNFMGR
ELSE ' '
END
)
FLEET_MGR_CODE
, COALESCE(FLTNAM,' ') FLEET_MGR_NAME
,
(
CASE
WHEN UNTRL1 IS NOT NULL
THEN UNTRL1
ELSE ' '
END
)
TRAILER_ID
, (COALESCE(DIDISP, ' ')) DISPATCH_NUMBER
, (COALESCE(BCMCNEW, ' ')) FED_MC_ID
, (COALESCE(DIUNIT, ' ')) DISPATCHED_UNIT
, CASE
WHEN UNETAD <> 0
AND UNETAT = ''
THEN SMIS.CVTDATETIM(CHAR(UNETAD),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN UNETAD <> 0
THEN SMIS.CVTDATETIM(CHAR(UNETAD),UNETAT, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN UNETAD = 0
THEN '0000-00-00T00:00:00-00:00'
END AS ETA_DATE_TIME
, (COALESCE(NEXTSTOP, 0 )) NEXTSTOP
FROM
INPROGRESS
INNER JOIN
IESQAFILE.PSMAINORVW
ON
ORDER_NUMBER= DIODR#
AND DIDISP = NUMBER_DISP
LEFT OUTER JOIN
IESQAFILE.LMCARR
ON
DIUNIT = BCCARR
LEFT OUTER JOIN
IESQAFILE.MMILES
ON
MMORD# = DIODR#
AND MMRECTYPE = 'D'
AND MMDSP# = DIDISP
LEFT OUTER JOIN
STOPGROUP
ON
STOPORDER = DIODR#
LEFT OUTER JOIN
IESQAFILE.DRIVERS
ON
DRCODE = DIDR1
LEFT OUTER JOIN
IESQAFILE.UNITS
ON
UNUNIT = DIUNIT
AND UNORD# = ORDER_NUMBER
LEFT OUTER JOIN
IESQAFILE.SUPMAST
ON
SUPCDE = UNSUPR
LEFT OUTER JOIN
IESQAFILE.FLTMAST
ON
UNFMGR = FLTCDE
WHERE
DIETAD = 0
AND DIETAT = '0000'
RCDFMT PSINPROGVW ;
LABEL ON COLUMN IESQAFILE.PSINPROGVW
( ORDER_NUMBER IS 'ORDER#' ,
SHIPPER_ID IS 'SHIPPER' ,
SHIPPER_NAME IS 'Name' ,
SHIPPER_ADDRESS_1 IS 'Address1' ,
SHIPPER_ADDRESS_2 IS 'Address2' ,
SHIPPER_CITY IS 'City' ,
SHIPPER_ST IS 'State' ,
SHIPPER_ZIP IS 'Zip' ,
SHIPPER_ZIP_EXT IS 'Zip Ext' ,
LOAD_AT_ID IS 'LOAD AT' ,
LOAD_AT_NAME IS 'Name' ,
LOAD_AT_ADDRESS_1 IS 'Address1' ,
LOAD_AT_ADDRESS_2 IS 'Address2' ,
LOAD_AT_CITY IS 'City' ,
LOAD_AT_ST IS 'State' ,
LOAD_AT_ZIP IS 'Zip' ,
LOAD_AT_ZIP_EXT IS 'Zip Ext' ,
LOAD_AT_LATITUDE IS 'Latitude Decimal' ,
LOAD_AT_LONGITUDE IS 'Longitude Decimal' ,
ORDER_DIV IS 'DIV #' ,
CONSIGNEE_ID IS 'CUSTOMER' ,
CONSIGNEE_NAME IS 'Name' ,
CONSIGNEE_ADDRESS_1 IS 'Address1' ,
CONSIGNEE_ADDRESS_2 IS 'Address2' ,
CONSIGNEE_CITY IS 'City' ,
CONSIGNEE_ST IS 'State' ,
CONSIGNEE_ZIP IS 'Zip' ,
CONSIGNEE_ZIP_EXT IS 'Zip Ext' ,
CONSIGNEE_LATITUDE IS 'Latitude Decimal' ,
CONSIGNEE_LONGITUDE IS 'Longitude Decimal' ,
TRAILER_TYPE IS 'TRLR TYPE' ,
ORDER_MESSAGE IS 'SPEC' ,
ADDITIONAL_STOPS IS 'STP COM #' ,
CMDTY_CODE IS 'CMDTY CODE' ,
CMDTY_DESCRIPTION IS 'CMDTY DESC.' ,
ORDER_WGT IS 'ORD WGT' ,
ORIGIN_CITY_CODE IS 'ORG CITY' ,
ORIGIN_CITY IS 'City Name' ,
ORIGIN_ST IS 'ORG ST' ,
DEST_CITY_CODE IS 'DEST CITY' ,
DEST_CITY_NAME IS 'City Name' ,
DEST_ST IS 'DEST ST' ,
PICK_UP_AREA IS 'P/U AREA' ,
PLAN_INFO IS 'PREASS TRAC' ,
NUMBER_LDS IS '# LDS' ,
NUMBER_DISP IS '# DISP' ,
NEW_PICKUP_AREA IS 'NEW P/U AREA' ,
LOAD_DISPATCHED IS 'LDS DISP' ,
CUST_SERV_REP IS 'Init' ) ;
LABEL ON COLUMN IESQAFILE.PSINPROGVW
( ORDER_NUMBER TEXT IS 'ORDER#' ,
SHIPPER_ID TEXT IS 'SHIPPER' ,
SHIPPER_NAME TEXT IS 'Name' ,
SHIPPER_ADDRESS_1 TEXT IS 'Address1' ,
SHIPPER_ADDRESS_2 TEXT IS 'Address2' ,
SHIPPER_CITY TEXT IS 'City' ,
SHIPPER_ST TEXT IS 'State' ,
SHIPPER_ZIP TEXT IS 'Zip' ,
SHIPPER_ZIP_EXT TEXT IS 'Zip Extension' ,
LOAD_AT_ID TEXT IS 'LOAD AT' ,
LOAD_AT_NAME TEXT IS 'Name' ,
LOAD_AT_ADDRESS_1 TEXT IS 'Address1' ,
LOAD_AT_ADDRESS_2 TEXT IS 'Address2' ,
LOAD_AT_CITY TEXT IS 'City' ,
LOAD_AT_ST TEXT IS 'State' ,
LOAD_AT_ZIP TEXT IS 'Zip' ,
LOAD_AT_ZIP_EXT TEXT IS 'Zip Extension' ,
LOAD_AT_LATITUDE TEXT IS 'Latitude Decimal' ,
LOAD_AT_LONGITUDE TEXT IS 'Longitude Decimal' ,
EST_REVENUE TEXT IS 'EST. REV.' ,
ORDER_DIV TEXT IS 'DIVISION NUMBER' ,
CONSIGNEE_ID TEXT IS 'CUSTOMER' ,
CONSIGNEE_NAME TEXT IS 'Name' ,
CONSIGNEE_ADDRESS_1 TEXT IS 'Address1' ,
CONSIGNEE_ADDRESS_2 TEXT IS 'Address2' ,
CONSIGNEE_CITY TEXT IS 'City' ,
CONSIGNEE_ST TEXT IS 'State' ,
CONSIGNEE_ZIP TEXT IS 'Zip' ,
CONSIGNEE_ZIP_EXT TEXT IS 'Zip Extension' ,
CONSIGNEE_LATITUDE TEXT IS 'Latitude Decimal' ,
CONSIGNEE_LONGITUDE TEXT IS 'Longitude Decimal' ,
TRAILER_TYPE TEXT IS 'TRAILER TYPE' ,
ORDER_MESSAGE TEXT IS 'SPECIAL' ,
ADDITIONAL_STOPS TEXT IS '# OF STOPS & COMMENTS' ,
CMDTY_CODE TEXT IS 'COMMODITY CODE' ,
CMDTY_DESCRIPTION TEXT IS 'COMMODITY DESCRIPTION' ,
ORDER_WGT TEXT IS 'ORDER WEIGHT' ,
ORIGIN_CITY_CODE TEXT IS 'ORIGIN CITY' ,
ORIGIN_CITY TEXT IS 'CITY NAME' ,
ORIGIN_ST TEXT IS 'ORIGIN ST' ,
DEST_CITY_CODE TEXT IS 'DESTINATION CITY' ,
DEST_CITY_NAME TEXT IS 'CITY NAME' ,
DEST_ST TEXT IS 'DESTINATION ST' ,
PICK_UP_AREA TEXT IS 'P/U AREA' ,
PLAN_INFO TEXT IS 'PREASSIGNED TRACTOR' ,
NUMBER_LDS TEXT IS 'NUMBER OF LOADS' ,
NUMBER_DISP TEXT IS 'NUMBER OF DISPATCHES' ,
NEW_PICKUP_AREA TEXT IS 'NEW PICKUP AREA' ,
LOAD_DISPATCHED TEXT IS 'LOADS DISPATCHED TO DESTINATION' ,
CUST_SERV_REP TEXT IS 'Customer Service Rep.' ) ;
GRANT ALTER , REFERENCES , SELECT
ON IESQAFILE.PSINPROGVW TO QPGMR WITH GRANT OPTION ;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T17:36:26.133",
"Id": "524842",
"Score": "0",
"body": "Have you looked at the visual explain for this? It will tell you what the SQL engine is doing behind the scenes, and also point out indexes that you should create. BTW, this is very hard to read. Maybe reformat so we can have a better chance to understand what is going on. I was going to do that, but gave up. The only thing worse than no formatting is inconsistent bad formatting."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T17:13:16.477",
"Id": "255810",
"Score": "0",
"Tags": [
"sql",
"db2",
"ibm-rpg"
],
"Title": "View returning results from multiple tables"
}
|
255810
|
<p>I am using Xamarin.Forms, Microcharts and SQLite.NET to create a mobile app. The SQLite.NET database stores details about books (book ID and entry date - the date it was entered in the system).</p>
<p>The bar chart displays the number of books entered this week on each day - from Monday to Sunday.</p>
<p>However, this implementation seems inefficient. Additionally, as DateTime fields in the database don't have an equivalent of DateTime.Date property in .NET the query checks between two dates to get the count for each day.</p>
<pre><code>using SkiaSharp;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Microcharts;
using ChartEntry = Microcharts.ChartEntry;
public GraphDisplayPage()
{
InitializeComponent();
DrawChart();
}
void DrawChart()
{
var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);
int mondayBookCount = App.Database.GetDailyCount(monday);
var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);
int tuesdayBookCount = App.Database.GetDailyCount(tuesday);
var wednesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Wednesday);
int wednesdayBookCount = App.Database.GetDailyCount(wednesday);
var thursday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Thursday);
int thursdayBookCount = App.Database.GetDailyCount(thursday);
var friday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Friday);
int fridayBookCount = App.Database.GetDailyCount(friday);
var saturday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Saturday);
int saturdayBookCount = App.Database.GetDailyCount(saturday);
var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Sunday);
int sundayBookCount = App.Database.GetDailyCount(sunday);
List<ChartEntry> entries = new List<ChartEntry>
{
new ChartEntry(mondayBookCount)
{
Label = "Monday",
ValueLabel = mondayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
},
new ChartEntry(tuesdayBookCount)
{
Label = "Tuesday",
ValueLabel = tuesdayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
},
new ChartEntry(wednesdayBookCount)
{
Label = "Wednesday",
ValueLabel = wednesdayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
},
new ChartEntry(thursdayBookCount)
{
Label = "Thursday",
ValueLabel = thursdayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
},
new ChartEntry(fridayBookCount)
{
Label = "Friday",
ValueLabel = fridayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
},
new ChartEntry(saturdayBookCount)
{
Label = "Saturday",
ValueLabel = saturdayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
},
new ChartEntry(sundayBookCount)
{
Label = "Sunday",
ValueLabel = sundayBookCount.ToString(),
Color = SKColor.Parse("#004daa")
}
};
chartView.Chart = new BarChart { Entries = entries, LabelTextSize = 32f, LabelOrientation = Orientation.Horizontal, ValueLabelOrientation = Orientation.Horizontal, Margin = 20 };
}
</code></pre>
<p>Book.cs</p>
<pre><code> public class Book : INotifyPropertyChanged
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
private DateTime bookSaveTime;
public DateTime BookSaveTime
{
get
{
return bookSaveTime;
}
set
{
if (bookSaveTime != value)
{
bookSaveTime= value;
OnPropertyChanged("BookSaveTime");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
</code></pre>
<p>SQLiteDatabase.cs:</p>
<pre><code>static SQLiteConnection database;
public const string DbFileName = "SQLite.db3";
public string CurrentState;
public SQLiteDatabase()
{
try
{
database = DependencyService.Get<ISQLiteService>().GetConnection(DbFileName);
database.CreateTable<Book>();
CurrentState = "Database created";
}
catch (SQLiteException ex)
{
CurrentState = ex.Message;
}
}
public int GetDailyCount(DateTime day)
{
var dayAfterCurrentDay = day.AddDays(1);
return database.ExecuteScalar<int>("SELECT COUNT(*) FROM Book WHERE bookSaveTime> ? AND bookSaveTime< ?;", day, dayAfterCurrentDay);
}
</code></pre>
<p>Is it possible to improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T21:32:42.363",
"Id": "504900",
"Score": "1",
"body": "I would think the `DrawChart` method could be shorter by applying DRY."
}
] |
[
{
"body": "<p>In this review let me try to focus on a single thing: <strong>eliminating duplicates</strong>.</p>\n<h2>What is the problem with duplicates?</h2>\n<ol>\n<li>The size of your code base could become quite lengthy. It ruins legibility.</li>\n<li>If you need to change one thing on the functionality, which affects all duplicates, then you have to do that in all occurrences.</li>\n<li>If you need to extend your datasource then it is appealing to use copy-paste, which is error-prone. With Ctrl+C & Ctrl+V you might forget to change an important property/method call/whatever which is duplicate specific.</li>\n</ol>\n<h2>How can I eliminate this?</h2>\n<ul>\n<li>The short answer: <strong>By loosening the coupling between data and functionality</strong>.</li>\n<li>In this particular case your implementation executes the same functionality over and over again against different data.</li>\n<li>So, first you have to identify which piece of functionality is executed multiple times:\n<ul>\n<li>Here I have used <code>{xyz}</code> to indicate placeholders, which changes for each duplicate.</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var {dayOfWeekDate} = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int){dayOfWeekEnumCalue});\nint {dayOfWeekBookCount} = App.Database.GetDailyCount({dayOfWeekDate});\n</code></pre>\n<h3><code>{dayOfWeekEnumValue}</code></h3>\n<ul>\n<li>You can get all values of <code>DayOfWeek</code> by using the <code>Enum.GetValues</code> functionality.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var days = (DayOfWeek[]) Enum.GetValues(typeof(DayOfWeek));\n</code></pre>\n<ul>\n<li>We can iterate through this collection to get each day:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var day in days)\n{\n var {dayOfWeekDate} = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)day);\n var {dayOfWeekBookCount} = App.Database.GetDailyCount({dayOfWeekDate});\n}\n</code></pre>\n<h3><code>{dayOfWeekDate}</code></h3>\n<ul>\n<li>This variable is scoped for the <code>foreach</code>. So, here we can use whatever name we want.\n<ul>\n<li>We can name it by describing what data is stored on it.</li>\n<li>It is better than naming it how do we want to use it. If we need to extend functionality and we need to use this variable in multiple method calls then the naming could become problematic.</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var day in days)\n{\n var specificDayAtMidnight = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)day);\n var {dayOfWeekBookCount} = App.Database.GetDailyCount(specificDayAtMidnight);\n}\n</code></pre>\n<h3><code>{dayOfWeekBookCount}</code></h3>\n<ul>\n<li>Here we are enlarging the scope of our interest.\n<ul>\n<li>Where and how do we want to use this data?</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>new ChartEntry({dayOfWeekBookCount})\n{\n Label = "Monday",\n ValueLabel = {dayOfWeekBookCount}.ToString(),\n Color = SKColor.Parse("#004daa")\n},\n</code></pre>\n<ul>\n<li>As we can see it is day specific. So, we have to bind the day and the book count.\n<ul>\n<li>This can be easily done by using for example a <code>Dictionary</code>:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>Dictionary<string, int> dailyBookCounts = new Dictionary<string, int>();\n</code></pre>\n<ul>\n<li>Here the <code>key</code> is the name of the day and <code>value</code> is the book count.</li>\n<li>We should populate this collection inside our <code>foreach</code> loop:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var day in days)\n{\n var specificDayAtMidnight = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)day);\n var bookCount = App.Database.GetDailyCount(specificDayAtMidnight);\n dailyBookCounts.Add(day.ToString("G"), bookCount);\n}\n</code></pre>\n<h3><code>entries</code></h3>\n<ul>\n<li>With these data in our hand we are able to eliminate the duplicates of the <code>ChartEntry</code> instance creation.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>List<ChartEntry> entries = new List<ChartEntry>();\nforeach (var dailyBookCount in dailyBookCounts)\n{\n entries.Add(new ChartEntry(dailyBookCount.Value)\n {\n Label = dailyBookCount.Key,\n ValueLabel = dailyBookCount.Value.ToString(),\n Color = SKColor.Parse("#004daa")\n });\n}\n</code></pre>\n<ul>\n<li>Depending on the C# version we can take advantage of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct\" rel=\"nofollow noreferrer\">deconstruction</a>:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var (nameOfTheDay, bookCountOfTheDay) in dailyBookCounts)\n{\n entries.Add(new ChartEntry(bookCountOfTheDay)\n {\n Label = nameOfTheDay,\n ValueLabel = bookCountOfTheDay.ToString(),\n Color = SKColor.Parse("#004daa")\n });\n}\n</code></pre>\n<h2>How does my code look like after these modifications?</h2>\n<pre class=\"lang-cs prettyprint-override\"><code>//Extract\nvar days = (DayOfWeek[]) Enum.GetValues(typeof(DayOfWeek));\nvar dailyBookCounts = new Dictionary<string, int>();\nforeach (var day in days)\n{\n var specificDayAtMidnight = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)day);\n var bookCount = App.Database.GetDailyCount(specificDayAtMidnight);\n dailyBookCounts.Add(day.ToString("G"), bookCount);\n}\n\n//Transform\nvar entries = new List<ChartEntry>();\nforeach (var (nameOfTheDay, bookCountOfTheDay) in dailyBookCounts)\n{\n entries.Add(new ChartEntry(bookCountOfTheDay)\n {\n Label = nameOfTheDay,\n ValueLabel = bookCountOfTheDay.ToString(),\n Color = SKColor.Parse("#004daa")\n });\n}\n\n//Load\nchartView.Chart = new BarChart\n{\n Entries = entries, \n LabelTextSize = 32f, \n LabelOrientation = Orientation.Horizontal, \n ValueLabelOrientation = Orientation.Horizontal, \n Margin = 20\n};\n</code></pre>\n<ul>\n<li>As you can see I've added 3 lines of comment. I've used here the <a href=\"https://en.wikipedia.org/wiki/Extract,_transform,_load\" rel=\"nofollow noreferrer\">Extract, Transform and Load</a> (or in short ETL) concept to separate the phases of your method. This improves legibility by helping the maintainer of your code where to locate a particular piece of functionality.</li>\n</ul>\n<h2>Is there something else which could improved?</h2>\n<ul>\n<li>Yes, there are two major concerns which could be addressed:\n<ul>\n<li>Async I/O</li>\n<li>Batch operation</li>\n</ul>\n</li>\n</ul>\n<h3>Async I/O</h3>\n<ul>\n<li>Whenever you perform a database query by calling the <code>App.Database.GetDailyCount</code> method you are blocking the execution of your code until the data retrieval finishes. Which is not bad, but your <code>Thread</code> does not do anything just waits for the response. So, you are basically wasting valuable computation resources.</li>\n<li>If you would use async (non-blocking) I/O calls then while the database performs the query your <code>Thread</code> will be freed and it could be able to execute any other code. So, this can improve your system throughput (by allowing to perform CPU based calculation while the application is waiting for an I/O operation to complete).</li>\n</ul>\n<h3>Batch operation</h3>\n<ul>\n<li>In your current implementation you perform 7 individual database calls. Which means there are 7 round trips between your app and database. It is not a problem on your dev machine because most probably both runs on the same machine. But in case of production environment they are likely separated and running on different machines. Which means there is a network latency which should be considered as well.</li>\n<li>By allowing to perform a batch operation on the database side you can reduce the number of round trips to 1 which means that the network latency can become negligible.</li>\n</ul>\n<p>Your code would look something like:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var startDates = new List<DateTime>();\nforeach (var day in days)\n{\n startDates.Add(DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)day));\n}\n\nDictionary<string, int> dailyBookCounts = await App.Database.GetWeeklyCountAsync(startDates);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T09:29:20.930",
"Id": "255839",
"ParentId": "255811",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255839",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T17:18:47.923",
"Id": "255811",
"Score": "2",
"Tags": [
"c#",
"sqlite",
"xamarin"
],
"Title": "Generate a bar chart of weekly data from SQLite.NET"
}
|
255811
|
<p>In my SwiftUI app, I'm trying to get some data from a json Api and display this data along with an image. First I have a function that fetches the data from the Api, then I have another function that downloads the image data. The image takes a while to appear(1-2) seconds.
I'm wondering if this is the best way to do it, especially if I'm downloading multiple images to display them in a List or a Grid.</p>
<pre><code>func fetchAPI() {
URLSession.shared.dataTask(with: url) { (data, response, error) in
/* Code that decodes the json and gets the imageURL string */
DispatchQueue.main.async {
self.downloadImage(url: imageURL) // call the function that downloads the imageData
}
} catch {
print("Error: \(error.localizedDescription)")
}
}
.resume()
}
</code></pre>
<p>The function that downloads the image:</p>
<pre><code>func downloadImage(url: String) {
guard let imageURL = URL(string: url) else {
print("Error: Invalid image URL")
return
}
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let recievedData = data, error == nil else {
print("Error: No Data")
return
}
DispatchQueue.main.async {
self.imageData = recievedData
}
}
.resume()
}
</code></pre>
|
[] |
[
{
"body": "<p>Maybe the image is in question is a little bit large or the internet connection used is a little bit slow.</p>\n<p>I personally would go about it differently.</p>\n<p>For <strong>UIKit</strong></p>\n<pre class=\"lang-swift prettyprint-override\"><code>import UIKit\nimport Foundation\n\nextension UIImageView {\n func load(url: URL) {\n DispatchQueue.global().async { [weak self] in\n if let data = try? Data(contentsOf: url) {\n if let image = UIImage(data: data) {\n DispatchQueue.main.async {\n self?.image = image\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>For <strong>SwiftUI</strong> we have to go about it a little bit differently but there are two ways</p>\n<p>The very simple one-time usage:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>import Foundation\nimport SwiftUI\nimport Combine\n\n// Image Loader\nclass ImageLoader: ObservableObject { \n var dataPublisher = PassthroughSubject<Data, Never>() \n var data = Data() { \n didSet { \n dataPublisher.send(data) \n } \n }\n\n init(urlString:String) { \n guard let url = URL(string: urlString) else { return } \n let task = URLSession.shared.dataTask(with: url) { data, response, error in \n guard let data = data else { return } \n DispatchQueue.main.async { \n self.data = data \n } \n } \n task.resume() \n }\n}\n\n// Image View\nstruct ImageView: View {\n @ObservedObject var imageLoader:ImageLoader\n @State var image:UIImage = UIImage()\n\n init(withURL url:String) {\n imageLoader = ImageLoader(urlString: url)\n }\n\n var body: some View {\n VStack { \n Image(uiImage: image)\n .resizable()\n .aspectRatio(contentMode: .fit)\n .frame(width:100, height:100)\n }.onReceive(imageLoader.dataPublisher) { data in\n self.image = UIImage(data: data) ?? UIImage()\n }\n }\n}\n\nstruct ImageView_Previews: PreviewProvider {\n static var previews: some View {\n ImageView(withURL: "")\n }\n}\n</code></pre>\n<p>The more advanced way</p>\n<pre class=\"lang-swift prettyprint-override\"><code>import Foundation\nimport SwiftUI\nimport Combine\n\n// ImageCache\nprotocol ImageCache {\n subscript(_ url: URL) -> UIImage? { get set }\n}\n\nstruct TemporaryImageCache: ImageCache {\n private let cache: NSCache<NSURL, UIImage> = {\n let cache = NSCache<NSURL, UIImage>()\n cache.countLimit = 100 // 100 items\n cache.totalCostLimit = 1024 * 1024 * 100 // 100 MB\n return cache\n }()\n \n subscript(_ key: URL) -> UIImage? {\n get {\n self.cache.object(forKey: key as NSURL)\n }\n set {\n newValue == nil ? self.cache.removeObject(forKey: key as NSURL) : self.cache.setObject(newValue!, forKey: key as NSURL)\n }\n }\n}\n\n// EnvironmentValues+ImageCache\nstruct ImageCacheKey: EnvironmentKey {\n static let defaultValue: ImageCache = TemporaryImageCache()\n}\n\nextension EnvironmentValues {\n var imageCache: ImageCache {\n get {\n self[ImageCacheKey.self]\n }\n set {\n self[ImageCacheKey.self] = newValue\n }\n }\n}\n\n// Image Loader\nclass ImageLoader: ObservableObject {\n @Published\n var image: UIImage?\n \n private(set) var isLoading = false\n \n private let url: URL\n private var cache: ImageCache?\n private var cancellable: AnyCancellable?\n \n private static let imageDownloadingQueue = DispatchQueue(label: "image-downloading")\n \n init(url: URL, cache: ImageCache? = nil) {\n self.url = url\n self.cache = cache\n }\n \n deinit {\n self.cancel()\n }\n \n func load() {\n guard !self.isLoading else { return }\n \n if let image = self.cache?[self.url] {\n self.image = image\n return\n }\n \n self.cancellable = URLSession.shared.dataTaskPublisher(for: self.url)\n .map {\n UIImage(data: $0.data)\n }\n .replaceError(with: nil)\n .handleEvents(receiveSubscription: { [weak self] _ in\n self?.onStart()\n },\n receiveOutput: { [weak self] in\n self?.cache($0)\n },\n receiveCompletion: { [weak self] _ in\n self?.onFinish()\n },\n receiveCancel: { [weak self] in\n self?.onFinish()\n })\n .subscribe(on: Self.imageDownloadingQueue)\n .receive(on: DispatchQueue.main)\n .sink { [weak self] in\n self?.image = $0\n }\n }\n \n func cancel() {\n self.cancellable?.cancel()\n }\n \n private func onStart() {\n self.isLoading = true\n }\n \n private func onFinish() {\n self.isLoading = false\n }\n \n private func cache(_ image: UIImage?) {\n image.map {\n self.cache?[self.url] = $0\n }\n }\n}\n\n// Image View\nstruct ImageView<Placeholder: View>: View {\n @StateObject\n private var loader: ImageLoader\n private let placeholder: Placeholder\n private let image: (UIImage) -> Image\n \n init(url: URL, @ViewBuilder placeholder: () -> Placeholder, @ViewBuilder image: @escaping (UIImage) -> Image = Image.init(uiImage:)) {\n self.placeholder = placeholder()\n self.image = image\n self._loader = StateObject(wrappedValue: ImageLoader(url: url, cache: Environment(\\.imageCache).wrappedValue))\n }\n \n var body: some View {\n self.content.onAppear(perform: loader.load)\n }\n \n private var content: some View {\n Group {\n if let image = self.loader.image {\n self.image(image)\n } else {\n self.placeholder\n }\n }\n }\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T09:09:29.300",
"Id": "256129",
"ParentId": "255818",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T18:42:58.037",
"Id": "255818",
"Score": "0",
"Tags": [
"json",
"swift",
"swiftui"
],
"Title": "Is this a good way to download images from json Api?"
}
|
255818
|
<p>Hello I am hoping someone can provide me feedback on my solution to this prob. If there are additional edge cases I should consider etc. Thank you!</p>
<p>The question: "Given a sentence with a set of delimiters, reverse the order of the words in the sentence and keep the delimiters in place."</p>
<pre><code>let isAlpha = (char) => {
let pat = /[a-zA-z]/igm; // match any alphabetic character
if(char.match(pat)){
return true
} else {
return false
}
}
function reverse(s){
let specialArr = []
for(ltr of s){
if(!isAlpha(ltr)){ // pull out all special characters in order
specialArr.push(ltr)
}
}
let regCharArr = s.split(/[^a-z]/ig).reverse() // use split to pull out all words separated by non alpha characters. then reverse
let result = [] // init result array
if(isAlpha(s[0])){
result = regCharArr.flatMap((val, idx) => [val, specialArr[idx]]) //use flatmap to combine the two arrays...if origin array starts with letter, combine special array into reg array
}
if(!isAlpha(s[0])){
result = specialArr.flatMap((val, idx) => [val, regCharArr[idx]]) // vice versa
}
for(let i = 0; i < result.length; i++){ // remove any undefineds
if(result[i] === undefined){
result.splice(i, 1)
}
}
return result.join('')
}
// let sentence = "one|twotwo/three:four" // four|three/twotwo:one
let sentence = "|brian/steve:chris|jon" // |jon/chris:steve|brian
console.log(reverse(sentence))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T19:43:49.880",
"Id": "504884",
"Score": "0",
"body": "[There is an answer at SO](https://stackoverflow.com/questions/66124459/how-does-one-reverse-the-word-order-within-a-string-but-does-keep-the-order-of-t/66125409#66125409)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T20:24:58.523",
"Id": "504890",
"Score": "0",
"body": "Thank you! I just took a look at your response. My solution breaks on spaces too..where as yours does not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T06:11:00.227",
"Id": "504919",
"Score": "1",
"body": "Could you add some testcases to describe what the requirement is? For example, what is \"word\" means here? Is \"twenty-three\" a single word or two? Will there always be some words between two delimiter characters? What is the expected output for `\"#a!!b?c\"`?"
}
] |
[
{
"body": "<p>The current implementation of <code>isAlpha</code> ...</p>\n<pre><code>let isAlpha = (char) => {\n // match any alphabetic character.\n let pat = /[a-zA-z]/igm;\n\n if(char.match(pat)){\n return true;\n } else {\n return false;\n }\n};\n</code></pre>\n<p>... can be refactored into something as short as this ...</p>\n<pre><code>function isAlpha(char) {\n return (/[a-zA-z]/).test(char);\n};\n</code></pre>\n<p>... or maybe even that ...</p>\n<pre><code>function isAlpha(char) {\n // \\w matches any word character\n // and is equal to [a-zA-Z0-9_]\n return (/\\w/).test(char);\n};\n</code></pre>\n<p>Why is that?</p>\n<p><code>isAlpha</code> gets invoked from within <code>reverse</code> always by providing a single character. Thus the regex can be simplified from <code>/[a-zA-z]/igm</code> to <code>/[a-zA-z]/</code>. Since <code>isAlpha</code> is supposed to return a boolean value do not use <code>match</code> and do no not return either <code>true</code> or <code>false</code> separately but use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test\" rel=\"nofollow noreferrer\"><code>RegExp.prototype.test</code></a> instead which already provides the correct return value.</p>\n<p>Thats all so far but I will continue looking through the code, since as of now I don't understand why one wants to test a string stepwise character by character.</p>\n<p>There is an answer of mine, regarding your question at StackOverflow. Maybe you get some inspiration from an alternative approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T20:13:32.487",
"Id": "255824",
"ParentId": "255819",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T19:05:44.337",
"Id": "255819",
"Score": "2",
"Tags": [
"javascript",
"strings"
],
"Title": "Javascript. Reverse order of words in string, but not special characters"
}
|
255819
|
<p>I made a command line in Python.
Before I go on and add more commands, is my program made well?</p>
<p>I don't like the huge amount of "if" statements in it. But I don't know a better way to do it. (JSON may be used later this is why I have it included)</p>
<p>Here's the code:</p>
<pre><code>import time
import json
print("Welcome to pyCMD, user\n")
time.sleep(0.2)
input("Press enter to start\n")
time.sleep(0.2)
def SavetoDisk(data, file):
with open(file, 'w') as outfile:
json.dump(data, outfile)
def ReadfromDisk(file):
with open(file) as json_file:
data = json.load(json_file)
return data
print('Starting command line, use "help . ." for help')
running = True
commandList = "add | sub | mult | div | exp | tetrate | python"
while running:
try:
userInput = input(': ')
tokens = userInput.split()
command = tokens[0]
args = [(token) for token in tokens[1:]]
except: print("unknown input error")
try:
arg1, arg2 = args
except ValueError:
print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')
if command == "add":
print(float(arg1) + float(arg2))
if command == "sub":
print(float(arg1) - float(arg2))
if command == "mult":
print(float(arg1) * float(arg2)) #math commands
if command == "div":
print(float(arg1) / float(arg2))
if command == "exp":
print(float(arg1) ** float(arg2))
if command == "tetrate":
for x in range(int(arg2)):
arg1 = float(arg1) * float(arg1)
print(arg1)
if command == "python":
exec(open(arg1).read())
if command == "help":
if arg1 == '.':
if arg2 == '.':
print('To see help about a command, type: "help [command] ." for list of commands type: "help command list"')
if arg1 == 'command':
if arg2 == 'list':
print(commandList)
if arg1 == 'add':
print("Add: \n Description: Adds 2 numbers \n Syntax: add [num1] [num2]")
if arg1 == 'sub':
print("Sub: \nDescription: Subtracts 2 numbers \n Syntax : sub [num1] [num2]")
if arg1 == 'mult':
print("Mult: \nDescription: Multiplies 2 numbers \n Syntax : mult [num1] [num2]")
if arg1 == 'div':
print("Div: \nDescription: Divides 2 numbers \n Syntax : div [num1] [num2]")
if arg1 == 'exp':
print("Exp: \nDescription: Raises 1 number by another \n Syntax : exp [num1] [num2]")
if arg1 == 'tetrate':
print("Tetrate: \nDescription: Tetration \n Syntax : tetrate [num1] [num2]")
if arg1 == 'python':
print("Python: \nDescription: Runs a python script \n Syntax : python [path/to/program.py] .")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T20:26:28.833",
"Id": "504891",
"Score": "2",
"body": "We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T08:08:55.953",
"Id": "504930",
"Score": "0",
"body": "(Know [YAGNI](https://en.m.wikipedia.org/wiki/You_aren%27t_gonna_need_it)?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T14:30:49.547",
"Id": "504970",
"Score": "1",
"body": "This is somewhat a case of \"reinventing the wheel to be built in a square shape from smaller round wheels\". A standard Python REPL is more capable, and already exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T14:48:23.273",
"Id": "504972",
"Score": "0",
"body": "Is the enforcement of exactly 2 args for all commands (with suggestion to add dummy `.`) a feature you desire? Or just a just side effect of original implementation with all commands going through same path?"
}
] |
[
{
"body": "<h2>Review regarding the main question: reducing the ifs</h2>\n<p>Let me start by saying that Python does not support <code>switch</code> statements, which would have been very useful in this case. I would recommend reading <a href=\"https://stackoverflow.com/a/60211/2467938\">this</a> StackOverflow answer on how to get a similar result (I will be using that approach here too).</p>\n<p>Something you should notice is that your if statements:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if command == "add":\n print(float(arg1) + float(arg2))\n</code></pre>\n<p>are running code that follows this pattern:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(arg operand arg)\n</code></pre>\n<p>So it follows the question: how do we generalise that?</p>\n<p>It turns out that we can use the <a href=\"https://docs.python.org/3/library/operator.html\" rel=\"noreferrer\"><code>operator</code></a> to our advantage here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import operator\ndef operation(a, b, operand):\n return operand(a, b)\n</code></pre>\n<p>Then you can map your "commands" to the different operands as such:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_operator(x):\n return {\n 'add': operator.add,\n 'multiply': operator.mul,\n ...\n }[x]\n</code></pre>\n<p>and finally you can reduce your multiple ifs with a single line of code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>operation(arg1, arg2, get_operator(command))\n</code></pre>\n<p>It must be noted that you could also have written:</p>\n<pre class=\"lang-py prettyprint-override\"><code>get_operator(command)(arg1, arg2)\n</code></pre>\n<p>One can argue that one approach is better than the other for different reasons related to abstractions, decomposition, etc...</p>\n<h2>General Review</h2>\n<h3>Argparse</h3>\n<p>Rather than doing all that tokenisation of the commands yourself, you should be using the <a href=\"https://docs.python.org/3/library/argparse.html#module-argparse\" rel=\"noreferrer\">argparse</a> module.\nI am not going to explain here how to convert your code to use argparse, but if you follow the tutorial in the documentation it should be straighforward how to do that. That will also massively reduce the code you have written for the help menu.</p>\n<h3>Naming</h3>\n<p>In Python it is good convention to use <code>snake_case</code> for naming variables and functions. So the function <code>SavetoDisk</code> would become <code>save_to_disk</code>.</p>\n<h3>Lists and Enums</h3>\n<p>Your <code>commandList</code> is not a list. It is just a string separated by the <code>|</code> character.\nRather consider using a true list and have <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">enums</a> rather than strings for your commands.</p>\n<pre class=\"lang-py prettyprint-override\"><code>commands = [ Command.ADD, Command.MULTIPLY, ...]\n</code></pre>\n<p>Best of luck!</p>\n<hr />\n<h2>Update on Python Pattern Matching</h2>\n<p>I just found out that the pattern matching proposals (<a href=\"https://www.python.org/dev/peps/pep-0636/\" rel=\"noreferrer\">PEP 636</a> and companions <a href=\"https://www.python.org/dev/peps/pep-0634/\" rel=\"noreferrer\">PEP 634</a>, <a href=\"https://www.python.org/dev/peps/pep-0635/\" rel=\"noreferrer\">PEP 635</a>) and have been accepted for development just yesterday <a href=\"https://lwn.net/Articles/845480/\" rel=\"noreferrer\">08/02/2021</a>!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T21:25:33.527",
"Id": "255826",
"ParentId": "255820",
"Score": "8"
}
},
{
"body": "<p>The first thing I notice with your code is that the code is <em>a very long</em> global script. To resolve this I'd start by moving your code into functions.</p>\n<p>The actual calculations could be as simple as say:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add(arg1, arg2):\n print(float(arg1) + float(arg2))\n</code></pre>\n<p>To then get the help information we could add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstring</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add(arg1, arg2):\n """\n Add:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n """\n print(float(arg1) + float(arg2))\n</code></pre>\n<p>We can get both the docstring and the output of the operation with Python. To get the docstring to be nicely formatted we can use <a href=\"https://docs.python.org/3/library/textwrap.html#textwrap.dedent\" rel=\"noreferrer\"><code>textwrap.dedent</code></a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> add("10", "5")\n15.0\n>>> import textwrap\n>>> textwrap.dedent(add.__doc__.strip("\\n"))\nAdd:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n\n</code></pre>\n<p>To then reduce the amount of lines of code we can bundle all these functions into a dictionary. And just index the dictionary to get a specific function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>COMMANDS = {\n "add": add,\n "sub": sub,\n # ...\n}\n\nfn = COMMANDS["add"]\nfn("10", "5")\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>15.0\n</code></pre>\n<p>Whilst you can build the dictionary and execute the commands yourself, you could instead subclass <a href=\"https://docs.python.org/3/library/cmd.html\" rel=\"noreferrer\"><code>cmd.Cmd</code></a>. You will need to change the functions slightly to only take a string as input, and prefix <code>do_</code> to any commands available to the commandline.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import cmd\n\n\nclass PyCMD(cmd.Cmd):\n intro = 'Welcome to pyCMD, user\\nStarting command line, use "help" for help'\n prompt = ": "\n\n def do_add(self, arg):\n """\n Add:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n """\n arg1, arg2 = arg.split()\n print(float(arg1) + float(arg2))\n\nPyCMD().cmdloop()\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Welcome to pyCMD, user\nStarting command line, use "help" for help\n: help\n\nDocumented commands (type help <topic>):\n========================================\nadd help\n\n: help add\n\n Add:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n \n: add 10 5\n15.0\n</code></pre>\n<p>The help is clearly a bit on the broken side. To fix this we can change the docstring after the function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class PyCMD(cmd.Cmd):\n def do_add(self, arg):\n # ...\n\n do_add.__doc__ = textwrap.dedent(do_add.__doc__.rstrip(" ").strip("\\n"))\n</code></pre>\n<p>This is a bit ugly and doing this for each function would be horrible. So we can create a function to do this.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def clean_doc(fn):\n fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\\n"))\n\n\nclass PyCMD(cmd.Cmd):\n def do_add(self, arg):\n # ...\n\n clean_doc(do_add)\n</code></pre>\n<p>This is still a bit on the ugly side so we can use <code>@</code> to do this for us. This is called a <a href=\"https://www.python.org/dev/peps/pep-0318/\" rel=\"noreferrer\">decorator</a>. This makes sense because we're decorating how <code>__doc__</code> is seen. Note that we changed <code>clean_doc</code> to return <code>fn</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def clean_doc(fn):\n fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\\n"))\n return fn\n\n\nclass PyCMD(cmd.Cmd):\n @clean_doc\n def do_add(self, arg):\n # ...\n</code></pre>\n<p>We can add another function like <code>clean_doc</code>, but this time make it a <a href=\"https://en.wikipedia.org/wiki/Closure_(computer_programming)\" rel=\"noreferrer\">closure</a> if you want to easily add your validation of two arguments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\n\ndef command(fn):\n @functools.wraps(fn)\n def wrapper(self, arg):\n args = [token for token in arg.split()]\n try:\n arg1, arg2 = args\n except ValueError:\n print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')\n else:\n return fn(self, arg1, arg2)\n return wrapper\n\n\nclass PyCMD(cmd.Cmd):\n @command\n @clean_doc\n def do_add(self, arg1, arg2):\n """\n Add:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n """\n print(float(arg1) + float(arg2))\n</code></pre>\n<hr />\n<pre class=\"lang-py prettyprint-override\"><code>import cmd\nimport textwrap\nimport functools\n\n\ndef command(fn):\n @functools.wraps(fn)\n def wrapper(self, arg):\n try:\n arg1, arg2 = arg.split()\n except ValueError:\n print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')\n else:\n return fn(self, arg1, arg2)\n return wrapper\n\n\ndef clean_doc(fn):\n fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\\n"))\n return fn\n\n\nclass PyCMD(cmd.Cmd):\n intro = 'Welcome to pyCMD, user\\nStarting command line, use "help" for help'\n prompt = ": "\n\n @command\n @clean_doc\n def do_add(self, arg1, arg2):\n """\n Add:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n """\n print(float(arg1) + float(arg2))\n\n\nPyCMD().cmdloop()\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Welcome to pyCMD, user\nStarting command line, use "help" for help\n: help\n\nDocumented commands (type help <topic>):\n========================================\nadd help\n\n: help add\nAdd:\n Description: Adds 2 numbers\n Syntax: add [num1] [num2]\n: add 10 5\n15.0\n</code></pre>\n<p><sup>Other commands left for you to implement</sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:05:08.513",
"Id": "504983",
"Score": "3",
"body": "What's great about this answer is separating the external behavior (prompt for a line, split, check number of words, support `help` command) from internal representation of possible commands. The internal representation is _idiomatic python functions_ . This is a widely applicable idea, and almost always makes both aspects clearer than when they're intermixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:51:50.777",
"Id": "504988",
"Score": "1",
"body": "This is a very well written answer. I love how you've turned the code into a beautiful, extensible framework for adding future commands as simply as possible. I love the decorators too. I definitely learned a thing or two from this answer, even though I considered myself very fluent in python and pythonic design!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T21:26:01.130",
"Id": "255827",
"ParentId": "255820",
"Score": "22"
}
}
] |
{
"AcceptedAnswerId": "255827",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T19:34:58.520",
"Id": "255820",
"Score": "10",
"Tags": [
"python",
"console"
],
"Title": "pyCMD; a simple shell to run math and Python commands"
}
|
255820
|
<p>so here I am trying to get some reviews from my code, where I have to replicate the norwegian flag using flexbox.</p>
<p>First to be sayed is that my teachers told me to divide the flag in two sections, where I have had to insert two of the four squares in eachone, but I ignored this since with declarations like <code>align-content: space-between;</code> I could send the four squares right to the corners and play with margins to adjust them, that's why I just created 4 containers (white squares) with its respective item (red squares).</p>
<p>Before I show my code, I want to tell that it was so diffuicult to me to deal with the size of the elements, first a try to use <code>flex-basis: ;</code> and <code>flex-grow: ;</code> to automatically give size to the squares, but this does'nt work for me, so I have to use <code>width: ;</code> and <code>height: ;</code>.</p>
<p>Due to all this I want to get reccomendations to improve my code or best alternatives to reach the objective and then a kind of explanation about the size of elements.</p>
<p>Here's the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
background-color: #00205B;
margin: 0;
display: flex;
flex-wrap: wrap;
align-content: space-between;
}
.white-square1, .white-square2, .white-square3, .white-square4{
background-color: #ffffff;
display: flex;
align-content: flex-start;
justify-content: space-between;
align-items: flex-start;
}
.white-square1, .white-square3{
margin: 0 50px 50px 0;
height: 43.8vh;
width: 25vw;
flex-grow: 1;
}
.white-square2, .white-square4{
margin: 0 0 50px 50px;
height: 43.8vh;
width: 50vw;
flex-grow: 2;
}
.white-square3{
margin: 50px 50px 0 0;
align-items: flex-end;
}
.white-square4{
margin: 50px 0 0 50px;
align-items: flex-end;
}
.red-square1, .red-square2, .red-square3, .red-square4{
background-color: #BA0C2F;
}
.red-square1, .red-square3{
margin: 0 50px 50px 0;
height: 37.8vh;
width: 25vw;
flex-grow: 1;
margin-left: 0;
}
.red-square2, .red-square4{
margin: 0 0 50px 50px;
height: 37.8vh;
width: 50vw;
flex-grow: 2;
margin-right: 0;
}
.red-square3{
margin: 50px 50px 0 0;
align-items: flex-end;
}
.red-square4{
margin: 50px 0 0 50px;
align-items: flex-end;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Flexbox Actividad 3</title>
</head>
<body>
<section class="white-square1">
<div class="red-square1"></div>
</section>
<section class="white-square2">
<div class="red-square2"></div>
</section>
<section class="white-square3">
<div class="red-square3"></div>
</section>
<section class="white-square4">
<div class="red-square4"></div>
</section>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h3>Quick implementation idea</h3>\n<p>Create a container <code>div</code> with two <code>div</code>s inside. Position those <code>div</code>s as a cross lust like in the Norwegian flag. After that give those <code>div</code>s a thick white border and the flag's red color would be simply the container <code>div</code>'s <code>background-color</code>.</p>\n<h3>Code review</h3>\n<ul>\n<li><code>Section</code>s are not an <code>appropriate</code> HTML element in this case. Use <code>div</code>'s instead.</li>\n<li>Do not style using <code>html</code> tags like <code>body</code>. Use CSS classes instead. Read about the <code>css specificity</code></li>\n<li><code>.red-square2, .red-square4{</code> this selector has both <code>margin</code> and <code>margin-righ</code> properties at once. <code>margin: a b c d</code> should be enough.</li>\n<li>Tidy up your CSS. In one line You style <code>.red-square3</code> and some lines below You style the same element. Why? Can't you use one CSS rule for that? :)</li>\n</ul>\n<h3>Improvement ideas</h3>\n<ul>\n<li>Move the CSS color to variables and place them in a separate file.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T23:38:47.053",
"Id": "504905",
"Score": "0",
"body": "I'll try your quick implementation idea, I did't think about it and sounds interesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T23:45:41.333",
"Id": "504907",
"Score": "0",
"body": "I'll try your quick implementation idea, I did't think about it and sounds interesting.\n\nAbout [CODE REVIEW]: \nWhere do I could read about how to use properly the semanthic tags? I´m reading HTML & CSS by Jon Duckett and don´t remember such recomendation, and actually it's kind of confusing how to use the other semanthic tags.\n\nSo it's better to add a class to the body tag and add style to that class instead to the body tag?\n\nI did't notice that, thx.\n\nIt's because first, I add declarations in general and then modify values according to my needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T18:42:28.010",
"Id": "504993",
"Score": "1",
"body": "By definition, section is the wrapping element that should begin with some kind of a heading <h1> etc..\n\n`The <section> element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content. Each section should be identified, typically by including a heading (h1-h6 element) as a child of the <section> element.`\n\nsource: https://html.spec.whatwg.org/multipage/sections.html#the-section-element"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T18:43:50.837",
"Id": "504994",
"Score": "0",
"body": "If my response was helpful - consider marking it as resolved :) Have a nice day"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T21:17:59.750",
"Id": "505010",
"Score": "1",
"body": "On Code Review, it's customary to wait a couple of days before handing out checkmarks. Don't sweat it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T19:12:09.470",
"Id": "505088",
"Score": "0",
"body": "THX Adam, I was waiting for new responses, but your answer was so helpful for me, so I marked as resolved, thanks for your time. <3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T19:17:57.487",
"Id": "505089",
"Score": "0",
"body": "Non problemo :) Always happy to help. Have a nice day and weekend :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T22:32:55.270",
"Id": "255828",
"ParentId": "255823",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "255828",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T20:08:17.570",
"Id": "255823",
"Score": "4",
"Tags": [
"css"
],
"Title": "Replicating the norwegian flag using CSS"
}
|
255823
|
<p>I had to write a TicTacToe game as an assignment for class & the last program I wrote used a few continues here and there. When I asked for a peer code-review I was informed that I should use additional variables rather than continue and break for my use-case. Did I make the same mistake in this code?</p>
<pre><code>import java.util.HashMap;
import java.util.Scanner;
public class TicTacToe {
public enum Box {
BAD_PLACEMENT(-2),
X(-1),
EMPTY(0),
O(1),
SOLVED(2),
RESET_GAME(3);
public int value;
@Override
public String toString() {
return Integer.toString(value);
}
public String asString() {
String rtn;
switch(value) {
case -1:
rtn = "X";
break;
case 0:
rtn = "-";
break;
case 1:
rtn = "O";
break;
default:
rtn = "Something has gone terribly wrong";
}
return rtn;
}
Box(int boxType){
this.value = boxType;
}
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
public static class Board {
// The referee will handle computing tictactoe solves
public class Referee {
Board currentBoard;
public Referee(Board b) {
this.currentBoard = b;
}
public Board getBoard() {
return this.currentBoard;
}
public Box checkSolveColumns() {
for (int x=0; x <= 2; x++) {
int currentSum = 0;
for(int y=0; y <= 2; y++)
currentSum+=getBoard().getBox(x, y).value;
if(currentSum == 3)
return Box.X;
if(currentSum == -3)
return Box.O;
}
return Box.EMPTY;
}
public Box checkSolveRows() {
for (int y=0; y <= 2; y++) {
int currentSum = 0;
for(int x=0; x <= 2; x++)
currentSum+=getBoard().getBox(x, y).value;
if(currentSum == 3)
return Box.X;
if(currentSum == -3)
return Box.O;
}
return Box.EMPTY;
}
public Box checkSolveDiagonals() {
int topLeftToBottomRightSum = 0;
int topRightToBottomLeftSum = 0;
// 0 1 2
topLeftToBottomRightSum+=getBoard().getBox(0, 0).value;// 0 [X][ ][ ]
topLeftToBottomRightSum+=getBoard().getBox(1, 1).value;// 1 [ ][X][ ]
topLeftToBottomRightSum+=getBoard().getBox(2, 2).value;// 2 [ ][ ][X]
// 0 1 2
topRightToBottomLeftSum+=getBoard().getBox(2, 0).value;// 0 [ ][ ][X]
topRightToBottomLeftSum+=getBoard().getBox(1, 1).value;// 1 [ ][X][ ]
topRightToBottomLeftSum+=getBoard().getBox(0, 2).value;// 2 [X][ ][ ]
if(topLeftToBottomRightSum == 3 || topRightToBottomLeftSum == 3)
return Box.X;
if(topLeftToBottomRightSum == -3 || topRightToBottomLeftSum == -3)
return Box.O;
return Box.EMPTY;
}
public Box checkSolve() {
if(isFull())
return Box.SOLVED;
// Observe this is "checked" not "check" > NAMING CONVENTIONS ROCK!!!
Box checkedSolveRows = checkSolveRows();
Box checkedSolveColumns = checkSolveColumns();
Box checkedSolveDiagonals = checkSolveDiagonals();
// return whatever guy won
if(checkedSolveRows != Box.EMPTY) {
return checkedSolveRows;}
if(checkedSolveColumns != Box.EMPTY) {
return checkedSolveColumns;}
if(checkedSolveDiagonals != Box.EMPTY) {
return checkedSolveDiagonals;}
// fall back to an empty return
return Box.EMPTY;
}
}
Referee referee;
public Box boardInternal[][];
public Board() {
this.referee = new Referee(this);
this.boardInternal = new Box[3][3];
for(int x=0; x<=2; x++) {
for(int y=0; y<=2; y++) {
this.boardInternal[x][y] = Box.EMPTY; // initialize every slot with an empty box
}
}
/* Ideally, this is our data structure for the boxes
*
* [EMPTY][EMPTY][EMTPY]
* [EMPTY][EMPTY][EMTPY]
* [EMPTY][EMPTY][EMTPY]
*/
}
public Box getBox(int x, int y) {
if(x > 2 || y > 2 || x < 0 || y < 0)
return Box.BAD_PLACEMENT;
return this.boardInternal[x][y];
}
public boolean isFull() {
// neat trick i picked up from lua to check a boolean in a return method
for(int x=0; x<=2; x++) {
for(int y=0; y<=2; y++) {
if(getBox(x, y)==Box.EMPTY)
return false;
}
}
return true;
}
public void resetGame() {
// Reset the board c:
this.referee = new Referee(this);
this.boardInternal = new Box[3][3];
for(int x=0; x<=2; x++) {
for(int y=0; y<=2; y++) {
this.boardInternal[x][y] = Box.EMPTY; // initialize every slot with an empty box
}
}
System.out.println("*** Game reset ***");
System.out.println("*** Welcome to TicTacToe! ***");
System.out.println("*** Type RESET to restart! ***");
System.out.println("*** Type QUIT to exit! ***");
}
public Box setBox(int x, int y, Box player) {
if(this.referee.checkSolve() == Box.SOLVED || player==Box.RESET_GAME) { resetGame(); return Box.RESET_GAME;} // board is already solved
Box currentBox = getBox(x, y); // get the current value of the box
Box rtn = null;
switch(currentBox) {
case EMPTY: // if the box is empty, we fill it with the player requesting the area
this.boardInternal[x][y] = player; // set the field
rtn = this.referee.checkSolve();
break; // break out of our switch
case BAD_PLACEMENT:
System.out.println("That is a invalid placement option!");
rtn = Box.BAD_PLACEMENT;
break;
default: // if the box is not EMPTY, we need to throw a invalid placement exception to notify the caller
System.out.println("That box is filled option!");
rtn = Box.BAD_PLACEMENT;
}
System.out.println(this.toString());
return rtn;
}
public String toString() {
StringBuilder boxResult = new StringBuilder(); // save the memories! (bad save the trees pun)
boxResult.append(String.format("\n 1 2 3\nA [%s][%s][%s]\nB [%s][%s][%s]\nC [%s][%s][%s]\n",
this.boardInternal[0][0].asString(),
this.boardInternal[0][1].asString(),
this.boardInternal[0][2].asString(),
this.boardInternal[1][0].asString(),
this.boardInternal[1][1].asString(),
this.boardInternal[1][2].asString(),
this.boardInternal[2][0].asString(),
this.boardInternal[2][1].asString(),
this.boardInternal[2][2].asString()
));
return boxResult.toString();
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Board ourBoard = new Board();
HashMap<String, Box> Players = new HashMap<String, Box>();
Players.put("Player1", Box.X);
Players.put("Player2", Box.O);
String currentPlayer = "Player1";
System.out.println("*** Welcome to TicTacToe! ***");
System.out.println("*** Type RESET to restart! ***");
System.out.println("*** Type QUIT to exit! ***");
System.out.println(ourBoard.toString());
do {
System.out.printf("Your move, %s: ",currentPlayer);
String desiredInput = keyboard.next();
Box inputResult = null;
if(desiredInput.toLowerCase().equals("quit")) // quit the program immediately
break;
if(desiredInput.toLowerCase().equals("reset")) // reset the game
inputResult = ourBoard.setBox(0, 0, Box.RESET_GAME);
else if(desiredInput != null) {
// we got an input let's see where we're going with this
if(desiredInput.length() != 2) {
// wrong answer buddy
System.out.printf("Hey, %s! Please enter your format in the format of \"LetterNumber\". ex. A2%n%s is in the wrong format!%n",
currentPlayer,
desiredInput);
continue;
} else {
// this is probably the correct format... let's check
char columnPicked = desiredInput.toLowerCase().charAt(0);
String rowPicked = desiredInput.split("")[1]; // get the 2 characters input
if(isInteger(rowPicked)) {
int decidedRow = Integer.parseInt(rowPicked);
decidedRow--;
switch(columnPicked) {
case 'a':
inputResult = ourBoard.setBox(0, decidedRow, Players.get(currentPlayer));
break;
case 'b':
inputResult = ourBoard.setBox(1, decidedRow, Players.get(currentPlayer));
break;
case 'c':
inputResult = ourBoard.setBox(2, decidedRow, Players.get(currentPlayer));
break;
default:
System.out.println("Could not decipher your column (A,B,C allowed.)");
continue;
}
} else {
System.out.println("Could not decipher your row (Only numbers allowed)");
continue;
}
}
}
// do a reset check here
switch(inputResult) {
case X:
System.out.println("Player 2 wins!"); // player2 win
currentPlayer = "Player1";
ourBoard.resetGame();
break;
case O:
System.out.println("Player 1 wins!"); // player1 win
currentPlayer = "Player1";
ourBoard.resetGame();
break;
case RESET_GAME:
System.out.printf("%n%s requested a reset for the previous game. Bad sport!%n", currentPlayer);
currentPlayer = "Player1";
break;
case BAD_PLACEMENT:
// nothing to really handle here but we should catch every possible outcome
break;
case SOLVED: // this doesn't mean solved, it's a draw
System.out.println("Draw game! Better luck next time!");
currentPlayer = "Player1";
ourBoard.resetGame();
break;
case EMPTY:
// give each player a turn
if(currentPlayer.equals("Player1"))
currentPlayer = "Player2";
else
currentPlayer = "Player1";
break;
default:
System.out.println("Something went wrong!");
System.out.println("RESULT: "+inputResult);
}
} while(true);
keyboard.close();
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>There are different opinions on this:</p>\n<blockquote>\n<pre><code> public String asString() {\n String rtn;\n switch(value) {\n case -1:\n rtn = "X";\n break;\n case 0:\n rtn = "-";\n break;\n case 1:\n rtn = "O";\n break;\n default:\n rtn = "Something has gone terribly wrong";\n }\n return rtn;\n }\n</code></pre>\n</blockquote>\n<p>There are some who say that a function should have a single exit point, and this is what you have done. That makes a lot of sense in languages like C, where you have to clean up your resources before you exit, but Java does that automatically. So I prefer the other approach - return as soon as the work is complete:</p>\n<pre><code> public String asString() {\n switch(value) {\n case -1: return "X";\n case 0: return "-";\n case 1: return "O";\n default:\n throw new IllegalStateException();\n }\n }\n</code></pre>\n<p>I've modified so that it always returns a 1-character string, and throws an exception in the invalid case (but see the caution about <code>toString()</code> calling this: <a href=\"//stackoverflow.com/a/42011744/4850040\">overriding Object's toString() method, but I have to throw exceptions</a>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:49:21.307",
"Id": "504966",
"Score": "0",
"body": "Thank you for the suggestion, I am new to Java so any tricks like this to minify my code helps a lot. I will take this into consideration!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T07:59:58.217",
"Id": "255836",
"ParentId": "255832",
"Score": "2"
}
},
{
"body": "<p>Your formatting is off at some places, use an automatic code formatter.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> BAD_PLACEMENT(-2),\n X(-1), \n EMPTY(0), \n O(1),\n SOLVED(2),\n RESET_GAME(3);\n</code></pre>\n<p>You're mixing state of a single box, global game-state and state of input. Ideally you wouldn't.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> @Override\n public String toString() {\n return Integer.toString(value);\n }\n</code></pre>\n<p>I'd keep the default <code>toString</code>, because that is what all debuggers will default to when you debug the application. Also, you theoretically constantly convert the value, it would be better to store the wanted value to begin with as a field on the enum itself (as you do with <code>value</code>).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public String asString() {\n String rtn;\n switch(value) {\n case -1:\n rtn = "X";\n break;\n case 0:\n rtn = "-";\n break;\n case 1:\n rtn = "O";\n break;\n default:\n rtn = "Something has gone terribly wrong";\n }\n return rtn;\n }\n</code></pre>\n<p>You can remove this whole logic if you just store this representation as an additional field on the <code>enum</code> itself.</p>\n<p>Also the name <code>asString</code> is rather poor, <code>getPlaySymbol</code> would be better.</p>\n<p>Also you can directly return the value. I know, that there's the style of having only one exit. However, keeping this style would only be interesting if you need to do some cleanup afterwards, and that is nearly never the case in Java (mostly in C). So improve readability by returning directly, because that will clear any question what is returned.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>Board currentBoard;\n</code></pre>\n<p>Why is this variable <code>package-private</code>?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public Referee(Board b) {\n</code></pre>\n<p>Don't shorten names just because you can. It makes the code harder to understand and maintain.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>return this.currentBoard;\n</code></pre>\n<p>Normally you'd only use <code>this</code> when there's need to differentiate between a local and class variable (which should only be in the constructor or a setter). But that's personal preference.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for(int y=0; y <= 2; y++)\n currentSum+=getBoard().getBox(x, y).value;\n</code></pre>\n<p>I'd advice to always use braces to define blocks/scopes to increase readability and decrease possibilities for mistakes.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if(this.referee.checkSolve() == Box.SOLVED || player==Box.RESET_GAME) { resetGame(); return Box.RESET_GAME;} // board is already solved\n</code></pre>\n<p>Having this on a single line is evil.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>HashMap<String, Box> Players = new HashMap<String, Box>();\n</code></pre>\n<p>Try to use the lowest common class or interface you can get away with to not bundle your logic by accident to specific implementations if not needed. In this case it would be <code>Map</code>.</p>\n<p>Also typo, should be <code>players</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>// wrong answer buddy\n</code></pre>\n<p>I might be old and grumpy, but if you ain't got something useful to say in the comments, don't type that comment. It's a waste of everyones time at the end of the day and it is infuriating to find comments like "lol" or "whoopsie oopsie" in a large code-base that you need to work on.</p>\n<hr />\n<p>Splitting the processing of the input logic into a few functions would help loosen up the main function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:41:18.523",
"Id": "255856",
"ParentId": "255832",
"Score": "3"
}
},
{
"body": "<p>I disagree wit the answer of @TobySpeight. Even in Java it is usefull to have a single exit out of your methods since it makes <em>refactorings</em> easier, especially if you want to split up methods that have grown into smaller ones.</p>\n<p>In addition I find your method <code>Box.asString()</code> inconsistent with the concept of Java <code>enum</code>s. You obviously already know that the <code>enum</code> values are <em>Objects</em> that you can configure via a <em>constructor</em>. You do that with the int-Value of the <code>Box</code>. So why don't you simply do the same for "translating" the int value to a String?</p>\n<p>If you did your enum <code>Box</code> would change to this:</p>\n<pre><code>public enum Box { \n\n BAD_PLACEMENT(-2,"Something has gone terribly wrong"),\n X(-1,"X"), \n EMPTY(0,"-"), \n O(1,"O"),\n SOLVED(2,"Something has gone terribly wrong"),\n RESET_GAME(3,"Something has gone terribly wrong");\n \n public int value;\n private final String representation;\n \n @Override\n public String toString() {\n return Integer.toString(value);\n }\n \n public String asString() {\n return representation;\n }\n \n Box(int boxType, String representation){\n this.value = boxType;\n this.representation = representation;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T12:30:35.223",
"Id": "256012",
"ParentId": "255832",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255836",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T00:30:01.573",
"Id": "255832",
"Score": "2",
"Tags": [
"java",
"tic-tac-toe",
"pointers"
],
"Title": "Tic-Tac-Toe game in Java"
}
|
255832
|
<p>So, I am using <code>Repository</code> pattern with Dapper and ADO.NET. I have my based DB infrastructure setup as follows:</p>
<pre><code>public class ConnectionFactory: IConnectionFactory
{
private readonly string dbConnectionString = Convert.ToString(ConfigurationManager.ConnectionStrings["MyDBConn"].ConnectionString);
private MySqlConnection _dbConnection;
public IDbConnection GetDBConnection
{
get
{
if(string.IsNullOrEmpty(dbConnectionString))
{
throw new ArgumentNullException("DB Connection string received a null argument!");
}
if (_dbConnection == null)
{
_dbConnection = new MySqlConnection(dbConnectionString);
}
if (_dbConnection.State != ConnectionState.Open)
{
_dbConnection.Open();
}
return _dbConnection;
}
}
public void CloseDBConnection()
{
if (_dbConnection != null && _dbConnection.State == ConnectionState.Open)
{
_dbConnection.Close();
}
}
}
</code></pre>
<p>And I have a <code>Repository</code> class that uses this infrastructure:</p>
<pre><code>public async Task<IEnumerable<UserInformation>> GetUserInformation()
{
IEnumerable<UserInformation> list;
string querystring = "SELECT * FROM users WHERE valid=1;";
try
{
list = await SqlMapper.QueryAsync<UserInformation>(_connectionFactory.GetDBConnection, querystring, param, commandType: CommandType.Text);
}
finally
{
_connectionFactory.CloseDBConnection();
}
return list;
}
</code></pre>
<p>For reading my <code>IReader</code> and converting to a dataset, I do the following:</p>
<pre><code>public async Task<DataSet> GetOrderDetails(int oid)
{
DataSet dataset = new DataSet();
string querystring = "select * from orders WHERE OrderId=@oid";
DynamicParameters param = new DynamicParameters();
param.Add("@oid", oid);
using (var list = await SqlMapper.ExecuteReaderAsync(_connectionFactory.GetDBConnection, querystring, param, commandType: CommandType.Text))
{
dataset = helper.ConvertDataReaderToDataSet(list);
}
return dataset;
}
</code></pre>
<p>Here <code>ConvertDataReaderToDataSet</code> is a method that only converts the <code>IReader</code> to a <code>Dataset</code>.</p>
<p>The problem that I having is that I am getting the following error after a while (from logs):</p>
<pre><code>2/10/2021 12:37:44 AM
Type: Exception
Error Message: error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Method Name: GetOrderDetails
</code></pre>
<p>I have researched this error and it suggests a memory leak. Can you guys help me identify what is the problem and review my DB infrastructure setup?</p>
<p>Edit: After a discussion, I have changed the implementation to this:</p>
<pre><code>public async Task<IEnumerable<UserInformation>> GetUserInformation()
{
IEnumerable<UserInformation> list;
string querystring = "SELECT * FROM users WHERE valid=1;";
using (var conn = new MySqlConnection(dbConnectionString))
{
list = await conn.QueryAsync<UserInformation>(querystring, commandType: CommandType.Text);
}
return list;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T12:16:34.600",
"Id": "504948",
"Score": "0",
"body": "Are you still getting the error message after the code edit? For future reference code review is for reviewing working code, a question containing code that is not working as expected should be possibly posted on stack overflow. If the code is now working as expected please remove the code that wasn't working and the error message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T12:35:04.180",
"Id": "504950",
"Score": "0",
"body": "@pacmaninbw This code is working. The question is about it's performance and better techniques on how it can be handled."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T12:58:07.983",
"Id": "504951",
"Score": "0",
"body": "`_dbConnectionString` is not a string. It's a connection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:20:09.613",
"Id": "504954",
"Score": "0",
"body": "@JesseC.Slicer Yes, I have made the required edit not to mislead readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T18:11:57.120",
"Id": "505269",
"Score": "0",
"body": "If you've changed `GetUserInformation`, and the broken version is not discussed in an answer, there is no reason to keep the broken version in the question."
}
] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>Why do you convert a <code>string</code> to a <code>string</code>: <code>Convert.ToString(ConfigurationManager.ConnectionStrings["MyDBConn"].ConnectionString);</code>? It's even called a Connection<strong>String</strong>.</p>\n</li>\n<li><p>Why do you use Dapper and then don't use it properly? Why return a <code>DataSet</code>? Why use <code>SqlMapper</code> and <code>DynamicParameters</code>? Why make life so hard for yourself when Dapper is making things so easy? Look at the homepage of <a href=\"https://dapper-tutorial.net/\" rel=\"noreferrer\">Dapper Tutorial and Documentation</a>:</p>\n<pre><code> using (var conn = new SqlConnection(connectionString))\n {\n var invoices = conn.Query<Invoice>(sql);\n }\n</code></pre>\n<p>That is all you need. No endless checking of the state of your connection, no opening and closing it yourself, no <code>try...finally</code> blocks which completely ignore any exception that might occur. Write the correct query and let Dapper map the results to your class.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T09:15:11.097",
"Id": "504938",
"Score": "0",
"body": "Thanks, I will make a note of this. So basically you are saying the current DB infrastructure has problems? If you could point where, that would be great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T11:19:25.820",
"Id": "504941",
"Score": "0",
"body": "@RahulSharma My main problem is that you seem to apply an outdated ADO.NET style code to Dapper. Whereas Dapper should (IMHO) be used is a quite simple way, as per the example. The whole GetDBConnection / CloseDBConnection is pointless, just use `using` (which you actually do in one of your methods!). Checking whether a connection string isn't null on every call is pointless. Should you `try...catch` possible exceptions when executing a query? Possibly, but that depends on your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T11:23:07.897",
"Id": "504942",
"Score": "0",
"body": "Also, encapsulating a db connection in a `using` statement also properly disposes of the connection, which most of your code doesn't. See https://stackoverflow.com/a/17168919/648075 ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T07:20:31.187",
"Id": "505108",
"Score": "0",
"body": "@RahulSharma Please stop reposting your comment. Whether your code now works is something only you can tell. I don't know how `SqlMapper` works and whether it properly disposes of a connection (but I assume it doesn't), so my advice should be applied everywhere you use a db connection. But you wouldn't have those issues if you'd use Dapper the \"proper\" (i.e. simplest) way (e.g. I have never passed the `commandType` parameter in Dapper calls)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T08:34:39.740",
"Id": "255837",
"ParentId": "255835",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "255837",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T06:17:12.673",
"Id": "255835",
"Score": "0",
"Tags": [
"c#",
"mysql",
"asp.net",
"async-await",
"dapper"
],
"Title": "Is this correct way to setup DB Infrastructure with repository pattern and Dapper"
}
|
255835
|
<p>I've used this code to make some inputs checks. On any failed check, I need to ask again for proper input. I used <code>labels</code> and <code>goto</code> to achieve this, which they seem to be disliked by programmers as a concept.</p>
<p>How could I achieve the same effect without labels/goto? I considered putting all this code in a function and calling itself from inside, but it repeated only once for some reason - didn't keep asking if kept getting wrong answers.</p>
<pre class="lang-golang prettyprint-override"><code>// 0 exits
var f float64
var n int
startGame := func() {
reception:
fmt.Println()
fmt.Print(`Give number (1-9): `)
_, err := fmt.Scan(&f)
// check letters or symbols
if err != nil {
fmt.Println("Letters or symbols not accepted")
goto reception
}
// exit
if f == 0 {
os.Exit(0)
}
// check for integers only
if f < 1 || f > 9 || f-math.Ceil(f) != 0 {
fmt.Println("Only integer numbers between 1-9 are accepted")
goto reception
}
n = int(f)
// check for empty cells
if myArray[n-1] == false {
fmt.Println("Empty cell", n)
goto reception
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>for {}</code> (for loop without condition) loops forever until <code>break</code>.</p>\n<ol>\n<li>Put the contents of the function in a <code>for {}</code>.</li>\n<li>Remove the label and replace <code>goto reception</code> with <code>continue</code>. This will cause the current iteration of the loop to end and execution will continue with another iteration, starting from the top of the block.</li>\n<li>Use <code>break</code> at the end to exit the for loop</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:12:26.677",
"Id": "256595",
"ParentId": "255840",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T11:34:49.310",
"Id": "255840",
"Score": "2",
"Tags": [
"go"
],
"Title": "Multiple input checks, repeat if conditions are not met"
}
|
255840
|
<p>I tried to create REST API in PHP because I would like to learn the basics before I will start use frameworks to create apps. I created a Model with CRUD methods which can be used in every model to avoid repeating code. Class Model will be inherited by classes like Product, Measurement etc. I want to create diet application for android and web app. I tried to separate backend from front and mobile app but because im newbie tried to use clean PHP instead using frameworks.
I wonder is that a good way because when I was looking where crud methods should be placed (in model or controller) I saw a lot of answers in both ways.
My model looks like:</p>
<pre><code><?php
class Model
{
protected $connection;
protected $tableName;
/**
* Model constructor.
* @param $connection
*/
public function __construct($connection)
{
$this->connection = $connection;
}
public function read($id)
{
$sql = "SELECT * FROM `$this->tableName` WHERE id = ?";
$stmt = $this->connection->prepare($sql);
$stmt->execute([$id]);
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return json_encode($result);
}
public function create($data)
{
$params = [];
$values = "";
foreach ($data as $key => $value) {
$params[] = $key;
$values .= "'$value',";
}
$params = implode(",", $params);
$values = rtrim($values, ",");
$sql = "INSERT INTO $this->tableName ($params) VALUES ($values)";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
return json_encode("Record created");
}
public function readAll()
{
$sql = "SELECT * FROM " . $this->tableName;
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return json_encode($result);
}
public function update($data, $id)
{
$set = "";
foreach ($data as $key => $value) {
$set .= $key . '=' . '"' . $value . '",';
}
$set = rtrim($set, " ,");
$sql = "UPDATE $this->tableName SET $set WHERE id = $id";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
return json_encode("Record updated");
}
public function delete($id)
{
$sql = "DELETE FROM `$this->tableName` WHERE id = ?";
$stmt = $this->connection->prepare($sql);
$stmt->execute([$id]);
return json_encode("Record deleted");
}
}
</code></pre>
<p>And then I extend Model for example Product like below:</p>
<pre><code><?php
include_once 'Model.php';
class Product extends Model
{
protected $tableName = 'products';
}
</code></pre>
<p>My controllers are currently empty. I dont know where add methods to validate data. I was watching tutorials and their way to print json data was creating url like /api/product/read.php and they created all methods in that way. But I think thats wrong way because if I understood well concept of rest api we should use http methods like get/post etc instead using another urls to every method. Then I created a directory api and added file products.php. In that file created switch to handle http methods and use proper methods that are inherited from Model class and I dont need to rewrite that methods for every model.</p>
<pre><code> <?php
include_once '../../bootstrap.php';
include_once '../model/Measurement.php';
include_once '../config/DatabaseConnector.php';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$url = $_SERVER['REQUEST_URI'];
$urls = explode('/', $url);
$id = end($urls);
$connection = new DatabaseConnector();
$products = new Product($connection->getConnection());
$input = (array) json_decode(file_get_contents('php://input'), TRUE);
switch ($_SERVER['REQUEST_METHOD']){
case 'GET': if ($id !== "products.php")
print_r($products->read($id));
else
print_r($products->readAll());
break;
case 'POST': print_r($products->create($input));
break;
case 'PUT': print_r($products->update($input, $id));
break;
case 'DELETE': print_r($products->delete($id));
break;
}
</code></pre>
<p>I will be extremally thankful if someone will rate my code, points out my mistakes and give me an example where to create validate methods. Thank you so much, have a good day!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:29:25.980",
"Id": "504958",
"Score": "0",
"body": "Welcome to Code Review! Please [edit] your question so that the title and body describe the real-world *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:30:16.710",
"Id": "504959",
"Score": "0",
"body": "You probably also want to tell us a bit about the schema of the database tables you're using, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:31:15.350",
"Id": "504960",
"Score": "0",
"body": "@TobySpeight the idea of this code is to be database schema agnostic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:34:44.820",
"Id": "504961",
"Score": "0",
"body": "Ah, so it's a library for other code to use with different data? I saw queries including `WHERE id = ?`, so that imposes at least one constraint on the data schema. Anyway a library makes sense for a review; can you update the title/description to explain that? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:38:05.517",
"Id": "504962",
"Score": "0",
"body": "Yes, I will explain what I want to achive with that code. Sorry that I didnt that at start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:49:20.170",
"Id": "504965",
"Score": "0",
"body": "Added explanation about project, I hope that I did that well and everyone will understand what I want to achive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T21:13:46.243",
"Id": "506089",
"Score": "0",
"body": "Should probably use paramaterized queries"
}
] |
[
{
"body": "<p>The idea is very good and the structure is correct. Do not listen to anyone who would say that a crud method should be implemented in the controller. All the controller's job is to get the input and to call the CRUD method from the model. So in this regard your code is all right.</p>\n<p>However, your model code suffers from the opposite mix-up: it shouldn't format the output. That's the controller's job. Do not return any status from your CRUD methods. Your CRUD methods should only return a raw data when applicable and let the controller to format the output.</p>\n<p>But you are overlooking a very serious vulnerability here - <strong>an SQL injection</strong>.</p>\n<p>You should really learn about this matter, it's a very critical issue. Nobody cares how clean or efficient your code is if it imposes a critical threat to the whole application.</p>\n<p>To mitigate this issue you should look into <em>two</em> places</p>\n<ul>\n<li>use the real protection instead of <a href=\"https://phpdelusions.net/pdo/cargo_cult_prepared_statement\" rel=\"nofollow noreferrer\">cargo cult prepared statements</a></li>\n<li>besides the table name, throw in a class property with a<strong>list of columns in the table</strong>, and add the field names to the SQL strictly from this list only.</li>\n</ul>\n<p>For the actual implementation you can look into similar <a href=\"https://codereview.stackexchange.com/questions/253882/a-lightweight-crud-based-on-the-table-data-gateway-pattern\">CRUD implementation I posted recently</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:57:05.263",
"Id": "504968",
"Score": "0",
"body": "Thank you. I created protected fields in class to handle column names but after a while I deleted that because I stated that I dont need that. Now I see that I should make that in first way. I heard about SQL injection but never tried to avoid that vulnerability. I will rewrite that to remove issues. Thank you so much, your answer was really helpful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:43:12.483",
"Id": "255844",
"ParentId": "255842",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255844",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:15:22.523",
"Id": "255842",
"Score": "2",
"Tags": [
"php"
],
"Title": "REST API in clean PHP"
}
|
255842
|
<p>Given the below code is there a way to eliminate the <code>else</code> clause from the below method?
In my workplace <code>else</code> clause is considered evil because it somehow decreases the readability of the code.</p>
<pre><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {
boolean isDateRangeValid = true;
final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);
if(requestContainsCustomDate || sessionContainsCustomDate(session)) {
if(requestContainsCustomDate) {
if(!isDateRangeValid(startDateFromParam, endDateFromParam)) {
isDateRangeValid = false;
startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();
endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();
}
} else {
startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();
endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();
}
setSessionAttributes(startDateFromParam, endDateFromParam, session);
}
return isDateRangeValid;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T16:48:25.153",
"Id": "504980",
"Score": "1",
"body": "While you have 3 answers, I would like to suggest that you read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) so that you can get some points on this site. The title of the question should indicate what the code does rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:28:34.263",
"Id": "505045",
"Score": "1",
"body": "I get the feeling that your workplace is trying to fight *cyclomatic complexity* by banning else statements but not realizing that this leads to incredible increase in *cognitive complexity*. You could read into these and try to educate your coworkers. There are static code analysis tools that can be used for measuring these within the build process and you should use them instead of making blanket bans on normal programming structures. https://en.wikipedia.org/wiki/Cyclomatic_complexity https://en.wikipedia.org/wiki/Cognitive_complexity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:34:35.857",
"Id": "505046",
"Score": "1",
"body": "And in case some of your coworkers read this: banning else statements is *not normal*. If that came up in a job interview I would prefer to choose another place to work."
}
] |
[
{
"body": "<p>"Else is evil"? That's a very peculiar point of view!</p>\n<p>But if you really want to avoid it, you can look at early return, provided that isn't also regarded as evil - some people are very firm on the "single entry, single exit" principle.</p>\n<p>Gilbert Le Blanc's code takes a similar approach to me, but in avoiding early return, he risks duplicated code execution, which may not be a problem here, but worries me a little.</p>\n<p>The code below is not checked in any detail, but shows the idea, though it does duplicate code.</p>\n<pre><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n\n if (requestContainsCustomDate(startDateFromParam, endDateFromParam)) {\n boolean isDateRangeValid = isDateRangeValid(startDateFromParam, endDateFromParam);\n if (!isDateRangeValid) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n return isDateRangeValid;\n }\n\n if (sessionContainsCustomDate(session)) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n }\n\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T16:09:11.653",
"Id": "504976",
"Score": "0",
"body": "I'm not sure I like the method in general. Its functionality seems more than a little messy, but without any background I'm not sure what can be done with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:00:07.057",
"Id": "504982",
"Score": "0",
"body": "Agreed with your comment, the above is bad code because it uses output parameters; it is a chunk of code extracted from a method that is around 1000 lines long and I can't do much about it as it would require me to refactor the entire method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T16:01:22.953",
"Id": "255851",
"ParentId": "255848",
"Score": "4"
}
},
{
"body": "<p>If I read correctly, the flow is:</p>\n<pre><code>if(A || B)\n{\n if(A)\n {\n if(C)\n {\n ...\n }\n }\n else\n {\n ...\n }\n}\n</code></pre>\n<p>Which is equivalent to:</p>\n<pre><code>if(A)\n{\n b = true\n if(C)\n {\n ...\n b = false\n }\n ...\n return b;\n}\nif(B)\n{\n ...\n}\nreturn true\n</code></pre>\n<p>So, in essence getting rid of the else can be done like this:</p>\n<pre><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);\n\n if(requestContainsCustomDate) {\n boolean isDateRangeValidResult = true;\n\n if(!isDateRangeValid(startDateFromParam, endDateFromParam)) {\n isDateRangeValidResult = false;\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n\n return isDateRangeValidResult;\n }\n\n if(sessionContainsCustomDate(session))\n {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n \n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n }\n\n return true;\n}\n</code></pre>\n<p>If I didn't had to follow some company view about the readability of a statement, I would write instead:</p>\n<pre><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n boolean isDateRangeValidResult = true;\n final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);\n\n if(requestContainsCustomDate) {\n if(!isDateRangeValid(startDateFromParam, endDateFromParam)) {\n isDateRangeValidResult = false;\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n setSessionAttributes(startDateFromParam, endDateFromParam, session); \n }\n else if(sessionContainsCustomDate(session))\n {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n setSessionAttributes(startDateFromParam, endDateFromParam, session); \n }\n\n return isDateRangeValidResult;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T16:12:06.357",
"Id": "504977",
"Score": "2",
"body": "Your second example calls setSessionAttributes under conditions where the original would not have done. This may or may not be acceptable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T16:15:54.450",
"Id": "504978",
"Score": "0",
"body": "You are right. I'm fixing it. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T16:09:29.337",
"Id": "255852",
"ParentId": "255848",
"Score": "2"
}
},
{
"body": "<p>TLDR, the code could be refactored as below. There are several things that can be improved, so please have a look at my comments at the bottom.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean validateAndSetDateRelatedSessionAttributes(String startDate, String endDate, HttpSession session) throws ParseException {\n final boolean isCustomDateIncludedInRequest = isCustomDateIncludedInRequest(startDate, endDate);\n\n boolean isCustomDateIncludedInRequestOrSession = isCustomDateIncludedInRequest || isCustomDateIncludedInSession(session);\n if (!isCustomDateIncludedInRequestOrSession) {\n return true;\n }\n\n boolean isDateRangeValid = isDateRangeValid(startDate, endDate);\n boolean shouldDefaultDatesBeAddedToTheSession = !isCustomDateIncludedInRequest || !isDateRangeValid;\n if (shouldDefaultDatesBeAddedToTheSession) {\n startDate = getDefaultStartDate(session);\n endDate = getDefaultEndDate(session);\n }\n\n setSessionAttributes(startDate, endDate, session);\n return isCustomDateIncludedInRequest ? isDateRangeValid : true;\n }\n\n private String getDefaultEndDate(HttpSession session) {\n return session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n\n private String getDefaultStartDate(HttpSession session) {\n return session.getAttribute(BACalendarConstant.START_DATE).toString();\n }\n</code></pre>\n<p><strong>Step by step refactoring and the reasoning behind each change</strong></p>\n<p>This is the original code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n boolean isDateRangeValid = true;\n final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);\n\n if(requestContainsCustomDate || sessionContainsCustomDate(session)) {\n if(requestContainsCustomDate) {\n if(!isDateRangeValid(startDateFromParam, endDateFromParam)) {\n isDateRangeValid = false;\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n } else {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n }\n return isDateRangeValid;\n}\n</code></pre>\n<p>The code is indeed quite difficult to read, with code duplication and nested ifs. It is not about that single else that you are referring to, but there is a range of things that can be done to make the code cleaner and concise.</p>\n<p>When the whole body of the function is executed when a condition is true, which seems to be the case here, you can return early. Please have a look at <a href=\"https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">Replacing Nested Conditional with Guard Clauses</a> refactoring technique for more information.</p>\n<p>But before, let us first simplify the condition of the first if, using the <a href=\"https://refactoring.guru/extract-variable\" rel=\"nofollow noreferrer\">Extract Conditional</a> refactoring technique as below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n boolean isDateRangeValid = true;\n final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);\n\n boolean isCustomDateIncludedInRequestOrSession = requestContainsCustomDate || sessionContainsCustomDate(session);\n if(isCustomDateIncludedInRequestOrSession) {\n if(requestContainsCustomDate) {\n if(!isDateRangeValid(startDateFromParam, endDateFromParam)) {\n isDateRangeValid = false;\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n } else {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n }\n return isDateRangeValid;\n}\n</code></pre>\n<p>Following that, we put the guard clause in place. We automatically remove one level of the <code>if</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n boolean isDateRangeValid = true;\n final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);\n\n boolean isCustomDateIncludedInRequestOrSession = requestContainsCustomDate || sessionContainsCustomDate(session);\n if (!isCustomDateIncludedInRequestOrSession) {\n return true;\n }\n if (requestContainsCustomDate) {\n if (!isDateRangeValid(startDateFromParam, endDateFromParam)) {\n isDateRangeValid = false;\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n } else {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n return isDateRangeValid;\n}\n</code></pre>\n<p>I can then see that you have a boolean variable called <code>isDateRangeValid</code> which is set to true in the beginning of the method. Then, in the inner <code>if</code> you do the following:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!isDateRangeValid(startDateFromParam, endDateFromParam)) {\n isDateRangeValid = false;\n ///...\n}\n</code></pre>\n<p>That can be replaced as below. I have also moved the <code>isDateRangeValid</code> closer to where it is used.</p>\n<pre class=\"lang-java prettyprint-override\"><code>boolean isDateRangeValid = true;\nif (requestContainsCustomDate) {\n isDateRangeValid = isDateRangeValid(startDateFromParam, endDateFromParam);\n if (!isDateRangeValid) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n} \n//...\n</code></pre>\n<p>If we replace the value of <code>isDateRangeValid</code> with the actual call, it becomes as below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>//...\nboolean isDateRangeValid = isDateRangeValid(startDateFromParam, endDateFromParam);\nif (requestContainsCustomDate) {\n if (!isDateRangeValid) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n} else {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n}\n\nsetSessionAttributes(startDateFromParam, endDateFromParam, session);\nreturn requestContainsCustomDate ? isDateRangeValid : true; // The change has been reflected here as well.\n</code></pre>\n<p>Here, it is easier to see the code duplication! The following part is repeated twice!</p>\n<pre class=\"lang-java prettyprint-override\"><code>startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\nendDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n</code></pre>\n<p>Thus, we can remove the duplication (and the <code>else</code>) by <em>enhancing the conditional</em> as below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {\n final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);\n\n boolean isCustomDateIncludedInRequestOrSession = requestContainsCustomDate || sessionContainsCustomDate(session);\n if (!isCustomDateIncludedInRequestOrSession) {\n return true;\n }\n\n boolean isDateRangeValid = isDateRangeValid(startDateFromParam, endDateFromParam);\n if (!requestContainsCustomDate || (requestContainsCustomDate && !isDateRangeValid)) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n }\n\n setSessionAttributes(startDateFromParam, endDateFromParam, session);\n return requestContainsCustomDate ? isDateRangeValid : true;\n}\n</code></pre>\n<p><strong>Bonus section</strong>:</p>\n<p>Based on <em><a href=\"https://en.wikipedia.org/wiki/Propositional_calculus\" rel=\"nofollow noreferrer\">Propositional Logic</a></em>, the expression in the <code>if</code> can be simplified even more.</p>\n<p>This statement <code>(i)</code>:</p>\n<p><code>!requestContainsCustomDate || (requestContainsCustomDate && !isDateRangeValid)</code> i.e. <code>!p || (p && !q)</code></p>\n<p>And this statement <code>(ii)</code>:</p>\n<p><code>!requestContainsCustomDate || !isDateRangeValid</code> i.e. <code>!p || !q</code></p>\n<p><strong>are exactly the same</strong>!</p>\n<p>You can verify this argument by testing the two expressions in the <a href=\"https://web.stanford.edu/class/cs103/tools/truth-table-tool/\" rel=\"nofollow noreferrer\">Standford University truth table tool</a>.</p>\n<p><strong>Cool bonus statement</strong>: The results are exactly the same with this expression <code>(iii)</code> as well <code>!(requestContainsCustomDate && isDateRangeValid)</code> (<a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">De Morgan's Laws</a>).</p>\n<p>I am going to use expression <code>(ii)</code>:</p>\n<p><code>!requestContainsCustomDate || !isDateRangeValid</code></p>\n<p>Which is extremely clear since it translates as below! <strong>IF</strong> the user did not request a custom date OR of the dates requested are not valid, use the default dates.</p>\n<p>So, back to code. We make the replacement as below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>//...\n\nboolean isDateRangeValid = isDateRangeValid(startDateFromParam, endDateFromParam);\nif (!requestContainsCustomDate || !isDateRangeValid) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n}\n//...\n</code></pre>\n<p>And we can make our intentions more clear by extracting the condition into a variable called <code>shouldDefaultDatesBeAddedToSession</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>//...\nboolean shouldDefaultDatesBeAddedToSession = !requestContainsCustomDate || !isDateRangeValid;\nif (shouldDefaultDatesBeAddedToSession) {\n startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();\n endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();\n}\n//...\n</code></pre>\n<p>We are missing the surrounding methods (e.g. <code>setSessionAttributes</code> etc). I am sure that we could also make it even cleaner, since there are still code smells in the code.</p>\n<p><strong>Further improvements / concerns</strong>:</p>\n<ol>\n<li><p><em>Single Responsibility Principle</em>: This is my most important concern. This method does many things! A method should be responsible for one thing only (<a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>) and should do that very well. Please break it down to do less stuff! This brings us to the:</p>\n</li>\n<li><p><em><a href=\"https://en.wikipedia.org/wiki/Command%E2%80%93query_separation\" rel=\"nofollow noreferrer\">Command-Query Separation</a></em>. Strive to separate the methods that DO something and have side effects from the methods that RETURN something. Also, please have a look at the <a href=\"https://medium.com/better-programming/what-is-a-pure-function-3b4af9352f6f\" rel=\"nofollow noreferrer\">Pure Functions</a>.</p>\n</li>\n<li><p><em>Stick to naming conventions for better clarity</em>. Avoid naming your variables like <code>requestContainsCustomDate</code>. Please stick to the related Java naming conventions. An alternative naming could be <code>isCustomDatePresent</code>. Boolean methods should start with <code>is</code> or if it makes more sense with <code>has</code>, <code>can</code>, or <code>should</code>.</p>\n</li>\n<li><p><em>OOP</em>! I see a lot of methods in the code, that take objects as parameters, to perform actions on those objects. For example, if possible, add the setSessionAttributes to the session object (or a wrapper/decorator of it), rather than passing the session in a method AND changing that session. A method from your method that does this is <code>setSessionAttributes(startDateFromParam, endDateFromParam, session);</code></p>\n</li>\n<li><p>Avoid noise when naming stuff. For example, in the<code>startDateFromParam</code> and <code>endDateFromParam</code> function arguments, the <code>FromParam</code> is noise. You can change the variables to <code>startDate</code> and <code>endDate</code>.</p>\n</li>\n<li><p>Make your intentions clear / Name your intentions. One could argue otherwise, but you could extract strange or large statements to their own variables, so that you can make your intention clear. An example is the below:</p>\n</li>\n</ol>\n<p><code>String defaultStartDate = session.getAttribute(BACalendarConstant.START_DATE).toString();</code></p>\n<ol start=\"7\">\n<li><em>BUG</em>? What is the intention of the return value? Do you want to return true if the dates requested have been successfully set? The function does not do that, so I have a suspicion that the return values could be wrong.</li>\n</ol>\n<p>The method becomes:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean validateAndSetDateRelatedSessionAttributes(String startDate, String endDate, HttpSession session) throws ParseException {\n final boolean isCustomDateIncludedInRequest = isCustomDateIncludedInRequest(startDate, endDate);\n\n boolean isCustomDateIncludedInRequestOrSession = isCustomDateIncludedInRequest || isCustomDateIncludedInSession(session);\n if (!isCustomDateIncludedInRequestOrSession) {\n return true;\n }\n\n boolean isDateRangeValid = isDateRangeValid(startDate, endDate);\n boolean shouldDefaultDatesBeAddedToTheSession = !isCustomDateIncludedInRequest || !isDateRangeValid;\n if (shouldDefaultDatesBeAddedToTheSession) {\n startDate = getDefaultStartDate(session);\n endDate = getDefaultEndDate(session);\n }\n\n setSessionAttributes(startDate, endDate, session);\n return isCustomDateIncludedInRequest ? isDateRangeValid : true;\n}\n\nprivate String getDefaultEndDate(HttpSession session) {\n return session.getAttribute(BACalendarConstant.END_DATE).toString();\n}\n\nprivate String getDefaultStartDate(HttpSession session) {\n return session.getAttribute(BACalendarConstant.START_DATE).toString();\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T15:55:52.673",
"Id": "255894",
"ParentId": "255848",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255851",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T15:32:18.487",
"Id": "255848",
"Score": "0",
"Tags": [
"java"
],
"Title": "Refactor method by removing else condition"
}
|
255848
|
<p>As a beginner project, I've start working on this carousel slider that would slide through an image and a testimonial on click.</p>
<p>The number of images and content slides would always be the same number. I got the javascript to work but I feel like I'm repeating myself on some of my helper classes. I've tried to rework them so I could use some higher order function to achieve what I'm trying to do but I haven't had any luck. If anyone could review this or point me in the right direction that would be great.</p>
<p>JSFiddle Link here: <a href="https://jsfiddle.net/ej87pdsb/" rel="nofollow noreferrer">https://jsfiddle.net/ej87pdsb/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// CAROUSEL GALLERY
const carouselBtns = document.querySelectorAll(`[class*='arr-']`);
const carouselImages = Array.from(document.querySelectorAll('.carousel-images img'));
const carouselContent = Array.from(document.querySelectorAll('.carousel-content .carousel-content-item'));
let currentSlide = 0;
function activateSlider(e) {
if (e.target.classList.contains('arr-next')) {
arrNextBtn();
} else {
arrPrevBtn();
}
}
function arrNextBtn() {
if (currentSlide == carouselImages.length - 1) {
currentSlide = 0;
} else {
currentSlide++;
}
addRemoveHideClass();
}
function arrPrevBtn() {
if (currentSlide == 0) {
currentSlide = carouselImages.length - 1;
} else {
currentSlide--;
}
addRemoveHideClass();
}
function addRemoveHideClass() {
carouselImages.filter(function (img) {
if (img == foundImage()) {
img.classList.remove('hide');
} else {
img.classList.add('hide');
}
});
carouselContent.filter(function (content) {
if (content == foundContent()) {
content.classList.remove('hide');
} else {
content.classList.add('hide');
}
});
}
function foundImage() {
const imageMatch = carouselImages.find(function findMatchingImage(img, index) {
if (index == currentSlide) {
return img;
}
});
return imageMatch;
}
function foundContent() {
const contentMatch = carouselContent.find(function findMatchingContent(content, index) {
if (index == currentSlide) {
return content;
}
});
return contentMatch;
}
carouselBtns.forEach(function (btn) {
btn.addEventListener('click', activateSlider);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* RESET STUFF */
html {
box-sizing: border-box;
scroll-behavior: smooth;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
/** FLEX / POSITIONING ON MOBILE **/
.carousel {
display: flex;
flex-flow: column wrap;
align-items: flex-start;
}
/* Previous and Next Arrow Positioning */
.carousel-arrs [class*='arr-'] {
position: absolute;
top: 37%;
background: none;
border: none;
z-index: 9999;
}
.carousel-arrs .arr-prev {
left: -2%;
}
.carousel-arrs .arr-next {
right: -2%;
}
/** SETTING SCROLLING CONTENT INLINE, HIDDING OVERFLOWS AND SETTING HEIGHTS AND WIDTHS FOR MAIN CONTENT SECTIONS **/
.carousel-content,
.carousel-images {
display: inline-flex;
overflow: hidden;
width:100%;
}
.carousel-content {
height: 450px;
min-height: 100%;
}
.carousel-images img {
width: 100vw;
min-width: 100%;
height: 310px;
object-fit: cover;
border-radius: 0.25rem 0.25rem 0% 0%; /* Rem Values Taken from BS4 .rounded class*/
}
.carousel-content-item {
min-width: 100%;
padding: 50px 40px;
}
/** MOBILE / TYPOGRAPHY / PADDING / MARGINS STYLING **/
.carousel {
border-radius: .25rem!important;
background-color: rgb(255, 255, 255);
box-shadow: 0 50px 100px -20px rgba(50, 50, 93, 0.25),
0 30px 60px -30px rgba(0, 0, 0, 0.3),
inset 0 -2px 6px 0 rgba(10, 37, 64, 0.35);
}
.carousel-arrs [class*='arr-'] svg {
background-color: #fff;
border-radius: 50%;
color: #00aeef;
box-shadow: none;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.105);
transition: cubic-bezier(0.23, 1, 0.32, 1);
pointer-events: all;
}
.carousel-arrs [class*='arr-'] svg:hover {
color: #f4af38;
transform: translateY(-2px);
}
/* Transitions and Hide Class Styling */
.carousel-images img, .carousel-content .carousel-content-item {
transition: visibility 0s, opacity 0.3s ease-in;
}
.hide {
position: absolute;
opacity: 0;
visibility: hidden;
}
/** STYLE OVERRIDES FOR 768PX AND ABOVE **/
@media (min-width: 768px) {
/** FLEX / POSITIONING **/
.carousel {
flex-flow: row nowrap;
align-items: stretch;
overflow:hidden;
}
/* Previous and Next Arrow Positioning */
.carousel-arrs [class*='arr-'] {
top: 50%;
}
.carousel-arrs .arr-prev {
left: 0%;
}
.carousel-arrs .arr-next {
right: 0%;
}
/* SETTING SCROLLING CONTENT INLINE, HIDDING OVERFLOWS AND SETTING HEIGHTS AND WIDTHS FOR MAIN CONTENT SECTIONS */
.carousel-content {
height: 550px;
align-items: center;
}
.carousel .carousel-images,
.carousel .carousel-content {
flex-basis: 50%;
}
/** MOBILE / TYPOGRAPHY / PADDING / MARGINS STYLING **/
.carousel-images {
background-color: #00afef44;
-webkit-clip-path: polygon(0 0, 100% 0%, 78% 100%, 0% 100%);
clip-path: polygon(0 0, 100% 0%, 78% 100%, 0% 100%);
}
.carousel-images img {
min-height: 100%;
-webkit-clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);
clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);
}
.carousel-content-item {
padding: 80px 70px 80px 0px;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="carousel">
<div class="carousel-arrs">
<button class="arr-prev">
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" fill="currentColor"
class="bi bi-arrow-left-circle-fill " viewBox="0 0 16 16">
<path
d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm3.5 7.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5z" />
</svg>
</button>
<button class="arr-next"><svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" fill="currentColor"
class="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16">
<path
d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z" />
</svg></button>
</div>
<div class="carousel-images">
<img src="https://stripe.com/img/v3/atlas_v2/user_photos/metafused.jpg" class="img-fluid center-block carousel-img" alt="">
<img src="https://stripe.com/img/v3/atlas_v2/user_photos/sheleadsafrica.jpg" class="img-fluid center-block carousel-img"
alt="">
<img src="https://stripe.com/img/v3/atlas_v2/user_photos/coin_tracker.jpg" class="img-fluid center-block carousel-img"
alt="">
</div>
<div class="carousel-content">
<div class="carousel-content-item">
<p class="font-weight-light h3 text-muted font-italic">Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam neque modi dolorem incidunt voluptatibus nostrum quae quo ad perferendis accusamus!
</p>
<p><strong class="h4">TEST
</strong> <br>
TEST </p>
</div>
<div class="carousel-content-item">
<p class="font-weight-light h3 text-muted font-italic">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum dolor tempore rerum est temporibus, amet cum. Quos distinctio impedit ipsum.</p>
<p><strong class="h4">test</strong> <br>
test Lorem, ipsum dolor.
</p>
</div>
<div class="carousel-content-item">
<p class="font-weight-light h3 text-muted font-italic">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quibusdam distinctio omnis odio dicta ad maiores accusantium voluptatibus cum nemo expedita?</p>
<p><strong class="h4">test</strong> <br>
test Lorem, ipsum dolor.
</p>
</div>
</div>
</section></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>The function <code>addRemoveHideClass()</code> uses to calls to the array method <code>filter()</code>. That method "<strong>creates a new array</strong> with all elements that pass the test implemented by the provided function." <sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">1</a></sup> That method is meant to filter an array of elements that match a certain criteria so it returns an array <sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#return_value\" rel=\"nofollow noreferrer\">2</a></sup>. If you just want to iterate over the elements in the array, you can use use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>.forEach()</code></a>, or a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loop</a> loop could be used instead. Also, each iteration of those loops calls <code>foundImage()</code> and <code>foundContent()</code>. This is quite inefficient. It would be more efficient to store the value of those calls outside the loop and use the stored value inside the loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:11:59.350",
"Id": "255854",
"ParentId": "255849",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255854",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T15:38:36.033",
"Id": "255849",
"Score": "3",
"Tags": [
"javascript",
"css",
"api",
"event-handling",
"dom"
],
"Title": "Carousel Using Vanilla Javascript"
}
|
255849
|
<p>In order to write some reports I have to manually copy the name of client, address, claim number, etc from a pdf that I receive. I want to automate this part of the report writing by using vba to copy the relevant information into my word file.</p>
<p>This is what my program does:</p>
<ol>
<li>open the pdf with adobe acrobat and copy the content of the file onto the clipboard</li>
<li>open an excel worksheet and paste that content there.</li>
<li>Loop through the worksheet and store the relevant information in variables</li>
<li>In my word document find a replace some keywords by the information that I want to put in</li>
</ol>
<p>I would like to know if my code follows best practices or if there's any recommendations to make it more robust. should I consider ditching the excel step or maybe using mailmerge instead of find and replace? that kind stuff.</p>
<p>There's also an issue with opening adobe to copy the content of the pdf, I had to put a delay but it looks clumsy and if the user changes window or starts clicking around then nothing is copied from the pdf.</p>
<p>Idk if I can ask this here but right now the macro just works on the same document, is it possible to make it make a copy of the document so that I don't have to manually save as and then discard the changes</p>
<pre><code>Public Declare PtrSafe Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As LongPtr)
Sub fillTemplatePDF()
Dim strExcelFilename As String
Dim strAdobeReaderExePath As String
'filename to a excelfile that will be used to run the program
'path to acrobat.exe
strExcelFilename = "C:\Users\jonix\Desktop\test1.xlsx"
strAdobeReaderExePath = "C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe"
Dim cell As Excel.Range 'used to traverse the excel file
Dim S(13) As String 'Find in excel text
Dim R(15) As String 'Replacement text
Dim Q(15) As String 'Find in word text
Dim j As Integer 'j is a counter
'Find in excell text
S(0) = "RCC Project #"
S(1) = "Client Company Name"
S(2) = "Client Contact"
S(3) = "Client Address"
S(4) = "City"
S(5) = "State"
S(6) = "ZIP Code"
S(7) = "Claim #"
S(8) = "Name of Insured"
S(9) = "Address of Loss"
S(10) = "City"
S(11) = "State"
S(12) = "ZIP Code"
'Find in word text
Q(0) = "<<RCC Project #>>"
Q(1) = "<<Client Company Name>>"
Q(2) = "<<Client Contact>>"
Q(3) = "<<Client Address>>"
Q(4) = "<<Client City>>"
Q(5) = "<<Client State>>"
Q(6) = "<<Client ZIP Code>>"
Q(7) = "<<Claim #>>"
Q(8) = "<<Name of Insured>>"
Q(9) = "<<Address of Loss>>"
Q(10) = "<<Loss City>>"
Q(11) = "<<Loss State>>"
Q(12) = "<<Loss ZIP Code>>"
Q(13) = "<<Evaluation>>"
Q(14) = "<<Date>>"
'Variables
Dim xlsApplication As Excel.Application
Dim xlsWorkbook As Excel.Workbook
Dim xlsWorksheet As Excel.Worksheet
Dim xlsRange As Excel.Range
Dim boolExcelWasNotRunning As Boolean
Dim strPDFFilename As String
Dim strShellPathName As String
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
If fd.Show = -1 Then
vrtSelectedItem = fd.SelectedItems(1)
End If
'pdf filenames
strPDFFilename = vrtSelectedItem
strShellPathName = strAdobeReaderExePath & " """ & strPDFFilename & """"
'COPY FROM ADOBE
'Open adobe
Call Shell( _
pathname:=strShellPathName, _
windowstyle:=vbNormalFocus)
'Wait because the last command is asynchronous
Sleep 3000
'Select all, copy
SendKeys "^a"
SendKeys "^c"
'wait again.
Sleep 3000
'PASTE IN EXCEL
'if Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set xlsApplication = GetObject(, "Excel.Application")
If Err Then
boolExcelWasNotRunning = True
Set xlsApplication = New Excel.Application
End If
On Error GoTo Err_Handler
'open excel visibly for debug
'xlsApplication.Visible = True
'Open the workbook/worksheet
Set xlsWorkbook = xlsApplication.Workbooks.Open(FileName:=strExcelFilename)
Set xlsWorksheet = ActiveWorkbook.Worksheets("Sheet1")
Cells.Clear
With xlsWorksheet
'paste
.Range("A1").Select
.PasteSpecial Format:="Text"
'FIND IN EXCEL
'find the words saved in S and store the values in R
j = 0
For Each a In .Range("A1:A30").Cells
If Left(a, Len(S(j))) = S(j) Then
R(j) = Mid(a, Len(S(j)) + 3)
j = j + 1
End If
If j = 13 Then
Exit For
End If
Next a
If Range("A8").Value Like "*EVALUATION" Then
R(13) = StrConv(.Range("A8").Value, vbProperCase)
MsgBox R(13)
Else
R(13) = Q(13)
End If
R(14) = Format(Date, "MMMM DD, YYYY ")
End With
'FIND IN WORD AND REPLACE
'Word: replace in the template
With ActiveDocument.Content.Find
For j = 0 To 15
.Replacement.Font.Color = wdColorBlack
.Text = Q(j)
.Replacement.Text = R(j)
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
Next j
End With
'CLOSE STUFF
'Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
'Close excel
If xlsApplication.Workbooks.Count > 1 Then
xlsWorkbook.Close
Else
xlsWorkbook.Saved = True
xlsApplication.Quit
End If
'Make sure you release object references.
Set xlsRange = Nothing
Set xlsWorksheet = Nothing
Set xlsWorkbook = Nothing
Set xlsApplication = Nothing
Set fd = Nothing
'quit
Exit Sub
Err_Handler:
MsgBox strExcelFilename & " caused a problem. " & Err.Description, vbCritical, _
"Error: " & Err.Number
If boolExcelWasNotRunning Then
xlsApplication.Quit
End If
End Sub
</code></pre>
<p>Here is a sample pdf of what I'm working with
<a href="https://drive.google.com/file/d/1RO4fJluN6i4G19V_OZ8a7kVJZkx72l8H/view?usp=sharing" rel="nofollow noreferrer">pdf</a></p>
<p>And the word document would have something like this:</p>
<blockquote>
<p> <<Date>><br><br><<Client Company Name>><br> <<Client Address>><br> <<Client City>>, <<Client State>> <<Client ZIP Code>><br>Attention: Mr./Mrs. <<Client Contact>><br>Re: <<Evaluation>><br><<Name of Insured>> Residence<br><<Address of Loss>><br> <<Loss City>>, <<Loss State>> <<Loss ZIP Code>><br> RCC Project #: <<RCC Project #>><br> Claim #: <<Claim #>><br>Dear Mr./Mrs. <<Client Contact>>,</p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:31:42.620",
"Id": "504984",
"Score": "3",
"body": "*is it possible to make it make a copy of the document* - of course it's possible =) I'm not very familiar with the Word object model but have you tried [`Document.SaveAs2`](https://docs.microsoft.com/en-us/office/vba/api/Word.SaveAs2)? That said you are correct to doubt this being the right place to ask - everything else in your post is 100% top-notch, congratulations on passing \"first post\" with flying colors!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T09:33:42.900",
"Id": "505640",
"Score": "1",
"body": "@joniponi Are you using a free version of Acrobat like Acrobat Reader or do you have a paid version like Acrobat Acrobat DC or Pro? I ask because the paid versions come with a library that you can use in VBA directly and there would be no need for using shell to copy contents. That library gives you a lot of functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-23T04:17:20.590",
"Id": "506104",
"Score": "0",
"body": "@CristianBuse thank you! I was using the free version but I do have Adobe Acrobat DC. I had not looked into that yet. Are you referring to Acrobat SDK? and do you have any suggestion on how to tackle it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-23T11:32:24.200",
"Id": "506123",
"Score": "0",
"body": "@janiponi I've added a response on how to read the file without shell. If I will have time I will expand on the rest of you code in the following days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T14:06:42.837",
"Id": "506223",
"Score": "0",
"body": "@joniponi I've added a longer solution in the Edit #1 section of the answer. Hope it helps."
}
] |
[
{
"body": "<p>If Adobe Acrobat DC is available then to convert a PDF file to an Excel .xlsx file use (code in a standard .bas module):</p>\n<pre><code>Option Explicit\nOption Private Module\n\n'*******************************************************************************\n'Save a PDF file as XLSX\n'*******************************************************************************\nPublic Function PDFToXlsx(ByVal inPDFFilePath As String, ByVal outXLSXFilePath) As Boolean\n If inPDFFilePath = vbNullString Then Exit Function\n If outXLSXFilePath = vbNullString Then Exit Function\n '\n On Error GoTo ErrorHandler\n Dim pdDoc As Object: Set pdDoc = CreateObject("AcroExch.PDDoc")\n '\n pdDoc.Open inPDFFilePath\n pdDoc.GetJSObject.SaveAs outXLSXFilePath, "com.adobe.acrobat.xlsx", True\n '\n PDFToXlsx = True\nCleanExit:\n On Error Resume Next\n pdDoc.Close\n On Error GoTo 0\nExit Function\nErrorHandler:\n PDFToXlsx = False\n Resume CleanExit\nEnd Function\n\n'*******************************************************************************\n'Get a file path by using an Excel FilePicker FileDialog\n'*******************************************************************************\nPublic Function BrowseForFile(Optional ByVal initialPath As String _\n , Optional title As String _\n , Optional filterDesc As String _\n , Optional filters As String _\n) As String\n Const dialogTypeFilePicker As Integer = 3\n '\n With Application.FileDialog(dialogTypeFilePicker)\n If title <> vbNullString Then .title = title\n If initialPath <> vbNullString Then .InitialFileName = initialPath\n .AllowMultiSelect = False\n If filterDesc <> vbNullString And filters <> vbNullString Then\n On Error Resume Next\n 'Add first on top of the default filters\n .filters.Add filterDesc, filters\n 'If not failed then remove all filters and add only the new filters\n If Err.Number = 0 Then\n .filters.Clear\n .filters.Add filterDesc, filters\n End If\n On Error GoTo 0\n End If\n .Show\n If .SelectedItems.Count > 0 Then\n BrowseForFile = CStr(.SelectedItems(1))\n End If\n End With\nEnd Function\n</code></pre>\n<p>And a quick demo:</p>\n<pre><code>Public Sub Demo()\n Dim tempPDFPath As String\n Dim tempXLSXPath As String\n Dim book As Workbook\n '\n tempPDFPath = BrowseForFile(initialPath:=vbNullString _\n , title:="Please select PDF file!" _\n , filterDesc:="PDF Files" _\n , filters:="*.pdf")\n If tempPDFPath = vbNullString Then Exit Sub\n '\n tempXLSXPath = VBA.Environ$("Temp") & "\\XL_" & CLng(VBA.Timer * 1000) & ".xlsx"\n If PDFToXlsx(tempPDFPath, tempXLSXPath) Then\n Set book = Application.Workbooks.Open(tempXLSXPath, False, True)\n '\n 'Do whatever you want with the Excel file\n Stop\n '\n '\n '\n End If\nCleanExit:\n On Error Resume Next\n book.Close False\n Kill tempXLSXPath\n On Error GoTo 0\nEnd Sub\n</code></pre>\n<p>The demo is written for Excel but it can be written for Word as well.</p>\n<p><strong>EDIT #1</strong></p>\n<p>Using the previous code to convert a PDF file to an XLSX file we can encapsulate all the logic of reading the data into a single method:</p>\n<pre><code>'*******************************************************************************\n'Returns a Keyed Collection of Collections containing data\n'*******************************************************************************\nPrivate Function GetAssigmentDataFromPDF() As Collection\n Dim tempPDFPath As String\n Dim tempXLSXPath As String\n '\n tempPDFPath = BrowseForFile(initialPath:=vbNullString _\n , title:="Please select PDF file!" _\n , filterDesc:="PDF Files" _\n , filters:="*.pdf")\n If tempPDFPath = vbNullString Then Exit Function\n '\n tempXLSXPath = VBA.Environ$("Temp") & "\\XL_" & CLng(VBA.Timer * 1000) & ".xlsx"\n If Not PDFToXlsx(tempPDFPath, tempXLSXPath) Then GoTo CleanExit\n '\n 'Note we run in a separate app in case there is one open but is busy\n Dim xlApp As Object: Set xlApp = CreateObject("Excel.Application") 'late-binded so no need for reference to Microsoft Excel XX.X Object Library\n Dim book As Object\n Dim arrValues() As Variant\n '\n Dim collData As Collection\n Dim v As Variant\n Dim colonIndex As Long\n Const COLON_CHAR As String = ":"\n Dim key_ As String\n '\n On Error GoTo CleanExit\n Set book = xlApp.Workbooks.Open(tempXLSXPath, False, True)\n arrValues = book.Worksheets(1).UsedRange.Value2\n '\n Set collData = New Collection\n For Each v In arrValues\n If VarType(v) = vbString Then\n colonIndex = InStr(1, v, COLON_CHAR)\n If colonIndex > 0 Then\n key_ = Left$(v, colonIndex - 1)\n If Not CollectionHasKey(collData, key_) Then\n collData.Add New Collection, key_\n End If\n collData.Item(key_).Add Trim$(Right$(v, Len(v) - colonIndex))\n ElseIf v Like "*EVALUATION" Then\n If Not CollectionHasKey(collData, "Evaluation") Then\n collData.Add StrConv(v, vbProperCase), "Evaluation"\n End If\n End If\n End If\n Next\n Set GetAssigmentDataFromPDF = collData\nCleanExit:\n On Error Resume Next\n If Not book Is Nothing Then book.Close False\n Kill tempXLSXPath\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>it uses an utility:</p>\n<pre><code>'*******************************************************************************\n'Returns a boolean indicating if a Collection has a specific key\n'Parameters:\n' - coll: a collection to check for key\n' - key_: the key being searched for\n'Does not raise errors\n'*******************************************************************************\nPublic Function CollectionHasKey(ByVal coll As Collection, ByVal key_ As String) As Boolean\n On Error Resume Next\n coll.Item key_\n CollectionHasKey = (Err.Number = 0)\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>The <code>GetAssigmentDataFromPDF</code> returns a collection of collections. Why? Because you have duplicates (e.g. City, State and Zip Code) and there could be more duplicates in the future depending on the source PDF and how your needs evolve. So, for each unique key the main collection will have a sub-collection with as many occurences it can find for that key (e.g. you can now have 5 Zip Codes in the pdf and this will still work).</p>\n<p>One other thing it does, it retrieves all key-value pairs from the PDF. In your case, the colon (:) character is found then the text is split into 2 parts, the key for fast retrieval and the actual value.</p>\n<p>Consider this method running on top of the previous:</p>\n<pre><code>Option Explicit\nOption Private Module\n\nPrivate Type CLIENT_INFO\n ciCompanyName As String\n ciContact As String\n ciAddress As String\n ciCity As String\n ciState As String\n ciZipCode As String\n ciClaimNo As String\nEnd Type\nPrivate Type LOSS_INFO\n liNameOfInsured As String\n liAddressOfLoss As String\n liCity As String\n liState As String\n liZipCode As String\nEnd Type\nPrivate Type ASSIGNMENT_DATA\n adRccProjectNo As String\n adEvaluation As String\n adClientInfo As CLIENT_INFO\n adLossInfo As LOSS_INFO\n isInitialized As Boolean\nEnd Type\n\n'*******************************************************************************\n'Returns an ASSIGNMENT_DATA structure\n'*******************************************************************************\nPrivate Function GetAssigmentData() As ASSIGNMENT_DATA\n Dim collData As Collection: Set collData = GetAssigmentDataFromPDF()\n If collData Is Nothing Then Exit Function\n '\n On Error GoTo CleanExit 'In case keys are missing\n With GetAssigmentData\n .adRccProjectNo = collData("RCC Project #")(1)\n If CollectionHasKey(collData, "Evaluation") Then\n .adEvaluation = collData("Evaluation")\n End If\n With .adClientInfo\n .ciCompanyName = collData("Client Company Name")(1)\n .ciContact = collData("Client Contact")(1)\n .ciAddress = collData("Client Address")(1)\n .ciCity = collData("City")(1)\n .ciState = collData("State")(1)\n .ciZipCode = collData("ZIP Code")(1)\n .ciClaimNo = collData("Claim #")(1)\n End With\n With .adLossInfo\n .liNameOfInsured = collData("Name of Insured")(1)\n .liAddressOfLoss = collData("Address of Loss")(1)\n .liCity = collData("City")(2)\n .liState = collData("State")(2)\n .liZipCode = collData("ZIP Code")(2)\n End With\n .isInitialized = True\n End With\nCleanExit:\nEnd Function\n</code></pre>\n<p>This method is only concerned with retrieving the minimum data you need but this can evolve without needing to change the <code>GetAssigmentDataFromPDF</code> method. For example you might want to capture the Email next time and all you need to do is to call <code>collData("Email")(1)</code>.</p>\n<p>The text replace part could sit in it's own method:</p>\n<pre><code>'*******************************************************************************\n'Replaces a text in Ms Word\n'*******************************************************************************\nPrivate Sub ReplaceTextInDoc(ByVal doc As Document _\n , ByVal searchText As String _\n , ByVal replacementText As String _\n)\n With doc.Content.Find\n .Replacement.Font.Color = wdColorBlack\n .Text = searchText\n .Replacement.Text = replacementText\n .Wrap = wdFindContinue\n .Format = False\n .MatchCase = False\n .MatchWholeWord = False\n .MatchWildcards = False\n .MatchSoundsLike = False\n .MatchAllWordForms = False\n .Execute Replace:=wdReplaceAll\n End With\nEnd Sub\n</code></pre>\n<p>so that the main method can be simplified to:</p>\n<pre><code>'*******************************************************************************\n'Main method\n'*******************************************************************************\nPublic Sub FillTemplatePDF()\n Dim assignmentData As ASSIGNMENT_DATA\n '\n assignmentData = GetAssigmentData()\n If Not assignmentData.isInitialized Then\n MsgBox "Could not retrieve assignment data!", vbInformation, "Cancelled"\n Exit Sub\n End If\n '\n Dim newDoc As Document\n '\n Set newDoc = Application.Documents.Add()\n newDoc.Range.InsertFile ThisDocument.FullName 'Copy contents into new book\n '\n ReplaceTextInDoc newDoc, "<<RCC Project #>>", assignmentData.adRccProjectNo\n With assignmentData.adClientInfo\n ReplaceTextInDoc newDoc, "<<Client Company Name>>", .ciCompanyName\n ReplaceTextInDoc newDoc, "<<Client Contact>>", .ciContact\n ReplaceTextInDoc newDoc, "<<Client Address>>", .ciAddress\n ReplaceTextInDoc newDoc, "<<Client City>>", .ciCity\n ReplaceTextInDoc newDoc, "<<Client State>>", .ciState\n ReplaceTextInDoc newDoc, "<<Client ZIP Code>>", .ciZipCode\n ReplaceTextInDoc newDoc, "<<Claim #>>", .ciClaimNo\n End With\n With assignmentData.adLossInfo\n ReplaceTextInDoc newDoc, "<<Name of Insured>>", .liNameOfInsured\n ReplaceTextInDoc newDoc, "<<Address of Loss>>", .liAddressOfLoss\n ReplaceTextInDoc newDoc, "<<Loss City>>", .liCity\n ReplaceTextInDoc newDoc, "<<Loss State>>", .liState\n ReplaceTextInDoc newDoc, "<<Loss ZIP Code>>", .liZipCode\n End With\n If assignmentData.adEvaluation <> vbNullString Then\n ReplaceTextInDoc newDoc, "<<Evaluation>>", assignmentData.adEvaluation\n End If\n ReplaceTextInDoc newDoc, "<<Date>>", Format(Now, "MMMM DD, YYYY")\nEnd Sub\n</code></pre>\n<p>I separated the tasks in individual methods to make code easier to follow and maintain. Each method builds on top of other(s) method(s).</p>\n<p><strong>Full code</strong></p>\n<p>Add this code to your Word file and run <code>FillTemplatePDF</code> (your original method name) to generate a new Word Document (unsaved):</p>\n<pre><code>Option Explicit\nOption Private Module\n\nPrivate Type CLIENT_INFO\n ciCompanyName As String\n ciContact As String\n ciAddress As String\n ciCity As String\n ciState As String\n ciZipCode As String\n ciClaimNo As String\nEnd Type\nPrivate Type LOSS_INFO\n liNameOfInsured As String\n liAddressOfLoss As String\n liCity As String\n liState As String\n liZipCode As String\nEnd Type\nPrivate Type ASSIGNMENT_DATA\n adRccProjectNo As String\n adEvaluation As String\n adClientInfo As CLIENT_INFO\n adLossInfo As LOSS_INFO\n isInitialized As Boolean\nEnd Type\n\n'*******************************************************************************\n'Main method\n'*******************************************************************************\nPublic Sub FillTemplatePDF()\n Dim assignmentData As ASSIGNMENT_DATA\n '\n assignmentData = GetAssigmentData()\n If Not assignmentData.isInitialized Then\n MsgBox "Could not retrieve assignment data!", vbInformation, "Cancelled"\n Exit Sub\n End If\n '\n Dim newDoc As Document\n '\n Set newDoc = Application.Documents.Add()\n newDoc.Range.InsertFile ThisDocument.FullName 'Copy contents into new book\n '\n ReplaceTextInDoc newDoc, "<<RCC Project #>>", assignmentData.adRccProjectNo\n With assignmentData.adClientInfo\n ReplaceTextInDoc newDoc, "<<Client Company Name>>", .ciCompanyName\n ReplaceTextInDoc newDoc, "<<Client Contact>>", .ciContact\n ReplaceTextInDoc newDoc, "<<Client Address>>", .ciAddress\n ReplaceTextInDoc newDoc, "<<Client City>>", .ciCity\n ReplaceTextInDoc newDoc, "<<Client State>>", .ciState\n ReplaceTextInDoc newDoc, "<<Client ZIP Code>>", .ciZipCode\n ReplaceTextInDoc newDoc, "<<Claim #>>", .ciClaimNo\n End With\n With assignmentData.adLossInfo\n ReplaceTextInDoc newDoc, "<<Name of Insured>>", .liNameOfInsured\n ReplaceTextInDoc newDoc, "<<Address of Loss>>", .liAddressOfLoss\n ReplaceTextInDoc newDoc, "<<Loss City>>", .liCity\n ReplaceTextInDoc newDoc, "<<Loss State>>", .liState\n ReplaceTextInDoc newDoc, "<<Loss ZIP Code>>", .liZipCode\n End With\n If assignmentData.adEvaluation <> vbNullString Then\n ReplaceTextInDoc newDoc, "<<Evaluation>>", assignmentData.adEvaluation\n End If\n ReplaceTextInDoc newDoc, "<<Date>>", Format(Now, "MMMM DD, YYYY")\nEnd Sub\n\n'*******************************************************************************\n'Replaces a text in Ms Word\n'*******************************************************************************\nPrivate Sub ReplaceTextInDoc(ByVal doc As Document _\n , ByVal searchText As String _\n , ByVal replacementText As String _\n)\n With doc.Content.Find\n .Replacement.Font.Color = wdColorBlack\n .Text = searchText\n .Replacement.Text = replacementText\n .Wrap = wdFindContinue\n .Format = False\n .MatchCase = False\n .MatchWholeWord = False\n .MatchWildcards = False\n .MatchSoundsLike = False\n .MatchAllWordForms = False\n .Execute Replace:=wdReplaceAll\n End With\nEnd Sub\n\n'*******************************************************************************\n'Returns an ASSIGNMENT_DATA structure\n'*******************************************************************************\nPrivate Function GetAssigmentData() As ASSIGNMENT_DATA\n Dim collData As Collection: Set collData = GetAssigmentDataFromPDF()\n If collData Is Nothing Then Exit Function\n '\n On Error GoTo CleanExit 'In case keys are missing\n With GetAssigmentData\n .adRccProjectNo = collData("RCC Project #")(1)\n If CollectionHasKey(collData, "Evaluation") Then\n .adEvaluation = collData("Evaluation")\n End If\n With .adClientInfo\n .ciCompanyName = collData("Client Company Name")(1)\n .ciContact = collData("Client Contact")(1)\n .ciAddress = collData("Client Address")(1)\n .ciCity = collData("City")(1)\n .ciState = collData("State")(1)\n .ciZipCode = collData("ZIP Code")(1)\n .ciClaimNo = collData("Claim #")(1)\n End With\n With .adLossInfo\n .liNameOfInsured = collData("Name of Insured")(1)\n .liAddressOfLoss = collData("Address of Loss")(1)\n .liCity = collData("City")(2)\n .liState = collData("State")(2)\n .liZipCode = collData("ZIP Code")(2)\n End With\n .isInitialized = True\n End With\nCleanExit:\nEnd Function\n\n'*******************************************************************************\n'Returns a Keyed Collection of Collections containing data\n'*******************************************************************************\nPrivate Function GetAssigmentDataFromPDF() As Collection\n Dim tempPDFPath As String\n Dim tempXLSXPath As String\n '\n tempPDFPath = BrowseForFile(initialPath:=vbNullString _\n , title:="Please select PDF file!" _\n , filterDesc:="PDF Files" _\n , filters:="*.pdf")\n If tempPDFPath = vbNullString Then Exit Function\n '\n tempXLSXPath = VBA.Environ$("Temp") & "\\XL_" & CLng(VBA.Timer * 1000) & ".xlsx"\n If Not PDFToXlsx(tempPDFPath, tempXLSXPath) Then GoTo CleanExit\n '\n 'Note we run in a separate app in case there is one open but is busy\n Dim xlApp As Object: Set xlApp = CreateObject("Excel.Application") 'late-binded so no need for reference to Microsoft Excel XX.X Object Library\n Dim book As Object\n Dim arrValues() As Variant\n '\n Dim collData As Collection\n Dim v As Variant\n Dim colonIndex As Long\n Const COLON_CHAR As String = ":"\n Dim key_ As String\n '\n On Error GoTo CleanExit\n Set book = xlApp.Workbooks.Open(tempXLSXPath, False, True)\n arrValues = book.Worksheets(1).UsedRange.Value2\n '\n Set collData = New Collection\n For Each v In arrValues\n If VarType(v) = vbString Then\n colonIndex = InStr(1, v, COLON_CHAR)\n If colonIndex > 0 Then\n key_ = Left$(v, colonIndex - 1)\n If Not CollectionHasKey(collData, key_) Then\n collData.Add New Collection, key_\n End If\n collData.Item(key_).Add Trim$(Right$(v, Len(v) - colonIndex))\n ElseIf v Like "*EVALUATION" Then\n If Not CollectionHasKey(collData, "Evaluation") Then\n collData.Add StrConv(v, vbProperCase), "Evaluation"\n End If\n End If\n End If\n Next\n Set GetAssigmentDataFromPDF = collData\nCleanExit:\n On Error Resume Next\n If Not book Is Nothing Then book.Close False\n Kill tempXLSXPath\n On Error GoTo 0\nEnd Function\n\n'*******************************************************************************\n'Save a PDF file as XLSX\n'*******************************************************************************\nPublic Function PDFToXlsx(ByVal inPDFFilePath As String, ByVal outXLSXFilePath) As Boolean\n If inPDFFilePath = vbNullString Then Exit Function\n If outXLSXFilePath = vbNullString Then Exit Function\n '\n On Error GoTo ErrorHandler\n Dim pdDoc As Object: Set pdDoc = CreateObject("AcroExch.PDDoc")\n '\n pdDoc.Open inPDFFilePath\n pdDoc.GetJSObject.SaveAs outXLSXFilePath, "com.adobe.acrobat.xlsx", True\n '\n PDFToXlsx = True\nCleanExit:\n On Error Resume Next\n pdDoc.Close\n On Error GoTo 0\nExit Function\nErrorHandler:\n PDFToXlsx = False\n Resume CleanExit\nEnd Function\n\n'*******************************************************************************\n'Get a file path by using an Excel FilePicker FileDialog\n'*******************************************************************************\nPublic Function BrowseForFile(Optional ByVal initialPath As String _\n , Optional title As String _\n , Optional filterDesc As String _\n , Optional filters As String _\n) As String\n Const dialogTypeFilePicker As Integer = 3\n '\n With Application.FileDialog(dialogTypeFilePicker)\n If title <> vbNullString Then .title = title\n If initialPath <> vbNullString Then .InitialFileName = initialPath\n .AllowMultiSelect = False\n If filterDesc <> vbNullString And filters <> vbNullString Then\n On Error Resume Next\n 'Add first on top of the default filters\n .filters.Add filterDesc, filters\n 'If not failed then remove all filters and add only the new filters\n If Err.Number = 0 Then\n .filters.Clear\n .filters.Add filterDesc, filters\n End If\n On Error GoTo 0\n End If\n .Show\n If .SelectedItems.Count > 0 Then\n BrowseForFile = CStr(.SelectedItems(1))\n End If\n End With\nEnd Function\n\n'*******************************************************************************\n'Returns a boolean indicating if a Collection has a specific key\n'Parameters:\n' - coll: a collection to check for key\n' - key_: the key being searched for\n'Does not raise errors\n'*******************************************************************************\nPublic Function CollectionHasKey(ByVal coll As Collection, ByVal key_ As String) As Boolean\n On Error Resume Next\n coll.Item key_\n CollectionHasKey = (Err.Number = 0)\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>You do not need any references for this code to work. The Acrobat and the Excel\nobjects are all late-binded.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T03:25:23.077",
"Id": "506192",
"Score": "0",
"body": "Thank you! it works great! thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-23T11:31:26.883",
"Id": "256369",
"ParentId": "255855",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256369",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T17:14:44.427",
"Id": "255855",
"Score": "4",
"Tags": [
"vba",
"pdf",
"ms-word"
],
"Title": "Copy data from a pdf into word for the purpose of starting a report"
}
|
255855
|
<p>This is a program in C++ that guesses a number given by the user. I have to do homework and there's my attempt to solve an exercise from the programming book. If you know what can be done better and how to make more beautiful my code, let know me.</p>
<pre><code>#include <iostream>
int main() {
std::cout << "Enter number from range 0 to 100: ";
int num;
std::cin >> num;
int guess = 50;
bool lower = false;
bool upper = false;
int min = 0;
int max = 100;
while (guess != num) {
if (num < guess) {
std::cout << "Is this number lower than " << guess << "? (0 - false, 1 - true)\n";
std::cin >> lower;
if (lower) {
upper = false;
max = guess;
}
} else if (num > guess) {
std::cout << "Is this number greater than " << guess << "? (0 - false, 1 - true)\n";
std::cin >> upper;
if (upper) {
lower = false;
min = guess;
}
} else {
std::cout << "Let's guess, this number is equal to 50, isn't it?\n";
}
guess = (min+max)/2;
}
std::cout << "You entered a number " << guess << ", did I guess?\n";
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h2>Overview:</h2>\n<p>You need to concentrate on writing self-documenting code. This basically means using self-documenting variable names and writing functions that do specific obvious self-documented tasks.</p>\n<pre><code>int main(int argc, char* argv[])\n{\n // Handle command line arguments.\n // Set appropriate variables.\n\n playGuessNumberGame(); // Pass parameters you extracted from\n // command line or environment.\n}\n\nvoid playGame()\n{\n int hiddenNumber = getNumberFromPlayer();\n bool finished = false;\n\n while(!finished) {\n int guess = getNumberFromPlayer(); // Or calculate guess ?\n printHint(hiddenNumber, guess);\n\n finished = guess == hiddenNumber;\n }\n}\n</code></pre>\n<hr />\n<p>Another thing I would think about is storing state in an object that is updated. In this case you have the guess that is updated based on whether it was lower or higher. I would wrap this logic into an object that understands how to use this data:</p>\n<pre><code>class Guesser\n{\n int min;\n int max;\n int currentGuess;\n public:\n Guesser(): min(0), max(100), currentGuess(50) {}\n int getBestGuess() const {return currentGuess;}\n void updateGuess(bool toLow) {\n if (toLow) {\n int newGuess = currentGuess + (max - currentGuess)/2;\n min = currentGuess;\n currentGuess = newGuess;\n }\n else {\n int newGuess = min + (currentGuess - min)/2;\n max = currentGuess;\n currentGuess = newGuess;\n }\n \n }\n};\n</code></pre>\n<p>This way you isolate the variables that are associated with guessing, so they are not accidentally modified by external code.</p>\n<h2>Issues</h2>\n<p>There seems to be an issue with your tests. You are both testing the actual value then asking for user input to confirm what you actually know.</p>\n<pre><code> if (num < guess) {\n // Why are you asking this question.\n // You already know that the num is less than guess.\n // Are you trying to automate the processes or trying to\n // get user input to direct the action?\n std::cout << "Is this number lower than " << guess << "? (0 - false, 1 - true)\\n";\n std::cin >> lower;\n\n\n // We know it is lower.\n // but you only update things if the user confirms.\n // if you get it wrong does this upset the program?\n if (lower) {\n upper = false;\n max = guess;\n }\n</code></pre>\n<h2>Code Review:</h2>\n<p>You don't check if the input is valid:</p>\n<pre><code> int num;\n std::cin >> num;\n</code></pre>\n<p>When accepting user input, always validate that you got something valid. Otherwise you will end up with the application locking up or going into an infinite loop. In this case the stream simply sets itself as bad when invalid data is input, which can be detected with <code>if ()</code></p>\n<pre><code> if (std::cin >> num) {\n // Read worked we have a number in the variable.\n }\n</code></pre>\n<p>Note: This will validate things like <code>54XX</code> as good, since the first part is a valid number. You may want to check the whole line to make sure it is just a number:</p>\n<pre><code>bool getValidNumberFromUser(int& num)\n{\n std::string userInput;\n std::getline(std::cin, userInput);\n\n std::stringstream userInputStream(userInput);\n\n if (userInputStream >> num) {\n // Succesfully read a number.\n // but there should be no other trash on the line.\n // so let us validate that we got just a number.\n char garbage;\n if (userInputStream >> garbage) {\n // we got some garbage so there was an error on\n // user input. Lets return false from this function.\n return false;\n }\n // If we got here not garbage.\n return true;\n }\n // If we get here the user input did not even start with a number\n // So let us fail.\n return false;\n}\n\nbool isNumberOutOfRange(int number)\n{\n return number < 0 || number > 100;\n}\n\n\nint getNumberFromPlayer()\n{\n std::cout << "Enter number from 0 -> 100\\n";\n\n int playerNumber;\n while(!getValidNumberFromUser(playerNumber) || isNumberOutOfRange(playerNumber)) {\n std::cout << "You entered an invalid number. Try Again\\n";\n }\n return playerNumber;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T21:42:26.500",
"Id": "255862",
"ParentId": "255860",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T20:35:43.133",
"Id": "255860",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"homework",
"binary"
],
"Title": "Binary guess game in C++"
}
|
255860
|
<p>I have a 2D Python array (list of lists). I treat this as a 'table'. Now I want to <strong>replace</strong> the first row and the top row with a header row and column. The row and the header are exactly the same.</p>
<p>I try this using list comprehension. It works out for the 'row' part, but the column part is not very Pythonic yet.</p>
<pre><code># The header that i want to add
headers = ['foo', 'bar', 'baz', 'other']
l = len(headers) + 1 # The final matrix is one element bigger
# square matrix of random size, filled with data
array = [['xxx' for i in range(l)] for j in range(l)]
# The concise one - add headers to top row
array[0] = ['Title'] + [category for category in headers]
# The ugly one - add headers for the rows
for i in range(l):
array[i][0] = array[0][i]
</code></pre>
<p>The final output should look like this (which it does):</p>
<pre><code>[['Title', 'foo', 'bar', 'baz', 'other'],
['foo', 'xxx', 'xxx', 'xxx', 'xxx'],
['bar', 'xxx', 'xxx', 'xxx', 'xxx'],
['baz', 'xxx', 'xxx', 'xxx', 'xxx'],
['other', 'xxx', 'xxx', 'xxx', 'xxx']]
</code></pre>
<p>I'm just not so happy with the 'for' loop. How can this be done more Pythonic?</p>
|
[] |
[
{
"body": "<p>Maybe this can help (if you don't want to use <code>numpy</code>):</p>\n<pre><code>headers = ['foo', 'bar', 'baz', 'other']\nl = len(headers)\n\narr = [["xxx" for i in range(l)] for j in range(l)]\n\n# adding top row\narr = [headers] + arr\n\n# adding first column\nheaders_mod = ['Title'] + headers\nnew_arr = [[headers_mod[i]]+arr[i] for i in range(l+1)]\n\nfor i in new_arr:\n print(*i)\n</code></pre>\n<p>gives you the output as:</p>\n<pre><code>Title foo bar baz other\nfoo xxx xxx xxx xxx\nbar xxx xxx xxx xxx\nbaz xxx xxx xxx xxx\nother xxx xxx xxx xxx\n</code></pre>\n<hr />\n<p>Otherwise, when dealing with array manipulations in python try going with <code>numpy</code>, <code>pandas</code>, as they provide better operations like by giving option for <code>axis</code>, <code>transpose</code>, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:06:32.617",
"Id": "505042",
"Score": "0",
"body": "After rethinking you are right. I'm just not that familiar wit NumPy. I changed one of my matrices to a numpy array and surprisingly my code was still working. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:08:56.047",
"Id": "505043",
"Score": "0",
"body": "Yeah, mostly its the same but with very useful features for mathematical manipulations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T05:56:14.707",
"Id": "255873",
"ParentId": "255861",
"Score": "2"
}
},
{
"body": "<p><code>numpy</code> is excellent for tables, but for a labeled table like this <code>pandas</code> might be better for your needs.</p>\n<p>Solution using numpy:</p>\n<pre><code>import numpy as np\n\n# The header that i want to add\nheaders = ['foo', 'bar', 'baz', 'other']\n\nll = len(headers)+1\ndata = [['xxx' for _ in range(ll)] for j in range(ll)]\n\ndata = np.array(data, dtype=object)\n\ndata[0,0] = 'Title'\ndata[0,1:] = headers\ndata[1:,0] = headers\n\nprint(data)\n</code></pre>\n<p>prints</p>\n<pre><code>[['Title' 'foo' 'bar' 'baz' 'other']\n ['foo' 'xxx' 'xxx' 'xxx' 'xxx']\n ['bar' 'xxx' 'xxx' 'xxx' 'xxx']\n ['baz' 'xxx' 'xxx' 'xxx' 'xxx']\n ['other' 'xxx' 'xxx' 'xxx' 'xxx']]\n</code></pre>\n<p>Setting <code>dtype</code> to <code>object</code> allows your array to mix strings and other data types you might want to use. If your data is just strings then you can use <code>'UN'</code> as the <code>dtype</code>, where N is the longest string you plan to use. (Numpy, when making an all string array automatically picks your longest string as the maximum length for the strings, which is fine unless your strings are all shorter than the headers you plan to add.)</p>\n<p>Alternate version of the above code:</p>\n<pre><code>import numpy as np\n\n# The header that i want to add\nheaders = ['foo', 'bar', 'baz', 'other']\n\n# Add Title to headers to simply later assignment\nheaders = ['Title'] + headers\n\nll = len(headers)\ndata = [['xxx' for _ in range(ll)] for j in range(ll)]\n\ndata = np.array(data)\n\ndata[0,:] = headers\ndata[:,0] = headers\n\nprint(data)\n</code></pre>\n<p><code>pandas</code>, on the other hand, is explicitly designed to handle headers</p>\n<pre><code>import numpy as np, pandas as pd\n\n# The header that i want to add\nheaders = ['foo', 'bar', 'baz', 'other']\n\nll = len(headers) + 1\ndata = [['xxx' for _ in range(ll)] for j in range(ll)]\n\ndata = np.array(data)\n\ndata = pd.DataFrame(data[1:,1:], columns=headers, index=headers)\ndata.columns.name = 'Title'\n\ndata.loc['foo','bar'] = 'yes'\nprint(data)\nprint('')\nprint(data['bar'])\nprint('')\nprint(data.loc['foo',:])\n</code></pre>\n<p>prints</p>\n<pre><code>Title foo bar baz other\nfoo xxx yes xxx xxx\nbar xxx xxx xxx xxx\nbaz xxx xxx xxx xxx\nother xxx xxx xxx xxx\n\nfoo yes\nbar xxx\nbaz xxx\nother xxx\nName: bar, dtype: object\n\nTitle\nfoo xxx\nbar yes\nbaz xxx\nother xxx\nName: foo, dtype: object\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T04:17:34.853",
"Id": "255914",
"ParentId": "255861",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T21:12:48.130",
"Id": "255861",
"Score": "2",
"Tags": [
"python",
"array"
],
"Title": "Add headers to colums and rows in Python - 2D array (list of lists)"
}
|
255861
|
<p>I have written a program in Go to compute the discrete logarithm mod primes (find <span class="math-container">\$x\$</span> such that <span class="math-container">\$h=g^x\mod p\$</span>), and the algorithm I am using can be easily parallelized. Essentially, I am trying to find a value <span class="math-container">\$a\$</span> satisfying some slow function, where <span class="math-container">\$a < 2^{20}\$</span>; rather than check these one by one, I would like to dispatch a number of goroutines to check concurrently.</p>
<p>I haven't written a ton of programs using Go channels before, so I am mostly looking for suggestions about proper usage of channels with goroutines. My actual program is much longer and contains additional math and processing that isn't relevant to my question. If necessary, however, I am happy to post the full code.</p>
<p>Specific things I am wondering about:</p>
<ul>
<li><p>Is there a standard way of determining how many goroutines I should spawn for running such nearly-identical tasks? Specifically, is it best to spawn approx. number of CPUs (4), or is the standard practice to have a goroutine spawned for each value I check? (i.e. move the goroutine inside the main loop, rather than feeding values through a channel; that would be <span class="math-container">\$\approx 2^{20}\$</span> calls.) I have heard the adage <em>"goroutines are not threads"</em> but I am not sure to what extent that can be (ab)used. I am aware I could performance-tune this parameter, but I'm curious how this question is usually answered when prototyping software.</p>
</li>
<li><p>I have buffered the <code>tx</code> channel so that, if multiple goroutines find a solution at approximately the same time, they don't deadlock waiting for additional reads from <code>tx</code> (I only care about one solution, but there may be many). There isn't a way to <em>block</em> writes to a channel, is there? Earlier, I was getting program panics after trying to write to a closed channel.</p>
</li>
<li><p>I have a single <code>rx</code> channel, to send data to my goroutines, which I close when I find my first solution. Is this the proper way to do so? I am aware that closing a channel only prevents further writes to it, not future reads. My goal is to have <em>all</em> goroutines stop once the <em>first</em> one completes.</p>
<ul>
<li>In addition, is this single-sender/multiple-receiver structure acceptable? I'm not aiming for optimal load balancing, of course. Another thing I had tried earlier was to create multiple receivers <span class="math-container">\$rx_i\$</span> for each of <span class="math-container">\$N\$</span> goroutines, and assign <span class="math-container">\$a\$</span> to <span class="math-container">\$rx_{a \% N}\$</span>. But that presupposes that each goroutine will take equal amounts of time, which isn't true in general.</li>
</ul>
</li>
</ul>
<p>Pseudocode:</p>
<pre><code>package main
import (
...
)
func process_equation(rx <- chan *big.Int, tx chan *big.Int) int {
for a := range rx {
v := very_slow_function_call(a) // returns bool
if v {
// found it!
tx <- fast_function_call(a) // returns big.Int
return
}
}
}
func main() {
NUM_GOROUTINES := 4
rx := make(chan *big.Int)
tx := make(chan *big.Int, NUM_GOROUTINES)
var wg sync.WaitGroup
wg.Add(NUM_GOROUTINES)
for i := 0; i < NUM_GOROUTINES; i++ {
go func() {
process_equation(rx, tx)
wg.Done()
}()
}
a := big.NewInt(0)
one := big.NewInt(1)
solution := new(big.Int)
done := false
// nonblocking read of `tx`; increment `a` and send otherwise
for !done {
select {
case solution = <-tx:
close(rx)
done = true
default:
// increment
a.Add(a, one)
rx <- new(big.Int).Set(a)
}
}
fmt.Println("a =", solution)
wg.Wait() // wait for other goroutines to exit
}
</code></pre>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T08:51:13.087",
"Id": "505113",
"Score": "0",
"body": "I'd remove the `Pseudocode:` part from your question because this looks like valid code in Go (even though there are parts omitted). [Asking for reviews on pseudocode is off-topic](https://codereview.meta.stackexchange.com/a/3652), so people might misunderstand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:28:23.543",
"Id": "505129",
"Score": "0",
"body": "ok. at that point this may be more on-topic at SE."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T21:56:24.433",
"Id": "255863",
"Score": "1",
"Tags": [
"go",
"concurrency"
],
"Title": "Parallelizing identical long-running tasks with Go channels"
}
|
255863
|
<p>This a block of code taken from a program I am working on that creates multiple files. This part of the code is to create files and sort them by date by appending the date to the file name. User chooses the first and last date and which day(s) he needs the files named in. So if someone wanted to create a Microsoft Word document for every Mon, Wed, and Fri in the year they can do it in one shot.</p>
<p>I am trying to see if there is any way to optimize this. I started with bash scripting few months ago and recently started learning Python this is my first project. I am trying to figure out how to maybe condense all the different blocks for each day of the week to one if that's possible so that way I can have just 1 progress bar. There are some variables in the block that are assigned earlier in the program by user input. I did not include it due to length.</p>
<pre><code>start = np.datetime64(input("Start with: "))
end = np.datetime64(input("End with : "))
print()
print(" *************************** ")
print("Choose Day(s) | All Days |")
print(" | ------------------------- |")
print("E.g. | S | M | T | W | T | F | S |")
print(" | ------------------------- |")
print("(1=On, 0=Off) | 1 | 1 | 1 | 1 | 1 | 1 | 1 |")
print(" | |")
print(" *************************** ")
print("S M T W T F S")
sun, mon, tue, wed, thu, fri, sat = map(int, input().split())
print()
if sun == 1:
first_sunday = np.busday_offset(start, 0, roll='forward', weekmask='Sun')
last_sunday = np.busday_offset(end, 0, roll='preceding', weekmask='Sun')
sun_count = np.busday_count(first_sunday, last_sunday, weekmask='Sun') + 1
for i in trange(sun_count, desc="Sunday"):
touch.touch(file_name + " " + datetime.strptime(str(first_sunday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_sunday += np.timedelta64(7, 'D')
if mon == 1:
first_monday = np.busday_offset(start, 0, roll='forward', weekmask='Mon')
last_monday = np.busday_offset(end, 0, roll='preceding', weekmask='Mon')
mon_count = np.busday_count(first_monday, last_monday, weekmask='Mon') + 1
for i in trange(mon_count, desc="Monday"):
touch.touch(file_name + " " + datetime.strptime(str(first_monday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_monday += np.timedelta64(7, 'D')
if tue == 1:
first_tuesday = np.busday_offset(start, 0, roll='forward', weekmask='Tue')
last_tuesday = np.busday_offset(end, 0, roll='preceding', weekmask='Tue')
tue_count = np.busday_count(first_tuesday, last_tuesday, weekmask='Tue') + 1
for i in trange(tue_count, desc="Tuesday"):
touch.touch(file_name + " " + datetime.strptime(str(first_tuesday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_tuesday += np.timedelta64(7, 'D')
if wed == 1:
first_wednesday = np.busday_offset(start, 0, roll='forward', weekmask='Wed')
last_wednesday = np.busday_offset(end, 0, roll='preceding', weekmask='Wed')
wed_count = np.busday_count(first_wednesday, last_wednesday, weekmask='Wed') + 1
for i in trange(wed_count, desc="Wednesday"):
touch.touch(file_name + " " + datetime.strptime(str(first_wednesday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_wednesday += np.timedelta64(7, 'D')
if thu == 1:
first_thursday = np.busday_offset(start, 0, roll='forward', weekmask='Thu')
last_thursday = np.busday_offset(end, 0, roll='preceding', weekmask='Thu')
thu_count = np.busday_count(first_thursday, last_thursday, weekmask='Thu') + 1
for i in trange(thu_count, desc="Thursday"):
touch.touch(file_name + " " + datetime.strptime(str(first_thursday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_thursday += np.timedelta64(7, 'D')
if fri == 1:
first_friday = np.busday_offset(start, 0, roll='forward', weekmask='Fri')
last_friday = np.busday_offset(end, 0, roll='preceding', weekmask='Fri')
fri_count = np.busday_count(first_friday, last_friday, weekmask='Fri') + 1
for i in trange(fri_count, desc="Friday"):
touch.touch(file_name + " " + datetime.strptime(str(first_friday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_friday += np.timedelta64(7, 'D')
if sat == 1:
first_saturday = np.busday_offset(start, 0, roll='forward', weekmask='Sat')
last_saturday = np.busday_offset(end, 0, roll='preceding', weekmask='Sat')
sat_count = np.busday_count(first_saturday, last_saturday, weekmask='Sat') + 1
for i in trange(sat_count, desc="Saturday"):
touch.touch(file_name + " " + datetime.strptime(str(first_saturday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
first_saturday += np.timedelta64(7, 'D')
</code></pre>
|
[] |
[
{
"body": "<p>Each of your <code>if</code> blocks does the same thing, but with different inputs.</p>\n<pre><code>if sun == 1:\n first_sunday = np.busday_offset(start, 0, roll='forward', weekmask='Sun')\n last_sunday = np.busday_offset(end, 0, roll='preceding', weekmask='Sun')\n sun_count = np.busday_count(first_sunday, last_sunday, weekmask='Sun') + 1\n \n for i in trange(sun_count, desc="Sunday"):\n touch.touch(file_name + " " + datetime.strptime(str(first_sunday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)\n first_sunday += np.timedelta64(7, 'D')\n</code></pre>\n<p>can be replaced with</p>\n<pre><code>abbrev= 'Sun'\nname = 'Sunday'\nif sun == 1:\n first = np.busday_offset(start, 0, roll='forward', weekmask=abbrev)\n last = np.busday_offset(end, 0, roll='preceding', weekmask=abbrev)\n count = np.busday_count(first, last, weekmask=abbrev) + 1\n \n for i in trange(count, desc=name):\n touch.touch(file_name + " " + datetime.strptime(str(first), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)\n first += np.timedelta64(7, 'D')\n</code></pre>\n<p>This allows you to fold the days into a <code>for</code> loop, like so:</p>\n<pre><code># Input the value for each day into a single list rather than individual variables\nday_input = (int(val) for val in input().split())\nNAMES = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')\n\nfor val, name in zip(day_input, NAMES):\n # Skip any day that was inputted as 0\n if not val: # integer 0 is equivalent to boolean False\n continue\n abbrev = name[:3]\n first = np.busday_offset(start, 0, roll='forward', weekmask=abbrev)\n last = np.busday_offset(end, 0, roll='preceding', weekmask=abbrev)\n count = np.busday_count(first, last, weekmask=abbrev) + 1\n \n for i in trange(count, desc=name):\n touch.touch(file_name + " " + datetime.strptime(str(first), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)\n first += np.timedelta64(7, 'D')\n</code></pre>\n<p>I replaced your call to <code>map</code> with a generator comprehension, which are generally considered the more aesthetic method of getting the same result. If you plan on using the values more than the once seen here you should use a list comprehension instead.</p>\n<p>Also, you can simplify your initial set of print statements by using a multiline string:</p>\n<pre><code>print(\n"""\n *************************** \nChoose Day(s) | All Days |\n | ------------------------- |\nE.g. | S | M | T | W | T | F | S |\n | ------------------------- |\n(1=On, 0=Off) | 1 | 1 | 1 | 1 | 1 | 1 | 1 |\n | |\n *************************** \nS M T W T F S""")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T00:39:32.353",
"Id": "255868",
"ParentId": "255864",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "255868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T22:01:21.857",
"Id": "255864",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"datetime"
],
"Title": "Printing the date of any day of the week as it occurs between two set dates"
}
|
255864
|
<p>This program adds together all elements in an array with the function <code>parallelReduce</code>. Includes testing on an initialization with all 1's and a calculation of the speed up. I only tried to optimize the kernel itself, not the data transfer by initializing on the GPU for example.</p>
<pre><code>#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <iostream>
#include <chrono>
#include <assert.h>
// To make error checking easier
inline cudaError_t checkCuda(cudaError_t result)
{
if (result != cudaSuccess) {
fprintf(stderr, "CUDA Runtime Error: %s\n", cudaGetErrorString(result));
assert(result == cudaSuccess);
}
return result;
}
/*
Parallel reduce helper function. When run
with n/2 threads, changes array a to a' such that
the sum of the first n elements of a is equal to
the sum of the first \lceil n/2 \rceil elements of a'
*/
__global__ void reduce(int* a, int n)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int stride = gridDim.x * blockDim.x;
for (int j = i; j < n / 2; j += stride)
{
a[j] += a[n - 1 - j];
}
}
/*
For an array a of length n, puts the sum of all elements in a[0]
*/
void parallelReduce(int* a, int n)
{
// Get some information about the GPU
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
int multiProcessors = prop.multiProcessorCount;
// Repeatedly use the helper function reduce to condense
// a to its first element
while (n > 1) {
int threadsPerBlock = 256;
int numberOfBlocks = 32 * multiProcessors;
reduce << <numberOfBlocks, threadsPerBlock >> > (a, n);
checkCuda(cudaGetLastError());
n = (n + n % 2) / 2; // Rounds n/2 up.
}
}
int main()
{
// Initialize vector with N 1's.
int N = (2 << 27) + 1; // The array size gets too big before we would need a long or long long for N.
size_t size = N * sizeof(int);
int* h_a;
checkCuda(cudaMallocHost(&h_a, size));
for (int i = 0; i < N; i++) {
h_a[i] = 1;
}
// Copy to device (can be done asynchronically to hide transfer time, but
// that messes up the timing of the kernel).
int* d_a;
checkCuda(cudaMalloc(&d_a, size));
checkCuda(cudaMemcpy(d_a, h_a, size, cudaMemcpyHostToDevice));
// Calculate the sum sequentially and time it.
auto tic = std::chrono::high_resolution_clock::now();
int hostSolution = 0;
for (int i = 0; i < N; i++)
{
hostSolution += h_a[i];
}
auto toc = std::chrono::high_resolution_clock::now();
int duration = std::chrono::duration_cast<std::chrono::milliseconds>(toc - tic).count();
std::cout << "The sequential function says the answer is " << hostSolution << " this took " << duration
<< " ms." << std::endl;
// Kernel computation
tic = std::chrono::high_resolution_clock::now();
parallelReduce(d_a, N);
checkCuda(cudaDeviceSynchronize());
toc = std::chrono::high_resolution_clock::now();
int parallelDuration = std::chrono::duration_cast<std::chrono::milliseconds>(toc - tic).count();
// Copy result back to host
int solution;
checkCuda(cudaMemcpy(&solution, &d_a[0], sizeof(int), cudaMemcpyDeviceToHost));
// Print the parallel result and speed up:
std::cout << "The parallel function says the answer is " << solution << " this took " << parallelDuration
<< " ms." << std::endl;
std::cout << "This means we have achieved a speed up of " << duration / parallelDuration << std::endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T22:08:01.120",
"Id": "506314",
"Score": "0",
"body": "Lol that’s definitely not a beginner question:) I don’t know anything about CUDA so I’m I can’t answer your question. Maybe you should consider bountying if you want to draw more attention"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T22:45:48.980",
"Id": "255865",
"Score": "2",
"Tags": [
"c++",
"beginner",
"cuda"
],
"Title": "Reduction on the gpu"
}
|
255865
|
<p>Well, hang-bar but same deal.</p>
<p>Any things I could've improved? (I'm starting to get into c++, so chose this as a basic project)</p>
<p>Actually, one question I had: I'm using code::blocks, which generates class headers+implementation files, but places the headers in an <code>include</code> folder while the implementation files go in <code>src</code>. I noticed that the code wouldn't compile in code::blocks till I added the compiler setting of <code>-Iinclude</code>. I assume that means it checks <code>/include</code> each time it wants to find a header, but that seems sorta weird that you would need to add that. Is it better practice to do that, or to just write the includes with full paths (e.g. the implementation of HangmanGame would have <code>#include ../include/HangmanGame.h</code>)?</p>
<p>One other question: I'm reasonably sure that some of the <code>#include</code>s from the STL are no longer needed (I removed whatever was using them), is there a tool in code::blocks (or another program) that allows me to easily see which <code>#include</code>s are currently not used? Since every <code>std::something</code> call comes from one <code>#include</code> or another, I would think there'd be some easy way to check that out.</p>
<p>Any feedback on that or other aspects appreciated.</p>
<p><code>main.cpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "HangmanGame.h"
#define RUNNING 0
int main()
{
HangmanGame game;
while (game.performTurn() == RUNNING) {};
return 0;
}
</code></pre>
<p><code>HangmanGame.h</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef HANGMANGAME_H
#define HANGMANGAME_H
#include <string>
#include <set>
class HangmanGame
{
public:
HangmanGame();
int performTurn();
private:
void printMan();
void printGuessWord();
void printWrongGuesses();
static std::string getRandomWord();
char getGuess();
void winGame();
void loseGame();
const std::string secretWord;
std::set<char> guessedLetters = {};
std::set<char> guessedWrongLetters = {};
};
#endif // HANGMANGAME_H
</code></pre>
<p><code>HangmanGame.cpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "HangmanGame.h"
#include <iostream>
#include <string>
#include <sstream>
#include <set>
#include <locale>
#include <algorithm>
#include <iterator>
#include <vector>
#include <fstream>
#define RUNNING 0
#define WIN 1
#define LOSE -1
HangmanGame::HangmanGame() : secretWord(getRandomWord()) {}
void HangmanGame::printMan()
{
std::cout << "|------------------------|\n|";
for (unsigned int i = 0; i < 6; i++) {
std::cout << ((i < guessedWrongLetters.size()) ? "\u2588\u2588\u2588\u2588" : " ");
}
std::cout << "|\n|------------------------|" << std::endl;
}
void HangmanGame::printGuessWord()
{
std::istringstream wordStream (secretWord);
char letter;
while (wordStream >> letter) {
std::cout << ((guessedLetters.find(letter) == guessedLetters.end()) ? '_' : letter) << " ";
}
std::cout << std::endl;
}
void HangmanGame::printWrongGuesses()
{
for (char letter : guessedWrongLetters) {
std::cout << letter << " ";
}
if (guessedLetters.size() > 0)
{
std::cout << std::endl;
}
}
std::string HangmanGame::getRandomWord()
{
std::vector<std::string> words;
std::ifstream file("words.txt");
std::string line;
srand(time(0));
while(getline(file,line)) words.push_back(line);
std::random_shuffle(words.begin(), words.end());
return words[0];
}
char HangmanGame::getGuess()
{
std::string inputStr;
std::locale loc;
while (true) {
std::cout << "Enter a letter: " << std::endl;
std::getline(std::cin, inputStr);
std::transform(inputStr.begin(), inputStr.end(), inputStr.begin(), ::tolower);
if (inputStr.length() != 1) {
std::cout << "Please enter one letter!" << std::endl;
continue;
}
if ((guessedLetters.find(inputStr[0]) != guessedLetters.end())) {
std::cout << "You've already guessed that letter!" << std::endl;
continue;
}
if (!isalpha(inputStr[0])) {
std::cout << "Please enter a letter!" << std::endl;
continue;
}
return inputStr[0];
}
}
int HangmanGame::performTurn()
{
std::cout << "Hang-o-meter (Don't let it fill up!!)" << std::endl;
printMan();
std::cout << std::endl;
std::cout << "Wrong guesses:" << std::endl;
printWrongGuesses();
std::cout << std::endl;
std::cout << "Word:" << std::endl;
printGuessWord();
std::cout << std::endl;
char guess = getGuess();
std::cout << std::endl;
guessedLetters.insert(guess);
if (std::count(secretWord.begin(), secretWord.end(), guess) > 0) {
std::cout << guess << " appears " << std::count(secretWord.begin(), secretWord.end(), guess) << " times in the word!" << std::endl;
} else {
std::cout << guess << " doesn't appear in the word." << std::endl;
guessedWrongLetters.insert(guess);
}
std::cout << std::endl << std::endl;
if (guessedWrongLetters.size() >= 6) {
loseGame();
return LOSE;
}
for (char c : secretWord) {
if (guessedLetters.find(c) == guessedLetters.end()) {
return RUNNING;
}
}
winGame();
return WIN;
}
void HangmanGame::winGame()
{
std::cout << "You win!" << std::endl << std::endl;
printMan();
std::cout << std::endl;
std::cout << "The word was:" << std::endl;
printGuessWord();
std::cout << std::endl;
}
void HangmanGame::loseGame()
{
std::cout << "You lose!" << std::endl << std::endl;
printMan();
std::cout << std::endl;
std::istringstream wordStream(secretWord);
auto begin = std::istream_iterator<char>(wordStream);
auto end = std::istream_iterator<char>();
std::set<char> temp(begin, end);
guessedLetters = temp;
std::cout << "The word was:" << std::endl;
printGuessWord();
std::cout << std::endl;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Constants</h1>\n<p>Instead of macros, use <code>constexpr</code> or <code>enum</code>, and put the constants in\na header file rather than duplicate them multiple times:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum class Status {\n Running, Win, Lose\n};\n</code></pre>\n<h1>Default constructor</h1>\n<p>Generally, I would expect default constructors to be lightweight. I\nwould make the secret word an argument of the constructor:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <utility>\n\nclass HangmanGame {\n std::string secret_word;\n // ...\npublic:\n explicit HangmanGame(std::string secret_word)\n : secret_word{std::move(secret_word)}\n {\n }\n // ...\n};\n</code></pre>\n<p>so that the class can be used with both set-word and random-word\ngames.</p>\n<h1>Random word generation</h1>\n<p>Instead of storing all words in memory, you can scan the file to find\nout the number of words and scan the file again to pick the <code>n</code>th\nword.</p>\n<h1>Miscellaneous</h1>\n<p><a href=\"https://stackoverflow.com/q/213907\">Use <code>\\n</code>, not <code>std::endl</code>.</a></p>\n<p>In <code>printGuessWord</code> and <code>loseGame</code>, the letters of a <code>std::string</code> can\nbe directly iterated over. There is no need to construct a\n<code>std::istringstream</code> for this.</p>\n<p>This works, but is technically unsound:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::transform(inputStr.begin(), inputStr.end(), inputStr.begin(), ::tolower);\n</code></pre>\n<p>In the eyes of a language lawyer, it should be replaced by</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::transform(\n inputStr.begin(), inputStr.end(), inputStr.begin(),\n [](unsigned char c) { return std::tolower(c); }\n);\n</code></pre>\n<p>(see <a href=\"https://stackoverflow.com/a/21805970\">Do I need to cast to <code>unsigned char</code> before calling <code>toupper()</code>,\n<code>tolower()</code>, et al.?</a>).</p>\n<p>In</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main()\n{\n HangmanGame game;\n while (game.performTurn() == RUNNING) {};\n return 0;\n}\n</code></pre>\n<p>the game logic is usually contained within a <code>.run()</code> method.</p>\n<h1>Q & A</h1>\n<blockquote>\n<p>Actually, one question I had: I'm using code::blocks, which\ngenerates class headers+implementation files, but places the headers\nin an <code>include</code> folder while the implementation files go in <code>src</code>. I\nnoticed that the code wouldn't compile in code::blocks till I added\nthe compiler setting of <code>-Iinclude</code>. I assume that means it checks\n<code>/include</code> each time it wants to find a header, but that seems sorta\nweird that you would need to add that. Is it better practice to do\nthat, or to just write the includes with full paths (e.g. the\nimplementation of HangmanGame would have <code>#include ../include/HangmanGame.h</code>)?</p>\n</blockquote>\n<p>I would go with <code>-Iinclude</code>. This way, the code is independent from\nthe organization of the source files is. You can modify the placement\nof files later without touching the code.</p>\n<blockquote>\n<p>One other question: I'm reasonably sure that some of the <code>#include</code>s\nfrom the STL are no longer needed (I removed whatever was using\nthem), is there a tool in code::blocks (or another program) that\nallows me to easily see which <code>#include</code>s are currently not used?\nSince every <code>std::something</code> call comes from one <code>#include</code> or\nanother, I would think there'd be some easy way to check that out.</p>\n</blockquote>\n<p>I'm not sure about Code::Blocks, but in general, I wouldn't worry\nabout this too much. In fact, one common practice is to put all\n<code>#include</code>s from the standard library to a precompiled header, so as\nnot to slow down (and sometimes even speed up) compilation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:21:52.600",
"Id": "505185",
"Score": "0",
"body": "Thanks for all the help - by the way, would it make sense to put the enum in the same header, or a different one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T01:30:18.347",
"Id": "505209",
"Score": "0",
"body": "@Theo The enum is going to be used as the return type of `performTurn`, and thus it is part of the public interface, so yes, it should be put in the same header. Alternatively, if you make `performTurn` private and expose only a `run` function, you can make the enum internal to the implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T06:04:10.293",
"Id": "255874",
"ParentId": "255870",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "255874",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T02:43:41.103",
"Id": "255870",
"Score": "4",
"Tags": [
"c++",
"hangman"
],
"Title": "C++ Hangman with a class"
}
|
255870
|
<p>I made a Tic-tac-toe game where you can play against the program or with another player in C++ and I know the code is far too long for what it is.
I've tried to optimize it using non-void functions (so I don't have to create multiple functions instead of 1 for similar code) and loops to condense some repetitive code. But I couldn't get anything to work.</p>
<p>I'm still a beginner, so I know I'm missing something.</p>
<pre><code>//Tic-tac-toe
#include <iostream>
#include <string>
#include <vector>
//variables
bool AI_is_smart, game_over, cheat, mistake;
int order, move, x, y;
int turn=1;
//vectors
std::vector<std::string> boxes{" ", " ", " ", " ", " ", " ", " ", " ", " "};
//functions
//Shows the progression of the game
void gameboard(){
std::cout<<" ___ ___ ___ \t _ _ _\n";
std::cout<<"| "<<boxes[0]<<" | "<<boxes[1]<<" | "<<boxes[2]<<" |\t|0|1|2|\n";
std::cout<<" ___ ___ ___ \t _ _ _ \n";
std::cout<<"| "<<boxes[3]<<" | "<<boxes[4]<<" | "<<boxes[5]<<" |\t|3|4|5|\n";
std::cout<<" ___ ___ ___ \t _ _ _ \n";
std::cout<<"| "<<boxes[6]<<" | "<<boxes[7]<<" | "<<boxes[8]<<" |\t|6|7|8|\n";
std::cout<<" ___ ___ ___ \t _ _ _\n\n";
}
//Determines if the game should end
bool game_over_conditions(){
if (boxes[0]+boxes[1]+boxes[2]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[3]+boxes[4]+boxes[5]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[6]+boxes[7]+boxes[8]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[0]+boxes[3]+boxes[6]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[1]+boxes[4]+boxes[7]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[2]+boxes[5]+boxes[8]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[0]+boxes[4]+boxes[8]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[2]+boxes[4]+boxes[6]=="xxx"){std::cout<<"x WINS!\n"; game_over = true;}
else if (boxes[0]+boxes[1]+boxes[2]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[3]+boxes[4]+boxes[5]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[6]+boxes[7]+boxes[8]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[0]+boxes[3]+boxes[6]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[1]+boxes[4]+boxes[7]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[2]+boxes[5]+boxes[8]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[0]+boxes[4]+boxes[8]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[2]+boxes[4]+boxes[6]=="ooo"){std::cout<<"o WINS!\n"; game_over = true;}
else if (boxes[0]!=" "&&boxes[1]!=" "&&boxes[2]!=" "&&boxes[3]!=" "&&
boxes[4]!=" "&&boxes[5]!=" "&&boxes[6]!=" "&&boxes[7]!=" "&&
boxes[8]!=" ")
{std::cout<<"TIE!\n"; game_over = true;}
}
//Determines if the AI should move with winning intent. If not then it should move randomly
bool AI_type(){
if(game_over==true){std::cout<<" ";}
else if(boxes[0]+boxes[2]=="oo"&&boxes[1]==" "){std::cout<<"Program's turn (o) ...\n";boxes[1]="o";AI_is_smart=true;}
else if(boxes[1]+boxes[2]=="oo"&&boxes[0]==" "){std::cout<<"Program's turn (o) ...\n";boxes[0]="o";AI_is_smart=true;}
else if(boxes[3]+boxes[4]=="oo"&&boxes[5]==" "){std::cout<<"Program's turn (o) ...\n";boxes[5]="o";AI_is_smart=true;}
else if(boxes[3]+boxes[5]=="oo"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[5]=="oo"&&boxes[3]==" "){std::cout<<"Program's turn (o) ...\n";boxes[3]="o";AI_is_smart=true;}
else if(boxes[6]+boxes[7]=="oo"&&boxes[8]==" "){std::cout<<"Program's turn (o) ...\n";boxes[8]="o";AI_is_smart=true;}
else if(boxes[6]+boxes[8]=="oo"&&boxes[7]==" "){std::cout<<"Program's turn (o) ...\n";boxes[7]="o";AI_is_smart=true;}
else if(boxes[7]+boxes[8]=="oo"&&boxes[6]==" "){std::cout<<"Program's turn (o) ...\n";boxes[6]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[3]=="oo"&&boxes[6]==" "){std::cout<<"Program's turn (o) ...\n";boxes[6]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[6]=="oo"&&boxes[3]==" "){std::cout<<"Program's turn (o) ...\n";boxes[3]="o";AI_is_smart=true;}
else if(boxes[3]+boxes[6]=="oo"&&boxes[0]==" "){std::cout<<"Program's turn (o) ...\n";boxes[0]="o";AI_is_smart=true;}
else if(boxes[1]+boxes[4]=="oo"&&boxes[7]==" "){std::cout<<"Program's turn (o) ...\n";boxes[7]="o";AI_is_smart=true;}
else if(boxes[1]+boxes[7]=="oo"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[7]=="oo"&&boxes[1]==" "){std::cout<<"Program's turn (o) ...\n";boxes[1]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[5]=="oo"&&boxes[8]==" "){std::cout<<"Program's turn (o) ...\n";boxes[8]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[8]=="oo"&&boxes[5]==" "){std::cout<<"Program's turn (o) ...\n";boxes[5]="o";AI_is_smart=true;}
else if(boxes[5]+boxes[8]=="oo"&&boxes[2]==" "){std::cout<<"Program's turn (o) ...\n";boxes[2]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[4]=="oo"&&boxes[8]==" "){std::cout<<"Program's turn (o) ...\n";boxes[8]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[8]=="oo"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[8]=="oo"&&boxes[0]==" "){std::cout<<"Program's turn (o) ...\n";boxes[0]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[4]=="oo"&&boxes[6]==" "){std::cout<<"Program's turn (o) ...\n";boxes[6]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[6]=="oo"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[6]=="oo"&&boxes[2]==" "){std::cout<<"Program's turn (o) ...\n";boxes[2]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[2]=="xx"&&boxes[1]==" "){std::cout<<"Program's turn (o) ...\n";boxes[1]="o";AI_is_smart=true;}
else if(boxes[1]+boxes[2]=="xx"&&boxes[0]==" "){std::cout<<"Program's turn (o) ...\n";boxes[0]="o";AI_is_smart=true;}
else if(boxes[3]+boxes[4]=="xx"&&boxes[5]==" "){std::cout<<"Program's turn (o) ...\n";boxes[5]="o";AI_is_smart=true;}
else if(boxes[3]+boxes[5]=="xx"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[5]=="xx"&&boxes[3]==" "){std::cout<<"Program's turn (o) ...\n";boxes[3]="o";AI_is_smart=true;}
else if(boxes[6]+boxes[7]=="xx"&&boxes[8]==" "){std::cout<<"Program's turn (o) ...\n";boxes[8]="o";AI_is_smart=true;}
else if(boxes[6]+boxes[8]=="xx"&&boxes[7]==" "){std::cout<<"Program's turn (o) ...\n";boxes[7]="o";AI_is_smart=true;}
else if(boxes[7]+boxes[8]=="xx"&&boxes[6]==" "){std::cout<<"Program's turn (o) ...\n";boxes[6]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[3]=="xx"&&boxes[6]==" "){std::cout<<"Program's turn (o) ...\n";boxes[6]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[6]=="xx"&&boxes[3]==" "){std::cout<<"Program's turn (o) ...\n";boxes[3]="o";AI_is_smart=true;}
else if(boxes[3]+boxes[6]=="xx"&&boxes[0]==" "){std::cout<<"Program's turn (o) ...\n";boxes[0]="o";AI_is_smart=true;}
else if(boxes[1]+boxes[4]=="xx"&&boxes[7]==" "){std::cout<<"Program's turn (o) ...\n";boxes[7]="o";AI_is_smart=true;}
else if(boxes[1]+boxes[7]=="xx"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[7]=="xx"&&boxes[1]==" "){std::cout<<"Program's turn (o) ...\n";boxes[1]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[5]=="xx"&&boxes[8]==" "){std::cout<<"Program's turn (o) ...\n";boxes[8]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[8]=="xx"&&boxes[5]==" "){std::cout<<"Program's turn (o) ...\n";boxes[5]="o";AI_is_smart=true;}
else if(boxes[5]+boxes[8]=="xx"&&boxes[2]==" "){std::cout<<"Program's turn (o) ...\n";boxes[2]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[4]=="xx"&&boxes[8]==" "){std::cout<<"Program's turn (o) ...\n";boxes[8]="o";AI_is_smart=true;}
else if(boxes[0]+boxes[8]=="xx"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[8]=="xx"&&boxes[0]==" "){std::cout<<"Program's turn (o) ...\n";boxes[0]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[4]=="xx"&&boxes[6]==" "){std::cout<<"Program's turn (o) ...\n";boxes[6]="o";AI_is_smart=true;}
else if(boxes[2]+boxes[6]=="xx"&&boxes[4]==" "){std::cout<<"Program's turn (o) ...\n";boxes[4]="o";AI_is_smart=true;}
else if(boxes[4]+boxes[6]=="xx"&&boxes[2]==" "){std::cout<<"Program's turn (o) ...\n";boxes[2]="o";AI_is_smart=true;}
else{AI_is_smart=false;}
}
//AI moves randomly else sequentially
void program_move_random(){
srand (time(NULL));
move = rand()%9;
if(AI_is_smart==false){
std::cout<<"Program's turn (o) ...\n";
if (boxes[move]!="x"&&boxes[move]!="o") {boxes[move]="o";}
else{ if(boxes[0]==" ") { ; boxes[0]="o";}
else if(boxes[0]!=" "){ int x=1;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=2;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=3;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=4;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=5;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=6;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=7;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){ int x=8;
if(boxes[x]==" ") {;boxes[x]="o";}
else if(boxes[x]!=" "){std::cout<<" ";
}
}
}
}
}
}
}
}
}
}
}
else if(AI_is_smart==false&&game_over==true){std::cout<<" ";
}
}
//Player moves when vs Program
void player_move(){
if(game_over==false){std::cin>>move;
if (boxes[move]=="o"){std::cout<<"Don't Cheat! You lose a turn...\n";}
else if (boxes[move]=="x"){std::cout<<"You already own that square! Please try again...\n";
std::cout<<"Your Turn (x) ...\n";
std::cin>>move;
if (boxes[move]=="x"){std::cout<<"Don't delay the game! You lose a turn...\n";}
else if (boxes[move]=="o"){std::cout<<"Don't Cheat! You lose a turn...\n";}
else {boxes[move]="x";}
}
else {boxes[move]="x";}
}
}
//Player 1 moves in pvp
void player1_move(){
if(game_over==false){
std::cin>>move;
if (boxes[move]=="o"){std::cout<<"Don't Cheat! Player x loses a turn...\n";}
else if (boxes[move]=="x"){std::cout<<"You already own that square! Player x please try again...\n";
std::cout<<"Player 1's turn (x)...\n";
std::cin>>move;
if (boxes[move]=="x") {std::cout<<"Don't delay the game! Player x loses a turn...\n";}
else if (boxes[move]=="o") {std::cout<<"Don't Cheat! Player x loses a turn...\n";}
else {boxes[move]="x";}
}
else {boxes[move]="x";}
}
}
//Player 2 moves in pvp
void player2_move(){
if(game_over==false){
std::cin>>move;
if (boxes[move]=="x"){std::cout<<"Don't Cheat! Player o loses a turn...\n";}
else if (boxes[move]=="o"){std::cout<<"You already own that square! Player o please try again...\n";
std::cout<<"Player 1's turn (o)...\n";
std::cin>>move;
if (boxes[move]=="o") {std::cout<<"Don't delay the game! Player o loses a turn...\n";}
else if (boxes[move]=="x") {std::cout<<"Don't Cheat! Player o loses a turn...\n";}
else {boxes[move]="o";}
}
else {boxes[move]="o";}
}
}
int main() {
std::cout<<"Tic-tac-toe\n";
std::cout<<" ___ ___ ___ "<<'\n';
std::cout<<"| 0 | 1 | 2 |"<<'\n';
std::cout<<" ___ ___ ___ "<<'\n';
std::cout<<"| 3 | 4 | 5 |"<<'\n';
std::cout<<" ___ ___ ___ "<<'\n';
std::cout<<"| 6 | 7 | 8 |"<<'\n';
std::cout<<" ___ ___ ___ "<<"\n\n";
std::cout<<"Player vs Program (Player moves first)... Press 1.\n";
std::cout<<"Player vs Program (Program moves first)... Press 2.\n";
std::cout<<"Player vs Player... Press 3.\n";
std::cin>>order;
/**********************************
1. Player vs Program (Player moves first)
**********************************/
if (order==1) {std::cout<<"\nSelected: Player vs Program (Player moves first)...\n";
for(game_over=false; game_over==false&&turn<8;){
if(game_over==false){
std::cout<<"\nTurn #"<<turn<<"\n";
std::cout<<"Player's turn (x)...\n";
player_move();
gameboard();
game_over_conditions();
AI_type();
program_move_random();
gameboard();
game_over_conditions();
std::cout<<"\n_______________________\n\n";
turn++;}
}
}
/**********************************
2. Player vs Program (Program moves first)
**********************************/
else if (order==2) {std::cout<<"Selected: Player vs Program (Program moves first)...\n\n";
for(game_over=false; game_over==false&&turn<8;){
if(game_over==false){
std::cout<<"\nTurn #"<<turn<<"\n";
AI_type();
program_move_random();
gameboard();
game_over_conditions();
std::cout<<"Player's turn (x)...\n";
player_move();
gameboard();
game_over_conditions();
std::cout<<"\n_______________________\n\n";
turn++;}
}
}
/**********************************
3. Player vs Player
**********************************/
else if (order==3) {std::cout<<"Selected: Player vs Player...\n\n";
for(game_over=false; game_over==false&&turn<8;){
if(game_over==false){
std::cout<<"Player 1's turn (x) ...\n";
player1_move();
gameboard();
game_over_conditions();
std::cout<<"Player 2's turn (x) ...\n";
player2_move();
gameboard();
game_over_conditions();}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T05:26:49.433",
"Id": "505039",
"Score": "0",
"body": "Welcome to Code Review. You can take a look at some of the other [tic-tac-toe posts here](https://codereview.stackexchange.com/questions/tagged/tic-tac-toe%20c%2b%2b?tab=Votes)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T06:47:22.207",
"Id": "505041",
"Score": "0",
"body": "Don't forget to add Program vs Program to prevent World War 3! :) https://www.youtube.com/watch?v=F7qOV8xonfY"
}
] |
[
{
"body": "<p>You are hard-coding which board indices You check. If You look how indices change, then there are rather simple patterns how they are generated.</p>\n<h1>a) For example generate indices through some loop</h1>\n<pre><code>//\n// For example to go through all rows\n//\nfor (int row = 0; row < 3; row++) {\n\n\n auto myCount = 0;\n auto emptyCount = 0;\n auto emptyIndex = 0;\n\n // go to the end of a row\n for (int column = 0; column < 3; column++) {\n auto boxIndex = 3 * row + column;\n\n\n /// gather information about row\n\n if (boxes[boxIndex] == "o") {\n myCount++;\n }\n else if (boxes[boxIndex] == " ") {\n emptyCount++;\n emptyIndex = boxIndex;\n }\n }\n\n /// decide what to do with a row\n\n if (myCount == 2 && emptyCount == 1) {\n std::cout << "Program's turn (o) ...\\n";\n boxes[boxIndex] = "o";\n AI_is_smart = true;\n\n break; // we found first row for AI, we can stop searching ...\n }\n}\n</code></pre>\n<h1>b) For example generate indices by making a stepper / walker</h1>\n<p>You gave it starting position, information about board, how many steps it has\nto make. Then You will ask it to move itself by one step and report it to\nYou.</p>\n<pre><code>//\n// For example to go through all rows\n//\nfor (int startRow = 0; startRow < 3; startRow++) {\n\n // initialize_stepper arguments (board rowCount, board columnCount, startRow, startColumn, columnIncrease)\n\n Stepper stepper = intitialize_stepper( 3, 3, 3, startRow, 0, 0, 1);\n\n // move_one_step_and_return_index() returns boxIndex or -1 if no position is possible\n while ((boxIndex = move_one_step_and_return_index( &stepper )) != -1) {\n \n\n if (boxes[boxIndex] == "o") {\n // ...\n }\n }\n}\n\n// stepper is someting like this\nint intitialize_stepper( int rowCount, int columnCount, int stepCount, int startRow, int startColumn, int stepRowIncrease, int stepColumnIncrease ) {\n ...\n}\n\nint move_one_step_and_return_index( Stepper *s )\n{\n if( s->steps_remaining <= 0 ) return -1;\n\n s->row += s->row_step;\n s->column += s->column_step; \n s->steps_remaining -- ;\n\n if( s->row >= s->rowCount || s->row < 0 ) return -1;\n if( s->column >= s->column Count || s->column < 0 ) return -1;\n\n auto boxIndex = s->columnCount * s->row + s->column;\n return boxIndex;\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T13:31:56.470",
"Id": "255889",
"ParentId": "255872",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T03:38:49.543",
"Id": "255872",
"Score": "3",
"Tags": [
"c++",
"beginner",
"game",
"tic-tac-toe"
],
"Title": "Tic-tac-toe Game Optimization (C++)"
}
|
255872
|
<h3>Problem statement</h3>
<p>I need to generate <a href="https://en.wikipedia.org/wiki/Numeronym" rel="nofollow noreferrer">numeronyms from a string</a>, let's say <code>qwerty</code> as follows:</p>
<pre><code>qwerty
q1erty
q2rty
q3ty
q4y
</code></pre>
<h3>Code</h3>
<p>Can this solution can be <strong>improved</strong> or if there's any <strong>better approach</strong>?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const str = 'qwerty';
const lastCharPos = str.length - 1;
str
.split('')
.map(
(_, i) =>
i !== lastCharPos &&
console.log(`${str[0]}${i ? i : ''}${str.slice(i + 1, lastCharPos)}${str[lastCharPos]}`)
);</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:20:00.250",
"Id": "505044",
"Score": "2",
"body": ".... why? How is it compression? How do you decompress?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:37:46.357",
"Id": "505048",
"Score": "0",
"body": "Compress is probably not the right word, this looks like a [numeronym](https://en.wikipedia.org/wiki/Numeronym) which seems to have many names (alphanumeric acronyms, alphanumeric abbreviations, or numerical contractions), e.g. `a11y` for accessibility, `i18n` for internationalization, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:59:26.720",
"Id": "505052",
"Score": "2",
"body": "Do you need all the intermediary strings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T11:37:22.327",
"Id": "505067",
"Score": "0",
"body": "@Setris exactly, thanks for correcting me with that!"
}
] |
[
{
"body": "<h2>Know the language</h2>\n<p>Part of being a programmer is being familiar with the language/s you are using. These days languages are changing yearly thus keeping up to date is very important. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript\">MDN JavaScript</a> provides a good JavaScript reference. Every now and then its good to peruse the site to keep your knowledge up to date.</p>\n<h2>Strings</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String slice\">String.slice</a> will slice to the end of the string if you don't include the second argument. Thus there is no need for the variable <code>lastCharPos</code></p>\n<p>If the arguments for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String slice\">String.slice</a> are negative the position of the slice if from the end of the string. eg <code>"abcd".slice(-2)</code> will return <code>"cd"</code></p>\n<p>You can <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String split\">String.split</a> a string using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Spread syntax\">... (Spread syntax)</a> spread operator. eg<code>[...str].map</code></p>\n<h2>Arrays</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array map\">Array.map</a> creates an array. You do not use the array and so you should have used <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array forEach\">Array.forEach</a></p>\n<p>Often when using arrays and their iteration functions like <code>map</code>, it forces you to adapt the code to fit the array function's needs, increasing the complexity of the source and at runtime. You do this twice...</p>\n<ol>\n<li>The need to soak the first argument of map <code>map((_, i) =></code> which is a hack in my view.</li>\n<li>As you have no control over the number of iterations you are forced to add two statements <code>i !== lastCharPos</code> and <code>i ? </code> in the ternary expression <code>i ? i : ''</code></li>\n</ol>\n<h2>Improving the code.</h2>\n<p>Always make your code portable by wrapping it in a function</p>\n<p>Code should be focused on one task (role) at a time. Because you created the code inline (not a function) you have combined various tasks into one.</p>\n<ol>\n<li>Creating the set of strings</li>\n<li>Outputting to the console.</li>\n</ol>\n<p>As a function you can separate the output from the creation, returning an array of strings that you can then use as needed. eg Output to console.</p>\n<p>The Array iteration functions are too cumbersome for what your code does. You can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. while\">while</a> loop and push the built string to an array which you return at the end.</p>\n<h2>Rewrite</h2>\n<p>Your function does not output anything if the string length is <= 1. It is unclear if this is just an output requirement. The rewrite will return the input string (as first item in the array) no matter what its size</p>\n<p>The string is sliced using a negative index to slice from the end of the string.</p>\n<p>I used a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. while\">while</a> loop but you can also use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for\">for</a> loop</p>\n<p>Using while loop</p>\n<pre><code>function numeronyms(str) {\n const result = [str], len = str.length;\n var i = 1;\n while (i < len - 1) { result.push(str[0] + (i++) + str.slice(i - len)) }\n return result;\n}\n</code></pre>\n<p>Using for loop</p>\n<pre><code>function numeronyms(str) {\n const result = [str], len = str.length;\n for (let i = 2; i < len; i ++) {\n result.push(str[0] + (i - 1) + str.slice(i - len));\n }\n return result;\n} \n</code></pre>\n<h2>Usage</h2>\n<p>To use the function so that it behaves the same as your code it needs to check the string length.</p>\n<pre><code>const str = "qwerty";\nif (str.length > 1) { console.log(numeronyms(str)) }\n</code></pre>\n<p>or</p>\n<pre><code>const str = "qwerty";\nstr.length > 1 && console.log(numeronyms(str));\n</code></pre>\n<p>Or just assign the array for use later</p>\n<pre><code>const numers = numeronyms("qwerty");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T12:59:39.977",
"Id": "255887",
"ParentId": "255875",
"Score": "2"
}
},
{
"body": "<p>A short review;</p>\n<ul>\n<li>You want to put this in a function</li>\n<li>That function should either create the numeronyms or do the outputting, not both</li>\n<li>You are using <code>&&</code> as an <code>if</code> statement, great for code golfing, not so great for code review</li>\n<li>Using <code>.map()</code> doesnt really make sense if you are not actually mapping, <code>.forEach()</code> makes more sense</li>\n<li>If you insist on <code>split</code> and <code>map</code> as a for loop, consider to <code>split</code> on str.substr(1)</li>\n<li>I would store the first and last character in a nicely named variable for better comprehension</li>\n</ul>\n<p>A counter proposal would be</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function generateNumeronyms(s){\n \n const out = [s], start = s[0];\n let i = 1, tail = s.substring(2);\n \n while(tail){\n out.push(start + i++ + tail);\n tail = tail.substring(1);\n }\n return out;\n}\n\n\nconsole.log(generateNumeronyms('qwerty').join('\\n'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T13:07:29.567",
"Id": "255888",
"ParentId": "255875",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T06:35:11.640",
"Id": "255875",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"strings",
"compression"
],
"Title": "Numeronym generation"
}
|
255875
|
<p>It is an extremely basic mini-game menu. <a href="http://cpp.sh/" rel="nofollow noreferrer">Link to my game</a>.</p>
<p>I know there are more experienced C++ programmers than me, so it would be a great help if you help make my code better.</p>
<p>Thank you.</p>
<p>PS: First time using Stack Exchange; please help me with how I can make my post better.</p>
<pre><code>// Example program
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <locale>
#include <unistd.h>
// Hangman Game
void greet()
{
std::cout << "=============\n";
std::cout << "UFO: The Game\n";
std::cout << "=============\n";
std::cout << "Instructions: save your friend from alien abduction by guessing the letters in the codeword.\n";
}
void display_status(std::vector<char> incorrect, std::string answer)
{
std::cout << "\nIncorrect Guesses:\n";
for (int i = 0; i < incorrect.size(); i++)
{
std::cout << incorrect[i] << ' ';
}
std::cout << "\nCodeword:\n";
for (int i = 0; i < answer.length(); i++)
{
std::cout << answer[i] << ' ';
}
}
void end_game(std::string answer, std::string codeword)
{
if (answer == codeword)
{
std::cout << "Hooray! You saved the person and earned a medal of honor!\n";
}
else
{
std::cout << "Oh no! The UFO just flew away with another person!\n";
}
}
void display_misses(int misses)
{
if (misses == 0 || misses == 1)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / \\ ( Send help! ) \n";
std::cout << " / 0 \\ / `-----------' \n";
std::cout << " / --|-- \\ / \n";
std::cout << " / | \\ \n";
std::cout << " / / \\ \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 2)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / 0 \\ ( Send help! ) \n";
std::cout << " / --|-- \\ / `-----------' \n";
std::cout << " / | \\ / \n";
std::cout << " / / \\ \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 3)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " /--|--\\ ( Send help! ) \n";
std::cout << " / | \\ / `-----------' \n";
std::cout << " / / \\ \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 3)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " /--|--\\ ( Send help! ) \n";
std::cout << " / | \\ / `-----------' \n";
std::cout << " / / \\ \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 4)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / | \\ ( Send help! ) \n";
std::cout << " / / \\ \\ / `-----------' \n";
std::cout << " / \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 5)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / / \\ \\ ( Send help! )\n";
std::cout << " / \\ / `-----------' \n";
std::cout << " / \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 6)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / \\ ( Send help! ) \n";
std::cout << " / \\ / `-----------' \n";
std::cout << " / \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
}
// End Hangman game functions
// Tic Tac Toe Game
std::string board[9] = {" ", " ", " ", " ", " ", " ", " ", " ", " "};
int player = 1;
int position = 0;
void introduction()
{
std::cout << "Press [Enter] to begin: ";
std::cin.ignore();
std::cout << "\n";
std::cout << "===========\n";
std::cout << "Tic-Tac-Toe\n";
std::cout << "===========\n\n";
std::cout << "Player 1) X\n";
std::cout << "Player 2) 0\n\n";
std::cout << "Here's the 3 x 3 grid:\n\n";
std::cout << " | | \n";
std::cout << " 1 | 2 | 3 \n";
std::cout << "_____|_____|_____ \n";
std::cout << " | | \n";
std::cout << " 4 | 5 | 6 \n";
std::cout << "_____|_____|_____ \n";
std::cout << " | | \n";
std::cout << " 7 | 8 | 9 \n";
std::cout << " | | \n\n";
}
bool is_winner()
{
bool winner = false;
// rows
if ((board[0] == board[1]) && (board[1] == board[2]) && board[0] != " ")
{
winner = true;
}
else if ((board[3] == board[4]) && (board[3] == board[5]) && board[3] != " ")
{
winner = true;
}
else if ((board[6] == board[7]) && (board[6] == board[8]) && board[6] != " ")
{
winner = true;
}
// columns
else if ((board[0] == board[3]) && (board[0] == board[6]) && board[0] != " ")
{
winner = true;
}
else if ((board[1] == board[4]) && (board[1] == board[7]) && board[1] != " ")
{
winner = true;
}
else if ((board[2] == board[5]) && (board[2] == board[8]) && board[2] != " ")
{
winner = true;
} // diagonals
else if ((board[0] == board[4]) && (board[0] == board[8]) && board[0] != " ")
{
winner = true;
}
else if ((board[2] == board[4]) && (board[2] == board[6]) && board[2] != " ")
{
winner = true;
}
return winner;
}
bool filled_up()
{
bool filled = true;
for (int i = 0; i < 9; i++)
{
if (board[i] == " ")
{
filled = false;
}
}
return filled;
}
void draw()
{
std::cout << " | | \n";
std::cout << " " << board[0] << " | " << board[1] << " | " << board[2] << "\n";
std::cout << "_____|_____|_____ \n";
std::cout << " | | \n";
std::cout << " " << board[3] << " | " << board[4] << " | " << board[5] << "\n";
std::cout << "_____|_____|_____ \n";
std::cout << " | | \n";
std::cout << " " << board[6] << " | " << board[7] << " | " << board[8] << "\n";
std::cout << " | | \n";
std::cout << "\n";
}
void set_position()
{
std::cout << "Player " << player << "'s Turn (Enter 1-9): ";
while (!(std::cin >> position))
{
std::cout << "Player " << player << ", please enter a valid number between 1 and 9: ";
std::cin.clear();
std::cin.ignore();
}
std::cout << "\n";
while (board[position - 1] != " ")
{
std::cout << "Oops, there's already something in that position!\n\n";
std::cout << "Player " << player << "'s Turn (Enter 1-9): ";
std::cin >> position;
std::cout << "\n";
}
}
void update_board()
{
if (player % 2 == 1)
{
board[position - 1] = "X";
}
else
{
board[position - 1] = "0";
}
}
void change_player()
{
if (player == 1)
{
player++;
}
else
{
player--;
}
}
void take_turn()
{
while (!is_winner() && !filled_up())
{
set_position();
update_board();
change_player();
draw();
}
}
void end_game()
{
if (is_winner())
{
std::cout << "There's a winner!\n";
}
else if (filled_up())
{
std::cout << "There's a tie!\n";
}
}
// End Tic Tac Toe functions
// Now for the intro
void first_thing() {
std::cout << "What game do you want to play?\n";
std::cout << "1) Hangman with UFO\n";
std::cout << "2) Tic Tac Toe\n";
std::cout << "3) Rock Paper Scisors\n";
std::cout << "4) Memory Game\n";
int game;
std::cin >> game;
// Hangman scenario
if (game == 1)
{
greet();
std::string codeword = "codecademy";
std::string answer = "__________";
int misses = 0;
std::vector<char> incorrect;
bool guess = false;
char letter;
while (answer != codeword && misses < 7)
{
std::cout << "Welcome to tic tac toe\n";
display_misses(misses);
display_status(incorrect, answer);
std::cout << "\n\nPlease enter your guess: ";
std::cin >> letter;
for (int i = 0; i < codeword.length(); i++)
{
if (letter == codeword[i])
{
answer[i] = letter;
guess = true;
}
}
if (guess)
{
std::cout << "\nCorrect!\n";
}
else
{
std::cout << "\nIncorrect! The tractor beam pulls the person in further.\n";
incorrect.push_back(letter);
misses++;
}
guess = false;
}
end_game(answer, codeword);
}
// Tic Tac Toe Scenario
else if (game == 2) {
std::cout << "Welcome to Tic Tac Toe Game!!\n";
introduction();
take_turn();
end_game();
}
// Rock Paper Scissors Scenario
else if (game == 3) {
srand(time(NULL));
int computer = std::rand() % 3 + 1;
int user;
std::cout << "====================\n";
std::cout << "rock paper scissors!\n";
std::cout << "====================\n";
std::cout << "1) Rock\n";
std::cout << "2) Paper\n";
std::cout << "3) Scissors\n";
std::cout << "SHOOT!!\n ";
std::cin >> user;
if (user == 1)
std::cout << "you choose: Rock\n";
else if (user == 2)
{
std::cout << "you choose: Paper\n";
}
else
{
std::cout << "you choose: Scissors\n";
}
if (computer == 1)
{
std::cout << "cpu choose: Rock\n";
}
else if (computer == 2)
{
std::cout << "cpu choose: Paper\n";
}
else
{
std::cout << "cpu choose: Scissors\n";
}
if (user == computer)
{
std::cout << "it's a tie!\n";
}
// user rock
else if (user == 1)
{
if (computer == 2)
{
std::cout << "you lost! booooo!\n";
}
if (computer == 3)
{
std::cout << "you won! woohoo!\n";
}
}
// user paper
else if (user == 2)
{
if (computer == 1)
{
std::cout << "you won! woohoo!\n";
}
if (computer == 3)
{
std::cout << "you lost! boo!\n";
}
}
// user scissors
else if (user == 3)
{
if (computer == 1)
{
std::cout << "you won! woohoo!\n";
}
if (computer == 2)
{
std::cout << "you lost! booooo!\n";
}
}
}
// Memory Game
else if(game == 4) {
std::cout << "Welcome to memory game!!\n";
std::cout << "So host please enter the 1st word: ";
std::string o1;
std::string o2;
std::string o3;
std::string o4;
std::string o5;
std::string o6;
std::string o7;
std::string o8;
std::string o9;
std::string o10;
std::cin >> o1;
std::cout << " 2nd: \n";
std::cin >> o2;
std::cout << " 3rd: \n";
std::cin >> o3;
std::cout << " 4th: \n";
std::cin >> o4;
std::cout << " 5th:\n";
std::cin >> o5;
std::cout << " 6th: \n";
std::cin >> o6;
std::cout << " 7th:\n";
std::cin >> o7;
std::cout << " 8th: \n";
std::cin >> o8;
std::cout << "9th: \n";
std::cin >> o9;
std::cout << " 10: \n";
std::cin >> o10;
std::cout << "\n";
std::cout << "---------------- \n";
std::cout << "Words are: \n";
std::cout << " " << o1 << ", " << o2 << ", " << o3 << ", " << o4 << ", " << o5 << ", " << o6 << ", " << o7 << ", " << o8 << ", " << o9 << ", " << o10 << " \n";
std::cout << "Remember, you have 60seconds.....\n\n";
std::cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n";
sleep(2);
std::cout << "Done!!\n";
std::cout << "Now enter word 1: ";
std::string ans1;
int points = 0;
std::string ans2;
std::string ans3;
std::string ans4;
std::string ans5;
std::string ans6;
std::string ans7;
std::string ans8;
std::string ans9;
std::string ans10;
std::cin >> ans1;
if (ans1 == o1) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "2nd: ";
std::cin >> ans2;
if (ans2 == o2) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "3rd: ";
std::cin >> ans3;
if (ans3 == o3) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "4th: ";
std::cin >> ans4;
if (ans4 == o4) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "5th: ";
std::cin >> ans5;
if(ans5 == o5) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "6th: ";
std::cin >> ans6;
if(ans6 == o6) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "7th: ";
std::cin >> ans7;
if (ans7 == o7) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "8th: ";
std::cin >> ans8;
if (ans8 == o8) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Inccorect\n";
--points;
}
std::cout << "9th: ";
std::cin >> ans9;
if (ans9 == o9) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
--points;
}
std::cout << "Final one: ";
std::cin >> ans10;
if (ans10 == o10) {
std::cout << "Correct\n";
++points;
}
else {
std::cout << "Incorrect\n";
points = points - 1;
}
std::cout << " You finished, let's see if you won?\n";
if (points < 0)
{
points = 0;
}
std::cout << "Your points are: " << points << "\n";
if (points > 5) {
std::cout << "Congrats you passed the text!!!\n\n";
}
else {
std::cout << "Oops try again!\n";
}
}
}
int main()
{
bool Quit = false;
char answer;
std::string name;
std::cout << "What is your name? ";
getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
std::cout << "Welcome to Kanav's Game\n";
while(!Quit) {
first_thing();
std::cout << "Would you like to quit Y / N: ";
std::cin >> answer;
answer = std::toupper(answer);
if (answer == 'Y')
{
Quit = true;
std::cout << "BYE!!!";
return 0;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T07:56:40.193",
"Id": "505051",
"Score": "0",
"body": "Welcome to Code Review! Thanks for this great question - I hope you get some good reviews, and I hope to see more of your contributions here in future!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T13:14:04.663",
"Id": "505071",
"Score": "0",
"body": "I think you can get much response if you break your question into pieces. One game per question. I want to answer ufo game but I don't want to go all over others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T22:58:04.613",
"Id": "505196",
"Score": "0",
"body": "Your link only goes to cpp.sh, not to your program."
}
] |
[
{
"body": "<p>This is a good first draft. Most of the program works and you've worked hard to get the logic right. As you continue to learn more, you'll be surprised at how fast the amount of code in this program shrinks while still doing the same thing.</p>\n<h1>1. Aim for small functions</h1>\n<p>As much as possible, you want each function to do one small thing so that someone reading the code can understand it quickly. Just reading the function in your question is difficult due to all the scrolling I have to do.</p>\n<p>For each function, ask yourself, "What one thing should this function do?" Anything besides this one thing should be in another function. Since the first line in <code>first_thing()</code> is <code>std::cout << "What game do you want to play?\\n";</code>, the function should only handle choosing a game to play. This function already has the right overall structure for this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int game;\nstd::cin >> game;\n\nif (game == 1)\n{\n // ...\n}\nelse if (game == 2)\n{\n // ..\n}\n</code></pre>\n<p>The problem is that you put the code for all the games right into this function. For each game in this function, cut the code, paste it into a new function, and call that new function from <code>first_thing()</code>. Then, the entire function becomes:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void first_thing()\n{\n int game;\n std::cin >> game;\n\n if (game == 1)\n {\n play_hangman();\n }\n else if (game == 2)\n {\n play_tic_tac_toe();\n }\n else if (game == 3)\n {\n play_rock_paper_scissors();\n }\n else if (game == 4)\n {\n play_memory();\n }\n}\n</code></pre>\n<p>Notice that the entire function now fits on one screen and the purpose of the function is clear. In fact, I would rename the function to <code>choose_game()</code>. Names are one of the most important things to consider when writing code. The name of a function or variable should tell you its purpose so that it's easy to understand the code. Plus, good names reduce the number of comments you have to write.</p>\n<h1>2. Keep variables contained inside functions</h1>\n<p>First, a test. What happens if you try to play two games of tic-tac-toe during a single program run? You can't play the second game because the board is already filled in from the first game. This is why variables should be placed inside functions. Once you have written a <code>play_tic_tac_toe()</code> function, you can start it like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void play_tic_tac_toe()\n{\n std::string board[9] = {" ", " ", " ", " ", " ", " ", " ", " ", " "};\n int player = 1;\n int position = 0;\n\n // The rest of the game.\n}\n</code></pre>\n<p>Now, every time you start a new game of tic-tac-toe by calling this function, a new board is created for a new game.</p>\n<p>But, now that the board how can the other functions like <code>update_board()</code> and <code>is_winner()</code> operate? You pass the board and all other information through the function parameters. For example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void update_board(std::string (&board)[9], int player, int position)\n{\n\n if (player % 2 == 1)\n {\n\n board[position - 1] = "X";\n }\n else\n {\n\n board[position - 1] = "0";\n }\n}\n</code></pre>\n<p>The weird <code>(&board)</code> syntax is for passing board as a reference. This means that any changes made to <code>board</code> inside this function are visible outside the function as well. If instead you wrote <code>std::string board[9]</code>, the <code>update_board()</code> function would get a copy of the board, so any changes would not be visible outside. The <code>player</code> and <code>position</code> variables are passed by copy, but we are not changing these variables, so it doesn't matter. The number 1 and a copy of number 1 are the same thing. Other C++ containers do not have this weird syntax. If your board was a <code>std::vector<std::string></code>, then the function would be called this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void update_board(std::vector<std::string>& board, int player, int position)\n</code></pre>\n<p>The ampersand (<code>&</code>) at the end of the type means pass-by-reference. No ampersand means a copy is made.</p>\n<p>These changes also make it easier for people reading your code (including yourself six months from now) to follow the logic. Every variable is either declared in the function, or is a parameter of that function. As it is now, I have to go hunting through the entire file to figure out how <code>board</code>, <code>position</code>, and <code>player</code> are defined.</p>\n<h1>3. Lots of repetitive code means you need another function.</h1>\n<p>Computers are very good at doing repetitive things; humans, not so much. We get bored. If you find yourself typing the same thing over and over, consider whether you can write a function to do the work for you. Consider this bit of code from the Rock, Paper, Scissors section:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> if (user == 1)\n std::cout << "you choose: Rock\\n";\n else if (user == 2)\n {\n\n std::cout << "you choose: Paper\\n";\n }\n\n else\n {\n std::cout << "you choose: Scissors\\n";\n }\n if (computer == 1)\n {\n std::cout << "cpu choose: Rock\\n";\n }\n else if (computer == 2)\n {\n std::cout << "cpu choose: Paper\\n";\n }\n else\n {\n std::cout << "cpu choose: Scissors\\n";\n }\n</code></pre>\n<p>You are converting a numeric choice into text. Plus, the rest of the text for the user and cpu are the same, so let's write them just once.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string number_to_rock_paper_scissors(int choice)\n{\n if(choice == 1) return "Rock";\n if(choice == 2) return "Paper";\n return "Scissors";\n}\n</code></pre>\n<p>Then, inside the main game function:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void play_rock_paper_scissors()\n{\n // ...\n std::cout << "you choose: " << number_to_rock_paper_scissors(user) << "\\n";\n std::cout << "cpu choose: " << number_to_rock_paper_scissors(computer) << "\\n";\n // ...\n}\n</code></pre>\n<p>Every bit of logic is in one place and you are no longer repeating yourself. Try writing a function to determine who wins given two rock/paper/scissor values.</p>\n<h1>4. Lots of repetitive variables means you need a container and loops</h1>\n<p>In your Memory game, you have the following variables:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> std::string o1;\n std::string o2;\n std::string o3;\n std::string o4;\n std::string o5;\n std::string o6;\n std::string o7;\n std::string o8;\n std::string o9;\n std::string o10;\n</code></pre>\n<p>If you have a set of objects that are all the same type and need them in a certain order (you have numbered them), that means you need a <code>vector</code>--specifically, a <code>std::vector<std::string></code>. Then, to fill up the vector, you just loop until you have enough words:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<std::string> words;\nwhile(words.size() < 10)\n{\n std::cout << "Enter word #" << words.size() + 1 << ": ";\n std::string input;\n std::cin >> input;\n words.push_back(input);\n}\n</code></pre>\n<p>You can do the same thing with all of the <code>ans1</code>, <code>ans2</code>, etc. variables by creating a <code>std::vector<std::string> answers</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<std::string> answers;\nwhile(answers.size() < words.size())\n{\n std::cout << "Enter guess for word #" << answers.size() + 1 << ": ";\n std::string input;\n std::cin >> input;\n answers.push_back(input);\n}\n</code></pre>\n<p>Then, after all the input, use a loop to compare the <code>answers</code> with the <code>words</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>points = 0;\nfor(int i = 0; i < words.size(); ++i)\n{\n std::cout << "Your answer for word #" << i + 1 << " is ";\n if(words[i] == answers[i])\n {\n std::cout << "correct!\\n";\n ++points;\n }\n else\n {\n std::cout << "incorrect!\\n";\n --points;\n }\n}\n</code></pre>\n<h1>5. I like the art for the UFO Hangman game</h1>\n<p>That's all.</p>\n<h1>Smaller details</h1>\n<p>You don't need <code>#include <locale></code> or <code>#include <unistd.h></code>. The second one is UNIX only.</p>\n<p>Prefer <code>std::vector</code> to basic arrays. They are much easier to work with and behave like the rest of C++. It would be nice if the tic-tac-toe board were a <code>std::vector</code> (see Section 2).</p>\n<p><code>sleep()</code> is not a standard C++ function and only works in Windows. The way to pause the program is to use <code>std::sleep_for()</code> inside <code>#include <thread></code>. <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_for\" rel=\"nofollow noreferrer\">Reference</a></p>\n<p>The <code>Quit</code> variable inside <code>main()</code> is not used since you <code>return</code> from <code>main()</code> before the <code>while()</code> condition can see it changed. You can use <code>while(true)</code> to the same effect and get rid of <code>Quit</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T04:36:07.033",
"Id": "505356",
"Score": "0",
"body": "How can you do the same thing with ans1 and ans2? Sorry I am just a beginner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T06:45:20.617",
"Id": "505360",
"Score": "0",
"body": "@ILoveHistory I've updated my answer. Let me know if this helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T04:01:27.583",
"Id": "505444",
"Score": "0",
"body": "Thank you @Mark H"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T08:01:30.217",
"Id": "255918",
"ParentId": "255877",
"Score": "3"
}
},
{
"body": "<p>Few suggestions:</p>\n<h1>Raw string literal</h1>\n<p>No need for multiple</p>\n<blockquote>\n<p>std::cout << ... << std::endl;</p>\n</blockquote>\n<p>Raw string literal may be used as shown below:</p>\n<pre><code>const auto sImage = R"(\n . \n | \n .-\\"^\\"-. \n /_....._\\\\ \n .-\\"` `\\"-. \n ( ooo ooo ooo ) \n '-.,_________,.-' ,-----------. \n /--|--\\\\ ( Send help! ) \n / | \\\\ / `-----------' \n / / \\\\ \\\\ / \n / \\\\ \n / \\\\ \n / \\\\ \n)"; \nstd::cout << sImage << std::endl;\n</code></pre>\n<h1>Passing objects by const ref</h1>\n<p>It is common practice to pass heavy stuff like strings via const reference to avoid copying</p>\n<blockquote>\n<p>void end_game(const std::string& answer, const std::string& codeword)</p>\n</blockquote>\n<h1>Design</h1>\n<p>This one is quite abstract, vague, and personal so I won't say anything about the given design but just suggest asking few questions:</p>\n<ol>\n<li>How easy will be to add few more games to this code?</li>\n<li>How easy would it be to modify existing games (maybe making tic tac toe on 4x4 grid or with 3 players)?</li>\n<li>How easy would it be to add different UI (maybe add support for multiple languages)?</li>\n</ol>\n<p>A better design usually makes at least some changes easier</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T04:27:29.240",
"Id": "505355",
"Score": "0",
"body": "Thank you, guys!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T16:51:04.950",
"Id": "256015",
"ParentId": "255877",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T06:54:38.350",
"Id": "255877",
"Score": "2",
"Tags": [
"c++",
"tic-tac-toe",
"hangman",
"rock-paper-scissors"
],
"Title": "Classic games selection"
}
|
255877
|
<p>I have an event handling code, something like</p>
<pre><code>void handleEventType1(EventType1 event1) {
if (someCheck()){
function1(event);
postCheckTrue();
} else {
function2(event);
postCheckFalse();
}
}
void handleEventType2(EventType2 event2) {
if (someCheck()){
function3(event);
postCheckTrue();
} else {
function4(event);
postCheckFalse();
}
}
</code></pre>
<p>I was hoping, I can do something like</p>
<pre><code>handleEvent(event1, Handler::function1, Handler::function2);
handleEvent(event2, Handler::function3, Handler::function4);
</code></pre>
<p>that will somehow call functions (1 or 2) or (3 or 4), but I'm somehow not able to solve it to my satisfaction.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T08:22:05.990",
"Id": "505053",
"Score": "0",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T08:23:03.803",
"Id": "505054",
"Score": "1",
"body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T08:23:33.260",
"Id": "505055",
"Score": "0",
"body": "FYI: pseudocode is off-topic."
}
] |
[
{
"body": "<p>First, lets use inheritance. We will inherit the specific event types from the event interface.</p>\n<pre><code>interface Event {}\n\nclass EventType1 implements Event{}\n\nclass EventType2 implements Event{}\n</code></pre>\n<p>Secondly, lets define the type of functions that we will call in the handleEvent() method. In this case it is <code>Consumer<Event></code></p>\n<p>Now our handleEvent() function will look like this</p>\n<pre><code>void handleEvent(Event event, \n Consumer<Event> option1, \n Consumer<Event> option2) {\n if (someCheck()) {\n option1.accept(event);\n } else {\n option2.accept(event);\n }\n}\n\n</code></pre>\n<p>Now we can call this function and pass instance of event interface and two lambdas or method references</p>\n<pre><code>Handler.handleEvent(new EventType1(),\n event -> {\n //do something\n }, \n event -> {\n //do something else;\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T13:08:44.910",
"Id": "505070",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T13:28:23.510",
"Id": "505072",
"Score": "1",
"body": "@TobySpeight I may have misunderstood something, but the author asked a question that I answered. He asked how to do what he wants, I showed how it can be done. If the question itself or my answer is irrelevant for this site, then you need to close it and forget about it. Sorry, maybe I should read the rules carefully. However, I provided assistance to the author."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T15:54:31.330",
"Id": "505077",
"Score": "0",
"body": "The question is off-topic (psuedo/hypothetical/example), so you would have been better leaving this one unanswered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T16:07:02.793",
"Id": "505078",
"Score": "0",
"body": "Thank you, I understood"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T12:38:01.630",
"Id": "255885",
"ParentId": "255878",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T08:12:09.873",
"Id": "255878",
"Score": "0",
"Tags": [
"java"
],
"Title": "How to use lambdas in \"template\""
}
|
255878
|
<p>As part of my NLP project at work, I want to loop over all files that are either PDF of docx in the same directory. The end purpose is to create a dataframe with text content of the files in one column and filename in another column. So I wrote a loop to open them up, extract the text, add it to a list as below:</p>
<pre><code>import docx
import PyPDF2
#wordfile
def ReadingText(filename):
doc=docx.Document(filename)
comp = []
for par in doc.paragraphs:
comp.append(par.text)
return '\n' .join(comp)
#PDF files
def Readingpdf(pdfname):
pdfRead=PyPDF2.PdfFileReader(pdfname)
comp = ""
for i in range(pdfRead.getNumPages()):
comp += pdfRead.getPage(i).extractText()
return comp
</code></pre>
<p>After that I will specify directory and perform the loop as below:</p>
<pre><code>directory= "my directory"
all_together = []
name = []
for filename in os.listdir(directory):
if filename.endswith(".docx"):
f = ReadingText(filename)
all_together.append(f)
name.append(filename)
elif filename.endswith(".pdf"):
try:
pdf = Readingpdf(filename)
all_together.append(pdf)
name.append(filename)
except:
pass
df = pd.DataFrame({"article":name,"text":all_together})
df.head(10)
</code></pre>
<p>It is doing the job, but I really want to develop myself so I want to know your opinion - be as harsh as you can.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T08:30:53.393",
"Id": "255879",
"Score": "2",
"Tags": [
"python",
"machine-learning",
"natural-language-processing"
],
"Title": "Looping over files to create a dataframe"
}
|
255879
|
<p>I use the SUBSTITUTE() function in my VBA code.</p>
<p>In Excel formula, we can nest it as shown in the thread below:</p>
<p><a href="https://stackoverflow.com/questions/22313965/how-can-i-combine-multiple-nested-substitute-functions-in-excel/22314382">https://stackoverflow.com/questions/22313965/how-can-i-combine-multiple-nested-substitute-functions-in-excel/22314382</a></p>
<p>How can we do it in VBA Excel code?</p>
<p>How can I make my code smarter?</p>
<pre><code> For Each cell In rng
cell = WorksheetFunction.Substitute(cell, " ", " ", 25)
cell = WorksheetFunction.Substitute(cell, " ", " ", 24)
cell = WorksheetFunction.Substitute(cell, " ", " ", 23)
Next
</code></pre>
|
[] |
[
{
"body": "<p>You do not want to read and write the cell multiple times. You only do a read and a write. You also need to check if the cell has a string. There is no point in running the replace on numbers or errors. Something like:</p>\n<pre><code>Dim v As Variant\nDim i As Long\nDim oldLen As Long\n\nFor Each cell In rng\n v = cell.Value2\n If VarType(v) = vbString Then\n oldLen = Len(v)\n For i = 25 To 23 Step -1\n v = WorksheetFunction.Substitute(v, " ", " ", i)\n Next i\n If Len(v) <> oldLen Then cell.Value2 = v\n End If\nNext\n</code></pre>\n<p>Or, if you want to be efficient then you read the range into array and replace the whole thing in one go:</p>\n<pre><code>Dim rngArea As Range\nDim arr() As Variant\nDim i As Long\nDim j As Long\nDim lastRow As Long\nDim hasChanged As Boolean\nDim v As Variant\nDim oldLen As Long\n\nFor Each rngArea In rng.Areas\n 'Read range into array of values\n If rngArea.Count > 1 Then\n arr = rngArea.Value2\n Else\n ReDim arr(1 To 1, 1 To 1)\n arr(1, 1) = rngArea.Value2\n End If\n \n i = 1\n j = 1\n lastRow = UBound(arr, 1)\n hasChanged = False\n For Each v In arr 'Traverse the 2D array column-wise\n If VarType(v) = vbString Then\n oldLen = Len(v)\n For i = 25 To 23 Step -1\n v = WorksheetFunction.Substitute(v, " ", " ", i)\n Next i\n If Len(v) <> oldLen Then\n arr(i, j) = v\n hasChanged = True\n End If\n End If\n i = i + 1\n If i > lastRow Then\n i = 1\n j = j + 1\n End If\n Next v\n If hasChanged Then\n rngArea.Value2 = arr\n End If\nNext rngArea\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T12:35:08.410",
"Id": "255884",
"ParentId": "255883",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255884",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T10:57:56.150",
"Id": "255883",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "VBA Excel substitute function for multiple conditions at once"
}
|
255883
|
<p>Input:</p>
<pre><code>$input = [
'category' => [
'1' => [
'name' => 'c1',
'attribute' => [
'1' => [
'name' => 'a1',
'option' => [
'1' => [
'name' => 'o1'
],
'2' => [
'name' => 'o2'
]
]
],
'2' => [
'name' => 'a2',
'option' => [
'3' => [
'name' => 'o3'
],
'4' => [
'name' => 'o4'
]
]
]
]
],
'2' => [
'name' => 'c2',
'attribute' => [
'3' => [
'name' => 'a3',
'option' => [
'5' => [
'name' => 'o5'
],
'6' => [
'name' => 'o6'
]
]
],
'4' => [
'name' => 'a4',
'option' => [
'7' => [
'name' => 'o7'
],
'8' => [
'name' => 'o8'
]
]
]
]
]
]
];
</code></pre>
<p>Output:</p>
<pre><code>$data = [
['category' => 1, 'categoryname' => 'c1', 'attribute' => 1, 'attributename' => 'a1', 'option' => 1, 'optionname' => 'o1'],
['category' => 1, 'categoryname' => 'c1', 'attribute' => 1, 'attributename' => 'a1', 'option' => 2, 'optionname' => 'o2'],
['category' => 1, 'categoryname' => 'c1', 'attribute' => 2, 'attributename' => 'a2', 'option' => 3, 'optionname' => 'o3'],
['category' => 1, 'categoryname' => 'c1', 'attribute' => 2, 'attributename' => 'a2', 'option' => 4, 'optionname' => 'o4'],
['category' => 2, 'categoryname' => 'c2', 'attribute' => 3, 'attributename' => 'a3', 'option' => 5, 'optionname' => 'o5'],
['category' => 2, 'categoryname' => 'c2', 'attribute' => 3, 'attributename' => 'a3', 'option' => 6, 'optionname' => 'o6'],
['category' => 2, 'categoryname' => 'c2', 'attribute' => 4, 'attributename' => 'a4', 'option' => 7, 'optionname' => 'o7'],
['category' => 2, 'categoryname' => 'c2', 'attribute' => 4, 'attributename' => 'a4', 'option' => 8, 'optionname' => 'o8'],
];
</code></pre>
<p>Method I used:</p>
<pre><code>$final = [];
foreach ($input as $k => $d) {
foreach ($d as $ki => $i) {
foreach ($i['attribute'] as $ka => $a) {
foreach ($a['option'] as $ko => $o) {
array_push($final, ['category' => $ki, 'categoryname' => $i['name'], 'attribute' => $ka, 'attributename' => $a['name'], 'option' => $ko, 'optionname' => $o['name']]);
};
}
}
};
</code></pre>
<p>I want to convert the <code>$input(INPUT)</code> data into <code>$data(OUTPUT)</code>. I mentioned my method which I used. Is it the best way we can use or is there any better option in terms of faster execution? What would be a better approach, or is it possible to just convert it into a one-liner?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T16:19:30.523",
"Id": "505081",
"Score": "1",
"body": "Welcome to Code Review! Where does this data come from? Does it come from a database, file, API, etc.? Is it a data source that you are able to control the format and/or the queries of?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T16:38:15.120",
"Id": "505082",
"Score": "0",
"body": "No, for now its just an array of data. Maybe in future i might want to do this with database. But for now its just an array."
}
] |
[
{
"body": "<p>As long as this input array is static in its depth and structure, the best and fastest technique (due to lowest overhead) is to use old-school loops.</p>\n<p>Beyond that, I would:</p>\n<ol>\n<li>Not declare variable that will not be used</li>\n<li>Use square brace pushing syntax</li>\n<li>Avoid excessively wide lines of code which demand the developer to horizontally scroll</li>\n<li>Use words as variable names to make your code more readable</li>\n</ol>\n<p>Code: (<a href=\"https://3v4l.org/YjEPg\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$final = [];\nforeach ($categorizedOptions as $categories) {\n foreach ($categories as $categoryId => $category) {\n foreach ($category['attribute'] as $attributeId => $attribute) {\n foreach ($attribute['option'] as $optionId => $option) {\n $final[] = [\n 'category' => $categoryId,\n 'categoryname' => $category['name'],\n 'attribute' => $attributeId,\n 'attributename' => $attribute['name'],\n 'option' => $optionId,\n 'optionname' => $option['name']\n ];\n }\n }\n }\n}\n</code></pre>\n<p>Don't worry with trying to convert this code into some sexy one-liner. Trying to do so with recursion or nested functions will make your code ugly and negatively impact performance.</p>\n<p>Even trying to get fancy with "array destructuring" and a <code>compact()</code> call don't look worth the effort. (<a href=\"https://3v4l.org/lYgYH\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T20:45:35.173",
"Id": "255898",
"ParentId": "255891",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255898",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T15:13:08.763",
"Id": "255891",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "Converting multi-dimensional array into row data"
}
|
255891
|
<p>I wrote this code to find opposites of words (i.e., words backwards). Input is a list of words. If this list contains a word + its opposite, then it should form a pair. The output should be a list of tuples (pairs).</p>
<p>The output should:</p>
<ul>
<li>contain every pair of words only once - it should contain either ('reed', 'deer') or ('deer', 'reed'), but not both.</li>
<li>not contain palindromes (words which are opposite to themselves) - e.g. 'refer'</li>
</ul>
<pre class="lang-python prettyprint-override"><code>def find_opposites(lst):
if lst == [] or len(lst) == 1:
return []
else:
opposites = [] # contains all words backwards (except palindromes)
result = []
for word in lst:
if word != word[::-1]: # avoid palindromes
opposites.append(word[::-1])
for word in opposites:
if word in lst:
# if word in both opposites list and original list,
# then it should form a pair with its opposite
tup = (word[::-1], word) # create tuple
if tup[::-1] not in result: # append tuple only if its opposite in not already in result
result.append(tup)
return result
</code></pre>
<p>I have tried to substitute the list opposites with a dictionary as I know lists are slower to process, but it still takes a very long time.</p>
<p>Please let me know if you have any ideas on how to make it run faster, as it takes ages when I run on my corpora which contains over 11.000 words. Thanks a lot :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T17:22:13.393",
"Id": "505087",
"Score": "2",
"body": "Please do not update the code in your question after receiving 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)*. Once a question has a first answer, that's the version all answers should be reviewing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T07:02:25.843",
"Id": "505106",
"Score": "0",
"body": "`I have tried to substitute the list opposites with a dictionary` close, very close :/ `I know lists are slower to process` lists are simpler, and there are things (like iteration) they're faster at. Dictionaries are faster at membership tests, for one thing, but look at which \"collection\" you iterate and which you check membership in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T08:26:23.757",
"Id": "505112",
"Score": "0",
"body": "(If this was tagged [tag:algorithm] (there is no tag *data structure*?!), I was tempted to suggest using ordering as an alternative to data structures supporting quasi-constant *in*.)"
}
] |
[
{
"body": "<p>The part <code>if word in lst</code> basically uses a for-loop to check the entire list again, which takes on average 11000/2=5500 tries. So you'll have 11000*5500 = 60.500.000 pairwise checks. That shouldn't take <em>ages</em> but still isn't efficient. There's also the checking of the result, which is a growing list so that takes longer after every result.</p>\n<p>If you used a dictionary, you should be getting better results, but only if you search on the keys.</p>\n<p>I think it would be clearer if you just convert <code>lst</code> and <code>result</code> to a set. Sets store unique values and are well-equipped to do fast searching.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T16:09:15.790",
"Id": "505079",
"Score": "1",
"body": "Not only are sets suited to fast searching, but set **intersection** (e.g. `inputs & reversed`) is the perfect tool for the exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T17:04:00.260",
"Id": "505085",
"Score": "0",
"body": "thanks for your answer. I tried with sets and it took even longer, but I am not used to using sets so I must have done something wrong. I then solved using a dictionary (I posted my solution as edit in the question)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T15:39:58.927",
"Id": "255893",
"ParentId": "255892",
"Score": "5"
}
},
{
"body": "<h2>Bug</h2>\n<p>Your function does not filter out duplicate pairs.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> words = ["test", "tset", "test", "tset"]\n>>> find_opposites(words)\n[('test', 'tset'), ('test', 'tset')]\n</code></pre>\n<h2>Improvements</h2>\n<ul>\n<li>Comprehension:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code># This part\nopposites = [] # contains all words backwards (except palindromes)\nresult = []\nfor word in lst: \n if word != word[::-1]: # avoid palindromes\n opposites.append(word[::-1])\n\n# can be rewritten as\nopposites = {word[::-1] for word in lst if word != word[::-1]}\n</code></pre>\n<p><code>word[::-1]</code> reverses the word, as you already used it.<br />\n<code>if word != word[::-1]</code> ensures palindromes are removed.<br />\n<code>{x for x in y}</code> is a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">comprehension</a>. More specifically, it is a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"noreferrer\">set</a>, which automatically removes duplicates.</p>\n<ul>\n<li><p>Membership tests<br />\nMembership tests like <code>a in b</code> are fast on data structures like sets or dictionaries because they use hash tables. On lists, every element is compared, which takes a lot of time.</p>\n</li>\n<li><p>Putting everything together<br />\nHere is my solution:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def find_opposites_new(lst):\n # create a set of reversed words of the original words, without palindromes\n backwards = {word[::-1] for word in lst if word != word[::-1]}\n # initiate the result list we want to return\n result = []\n # initiate the set we use to check if a word or its reversed version is already\n # in the result list\n check_set = set()\n # loop over all words\n for word in lst:\n # if the word is also in the reversed words and not in the results already\n if word in backwards and word not in check_set:\n # reverse the word\n b_word = word[::-1]\n # add the word and its reversed version to the check set\n check_set.add(word)\n check_set.add(b_word)\n # add the tuple to the results\n result.append((word, b_word))\n return result\n</code></pre>\n<ul>\n<li>Test on random words</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport time\nfrom string import ascii_lowercase\n\n# list of 10000 random words of length 3 to 20, will probably have some reverse words\nrandom_words = [\n "".join(random.choices(population=ascii_lowercase, k=random.randint(3, 20)))\n for _ in range(10000)\n]\n\n# measure time at starts and ends\nstart = time.time()\nfind_opposites(words)\nend = time.time()\n\nstart_new = time.time()\nfind_opposites_new(words)\nend_new = time.time()\n\n# calculate times\nprint(f"old {end-start:} sec")\nprint(f"new {end_new-start_new:} sec")\n# old 1.2763020992279053 sec\n# new 0.00501561164855957 sec\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T07:34:43.540",
"Id": "505109",
"Score": "1",
"body": "While behaviour in presence of duplicate words in the input is unspecified (`[\"test\", \"tset\", \"test\"]`), note that the original does *not* show a pair and its reverse."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T18:20:52.330",
"Id": "255896",
"ParentId": "255892",
"Score": "7"
}
},
{
"body": "<p>As others have mentioned, your program runs slowly because it is doing a lot of membership tests against fairly large lists, which is expensive. If you replace your lists with sets, that alone should improve performance by quite a bit.</p>\n<p>Creating a set from the input list of words is also important to ensure the correctness of your algorithm. As @Tweakimp pointed out, we only want to find pairs of opposites within a collection of <em>unique</em> words, to avoid the possibility of duplicates of the same pair from showing up in the results.</p>\n<p>Below is a simple algorithm which calculates all the pairs in one pass.</p>\n<ul>\n<li>Create <code>unique_words: set[str]</code> from the input list of words.</li>\n<li>Create <code>results: list[tuple[str, str]]</code> for our results. This will be our return value.</li>\n<li>Create <code>words_seen: set[str]</code> to track which words from <code>unique_words</code> we've seen so far.</li>\n<li>Iterate over <code>unique_words</code>; for each <code>word</code>, also calculate <code>reversed_word</code>.\n<ul>\n<li>If we haven't seen <code>reversed_word</code> yet, then we don't know if <code>word</code> has a matching pair (yet). So we add <code>word</code> to <code>words_seen</code>.</li>\n<li>If we <strong>have</strong> seen <code>reversed_word</code>, then we just found a matching pair, so we append <code>(word, reversed_word)</code> to <code>results</code>.</li>\n</ul>\n</li>\n<li>Return <code>results</code>.</li>\n</ul>\n<pre class=\"lang-python prettyprint-override\"><code>def find_opposites(words):\n unique_words = set(words)\n\n results = []\n words_seen = set()\n\n for word in unique_words:\n reversed_word = word[::-1]\n\n # if we have already seen reversed_word,\n # then we found a new pair of opposites: (word, reversed_word)\n if reversed_word in words_seen:\n results.append((word, reversed_word))\n else:\n words_seen.add(word)\n\n return results\n</code></pre>\n<p>Because we start with the set <code>unique_words</code>, we actually don't need to check explicitly for the palindrome case. This is because in order for a palindrome to end up in <code>results</code>, there would need to be at least two instances of the same palindrome in <code>unique_words</code>, which is impossible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T05:41:45.960",
"Id": "505102",
"Score": "0",
"body": "Simpler and also a bit faster than my solution, well done :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T23:55:23.860",
"Id": "255904",
"ParentId": "255892",
"Score": "9"
}
},
{
"body": "<p>This code is fast and simple. It takes around 5ms to find 15-odd pairs in 10,000 words.</p>\n<p>The speed comes from using a set lookup and comprehensions.</p>\n<pre><code>def find_opposites_set1(words):\n reversed_words = [word[::-1] for word in words]\n unique_reversed_words = set(reversed_words)\n return [\n (word, reversed_word) \n for word, reversed_word\n in zip(words, reversed_words)\n if word in unique_reversed_words and word < reversed_word\n ]\n</code></pre>\n<p>Some explanations:</p>\n<ol>\n<li><p>set lookup for reversed words-- fast to create and much faster to check membership (<code>if word in unique_reversed_words</code>) than scanning a list</p>\n</li>\n<li><p><code>if ... and word < reversed_word</code> removes duplicates and palindromes from the results (thanks to <a href=\"https://codereview.stackexchange.com/a/255945/237575\">Eric Duminil's answer</a> for this idea.) This works so long as the original word list contains unique words</p>\n</li>\n<li><p>Boolean <code>and</code> is a short-circuiting operator in Python so <code>and word < reversed_word</code> will only be executed 15 or so times, rather than 10,000 times if the palindromes are weeded out before the pairs are identified</p>\n</li>\n<li><p><code>zip()</code> pairs words and their reverse together to avoid recalculating <code>word[::-1]</code></p>\n</li>\n</ol>\n<p>A slightly different method uses set intersection to find pairs quickly but needs to recalculate a few of the word reversals. In practice the two solutions seem to perform similarly:</p>\n<pre><code>def find_opposites_set2(words):\n reversed_words = (word[::-1] for word in words)\n paired = set(words).intersection(reversed_words)\n return [\n (word, reversed_word)\n for word, reversed_word\n in zip(paired, (word[::-1] for word in paired))\n if word < reversed_word\n ]\n</code></pre>\n<p>This second algorithm will work if the original word list contains duplicate words. So, for example, you could apply this function to the text of a book to see how many reversed words occur naturally in a text. Here's the result of applying it to 153,000 words from the <a href=\"https://www.gutenberg.org/files/64576/64576-0.txt\" rel=\"nofollow noreferrer\">Seneca Minor Dialogues</a> on Project Gutenberg:</p>\n<pre><code>(runtime 0.3s for 153,000 words)\n\n[('brag', 'garb'), ('now', 'won'), ('dog', 'god'), ('as', 'sa'), ('is', 'si'),\n ('NO', 'ON'), ('evil', 'live'), ('saw', 'was'), ('doom', 'mood'), ('en', 'ne'),\n ('draw', 'ward'), ('al', 'la'), ('pas', 'sap'), ('dam', 'mad'), ('no', 'on'), \n ('are', 'era')]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:00:00.373",
"Id": "255921",
"ParentId": "255892",
"Score": "3"
}
},
{
"body": "<p>You could simply compare the word and its reverse with <code>word < word[::-1]</code> in order to avoid palindromes and duplicate entries.</p>\n<p>If <code>words</code> is a set containing all the possible words, you can create a set of results directly:</p>\n<pre><code>mirror_words = {w for w in words if w < w[::-1] and w[::-1] in words}\n</code></pre>\n<p>After initializing <code>words</code> with:</p>\n<pre><code>with open('/usr/share/dict/american-english') as wordbook:\n words = {word.strip() for word in wordbook}\n</code></pre>\n<p>The above line returns:</p>\n<blockquote>\n<p>{'paws', 'buns', 'gut', 'rebut', 'maws', 'bus', 'pools', 'saw', 'bats', 'mar', 'naps', 'deer', 'spay', 'deeps', 'bat', 'flow', 'straw', 'but', 'abut', 'nuts', 'cod', 'diaper', 'eh', 'dray', 'keel', 'debut', 'pots', 'flog', 'sports', 'ergo', 'pot', 'pas', 'no', 'guns', 'spot', 'bard', 'keels', 'ho', 'may', 'dial', 'gals', 'don', 'agar', 'pat', 'dam', 'ajar', 'leper', 'lap', 'pets', 'dim', 'snips', 'lever', 'leer', 'sleets', 'mart', 'spit', 'now', 'sway', 'deliver', 'sprat', 'parts', 'gnat', 'buts', 'nap', 'bad', 'pis', 'are', 'gulp', 'nit', 'dew', 'way', 'smart', 'deep', 'raw', 'pus', 'peels', 'net', 'snot', 'sloops', 'girt', 'remit', 'got', 'ah', 'looter', 'loop', 'emit', 'redraw', 'not', 'emir', 'part', 'door', 'ares', 'lop', 'ate', 'eviler', 'dos', 'am', 'bin', 'decal', 'avid', 'brag', 'bud', 'meet', 'nips', 'mu', 'snaps', 'gal', 'loops', 'desserts', 'pans', 'nip', 'bag', 'pols', 'hoop', 'em', 'raps', 'denim', 'ports', 'bur', 'draws', 'saps', 'pit', 'tow', 'pees', 'bog', 'stew', 'ban', 'drawer', 'it', 'par', 'loots', 'doom', 'bun', 'denier', 'liar', 'draw', 'gnus', 'rat', 'bed', 'burg', 'dog', 'spots', 'pals', 'lager', 'gel', 'eel', 'keep', 'mat', 'snoops', 'dual', 'devil', 'gem', 'mils', 'edit', 'tort', 'rats', 'moor', 'pay', 'rot', 'new', 'per', 'pins', 'spat', 'snit', 'gum', 'loot', 'gums', 'decaf', 'gas', 'nut', 'fer', 'knits', 'evil'}</p>\n</blockquote>\n<p>Note that 'paws' and 'evil' are included, but not 'swap' or 'live'.</p>\n<p>If you want, you can sort it and show the pairs:</p>\n<pre><code>sorted((w, w[::-1]) for w in mirror_words)\n</code></pre>\n<blockquote>\n<p>[('abut', 'tuba'), ('agar', 'raga'), ('ah', 'ha'), ('ajar', 'raja'), ('am', 'ma'), ('are', 'era'), ('ares', 'sera'), ('ate', 'eta'), ('avid', 'diva'), ('bad', 'dab'), ('bag', 'gab'), ('ban', 'nab'), ('bard', 'drab'), ('bat', 'tab'), ('bats', 'stab'), ('bed', 'deb'), ('bin', 'nib'), ('bog', 'gob'), ('brag', 'garb'), ('bud', 'dub'), ('bun', 'nub'), ('buns', 'snub'), ('bur', 'rub'), ('burg', 'grub'), ('bus', 'sub'), ('but', 'tub'), ('buts', 'stub'), ('cod', 'doc'), ('dam', 'mad'), ('debut', 'tubed'), ('decaf', 'faced'), ('decal', 'laced'), ('deep', 'peed'), ('deeps', 'speed'), ('deer', 'reed'), ('deliver', 'reviled'), ('denier', 'reined'), ('denim', 'mined'), ('desserts', 'stressed'), ('devil', 'lived'), ('dew', 'wed'), ...</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T04:08:17.187",
"Id": "505211",
"Score": "0",
"body": "(To pick a nit, a *set of words with differing reverse present* isn't quite `a list of tuples`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T09:13:32.780",
"Id": "505217",
"Score": "0",
"body": "@greybeard unless I'm missing something, my last line of code outputs the desired result, doesn't it? Mirror words is indeed a set and has a different format, but I still wanted to mention it because it's easy to create, it should be efficient and it doesn't require an \"already seen\" set. And it basically contains the exact same information as the desired output, just in a more compact format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T18:02:51.950",
"Id": "505702",
"Score": "0",
"body": "Really nice solution-- simple and performs as well as any other answer here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T14:22:29.140",
"Id": "255945",
"ParentId": "255892",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T15:15:04.263",
"Id": "255892",
"Score": "11",
"Tags": [
"python",
"performance",
"python-3.x",
"time-limit-exceeded",
"timeout"
],
"Title": "Finding reversed word pairs"
}
|
255892
|
<p>Here is my code. Let me describe what I do here. I have 7kg soaps, and 2kg soaps. And I have total kg that mean how many kg soaps I need. I should use 7kg soaps first, if there is no need I shouldn't use 2 kg soaps. If I don't use any 2kg soaps, it must return -1, if I use 2 kg soaps it must return the amount of how many of them I use. I have <code>prepareCargoPacket(int 7kg soap, int 2 kg soap, int totalKg)</code>.</p>
<p>For example, <code>prepareCargoPacket(2,2,16);</code> return 1s since I use 2kg soaps one time. <code>prepareCargoPacket(1,3,10);</code> returns -1 because I can't get 10kg from these values, and I can't use 2kg soaps</p>
<pre><code>package com.bit32.cargocalculation;
public class CargoCalculation {
/**
* Returns how many 2Kgs soap we need to use
*
* @param count7Kg -> count of how many 7Kgs soaps we have
* @param count2Kg -> count of how many 2Kgs soaps we have
* @param totalKg -> the needed Kg I have to get
* @return
*/
public int prepareCargoPacket(int count7Kg, int count2Kg, int totalKg) {
int solution = -1; // if there is no answer, or no need for 2Kgs soaps, the answer is -1
// if we have 7Kg ones many more than totalKg, we should decrease it to get from 2Kgs.
if (7*count7Kg > totalKg) {
return prepareCargoPacket(count7Kg-1, count2Kg, totalKg);
// if we have enough 7Kgs that are equal to totalKg, we will not use 2Kgs.
} else if (7*count7Kg == totalKg) {
return solution; // solution = -1
// if we have 7Kgs less than totalKg
} else {
// currentTotalKg is equal to the amount of Kg that we can use for 2Kgs
int currentTotalKg;
for (int i = count7Kg; i>=0; i--) {
currentTotalKg = totalKg - 7*i;
if (currentTotalKg % 2 == 0 && count2Kg*2 >= currentTotalKg) {
solution = currentTotalKg/2;
break;
}
return solution;
}
}
return solution;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T20:14:27.523",
"Id": "505090",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly. It will probably be something about cargo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T23:00:04.683",
"Id": "505092",
"Score": "3",
"body": "(I found the required return values followed to the letter. I still wonder if *required amount could be satisfied using zero 2 kg soaps* shouldn't return 0, leaving -1 for *no way to satisfy request*.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:04:20.577",
"Id": "505116",
"Score": "0",
"body": "To be honest, you are right. I thought so too. But someone asked me to solve this and he said i should return -1 if i dont use 2kgs. But i think its better if i can get total Kgs, without using 2kgs, it should return 0"
}
] |
[
{
"body": "<p>First of all, your code doesn't actually work for some cases. The <code>return</code> statement in the <code>for</code> loop causes the loop to only ever run once. This means your function doesn't find a solution for <code>prepareCargoPacket(2, 10, 12)</code> (it tries with 1 7kg soap, fails the <code>if</code> check since 5 isn't a multiple of 2, then returns <code>-1</code> without ever trying with no 7kg soaps). Removing that <code>return</code> fixes it.</p>\n<p>Another thing I want to point out is that your way to cap the number of 7kg soaps is really not very efficient. If you need to make a total weight of 6kg when you have 200000 7kg soaps available, your function will call itself 200000 times. This is not ideal, for multiple reasons. Not only is it a lot of steps (each of which takes some amount of time), but the program will also internally keep track of each function call in the call stack, and that thing can only get so big before your program crashes with a <code>java.lang.StackOverflowError</code>.</p>\n<p>A way around that is to notice that if you have more than <code>totalKg / 7</code> 7kg soaps, the total weight is already too high. So if you have too many 7kg soaps at the start, you don't need to keep trying with 1 less each time, because <code>totalKg / 7</code> just gives you a nice upper bound.</p>\n<p>To finish off with some nitpicking, I'm not a huge fan of repeating the weights of the soaps all over the place like that. If the person who wants this software comes up to you and says "Hi, sorry, we switched from 7kg soaps to 5kg soaps, can you update the program for us?" it would be annoying to replace the weight everywhere, and there'd be a risk of missing a place. A nicer approach could be replacing the numbers with constant variables, maybe something like <code>final int HEAVY_WEIGHT = 7;</code> and <code>final int LIGHT_WEIGHT = 2;</code>? That way, if the weights need changing, it only happens in one place. At that point I might also look into renaming the input parameters to something like <code>heavyAvailable</code> and <code>lightAvailable</code> to match those while I'm at it.</p>\n<h2>A few more thoughts</h2>\n<p>I looked some more, and came up with a few more comments.</p>\n<p>Apart from the issue with there possibly being a lot of function calls, having the function call itself at all feels like it makes the logic a bit harder to follow. I'd like to restructure it so that that isn't necessary, with that initial check being used not to re-enter the function, but to determine where the loop starts.</p>\n<p>Another, fairly minor issue is that this function keeps going for longer that it might have to even though it should know it won't find a solution. For example, if called as <code>prepareCargoPacket(5, 0, 36)</code> we get to the loop, notice we don't have enough 2kg soaps to reach the weight of 1kg that's missing. But then we continue to check if we can make 8kg instead. Which we can't since we have too few soaps. So we go on to check 15kg instead. But we can't make that either, so we check if we can make 22kg... Now imagine if instead of starting at 5 and 36 we'd started at something like 142,857,142 and 1,000,000,000.<br />\nWell, you don't have to imagine. I tested it, and it was still really fast. Never underestimate a computer's ability to do math quickly. Still, it can matter if the loop contains anything more complicated than a few basic math operators and a few <code>if</code>s, so I'm bringing it up for future reference anyway. I also feel like switching the loop condition to take that into account also makes the code a bit cleaner, but it also arguably becomes a bit less obvious why it's written the way it is, so it might not actually be an improvement.</p>\n<p>The solution variable doesn't seem entirely necessary to be honest. Each time the function returns, it either returns <code>-1</code>, or it changes <code>solution</code> for the first time and then immediately returns. At that point, I might get rid of that variable to save the reader from having to keep track of whether it's been updated. That's a matter of taste, though, there are definitely people who'd disagree with me on that.</p>\n<p>Finally, since I've already done some nitpicking about variable names, I might as well complain about the last few. <code>totalKg</code> doesn't feel as descriptive as it could be. It and <code>currentTotalKg</code> are also a bit confusable, because "the total" and "the current total" don't really feel all that distinct to me - while that <em>is</em> sometimes the best way to describe two values, we might want to look for something that makes their purposes even more obvious. Going by what they're doing, <code>totalKg</code> might be more accurately described as the <code>goalWeight</code> or <code>targetWeight</code>, and since <code>currentTotalKg</code> is the amount we're missing to be able to reach that we might call that <code>missingWeight</code> or <code>remainingWeight</code> perhaps?</p>\n<p>Taking all that into account, I might write something a bit like</p>\n<pre><code>package com.bit32.cargocalculation;\n\npublic class CargoCalculation {\n\n public static final int HEAVY_WEIGHT = 7;\n public static final int LIGHT_WEIGHT = 2;\n\n /**\n * Calculates how many lightweight soaps we need to use to reach exactly the target weight, if possible\n * If no lightweight soaps are required, or if the target weight can't be reached, returns -1\n *\n * @param heavyAvailable The number of heavy soaps that can be used\n * @param lightAvailable The number of light soaps that can be used\n * @param targetWeight The desired sum of the weights of all the soaps\n * @return\n */\n public int prepareCargoPacket(int heavyAvailable, int lightAvailable, int targetWeight) {\n int maxHeavyUsed;\n if (HEAVY_WEIGHT * heavyAvailable > targetWeight) {\n maxHeavyUsed = targetWeight / HEAVY_WEIGHT;\n } else {\n maxHeavyUsed = heavyAvailable;\n }\n\n // Loop until we find a solution, or until we know we can't\n for (int remainingWeight = targetWeight - HEAVY_WEIGHT * maxHeavyUsed;\n remainingWeight <= LIGHT_WEIGHT * lightAvailable;\n remainingWeight += HEAVY_WEIGHT) {\n if (remainingWeight == 0) {\n // Special case: We have to return -1 if we don't need light soaps\n return -1;\n } else if (remainingWeight % LIGHT_WEIGHT == 0 &&\n lightAvailable * LIGHT_WEIGHT >= remainingWeight) {\n return remainingWeight / LIGHT_WEIGHT;\n }\n }\n\n // No solution\n return -1;\n }\n}\n</code></pre>\n<p>Though as I said if you think it's clearer to write the loop as <code>for (int i = maxHeavyUsed; i >= 0; i--)</code> (and then define <code>remainingWeight</code> inside the loop), you can do that instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:25:04.997",
"Id": "505117",
"Score": "0",
"body": "Hello, I thank you so much.!! Your reply is very helpful. You are absolutely right. I should change my variable names as you said. You found my mistake, when you put that values it returns -1, but it should check when i dont have any 7kg soaps, ill correct it now! Thanks so much. Do you have more recommendations for me? I am new to java programming. I will be so glad if you can help more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:48:47.417",
"Id": "505121",
"Score": "0",
"body": "Hello Sara. I changed my code for not keeping trying with 1 less each time. `if(HEAVY_WEIGHT*heavyAvailable > totalWeight) {\n heavyAvailable = totalWeight/HEAVY_WEIGHT + 1;\n \n return prepareCargoPacket(heavyAvailable-1, lightAvailable, totalWeight);` Have I done it correctly you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T17:39:40.600",
"Id": "505152",
"Score": "1",
"body": "@Semih It's an improvement for sure, but I feel like for this the neatest approach doesn't involve the function calling itself at all. I updated my review with a few more thoughts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T10:46:36.657",
"Id": "505314",
"Score": "1",
"body": "Hello, thank you so much, you help so much, your code is great! How can I get better at naming variables etc? Does that happen just by experience? Btw this question was asked me for job interview. And i think i just should let it stay as it was , i just changed my variable names as you said. Since its job interview, your last code seemed to me a bit more experienced, so i didnt want to change it, but im trying to understand your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T01:45:52.660",
"Id": "505354",
"Score": "1",
"body": "I'd say it's mostly an experience thing, but for learning to write code that's easy to read and understand (which I'd like to think my code is) it's important to learn what that looks like. When writing code, it's often hard to tell (since you already understand the code without reading it), so I think a good way to practice is to read and/or edit other people's code (or your own code, if it's been a while since you touched it). Over time you'll develop a feeling for what \"good code\" looks like, and then you can try to apply that to code you already understand - including code you're writing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T10:07:24.400",
"Id": "505375",
"Score": "1",
"body": "Thanks for detailed explanation. I really appreciate it. Is there anyway to reach you if i have any questions or if i want any suggestions from you, would it be appropriate for me to text you, on here, or reddit maybe, .. Thanks again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T17:16:49.343",
"Id": "506228",
"Score": "0",
"body": "Hello, I'm trying to learn Java, and Spring Boot. Do you have any online course or something to recommend me? Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T21:41:14.567",
"Id": "506311",
"Score": "1",
"body": "@Semih Hi, sorry, I'm afraid I don't. Also, you're right that this might not be the best place for more questions, so we should probably take this somewhere else. If twitter is fine for you my twitter account should be listed on my stack exchange profile now, but if you'd prefer something else let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T09:01:44.350",
"Id": "506333",
"Score": "0",
"body": "Thank you for answering. I just bought a course on udemy. People say it's good one. Tbh I dont use social media. I mean I just have this stack exchange, reddit, gmail, and linkedin accounts. If either of those may be an option for you, I'd like it if i have any questions to ask you for the future. Thank you again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T19:29:06.267",
"Id": "506453",
"Score": "1",
"body": "@Semih Well, in that case reddit is fine, I'm /u/fendse on there. Hope the udemy course works out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T09:19:04.767",
"Id": "506652",
"Score": "0",
"body": "thank you, for now its going very well. I am just on methods section. Sorry for replying late, i just got online. I texted you there, thank you"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T00:56:44.657",
"Id": "255908",
"ParentId": "255895",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255908",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T17:37:34.957",
"Id": "255895",
"Score": "2",
"Tags": [
"java"
],
"Title": "Combining multiple masses to obtain a desired total mass"
}
|
255895
|
<p><strong>Input</strong></p>
<p>I start with a vector of integers or floats, e.g.:</p>
<pre><code>[10, 100, 20, 5, 50]
</code></pre>
<p><strong>Output</strong></p>
<p>I want to return a list of differences or "deltas" between elements of the sorted version of this vector. Differences are then presented in the same order as the items from the original, unsorted vector.</p>
<p>The above example vector would return, for instance:</p>
<pre><code>[5, 50, 10, 5, 30]
</code></pre>
<p><strong>Procedure</strong></p>
<p>The procedure I have is to:</p>
<ol>
<li>Order the input vector, e.g.,:</li>
</ol>
<pre><code>[5, 10, 20, 50, 100]
</code></pre>
<ol start="2">
<li>Calculate the differences between each pair of elements in the sorted vector (using the first element as-is; i.e., the difference between that value and zero):</li>
</ol>
<pre><code>[5, 5, 10, 30, 50]
</code></pre>
<ol start="3">
<li>Reorder differences by the original index of elements from the input vector:</li>
</ol>
<pre><code>[5, 50, 10, 5, 30]
</code></pre>
<p><strong>Function</strong></p>
<p>I am working in Javascript. This is the code I have written so far:</p>
<pre><code>/**
* Remap input vector into a vector of state-sorted delta scores
*
* @param {Array} 1d array of numbers
* @returns {Array} 1d array of per-element differences sorted by input index indices
*/
remapVectorToIndexSortedDiffs(vector) {
const l = vector.length;
const indices = [...Array(l).keys()];
const vals = indices
.sort((a, b) => vector[a] < vector[b] ? -1 : vector[a] > vector[b] ? 1 : 0 )
.map((d, i) => { const k = indices[i]; const v = vector[k]; return { i:k , d:v }; });
const deltas = new Array(l);
deltas[0] = vals[0];
for (let idx = 1; idx < l; idx++) deltas[idx] = { i : vals[idx].i, d : vals[idx].d - vals[idx - 1].d };
return deltas
.sort((a, b) => (a.i > b.i) ? 1 : -1)
.map((d) => d.d);
}
</code></pre>
<p>I'm working with a large 2D matrix of such vectors and would like to optimize this function as much as possible, for both memory and speed (though speed is higher priority).</p>
<p>Are there ways I can improve this function in Javascript?</p>
|
[] |
[
{
"body": "<h2>Array is not a Vector</h2>\n<p>JavaScript does not have vectors, it uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array\">Array</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a> that can both behave like vectors (grows and shrinks).</p>\n<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array\">Array</a>s can also be sparse [hash map] or dense [flat sequential array].</p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a>s are sparse.</p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a>s do not have a length property</p>\n</li>\n</ul>\n<p>As you have not defined what you mean by <code>vector</code> one must make an assumption in regard to what the variable <code>vector</code> will contain and the general rule for arrays is that they are dense with numeric 0 based indexes.</p>\n<p>My assumption that it is an array is based on the following</p>\n<ul>\n<li><p><strong>Is <code>vector</code> an Array?</strong></p>\n<p>The question's examples show arrays <code>[5, 10, 20, 50, 100]</code> and Objects do not (may not) have a length property.</p>\n</li>\n<li><p><strong>Is <code>vector</code> a dense array?</strong></p>\n<p>The line <code>= vector.length;</code> would return the last index of a sparse array. eg <code>a = []; a[100] = 1; console.log(a.length);</code> outputs 101 but has only 1 item. Your code would fail if you passed a sparse array.</p>\n</li>\n</ul>\n<p>Once we have established that the input is a standard array we can begin to optimize the function</p>\n<h2>Too complex</h2>\n<p>The first part of the function is overly complex and mostly redundant.</p>\n<h2>Sort</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array sort\">Array.sort</a> is required but can be simplified as follows</p>\n<pre><code>.sort((a,b) => vector[a] - vector[b])\n</code></pre>\n<h2>Tracking sorted position</h2>\n<p>There is no need to track the sort position by creating an object for each item. The sort position is already available in the <code>indices</code> array by index. Eg <code>indices[0]</code> gives the sort position for the first item.</p>\n<p>Thus the need to call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array map\">Array.map</a> and create <code>{i,d}</code> for each item is not needed, however if it were required it could be better</p>\n<h2>Better the map</h2>\n<p>Properties names are very poor and the map function is also too complex. the line</p>\n<blockquote>\n<pre><code>.map((d, i) => { const k = indices[i]; const v = vector[k]; return { i: indices[i] , value: vector[indices[i]] }; });\n</code></pre>\n</blockquote>\n<p>could be be simplified to</p>\n<pre><code>.map(pos => ({pos , value: vector[pos]}));\n</code></pre>\n<h2>Avoid duplicated processing</h2>\n<p>You create the array indices using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array keys\">Array.keys</a> . <code>const indices = [...Array(l).keys()]</code> to get an ordered list of indexes, then lower down you create the array <code>const deltas = new Array(l);</code></p>\n<p>Note that the both lines are based on identical arrays. If you create <code>deltas</code> first and use it to get the keys you can remove one of the created arrays.</p>\n<pre><code> const deltas = new Array(l);\n const indices = [...deltas.keys()];\n</code></pre>\n<h2>Calculate deltas and return</h2>\n<p>There are a lot of changes before we get to the meat of the function so all the rest of your original code can be replaced while considering the following...</p>\n<h3>Changes</h3>\n<ul>\n<li>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for\">for</a> loop can be replaced with the simpler <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. while\">while</a> loop.</li>\n<li>There is no need to create yet another object for each value. Once you have used the sorted positions they can be ignored.</li>\n<li>The final sort and map operations are not required.</li>\n<li>The first entry in the resulting array deltas<code>may not be at position 0 so the array</code>deltas` must be pre-assigned space to avoid creating a sparse array.</li>\n</ul>\n<p><strong>BTW:</strong> Always delimit code blocks, eg <code>for(i = 0; i < 10; i++) foo += i;</code> is better as <code>for(i = 0; i < 10; i++) { foo+=i; }</code></p>\n<h2>Rewrite</h2>\n<p>Changing the overly long function name <code>remapVectorToIndexSortedDiffs</code> with <code>sortedDiffs</code></p>\n<p>The functions complexity (time and storage) is the same,\nhowever its memory use and performance have been improved significantly.</p>\n<pre><code>function sortedDiffs(vector) {\n var i = 0;\n const length = vector.length, deltas = Array(length);\n const idxs = [...deltas.keys()].sort((a, b) => vector[a] - vector[b]);\n deltas[idxs[i]] = vector[idxs[i]];\n while (i++ < length - 1) {\n deltas[idxs[i]] = vector[idxs[i]] - vector[idxs[i - 1]];\n }\n return deltas;\n}\n</code></pre>\n<p>or a less verbose version.</p>\n<pre><code>function sortedDiffs(vecs) {\n var i = 0;\n const len = vecs.length - 1, res = Array(len + 1);\n const idxs = [...res.keys()].sort((a, b) => vecs[a] - vecs[b]);\n res[idxs[i]] = vecs[idxs[i]];\n while (i++ < len) { res[idxs[i]] = vecs[idxs[i]] - vecs[idxs[i - 1]] }\n return res;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T11:17:00.160",
"Id": "255929",
"ParentId": "255899",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255929",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T21:07:58.603",
"Id": "255899",
"Score": "0",
"Tags": [
"javascript",
"sorting",
"hash-map"
],
"Title": "Calculating ordered differences between elements in vector"
}
|
255899
|
<p>I'm learning Python and I'm building a basic madlib generator. The code below works as expected. I'm just wondering if it uses best practice / can be made better.</p>
<pre><code>def intro():
print("Welcome to our madlib generator!")
print("We'll ask you for a serious of words, you'll give us the words, and "
"we'll make a dope ass story out of it!")
print("Let's get some info from you first.")
print("Select the type of madlib you want. ")
madlib_type = input("1. Short Story\n2. Poem\n")
return madlib_type
def user_input():
name = input("Enter a name: ")
color = input("Enter a color: ")
animal = input("Enter an animal: ")
food = input("Enter a food: ")
item = input("Enter an item: ")
adjective = input("Enter an adjective: ")
noun1 = input("Enter a plural noun: ")
noun2 = input("Enter any noun: ")
return [name, color, animal, food, item, adjective, noun1, noun2]
class MadlibGenerator:
def __init__(self, *args):
self.name = args[0].title()
self.color = args[1]
self.animal = args[2]
self.food = args[3]
self.item = args[4]
self.adjective = args[5]
self.noun1 = args[6]
self.noun2 = args[7]
def short_story_generator(self):
print(f"There once was a person named {self.name}. {self.name} LOVED "
f"{self.animal}s. They were {self.name}'s favorite animal.")
print(f"One day, {self.name} was walking down the street wearing "
f"{self.color} pants and a {self.color} shirt. In fact, all of "
f"{self.name}'s ")
print(f"clothes were {self.color}! In one of {self.name}'s hand, "
f"there was a bright green {self.item}. In the other, there was "
f"a big {self.food} that {self.name} was waiting to eat!")
def poem_generator(self):
print(f"Roses are {self.adjective}")
print(f"{self.noun1} are blue")
print(f"I can't start my day without {self.noun2}")
madlib_type = intro()
madlib_input = user_input()
madlib = MadlibGenerator(madlib_input[0], madlib_input[1], madlib_input[2],
madlib_input[3], madlib_input[4], madlib_input[5],
madlib_input[6], madlib_input[7])
if madlib_type == "1":
madlib.short_story_generator()
if madlib_type == "2":
madlib.poem_generator()
</code></pre>
|
[] |
[
{
"body": "<p>You're asking for a lot of words you don't use. It might be nicer to only ask the user for relevant words. Maybe instead of <code>user_input</code> taking no arguments, it could take a list of descriptions like <code>user_input(["a name", "a color", "a different color"])</code> and ask based on those?</p>\n<p>I don't see why the two story generators live in the same class like that. Passing the same data to multiple generators is probably not very useful very often. The functions can just as easily take the words as arguments themselves instead. This doesn't make the idea of a <code>MadlibsGenerator</code> class inappropriate, but the two functions belong to <em>different</em> generators, and the functions' input doesn't need to be directly tied to a generator at all.</p>\n<p>The generators also do two different things each - they both generate the stories and print them. Usually, it would be better to do those separately, in case you maybe want to do something else with the stories as well.</p>\n<p>You don't check if the user provides valid input when selecting which generator to use. If I'm asked to pick 1 or 2 and enter 3, I'd probably expect an error message and maybe an opportunity to try again. Instead, the program just keeps going as usual, except I don't get a fun story at the end.</p>\n<p>Some day, someone else might want to use these functions (or maybe you'll want to use them for something else). They'll probably try importing your file as a module. When they do that, the entire file is run, which right now means the entire madlibs program. That's probably not what they wanted. You can prevent that by placing the program logic inside an <code>if __name__ == "__main__":</code> block, so that it doesn't execute when the file is imported.</p>\n<p>Branching on a string to figure out which generator to use is a bit ugly. Just being able to look it up in a dictionary would be nice, and might also make it easier to add new ones, since we only need to update one place rather than having to worry about keeping <code>intro</code> and the <code>if</code>s in sync.</p>\n<p>But if we don't want to update <code>intro</code> each time we come up with a new generator we still have a problem - it needs to know what to call all the different generators when telling us what our options are. We could put that in the dictionary I mentioned above, or if we're already putting stuff in our generator objects we can add a <code>name</code> field in there as well. The latter is probably tidier.</p>\n<p>Taken all together, we might get something like</p>\n<pre><code>class MadlibsGenerator:\n def __init__(self, name, descriptions, generator):\n self.name = name\n self.descriptions = descriptions\n self.generator = generator\n \n def __call__(self, *args, **kwargs):\n return self.generator(*args, **kwargs)\n\ndef intro(generators):\n print("Welcome to our madlib generator!")\n print("We'll ask you for a serious of words, you'll give us the words, and "\n "we'll make a dope ass story out of it!")\n print("Let's get some info from you first.")\n print("Select the type of madlib you want. ")\n\n for key in generators:\n print(f"{key}. {generators[key].name}")\n\n while True:\n selection = input()\n if selection in generators:\n break\n else:\n print(f"No generator \\"{selection}\\", please try again.")\n\n return generators[selection]\n\ndef user_input(descriptions):\n words = []\n for description in descriptions:\n words.append(input(f"Enter {description}: "))\n\n return words\n\n\ndef generate_short_story(name, animal, color, item, food):\n return (f"There once was a person named {name}. {name} LOVED "\n f"{animal}s. They were {name}'s favorite animal.\\n"\n f"One day, {name} was walking down the street wearing "\n f"{color} pants and a {color} shirt. In fact, all of "\n f"{name}'s\\n"\n f"clothes were {color}! In one of {name}'s hand, "\n f"there was a bright green {item}. In the other, there was "\n f"a big {food} that {name} was waiting to eat!")\n\n\n\ndef generate_poem(adjective, noun1, noun2):\n return (f"Roses are {adjective}\\n"\n f"{noun1} are blue\\n"\n f"I can't start my day without {noun2}")\n\n\nif __name__ == "__main__":\n generators = {\n "1": MadlibsGenerator("Short Story",\n ["a name", "an animal", "a color", "an item", "a food"],\n generate_short_story),\n "2": MadlibsGenerator("Poem",\n ["an adjective", "a plural noun", "any noun"],\n generate_poem)\n }\n\n generator = intro(generators)\n madlib_input = user_input(generator.descriptions)\n print(generator(*madlib_input))\n</code></pre>\n<h2>Update</h2>\n<p>At this point, you might start to think: "Hang on, each of those generator functions just puts strings into another string - creating a function each time we want to do that seems clumsy". And you have a point. While f-strings are nice, there are other options available that let us specify the template in one place and later use it in another. For example, strings already have a <code>format</code> method. We could take advantage of that and replace the generator functions with strings like</p>\n<pre><code>poem_template = """\nRoses are {0}\n{1} are blue\nI can't start my day without {2}\n"""\n</code></pre>\n<p>And instead of having our generators call these functions, we can have them call <code>.format</code> on these strings like</p>\n<pre><code>class MadlibsGenerator:\n def __init__(self, name, descriptions, template):\n self.name = name\n self.descriptions = descriptions\n self.template = template.strip()\n\n def __call__(self, *args):\n return self.template.format(*args)\n</code></pre>\n<p>And now we can create generators like <code>greeting_generator = MadlibsGenerator("Greeting", ["a name"], "Hi there, {0}!")</code> if we want to. Neat!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T18:23:36.840",
"Id": "505156",
"Score": "1",
"body": "Well this is much cleaner. I figured I'd create a class since I'm trying to make classes out of everything, but learning about when to actually use classes is something I'll need to keep an eye on.\n\nI love passing descriptions to user_input and only asking what's required for the type of story. I'm working on understanding the flow of information here from intro to the final print statement, so I might have some more questions later. \n\nWith regards to using the `main` block, I'm assuming that now when the file is imported, they can choose to use the functions as needed, is that right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T19:16:57.467",
"Id": "505165",
"Score": "1",
"body": "@pylearn Honestly, while I think the original class was a bit oddly designed on second thought I don't think using a class here is a bad approach. It really is meaningful to talk about \"a generator\" (my code example even does that), and avoiding classes did make my code a bit more awkward I feel. I've updated my review (and code) a bit.\n\nAlso, yes, when someone imports a file they can use any functions, classes and variables from that file however they like, but any code in an `if __name__ == \"__main__\"` block doesn't run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T19:46:51.750",
"Id": "505167",
"Score": "0",
"body": "Checking the edit out now (thanks for continuing to answer my questions!). For this code block: \n`def __call__(self, *args, **kwargs): return self.generator(*args, **kwargs)` \nIs it essentially just running a call to the instance of the class with the passed in generator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:02:48.457",
"Id": "505169",
"Score": "1",
"body": "@pylearn Yeah. The `__call__` method is just what happens when you call an instance of a class as though it was a function, and in this case it just passes the arguments to the \"generator\" function that instance has."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T02:16:38.810",
"Id": "255910",
"ParentId": "255900",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255910",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T21:37:44.003",
"Id": "255900",
"Score": "3",
"Tags": [
"python",
"beginner"
],
"Title": "Building a madlib generator"
}
|
255900
|
<p>I wrote a simple word-counter in Python a while ago, capable of processing DOCX, XLSX, TXT, and some PDF files. Now I gave it a simple GUI - this is my first tkinter program ever. What do you think?</p>
<pre><code>import openpyxl
import docx2txt
import PyPDF2
import tkinter
from tkinter import filedialog
def excel_counter(filename):
count = 0
wb = openpyxl.load_workbook(filename)
for sheet in wb:
for row in sheet:
for cell in row:
text = str(cell.value)
if text != "None":
word_list = text.split()
count += len(word_list)
return count
def pdf_counter(filename):
pdf_word_count = 0
pdfFileObj = open(filename, "rb")
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
number_of_pages = pdfReader.getNumPages() - 1
for page in range(0, number_of_pages + 1):
page_contents = pdfReader.getPage(page - 1)
raw_text = page_contents.extractText()
text = raw_text.encode('utf-8')
page_word_count = len(text.split())
pdf_word_count += page_word_count
return pdf_word_count
def uploadaction(event=None):
root = tkinter.Tk()
root.destroy()
filename = filedialog.askopenfilename()
return filename
def wordcounter(file):
extension = file.split(".")[-1]
if extension == "xlsx":
current_count = excel_counter(file)
return current_count
if extension == "docx":
text = docx2txt.process(file)
current_count = len(text.split())
return current_count
if extension == "txt":
f = open(file, "r")
text = f.read()
current_count = len(text.split())
return current_count
if extension == "pdf":
pdf_word_count = pdf_counter(file)
return pdf_word_count
window = tkinter.Tk()
wordcount = wordcounter(uploadaction())
label = tkinter.Label(text=f"Word Count: {wordcount}")
label.pack()
window.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>One suggestion is to simplify your top-level function by taking\nadvantage of a library and using a data structure to eliminate conditional logic.</p>\n<pre><code>import pathlib\n\ndef wordcounter(file_path):\n # Let a built-in library solve this problem.\n extension = pathlib.Path(file_path).suffix\n\n # Hold the counter functions in a data structure.\n # You'll need to create a couple of these.\n counters = {\n 'xlsx': excel_counter,\n 'docx': word_counter,\n 'txt': txt_counter,\n 'pdf': pdf_counter,\n }\n\n # Then just do what you want directly rather than checking conditions.\n return counters[extension](file_path)\n</code></pre>\n<p>Another observation is that your counter functions are duplicating the word\ncounting logic. Such duplication is often a signal that there are refactoring\npossibilities: more specifically, the thing being duplicated might belong in\nits own function. If we do that, you'll need to convert your current counter\nfunctions (which take a path and return an integer) into reader functions (take a path\nand yield chunks of text). Such a refactor is illustrated for <code>excel_reader</code>.\nAnd those changes will imply a few simple adjustments in <code>wordcounter</code>.</p>\n<pre><code>def count_words(reader, file_path):\n n = 0\n for text in reader(file_path):\n n += len(text.split())\n return n\n\ndef excel_reader(file_path):\n wb = openpyxl.load_workbook(filename)\n for sheet in wb:\n for row in sheet:\n for cell in row:\n # Your current logic.\n text = str(cell.value)\n if text != "None":\n yield text\n\n # I've never used openpxl, but a quick internet\n # search suggests that this is more robust conditional\n # check to filter out empty cells.\n if cell.value is not None:\n yield str(cell.value)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T09:33:18.390",
"Id": "255923",
"ParentId": "255901",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T21:51:27.357",
"Id": "255901",
"Score": "3",
"Tags": [
"python",
"tkinter"
],
"Title": "Multi-format word counter"
}
|
255901
|
<p>I've been lucky enough to get my first job as a junior PHP developer. I am concerned I'm not good enough. I would like to brush up on my coding skills and get as much constructive criticism as I can.</p>
<p>This is a SQL query builder, built for MySQL that provides a fluent, chaining API to build a query, and allows you to output the raw SQL. How can I improve the quality of it, as well as any features you can think of that I can try to practice.</p>
<p>API:</p>
<pre><code>$qb = new QueryBuilder('users');
$qb
->where('username', 'googun')
->orWhere('username', 'janetjackson')
->select(['id', 'username', 'email'])
->orderBy('id', 'DESC')
->limit(5);
</code></pre>
<p>QueryBuilder class:</p>
<pre><code><?php
class QueryBuilder {
private $tableName;
private $whereClauses;
private $selectColumns;
private $maxResults;
private $orderBy;
public function __construct($tableName) {
$this->tableName = $tableName;
$this->whereClauses = [];
$this->selectColumns = ['*'];
$this->maxResults = -1;
}
public function where($column, $valueOrOperator, $value = null) : QueryBuilder {
if ($value == null) {
return $this->appendWhere($column, '=', $valueOrOperator);
}
return $this->appendWhere($column, $valueOrOperator, $value);
}
private function appendWhere($column, $operator, $value, $join = 'AND') : QueryBuilder {
$this->whereClauses[] = [
'column' => $column,
'operator' => $operator,
'value' => $value,
'join' => $join
];
return $this;
}
private function whereRaw($rawSql) : QueryBuilder {
$this->whereClauses[] = [
'raw_sql' => $rawSql,
'join' => 'AND'
];
return $this;
}
public function orWhere($column, $valueOrOperator, $value = null) : QueryBuilder {
if ($value == null) {
return $this->appendWhere($column, '=', $valueOrOperator, 'OR');
}
return $this->appendWhere($column, $valueOrOperator, $value);
}
public function orWhereRaw($rawSql) : QueryBuilder {
$this->whereClauses[] = [
'raw_sql' => $rawSql,
'join' => 'OR'
];
return $this;
}
public function select(array $columns) : QueryBuilder {
$this->selectColumns = $columns;
return $this;
}
public function limit(int $amount) : QueryBuilder {
$this->maxResults = $amount;
return $this;
}
public function orderBy(string $column, string $direction) {
$this->orderBy = $column . ' ' . $direction;
return $this;
}
public function buildDefaultQuery() : string {
return 'SELECT ' . implode(',', $this->selectColumns) . ' FROM ' . $this->tableName . ' ';
}
public function parseClauseValue($value) : string {
return is_numeric($value) ? $value : '\'' . $value . '\'';
}
public function appendWhereClausesToQuery($query) : string {
$query .= 'WHERE ';
foreach ($this->whereClauses as $key => $clause) {
if ($key >= 1) {
$query .= ' ' . $clause['join'] . ' ';
}
if (array_key_exists('raw_sql', $clause)) {
$query .= $clause['raw_sql'];
}
else {
$parsedValue = $this->parseClauseValue($clause['value']);
$query .= $clause['column'] . ' ' . $clause['operator'] . ' ' . $parsedValue;
}
}
return $query;
}
public function appendOrderByToQuery($query) : string {
$query .= ' ORDER BY ' . $this->orderBy;
return $query;
}
public function appendLimitSqlToQuery($query) : string {
$query .= ' LIMIT ' . $this->maxResults . ';';
return $query;
}
public function toSql() {
$query = $this->buildDefaultQuery();
if (count($this->whereClauses) > 0) {
$query = $this->appendWhereClausesToQuery($query);
}
if (strlen($this->orderBy) > 0) {
$query = $this->appendOrderByToQuery($query);
}
if ($this->maxResults >= 0) {
$query = $this->appendLimitSqlToQuery($query);
}
return $query;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T03:01:46.977",
"Id": "505624",
"Score": "3",
"body": "\"_I am concerned I'm not good enough._\" ...me too and I've been doing web dev since 2007. Perhaps this is an unshakable feeling for some people."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T03:58:13.713",
"Id": "510288",
"Score": "0",
"body": "Practice, practice. Experiment. Ask questions. You _can_ get _better_; focus on that, not on \"good enough\"."
}
] |
[
{
"body": "<h2>Initial Feedback</h2>\n<p>The code looks quite modern - with return types declared, chaining supported, etc. The code is somewhat in-line with <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a> and thus is quite readable, though a few rules aren't followed - e.g.</p>\n<ul>\n<li><p><a href=\"https://www.php-fig.org/psr/psr-12/#44-methods-and-functions\" rel=\"nofollow noreferrer\">4.4 Methods and Functions</a></p>\n<blockquote>\n<p>Method and function names MUST NOT be declared with space after the method name. The opening brace MUST go on its own line, and the closing brace MUST go on the next line following the body. There MUST NOT be a space after the opening parenthesis, and there MUST NOT be a space before the closing parenthesis.</p>\n</blockquote>\n<p>I don't totally agree with this one after having worked with PHP (and JavaScript) for many years involving methods and functions where the opening brace is on the same line as the method name.</p>\n</li>\n<li><p><a href=\"https://www.php-fig.org/psr/psr-12/#45-method-and-function-arguments\" rel=\"nofollow noreferrer\">4.5 Method and Function Arguments</a></p>\n<blockquote>\n<p>When you have a return type declaration present, there MUST be one space after the colon followed by the type declaration. The colon and declaration MUST be on the same line as the argument list closing parenthesis with no spaces between the two characters.</p>\n</blockquote>\n</li>\n</ul>\n<h2>Suggestions</h2>\n<h3>DocBlocks</h3>\n<p><a href=\"https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md\" rel=\"nofollow noreferrer\">PSR-5</a> is in draft status currently but is commonly followed amongst PHP developers. It recommends adding docblocks above structural elements like classes, methods, properties, etc. Many popular IDEs will index the docblocks and use them to suggest parameter names when using code that has been documented. At least do it for the methods like the constructor, in case you forget which order the parameters are in.</p>\n<h3>Comparison operators</h3>\n<p>In methods <code>where()</code> and <code>orWhere()</code> there is a comparison with <code>null</code></p>\n<blockquote>\n<pre><code>if ($value == null) {\n</code></pre>\n</blockquote>\n<p>This uses loose equality checking. It is wise to get in the habit of using <a href=\"https://www.php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">strict equality comparisons</a> - i.e. <code>===</code> and <code>!==</code> unless you are sure you want to allow types to be coerced <sup><a href=\"https://softwareengineering.stackexchange.com/questions/126585/what-are-some-examples-of-wartiness-making-a-programming-language-more-useful\">1</a></sup>.</p>\n<h3>SQL Injection prevention: Bound parameters</h3>\n<p><a href=\"https://phpdelusions.net/sql_injection\" rel=\"nofollow noreferrer\">SQL injection</a> is very important to consider! One technique for mitigating this is to use bound parameters. I'd want to ensure parameters are bound to my queries whenever possible.</p>\n<h3>Default values for properties</h3>\n<p>The constructor sets values for these properties:</p>\n<blockquote>\n<pre><code>$this->whereClauses = [];\n$this->selectColumns = ['*'];\n$this->maxResults = -1;\n</code></pre>\n</blockquote>\n<p>Those lines could be eliminated by setting the values on the property declarations:</p>\n<pre><code> private $whereClauses = [];\n private $selectColumns = ['*'];\n private $maxResults = -1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T01:07:08.307",
"Id": "255909",
"ParentId": "255903",
"Score": "3"
}
},
{
"body": "<p>When I started using MySQL 22 years ago, I thought about doing what you are doing. I quickly decided against it -- It is too much of a "moving target", and some constructs get quite clumsy to specify.</p>\n<p>But the coup de grâce was when I realized that the number of keystrokes would be more than simply learning and writing SQL.</p>\n<p>Instead, I adopted a coding style of indenting, when to split rows, etc.</p>\n<p>Still, your project is a useful learning exercise. It will 'force' you to learn all the syntax and what it all does.</p>\n<p>PS: stackoverflow.com has lots and lots of questions about MySQL.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T09:40:20.110",
"Id": "510326",
"Score": "0",
"body": "`When I started using MySQL 22 years ago` It's a long time ago:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T16:17:13.237",
"Id": "510356",
"Score": "0",
"body": "@Mantykora7 - I just read a Question for which one answer was \"use `STRAIGHT_JOIN`\". The response came back: \"Alas, that construct is not available in the framework I am using.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T12:40:51.620",
"Id": "513243",
"Score": "0",
"body": "It has downsides too. A piece of typed code which calls multiple well defined methods on a builder instance is much easier to validate then a raw sql query string. But I agree that sometimes when you need something special, builders just don't have it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T04:08:58.560",
"Id": "258827",
"ParentId": "255903",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T22:51:33.563",
"Id": "255903",
"Score": "5",
"Tags": [
"php",
"sql",
"mysql"
],
"Title": "PHP: Simple SQL query builder"
}
|
255903
|
<p>I am making a simple game like Wolfenstein 3d on C using raycasting. To calculate the length of the rays, I use the DDA algorithm. I apply the part of the code that calculates the length of the rays and the size of the wall on the vertical line where the ray hit. How can I optimize and improve my code?</p>
<pre><code>
/*
** Function: void calculate()
**
** Arguments: main struct and i
**
** return: void
**
** Description: The raycasting loop is a for loop that goes through every x,
** so there is a calculation for every vertical stripe of the screen.
*/
void calculate(t_cub3d *cub)
{
int i;
i = 0;
while (i < cub->window.res_width)
{
calculate_cam(cub, &i);
// field_x and field_y represent the current square of the map the ray is in.
cub->field.field_x = cub->player.x_pos;
cub->field.field_y = cub->player.y_pos;
calculate_ray_dir(cub);
calculate_step(cub);
calculate_wall(cub);
calculate_height(cub);
draw(cub, i);
i++;
}
calculate_sprite(cub);
}
/*
** Function: void calculate_cam()
**
** Arguments: main struct, variable counter(width)
**
** return: void
**
** Description: x_camera is the x-coordinate on the camera plane
** that the current x-coordinate of the screen represents, done this way
** so that the right side of the screen will get coordinate 1, the center
** of the screen gets coordinate 0, and the left side of the screen gets coordinate -1
*/
void calculate_cam(t_cub3d *cub, int *i)
{
cub->camera.x_camera = 2 * *i / (double)(cub->window.res_width) - 1;
cub->ray.dir_ray_x = cub->player.x_dir + cub->camera.x_plane * \
cub->camera.x_camera;
cub->ray.dir_ray_y = cub->player.y_dir + cub->camera.y_plane * \
cub->camera.x_camera;
}
/*
** Function: void calculate_ray_dir()
**
** Arguments: main struct
**
** return: void
**
** Description: x_deltaDist and y_deltaDist are the distance the ray
** has to travel to go from 1 x-side to the next x-side, or from 1 y-side
** to the next y-side.
*/
void calculate_ray_dir(t_cub3d *cub)
{
if (cub->ray.dir_ray_y == 0)
cub->ray.x_deltadist = 0;
else
{
if (cub->ray.dir_ray_x == 0)
cub->ray.x_deltadist = 1;
else
cub->ray.x_deltadist = fabs(1 / cub->ray.dir_ray_x);
}
if (cub->ray.dir_ray_x == 0)
cub->ray.y_deltadist = 0;
else
{
if (cub->ray.dir_ray_y == 0)
cub->ray.y_deltadist = 1;
else
cub->ray.y_deltadist = fabs(1 / cub->ray.dir_ray_y);
}
}
/*
** Function: void calculate_step()
**
** Arguments: main struct
**
** return: void
**
** Description: x_sideDist and y_sideDist are initially the distance
** the ray has to travel from its start position to the first x-side and
** the first y-side.
*/
void calculate_step(t_cub3d *cub)
{
if (cub->ray.dir_ray_x < 0)
{
cub->ray.x_ray_step = -1;
cub->ray.x_sidedist = (cub->player.x_pos - (double)(cub->field.field_x))
* cub->ray.x_deltadist;
}
else
{
cub->ray.x_ray_step = 1;
cub->ray.x_sidedist = (((double)(cub->field.field_x) + 1.0 - \
cub->player.x_pos) * cub->ray.x_deltadist);
}
if (cub->ray.dir_ray_y < 0)
{
cub->ray.y_ray_step = -1;
cub->ray.y_sidedist = (cub->player.y_pos - (double)(cub->field.field_y))
* cub->ray.y_deltadist;
}
else
{
cub->ray.y_ray_step = 1;
cub->ray.y_sidedist = ((double)(cub->field.field_y) + 1.0 - \
cub->player.y_pos) * cub->ray.y_deltadist;
}
}
/*
** Function: void calculate_wall()
**
** Arguments: main struct
**
** return: void
**
** Description: DDA algorithm. It's a loop that increments the ray with 1 square
** every time, until a wall is hit.
*/
void calculate_wall(t_cub3d *cub)
{
int is_wall;
is_wall = 0;
cub->window.side = 0;
while (is_wall == 0)
{
if (cub->ray.x_sidedist < cub->ray.y_sidedist)
{
cub->ray.x_sidedist += cub->ray.x_deltadist;
cub->field.field_x += cub->ray.x_ray_step;
cub->window.side = 0;
}
else
{
cub->ray.y_sidedist += cub->ray.y_deltadist;
cub->field.field_y += cub->ray.y_ray_step;
cub->window.side = 1;
}
if (cub->field.map[cub->field.field_y][cub->field.field_x] == '1')
is_wall = 1;
}
calculate_distto_wall(cub);
}
/*
** Function: void calculate_distto_wall()
**
** Arguments: main struct
**
** return: void
**
** Description: calculate the distance of the ray to the wall
*/
void calculate_distto_wall(t_cub3d *cub)
{
if (cub->window.side == 0)
{
cub->ray.wall_dist = ((double)(cub->field.field_x) - cub->player.x_pos \
+ (1 - cub->ray.x_ray_step) / 2) / cub->ray.dir_ray_x;
}
else
{
cub->ray.wall_dist = ((double)(cub->field.field_y) - cub->player.y_pos \
+ (1 - cub->ray.y_ray_step) / 2) / cub->ray.dir_ray_y;
}
}
/*
** Function: void calculate_height()
**
** Arguments: main struct
**
** return: void
**
** Description: calculate the height of the line that has to be
** drawn on screen
*/
void calculate_height(t_cub3d *cub)
{
cub->window.height_ln = (int)(cub->window.res_height / cub->ray.wall_dist);
cub->window.top_wall = (cub->window.height_ln * -1) / 2 + \
cub->window.res_height / 2;
if (cub->window.top_wall < 0)
cub->window.top_wall = 0;
cub->window.bottom_wall = cub->window.height_ln / 2 + \
cub->window.res_height / 2;
if (cub->window.bottom_wall >= cub->window.res_height)
cub->window.bottom_wall = cub->window.res_height - 1;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Use the Doxygen language to document your functions</h1>\n<p>It looks like you use some ad-hoc way to document your functions. It's very good to add that documentation, but there are tools out there that make it even more useful, like <a href=\"https://www.doxygen.nl/index.html\" rel=\"nofollow noreferrer\">Doxygen</a>. Once you reformat your comments to follow the Doxygen syntax, you can then use the Doxygen tools to generate documentation in PDF, HTML and various other formats. It can also check whether your documentation is correct, for example whether you have documented all the parameters. It would have already found an error in the first functions: you mentino <code>i</code> in the description of the function arguments, but there is no such thing.</p>\n<h1>Pass integers by value</h1>\n<p>Why are you passing <code>i</code> by reference to <code>calculate_sam()</code>? You should just pass it by value, otherwise you pay for unnecessary dereferencing of the pointer.</p>\n<h1>Naming things</h1>\n<p>You should try to give more descriptive names to functions. Naming everything <code>calculate_something()</code> is not very useful, as calculating is what your computer is basically doing all the time. It looks like <code>calculate()</code> is actually causing everything to be drawn, since it calls <code>draw()</code>. So maybe it should be names something like <code>draw_scene()</code> instead? And <code>draw()</code> should probably be <code>draw_column()</code>?</p>\n<p>Why is there <code>x_pos</code> and <code>x_plane</code> but <code>field_x</code>? Having a consistent ordering of words makes it easier to read your code. But then also, there is a redundancy in <code>field.field_x</code>, maybe rename it so you can just write <code>field.x</code>?</p>\n<p>What is <code>cub</code>? Is it representing a cube? If so, don't arbitrarily remove a single letter from a word, you might <a href=\"https://unix.stackexchange.com/questions/128708/why-wasnt-creat-called-create\">regret it</a> later.</p>\n<p>Furthermore, if you have a variable holding a coordinate, use <code>x</code> and <code>y</code> instead of <code>i</code>.</p>\n<h1>Have functions return values</h1>\n<p>Your functions don't return anything, but rather modify the object pointed to. Although you might think that keeps things together, it actually makes them harder to use, and will likely cause lots of temporary variables to be put into <code>t_cub3d</code>, which will waste memory. Try to have functions <code>return</code> their results, and only pass those variables to them that they need to use.</p>\n<p>For example, <code>calculate_cam()</code> seems to only calculate <code>x_camera</code> as a temporary value, and the only thing used by other code (as far as I can see) is the ray's direction. So, assuming <code>cub->ray</code> has type <code>r_ray</code>, I would write:</p>\n<pre><code>t_ray calculate_cam(const t_cub3d *cub, int x)\n{\n int x_camera = 2.0 * x / cub->window.res_width - 1;\n t_ray ray;\n ray.dir_ray_x = cub->player.x_dir + cub->camera.x_plane * x_camera;\n ray.dir_ray_y = cub->player.y_dir + cub->camera.y_plane * x_camera;\n return ray;\n}\n</code></pre>\n<h1>Use <code>bool</code> where appropriate</h1>\n<p>When you have a variable that hold a value that should mean "true" or "false", use <code>bool</code> from <code><stdbool.h></code>. For example, <code>is_wall</code> is a good candidate for that.</p>\n<h1>Prefer <code>for</code> over <code>while</code> where appropriate</h1>\n<p>The advantage of a <code>for</code>-statement is that you can clearly put the initial value, the end condition and the increment at the top of the loop. So in <code>calculate()</code>, I would write:</p>\n<pre><code>for (int i = 0; i < cub->window.res_width; i++)\n{\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T22:04:33.007",
"Id": "255965",
"ParentId": "255913",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255965",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T03:16:14.820",
"Id": "255913",
"Score": "3",
"Tags": [
"algorithm",
"c",
"raycasting"
],
"Title": "Implementation of the DDA algorithm with raycasting"
}
|
255913
|
<p><a href="https://i.stack.imgur.com/iWJqe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iWJqe.png" alt="The exercise" /></a></p>
<blockquote>
<p>Exercise 1-22. Write a program to "fold" long input lines into two or
more shorter lines after the last non-blank character that occurs
before the n-th column of input. Make sure your program does something
intelligent with very long lines, and if there are no blanks or tabs
before the specified column.</p>
</blockquote>
<p>The key idea is that I process whitespace character by character while processing a sequence of non-blank characters block by block, i.e. I read a block then decide whether to print it in the current line or next line.</p>
<pre><code>#include <stdio.h>
#define LINE_MAX_SIZE 21 /* The maximum number of columns allowed in a single line */
#define IN_NON_BLANK_SEQ 1 /* Indicate that a sequence of non-blank character are being processed */
#define TAP_STOP_DIST 5
#define NON_BLANK(ch) (ch != '\t' && ch != '\n' && ch != ' ')
int get_next_tap_pos(int current_column) {
// columns numbered 0, 1, 2... there is a tap stop at 0, 5, 10, 15, 20
return current_column / TAP_STOP_DIST * TAP_STOP_DIST + TAP_STOP_DIST;
}
int main(void)
{
char block[LINE_MAX_SIZE+1];
int column_pos = 0; /* Indicate the current column in the output where the next character will be printed*/
int index_non_blank = 0; /* Indicate the number of the non-blank char in the next non-blank char sequence */
int state = !IN_NON_BLANK_SEQ; /* Indicate whether a non-blank character is being processed */
int ch;
while ( (ch = getchar()) != EOF) {
if (NON_BLANK(ch)) {
state = IN_NON_BLANK_SEQ;
if (index_non_blank == LINE_MAX_SIZE) {
// There is a word bigger than the size of the line
block[LINE_MAX_SIZE] = '\0';
// Should I print it in the current line or in the next line ?
// Our word is as big as our line. so if current line is not empty, we can't print it here
if (column_pos != 0)
putchar('\n');
printf("%s\n", block);
column_pos = 0;
index_non_blank = 0;
block[index_non_blank] = ch;
}
else {
block[index_non_blank] = ch;
++index_non_blank;
}
}
else {
// Is there a non-blank sequence that just finished ?
if (state == IN_NON_BLANK_SEQ) {
// Should the current word be printed in the current line or next line ?
block[index_non_blank] = '\0';
int expected_column_num = column_pos + index_non_blank;
if (expected_column_num <= LINE_MAX_SIZE) {
printf("%s", block);
column_pos = expected_column_num;
}
else {
putchar('\n');
printf("%s", block);
column_pos = index_non_blank;
}
state = !IN_NON_BLANK_SEQ;
index_non_blank = 0;
}
// now print the whitespace character and update column position
if (ch == '\n') {
putchar(ch);
column_pos = 0;
}
else if (ch == ' ' && column_pos < LINE_MAX_SIZE) {
putchar(ch);
++column_pos;
}
else if (ch == '\t' && column_pos < LINE_MAX_SIZE) {
putchar(ch);
column_pos = get_next_tap_pos(column_pos);
}
else {
putchar('\n');
column_pos = 0;
}
}
}
}
</code></pre>
<p>Github <a href="https://github.com/AhmedAlaa-10/The-C-programming-language.-k-R-2-solutions-by-me/blob/main/Chap.%201/ex22.c" rel="nofollow noreferrer">link</a></p>
|
[] |
[
{
"body": "<p>This looks pretty competent code to me. Good to see that you've included handling for tabs.</p>\n<p>I only have minor points to raise:</p>\n<ul>\n<li>\n<blockquote>\n<pre><code>#define NON_BLANK(ch) (ch != '\\t' && ch != '\\n' && ch != ' ') \n</code></pre>\n</blockquote>\n<p>If we include <code><ctype.h></code>, we should be able to use <code>isspace()</code> instead of this macro. In any case, a function is preferred to a macro, especially a macro that expands its arguments more than once (we can't call this with an argument such as <code>*++p</code>, for example).</p>\n</li>\n<li>\n<blockquote>\n<pre><code>#define IN_NON_BLANK_SEQ 1\n</code></pre>\n</blockquote>\n<p>We only have two states, so we should use a boolean (with a better name than <code>state</code>). Assuming we have <code><stdbool.h></code>, then I'd replace <code>int state = !IN_NON_BLANK_SEQ;</code> with</p>\n<pre><code> bool in_blank_seq = false;\n</code></pre>\n<p>Actually, we might not need this at all - I think that when we have most recently seen whitespace, then <code>index_non_blank</code> is non-zero.</p>\n</li>\n<li>\n<blockquote>\n<pre><code>int column_pos = 0;\nint index_non_blank = 0;\n</code></pre>\n</blockquote>\n<p>These two could be unsigned. But that might not matter, given the small range of values they ever hold.</p>\n</li>\n<li>\n<blockquote>\n<pre><code>#define TAP_STOP_DIST 5\nint get_next_tap_pos(int current_column) {\n</code></pre>\n</blockquote>\n<p>Spelling - that should be <strong>tab</strong>. And what kind of terminal has tab stops every five characters? Pretty much every terminal (and terminal emulator) I've ever used has tab stops every <em>eight</em> characters, at least unless specifically changed.</p>\n</li>\n<li>\n<blockquote>\n<pre><code>#define LINE_MAX_SIZE 21\n</code></pre>\n</blockquote>\n<p>Additional exercise - make this configurable, by command-line option.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T07:53:42.697",
"Id": "255917",
"ParentId": "255915",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255917",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T05:20:21.177",
"Id": "255915",
"Score": "4",
"Tags": [
"c"
],
"Title": "The solution for the exercise 1-22 from the book \"The C programming language\" K&R2"
}
|
255915
|
<p>I am using Facebook's Javascript SDK for the login, and I am validating it with PHP Graph SDK v5.x</p>
<p>Here is the JS:</p>
<pre><code>logInWithFacebook = function() {
FB.login(function(response) {
if (response.authResponse) {
console.log (response.authResponse);
$.ajax({
type: 'POST',
url: 'facebook-validate-php-sdk.php',
data: response.authResponse,
success: function(response){
console.log (response);
//Success
}
});
} else {
alert('User canceled login or did not fully authorize.');
}
}, {scope: 'user_link, email'});
return false;
};
window.fbAsyncInit = function() {
FB.init({
appId: 'xxx',
cookie: false,
version: 'v9.0'
});
};
</code></pre>
<p>Here is the PHP that validates:</p>
<pre><code>require_once 'php-graph-sdk-5.x/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxx',
'app_secret' => 'xxx',
'default_graph_version' => 'v9.0',
]);
//$helper = $fb->getJavaScriptHelper();
try {
//$accessToken = $helper->getAccessToken();
$accessToken = $_POST['accessToken'];
}catch(Facebook\Exception\ResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exception\SDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No OAuth data could be obtained.';
exit;
}
// User is logged in!
//Get Data
try {
// Returns a `Facebook\Response` object
$response = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,picture.type(large),birthday', $accessToken);
} catch(Facebook\Exception\ResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exception\SDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
var_dump ($user);
</code></pre>
<p>As you can see, I opted to pass the access token with POST instead of a cookie. Since I am not going to be establishing a session on my project I figured that would be best. Would that be a correct assumption? Is this code secure? Any tips or thoughts?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T10:24:22.637",
"Id": "255925",
"Score": "0",
"Tags": [
"javascript",
"php",
"facebook"
],
"Title": "Facebook Login with JS and validate with PHP - Secure?"
}
|
255925
|
<p>I am trying to understand the right usage of Task vs ValueTask in .NetCore2.0(+) or C# 7.0(+)</p>
<p>Task -</p>
<ol>
<li>Is a class/object types & uses heap memory</li>
<li>should be used in async method when the operation would complete <strong>eventually</strong> ex. network call</li>
</ol>
<p>ValueTask -</p>
<ol>
<li>Is a struct/value type & uses stack memory</li>
<li>should be used in async method when the operation output is already in memory or the operation completes <strong>immediately</strong></li>
</ol>
<p>Based on this is my implementation justifies both usage right?</p>
<pre><code>public class Utility
{
public async ValueTask<int> Add(int n1, int n2)
{
//immediately available
return await Task.Run(() => (n1 + n2))
.ConfigureAwait(false);
}
public async Task<string> Get(string email)
{
//eventually available
string user = await Task.Run(() => GetFromDb(email))
.ConfigureAwait(false);
string GetFromDb(string email)
{
// do a database call over network
// & get the user based on the input email
return "User from Db";
}
return user;
}
}
</code></pre>
<p>Please review & suggest. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T11:03:40.000",
"Id": "505123",
"Score": "1",
"body": "Did you read [this](https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T11:05:26.990",
"Id": "505124",
"Score": "0",
"body": "Yes but couldn't catch each bit of this article so this one https://www.infoworld.com/article/3565433/how-to-use-valuetask-in-csharp.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:23:17.827",
"Id": "505187",
"Score": "0",
"body": "I found many reviews for your code but none of them marked as accepted. Please review your posts and select the most useful answers to accept. You can find that questions on the profile page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T08:35:37.197",
"Id": "505301",
"Score": "0",
"body": "@aepot Where are the review(s)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T09:14:03.340",
"Id": "505307",
"Score": "0",
"body": "Open your profile, open last questions, there's the reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:43:17.463",
"Id": "505371",
"Score": "0",
"body": "@Kgn-web I think you should look this problem rather from the consumer perspective. `ValueTask` can't be awaited multiple times and it is not suitable for blocking calls. If these constraints aren't violating the requirements then you should give it a try to use `ValueTask`. As always measure, measure and measure. I also encourage you read these blogs: [1](https://blog.stephencleary.com/2020/03/valuetask.html), [2](https://blog.marcgravell.com/2019/08/prefer-valuetask-to-task-always-and.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T10:07:53.330",
"Id": "505376",
"Score": "0",
"body": "@PeterCsala, Thanks for sharing. I have gone through #1 of this. 1 quick question as async-await has cost & if the process output is immediately available then why should I even bother to use ValueTask, what wrong in making the method as regular synchronous in this case. Please suggest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T10:43:15.833",
"Id": "505378",
"Score": "0",
"body": "@Kgn-web The `async`-`await`calls will be wrapped inside an async state machine during compile time. It shines when you have more than one `await` statement inside your async method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T10:45:00.120",
"Id": "505379",
"Score": "0",
"body": "@Kgn-web Back to your sample, this `Task.Run` is an overkill here. `Task.FromResult(n1 + n2);` or `new ValueTask<int>(n1 + n2)` would be better. Please read David Fowler (ASP.NET Architect)'s [Async guideline](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#prefer-taskfromresult-over-taskrun-for-pre-computed-or-trivially-computed-data)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:23:44.880",
"Id": "505382",
"Score": "0",
"body": "@PeterCsala https://www.red-gate.com/simple-talk/dotnet/net-framework/the-overhead-of-asyncawait-in-net-4-5/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:24:49.720",
"Id": "505383",
"Score": "1",
"body": "@PeterCsala if you refer the above shared link, for my scenario (similar scenario), I should keep the function normal synchronous no Task nor ValueTask (Just trying to understand)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:28:43.630",
"Id": "505385",
"Score": "0",
"body": "@Kgn-web If you don't need to perform any async I/O or any method on a ThreadPool thread then you don't have to define it as async. As I stated above there will be an async state machine after compilation, which obviously will impose some overhead for the runtime as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T09:23:15.127",
"Id": "505455",
"Score": "0",
"body": "@Kgn-web Do you mind if I leave a post where I capture all the information which has been mentioned in the comments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T09:32:14.237",
"Id": "505458",
"Score": "0",
"body": "@PeterCsala no it's fine"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T10:49:13.010",
"Id": "255927",
"Score": "0",
"Tags": [
"c#",
"task-parallel-library"
],
"Title": "Is the right usecase implemenation of ValueTask and Task in C#"
}
|
255927
|
<p>I would like to know if my Routing system respects the solid principle ?</p>
<p>The system is simple, Router class contains the routes and returns the correct route and Route class represents a route, contains a path and an action to call. Router takes the Request class as a parameter in its constructor to try to respect the solid principle.</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/SOLID" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/SOLID</a></li>
<li><a href="https://guillaume-richard.fr/principe-solid-simplifies-avec-des-exemples-en-php/" rel="nofollow noreferrer">https://guillaume-richard.fr/principe-solid-simplifies-avec-des-exemples-en-php/</a>
ETC...........</li>
</ul>
<p>I would like to know what's good and what isn't.</p>
<pre><code>class Router
{
private $request;
private $routes = [];
public function __construct(Request $request)
{
$this->request = $request;
}
public function get(string $path, string $action)
{
return $this->addRoute($path, $action, 'GET');
}
private function addRoute(string $path, string $action, string $method)
{
$route = new Route($path, $action);
$this->routes[$method][] = $route;
return $route;
}
public function run()
{
if(!isset($this->routes[$this->request->getMETHOD()])) {
throw new RouterException('REQUEST_METHOD does not exist');
}
foreach ($this->routes[$this->request->getMETHOD()] as $route) {
if ($route->match($this->request->getUri())) {
return $route->call();
}
}
throw new RouterException("La page demandée est introuvable.");
}
}
</code></pre>
<pre><code>class Route
{
private $path;
private $action;
private $matches;
private $parameters = [];
public function __construct(string $path, string $action)
{
$this->path = trim($path, '/');
$this->action = $action;
}
public function where(string $param, string $regex)
{
$this->parameters[$param] = str_replace('(', '(?:', $regex);
return $this;
}
public function match(string $requestUri)
{
$requestUri = trim($requestUri, '/');
$path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->path);
$regex = "#^$path$#";
if (preg_match($regex, $requestUri, $matches)) {
array_shift($matches);
$this->matches = $matches;
return true;
} else {
return false;
}
}
private function paramMatch(array $match)
{
if (isset($this->parameters[$match[1]])) {
return '(' . $this->parameters[$match[1]] . ')';
}
return '([^/]+)';
}
public function call()
{
$parameters = explode('@', $this->action);
$controller = "Src\\Controller\\" . $parameters[0];
$controller = new $controller();
$method = $parameters[1];
return call_user_func_array([$controller, $method], $this->matches);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Router should not accept request object in constructor. You will need a new router for each request.\nI know PHP spawns a new process for each request so it gets created for each request anyway. But in tests it may be different...\nAnd anyway it doesn't make much sense to hide the request inside the router from the logical point of view.\nHiding a constructor dependency means that the dependency is an implementation detail. And sure you agree that request is not just an implementation detail of a router. It is the input for routing.</p>\n<p>Also the route should not be aware of how to determine controller class and surely it doesn't want to know or, and thats even worse, force no constructor arguments for all controllers. There should be a controller factory that knows the details.</p>\n<p>And you don't want to pass controller factory to every route. So maybe instead, route should just define path mapping and controller factory should take a route as an input. Router would then pass the matched route to the controller factory.</p>\n<p>Another thing is that the addRoute method doesn't really belong on a router, it belong on a router builder. You register routes on the builder and finalize by calling it's createRouter method.</p>\n<p>What's entirely missing in your code is an "application" class - that's the one where run method belongs, not the router, router should really have a method that accepts request object and returns response object. Application might have a request factory, the router and some kind of response emitter which takes the response object returned by router and send it's representation to the client.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T19:16:56.937",
"Id": "256021",
"ParentId": "255928",
"Score": "0"
}
},
{
"body": "<p>As a general best practice rule, I would advise that any time you are going to be feeding a variable into a regex pattern string AND that variable isn't 100% guaranteed to be free of characters with special meaning to the regex engine -- you should always bake in a <code>preg_quote()</code> call for stability/security.</p>\n<hr />\n<p>Focusing on <code>match()</code> and <code>paramMatch()</code>...</p>\n<p>Fundamentally, I don't see any re-usable utility in declaring <code>paramMatch()</code> as a single-use method. I think it should be declared as an anonymous function within <code>match()</code>. The lookup can be simplified using a null coalescing operator. I would also declare the method's return type and try to minimize the number of single-use variables declared. Trivially, <code>\\w</code> doesn't not benefit from being packaged in a character class -- you can lose the square braces.</p>\n<pre><code>public function match(string $requestUri): bool\n{\n $path = preg_replace_callback(\n '#:(\\w+)#',\n function ($m) {\n return '(' . ($this->parameters[$m[1]] ?? '[^/]+') . ')';\n },\n $this->path\n );\n if (preg_match("#^" . $path . "$#", trim($requestUri, '/'), $matches)) {\n array_shift($matches);\n $this->matches = $matches;\n return true;\n } else {\n return false;\n }\n}\n \n</code></pre>\n<hr />\n<p>If you want to have declarative variable names in <code>call()</code>, you might consider the following alternative style. I think prepending the namespace path to <code>$this->action</code> before exploding is tolerable to make the preparation more direct. Also, as a matter of habit, when I know the exact number of expected elements to be generated by an <code>explode()</code> call, I always declare the limit parameter so that the function can immediately stop assessing the string when satisfied.</p>\n<pre><code>[$controller, $method] = explode('@', "Src\\\\Controller\\\\" . $this->action, 2);\nreturn call_user_func_array([new $controller(), $method], $this->matches);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T21:49:36.377",
"Id": "505439",
"Score": "0",
"body": "I will see all this, make the modifications and I will post my corrected code to morrow. thank you for your explanation, is helpful !!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T03:58:59.983",
"Id": "256031",
"ParentId": "255928",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T10:51:46.450",
"Id": "255928",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"mvc",
"url-routing"
],
"Title": "Router and solid principle"
}
|
255928
|
<p>Below you can see a class and a function. The class is just an dummy entity. The functon has a switch statement. That switch statement calculates the tax by to a predefined hardcoded string, and I don't like that. What's next, this switch statement violates the Open/Closed principle.</p>
<p>The class entity:</p>
<pre><code>class Product {
private int $id;
private string $name;
private int $price;
private string $category;
public function __construct(int $id, string $name, int $price, string $category) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->category = $category;
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getPrice(): int
{
return $this->price;
}
public function getCategory(): string
{
return $this->category;
}
}
</code></pre>
<p>The client code:</p>
<pre><code>//$product = new Product(200, 'Bread', 200, 'Food'); // A different product category
$product = new Product(100, 'Chair', 5000, 'Furniture');
$taxForChair = calculateTax($product);
var_dump($taxForChair); // float 1050
exit;
function calculateTax(Product $product): float {
// The switch statement below decreases adaptablity.
// The function also violates the Open/Closed principle.
// At this point, it has 2 cases.
// When the Business Rule change by create a new product category, then this function needs to change too.
switch($product->getCategory()) {
case 'Furniture':
$tax = $product->getPrice() / 100 * 21;
break;
case 'Food':
$tax = $product->getPrice() / 100 * 9;
break;
default:
$tax = 0;
break;
}
return (float)$tax;
}
</code></pre>
<p>Would you be so kind and write a better <code>calculateTax</code> function?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T12:01:33.287",
"Id": "505125",
"Score": "1",
"body": "These comments looks like teacher's remarks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:20:00.537",
"Id": "505128",
"Score": "0",
"body": "@YourCommonSense they were my own, so that means you think I'm a teacher. I take that as a compliment :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:58:21.367",
"Id": "505137",
"Score": "0",
"body": "Welcome to the Code Review Community. We make suggestions on how the code can be improved, we don't re-write the code. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T21:09:30.227",
"Id": "506088",
"Score": "0",
"body": "I think you are better off creating an interface `Product` and concrete classes that implement those interfaces or abstract class. In each concrete class you define getPrice to be specific to that product and you get rid of the switch statement and simply call getPrice()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T23:06:33.403",
"Id": "507275",
"Score": "0",
"body": "The title of this question expresses your concern for the script, but it should be explaining what the script does."
}
] |
[
{
"body": "<p>I fixed it by myself by introducing abstract classes, see below:</p>\n<pre><code>class Product {\n private int $id;\n private string $name;\n private int $price;\n private Category $category;\n \n public function __construct(int $id, string $name, int $price, Category $category) {\n $this->id = $id;\n $this->name = $name;\n $this->price = $price;\n $this->category = $category;\n }\n public function getId(): int\n {\n return $this->id;\n }\n public function getName(): string\n {\n return $this->name;\n }\n public function getPrice(): int\n {\n return $this->price;\n }\n public function getCategory(): Category\n {\n return $this->category;\n }\n}\n</code></pre>\n<p>here it goes</p>\n<pre><code>abstract class Category { \n abstract public function calculateTax(int $price): float;\n}\nclass CategoryFurniture extends Category {\n public function calculateTax(int $price): float {\n return (float)($price / 100 * 21);\n }\n}\nclass CategoryFood extends Category {\n public function calculateTax(int $price): float {\n return (float)($price / 100 * 9);\n }\n}\n\n//$product = new Product(200, 'Bread', 200, new CategoryFood); \n$product = new Product(100, 'Chair', 5000, new CategoryFurniture);\n\n$taxForChair = calculateTax($product);\nvar_dump($taxForChair); // float 1050\nexit;\n\nfunction calculateTax(Product $product): float {\n \n $price = $product->getPrice();\n \n $category = $product->getCategory();\n return $category->calculateTax($price);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:48:35.540",
"Id": "505132",
"Score": "0",
"body": "As long as the tax is calculated using the same formula,I would rather store the actual values in the *database*. This way you won't have to edit any code at all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:18:36.330",
"Id": "255939",
"ParentId": "255930",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T11:22:32.580",
"Id": "255930",
"Score": "0",
"Tags": [
"php"
],
"Title": "Switch statement decreases adaptability of a function"
}
|
255930
|
<p>This is a game in which a sequence of 4 characters is displayed to the player, one at a time with a delay between them. Then the player must input that sequence as it was displayed.</p>
<p>Sequences are displayed until input is incorrect.</p>
<p>The characters composing the sequences are chosen at random and they are all lines.</p>
<pre><code>__all__ = []
import random
import time
from colorama import deinit, init
MSG_ASK = 'What was the sequence? '
MSG_CORRECT = '\033[32mCorrect!\033[0m'
MSG_INCORRECT = '\033[31mIncorrect\033[0m'
def main():
k = 4
lines = r'|\-/'
seconds = 1
init()
while True:
s = ''
sequence = random.choices(lines, k=k)
sequence = ''.join(sequence)
for i in range(k):
if not i:
s = ''
elif i == 1:
s = ' '
else:
s = i * ' '
print(s, sequence[i], end='\r')
time.sleep(seconds)
print(f'{s} ')
if input(MSG_ASK) == sequence:
print(MSG_CORRECT)
else:
print(MSG_INCORRECT)
break
deinit()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>Using <code>__all__ = []</code> is mostly useless in the main program, and should probably be removed.</p>\n<hr />\n<p>This is hard to read:</p>\n<pre class=\"lang-py prettyprint-override\"><code>MSG_CORRECT = '\\033[32mCorrect!\\033[0m'\nMSG_INCORRECT = '\\033[31mIncorrect\\033[0m'\n</code></pre>\n<p>This is much easier:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from colorama import Fore\n\nMSG_CORRECT = Fore.GREEN + 'Correct!' + Fore.RESET\nMSG_INCORRECT = Fore.RED + 'Incorrect' + Fore.RESET\n</code></pre>\n<p>Note: <code>Style.RESET_ALL</code> would be an exact translation of <code>\\033[0m</code>. Adjust as desired.</p>\n<hr />\n<p>You could pull your loop body out into separate functions:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_random_sequence(length: int, characters: str) -> str:\n """\n Generate a random sequence of characters.\n """\n\n return ''.join(random.choices(characters, k=length))\n\ndef show_sequence(sequence: str, seconds_per_character: float) -> None:\n """\n Display a sequence to the user, one character at a time, on one line,\n using the given delay between characters.\n\n After the last character has been shown, clear the line.\n """\n\n for i, ch in enumerate(sequence):\n print(' ' * i, ch, end='\\r')\n time.sleep(seconds_per_character)\n\n print(' ' * len(sequence), ' ')\n</code></pre>\n<p>I've done several things here:</p>\n<ul>\n<li>type-hints and a <code>"""docstring"""</code> have been added</li>\n<li><code>sequence</code> is computed in one step</li>\n<li>removed the <code>s</code> variable, since it can be directly computed as <code>' ' * i</code></li>\n<li>looped directly over the sequence, using <code>enumerate</code> to keep track of the index.</li>\n<li>speed, length and characters are all arguments to the functions, so the challenge could become programmatically harder (ie, faster or longer)</li>\n</ul>\n<hr />\n<p>With the above function, the main loop becomes simpler:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n k = 4\n lines = r'|\\-/'\n seconds = 1\n\n init()\n\n while True:\n sequence = generate_random_sequence(k, lines)\n show_sequence(sequence, seconds)\n\n guess = input(MSG_ASK)\n if guess == sequence:\n print(MSG_CORRECT)\n else:\n print(MSG_INCORRECT)\n break\n\n deinit()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T00:04:06.460",
"Id": "255971",
"ParentId": "255935",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T12:14:37.783",
"Id": "255935",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"game"
],
"Title": "python Repeat the Sequence"
}
|
255935
|
<p>The task: user-generated news feed:</p>
<ol>
<li><p>User select what data type he wants to add</p>
</li>
<li><p>Provide record type required data</p>
</li>
<li><p>Record is published on text file in special format</p>
</li>
</ol>
<p>Types of data:</p>
<ol>
<li><p>News – text and city as input. Date is calculated during publishing.</p>
</li>
<li><p>Private ad – text and expiration date as input. Day left is calculated during publishing.</p>
</li>
<li><p>Your unique one with unique publish rules.</p>
</li>
</ol>
<p>Expected result:</p>
<pre><code>News -------------------------
Something happened
London, 03/01/2021 13.45
------------------------------
News -------------------------
Something other happened
Minsk, 24/01/2021 20.33
------------------------------
Private Ad ------------------
I want to sell a bike
Actual until: 01/03/2021, 21 days left
------------------------------
Joke of the day ------------
Did you hear about the claustrophobic astronaut?
He just needed a little space
Funny meter – three of ten
------------------------------
</code></pre>
<p>My code:</p>
<pre><code>from datetime import datetime, date
from sys import exit
class Article:
def __init__(self, title, text, line_width):
self.title = title
self.text = text
self.line_width = line_width
@staticmethod
def publish_article(formatted_text):
with open("all_news.txt", "a") as file:
file.write(formatted_text)
class News(Article):
def __init__(self, title, text, city, date, line_width):
Article.__init__(self, title, text, line_width)
self.city = city
self.date = date
def format_text(self):
return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
f"{self.text} \n"\
f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \n"\
f"{'-'*self.line_width}\n\n\n"
class Ad(Article):
def __init__(self, title, text, end_date, line_width):
Article.__init__(self, title, text, line_width)
self.end_date = end_date
def format_text(self):
day, month, year = map(int, self.end_date.split('/'))
days_left = (date(year, month, day) - date.today()).days
return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
f"{self.text} \n"\
f"Actual until: {date(year, month, day).strftime('%d/%m/%Y')}, {days_left} days left \n"\
f"{'-'*self.line_width}\n\n\n"
class PersonalNews(Article):
def __init__(self, title, text, line_width):
Article.__init__(self, title, text, line_width)
def format_text(self):
return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
f"{self.text} \n"\
f"{'-'*self.line_width}\n\n\n"
while True:
user_input = input('Enter a number: '
'1 - Publish news;\n'
'2 - Publish ad; \n'
'3 - Publish personal news\n'
'q - Exit\n')
if user_input == "1":
new_news = News("News",
input('Print your text\n'),
input('Print city for the news\n'), datetime.now(), 30)
new_news.publish_article(new_news.format_text())
elif user_input == "2":
new_news = Ad("Private Ad",
input("Input your text\n"),
input('Print endDate of ad in format DD/MM/YEAR\n'), 30)
new_news.publish_article(new_news.format_text())
elif user_input == "3":
new_news = PersonalNews(input("Input your title\n"),
input("Input your text\n"), 30)
new_news.publish_article(new_news.format_text())
elif user_input == "q":
exit(0)
else:
print("Incorrect input. Please enter a number (1, 2, 3) or 'q' for exit")
</code></pre>
|
[] |
[
{
"body": "<h2>Shadowing</h2>\n<p>Your <code>date</code> parameter to the constructor of <code>News</code> is poorly-named, because it shadows the built-in <code>date</code> that you've imported from <code>datetime</code>.</p>\n<h2>Super</h2>\n<p>Your call to <code>Article.__init__()</code> should use <code>super()</code> instead.</p>\n<h2>Data classes</h2>\n<p><code>Article</code> can just be a <code>@dataclass</code> with its explicit <code>__init__</code> removed.</p>\n<h2>Static methods</h2>\n<p><code>publish_article</code> doesn't make sense as a static method. In your invocations, you're always calling <code>format_text()</code> on a child instance, then passing that to a static method on the parent. Instead:</p>\n<ul>\n<li>Define <code>format_text(self) -> str: raise NotImplementedError()</code> on <code>Article</code> to declare it abstract</li>\n<li>Change <code>publish_article(self)</code> to simply <code>file.write(self.format_text())</code></li>\n</ul>\n<h2>Backslash continuation</h2>\n<p>Change this:</p>\n<pre><code> return f"{self.title}{(self.line_width - len(self.title)) * '-'}\\n"\\\n f"{self.text} \\n"\\\n f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \\n"\\\n f"{'-'*self.line_width}\\n\\n\\n"\n</code></pre>\n<p>to drop the backslashes and use parens instead:</p>\n<pre><code> return (\n f"{self.title}{(self.line_width - len(self.title)) * '-'}\\n"\n f"{self.text} \\n"\n f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \\n"\n f"{'-'*self.line_width}\\n\\n\\n"\n )\n</code></pre>\n<h2>Date parsing</h2>\n<p>This is evil:</p>\n<pre><code> day, month, year = map(int, self.end_date.split('/'))\n</code></pre>\n<p>Instead, you should be using an actual parsing method out <code>datetime</code> to get you a <code>date</code> instance; then referring to its members. Since you're looking for <code>DD/MM/YEAR</code>, this will be:</p>\n<pre><code>end_date = datetime.strptime(self.end_date, '%d/%m/%Y').date()\n# Use end_date.day, end_date.month, end_date.year\n</code></pre>\n<p>That said, if you're at all able, drop that date format like a sack of rotten potatoes. YYYY-mm-dd is sortable and unambiguous.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T10:29:45.240",
"Id": "505377",
"Score": "0",
"body": "Thanks a lot, a very useful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T00:26:30.060",
"Id": "255973",
"ParentId": "255936",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T12:15:58.937",
"Id": "255936",
"Score": "2",
"Tags": [
"python"
],
"Title": "News feed python script"
}
|
255936
|
<p>I have this array of objects:</p>
<pre class="lang-js prettyprint-override"><code>const dataset = [
{name: 'Paul', age: 10},
{name: 'Marcus', age: 5},
{name: 'Jennifer', age: 1},
{name: 'Linda', age: 53},
{name: 'Mary', age: 4},
{name: 'Rose', age: 40},
{name: 'Peter', age: 2},
]
</code></pre>
<p>and an array of ranges:</p>
<pre class="lang-js prettyprint-override"><code>const buckets = [[0, 10], [10, 20], [20, 30], [30, 60]]
</code></pre>
<p>This is what I would like to get:</p>
<pre class="lang-js prettyprint-override"><code>const result = {
"0-10": {
res: [{name: 'Marcus', age: 5}, {name: 'Jennifer', age: 1}, {name: 'Mary', age: 4}, {name: 'Peter', age: 2}],
count: 4
},
"10-20": {res: [{name: 'Paul', age: 10}], count: 1},
"20-30": {res: [], count: 0},
"30-60": {res: [{name: 'Linda', age: 53}, {name: 'Rose', age: 40}], count: 2},
}
</code></pre>
<p>So I would like to get an object where each key is the bucket range (as string) and each value is an object that contains two info: <code>res</code> should be an array of people whose <code>age</code> is inside that bucket (<code>min <= age < max</code>) and <code>count</code> is the lenght of that array.</p>
<p>Here is my code:</p>
<pre class="lang-js prettyprint-override"><code>const res = buckets.reduce((acc, bucketExtent) => {
const keyBucket = `${bucketExtent[0]}-${bucketExtent[1]}`
const people = dataset.filter(
(s) => s['age'] >= bucketExtent[0] && s['age'] < bucketExtent[1]
)
acc[keyBucket] = {
res: people,
count: people.length,
}
return acc
}, {})
</code></pre>
<p>It works but there is a smarter way? I prefer not to loop everytime the <code>dataset</code> array because it will be very large</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:36:18.167",
"Id": "505130",
"Score": "0",
"body": "That `count` property hurts my brain.. why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:54:30.277",
"Id": "505135",
"Score": "0",
"body": "It's only an example"
}
] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li>You are definitely looping indeed over every entry 4 times</li>\n<li>This belongs in a well named function</li>\n<li>Other than that, it is very straight forward and understandable</li>\n</ul>\n<p>I was thinking that people don't live all that long, you could easily build a lookup table for every possible age. This could speed this up quite a bit.</p>\n<p>So something like this;</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const dataset = [\n {name: 'Paul', age: 10},\n {name: 'Marcus', age: 5},\n {name: 'Jennifer', age: 1},\n {name: 'Linda', age: 53},\n {name: 'Mary', age: 4},\n {name: 'Rose', age: 40},\n {name: 'Peter', age: 2},\n]\n\nconst buckets = [[0, 10], [10, 20], [20, 30], [30, 60]]\n\nfunction createAgeBuckets(dataset, buckets){\n const start = 0, end = 1;\n const out = {}, ages = [];\n \n //Create age range\n for(const bucket of buckets){\n bucketRange = `${bucket[start]}-${bucket[end]}`;\n out[bucketRange] = {res: [], count: 0}; \n for(let age = bucket[start]; age < bucket[end];age++){\n ages[age] = out[bucketRange];\n }\n }\n\n //Create bucketses\n dataset.forEach(person => {\n ages[person.age].res.push(person);\n ages[person.age].count++;\n });\n\n return out;\n}\n\nconsole.log(createAgeBuckets(dataset, buckets));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:59:35.820",
"Id": "255942",
"ParentId": "255937",
"Score": "1"
}
},
{
"body": "<p>One approach for reducing the amount of nested loops was to create kind of an <strong><code>usher</code></strong> or <em><strong>attendant</strong></em> functionality which takes/reads a number value and immediately, due to simple min/max value comparison, returns the correct bucket key.</p>\n<p>Since one has to preprocess this <code>usher</code> from a list of (bucket) ranges, one in addition can create (within the same process) each possible bucket's default entry (key and value) as kind of an <code>index</code> which then is part of the start value of the later data reducing/collecting process.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function createBucketConfig(bucketList) {\n const {\n\n index, // bucket index.\n assignmentList,\n\n } = bucketList.reduce((config, [min, max]) => {\n\n const bucketKey = `${ min }-${ max }`;\n const assignment = num => (num < max) && (num >= min) && bucketKey;\n\n config.index[bucketKey] = { res: [], count: 0 }; // default bucket value.\n config.assignmentList.push(assignment);\n\n return config;\n\n }, { index: {}, assignmentList: [] });\n\n const usher = num => {\n let bucketKey;\n assignmentList.some(assignment => {\n bucketKey = assignment(num);\n return !!bucketKey;\n });\n return bucketKey || 'out-of-range';\n };\n\n return {\n index, // bucket index.\n usher, // bucket usher.\n }\n}\n\n\nconst dataset = [\n {name: 'Paul', age: 10},\n {name: 'Marcus', age: 5},\n {name: 'Jennifer', age: 1},\n {name: 'Linda', age: 53},\n {name: 'Mary', age: 4},\n {name: 'Rose', age: 40},\n {name: 'Peter', age: 2},\n];\nconst buckets = [[0, 10], [10, 20], [20, 30], [30, 60]];\n\n\nconst { index, usher } = createBucketConfig(buckets);\n\nconsole.log('usher(0) :', usher(0));\nconsole.log('usher(5) :', usher(5));\nconsole.log('usher(10) :', usher(10));\nconsole.log('usher(11) :', usher(11));\nconsole.log('usher(19) :', usher(19));\nconsole.log('usher(20) :', usher(20));\nconsole.log('usher(29) :', usher(29));\nconsole.log('usher(30) :', usher(30));\nconsole.log('usher(60) :', usher(60));\n\nconsole.log('default bucket index ... ', index);\n\nconsole.log(\n 'reduced into buckets via preprocessed bucket config ...',\n\n dataset.reduce((collector, data) => {\n const { usher, index } = collector;\n const bucketKey = usher(data.age);\n\n const bucket = index[bucketKey] || (index[bucketKey] = { res: [] });\n\n bucket.res.push(data);\n bucket.count = bucket.res.length;\n\n return collector;\n\n }, createBucketConfig(buckets)).index\n);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:39:09.800",
"Id": "508169",
"Score": "0",
"body": "@whitecircle ... are there any questions left regarding the above approach?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T16:35:42.830",
"Id": "256625",
"ParentId": "255937",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T13:13:11.043",
"Id": "255937",
"Score": "4",
"Tags": [
"javascript",
"mapreduce"
],
"Title": "Put every object in a specified bucket"
}
|
255937
|
<p>I am new to C++ and Data structures, so I have started writing a custom vector as a practice.
Please provide critique and advice.
I know it is quite long, so thank you very much in advance. I just want to get better and not to get used to bad practices.</p>
<pre><code> #pragma once
#include <iostream>
#include <utility>
#include <algorithm>
#include <cstddef>
namespace DataStructures {
template<typename T>
class vector {
public:
using size_type = std::size_t;
template <typename DataType>
class BDIterator {
friend class vector;
public:
using difference_type = ptrdiff_t;
using value_type = DataType;
using pointer = DataType*;
using reference = DataType&;
using iterator_category = std::random_access_iterator_tag;
explicit BDIterator(const pointer data = nullptr) : m_address(data) {
}
reference operator*() const {
return *m_address;
}
pointer operator->() const {
return m_address;
}
BDIterator& operator++() {
++m_address;
return *this;
}
BDIterator operator++(int) {
BDIterator res(*this);
++(*this);
return res;
}
BDIterator& operator+=(int n) {
while (n--) {
++(*this);
}
return *this;
}
BDIterator operator+(int n) const {
BDIterator tmp(*this);
tmp += n;
return tmp;
}
BDIterator& operator--() {
--m_address;
return *this;
}
BDIterator operator--(int) {
BDIterator res(*this);
--(*this);
return res;
}
BDIterator& operator-=(int n) {
while (n--) {
--(*this);
}
return *this;
}
BDIterator operator-(int n) const {
BDIterator tmp(*this);
tmp -= n;
return tmp;
}
difference_type operator-(const BDIterator& rhs) const {
return m_address - rhs.m_address;
}
reference operator[](size_type ind) const {
return (*(*this + ind));
}
bool operator==(const BDIterator& other) const noexcept {
return m_address == other.m_address;
}
bool operator!=(const BDIterator& other) const noexcept {
return !(other == *this);
}
bool operator<(const BDIterator& other) const noexcept {
return m_address < other.m_address;
}
bool operator>(const BDIterator& other) const noexcept {
return other < *this;
}
private:
pointer m_address;
};
template <>
class BDIterator<T> {
public:
operator BDIterator<const T>() {
return BDIterator<const T>(m_address);
}
};
using iterator = BDIterator<T>;
using const_iterator = BDIterator<const T>;
template <typename DataType>
class BDRIterator {
friend class vector;
public:
using difference_type = ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;
explicit BDRIterator(const pointer data = nullptr) : m_address(data) {}
explicit BDRIterator(BDIterator<T> iterator) : m_address(iterator.m_address - 1) {}
reference operator*() const {
return *m_address;
}
pointer operator->() const {
return m_address;
}
BDRIterator& operator++() {
--m_address;
return *this;
}
BDRIterator operator++(int) {
BDRIterator res(*this);
--(*this);
return res;
}
BDRIterator& operator+=(int n) {
while (n--) {
++(*this);
}
return *this;
}
BDRIterator operator+(int n) const {
BDRIterator tmp(*this);
tmp -= n;
return tmp;
}
BDRIterator& operator--() {
++m_address;
return *this;
}
BDRIterator operator--(int) {
BDRIterator res(*this);
++(*this);
return res;
}
BDRIterator& operator-=(int n) {
while (n--) {
--(*this);
}
return *this;
}
BDRIterator operator-(int n) const {
BDRIterator tmp(*this);
tmp += n;
return tmp;
}
difference_type operator-(const BDRIterator& rhs) const {
return m_address - rhs.m_address;
}
reference operator[](size_type ind) const {
return (*(m_address - ind));
}
BDIterator<T> base() {
return BDIterator<T>(m_address + 1);
}
bool operator==(const BDRIterator& other) const noexcept {
return m_address == other.m_address;
}
bool operator!=(const BDRIterator& other) const noexcept {
return !(other == *this);
}
bool operator<(const BDRIterator& other) const noexcept {
return m_address > other.m_address;
}
bool operator>(const BDRIterator& other) const noexcept {
return other < *this;
}
private:
pointer m_address;
};
using reverse_iterator = BDRIterator<T>;
using const_reverse_iterator = BDRIterator<const T>;
explicit vector(size_type = INITIAL_CAPACITY);
vector(size_type, const T&);
template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>
vector(InputIterator first, InputIterator last) : vector(std::distance(first, last)) {
while (first != last) {
emplace_back(*first);
++first;
}
}
vector(const vector&);
vector(vector&&) noexcept;
vector(std::initializer_list<T>);
vector& operator=(vector);
vector& operator=(vector&&) noexcept;
vector& operator=(std::initializer_list<T>);
~vector();
template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>
void assign(InputIterator, InputIterator) {
vector tmp(first, last);
tmp.swap(*this);
}
void assign(size_type, const T&);
void assign(std::initializer_list<T>);
void push_back(const T&);
void push_back(T&&);
template<typename... Ts>
void emplace_back(Ts&&...);
void pop_back() noexcept;
iterator erase(const_iterator);
iterator erase(const_iterator, const_iterator);
iterator insert(iterator position, const T& val);
iterator insert(iterator position, size_type n, const T& val);
template<class InputIterator>
iterator insert(iterator position, InputIterator first, InputIterator last);
iterator insert(iterator position, T&& val);
iterator insert(iterator position, std::initializer_list<T> il);
template <typename... Ts>
iterator emplace(const_iterator position, Ts&&... args);
void reserve(size_type);
void resize(size_type);
void resize(size_type, const T&);
T& operator[](size_type);
const T& operator[](size_type) const;
T& at(size_type);
const T& at(size_type) const;
T& front();
const T& front() const;
T& back();
const T& back() const;
T* data() noexcept;
const T* data() const noexcept;
bool empty() const noexcept;
size_type size() const noexcept;
size_type capacity() const noexcept;
bool contains(const T&) const noexcept;
void shrink_to_fit();
void swap(vector&);
void clear() noexcept;
iterator begin() noexcept {
return iterator(m_data);
}
iterator end() noexcept {
return iterator(m_data + m_size);
}
const_iterator begin() const noexcept {
return const_iterator(m_data);
}
const_iterator end() const noexcept {
return const_iterator(m_data + m_size);
}
reverse_iterator rbegin() noexcept {
return reverse_iterator(end());
}
reverse_iterator rend() noexcept {
return reverse_iterator(begin());
}
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(begin());
}
const_iterator cbegin() const noexcept {
return begin();
}
const_iterator cend() const noexcept {
return end();
}
const_reverse_iterator crbegin() const noexcept {
return rbegin();
}
const_reverse_iterator crend() const noexcept {
return rend();
}
private:
void allocateMemory_(T*&, size_type);
void destructObjects_() noexcept;
void moveBackwards_(const_iterator, size_type);
private:
size_type m_size = 0;
size_type m_capacity = 0;
T* m_data = nullptr;
static const short INITIAL_CAPACITY = 2;
static const short FACTOR = 2;
};
template<typename T>
bool operator==(const vector<T>& lhs, const vector<T>& rhs);
template<typename T>
bool operator!=(const vector<T>& lhs, const vector<T>& rhs);
template<typename T>
bool operator>(const vector<T>& lhs, const vector<T>& rhs);
template<typename T>
bool operator>=(const vector<T>& lhs, const vector<T>& rhs);
template<typename T>
bool operator<(const vector<T>& lhs, const vector<T>& rhs);
template<typename T>
bool operator<=(const vector<T>& lhs, const vector<T>& rhs);
template<typename T>
vector<T>::vector(size_type capacity) : m_capacity(capacity) {
allocateMemory_(m_data, m_capacity);
}
template<typename T>
vector<T>::vector(size_type n, const T& val) : vector(n) {
while (n--) {
emplace_back(val);
}
}
template<typename T>
vector<T>::vector(const vector& rhs) : vector(rhs.cbegin(), rhs.cend()) {}
template<typename T>
vector<T>::vector(vector&& rhs) noexcept : m_data(nullptr), m_size(0), m_capacity(0) {
rhs.swap(*this);
}
template<typename T>
vector<T>::vector(std::initializer_list<T> rhs) : vector(rhs.begin(), rhs.end()) {
}
template<typename T>
vector<T>& vector<T>::operator=(vector rhs) {
rhs.swap(*this);
return *this;
// return *this = vector<T>{rhs}; <- copy-assign via move-assign
}
template<typename T>
vector<T>& vector<T>::operator=(vector&& rhs) noexcept {
rhs.swap(*this);
return *this;
}
template<typename T>
vector<T>& vector<T>::operator=(std::initializer_list<T> il) {
vector tmp(il.begin(), il.end());
tmp.swap(*this);
return *this;
}
template<typename T>
vector<T>::~vector() {
clear();
}
template<typename T>
void vector<T>::assign(size_type n, const T& val) {
vector tmp(n, val);
tmp.swap(*this);
}
template<typename T>
void vector<T>::assign(std::initializer_list<T> il) {
assign(il.begin(), il.end());
}
template<typename T>
void vector<T>::push_back(const T& element) {
emplace_back(element);
}
template<typename T>
void vector<T>::push_back(T&& element) {
emplace_back(std::move(element));
}
template <typename T>
template <typename ...Ts>
void vector<T>::emplace_back(Ts&&... args) {
if (!m_data || m_size == m_capacity) {
reserve(m_capacity * FACTOR);
}
new(m_data + m_size) T(std::forward<Ts>(args)...);
++m_size;
}
template<typename T>
void vector<T>::pop_back() noexcept {
m_data[--m_size].~T();
}
template<typename T>
typename vector<T>::iterator vector<T>::erase(typename vector<T>::const_iterator position) {
//std::advance(it,std::distance(cbegin(),position));
//iterator iter = begin() + ( position - cbegin() );
//std::move( iter + 1, end(), iter );
//pop_back();
//return iter;
return erase(position, position + 1);
}
template<typename T>
typename vector<T>::iterator
vector<T>::erase(typename vector<T>::const_iterator first, typename vector<T>::const_iterator last) {
//UB on invalid range
iterator iter = begin() + (first - cbegin());
int removed_elements = last - first;
std::move(last, cend(), iter);
while (removed_elements--) {
pop_back();
}
return iter;
}
template<typename T>
typename vector<T>::iterator vector<T>::insert(vector::iterator position, const T& val) {
moveBackwards_(position-1, 1);
size_type offset = position - cbegin();
m_data[offset] = val;
++m_size;
return (begin() + offset);
}
template<typename T>
typename vector<T>::iterator vector<T>::insert(vector::iterator position, size_type n, const T& val) {
moveBackwards_(position-1, n);
size_type offset = position - cbegin();
for (int i = 0; i < n; ++i) {
m_data[offset + i] = val;
}
m_size += n;
return (begin() + offset);
}
template<typename T>
template<class InputIterator>
typename vector<T>::iterator
vector<T>::insert(vector::iterator position, InputIterator first, InputIterator last) {
size_type count = std::distance(first, last);
moveBackwards_(position-1, count);
size_type offset = position - cbegin();
int i = 0;
while (first != last) {
m_data[offset + i] = *first;
++first;
++i;
}
m_size += count;
return (begin() + offset);
}
template<typename T>
template<typename ...Ts>
typename vector<T>::iterator vector<T>::emplace(vector<T>::const_iterator position, Ts&&...args)
{
moveBackwards_(position, 1);
size_type offset = position - cbegin();
new(m_data + offset - 1)T(std::forward<Ts>(args)...);
++m_size;
return (begin() + offset);
}
template<typename T>
typename vector<T>::iterator vector<T>::insert(vector::iterator position, T&& val) {
return emplace(position, std::forward<T>(val));
}
template<typename T>
typename vector<T>::iterator vector<T>::insert(vector::iterator position, std::initializer_list<T> il) {
return insert(position, il.begin(), il.end());
}
template<typename T>
void vector<T>::reserve(size_type size) {
if (size == 0) {
size = INITIAL_CAPACITY;
}
else if (size <= m_capacity) {
return;
}
T* newData = nullptr;
allocateMemory_(newData, size);
size_type i = 0;
for (; i < m_size; ++i) {
new(newData + i)T(std::move(m_data[i]));
}
clear();
m_data = newData;
m_capacity = size;
m_size = i;
}
template<typename T>
void vector<T>::resize(size_type size) {
resize(size, T());
}
template<typename T>
void vector<T>::resize(size_type size, const T& value) {
reserve(size);
if (size <= m_size) {
while (m_size > size) {
pop_back();
}
}
else {
while (m_size < size) {
push_back(value);
}
}
}
template<typename T>
T& vector<T>::operator[](size_type idx) {
return *(m_data + idx);
}
template<typename T>
const T& vector<T>::operator[](size_type idx) const {
return *(m_data + idx);
}
template<typename T>
T& vector<T>::at(size_type idx) {
if (idx >= m_size) {
throw (std::out_of_range("Invalid index"));
}
return *(m_data + idx);
}
template<typename T>
const T& vector<T>::at(size_type idx) const {
if (idx >= m_size) {
throw (std::out_of_range("Invalid index"));
}
return *(m_data + idx);
}
template<typename T>
T& vector<T>::front() {
return *m_data;
}
template<typename T>
const T& vector<T>::front() const {
return *m_data;
}
template<typename T>
T& vector<T>::back() {
return *(m_data + m_size - 1);
}
template<typename T>
const T& vector<T>::back() const {
return *(m_data + m_size - 1);
}
template<typename T>
T* vector<T>::data() noexcept {
return m_data;
}
template<typename T>
const T* vector<T>::data() const noexcept {
return m_data;
}
template<typename T>
bool vector<T>::empty() const noexcept {
return (m_size == 0);
}
template<typename T>
typename vector<T>::size_type vector<T>::size() const noexcept {
return m_size;
}
template<typename T>
typename vector<T>::size_type vector<T>::capacity() const noexcept {
return m_capacity;
}
template<typename T>
bool vector<T>::contains(const T& element) const noexcept {
for (int i = 0; i < m_size; ++i) {
if (m_data[i] == element) {
return true;
}
}
return false;
}
template<typename T>
void vector<T>::shrink_to_fit() {
vector(*this).swap(*this);
}
template<typename T>
void vector<T>::swap(vector& rhs) {
using std::swap;
swap(m_data, rhs.m_data);
swap(m_size, rhs.m_size);
swap(m_capacity, rhs.m_capacity);
}
template<typename T>
void vector<T>::clear() noexcept {
destructObjects_();
operator delete(m_data);
m_data = nullptr;
m_capacity = 0;
}
template<typename T>
void vector<T>::allocateMemory_(T*& destination, size_type capacity) {
destination = static_cast<T*>(operator new[](capacity * sizeof(T)));
}
template<typename T>
void vector<T>::destructObjects_() noexcept {
while (!empty()) {
pop_back();
}
}
template<typename T>
void vector<T>::moveBackwards_(vector::const_iterator position, size_type space) {
size_type elementsToMove = end() - position;
if (m_size + space >= m_capacity) {
reserve(m_capacity * FACTOR);
}
for (int i = 0; i < elementsToMove; ++i) {
new(m_data + m_size + space - i) T(std::move(m_data[m_size - i]));
}
}
template<typename T>
bool operator==(const vector<T>& lhs, const vector<T>& rhs) {
if (lhs.size() != rhs.size()) {
return false;
}
for (int i = 0; i < lhs.size(); ++i) {
if (lhs[i] != rhs[i]) {
return false;
}
}
return true;
}
template<typename T>
bool operator!=(const vector<T>& lhs, const vector<T>& rhs) {
return !(lhs == rhs);
}
template<typename T>
bool operator>(const vector<T>& lhs, const vector<T>& rhs) {
return rhs < lhs;
}
template<typename T>
bool operator>=(const vector<T>& lhs, const vector<T>& rhs) {
return !(lhs < rhs);
}
template<typename T>
bool operator<(const vector<T>& lhs, const vector<T>& rhs) {
int i = 0;
while (i < lhs.size() && i < rhs.size() && lhs[i] == rhs[i]) {
++i;
}
if (i == lhs.size() || i == rhs.size()) {
return lhs.size() < rhs.size();
}
return lhs[i] < rhs[i];
}
template<typename T>
bool operator<=(const vector<T>& lhs, const vector<T>& rhs) {
return !(rhs < lhs);
}
}
</code></pre>
<p>Questions:</p>
<ul>
<li>I can't understand this part:</li>
</ul>
<pre><code> template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>
</code></pre>
<ol>
<li>Why do I need <code>typename = </code>?</li>
<li>Is there any way I can separate declaration from definition here?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T17:02:10.330",
"Id": "505150",
"Score": "2",
"body": "You do know that writing a good Vector (even one that's not allocator-aware) is pretty advanced for an exercise, right? And if you don't understand why you need `typename`, how did you actually write that part? You are expected to understand your code when you post it here, so your question 1 is off-topic. To some extent, so is question 2, but that's likely to be answered in the course of review anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T17:31:10.193",
"Id": "505151",
"Score": "2",
"body": "@TobySpeight I am just starting to read about type traits and saw somewhere it was done this way. I don't see what's wrong with asking about it when I could not find a proper explanation. Isn't that the whole point of the exercise?\nAnd yes, I know that writing a good vector is pretty advanced, but I got to start somewhere. Everyone starts with vector when talking about Data Structures, as far as I know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T18:09:20.447",
"Id": "505154",
"Score": "0",
"body": "Trying to re-invent the wheel is a big bad practice that should be avoided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T18:35:55.660",
"Id": "505158",
"Score": "4",
"body": "@Casey Nonsense. Re-implementing existing stuff is one of the best ways to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T19:45:39.643",
"Id": "505166",
"Score": "3",
"body": "Have a read here: https://lokiastari.com/series/ Look at the four articles I wrote about vectors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:46:35.857",
"Id": "505171",
"Score": "4",
"body": "I was just making sure you know the level you're aiming at here. If that's what you want to attempt, there's nothing wrong with that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T11:44:28.237",
"Id": "505317",
"Score": "0",
"body": "My favorite pitfall when implementing `vector`, found in almost every implementation attempt: `v.push_back(v[0])` runs into undefined behavior when the vector needs to grow, because `reserve` frees the old memory and thus invalidates the reference given to `push_back` before the new object is created."
}
] |
[
{
"body": "<h2>Answers</h2>\n<pre><code>template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>\nvector(InputIterator first, InputIterator last)\n</code></pre>\n<blockquote>\n<p>I can't understand this part:</p>\n</blockquote>\n<p>This is using SFINE to make that constructor available or not available depending on the type of the iterator used.</p>\n<p>If the user of your class passed two iterators that are not <code>integral</code> then the <code>std::enable_if</code> will fail to resolve. This means that compilation will fail as this constructor is not valid (not all the type resolved correctly).</p>\n<p>This causes an error for the user of your code (i.e. they get an error that they are not using a valid constructor). This is better than getting an error that points deep inside your vector code saying some type they have never used or heard of is not compiling and then thinking you wrote a bad vector class.</p>\n<p>Note: SFINE: > <code>Substitution Failure Is Not an Error</code> (another great acronym from C++ just like RAII). What this is saying that if we are trying to resolve types (using substitution) and not all the types can be resolved this is not an error. The offending method/class is simply never created.</p>\n<p>You can think of SFINE as the predecessor to <code>C++ concepts</code> (coming to you in a compiler where std=20). Concepts has been bounced around a lot over the last 17 years never quite making into the standard because of issues; so SFINE is the crippled cousin that sort of gets us 90% of what we want even if it is hard to read.</p>\n<blockquote>\n<p>Why do I need typename = ?</p>\n</blockquote>\n<p>The <code>std::enable_if</code> either resolves to a type or not. Which makes it compile or not. But you need a template parameter for it. But like parameters to normal functions it is rarely used so you can leave off the name.</p>\n<p>You could write it like <code><typename I, typename Enabled = std::endable_if<......></code> You then have the typename in Enabled but you don't use it.</p>\n<blockquote>\n<p>Is there any way I can separate declaration from definition here?</p>\n</blockquote>\n<p>Sure it is just like normal functions with predefined parameters. You declare it like above. But the definition you don't add the <code> = stuff</code> part.</p>\n<p>Example:</p>\n<pre><code> // declaration\n int function1(int val = 5);\n\n // definition\n int function1(int val) {return val + 1;} // note no = 5 here.\n</code></pre>\n<p>Note: here you don't need a parameter name here either.</p>\n<pre><code> // declaration\n int function2(int = 8);\n\n // definition\n int function2(int) {return 8;} // note no = 8 here.\n</code></pre>\n<p>Same thing for the template parameters:</p>\n<pre><code> // declaration\n template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>\n vector(InputIterator first, InputIterator last);\n\n // definition\n template<typename InputIterator, typename>\n vector(InputIterator first, InputIterator last)\n : vector(std::distance(first, last))\n {\n while (first != last) {\n emplace_back(*first);\n ++first;\n }\n }\n</code></pre>\n<p>Note in later version (C++14) both <code>std::enable_if</code> and <code>std::is_integral</code> have helper things that shorten that up a lot. For meta things that return types add the suffix <code>_t</code> (no longer need the typename), for meta things that return values add the suffix <code>_v</code>. This shortens the above_to:</p>\n<pre><code>template<typename InputIterator, typename = std::enable_if_t<!std::is_integral_v<InputIterator>>>\nvector(InputIterator first, InputIterator last);\n</code></pre>\n<h2>Overview</h2>\n<p>Overall this is very good.</p>\n<p>Couple of minor issues that I have documented below, but your memory management is relatively solid. Only a couple of minor mistakes around the lifetime of objects (where you use placement new on an object whose lifetime has already started).</p>\n<p>Normally I don't suggest this (as people have a lot of work to do). But for this project the next step is add a bunch of unit tests.</p>\n<p>In generally using DRY principles to make sure you don't repeat the code is good. I think you overuse this a bit especially for trivial functions that simply return an iterator. There are a lot of places were it would have been more obvious to do maths using the m_data object rather than getting the iterator and doing mathematics with that.</p>\n<h2>Code Review</h2>\n<p>A member class is part of the parent class and thus has accesses to all its members. In this case <code>BDIterator</code> is a member of <code>vector</code> so <code>BDIterator</code> automatically has accesses to all members of vector.</p>\n<pre><code> class BDIterator {\n friend class vector; // Thus this line is not needed.\n</code></pre>\n<hr />\n<p>The advantaage of random accesses iterator is that you do a const time increment of the iterator. You have a <code>O(n)</code> cost to increment the iterator here.</p>\n<pre><code> BDIterator& operator+=(int n) {\n while (n--) {\n ++(*this);\n }\n return *this;\n }\n</code></pre>\n<hr />\n<p>Normally you implement <code>+</code> using the <code>+=</code>. You have done it the other way around. Not really a big deal but its interesting. For this iterator it is som simple that adding this level of indirection is not really needed.</p>\n<pre><code> BDIterator operator+(int n) const {\n BDIterator tmp(*this);\n tmp += n;\n return tmp;\n }\n</code></pre>\n<hr />\n<p>This seems like a complex way of writting <code>return m_address[ind]</code>.</p>\n<pre><code> reference operator[](size_type ind) const {\n return (*(*this + ind));\n }\n</code></pre>\n<p>Here you are getting a reference to an iterator adding an offset which creates a new iterator then de-referencing the temporary iterator object. I am sure the compiler works it all out and gives you an effecient implementation. But I don't think you need to make it work that hard:</p>\n<hr />\n<p>I would not bother writting a reverse iterator. You can use the staandard wrapper <a href=\"https://en.cppreference.com/w/cpp/iterator/reverse_iterator\" rel=\"noreferrer\">std::reverse_iterator</a></p>\n<hr />\n<p>Why does the copy constructor use a const reference but the copy assignment takes a member.</p>\n<pre><code> vector(const vector&);\n vector& operator=(vector);\n</code></pre>\n<hr />\n<p>This is a syntax error so this would generate an error if you had a unit test. You get away with this because it is a template and you don't use it.</p>\n<pre><code> template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>\n void assign(InputIterator, InputIterator) { // Missing parameters names\n vector tmp(first, last);\n tmp.swap(*this);\n }\n</code></pre>\n<hr />\n<p>This has a different meaning to <code>std::vector</code>.</p>\n<pre><code>template<typename T>\nvector<T>::vector(size_type capacity) : m_capacity(capacity) {\n allocateMemory_(m_data, m_capacity);\n}\n</code></pre>\n<p>You are using the passed size to mean the capacity. While std::vector uses it means to actual size of the object (i.e. it will filled with <code>capacity</code> valid objects (default constructed)).</p>\n<hr />\n<strike>\nDon't think passing const iterators to a method that mutates the object is sending the correct message.\n \n template\n typename vector::iterator\n vector::erase(typename vector::const_iterator first, typename vector::const_iterator last) {\n</strike>\n<hr />\n<p>In the last three uses of insert:</p>\n<pre><code>typename vector<T>::iterator vector<T>::insert(vector::iterator position, const T& val)\ntypename vector<T>::iterator vector<T>::insert(vector::iterator position, size_type n, const T& val)\ntypename vector<T>::iterator\n vector<T>::insert(vector::iterator position, InputIterator first, InputIterator last) \n</code></pre>\n<p>The method <code>moveBackwards_()</code> moves objects to the right but the object at location <code>position</code> is left in a valid state (we know this because you use <code>operator[]</code> to access the object then <code>operator=</code> to copy the inserted value over the current value.</p>\n<p>But in this method:</p>\n<pre><code>typename vector<T>::iterator vector<T>::emplace(vector<T>::const_iterator position, Ts&&...args)\n</code></pre>\n<p>You use <code>placement new</code> to construct the obejct. This is <strong>ILLEGAL</strong> as you are calling new on an object whoses lifetime has not ended.</p>\n<pre><code> new(m_data + offset - 1)T(std::forward<Ts>(args)...);\n</code></pre>\n<p>Two alternative are possible. A) End the lifetime of the object (then call new) B) create a new object and move it to that location:</p>\n<pre><code>// End Lifetime:\nm_data[offset].~T();\nnew(m_data + offset)T(std::forward<Ts>(args)...);\n\n// Create and move object.\nm_data[offset] = T(std::forward<Ts>(args)...); // This will move.\n</code></pre>\n<hr />\n<p>Still in <code>emplace()</code>:</p>\n<p>Why do you use <code>-1</code> here?</p>\n<pre><code> new(m_data + offset - 1)T(std::forward<Ts>(args)...);\n</code></pre>\n<p>In all the above <code>insert()</code> uses cases the position of insert is at <code>m_data + offset</code>. What has changed here?</p>\n<hr />\n<p>Inline comments:</p>\n<pre><code>template<typename T>\nvoid vector<T>::reserve(size_type size) {\n if (size == 0) {\n size = INITIAL_CAPACITY;\n }\n // Don't think you want the "else" here.\n //\n // Otherwise by setting a reserve of zero you will also\n // force a resize to a smaller size when no other resize\n // forces a reduction of a size.\n else if (size <= m_capacity) {\n return;\n }\n\n // You shoudl hold this in `std::unique_ptr`\n // If the next loop throws while moving/copying elements\n // you will leak the object.\n T* newData = nullptr;\n allocateMemory_(newData, size);\n\n // You should only use move here if the type T\n // gurnatees that T has a nothrow move constructor.\n // otherwise you need to use copy to ensure that\n // you provide the strong exception gurantee.\n size_type i = 0;\n for (; i < m_size; ++i) {\n new(newData + i)T(std::move(m_data[i]));\n }\n\n\n // If calling the destructor of any of the T object\n // throws an exception then you will leave your object in\n // an invalid state.\n //\n // better to swap the state of the current object and the\n // temporary array first. Then you can destroy the old arry.\n clear();\n\n m_data = newData;\n m_capacity = size;\n m_size = i;\n}\n</code></pre>\n<p>I would write it like this:</p>\n<pre><code>template<typename T>\nvoid vector<T>::reserve(size_type size) {\n\n if (size == 0) {\n size = INITIAL_CAPACITY;\n }\n if (size <= m_capacity) {\n return;\n }\n std::vector<T> tmp(size); // remember you constructor sets capacity.\n\n // Copy if you can't move.\n for(auto& item: *this) {\n tmp.emplace_back(std::move(item));\n } \n\n swap(tmp);\n}\n</code></pre>\n<hr />\n<p>You should mark <code>swap()</code> as <code>noexcept</code>:</p>\n<pre><code>template<typename T>\nvoid vector<T>::swap(vector& rhs) {\n</code></pre>\n<hr />\n<p>Comments inline:</p>\n<pre><code>template<typename T>\nvoid vector<T>::moveBackwards_(vector::const_iterator position, size_type space) {\n size_type elementsToMove = end() - position;\n if (m_size + space >= m_capacity) {\n reserve(m_capacity * FACTOR);\n }\n\n // You can only use `placement new` when you are copying elements beyond\n // m_size. Any elements that are being moved into the current array size\n // must use a normal assignment (move or copy).\n //\n // So the first `space` elements you can use placement new.\n // After that you must use assignment.\n //\n // Also most of the methods that use this method assume that\n // they will be copying into an array of objects whose life time\n // has been started. So for large values of `space` where you \n // moving a small number of elements beyond the end of the array\n // you will need to default construct the object\n for (int i = 0; i < elementsToMove; ++i) {\n new(m_data + m_size + space - i) T(std::move(m_data[m_size - i]));\n }\n}\n</code></pre>\n<hr />\n<p>I don't think this is correct:</p>\n<pre><code>template<typename T>\nbool operator>=(const vector<T>& lhs, const vector<T>& rhs) {\n return !(lhs < rhs);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:30:56.353",
"Id": "505189",
"Score": "0",
"body": "Just to point out that `std::vector::erase` actually does take a `const_iterator` (since C++11): https://en.cppreference.com/w/cpp/container/vector/erase Which, btw, lets us do sneaky things like `auto non_const_it = v.erase(const_it, const_it); // erase nothing, get a non-const iterator!` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:36:47.290",
"Id": "505190",
"Score": "0",
"body": "@user673679 Done a strike through on that item. But I will stick by my comment in this comment. I don't think using const iterator sends the correct message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T09:10:16.593",
"Id": "505306",
"Score": "0",
"body": "@MartinYork Thanks so much! An awesome explanation on SFINAE.\n`Still in emplace(): Why do you use -1 here?` Got confused for some reason. Why do you think my operator>= is not correct? As with numbers : if a number (a) is not smaller than another (b), this means that either a==b or a>b?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:15:02.543",
"Id": "255960",
"ParentId": "255946",
"Score": "9"
}
},
{
"body": "<p><strong>Correctness and testing</strong>:</p>\n<p>First off... note that compilers are not required to <em>do</em> anything with template code unless it's actually used ("instantiation"). Some compilers (or versions of a particular compiler) may check (some) template code for correctness, others may not.</p>\n<p>So writing a template function, we cannot rely on the compiler to give us a compiler error if we make a mistake. This makes unit testing essential - we only know if the function compiles when we use it in some code (let alone whether it does the correct thing).</p>\n<p>There are a couple of things my compiler picks up straight away:</p>\n<pre><code> template <>\n class BDIterator<T> {\n public:\n operator BDIterator<const T>() {\n return BDIterator<const T>(m_address);\n }\n };\n</code></pre>\n<p>This doesn't behave the way you expect it to. Adding a class specialization like this is creating a whole new type of class when the type is T. So <code>m_address</code> doesn't exist in this class, and this is the only function. (There are some other ways of adding the necessary const functionality to an iterator, which I'll talk about below).</p>\n<pre><code> template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>\n void assign(InputIterator, InputIterator) {\n vector tmp(first, last);\n tmp.swap(*this);\n }\n</code></pre>\n<p>We forgot to name the function arguments to <code>first</code> and <code>last</code>!</p>\n<p>(There may be more things that won't compile when we try to use them.)</p>\n<hr />\n<p><strong>typedefs</strong>:</p>\n<p>We're missing a few more standard (and useful) typedefs from the <code>vector</code> class:</p>\n<p><code>value_type</code>, <code>difference_type</code>, <code>pointer</code>, <code>const_pointer</code>, <code>reference</code>, <code>const_reference</code></p>\n<hr />\n<p><strong>std::reverse_iterator</strong>:</p>\n<p>After implementing the forward iterator correctly, we can use the standard library to generate the reverse one:</p>\n<pre><code>using iterator = BDIterator<T>;\nusing reverse_iterator = std::reverse_iterator<iterator>;\n</code></pre>\n<hr />\n<p><strong>constructors</strong>:</p>\n<pre><code> explicit vector(size_type = INITIAL_CAPACITY);\n</code></pre>\n<p>Note that the standard library takes the initial <em>size</em> as an argument, not the capacity, which may confuse users.</p>\n<pre><code> template<typename InputIterator, typename = typename std::enable_if<!std::is_integral<InputIterator>::value>::type>\n vector(InputIterator first, InputIterator last) : vector(std::distance(first, last)) {\n while (first != last) {\n emplace_back(*first);\n ++first;\n }\n }\n</code></pre>\n<p>Using <code>std::distance</code> means that calling this function with "input" iterators (one-pass only) won't work at all, and calling it with "forward" or "bidirectional" iterators (no random access) may be slow.</p>\n<p>A simpler implementation that just calls <code>emplace_back</code> would avoid these issues.</p>\n<p>If we want to pre-allocate memory for random-access iterators, we can do that by <a href=\"https://en.cppreference.com/w/cpp/iterator/iterator_tags\" rel=\"nofollow noreferrer\">dispatching to another function based on the iterator tag</a>.</p>\n<hr />\n<p><strong>use <a href=\"https://en.cppreference.com/w/cpp/header/algorithm\" rel=\"nofollow noreferrer\">standard algorithms</a> where convenient</strong>:</p>\n<pre><code>template<typename T>\nbool vector<T>::contains(const T& element) const noexcept {\n for (int i = 0; i < m_size; ++i) {\n if (m_data[i] == element) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<p>Could be: <code>return std::find(begin(), end(), element) != end();</code></p>\n<pre><code>template<typename T>\nbool operator==(const vector<T>& lhs, const vector<T>& rhs) {\n if (lhs.size() != rhs.size()) {\n return false;\n }\n for (int i = 0; i < lhs.size(); ++i) {\n if (lhs[i] != rhs[i]) {\n return false;\n }\n }\n return true;\n\n}\n</code></pre>\n<p>Could be: <code>return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());</code></p>\n<pre><code>template<typename T>\nbool operator<(const vector<T>& lhs, const vector<T>& rhs) {\n int i = 0;\n while (i < lhs.size() && i < rhs.size() && lhs[i] == rhs[i]) {\n ++i;\n }\n if (i == lhs.size() || i == rhs.size()) {\n return lhs.size() < rhs.size();\n }\n return lhs[i] < rhs[i];\n}\n</code></pre>\n<p>Could be: <code>return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());</code></p>\n<pre><code>template<typename T>\ntemplate<class InputIterator>\ntypename vector<T>::iterator\n vector<T>::insert(vector::iterator position, InputIterator first, InputIterator last) {\n size_type count = std::distance(first, last);\n moveBackwards_(position-1, count);\n \n size_type offset = position - cbegin();\n int i = 0;\n while (first != last) {\n m_data[offset + i] = *first;\n ++first;\n ++i;\n }\n m_size += count;\n return (begin() + offset);\n}\n</code></pre>\n<p>Could perhaps use: <code>std::copy(first, last, begin() + offset);</code></p>\n<p>Note, however, that <code>moveBackwards_</code> may reallocate memory. If it does, the position iterator is invalidated (it still points to the old memory), so we can't do <code>position - cbegin()</code>!</p>\n<hr />\n<p><strong>use uninitialized memory algorithms</strong>:</p>\n<p>C++17 and C++20 also give us <a href=\"https://en.cppreference.com/w/cpp/memory\" rel=\"nofollow noreferrer\">various algorithms for dealing with uninitialized memory</a>. So if they're available, you might want to:</p>\n<ul>\n<li>use <code>std::construct_at</code> instead of placement new.</li>\n<li>use std::destroy(begin(), end()); to destroy objects, instead of repeatedly calling <code>pop_back()</code>.</li>\n<li>use <code>std::uninitialized_move</code> in <code>reserve</code></li>\n<li>use <code>std::uninitialized_move</code> in <code>moveBackwards_</code> (with reverse iterators).</li>\n</ul>\n<hr />\n<p><strong>const and non-const iterators</strong>:</p>\n<p>Nearly everything is the same between const and non-const iterators, so we're really just trying to avoid code duplication.</p>\n<p>Personally I like the trick of adding an extra <code>bool</code> template parameter to the iterator class like so:</p>\n<pre><code>template<class T, bool IsConst>\nclass BDIterator { ... };\n</code></pre>\n<p>Then we can use <code>enable_if</code> to conditionally add the functionality we need:</p>\n<pre><code> template<class C = IsConst, class = std::enable_if_t<C>>\n BDIterator(BDIterator<T, false> other): m_address(other.m_address) { }\n</code></pre>\n<p>And we can declare the iterators as:</p>\n<pre><code>using iterator = BDIterator<T, false>;\nusing const_iterator = BDIterator<T, true>;\n</code></pre>\n<p><a href=\"https://quuxplusone.github.io/blog/2018/12/01/const-iterator-antipatterns/\" rel=\"nofollow noreferrer\">See here for more details</a>.</p>\n<hr />\n<p><strong>pointer arithmetic</strong>:</p>\n<pre><code> BDIterator& operator+=(int n) {\n while (n--) {\n ++(*this);\n }\n return *this;\n }\n</code></pre>\n<p>Rather than repeatedly calling the increment operator, we could just do <code>m_address += n</code>. (And similarly for <code>operator-=</code>).</p>\n<p>Note also that <code>+=</code>, <code>-=</code>, <code>+</code> and <code>-</code> should take the <code>n</code> parameter as a <code>difference_type</code>, and not an <code>int</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T08:33:36.937",
"Id": "505300",
"Score": "0",
"body": "Thank you so much! Learner so many new things!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:22:56.120",
"Id": "255961",
"ParentId": "255946",
"Score": "12"
}
},
{
"body": "<h1>Iterators don't need to be <code>friend</code>s with <code>class vector</code></h1>\n<p>The iterator classes do not need access to private members of <code>vector</code>, so the <code>friend</code> declarations can be removed.</p>\n<h1>Mistakes when using <code>*this</code></h1>\n<p>There are bugs in your implementation, mainly because you do things like:</p>\n<pre><code>BDIterator operator++(int) {\n BDIterator res(*this);\n ++(*this);\n return res;\n}\n</code></pre>\n<p>The line <code>++(*this)</code> should have just been <code>++m_address</code>. In this case it works out, but in the case of the reverse iterator, you introduced a bug:</p>\n<pre><code>BDRIterator operator++(int) {\n BDRIterator res(*this);\n --(*this);\n return res;\n}\n</code></pre>\n<p>Because you call <code>--(*this)</code>, it will actually call <code>BDRIterator::operator--()</code> on itself, which will move the pointer in the wrong direction. I suggest you avoid using <code>*this</code> except when really necessary, like when a function needs to return a reference to its own object.</p>\n<h1>Use the right template parameter</h1>\n<p><code>class BDRIterator</code> is a template with template parameter <code>DataType</code>, however several declarations inside it refer to <code>T</code>, which is wrong.</p>\n<h1>Unnecessary <code>while</code>-loops</h1>\n<p>I see you are using <code>while</code>-loops in <code>operator+=()</code> and <code>operator-=()</code>, but not in <code>operator+</code> and <code>operator-</code>. I guess that is to avoid circular references because, again, you are using <code>*this</code> when you shouldn't. Just have all these operators operator directly on <code>m_address</code> instead.</p>\n<h1>Reverse iterator undefined behavior</h1>\n<p>If you have a pointer to an array, only pointers to elements inside the array, and a pointer right past the end of the array (where the next element would be if it were one element larger) are valid. In your case, <code>rend()</code> points to an address before the start of the array, and thus might invoke undefined behaviour. The fact that <code>base()</code> exists and points to one element further than what the reverse iterator should point to should have been a hint: you have to make <code>rbegin()</code> point to the same address as <code>end()</code>, and <code>rend()</code> the same as <code>begin()</code>. This means it will be one off, but you should just account for that in the dereferencing operators.</p>\n<p>The documentation for <a href=\"https://en.cppreference.com/w/cpp/iterator/reverse_iterator\" rel=\"noreferrer\"><code>std::reverse_iterator</code></a> has a clear diagram of how you should implement it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T09:18:58.947",
"Id": "505308",
"Score": "0",
"body": "Thanks for the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:26:01.913",
"Id": "255963",
"ParentId": "255946",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T14:42:15.597",
"Id": "255946",
"Score": "8",
"Tags": [
"c++",
"c++11",
"vectors"
],
"Title": "C++ Creating custom vector"
}
|
255946
|
<p>I have a function dominates() that seems to be the bottleneck of my algorithm (after profiling it). the function is as follows:</p>
<pre><code>def dominates(self, label1: Label, label2: Label):
"""
compares two labels based on dominance rules
:param label1: label object
:param label2: label object
:return: label2 if label2 is dominated by label1, else returns label1 if label1 is dominated by label2 else returns None
"""
if label1.cost - label1.maxP * label1.ratePiP <= label2.cost - label2.maxP * label2.ratePiP:
if label1.loadF <= label2.loadF:
if label1.part <= label2.part :
if label1.cost - (label2.loadF - label1.loadF) * label1.ratePiP <= label2.cost :
if label1.cost - (label2.loadF + label2.maxP - label1.loadF) * label1.ratePiP <= label2.cost - label2.maxP * label2.ratePiP :
if all(l1 <=l2 for l1,l2 in zip(label1.custk, label2.custk)):
return label2
else:
if label1.loadF >= label2.loadF:
if label1.part >= label2.part:
if label1.cost - (label2.loadF - label1.loadF) * label1.ratePiP >= label2.cost :
if label1.cost - (label2.loadF + label2.maxP - label1.loadF) * label1.ratePiP >=label2.cost - label2.maxP * label2.ratePiP:
if all(l1>= l2 for l1, l2 in zip(label1.custk, label2.custk)):
return label1
</code></pre>
<p>Here is the definition for the label class (it is basically a container of information):</p>
<pre><code>class Label(object):
def __init__(self, node, loadf=None, cost=None, part=None, custk=None, ratePiP=None, maxP=None,
rdp=None, route=None, previous_label=None, ):
self.node: int= node
self.loadF: int = loadf
self.cost: float= cost
self.part: int= part
self.custk = custk # array.array
self.ratePiP: float = ratePiP
self.maxP: int = maxP
self.previous_label : Label= previous_label
self.rdp: List[str]= rdp
self.route = route # array.array
</code></pre>
<p>These dominance rules come from a paper <a href="https://pubsonline.informs.org/doi/10.1287/trsc.2015.0635" rel="nofollow noreferrer">A Branch-Price-and-Cut Algorithm for the Inventory-Routing Problem </a> and the dominance rules are stated there (see picture). It will be long to explain the math behind those conditions and not useful for this post.<br />
<a href="https://i.stack.imgur.com/Oe9oz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Oe9oz.png" alt="enter image description here" /></a><br />
<span class="math-container">\$T_i^{part} \$</span> can take either 0 or 1 (0 more often than 1).<br />
In case <span class="math-container">\$T_i^{part}\$</span> is equal to 0, then <span class="math-container">\$T_i^{maxP}\$</span> and <span class="math-container">\$T_i^{ratePiP}\$</span> are equal to 0.<br />
if <span class="math-container">\$T_i^{part} \$</span> takes 1, then <span class="math-container">\$T_i^{maxP}\$</span> takes non-negative integer values while <span class="math-container">\$T_i^{ratePiP}\$</span> can take any value in R.<br />
The function is called multiple times in the function discard_dominated() below:</p>
<pre><code>def discard_dominated(self, ULj):
"""
:param ULj: list of untreated labels associated with the same vertex
:return: list of non-dominated labels in ULj
"""
dom = self.dominates
to_remove = [dom(label2, label1) for ind, label2 in enumerate(ULj) for label1 in ULj[ind + 1:]]
to_remove = set(to_remove)
return [lab for lab in ULj if lab not in to_remove]
</code></pre>
<p>This function is also called many times in a while loop.<br />
<code>label.cost</code> and <code>label.ratePiP</code> are floats and <code>label.part</code> and <code>label.loadF</code> and <code>label.maxP</code> are integers while <code>label.custk</code> is array.array full of 0 and 1.<br />
I tried to first compute the conditions and save them in local variables and check them (if first condition and second condition and ...) but it was taking more time.<br />
For one small instance that I am testing my algorithm on, the <code>len(ULj)</code> is between 10 and 80 and the length of the removed labels (<code>len(to_remove)</code>) is between 1 and 57 and have most of the time a length less than 10. however for larger instances I would expect that these numbers would be much larger than this. Also the elements of the list <code>ULj</code> are unique by construction.<br />
The number of calls is quite high (25,000,000+ times) and have done my best to reduce it. I am now testing on small instances and it does not seem ok for me to have that much time spent on this function (28971 ms) for small instances. Any idea how to speed it up?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T00:17:35.537",
"Id": "505206",
"Score": "2",
"body": "We cannot review this code as it does not have enough context. Please include any calling code, plus the definition for `Label`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T10:25:42.870",
"Id": "505223",
"Score": "0",
"body": "(This seems to return None in some, if not most cases: intentionally so?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T10:39:36.127",
"Id": "505225",
"Score": "1",
"body": "The part multiplying `label2.maxP` by `label1.ratePiP` in particular begs explanation. Please don't remove the [docstrings](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T12:48:52.557",
"Id": "505232",
"Score": "0",
"body": "@greybeard exactly if the first set of conditions is true then label2 is dominated and it is returned (to be removed from another list) and if the second set of conditions is true then label1 is dominated and is returned, otherwise, we cannot conclude anything and none of the labels is dominated by the other thus the function returns None"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T13:10:46.820",
"Id": "505235",
"Score": "0",
"body": "@Reinderien I added as much details as I see necessary"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T16:16:54.837",
"Id": "505328",
"Score": "0",
"body": "The dominance rules specify a partial order. I'm anything but convinced the approach to removing dominated item coded in `discard_dominated()` is optimal - looking into this next. It would be reassuring to *know* whether the elements of *list*s (say, `ULj` - *unhandled labels of vertex j*?) are unique - it may be beneficial to keep them in *set*s instead for documentation, if not performance benefits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T22:51:48.030",
"Id": "505348",
"Score": "1",
"body": "(Don't prematurely [accept](https://codereview.stackexchange.com/help/accepted-answer) an answer: while \"acceptance can be shifted\", a question with an accepted answer doesn't get quite the same attention.)"
}
] |
[
{
"body": "<p>You use a docstring to good effect. I'd think it <em>great</em> if you followed <a href=\"https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings\" rel=\"nofollow noreferrer\">the rules</a> closely:</p>\n<pre><code>"""\n<whatever sums up this module>.\n\nDominance as defined in Desaulniers/Rakke/Coelho:\n"A Branch-Price-and-Cut Algorithm for the Inventory-Routing Problem"\n"""\n\n\ndef dominates(self, label1: Label, label2: Label):\n """\n Compare two labels based on dominance rules.\n \n :param label1: label object\n :param label2: label object\n :return: label2 if label2 is dominated by label1,\n else returns label1 if label1 is dominated by label2,\n else returns None\n """\n pass\n</code></pre>\n<p>(I'd probably return a truth value, name the method <code>dominated()</code>, or reverse the logic to get <code>dominator()</code>.)</p>\n<p>Let me suggest rewriting</p>\n<p><span class=\"math-container\">$$\\text{(f) }T_1^{cost} - (T_2^{loadF} + T_2^{maxP} - T_1^{loadF})T_1^{ratePiP}\n\\le T_2^{cost} - T_2^{maxP} T_2^{ratePiP}$$</span>\nadding <span class=\"math-container\">\\$T_2^{maxP} T_1^{ratePiP}\\$</span> to both sides turns <em>multiplication of different measures, one from each label</em><br />\ninto <em>scaling differences in loadF by <span class=\"math-container\">\\$T_1^{ratePiP}\\$</span> and differences in ratePiP by <span class=\"math-container\">\\$T_2^{maxP}\\$</span></em>:</p>\n<p><span class=\"math-container\">$$\\text{(f) }T_1^{cost} + (T_1^{loadF} - T_2^{loadF})T_1^{ratePiP}\n\\le T_2^{cost} + (T_1^{ratePiP} - T_2^{ratePiP})T_2^{maxP}$$</span>\nDenoted like this, conditions (e) and (f) look dependant on the signum of <span class=\"math-container\">\\$(T_1^{ratePiP} - T_2^{ratePiP})T_2^{maxP}\\$</span>: if negative, (f) implies (e), else (e) implies (f).<br />\n(If <span class=\"math-container\">\\$T_2^{maxP}\\$</span> was known to be non-negative, comparing rates would suffice.)</p>\n<p>One thing nagging me is <em>dominates</em> in case of <em>all equals</em>.</p>\n<p>Ordering the evaluation of conditions by increasing cost looks prudent; another criterion is <em>more selective first</em>. (One more place where <em>code documentation</em>/<em>review context</em> was valuable: what <em>is</em> <code>Label.part</code>?).<br />\nI'd try and get rid of some of the indentation levels. For readability, I'd prefer <code>and</code> here over <code>return None</code>.<br />\nThe top <code>if</code>-statement and the <code>else</code>-statement look symmetrical enough to be <em>duplicated code</em>: a maintenance nightmare if nothing else. You can get rid of that introducing <em>roles</em>.</p>\n<pre><code>def dominates(self, label1: Label, label2: Label):\n """\n Compare two labels based on dominance rules.\n \n :param label1: label object\n :param label2: label object\n :return: label2 if label2 is dominated by label1,\n else returns label1 if label1 is dominated by label2,\n else returns None\n """\n champ, other = (label2, label1 # (c)\n ) if label1.part <= label2.part else (label1, label2)\n if (champ.loadF < other.loadF # (a)\n or champ.cost - champ.maxP * champ.ratePiP # (d)\n < other.cost - other.maxP * other.ratePiP):\n return None\n scaled_rate_delta = (other.ratePiP - champ.ratePiP) * champ.maxP\n if (other.cost + (other.loadF - champ.loadF) * other.ratePiP\n <= champ.cost + min(0, scaled_rate_delta) # (e)&(f)\n and all(lo <= lc for lo, lc in zip(other.custk, champ.custk))): # (b)\n return champ\n \n return None\n</code></pre>\n<p>I hope some calls can be obviated excluding inferiors from further competition:</p>\n<pre><code>def discard_dominated(self, ULj):\n """\n Discard dominated labels from ULj.\n \n :param ULj: collection of untreated labels associated with the same vertex\n :return: collection of non-dominated labels in ULj\n """\n survivors = set() # no domination within this set\n for sample in ULj:\n # casualties = { dominates(sample, veteran) for veteran in survivors }\n casualties = set()\n for veteran in survivors: # allows "early out"\n inferior = dominates(sample, veteran)\n if inferior is sample:\n break # casualties empty (really?)\n if inferior: # is veteran/not None\n casualties += veteran\n else:\n survivors += sample\n survivors -= casualties # not dead sure this belongs in else\n return survivors\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T19:57:37.800",
"Id": "505278",
"Score": "1",
"body": "(Without a test harness, I've more likely gotten at least one negation wrong than all of them right: anybody confident to know better please correct.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T15:23:18.963",
"Id": "505323",
"Score": "0",
"body": "in case of equality, both labels are equivalent and one should remain, the other is discarded (hence return label2 in my first function). I tried your code but it takes even more time. However, I will see what I can do with your insights regarding (e) and (f)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T15:26:40.570",
"Id": "505324",
"Score": "0",
"body": "also T_2^maxP is non-negative and T2^part can take either 0 or 1, and takes 0 more times than 1. also if T2^part is 0 then T2^ratePiP and T2maxP are equal to 0 which means the conditions (d) (e) and (f) are reduced to T_1^cost <=T_2^cost. I will see if this will speed up my function!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T11:57:17.137",
"Id": "505381",
"Score": "0",
"body": "Not sure about this one because function calls overheads but `other, champ = sorted((label1, label2), key=operator.attrgetter('part'))` might be more readable than your ternary"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T19:56:06.330",
"Id": "255999",
"ParentId": "255948",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T16:26:26.597",
"Id": "255948",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"scipy"
],
"Title": "compare between two labels /objects -dominance rules"
}
|
255948
|
<p><strong>Relevant Background:</strong></p>
<p>Greetings. This is my first attempt at using the OOP paradigm (only really used <code>R</code> prior to this).</p>
<p>The project prompt came from <code>JetBrains Academy</code> where I am currently working through the <code>Python Developer</code> track. The code works as expected and was accepted for the particular stage I am on, but I have some specific questions that will hopefully improve the program.</p>
<p><strong>Objective:</strong></p>
<blockquote>
<p>You should allow customers to create a new account in our banking system.</p>
</blockquote>
<p><strong>Program Details:</strong></p>
<blockquote>
<p>Once the program starts, you should print the menu:</p>
</blockquote>
<pre><code>1. Create an account
2. Log into account
0. Exit
</code></pre>
<blockquote>
<p>In our banking system, the credit card number's IIN (first 6 digits) must be 400000.</p>
</blockquote>
<blockquote>
<p>We often see 16-digit credit card numbers today, but it’s possible to issue a card with up to 19 digits using the current system. In the future, we may see longer numbers becoming more common.
In our banking system, the customer account number can be any, but it should be unique. And the whole card number should be 16-digit length.</p>
</blockquote>
<blockquote>
<p>If the customer chooses ‘Create an account’, you should generate a new card number which satisfies all the conditions described above. Then you should generate a PIN code that belongs to the generated card number. A PIN code is a sequence of any 4 digits. PIN should be generated in a range from 0000 to 9999.</p>
</blockquote>
<blockquote>
<p>If the customer chooses ‘Log into account’, you should ask them to enter their card information. Your program should store all generated data until it is terminated so that a user is able to log into any of the created accounts by a card number and its pin. You can use an array to store the information.</p>
</blockquote>
<blockquote>
<p>After all information is entered correctly, you should allow the user to check the account balance; right after creating the account, the balance should be 0. It should also be possible to log out of the account and exit the program.</p>
</blockquote>
<p><strong>Specific Questions:</strong></p>
<ul>
<li><p>I'd like to know how to have the code chunk below print <em>just</em> <code>Bye!</code> and not <code>Bye!</code> and then <code>None</code> below it:</p>
<pre><code> elif account_balance_selection == "0":
print("\n")
print("Bye!")
> Bye!
> None
should be:
> Bye!
</code></pre>
</li>
<li><p>I am using the following code to generate and store the <code>credit card number</code> and <code>pin number</code>.</p>
<pre><code> def create_account(self):
credit_card_number = "400000" + format(randint(0000000000, 9999999999), '010d')
pin_number = format(randint(0000, 9999), '04d')
self.card_numbers.append(credit_card_number)
self.pin_numbers.append(pin_number)
</code></pre>
</li>
</ul>
<p>Is there a way to ensure that the numbers that are getting added to <code>card_numbers</code> and <code>pin_numbers</code> are unique? Either during the generation stage, or somehow prior to appending them to the their respective arrays?</p>
<p><strong>Code:</strong></p>
<pre><code> from random import randint
class BankingSystem:
def __init__(self):
self.card_numbers = []
self.pin_numbers = []
self.iin = 400000
def main_welcom_screen(self):
print(
"1. Create an account\n"
"2. Log into account\n"
"0. Exit"
)
main_menu_selection = str(input())
if main_menu_selection == "1":
self.create_account()
if main_menu_selection == "2":
self.account_login()
if main_menu_selection == "0":
print("\n")
return "Bye!"
def create_account(self):
credit_card_number = "400000" + format(randint(0000000000, 9999999999), '010d')
pin_number = format(randint(0000, 9999), '04d')
self.card_numbers.append(credit_card_number)
self.pin_numbers.append(pin_number)
print("\n")
print("Your card has been created")
print("Your card number:")
print(credit_card_number)
print("Your pin number:")
print(pin_number)
print("\n")
self.main_welcom_screen()
def account_login(self):
print("\n")
print("Enter your card number:")
entered_card_number = int(input())
print("Enter your PIN:")
entered_pin_number = int(input())
if str(entered_card_number) in self.card_numbers and str(entered_pin_number) in
self.pin_numbers:
print("\n")
print("You have successfully logged in!")
self.account_balance()
else:
print("\n")
print("Wrong card number of PIN!")
print("\n")
self.main_welcom_screen()
def account_balance(self):
print(
"\n1. Balance\n"
"2. Log out\n"
"0. Exit"
)
account_balance_selection = str(input())
if account_balance_selection == "1":
print("\n")
print("Balance: 0")
self.account_balance()
elif account_balance_selection == "2":
print("\n")
print("You have successfully logged out!")
print("\n")
self.main_welcom_screen()
elif account_balance_selection == "0":
print("\n")
print("Bye!")
print(BankingSystem().main_welcom_screen())
</code></pre>
|
[] |
[
{
"body": "<p>As is somewhat common for beginner OOP code, it's not particularly OOP; it's an awkward wrapper around a collection of methods that are still procedural. Consider attempting the following:</p>\n<ul>\n<li>Make an <code>Account</code> class</li>\n<li>Store the accounts as a dictionary of <code>Account</code> objects by card number, not separated arrays of cards and PINs</li>\n<li>Saying "PIN number" is redundant ("personal identification number number")</li>\n<li><code>iin</code> is never used; delete it</li>\n<li>Make a convenience function to show a text menu and call an associated function reference</li>\n<li><code>str(input())</code> is redundant; <code>input</code> already returns a string</li>\n<li>Call <code>input</code> with a prompt string, not a blank</li>\n<li>It's <code>welcome</code>, not <code>welcom</code></li>\n<li>Use f-strings for your digit formatting code</li>\n<li>Do not use <code>randint</code>; use <code>randrange</code> since it's more natural to express an exclusive maximum here</li>\n<li>Do not use <code>randint</code> for the PIN; use the <code>secrets</code> module for cryptographic strength</li>\n<li>You were printing <code>None</code> because of your <code>print(BankingSystem().main_welcom_screen())</code>, which is meaningless because that function does not return anything</li>\n<li>You have a critical bug where <em>any combination</em> of existing PIN and card number will allow login; but this should be a match to a specific card-PIN pair</li>\n<li>You have another bug where the calls out of <code>main_welcom_screen</code> recurse back to <code>main_welcom_screen</code>, so eventually you will blow your stack. Don't recurse here.</li>\n<li>Consider adding validation for your menu choices</li>\n<li>Consider adding an anti-bruteforce hang after invalid PIN input</li>\n<li>Do NOT acquire a user's PIN via regular <code>input</code>, which exposes the PIN to over-the-shoulder; use <code>getpass</code> instead</li>\n</ul>\n<h2>Example implementation</h2>\n<pre><code>from dataclasses import dataclass\nfrom getpass import getpass\nfrom random import randrange\nfrom secrets import randbelow\nfrom time import sleep\nfrom typing import Dict, Tuple, Callable, ClassVar\n\n\nclass Menu:\n MENU: ClassVar[Tuple[\n Tuple[\n str, Callable[['Menu'], bool]\n ], ...\n ]]\n\n def screen(self):\n prompt = '\\n'.join(\n f'{i}. {name}'\n for i, (name, fun) in enumerate(self.MENU)\n ) + '\\n'\n\n while True:\n choice = input(prompt)\n\n try:\n name, fun = self.MENU[int(choice)]\n except ValueError:\n print('Invalid integer entered')\n except IndexError:\n print('Choice out of range')\n else:\n if fun(self):\n break\n\n\n@dataclass\nclass Account(Menu):\n card: str\n pin: str\n\n @classmethod\n def generate(cls) -> 'Account':\n return cls(\n card=f'400000{randrange(1e10):010}',\n pin=f'{randbelow(10_000):04}',\n )\n\n def dump(self):\n print(\n f"Your card number: {self.card}\\n"\n f"Your PIN: {self.pin}"\n )\n\n def balance(self):\n print('Balance: 0')\n\n def logout(self) -> bool:\n print('You have successfully logged out!')\n return True\n\n def exit(self):\n print('Bye!')\n exit()\n\n MENU = (\n ('Exit', exit),\n ('Balance', balance),\n ('Log out', logout),\n )\n\n\nclass BankingSystem(Menu):\n def __init__(self):\n self.accounts: Dict[str, Account] = {}\n\n def create_account(self):\n account = Account.generate()\n print('Your card has been created')\n account.dump()\n self.accounts[account.card] = account\n\n def log_in(self):\n for _ in range(3):\n card = input('Enter your card number: ')\n pin = getpass('Enter your PIN: ')\n\n account = self.accounts.get(card)\n if account is None or account.pin != pin:\n print('Wrong card or PIN')\n sleep(2)\n else:\n print('You have successfully logged in!')\n account.screen()\n break\n\n def exit(self) -> bool:\n print('Bye!')\n return True\n\n MENU = (\n ('Exit', exit),\n ('Create an account', create_account),\n ('Log into an account', log_in),\n )\n\n\nBankingSystem().screen()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T23:50:13.203",
"Id": "505205",
"Score": "0",
"body": "Thank for this. I am looking forward to reviewing this in more detail. A lot to learn!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T13:44:19.517",
"Id": "505236",
"Score": "1",
"body": "But I always use my PIN number in the ATM machine...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T20:35:15.250",
"Id": "505281",
"Score": "0",
"body": "Your `Account` class is missing a `balance` and the card numbers are not unique. Your interactive menu system is great, but it distracts from the actual exercise: write an `Account` class. Mixing data with the menu system is also not a good idea (\"dataclass Account extends Menu\"?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T20:49:27.967",
"Id": "505282",
"Score": "0",
"body": "@danzel The missing balance is deliberate: it's the exact same as what the OP posted. The same goes for uniqueness: I've deliberately left out the machinery that would be required to generate unique card numbers. As for mixing data with the menu, I agree; but - baby steps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T21:06:14.493",
"Id": "505283",
"Score": "0",
"body": "@Reinderien generating the card number inside the `Account` class is a design flaw since neither the `Account` class nor its instances should know of any other card number. It's up to the BankingSystem to choose a (new and unique) card number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T23:18:49.550",
"Id": "505292",
"Score": "0",
"body": "@danzel You're welcome to write your own answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T17:35:13.007",
"Id": "505601",
"Score": "0",
"body": "`Account` class methods, should return their values only, not `print` the values. \"Business\" classes should be user interface ( console, GUI, web resource, etc.) neutral."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T22:18:50.017",
"Id": "255966",
"ParentId": "255951",
"Score": "8"
}
},
{
"body": "<blockquote>\n<p>Is there a way to ensure that the numbers that are getting added to\ncard_numbers and pin_numbers are unique? Either during the generation\nstage, or somehow prior to appending them to the their respective\narrays?</p>\n</blockquote>\n<p>AFAIK the card number does not have to be random, just unique. So I would generate the numbers in a <strong>sequential</strong> manner, and store them to a database with a unique constraint.</p>\n<p>In SQL you could perform a SELECT MAX statement to retrieve the largest card number and increment the range, but watch out for race conditions (use database locks).</p>\n<p>For this, you need some persistence. For a self-contained system (vs distributed systems used in the real world) using a small SQLite database would be a good option.</p>\n<p>Generating a random card number like what you're doing offers no guarantee that it will be unique, especially since you don't check the number against the list of previously generated numbers. A collision is extremely unlikely, since the range is very large but the code is nonetheless flawed in this aspect.</p>\n<p>Say that we stick to your approach but store the card number as integer rather than string. Then you can retrieve the maximum number with the max function:</p>\n<pre><code>max(self.card_numbers)\n</code></pre>\n<p>and increment it by 1 or 10 or whatever.</p>\n<p>Could be something like:</p>\n<pre><code>def generate_card_number():\n # list is empty, first number shall be 4000000000000000\n if len(self.card_numbers) == 0:\n credit_card_number = 4000000000000000\n else:\n # increment\n credit_card_number = max(self.card_numbers) +1\n \n self.card_numbers.append(credit_card_number)\n # or return a value\n return credit_card_number\n</code></pre>\n<p>As for the PIN number what you are doing seems reasonable. It has to be random but not unique, since it's perfectly conceivable more than one customer will share the same PIN, which is definitely unavoidable after a few thousand customers.</p>\n<p>Note that in the real world the last digit in a credit card number is a check-digit generated according to the Luhn algorithm. So the generation rules are a bit more complicated actually.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T21:34:44.970",
"Id": "505343",
"Score": "0",
"body": "Thank you very much for this perspective and insight. The next step in the project is to implement the Luhn algorithm!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T23:10:43.767",
"Id": "255968",
"ParentId": "255951",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "255966",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T18:15:12.817",
"Id": "255951",
"Score": "6",
"Tags": [
"python",
"beginner",
"object-oriented"
],
"Title": "Simple Banking System with Python"
}
|
255951
|
<p>I scraped data from a local .html page and the below code is working. I am a newbie to scraping, just tried with a simple HTML page. It takes 10 sec to complete execution and print data. If I did anything wrong or need improvements, please let me know.</p>
<pre><code>from bs4 import BeautifulSoup
import json
import pyodbc
import datetime
class JsonClass:
def __init__(self, Date, DocumentType, Procedure, NoOfPages):
self.Date = Date
self.DocumentType = DocumentType
self.Procedure = Procedure
self.NoOfPages = NoOfPages
def json_to_db(json_string):
conn = pyodbc.connect('Driver={SQL Server};' 'Server=xyz-PAVILION;' 'Database=jsondata;' 'Trusted_Connect=yes')
conn.autocommit = True
cursor = conn.cursor()
try:
cursor.execute('EXEC prcJsonInsertData @json = ?',
json_string) # Passing Json Data to DB via Stored Procedure(SP)
print('Data inserted')
except pyodbc.Error as error:
print('Error : %s' % error)
return False
except:
print('Operation Failed')
return False
conn.close()
return True
def json_serialize(dict_list):
with open('html_to_json.json', 'w') as file_out:
json.dump(dict_list, file_out, indent=4) # Serializing dict_list and writing in .json file
return json.dumps(dict_list)
def json_deserilaize(json_string):
with open('html_to_json.json', 'r') as file_out:
json_data = json.load(file_out) # Deserialization Data
json_class = [JsonClass(**i) for i in json_data] # Binding Json_data to Json_Class
print('********* After Deserialization *******************')
print('-------------------------------------')
for i in json_class:
print('Date : ' + i.Date)
print('DocumentType : ' + i.DocumentType)
print('Procedure : ' + i.Procedure)
print('NoOfPages : ' + i.NoOfPages)
print('-------------------------------------')
def html_data():
my_file = open("C:/Users/xyz/Downloads/sample.htm", 'r')
soup = BeautifulSoup(my_file, 'html.parser', from_encoding="UTF-8")
t_body = soup.find('tbody')
rows = t_body.find_all('tr')
dict_list = []
for row in rows:
column = row.find_all('td')
column = [x.text for x in column]
record = dict()
date_obj = datetime.datetime.strptime(column[1], '%d.%m.%Y')
record['Date'] = date_obj.date().isoformat()
record['DocumentType'] = column[2]
record['Procedure'] = column[3].replace('\u00a0/\u00a0', '/').replace('\u00a0', '/')
record['NoOfPages'] = column[4]
dict_list.append(record)
json_string = json_serialize(dict_list) # Func - 1
if json_to_db(json_string): # Func - 2
json_deserilaize(json_string) # Func - 3
if __name__ == '__main__':
html_data()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T19:20:54.340",
"Id": "505277",
"Score": "1",
"body": "Please do not update the code in your question after receiving 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": "<h2>PEP8 names</h2>\n<p>All of these variables:</p>\n<pre><code>def __init__(self, Date, DocumentType, Procedure, NoOfPages):\n self.Date = Date\n self.DocumentType = DocumentType\n self.Procedure = Procedure\n self.NoOfPages = NoOfPages\n</code></pre>\n<p>should be lower_snake_case.</p>\n<h2>Data classes</h2>\n<p>Replace <code>JsonClass</code> with a <code>@dataclass</code> that uses an implicit <code>__init__</code>.</p>\n<h2>Connection</h2>\n<p>First note that there's no point in separating out your connection parameters like</p>\n<pre><code>'Driver={SQL Server};' 'Server=xyz-PAVILION;'\n</code></pre>\n<p>since they will be implicitly concatenated to</p>\n<pre><code>'Driver={SQL Server};Server=xyz-PAVILION;'\n</code></pre>\n<p>Beyond that, the <a href=\"https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#connect\" rel=\"nofollow noreferrer\">documentation</a> states that kwargs are converted to a formatted conn string, so you're better off writing</p>\n<pre><code>pyodbc.connect(\n Driver='{SQL Server}',\n Server='xyz-PAVILION',\n Database='jsondata',\n Trusted_Connect='yes',\n)\n</code></pre>\n<h2>Context management</h2>\n<p>Use a <code>with</code> on your connection and cursor objects; read</p>\n<p><a href=\"https://github.com/mkleehammer/pyodbc/wiki/Connection#context-manager\" rel=\"nofollow noreferrer\">https://github.com/mkleehammer/pyodbc/wiki/Connection#context-manager</a></p>\n<h2>Exception interference</h2>\n<p>Don't convert exceptions to booleans, as in</p>\n<pre><code>except pyodbc.Error as error:\n print('Error : %s' % error)\n return False\nexcept:\n print('Operation Failed')\n return False\nconn.close()\nreturn True\n</code></pre>\n<p>Deal with the exceptions, potentially wrapping them in your own exception types, and catching them at an upper level.</p>\n<h2>Double serialization</h2>\n<p>Don't do this:</p>\n<pre><code>with open('html_to_json.json', 'w') as file_out:\n json.dump(dict_list, file_out, indent=4) # Serializing dict_list and writing in .json file\nreturn json.dumps(dict_list)\n</code></pre>\n<p>Hold onto the result of <code>dumps</code> and write that string to the file.</p>\n<h2>Print helpers</h2>\n<p>Move this code:</p>\n<pre><code> print('Date : ' + i.Date)\n print('DocumentType : ' + i.DocumentType)\n print('Procedure : ' + i.Procedure)\n print('NoOfPages : ' + i.NoOfPages)\n</code></pre>\n<p>to a method of <code>JsonClass</code>.</p>\n<h2>Hard-coded paths</h2>\n<pre><code>my_file = open("C:/Users/xyz/Downloads/sample.htm", 'r')\n</code></pre>\n<p>should not be hard-coded. Set it as some kind of parameter - a command-line argument maybe.</p>\n<h2>Dict literals</h2>\n<pre><code> record = dict()\n date_obj = datetime.datetime.strptime(column[1], '%d.%m.%Y')\n record['Date'] = date_obj.date().isoformat()\n record['DocumentType'] = column[2]\n record['Procedure'] = column[3].replace('\\u00a0/\\u00a0', '/').replace('\\u00a0', '/')\n record['NoOfPages'] = column[4]\n</code></pre>\n<p>should not call <code>dict()</code>, should not individually index keys, and should instead use a dict <code>{}</code> literal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T18:36:28.970",
"Id": "505272",
"Score": "0",
"body": "Print Helpers is not working. I created a method def PrintData(i) in JsonClass and using a loop to pass i(parameter to PrintData() method) from the json_desrialisation method. for i in json_class: ....JsonClass.PrintData(i)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T18:38:26.373",
"Id": "505273",
"Score": "0",
"body": "It shouldn't be `def PrintData(i)`; it should be `def print_data(self)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T19:17:00.403",
"Id": "505275",
"Score": "0",
"body": "I done changes to the above code. Have a look but the helper method is not working(getting a \" TypeError: print_data() missing 1 required positional argument: 'i' \")"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T17:36:58.990",
"Id": "505334",
"Score": "0",
"body": "As Mast indicated, you should not be editing this question. If your new solution no longer works, consider posting on StackOverflow."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T00:11:48.803",
"Id": "255972",
"ParentId": "255954",
"Score": "2"
}
},
{
"body": "<p>Looks like you are trying to get rid of the Unicode <a href=\"https://en.wikipedia.org/wiki/Non-breaking_space\" rel=\"nofollow noreferrer\">non-breaking space</a>:</p>\n<pre><code>record['Procedure'] = column[3].replace('\\u00a0/\\u00a0', '/').replace('\\u00a0', '/')\n</code></pre>\n<p>Dealing with Unicode or character set conversions can be a headache, so I would suggest that you have a look at existing libraries to "normalize" the data. For example: <a href=\"https://docs.python.org/3.5/library/unicodedata.html#unicodedata.normalize\" rel=\"nofollow noreferrer\">unicodedata.normalize</a>\nTo convert those non-breaking spaces to regular spaces I would try this:</p>\n<pre><code>import unicodedata\n\nrecord['Procedure'] = unicodedata.normalize("NFKD", column[3])\n</code></pre>\n<p>The benefit would be to "downgrade" a number of pesky characters you may encounter and not just this particular one.</p>\n<p>Some background reading: <a href=\"https://en.wikipedia.org/wiki/Unicode_equivalence\" rel=\"nofollow noreferrer\">Unicode equivalence</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T21:07:07.673",
"Id": "256002",
"ParentId": "255954",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T19:37:53.993",
"Id": "255954",
"Score": "3",
"Tags": [
"python-3.x",
"json"
],
"Title": "Web Scraping, Serializing and Deserializing in Python"
}
|
255954
|
<p>I'm learning Python and I'm building a basic random numbr generator. The code below works as expected. I'm just wondering if it uses best practice / can be made better.</p>
<p>Some future considerations might be adding a way for users to pick a random that isn't limited to 0-50 or 0-100, and finding a way to scale the number of guesses dynamically based on their choice.</p>
<pre><code>import random
"""
Make a program in which the computer randomly chooses a number between 1 to 10,
1 to 100, or any range.
"""
def intro():
print(f"Welcome to our number guessing game.")
print(f"We'll ask you to pick a range of numbers from 0 up to 100."
f"Then you'll get some chances to guess the number. "
f"The number of guesses you get will scale based on the range you "
f"choose. From 0 - 50, you'll get 5 chances. From 0 - 100, you'll"
f"get 10 chances. Good luck!")
print("Choose a range: ")
print("1. 0 - 50")
print("2. 0 - 100\n")
num_guesses = {
"1": (5, 50),
"2": (10, 100)
}
num_range = input()
while True:
if num_range == "1" or num_range == "2":
return num_guesses[num_range]
else:
print(f"{num_range} is not a valid selection. "
f"Please select either 1 or 2.")
num_range = input()
def guess_number(num_guesses, num_range):
random_number = random.randint(0, num_range)
guess_count = 0
print(f"Random num is: {random_number}")
while guess_count < num_guesses:
guess = int(input(f"Pick a random number between 0 and "
f"{num_range}: \n"))
if guess == random_number:
print("CONGRATS, YOU WIN!")
break
else:
guess_count += 1
print(f"Incorrect, try again! You have "
f"{num_guesses - guess_count} guess(es) left.\n")
else:
print("Womp womp, you lose :(.")
if __name__ == "__main__":
num_guesses, num_range = intro()
guess_number(num_guesses, num_range)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T23:10:51.240",
"Id": "505197",
"Score": "0",
"body": "In `guess_number()`, `print(f\"Random num is: {random_number}\")` comes before the `while` loop. Doesn't that tell the user what the number is before they make any guesses? It should probably go at the end with `print(\"Womp womp, you lose :(.\")`."
}
] |
[
{
"body": "<p>First, an issue with behaviour: In <code>guess_number</code> you don't make sure the input from the user is a number at all. So you might end up calling <code>int("oops")</code>. This raises a <code>ValueError</code>, and since there's nothing to catch that, the program crashes. You'll want to do something about that. A simple solution could be</p>\n<pre><code>try:\n guess = int(input(...))\n if guess == random_number:\n ...\n else\n ...\nexcept ValueError:\n print("That doesn't look like a number to me, but that's OK, I'll count it anyway :)")\n guess_count += 1\n</code></pre>\n<p>Side note, guesses that aren't in the interval also add to the counter. That might be on purpose, but since the validity of the input wasn't checked at all I don't want to assume, so I'm pointing it out.</p>\n<p>There are also a couple minor issues with <code>intro</code></p>\n<p>First off, you're duplicating the <code>num_range = input()</code> line. If you get the input at the start of the loop (before the if) instead it'll be easier to change if for some reason you need to</p>\n<p>Second, in python the usual approach is that it's better to ask for forgiveness than permission. That if check would usually be written using a <code>try</code>/<code>except KeyError</code> block (a bit like above). But if you don't want to do that, a more robust approach than the current one could be to check <code>if num_range in num_guesses</code>, in case a new option is added, or the program changes from accepting <code>1</code> and <code>2</code> to accepting <code>"a"</code> and <code>"b"</code>.</p>\n<p>On a related third note, the messages don't actually know what options are available, so there's a risk they get out of sync with the rest of the program. You can get a list of valid options as <code>num_guesses.keys()</code>, or use a for loop to iterate over the keys in <code>num_guesses</code> directly</p>\n<p>Finally, I don't love the variable names. <code>num_guesses</code> sounds like it should be the number of guesses, but it isn't a number at all. Similarly, <code>num_range</code> doesn't have much to do with ranges of numbers either. <code>num_range</code> feels like it would be better described by a name like <code>selection</code> or <code>choice</code>, and <code>num_guesses</code> is a collection of available options, so maybe it could be called <code>options</code>?</p>\n<pre><code>options = {\n "1": (5, 50),\n "2": (10, 100)\n}\n\nprint("Welcome to ... on the range you choose.")\n\nfor option in options:\n print(f"From 0 - {options[option][1]}, you'll get {options[option][0]} chances.")\n\nwhile True:\n print("Choose a range:")\n for option in options:\n print(f"{option}. 0 - {options[option][1]}")\n\n selection = input()\n try:\n return options[selection]\n except KeyError:\n print(f"{selection} is not a valid selection.")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:43:36.467",
"Id": "255964",
"ParentId": "255955",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T19:38:41.630",
"Id": "255955",
"Score": "3",
"Tags": [
"python",
"beginner",
"number-guessing-game"
],
"Title": "Random number generator [Beginner]"
}
|
255955
|
<p>I have devised a recursive function to grab the "nearest" element. This is a bit different than <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/closest" rel="nofollow noreferrer"><code>Element.closest</code></a>, because instead of traversing just the immediate parent(s); it traverses up but checks left-right-up-down.</p>
<p>Is there a more efficient check for siblings that I am missing?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if (Element.prototype.nearest === undefined) {
const nearest = (el, selector) => {
if (el == null) return undefined;
const prev = el.previousElementSibling;
if (prev?.matches(selector)) return prev;
const next = el.nextElementSibling;
if (next?.matches(selector)) return prev;
const parent = el.parentElement;
if (parent?.matches(selector)) return parent;
const relative = parent.querySelector(selector);
if (relative) return relative;
return nearest(el.parentElement, selector);
};
Element.prototype.nearest = function(selector) {
return nearest(this, selector);
};
}
const handleClick = (e) => {
const btn = e.target;
console.log(btn.nearest('.child'));
console.log(btn.nearest('.grand-parent'));
console.log(btn.nearest('#child-1'));
}
document.querySelectorAll('.btn').forEach(btn =>
btn.addEventListener('click', handleClick));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
display: flex;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grand-parent">
<div class="parent">
<div class="child" id="child-1">
<button class="btn">
Click
</button>
</div>
<div class="child" id="child-2">
<button class="btn">
Click
</button>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T17:30:56.937",
"Id": "505258",
"Score": "0",
"body": "1) The first check should be on `el` itself, probably, because it's actually nearest and to match the behavior of `closest`. 2) It should return `null` like all DOM methods do. 3) typo: the 2nd `return prev` should have `next`"
}
] |
[
{
"body": "<h2>Question</h2>\n<blockquote>\n<p><em>"Is there a more efficient check for siblings that I am missing?"</em></p>\n</blockquote>\n<p>As done in the example code you gave. No.</p>\n<p>You can rewrite the code to remove some of the unneeded complexity. See rewrites at bottom of answer.</p>\n<h2>Bug</h2>\n<p>The line...</p>\n<pre><code> const relative = parent.querySelector(selector);\n</code></pre>\n<p>...will throw if <code>parent</code> is <code>null</code></p>\n<h2>Unsafe prototype extension</h2>\n<p>It is a bad idea to add to an existing prototype without precautions. <code>Element.prototype.nearest</code> may not be used at the moment, but at any time it could be added to the DOM, breaking any code that you use it in.</p>\n<p>There are three ways to avoid conflicts/future proof prototype extensions.</p>\n<p>.1 100% safe. Don't!!! extending the prototype is an open trap ready to bite at any moment.</p>\n<p>.2 Almost safe. Use a non standard naming convention eg <code>Element.prototype.select_nearest</code> The standard will not use this name, but this does not mean it is 100% safe as anyone else may use the name.</p>\n<p>.3 Safe but awkward. Use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Symbol\">Symbol</a> to define the prototype name. This will guarantee the uniqueness of the name. Unfortunately it does mean you will need to use <code>bracket[notation]</code> to access the property and share that property with code that needs access. For example</p>\n<pre><code>// define\nconst nearest = Symbol("nearest");\nElement.prototype[nearest] = function() { /* ... code ... */ } // prototype is global\n\n// call\nbtn[nearest](".child");\n</code></pre>\n<p>To give access to the symbol in global scope use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Symbol for\">Symbol.for</a></p>\n<pre><code>\n{ // scope block\n const nearest = Symbol.for("nearest"); // find or create\n Element.prototype[nearest] = function() { log("Nearest") } // prototype is global\n}\n\n// Access in unconnected scope\n{ \n Symbol.for("nearest")\n btn[nearest](".child");\n\n // or \n btn[Symbol.for("nearest")](".child");\n}\n</code></pre>\n<h2>Style</h2>\n<p>A note on style.</p>\n<p>Its a bad habit not to delimit code blocks with <code>{}</code> eg <code>if (prev?.matches(selector)) return prev;</code> is safer as <code>if (prev?.matches(selector)) { return prev; }</code></p>\n<h2>Unbound function?</h2>\n<p>Why add to the element prototype a function that calls an unbound arrow function. This just makes the code unduly complex.</p>\n<p>You could either call the function <code>nearest</code> directly eg <code>nearest(btn, '.child');</code> or keep it on the prototype and avoiding the secondary call and the need to pass <code>this</code> See rewrites.</p>\n<h2>Rewrite</h2>\n<p>Several rewrites as examples, though apart from the bugs and the points outlined above I don't see any real need for a rewrite.</p>\n<h3>As prototype</h3>\n<pre><code>const nearest = Symbol.for("nearest");\nElement.prototype[nearest] = function(selector) { \n const prev = this.previousElementSibling;\n if (prev?.matches(selector)) { return prev }\n const next = this.nextElementSibling;\n if (next?.matches(selector)) { return next }\n const parent = this.parentElement;\n if (parent) {\n if (parent.matches(selector)) { return parent }\n return parent.querySelector(selector) ?? parent[nearest](selector);\n }\n}\n\n</code></pre>\n<h3>As function</h3>\n<pre><code>\nfunction nearest(self, sel) { \n const prev = self.previousElementSibling;\n if (prev?.matches(sel)) { return prev }\n const next = self.nextElementSibling;\n if (next?.matches(sel)) { return next }\n const parent = self.parentElement;\n if (parent) {\n if (parent.matches(sel)) { return parent }\n return parent.querySelector(sel) ?? parent.nearest(parent, sel);\n }\n}\n\n</code></pre>\n<p>or</p>\n<pre><code>const matches = (el, sel) => el && el.matches(sel) ? el : undefined;\nfunction nearest(self, sel) { \n const parent = self.parentElement;\n const sibling = matches(self.previousElementSibling, sel) ?? \n matches(self.nextElementSibling, sel) ??\n matches(parent, sel) ?? \n parent?.querySelector(selector) ?? \n parent?.nearest(parent, selector);\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T00:49:00.727",
"Id": "256007",
"ParentId": "255957",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256007",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T19:56:52.763",
"Id": "255957",
"Score": "1",
"Tags": [
"javascript",
"performance"
],
"Title": "Optimize \"nearest\" Element query prototype"
}
|
255957
|
<p>I would like to receive constructive feedback on my simulation framework (this is for my thesis work). I have no formal background in programming, and I am wondering if there is a more effective and efficient way to structure my codes for better readability and scalabiilty so that people can easily understand, modify, and build on my codes while achieving high computational efficiency.</p>
<p>Here is a brief description of my simulation model. For each agent I create in my simulation world, they go through a number of event processes annually until they die, reach the maximum age (e.g., 111), or reach the max. time window (e.g., 2050 if an agent is created in 2015 and I set the time window to be 35). I am using a <strong>modular</strong> apporach, in which each module contains at least one process (so far I have not encoutered more than 1, but I think I would in the future): a process function for that module and input parameters for that process function.</p>
<p>To facilliate that framework, I have created an abstract type Simulation_Module under which event modules (birth and death) are contained.</p>
<p><strong>abstractModule.jl</strong>:</p>
<pre><code>abstract type Agent_Module end
abstract type Simulation_Module end
# sub modules
abstract type Birth_Module <: Simulation_Module end
abstract type Death_Module <: Simulation_Module end
</code></pre>
<p><strong>agent.jl</strong>: Here is an agent module</p>
<pre><code>mutable struct Agent{Z<:Bool,Y<:Int64} <: Agent_Module
sex::Z
age::Y
birth_year::Y
cal_year::Y
alive::Z
end
function set_agent!(ag, sex, age, birth_year,cal_year,alive)
ag.sex = sex;
ag.age= age;
ag.birth_year = birth_year;
ag.cal_year = cal_year;
ag.alive = alive;
nothing
end
agent = Agent(false,0,2015,2015,true)
</code></pre>
<p><strong>birth.jl</strong>: Birth module</p>
<pre><code>mutable struct Birth <: Birth_Module
parameters::Union{AbstractDict,Nothing}
process::Function
end
parameter_names = nothing
function birth_process(cal_year_index::Int64,parameters::Union{AbstractDict,Nothing}=nothing)::Bool
rand(Bernoulli(0.5))
end
birth = Birth(Dict_initializer(parameter_names),birth_process)
</code></pre>
<p><strong>death.jl</strong></p>
<pre><code>mutable struct Death <: Death_Module
parameters::Union{AbstractDict,Nothing}
process::Function
end
parameter_names = nothing
function death_process(ag::Agent,parameters::Union{AbstractDict,Nothing}=nothing)::Bool
rand(Bernoulli(0.5))
end
death = Death(Dict_initializer(parameter_names),death_process)
</code></pre>
<p><strong>Simulation.jl</strong>: It contains a struct for Simulation and a run function for running a simulation.</p>
<pre><code>using Setfield, Distributions, StatsFuns
using TimerOutputs
function Dict_initializer(parameter_names::Union{Nothing,Vector{Symbol}})
isnothing(parameter_names) ? nothing : Dict(parameter_names .=> missing)
end
# abstract types
include("abstractModule.jl")
# agent
include("agent.jl")
# event proceses
include("birth.jl")
include("death.jl")
mutable struct Simulation <: Simulation_Module
max_age::Int64
starting_calendar_year::Int64
time_horizon::Int64
n::Int64 # number of agents to create in each year
Agent::Agent_Module
Birth::Birth_Module
Death::Death_Module
OutcomeMatrix::AbstractDict # needs to be a dictionary
end
function run(simulation::Simulation_Module)
# Is it better to define the fields of the simulation object
# separately if I am going to use
# them in simulation multiple times?
max_age::Int64 = simulation.max_age
min_cal_year::Int64 = simulation.starting_calendar_year
max_cal_year::Int64 = min_cal_year + simulation.time_horizon - 1
simulation.n = (isnothing(simulation.n) ? 100 : simulation.n)
n::Int64 = simulation.n
max_time_horizon::Int64 = simulation.time_horizon
cal_years::Vector{Int64} = collect(min_cal_year:1:max_cal_year)
# store events
# total num of agents
n_list = zeros(Int64,simulation.time_horizon,2)
# store events by cal year, age, and sex for each event type
event_list::Vector{String} = ["death","alive"]
event_matrix = zeros(Int64,length(cal_years),max_age,2,length(event_list))
# time the performance
to = TimerOutput()
# initiate variables
tmp_n::Int64 = 0
tmp_cal_year_index::Int64 = 0
@timeit to "sleep" sleep(0.02)
for cal_year in cal_years
# for each calendar year
@timeit to "calendar year $cal_year" begin
tmp_cal_year_index = cal_year - min_cal_year + 1
for i in 1:n
# initialization: create a new agent
set_agent!(simulation.Agent,simulation.Birth.process(tmp_cal_year_index),0,tmp_cal_year_index,tmp_cal_year_index,true)
# update the total number of agents added to the simulation
n_list[tmp_cal_year_index,simulation.Agent.sex+1] +=1
# go through event processes for each agent until
# death or max age or max time horizon
while(simulation.Agent.alive && simulation.Agent.age <= max_age && simulation.Agent.cal_year <= max_time_horizon)
# I have other event processes
# death - the last process
if simulation.Death.process(simulation.Agent)
# dead
simulation.Agent.alive = false
event_matrix[simulation.Agent.cal_year,simulation.Agent.age+1,simulation.Agent.sex+1,1] += 1
else
# still alive!
event_matrix[simulation.Agent.cal_year,simulation.Agent.age+1,simulation.Agent.sex+1,2] += 1
simulation.Agent.age += 1
simulation.Agent.cal_year += 1
end
end # end while loop
end # end for loop: agents
end # end of begin timeit
end # end for loop: cal year
print_timer(to::TimerOutput)
# convert the event matrix into a dictionary
tmp_event_dict = Dict()
for jj in 1:length(event_list)
tmp_event_dict[event_list[jj]] = [event_matrix[:,:,1,jj],event_matrix[:,:,2,jj]]
end
# reshape event matrix into a dictionry of list of matrices
simulation.OutcomeMatrix = Dict("n" => n_list,
"outcome_matrix" => tmp_event_dict)
print("\n Simulation finished. Check your simulation object for results.")
return nothing
end
# test run
simulation = Simulation(111,2015,25,5000, agent, birth, death,Dict());
run(simulation)
</code></pre>
<p>You can directly download the files from:
<a href="https://www.dropbox.com/sh/nrip5dc2rus6oto/AADIlZsngwjuUOwir9O2AeMsa?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/sh/nrip5dc2rus6oto/AADIlZsngwjuUOwir9O2AeMsa?dl=0</a></p>
<p>I have just provided two modules, and my run function is very simple but you can imagine I would have many more processes and hence a complicated run function.</p>
<p>Besides any feedback you may have, I would like to know whether there is a better (in terms of readability, scalability, and efficiency) frameworks/tools I could use (e.g., software-wise, structure of "modules", julia types, built-in functions, etc).</p>
<p>If anything is unclear please let me know. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T08:58:24.837",
"Id": "505305",
"Score": "0",
"body": "I think it would be useful to understand what is your objective, i.e. what you want to discover with your simulation. If you state more in details yr subject you may receive more domain specific suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T02:33:33.200",
"Id": "505526",
"Score": "0",
"body": "Thanks for your comment. I was hoping to get feedback on my simulation framework, which is for a discrete event simulation for discrete time, and efficiency/effectivness."
}
] |
[
{
"body": "<p>That was a fun one. I only comment on the Julia parts, not the content, since the former was intense enough.</p>\n<h2>Deconstruction</h2>\n<pre><code>abstract type Simulation_Module end\n</code></pre>\n<p>In Julia, PascalCase, as in <code>SimulationModule</code>, is preferred for types. For variable/function names, opinions differ between <code>flatcase</code> and <code>snake_case</code>.</p>\n<hr />\n<pre><code>mutable struct Agent{Z<:Bool,Y<:Int64} <: Agent_Module\n sex::Z\n age::Y\n birth_year::Y\n cal_year::Y\n alive::Z\nend\n</code></pre>\n<p>Those type parameters make no sense at all. <code>Bool</code> and <code>Int64</code> are concrete types, so just use them directly: <code>sex::Bool</code> etc. I'd spell out <code>calendar_year</code> explicitely. Replace <code>Int64</code> by <code>Int</code> unless you have specific reasons for using a certain size (<code>Int</code> is a uses the platforms word size).</p>\n<p>Also, do think twice whether your types need to be mutable. Perhaps the algorithm works just as well with immutable types and the respective style.</p>\n<hr />\n<pre><code>function set_agent!(ag, sex, age, birth_year,cal_year,alive)\n ag.sex = sex;\n ag.age= age;\n ag.birth_year = birth_year;\n ag.cal_year = cal_year;\n ag.alive = alive;\n nothing\nend\n</code></pre>\n<p>That's a weird one, but I understand it follows from making <code>Agent</code> mutable. I suggest to replace usages of <code>set_agent!</code> by updates with a new agent: <code>simulation.agent = Agent(...)</code>.</p>\n<p>If you insist on this function: take care of proper spacing (<code>ag.age = age</code>), and return the updated instance from it (<code>return ag</code>). Throw away those colons <code>;</code>, too.</p>\n<p>BTW, you load <code>Setfield</code> below. This function would be the ideal place to refactor using it.</p>\n<hr />\n<pre><code>mutable struct Birth <: Birth_Module\n parameters::Union{AbstractDict,Nothing}\n process::Function\nend\n</code></pre>\n<p>Here we have the opposite case from <code>Agent</code>: <code>AbstractDict</code> and <code>Function</code> <em>are</em> abstract types, so you <em>do</em> want to make them parameters. Besides, abstracting the dict type might be an overkill; isn't there more specific information you have?</p>\n<p>Furthermore, is it really needed to distinguish between <code>nothing</code> and an empty dictionary? Also, my point about mutability from above.</p>\n<p>Suggestion:</p>\n<pre><code>mutable struct Birth{F, P} <: BirthModule\n parameters::Dict{Symbol, P}\n process::F\nend\n</code></pre>\n<hr />\n<pre><code>parameter_names = nothing\n</code></pre>\n<p>Uh. You know what you are doing there? You declare a <em>mutable global variable</em>, which is bad for type stability to begin with. And then you write to it multiple times from the top level, in every <code>include</code>!</p>\n<p>Make the variable local wherever you use it.</p>\n<hr />\n<pre><code>birth = Birth(Dict_initializer(parameter_names),birth_process)\n</code></pre>\n<p>Same here. Make it local.</p>\n<hr />\n<pre><code>function Dict_initializer(parameter_names::Union{Nothing,Vector{Symbol}})\n isnothing(parameter_names) ? nothing : Dict(parameter_names .=> missing)\nend\n</code></pre>\n<p>Style-wise, call it <code>init_parameters</code> or something.</p>\n<p>And I suggest to get rid of it completely. It's ugly and will lead to weird types. Probably you want to avoid checking for the parameters being present in the simulation functions; you could refactor that by using convenience functions such as <a href=\"https://docs.julialang.org/en/v1/base/collections/#Base.get!-Tuple%7BFunction,Any,Any%7D\" rel=\"nofollow noreferrer\"><code>get!</code></a> wherever the parameters are modified.</p>\n<p>Or even better, implement immutable parameter updates using <a href=\"https://docs.julialang.org/en/v1/base/base/#Core.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a> and <code>SetField</code>, with an appropriate initialization.</p>\n<hr />\n<pre><code> Agent::Agent_Module\n Birth::Birth_Module\n Death::Death_Module\n</code></pre>\n<p>Fields should be in lower case.</p>\n<p>In the case of <code>Simulation</code>, a mutable type seem reasonable to me. But perhaps a more elegant design is possible by separating simulation parameters (agent, time horizon, max age) that stays constant from a mutable "simulation state" type.</p>\n<hr />\n<pre><code>OutcomeMatrix::AbstractDict # needs to be a dictionary\n</code></pre>\n<p>And why is it called a matrix, then? Also, either make the dictionary type a parameter (<code>{D<:AbstractDict}</code>), or switch to a concrete type.</p>\n<hr />\n<pre><code>max_age::Int64 = simulation.max_age\n</code></pre>\n<p>The type assertion is not necessary. Also, you have <code>SetField</code> to do this for you!</p>\n<hr />\n<pre><code>simulation.n = (isnothing(simulation.n) ? 100 : simulation.n)\n</code></pre>\n<p><code>simulation.n</code> is an <code>Int64</code>, and thus cannot be <code>nothing</code>.</p>\n<p>Pass the initial <code>n</code> as a parameter to the <code>run</code> function, or put it into the simulation parameter type I proposed before, or at least make the number a global <code>const</code>.</p>\n<hr />\n<pre><code>max_time_horizon::Int64 = simulation.time_horizon\n</code></pre>\n<p>Use consistent naming here.</p>\n<hr />\n<pre><code>cal_years::Vector{Int64} = collect(min_cal_year:1:max_cal_year)\n</code></pre>\n<p><code>collect(min_cal_year:max_cal_year)</code> should suffice. But think about whether you need to allocate this vector in the first place. Aren't you only iterating over it? Then the range is enough. Or could you even just recalculate it in every step from the initial year and the current <code>n</code>?</p>\n<hr />\n<pre><code>n_list = zeros(Int64,simulation.time_horizon,2)\n</code></pre>\n<p>Not a good name. It's neither a list (but a <code>Vector</code>), nor has it an appearent connection to <code>n</code>.</p>\n<p>Also, it has fixed size. You could replace it by a tuple or two variables.</p>\n<p>Watch your spaces!</p>\n<hr />\n<pre><code>event_list::Vector{String} = ["death","alive"]\n</code></pre>\n<p>Symbols would be preferred: <code>[:death, :alive]</code>.</p>\n<hr />\n<pre><code> tmp_n::Int64 = 0\n tmp_cal_year_index::Int64 = 0\n</code></pre>\n<p>Better names for that, please! Or get rid of the variable all together.</p>\n<hr />\n<pre><code>event_matrix = zeros(Int64,length(cal_years),max_age,2,length(event_list))\n</code></pre>\n<p>Maybe this can get a better name, too... <code>events</code>? And it seems that you didn't completely decide whether to make the kinds of events fixed or parametrizable. If there are only ever going to be two kinds, use a <code>const N_EVENTS = 2</code>. Otherwise, parametrize the simulation by event types (and then change how you handle <code>event_list</code>).</p>\n<p>Also, that <code>2</code> needs to be a constant too, I have no idea what it the dimension stands for. Perhaps use a type like <a href=\"https://github.com/JuliaArrays/AxisArrays.jl\" rel=\"nofollow noreferrer\"><code>AxisArray</code></a> to make all dimensions more explicit.</p>\n<p>Spacing, again!</p>\n<hr />\n<pre><code>n_list[tmp_cal_year_index,simulation.Agent.sex+1] +=1\n</code></pre>\n<p>Ah, so this should have been called <code>agent_counts</code> or like that. Again, spacing!</p>\n<pre><code>n_list[tmp_cal_year_index, simulation.agent.sex + 1] += 1\n</code></pre>\n<p>And wait, what? The <code>sex</code> is a <code>Bool</code>. Why are you incrementing it? Make the semantics of using a <code>Bool</code> to select the column more explicit. Perhaps there is an array type that can do that. You could create your own even (or give up the social construction of there being a limited number of two distinct sexes :))</p>\n<hr />\n<pre><code>if simulation.Death.process(simulation.Agent)\n</code></pre>\n<p>This looks like an updating operation. In that case, the name of the field of the death module should be <code>process!</code>.</p>\n<p>This also shows that you should add more docstrings. Document the interface that <code>process!</code> needs to fulfill somewhere, too!</p>\n<hr />\n<pre><code># convert the event matrix into a dictionary\n tmp_event_dict = Dict()\n for jj in 1:length(event_list)\n tmp_event_dict[event_list[jj]] = [event_matrix[:,:,1,jj],event_matrix[:,:,2,jj]]\n end\n\n # reshape event matrix into a dictionry of list of matrices\n simulation.OutcomeMatrix = Dict("n" => n_list,\n "outcome_matrix" => tmp_event_dict)\n</code></pre>\n<p>This looks a bit gross. Suggestion: have a separate type for simulation results. Then drop <code>OutcomeMatrix</code> and instead of writing the simulation result to the simulation object, return a simulation result object.</p>\n<p>Apart from that:</p>\n<ul>\n<li><p><code>tmp_</code> is a really bad prefix. Try to construct the thing directly:</p>\n<pre><code>outcome_matrix = [(event_matrix[:,:,1,jj], event_matrix[:,:,2,jj]) for jj in eachindex(event_list)]\n</code></pre>\n<p>This also uses tuples instead of constant-length arrays, and avoids an untyped <code>Dict()</code>.</p>\n<p>Additionally, you copy over the whole event matrix into slices. That's bad for memory. You could use <a href=\"https://docs.julialang.org/en/v1/base/arrays/#Views-(SubArrays-and-other-view-types)\" rel=\"nofollow noreferrer\">views</a>, or make the logic part of the suggested result type -- pack the event matrix into it, and add some nice custom accessors instead of the dictionary conversion.</p>\n</li>\n<li><p>Once more, <code>OutcomeMatrix</code> is obviously not a matrix. If you do something like this at all, use <code>Symbols</code> in the dict. Even better, use a <code>NamedTuple</code> instead: <code>(;n = n_list, outcome_matrix = outcome_matrix)</code>, or in newer Julias <code>(;n = n_list, outcome_matrix)</code> with the naming inferred automatically.</p>\n</li>\n</ul>\n<hr />\n<pre><code>simulation = Simulation(111,2015,25,5000, agent, birth, death,Dict());\n</code></pre>\n<p>Again, this looks like Fortran with more indirection: you pass in a mutable object to use as the output. Make the simulation result the return value of <code>run</code>.</p>\n<p>Remove the colon.</p>\n<h2>More general design suggestions</h2>\n<ol>\n<li>Think about whether you need so much abstraction. E.g., the abstract base types for everything.</li>\n<li>Perhaps try to rewrite <code>run</code> as a combination of an <code>init!</code> and a <code>step!</code> function on a mutable <code>SimulationState</code> object. Then, derive an iterator from it so that you can do <code>for step in run(simulation) ...</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T17:48:27.300",
"Id": "505985",
"Score": "0",
"body": "Yeah, I was bored."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T04:37:49.323",
"Id": "506015",
"Score": "0",
"body": "Thanks a lot. I will go over these carefully and may bother you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T17:47:59.550",
"Id": "256307",
"ParentId": "255958",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T03:58:17.763",
"Id": "255958",
"Score": "3",
"Tags": [
"julia",
"simulation"
],
"Title": "Discrete event simulation framework for discrete times in Julia"
}
|
255958
|
<p>I needed a way to pause multiple threads from a single parent thread, this was my solution for the general case. I would like advice on code quality and enhancements. I'm particularly interested if there are any weird edge case usages where this fails in terms of synchronization, and what I should do to prevent them.</p>
<pre><code>//threadpause.h
#ifndef UTIL_THREADPAUSE_H
#define UTIL_THREADPAUSE_H
#include <condition_variable>
#include <mutex>
namespace util {
class ThreadPause{
public:
explicit ThreadPause(bool paused = false);
[[nodiscard]]
bool is_paused() const;
void wait();
void pause();
void resume();
private:
bool m_paused;
std::mutex m_mutex;
std::condition_variable m_cv;
};
}
#endif //UTIL_THREADPAUSE_H
</code></pre>
<p>|</p>
<pre><code>//threadpause.cpp
#include "threadpause.h"
util::ThreadPause::ThreadPause(bool paused) : m_paused(paused){
}
bool util::ThreadPause::is_paused() const {
return m_paused;
}
void util::ThreadPause::wait() {
while(is_paused()){
std::unique_lock<std::mutex> lock(m_mutex);
//need the condition in here in case of spurious wake up,
//wont exit condition unless condition true
m_cv.wait(lock, [&paused = m_paused]{return !paused;});
}
}
void util::ThreadPause::pause() {
//lock around the variable so with can modify it
std::unique_lock<std::mutex> lock(m_mutex);
m_paused = true;
}
void util::ThreadPause::resume() {
//lock around the variable so with can modify it
std::unique_lock<std::mutex> lock(m_mutex);
m_paused = false;
//unlock to stop threads from immediately locking when notify is called.
lock.unlock();
m_cv.notify_all();
}
</code></pre>
<p>|</p>
<pre><code>//example useage main.cpp
#include "threadpause.h"
#include <thread>
#include <atomic>
#include <chrono>
#include <vector>
#include <iostream>
int main(){
using namespace std::chrono_literals;
std::size_t thread_count = 10;
std::atomic<bool> exit_threads(false);
util::ThreadPause thread_pause;
std::vector<int> increments(thread_count, 0);
auto thread_function = [](
std::atomic<bool>& exit_threads,
util::ThreadPause& thread_pause,
int& increment){
while(!(exit_threads.load())){
thread_pause.wait();
//... your work would normally go here
increment += 10;
}
};
std::vector<std::thread> threads;
for(std::size_t i = 0; i < thread_count; ++i){
threads.emplace_back(thread_function,
std::ref(exit_threads),
std::ref(thread_pause),
std::ref(increments[i]));
}
std::this_thread::sleep_for(100ms);
thread_pause.pause();
std::this_thread::sleep_for(100ms);
std::cout << "Current values for increments: \n";
for(auto increment : increments){
std::cout << increment << "\n";
}
std::this_thread::sleep_for(100ms);
std::cout << "Pause values for increments: \n";
for(auto increment : increments){
std::cout << increment << "\n";
}
thread_pause.resume();
std::this_thread::sleep_for(100ms);
thread_pause.pause();
std::this_thread::sleep_for(100ms);
std::cout << "Resume values for increments: \n";
for(auto increment : increments){
std::cout << increment << "\n";
}
thread_pause.resume();
exit_threads.store(true);
for(auto& thread : threads){
thread.join();
}
std::cout << "Threads Joined!\n";
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:46:47.103",
"Id": "505172",
"Score": "2",
"body": "\"I needed a way to pause multiple threads from a single parent thread\" Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:52:03.647",
"Id": "505174",
"Score": "0",
"body": "@Mast I had multiple threads that were doing serious work and had lots of setup, and in a UI I had states where these threads would not need to do this work, and them doing this work would bog down what I wanted to do at that time, but I did not want to do the song and dance of re initializing those threads when I needed them again on another UI state switch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:53:29.777",
"Id": "505176",
"Score": "0",
"body": "Could you post your actual code instead of this simplified example? Stack Overflow likes simplifications, Code Review likes details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:55:02.007",
"Id": "505178",
"Score": "0",
"body": "@Mast No, sorry. This code will run if that's what you're worried about. I'll elaborate about my use case in the post, but that's the best I can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:58:50.710",
"Id": "505179",
"Score": "1",
"body": "Could you at least make more alike to your original code? Hypothetical code simply doesn't do well here. It's harder on the reviewers and the answers aren't as useful to you and future readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:05:31.060",
"Id": "505180",
"Score": "0",
"body": "@Mast I'm unsure of what the issue is with the example use case, it's essentially what you describe. There are indeed other questions in different languages here about thread pausers, and it's a common enough question on stackoverflow. I'm not even sure what my specific use case brings to the table now that I think of it. I don't mean to be rude, but I don't know what makes this different from someone making an array class, and posting it on here, or some sort of algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:06:10.080",
"Id": "505181",
"Score": "0",
"body": "@Mast infact, I have done more than these similar examples: https://codereview.stackexchange.com/questions/14502/thread-pausing-resuming-implementation https://codereview.stackexchange.com/questions/26724/thread-pausing-resuming-canceling-with-qt https://codereview.stackexchange.com/questions/161634/pause-resume-producer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:06:58.963",
"Id": "505182",
"Score": "0",
"body": "Those are all challenges, specific problems meant to solve a particular problem to get better at solving problems. In your case though, you have actual code that may or may not run into edge cases of which we simply can't be sure if you don't show the actual code. Different situations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:08:19.777",
"Id": "505183",
"Score": "0",
"body": "Never use an existing post as an example. 2 of the links you have are old and the rules have changed over time. The third isn't a great question either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:10:12.413",
"Id": "505184",
"Score": "1",
"body": "If you're fine with posting the bare minimum, that's fine with me. I'm just trying to get you the best experience possible on this site. 10% of the questions on this site never get answered."
}
] |
[
{
"body": "<h1>Design review</h1>\n<p>I don’t see any major problems with the code, but it is <em>probably</em> over-complicated for what you really want it to do. But of course, there’s no way to be sure, because you’re not actually telling what you actually want it to do. So this review is going to contain a lot of: “ Depends on what you’re actually doing.”</p>\n<p>As is the norm with concurrent code these days, there’s the expected <code>std::condition_variable</code>—for reasons beyond me, <code>std::condition_variable</code> has become the <code>std::endl</code> of concurrent code. <em>Everybody</em> uses it; nobody really seems to understand why; and 95% of the time, a simple <code>std::atomic_flag</code> would do just as well (which also seems true in this case, but only with the C++20 <code>std::atomic_flag</code>). But is <em>this</em> actually a case where you <em>need</em> <code>std::condition_variable</code>? Depends on what you’re actually doing.</p>\n<p>The one thing I try to impress on everybody with regards to concurrent programming is that concurrent programming is still in its infancy. Established programming paradigms have patterns that apply virtually universally; for example, the guideline against using <code>goto</code> in structured programming is pretty much a rule you can apply without thought all the time everywhere. But concurrent programming is still very much the wild west: there are very, very few “one size fits all” solutions.</p>\n<p>What that means in this case is that there is no one right way to “pause” a thread. It really depends on how long you want to pause for. If you just want to pause for a few nanoseconds, then you can get away with a spin-lock (or something similar that doesn’t actually require literally spinning, <a href=\"https://software.intel.com/content/www/us/en/develop/articles/benefitting-power-and-performance-sleep-loops.html\" rel=\"nofollow noreferrer\">like using <code>__mm_pause</code> on x86 architectures</a>). Much more than that, then maybe you want to yield the thread’s time slice. Much more than that, maybe you want to tell the thread scheduler to stop scheduling the thread until notified.</p>\n<p>Basically, it is impossible to have a “one size fits all” solution for “pausing” because you have to balance:</p>\n<ul>\n<li>how long you want to pause</li>\n<li>how quickly you want to resume when unpaused; and</li>\n<li>how many resources you want to use.</li>\n</ul>\n<p>This is an engineering trilemma (similar to “you can have it quickly, you can have it cheaply, you can have it done well; choose any two”). There is no “correct” solution.</p>\n<p>Given that you’re not telling what you actually want to do, I have to guess that you don’t intend to pause for long periods of time. The reason why I assume that is because if you are pausing for really long periods, it doesn’t really make sense to keep the threads live and sleeping… it makes much more sense to release those resources, and reacquire them if you need them again—that’s just being a much better citizen on limited-resource devices. On the other hand, if you’re not targeting limited-resource devices, then holding on to those threads and sleeping them for long periods <em>would</em> make sense. So, once again: Depends on what you’re actually doing.</p>\n<p>There’s also another dimension worth mentioning here. When you say something like, “I want to pause a bunch of threads,” you’re not <em>actually</em> saying what you <em>really</em> want to do. You’re missing the forest for the trees. You’re (almost certainly) not writing a program whose purpose is to create and manage a bunch of threads; you’re writing a program that does something actually useful, and managing those threads is just an implementation issue. For that reason, thread management shouldn’t be the focus… if anything, it should be pretty much invisible. And most modern concurrent tools are designed around that thinking.</p>\n<p>Put another way: if you are thinking, “I want to pause a bunch of a threads,” then you’re thinking wrong. You <em>should</em> be thinking, “I want to do a bunch of tasks, but sometimes it will be necessary to wait for the next set of tasks to be ready”. Worded that way, the entire notion of a thread pausing utility is specious. You probably want something more like a concurrent queue, which will make handling a bunch of tasks <em>much</em> more natural, and will <em>automatically</em> and invisibly handle all the pausing necessary, <em>AND</em> even automatically handle scaling.</p>\n<p>But, as always: Depends on what you’re actually doing.</p>\n<p><em>HOWEVER</em>, there’s a <em>reason</em> that other way of thinking is so prevalent. If you just focus on the pausing, you’re failing to see the bigger picture and introducing all kinds of unnecessary headaches. What happens if the “pause” is never “unpaused”? In that case, your app locks up. How does pausing interact with stopping/ending the thread? These issues are problems with a design based on “pausing threads”… but they would evaporate entirely if your focus was on the actual task(s) at hand:</p>\n<ul>\n<li>What happens if no new tasks ever become ready? Meh, same thing that happens when all tasks are done. Not a problem.</li>\n<li>How does no tasks being ready interact with ending the overall job? Quite naturally; the job obviously ends when there are no more tasks to do. So, not a problem.</li>\n</ul>\n<p>So here’s a summary of the design overview:</p>\n<ul>\n<li>Your current design may be absurdly overwrought for what you need… or it may be perfect. Depends on what you’re actually doing.</li>\n<li>The entire concept may be pointless and misguided; rather than a “thread pauser”, you may actually need something completely different, like a concurrent queue… or it may be exactly what you need. Depends on what you’re actually doing.</li>\n<li>The concept may be fundamentally flawed, because it doesn’t actually model what you really need, and for that reason doesn’t interact well with the rest of the design.</li>\n</ul>\n<p>So this review might end up being completely useless to you. <a href=\"https://codereview.stackexchange.com/q/255959/170106#comment505179_255959\">But you can’t say you weren’t warned.</a></p>\n<h1>Code review</h1>\n<pre><code>explicit ThreadPause(bool paused = false);\n</code></pre>\n<p>I am generally not a fan of defaulted paramaters—they cause far more trouble than they’re generally worth, especially in a case like this.</p>\n<p>On top of that, using a <code>bool</code> in this context is kinda muddying the waters. When I see <code>auto thread_pause = util::ThreadPause{true};</code>, it’s not actually clear that that means that any thread that uses <code>thread_pause</code> will start out paused… or rather, will not “start” at all. Which is pretty dangerous, because it could lock up the whole app, depending. There doesn’t seem like a good reason to have this kind of interface when the following is more clear:</p>\n<pre><code>auto thread_pause = util::ThreadPause{};\nthread_pause.pause();\n\n// now do whatever.\n</code></pre>\n<p>The only counter argument is that setting the <code>bool</code> in the constructor is <em>much</em> more efficient than calling <code>pause()</code>. That’s true, but it’s more a criticism of <code>pause()</code> than of the pattern… <code>pause()</code> <em>shouldn’t</em> be so inefficient. But we’ll get to that.</p>\n<pre><code>[[nodiscard]]\nbool is_paused() const;\n</code></pre>\n<p>Given the purpose of this class, this function seems completely pointless. It will never be a good idea to use it, because by the time you get the result, it may no longer be true.</p>\n<pre><code>void wait();\n</code></pre>\n<p>This isn’t a great name for this function for several reasons. It’s not really clear that the intention is that this is the co-operation point between the controller and the worker thread. If the “pause” isn’t active, then you’re not actually waiting on anything.</p>\n<p>I get that you want to make the logical connection to waiting (and maybe later you could add <code>wait_for()</code> and <code>wait_until()</code>), but given what a thread pausing thingy actually does (or rather, <em>should</em> do), it doesn’t quite match the model. But we’ll get more into that later.</p>\n<p>Now into the actual implementation:</p>\n<pre><code>void util::ThreadPause::wait() {\n while(is_paused()){\n std::unique_lock<std::mutex> lock(m_mutex);\n //need the condition in here in case of spurious wake up, \n //wont exit condition unless condition true\n m_cv.wait(lock, [&paused = m_paused]{return !paused;});\n }\n}\n</code></pre>\n<p>I’m not sure a loop makes sense here. That’s a rather vicious pausing strategy. What it would mean is that someone calls <code>resume()</code>… then the worker thread notices the pause is no longer active, the condition is satisfied, and the lock released… but <em>then</em>, in that <em>tiny</em> space between destructing <code>lock</code> and checking the loop condition again, someone calls <code>pause()</code> again.</p>\n<p>It’s a little bit absurd to assume that would likely happen, or that if it did, that it should be honoured. If the thread was unpaused, you might as well let it go ahead and do its work… if it happened to be re-paused while attempting to do that, it will notice it on the next loop. That seems fine enough.</p>\n<pre><code>void util::ThreadPause::pause() {\n //lock around the variable so with can modify it\n std::unique_lock<std::mutex> lock(m_mutex);\n m_paused = true;\n}\n\nvoid util::ThreadPause::resume() {\n //lock around the variable so with can modify it\n std::unique_lock<std::mutex> lock(m_mutex);\n m_paused = false;\n //unlock to stop threads from immediately locking when notify is called.\n lock.unlock();\n m_cv.notify_all();\n}\n</code></pre>\n<p>These are where I’d say the biggest over-engineering problems lie, as well as the biggest efficiency headaches. You are correct to protect a naked <code>bool</code> with a mutex. The question is… does it really need to be a naked <code>bool</code>?</p>\n<p>What if <code>m_paused</code> were a <code>std::atomic<bool></code> instead?</p>\n<p>Let’s start with <code>pause()</code>.</p>\n<p>You don’t specify what is supposed to happen if <code>pause()</code> is called while already paused, but it does just work. However, whether already paused or not, the calling thread has to acquire a lock, which will probably block (because all the worker threads using the object are repeatedly calling <code>wait()</code>, which also locks the same mutex). That block is completely unnecessary. All you really want to do is properly set <code>m_paused</code> and publish that. That’s what atomics are for:</p>\n<pre><code>class ThreadPause\n{\n // ... [snip] ...\n\n std::atomic<bool> m_paused;\n std::mutex m_mutex;\n std::condition_variable m_cv;\n};\n\nvoid util::ThreadPause::wait()\n{\n if (m_paused) // or: m_paused.load(std::memory_order_acquire)\n {\n auto lock = std::unique_lock{m_mutex};\n m_cv.wait(lock, [&m_paused]{ return not m_paused; }); // or with acquire\n }\n}\n\nvoid util::ThreadPause::pause()\n{\n m_paused = true; // or: m_paused.store(std::memory_order_release)\n}\n\nvoid util::ThreadPause::resume()\n{\n if (m_paused.exchange(false)) // memory_order_acq_rel\n {\n m_cv.notify_all();\n }\n}\n</code></pre>\n<p><code>wait()</code> is basically unchanged (though in practice, the case when unpaused is resolved <em>MUCH</em> faster because there will be less pointless locking/unlocking). <code>pause()</code> and <code>resume()</code> are now going to be <em>MUCH</em> faster, and possibly lock-free.</p>\n<p>Note that in C++20, atomics have evolved to include wait-notify semantics, and are <em>MUCH</em> more efficient than condition variables. So you could do:</p>\n<pre><code>class ThreadPause\n{\n // ... [snip] ...\n\n std::atomic_flag m_paused;\n};\n\nvoid util::ThreadPause::wait()\n{\n m_paused.wait(true); // or: m_paused.wait(true, std::memory_order::acquire)\n}\n\nvoid util::ThreadPause::pause()\n{\n m_paused.test_and_set(); // memory_order::acq_rel\n // possibly memory_order::release?\n}\n\nvoid util::ThreadPause::resume()\n{\n if (m_paused.test()) // memory_order::acquire\n {\n m_paused.clear(); // memory_order::release\n m_paused.notify_all();\n }\n}\n</code></pre>\n<p>The downside is that if you want to implement <code>wait_for()</code> or <code>wait_until()</code>, things get tougher.</p>\n<h2>An alternative concept</h2>\n<p>You have already noticed, as seen in the example code, that to properly control a thread you need a pause token <em>and</em> an exit/stop token. You currently have them as two separate things… which creates problems. (What happens if pause if true and exit is true? Wait to exit? What order to check pause/exit in? And so on.)</p>\n<p>Perhaps it would make more sense to create a unified control token that determines whether a thread should run, or should be suspended temporarily (paused), or suspended permanently (stopped). This would simplify both control and setup (because you don’t need to pass multiple “things” to the thread to control it).</p>\n<p>You’ll notice I’ve also been using specific terminology, talking about “tokens”. That’s because I’m looking at <a href=\"https://en.cppreference.com/w/cpp/header/stop_token\" rel=\"nofollow noreferrer\">the C++20 <code><stop_token></code> library</a>. <code><stop_token></code> goes half-way to what you need; it controls stopping threads, but not pausing them. So you need to extend them. Maybe something like this:</p>\n<pre><code>namespace util {\n\nenum class control_state\n{\n running,\n paused,\n stopped\n};\n\nclass control_token\n{\npublic:\n auto request_stop() noexcept -> void; // sets state to stopped\n auto request_pause() noexcept -> void; // sets state to paused if not stopped\n auto request_unpause() noexcept -> void; // sets state to running if not stopped\n\n [[nodiscard]] auto stop_requested() const noexcept -> bool;\n [[nodiscard]] auto stop_possible() const noexcept -> bool;\n\n [[nodiscard]] auto state() const noexcept -> control_state;\n};\n\n// used to control multiple threads\nclass control_source\n{\npublic:\n auto request_stop() noexcept -> void;\n auto request_pause() noexcept -> void;\n auto request_unpause() noexcept -> void;\n\n [[nodiscard]] auto stop_requested() const noexcept -> bool;\n [[nodiscard]] auto stop_possible() const noexcept -> bool;\n\n [[nodiscard]] auto state() const noexcept -> control_state;\n\n [[nodiscard]] auto get_token() const noexcept -> control_token;\n};\n\n// blocks if paused, otherwise returns either running or stopped\n[[nodiscard]] auto control_wait(control_token const&) -> control_state;\n[[nodiscard]] auto control_wait(control_source const&) -> control_state;\n// maybe also wait_for() and wait_until()\n\n// maybe also control_callback\n\nclass controlled_thread\n{\npublic:\n ~controlled_thread();\n\n auto get_control_source() const noexcept -> control_source;\n auto get_control_token() const noexcept -> control_token;\n\n auto request_stop() noexcept -> bool;\n auto request_pause() noexcept -> bool;\n auto request_unpause() noexcept -> bool;\n\n // other, standard thread functions\n\nprivate:\n std::thread _thread; // exposition only\n control_source _control; // exposition only\n};\n\ncontrolled_thread::~controlled_thread()\n{\n if (_thread.joinable())\n {\n _control.request_stop();\n _thread.join();\n }\n}\n\n} // namespace util\n</code></pre>\n<p>And you might rewrite your <code>main()</code> example like this:</p>\n<pre><code>auto main() -> int\n{\n using namespace std::chrono_literals;\n\n auto thread_function = [](std::stop_token stop_token, util::control_source control_source, int& increment)\n {\n // note that we need to check *both* the stop_token and the control_source\n //\n // why?\n //\n // because the control_source is the overall control for the entire\n // collection of threads - if we use that to stop, it stops *all* the\n // threads\n //\n // the stop_token is the control for this one single thread - if that\n // says to stop, then only this one thread is being stopped\n //\n // we need both, because the control source is how we pause/unpause/stop\n // the threads AS A GROUP... while the stop token is how we handle\n // single threads being stopped separate from the group (usually by\n // being destroyed)\n //\n // if we don't use stop_token - if we only use control_source - then\n // we can't destroy individual threads without first stopping the\n // entire group... which is clunky and dangerous\n\n while (not stop_token.stop_requested() and control_wait(control_source) != control_state::stopped)\n {\n increment += 10;\n }\n };\n\n // control source to control multiple threads\n auto control_source = util::control_source{};\n\n std::size_t thread_count = 10;\n\n auto increments = std::vector(thread_count, 0);\n auto threads = std::vector<std::jthread>{};\n for (auto i = std::size_t{0}; i < threads.size(); ++i)\n {\n threads.emplace_back(thread_function, control_source, std::ref(increments[i])});\n }\n\n // i used std::jthreads rather than util::controlled_threads because the\n // threads aren't being controlled (that is, paused/unpaused) individually\n //\n // however, you could use util::controlled_thread, which (with some minor\n // modifications to the thread function) would allow you to pause threads\n // individually, as well as pausing the entire group at once, if that's of\n // interest to you\n\n std::this_thread::sleep_for(100ms);\n\n control_source.request_pause();\n std::this_thread::sleep_for(100ms);\n std::cout << "Current values for increments: \\n";\n for(auto increment : increments){\n std::cout << increment << "\\n";\n }\n std::this_thread::sleep_for(100ms);\n std::cout << "Pause values for increments: \\n";\n for(auto increment : increments){\n std::cout << increment << "\\n";\n }\n\n control_source.request_resume();\n std::this_thread::sleep_for(100ms);\n\n control_source.request_pause();\n std::this_thread::sleep_for(100ms);\n std::cout << "Resume values for increments: \\n";\n for(auto increment : increments){\n std::cout << increment << "\\n";\n }\n\n // control_source.request_resume(); // not necessary unless you actually want to resume before stopping\n \n control_source.request_stop(); // not strictly necessary (see next comment)\n\n // threads will automatically stop and join\n //\n // note that this will happen even if an exception is thrown (and caught),\n // unlike the original code\n //\n // if control_source.request_stop() was not called, that's fine, because\n // each individual thread in threads will still be stopped individually by\n // its stop_token on destruction (rather than all of them being stopped at\n // once by the shared control_source *then* being destroyed... same shit,\n // different pile)\n}\n</code></pre>\n<p>This mechanism is non-trivial to implement, but it <em>so</em> worth it when it comes to safety (not to mention efficiency). As you can see, it makes pretty much the entire last fifth or so of your <code>main()</code> no longer necessary; all cleanup is automatic… and safe, because it happens even in the event of an exception… and everything cleans up properly even if the threads were paused at destruction time (which might easily happen if an unexpected exception is thrown while paused).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T04:13:40.537",
"Id": "255975",
"ParentId": "255959",
"Score": "4"
}
},
{
"body": "<p>Setting aside whether this is actually the code you want (I'm smelling an <a href=\"https://en.wikipedia.org/wiki/XY_problem\" rel=\"nofollow noreferrer\">XY Problem</a> here) that has been addressed by other answers.</p>\n<p>I'd like to point out that the reading of <code>m_paused</code> in <code>is_paused()</code> and consequently in <code>wait()</code> without a mutex lock is unsafe access to shared memory. Yes, it'll eventually work most of the time on most systems but under the strictest interpretation of the as-if rule in the C++standard, a thread calling <code>is_paused()</code> may not perceive a change to the <code>m_paused</code> variable from another thread for a really long (indefinite) time. It's unlikely that compilers would generate such code and CPU memory models would eventually give you consistency but there are no absolute guarantees with how the code is written.</p>\n<p>You need to hold the muted lock when reading the variable in order to enforce a memory barrier so that the thread reading it sees a consistent state of the world. Alternatively an arguably better solution would be to use <code>std::atomic_bool</code> instead which has an implied memory barrier for that variable and it would simplify your code a bit.</p>\n<p>I wanted to call this out because it's a common misconception that you can safely read fundamental types in a multi threaded context and this is wrong and a frequent source of bugs. For more info see this excellent SO thread: <a href=\"https://stackoverflow.com/questions/35226128/are-c-c-fundamental-types-atomic\">https://stackoverflow.com/questions/35226128/are-c-c-fundamental-types-atomic</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T09:39:16.450",
"Id": "255979",
"ParentId": "255959",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T20:23:05.447",
"Id": "255959",
"Score": "-1",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "C++17 multi threaded thread \"pauser\""
}
|
255959
|
<p>I've implemented a simple program to sort an input of unique numbers given as decimals on a separate line. The idea is, since all numbers are unique, to use a (long) bitfield where a <em>1</em> on index <em>n</em> represents that the number <em>n</em> is in the sorted list. The algorithm thus consists of these phases (as described in the book):</p>
<pre><code>/* phase 1: initialize set to empty */
for i = [0, n)
bit[i] = 0
/* phase 2: insert present elements into the set */
for each i in the input file
bit[i] = 1
/* phase 3: write sorted output */
for i = [0, n)
if bit[i] == 1
write i on the output file
</code></pre>
<p>In order to (re-)freshen my Rust, I chose to implement this in Rust, to be an efficient replacement for sort(1) when given the <code>-n</code> option, assuming unique input. Thus the program can be called as:</p>
<pre><code>$ bitfield # sorts stdin, writes to stdout
$ bitfield foo # sorts foo, writes to stdout
$ bitfield foo - bar # sorts foo, stdin, bar, writes to stdout
</code></pre>
<p>As with the exercise, I assume <em>n</em> (<code>MAXNUM</code>) to be <em>10,000,000</em>:</p>
<pre class="lang-rust prettyprint-override"><code>use std::io::*;
use std::fs::File;
use std::env;
const MAXNUM: usize = 10_000_000;
const _MAXLINES: usize = 1_000_000;
fn fill(src: impl BufRead, bitfield: &mut[u8; MAXNUM >> 3]) -> Result<()> {
for line in src.lines() {
let num = line?.parse::<usize>().unwrap();
if num > MAXNUM {
return Err(Error::new(ErrorKind::Other, "number too large!"));
}
bitfield[num >> 3] |= 1 << (num & 0b111);
}
return Ok(());
}
fn print_sorted(bitfield: &[u8; MAXNUM >> 3], dest: impl Write) -> Result<()> {
let mut dest = BufWriter::new(dest);
for (i, byte) in bitfield.iter().enumerate() {
for bit in 0..=0b111 {
if byte & (1 << bit) != 0 {
write!(&mut dest, "{}\n", (i << 3) | bit)?;
}
}
}
return Ok(());
}
fn main() -> Result<()> {
let mut bitfield: [u8; MAXNUM >> 3] = [0; MAXNUM >> 3];
let args: Vec<_> = env::args().skip(1).collect();
if args.is_empty() {
fill(stdin().lock(), &mut bitfield)?;
}
for arg in args {
if arg == "-" {
fill(stdin().lock(), &mut bitfield)?;
} else {
let f = match File::open(&arg) {
Err(e) => {
eprintln!("{}: {}", &arg, e);
continue;
}
Ok(f) => BufReader::new(f),
};
fill(f, &mut bitfield)?;
}
}
print_sorted(&bitfield, stdout())?;
return Ok(());
}
</code></pre>
<p>To test, I used GNU/shuf(1), time(1), and cmp(1):</p>
<pre><code>$ shuf -i 1-10000000 -n 1000000 > foo
$ time ./target/release/bitsort foo > bar
0.19s user 0.03s system 97% cpu 0.221 total
$ time sort -n foo > bar2
1.56s user 0.06s system 291% cpu 0.556 total
$ cmp bar bar2
</code></pre>
<p>Ideas?</p>
|
[] |
[
{
"body": "<h1><code>use</code> declarations</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::env;\nuse std::fs::File;\nuse std::io::*;\n</code></pre>\n<p>That's a sneaky way to import <code>io::{Error, Result}</code>. For the sake of\nreadability, it may be beneficial to spell out <code>io::</code> each time. Also\nsee the Error handling section below.</p>\n<p><code>use</code> declarations can be condensed. For example:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{env, fs::File, io};\n</code></pre>\n<h1>Allocation</h1>\n<pre><code>let args: Vec<_> = env::args().skip(1).collect();\n</code></pre>\n<p>This is an unnecessary allocation. The <code>main</code> function can be\nrewritten in terms of iterators using <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.peekable\" rel=\"nofollow noreferrer\"><code>peekable</code></a>:</p>\n<pre><code>fn main() -> Result<()> {\n // ...\n\n let mut args = env::args().skip(1).peekable();\n\n if args.peek().is_none() {\n // read from stdin\n }\n\n for arg in args {\n // handle arg\n }\n\n // ...\n}\n</code></pre>\n<h1>Error handling</h1>\n<p>Instead of unwrapping the result of <code>parse</code>, you can propagate the\nerror.</p>\n<p>For a larger program, I would suggest using the <a href=\"https://docs.rs/anyhow/\" rel=\"nofollow noreferrer\"><code>anyhow</code></a> crate\nfor error handling, which reduces a lot of boilerplate.</p>\n<h1>Miscellaneous</h1>\n<p>Don't write <code>return Ok(());</code> at the end of a function — just use\n<code>Ok(())</code>.</p>\n<p>I think you meant <code>>=</code> here: <code>if num > MAXNUM</code>.</p>\n<p>In <code>print_sorted</code>, you wrap the writer in a <code>BufWriter</code>. What if the\nwriter is already buffered? I would leave the decision to the caller.</p>\n<p>You can use <code>let mut bitfield = [0_u8; MAXNUM >> 3];</code> for less\nduplication.</p>\n<p>Using a crate like <a href=\"https://docs.rs/bit-set/\" rel=\"nofollow noreferrer\"><code>bit-set</code></a> might be good for readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T12:32:00.520",
"Id": "505231",
"Score": "1",
"body": "Tyvm! Regarding import, I do need a bit more (ErrorKind, stdin, stdout, BufRead, Write, BufReader, BufWriter) unfortunately. I do like peek though, although it needs `args` to become mut then, as you did. I now propagate the error and also used expressions instead of explicit returns. I originally chose to use BufWriter, since I also used the BufRead trait and to be consistent. I will keep bit-set in mind, when I have to \"real work\" programs. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T06:31:27.460",
"Id": "255976",
"ParentId": "255962",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T21:24:43.083",
"Id": "255962",
"Score": "3",
"Tags": [
"performance",
"sorting",
"rust",
"unix",
"bitset"
],
"Title": "Programming Pearls -- Column 1: Sorting unique numbers with bitfield"
}
|
255962
|
<p>I'm seeing a web course of computational statistics, the first project consists of a random walker, the implementation I have done works as intended:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
WALKER_STEPS: int = 5_000
# random orientation converted from degrees to radians
directions: np.array = rd.uniform(low=0, high=360, size=WALKER_STEPS) * np.pi / 180
x: list = [0]
y: list = [0]
idx: int = 0
for rad in directions:
# updates the positions of the walker
x.append(x[idx] + np.cos(rad))
y.append(y[idx] + np.sin(rad))
idx += 1
plt.plot(x, y)
plt.show()
</code></pre>
<p>I don't like the way I'm adding new elements to the lists <code>x, y</code> and I think that there's a more elegant way to do it.</p>
<p>Here a image of the result:</p>
<p><img src="https://i.stack.imgur.com/hqrgF.png" alt="Execution of Random Walk Algorithm" /></p>
<p>Note: I didn't do an abstraction because the exercise in small.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:02:13.607",
"Id": "505368",
"Score": "1",
"body": "Why do you feel that you need to improve performance here? I tested the code, and running 5000 iterations only takes around 20ms which feels pretty fast. Is it just for personal interest, or is there some requirement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T17:31:11.097",
"Id": "505422",
"Score": "0",
"body": "@maxb It's personal interest, I'm near to get my degree (I hope) and I feel quite nervious regarding the \"real world\" (my work after getting a job). I feel like I haven't learned well in college so I'm doing web courses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:49:39.943",
"Id": "505462",
"Score": "1",
"body": "I get that feeling. While this might wander a bit off topic, I'll say that studying to become a programmer/software engineer and actually working as one are two very different things. However, you'll learn a ton of stuff at your first job, so your days of learning definitely don't end when you get your degree. Best of luck!"
}
] |
[
{
"body": "<p>Use <code>np.cumsum()</code></p>\n<pre><code>import numpy as np\nimport numpy.random as rd\nimport matplotlib.pyplot as plt\nWALKER_STEPS: int = 5_000\n\n# random orientation converted from degrees to radians\ndirections: np.array = rd.uniform(low=0, high=360, size=WALKER_STEPS) * np.pi / 180\n\nx = np.cos(directions).cumsum()\ny = np.sin(directions).cumsum()\n\nplt.plot(x, y)\nplt.show()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:08:46.617",
"Id": "505370",
"Score": "1",
"body": "This is a really great improvement, but not strictly equal to the original code since it doesn't add the `0` value at the start of the array. You could just do something like `x = np.empty(WALKER_STEPS+1); y = np.empty(WALKER_STEPS+1); x[0] = 0; y[0] = 0; x[1:] = np.cos(directions).cumsum(); y[1:] = np.sin(directions).cumsum()` (sorry for the clutter) which exactly reproduces the original code but keeps the performance of your solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T23:27:48.527",
"Id": "255970",
"ParentId": "255967",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255970",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T22:26:02.323",
"Id": "255967",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Improving Efficiency of Random Walker"
}
|
255967
|
<p>I made a word search searcher that searches whether a word search contains a given word. My code is super messy I know, way too many try blocks, nested loops etc. Maybe I've just used a bad approach. I'd love some tips on things like this. The program assumes the copied word search is a perfect rectangle or square.</p>
<pre><code>charsInRow = input("Amount of characters in each row:\n")
charsInCol = input("Amount of characters in each column:\n")
allChar = input("Paste all the characters in:\n")
def Main():
PopulateArray()
FindWords()
def PopulateArray():
global allChar
allChar.lower()
allChar = list("".join(allChar.split()))
return allChar
def IsValid():
global charsInRow
global charsInCol
try:
charsInRow = int(charsInRow)
charsInCol = int(charsInCol)
except ValueError:
return False
return True
def FindWords():
wordToFind = input("What word would you like to search?")
wordToFind.lower()
wordSearched = ""
x = 0
for n in range(0, len(allChar) - 1):
if allChar[n] == wordToFind[0]:
while x <= len(wordToFind):
for i in range(0, len(wordToFind) * charsInRow, charsInRow):
try:
if allChar[n + i] == wordToFind[x]:
wordSearched = wordSearched + allChar[n + i]
n = n + i
break
except IndexError:
pass
try:
if allChar[n - i] == wordToFind[x]:
wordSearched = wordSearched + allChar[n-i]
n = n-i
break
except IndexError:
pass
try:
if allChar[(n + i) + 1] == wordToFind[x]:
wordSearched = wordSearched + allChar[(n+i) + 1]
n = (n+i) + 1
break
except IndexError:
pass
try:
if allChar[(n - i) + 1] == wordToFind[x]:
wordSearched = wordSearched + allChar[(n - i) + 1]
n = (n - i) + 1
break
except IndexError:
pass
try:
if allChar[(n - i) - 1] == wordToFind[x]:
wordSearched = wordSearched + allChar[(n - i) - 1]
n = (n - i) - 1
break
except IndexError:
pass
try:
if allChar[(n + i) - 1] == wordToFind[x]:
wordSearched = wordSearched + allChar[(n + i) - 1]
n = (n + i) - 1
break
except IndexError:
pass
try:
if allChar[(n + 1)] == wordToFind[x]:
wordSearched = wordSearched + allChar[n + 1]
n = n + 1
break
except IndexError:
pass
try:
if allChar[(n - 1)] == wordToFind[x]:
wordSearched = wordSearched + allChar[n - 1]
n = n - 1
break
except IndexError:
pass
x += 1
if wordToFind == wordSearched:
print(True)
else:
print(False)
print(wordSearched)
if IsValid():
if len(allChar) == int(charsInRow) * int(charsInCol):
Main()
else:
print("Not correct amount of characters, please try again")
else:
print("Please input numerical values for amount of characters.")
input()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T10:32:39.603",
"Id": "505224",
"Score": "0",
"body": "what is a \"word search\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T12:22:54.503",
"Id": "505229",
"Score": "2",
"body": "It's probably a good idea to show some sample input, to help those who don't understand the description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T12:24:28.850",
"Id": "505230",
"Score": "1",
"body": "@Hubert, I believe it's a form of puzzle where words are to be found in a grid of letters. All the words form straight lines horizontally, vertically or diagonally (in either direction)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T21:56:15.840",
"Id": "505285",
"Score": "0",
"body": "If you run the code it works fine, you input in all the letters in the word search and give the amount in the rows and columns. Then it will ask for you to input a word to tell you whether or not it is on there."
}
] |
[
{
"body": "<h2>Naming</h2>\n<p>For your names to be PEP8-complicant, both your method names and variable names should adopt lower_snake_case, i.e.</p>\n<pre><code>chars_in_row\nall_char\npopulate_array\nfind_words\n</code></pre>\n<h2>Side-effects</h2>\n<p><code>IsValid</code> is troubled. It does <em>not</em> do what it says on the tin - not only does it test validity of two variables, it actually converts them in-place. In addition, it improperly uses globals.</p>\n<p>A better name for this would be <code>try_parse</code>, perhaps accepting a single string, not touching any globals, and returning an <code>Optional[int]</code> that is <code>None</code> if invalid.</p>\n<h2>Repeated tries</h2>\n<p>For your blocks that look like this:</p>\n<pre><code> try:\n if allChar[n + i] == wordToFind[x]:\n wordSearched = wordSearched + allChar[n + i]\n n = n + i\n break\n except IndexError:\n pass\n</code></pre>\n<p>there are two major issues. First, you should be looping through a list of indices starting with <code>n + i</code>, <code>n - i</code>, etc. so that you don't have to repeat those blocks; for example</p>\n<pre><code>indices = (\n n + i,\n n - i,\n # ...\n)\nfor index in indices:\n # ...\n</code></pre>\n<p>Also, the fact that you're silencing <code>IndexError</code> suggests that your indexing is just wrong, and you need to re-examine your indexing bounds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T22:02:36.530",
"Id": "505286",
"Score": "0",
"body": "Not really sure what is meant by looping through a list of indices, how would that look?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T17:35:31.540",
"Id": "505332",
"Score": "0",
"body": "Edited; shown is a tuple instead of a list but same idea"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T15:59:59.097",
"Id": "255987",
"ParentId": "255978",
"Score": "4"
}
},
{
"body": "<p>Computers should work for people, not the other way around. You don't need to\nforce a user to tell you both the number of rows and columns; one dimension\nwill suffice. Also, a user's command line terminal has many nice features such\nas the ability to recall previously entered commands so you don't have to\nretype things over and over. Your Python program lacks those conveniences. That\nmeans you can improve your user's experience by avoiding <code>input()</code> at all costs\nand instead receiving user input the standard, history-proven way: via\ncommand-line arguments and options. Python has a built-in library that does a\ndecent job handling such arguments for you.</p>\n<p>Global variables are almost never needed (other than constants, function definitions, and class definitions). That's because functions can pass\narguments and return values among themselves.</p>\n<p>Those two suggestions give us the following program structure. This\nis just a sketch. The implementation details for input validation, word searching,\nand user-friendly results printing are left to you.</p>\n<pre><code>import argparse\nimport sys\n\ndef main(args):\n # Get user arguments.\n opts = parse_args(args)\n\n # Validate user inputs.\n ...\n\n # Compute any need information, such as the number\n # of columns and other data you might want to assist with\n # searching (more on that below).\n cols = len(opts.characters) // opts.rows\n\n # Perform the word search.\n searches = find_words(opts.characters, opts.rows, opts.cols, opts.words)\n\n # Report to user. Enhance as needed.\n print(searches)\n\ndef parse_args(args):\n ap = argparse.ArgumentParser()\n ap.add_argument('characters')\n ap.add_argument('words', nargs = '*')\n ap.add_argument('--rows', type = int)\n return ap.parse_args(args)\n\ndef find_words(characters, rows, cols, words):\n # Do the searching, collecting results in some type\n # of data structure or object.\n searches = {\n w : w in characters\n for w in words\n }\n\n # Return that information to main().\n # Do not print() here. Keep algorithm and presentation separate.\n return searches\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n<p>As you noted, your current approach to perform the searches is very complex and\nrepetitive. This makes it error prone, difficult to reason about, and awkward\nto change in the future. It also has some bugs: for example, in my attempted usage\nit failed to find words on a reverse diagonal. There's not much point in\nreviewing the code in its current state. You need a better plan.</p>\n<p>There are many possible ways to simplify the situation. One suggestion\nis to stop trying to write word-searching logic and instead consider this question\nHow could you reorganize the data to make word searching trivially easy?\nHere's one idea:</p>\n<pre><code># Given this:\ncharacters = 'catsdogseels'\n\n# Create this:\ngrid = [\n # The rows.\n 'cats',\n 'dogs',\n 'eels',\n 'cde',\n # The columns.\n 'aoe',\n 'tgl',\n 'sss',\n # The diagonals.\n 'c',\n 'da',\n 'eot',\n 'egs',\n 'ls',\n 's',\n],\n</code></pre>\n<p>The rows are easy to create using Python's ability to slice into lists\nin various ways. The columns can be created by transposing the rows. You can\nsearch the internet for how to write a <code>transpose()</code> function in a few lines of code.</p>\n<p>The diagonals are tricker, but here's one method:</p>\n<pre><code># Start with the rows.\n'cats'\n'dogs'\n'eels'\n\n# Shift and pad them.\n'cats '\n' dogs '\n' eels'\n\n# Then transpose() those values and strip off the spaces.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:42:53.883",
"Id": "505401",
"Score": "0",
"body": "_one dimension will suffice._ - OP states that the input may either be square or rectangular, so if you infer one dimension, you're unable to validate that the input has the correct length for the second. Maybe this is fine, but it's worth pointing out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:49:00.717",
"Id": "505402",
"Score": "0",
"body": "_avoiding input() at all costs_ is, I'm afraid, unable to justify. There are many reasons one might prefer stdin (which can be trivially redirected from the command line anyway) - including wanting to avoid pollution of the history buffer, or the need to enclose input in quotes, escaping edge cases, etc. Encourage the right tool for the job. In this case perhaps the dimensions could be optionally provided as arguments but it would be annoying to need the same for the bulk input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:04:03.807",
"Id": "505405",
"Score": "0",
"body": "By \"unable to justify\" I mean \"difficult to justify\" - my grammar glands clearly aren't awake yet"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T18:18:34.277",
"Id": "505426",
"Score": "0",
"body": "@Reinderien Perhaps I misunderstood what the OP is doing or overlooked something, but if you tell me there are 5 rows and give me 20 characters, 4 columns seems a safe inference. And your `input()` examples are mostly edge cases, in my experience. The vast majority of command-line programs don't need it. Consider the set of Unix tools: user interactivity is a tiny fraction of all usages. I groan every time I see Python educational materials encouraging new programmers to write so many CLI programs that revolve around tedious Q&A-style interactivity. It's misguided and teaches bad habits."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T11:20:03.897",
"Id": "256042",
"ParentId": "255978",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T08:11:23.683",
"Id": "255978",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Word search searcher"
}
|
255978
|
<p>In my machine learning programs I have the typical situation where I need to perform certain operations on data, which results in the following graph:</p>
<ul>
<li>data --op A--> intermediate_state --op B--> final result type 1</li>
<li>data --op A--> intermediate_state --op C--> final result type 2</li>
<li>data --op A--> intermediate_state --op D--> final result type 3</li>
</ul>
<p>So in order to not have to repeat operation A all the time I provide a "fit" method, which implements operation A.
Then, I implement transformation methods that implement the other operations.
However, since I usually only need some of the final results in the graph leaves, I want to calculate those on the one hand lazily, but then cache the result.</p>
<p>Since the operations require a parameter, I provide this one in the constructor.
I also need to pass a parametrized object with the same parametrization to different parts of the the program, where the data of operation A changes, without the parametrization changing.
That is the reason why <code>fit</code> is it's own method and not part of the constructor.
Also, because of that I cannot simply cache the results of the operations that are not A, without resetting them after invoking a new <code>fit</code>.</p>
<p>Here is my result in Python:</p>
<pre><code>class MyClass:
def __init__(self, parameter):
self.parameter = parameter
# expensive machine learning fitting
def fit(self, data) -> MyClass:
self.intermediate_data_ = data + self.parameter + 2
self._complex_transform1 = None
self._complex_transform2 = None
return self
# expensive machine learning operation version 1
@property
def complex_transform1(self):
if self._complex_transform1 is None:
self._complex_transform1 = self.intermediate_data_ / self.parameter / 2
return self._complex_transform1
# expensive machine learning operation version 2
@property
def complex_transform2(self):
if self._complex_transform2 is None:
self._complex_transform2 = self.intermediate_data_ / self.parameter / 5
return self._complex_transform2
</code></pre>
<p>The problem I have with this approach is that I am repeating quite a bit of boiler plate code.
(Note, that I have many more operations that are not A.)
Namely:</p>
<ol>
<li><p>The variables <code>self._complex_transform1</code> and <code>self._complex_transform2</code></p>
</li>
<li><p>The constructs <code>if self._complex_transform1 is None:</code> could be reduced from</p>
<pre><code> if self._complex_transform1 is None:
self._complex_transform1 = self.intermediate_data_ / self.parameter / 2
return self._complex_transform1
</code></pre>
</li>
</ol>
<p>to</p>
<pre><code> return self.intermediate_data_ / self.parameter / 2
</code></pre>
<p>and I would save a nesting.</p>
<p>I was thinking of defining a container class that contains the results and is reset by fit. But I do not see how to implement this without basically introducing the same about of boilerplate code into the transform methods.</p>
<p>Some decorator-approach might be great, but I am not sure how to approach this.</p>
|
[] |
[
{
"body": "<p>This might be a job for <code>@functools.cached_property</code>. It works a lot like <code>@property</code>, except it remembers the value between calls. The value can then be cleared using <code>del</code> in the <code>fit</code> function, or elsewhere if needed.</p>\n<p>Unfortunately, the properties can't be <code>del</code>ed until they've been set, which means we have to re-add the boiledplate in <code>fit</code> in the form of <code>try: del x; except AttributeError: pass</code>. Maybe that's an improvement since it's at least centralized, but it's still not ideal.</p>\n<p>There are workarounds like</p>\n<pre><code>def fit(self, data):\n self.intermediate_data_ = ...\n\n for prop in ["complex_transform1", "complex_transform2"]:\n try:\n delattr(self, prop)\n except AttributeError:\n pass\n\n return self\n</code></pre>\n<p>Or perhaps something like</p>\n<pre><code>def fit(self, data):\n self.intermediate_data_ = ...\n\n for prop in self.reset_on_fit:\n delattr(self, prop)\n\n self.reset_on_fit = []\n return self\n</code></pre>\n<p>with the properties looking like</p>\n<pre><code>@cached_property\ndef complex_transform1(self):\n self.reset_on_fit.append("complex_transform1")\n return self.intermediate_data_ / self.parameter / 2\n</code></pre>\n<p>But putting that data into a hardcoded string is not very refactor-friendly. Perhaps we can define a decorator to figure that out for us?</p>\n<p>Well, I haven't tested it very thoroughly, but I think we can:</p>\n<pre><code>from functools import cached_property, wraps\n\ndef resets_on_fit(fn):\n @wraps(fn)\n def wrapper(self):\n self.reset_on_fit.append(fn.__name__)\n return fn(self)\n\n return wrapper\n\nclass MyClass:\n # ...\n\n def fit(self, data):\n self.intermediate_data_ = data + self.parameter + 2\n \n for prop in self.reset_on_fit:\n delattr(self, prop)\n \n self.reset_on_fit = []\n return self\n\n @cached_property\n @resets_on_fit\n def complex_transform1(self):\n return self.intermediate_data_ / self.parameter / 2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T14:53:14.313",
"Id": "505238",
"Score": "0",
"body": "Thanks! In the meantime I also found and alternative solution. Could you review this and give me feedback? I also added a question there, because I am not even quite sure how I managed to get this working. Me turning a class member into an instance member is a mechanism I really don't get."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T14:30:59.243",
"Id": "255983",
"ParentId": "255980",
"Score": "1"
}
},
{
"body": "<p>One option is to use the code in the following. Not only should the code be very convenient, but also pretty fast after fitting. It was partly inspired by <a href=\"https://github.com/pydanny/cached-property\" rel=\"nofollow noreferrer\">https://github.com/pydanny/cached-property</a>, which also inspired the <code>@cached_property</code> of standard python's <code>functools</code>.</p>\n<p>The exciting additional part (and the part that I came up with :-)) is that we do not only decorate the method that is obviously decorated, but also the methods that are given as arguments.</p>\n<pre><code>import functools\nimport types\nfrom typing import Union, Iterable\n\n\nclass cached_resetable_property(object):\n\n def __init__(self, resetting_methods: Union[str, Iterable[str]]):\n self.resetting_methods = list(resetting_methods) if isinstance(resetting_methods, Iterable) else [resetting_methods]\n self.reset_methods_that_are_already_wrapped = []\n\n def __call__(self, function):\n self.__doc__ = getattr(function, "__doc__")\n self.function = function\n return self\n\n def __get__(self, obj, cls):\n \n decorated_function_name = self.function.__name__\n\n for reset_method_name in self.resetting_methods:\n if reset_method_name not in self.reset_methods_that_are_already_wrapped:\n self.reset_methods_that_are_already_wrapped.append(reset_method_name)\n reset_method = getattr(obj, reset_method_name)\n \n @functools.wraps(reset_method)\n def wrapper(self_wrapper, *args, **kwargs):\n try:\n delattr(self_wrapper, decorated_function_name)\n except AttributeError:\n print('Twice fit')\n return reset_method(*args, **kwargs) # still bound zu obj, that is why not reset_method(self_wrapper, *args, **kwargs) \n \n setattr(obj, reset_method_name, types.MethodType(wrapper, obj))\n\n value = obj.__dict__[decorated_function_name] = self.function(obj)\n return value\n\n\nclass MyClass:\n\n def __init__(self, parameter):\n self.parameter = parameter\n\n def fit(self, data):\n print('fit')\n self.intermediate_data_ = data + self.parameter + 2\n print(self.__dict__.keys())\n return self\n\n @cached_resetable_property(['fit'])\n def trans1(self):\n print('trans 1 - calc')\n return self.intermediate_data_ / self.parameter / 2\n\n @cached_resetable_property(['fit'])\n def trans2(self):\n print('trans 2 - calc')\n return self.intermediate_data_ / self.parameter / 5\n\n\nmyclass = MyClass(2)\nmyclass.fit(10)\nt1_a_f1 = myclass.trans1\nt1_b_f1 = myclass.trans1\nt2_a_f1 = myclass.trans2\nassert t1_a_f1 == 3.5\nassert t1_b_f1 == 3.5\nassert t2_a_f1 == 1.4\n\nmyclass.fit(20)\nt1_a_f2 = myclass.trans1\nt1_b_f2 = myclass.trans1\nt2_a_f2 = myclass.trans2\nassert t1_a_f2 == 6\nassert t1_b_f2 == 6\nassert t2_a_f2 == 2.4\n\nmyclass2 = MyClass(3)\nassert myclass2.parameter == 3\nmyclass2.fit(15)\nassert myclass2.intermediate_data_ == 15 + 3 + 2\nt1_a_f3 = myclass2.trans1\nt1_b_f3 = myclass2.trans1\nassert t1_a_f3 == myclass2.intermediate_data_ / 3 / 2\nassert t1_b_f3 == myclass2.intermediate_data_ / 3 / 2\n\nt1_c_f2 = myclass.trans1\nassert t1_a_f2 == t1_c_f2\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T14:47:15.707",
"Id": "255984",
"ParentId": "255980",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255984",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T11:58:05.677",
"Id": "255980",
"Score": "3",
"Tags": [
"python",
"cache"
],
"Title": "Caching that resets itself under certain circumstances: Reduce boiler plate code"
}
|
255980
|
<p>This program takes a symbolic link as argument, and swaps the link with its referent. For example, given <code>a -> b</code>, the result will be <code>b -> a</code>. It creates a relative link if the original was relative, otherwise an absolute link.</p>
<p>I wanted to ensure that this is an all-or-nothing command, so if it fails, it leaves everything as it was. This isn't completely achievable in the face of concurrent modification, but it does make a best-effort attempt to undo changes if it was unsuccessful. I also use <code>rm</code> with <code>--no-clobber</code> and <code>ln</code> without <code>--force</code> to avoid data loss regardless.</p>
<pre><code>#!/bin/bash
set -eu -o pipefail
die()
{
printf '%q: ' "$1"; shift
printf '%s\n' "$@"
exit 1
}
usage()
{
cat <<END
Usage: $0 FILE
FILE a symlink
The symlink will be swapped with its target
END
}
undo=""
add_undo()
{
# prepend a command to the undo list
local command
printf -v command '%q ' "$@"
undo="$command"$'\n'"$undo"
}
restore()
{
# execute the undo commands
eval "$undo" ||
die "$0" "Failed to restore to initial state!"
}
trap restore ERR;
if [ $# -ne 1 ]
then
usage >&2
exit 1
fi
case "$1" in
-h|--help)
usage; exit ;;
esac
test -L "$1" || die "$1" 'not a symlink'
test -e "$1" || die "$1" 'dangling symlink'
target=$(readlink -e "$1")
lnopts=(--symbolic)
case "$(readlink "$1")" in
/*)
# make $1 absolute, without following the link itself
set -- "$(realpath --no-symlinks "$1")"
;;
*)
lnopts+=(--relative)
;;
esac
# Create temporary working directory alongside the link
linkdir="$(mktemp --directory --tmpdir="$(dirname "$1")")"
test -d "$linkdir"
add_undo rm -r "$linkdir"
# Move the symlink into tempdir
mv -T "$1" "$linkdir/link"
add_undo mv -T "$linkdir/link" "$1"
# Create a new symlink next to the target
newlink="$(mktemp --dry-run --tmpdir="$(dirname "$target")")"
test -n "$newlink"
ln "${lnopts[@]}" "$1" "$newlink"
add_undo rm "$newlink"
# Move the target to its new location
# This is the riskiest and most expensive thing to restore, so do it last
mv -T --no-clobber "$target" "$1"
add_undo mv "$1" "$target"
# Move the new link into position left by target
mv -T --no-clobber "$newlink" "$target"
# Succeeded, so remove the temporary directory
undo=""
rm -r "$linkdir"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:43:30.007",
"Id": "507757",
"Score": "0",
"body": "Does this code work if your current working directory is not where the link is and the link is provided with a relative or absolute path? Does it work if the symlink itself points to an absolute or relative path? Reading the code, I get the impression it expects a and b both to be in the current directory, but I'm not confident in that impression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:56:22.110",
"Id": "507758",
"Score": "1",
"body": "It's supposed to work wherever the link and target are. I did my testing by hand, before I posted, so exactly what I tested is somewhat vague, but I'm reasonably certain I exercised the cases you mention. It really shouldn't matter where your working directory is, and quite a lot of the anticipated error conditions only occur when link and target are on different filesystems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:57:37.747",
"Id": "507759",
"Score": "0",
"body": "It's definitely tested for the link being absolute and relative - there's logic there to ensure the replacement link is of the same kind. I *think* it works if the target itself is a symlink, though I probably forgot to test that."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T12:12:55.713",
"Id": "255981",
"Score": "1",
"Tags": [
"bash",
"file-system"
],
"Title": "Swap a symbolic link with its target"
}
|
255981
|
<p>I am looking for a bit of help. I am having to cycle through 1400 clients code on my server, I have to check what Version of the software they are on and check for customization's to the code so when we apply updates, those aren't lost. I tried to do it serialized, as you might have guessed, that took forever. I then Tried running it parallel, as you might have expected, I am getting "Os Error, too many open files" I tried to resolve this by throwing in "sleep(random())" Which Works, But this seems convoluted and slows down the process considerably, and it could also be my code is complete garbage, any insight would be great.</p>
<p>I am using git in CLI to get version, this seems to be heavy? Is there a better way to pull tags?</p>
<p>Here, I get a list of the clients, I do some editing to get the pathing</p>
<pre><code>def full_check(client_list, cur_vers):
for c in client_list:
if sc.venue_check(c):
url = sc.surl(c[0])
if url is not None:
path = f'/home/ubuntu/site-files/{url}'
# Maximizing output, this cut run time by 90%
# Hard to log though...
nschools.append({
'path': path,
'cur_vers': cur_vers,
'client': c[0],
'schema_version': c[2]
})
# Here, I am then looping through the paths I get, I put a sleep to stop it from bugging out
# about OS File open Limits
for s in nschools:
print(s['path'])
sleep(random())
t = threading.Thread(target=vers_check, args=(s['path'], s['cur_vers'], s['client'], s['schema_version']))
t.start()
</code></pre>
<p>Here I am going through doing some version checking</p>
<pre><code>def vers_check(path, cur_vers, client, schema_version):
"""
This Checks the Schools Release.
TODO Add logging and Return Functionality.
:param client:
:param schema_version:
:param path:
:param school:
:param cur_vers:
:return:
"""
os.chdir(path)
try:
vers = subprocess.check_output(["git", "describe", "--tags"]).strip().decode('utf-8')
raw = str(vers).strip('-')
rawsplit = raw.split('-')
st = rawsplit[0]
if str(st) != cur_vers:
cschools.append({
'client': client,
'schema_version': schema_version,
'sw_version': st,
'path': path,
'is_update': False
})
log.log('warn', 'Version Check', f'The School {client} is on Software Version {st} and Schema Version {schema_version} Which is Out Of Date. Current Version is {cur_vers}')
else:
cschools.append({
'client': client,
'schema_version': schema_version,
'sw_version': st,
'path': path,
'is_update': True
})
log.log('info', 'Version Check', f'The School is on Software Version {st} and Schema Version {schema_version} Which is Up To Date. Current Version is {cur_vers}')
except subprocess.CalledProcessError as e:
log.log('err', 'Failed Version Check', f'We were unable to get the version for {client}', e)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:02:59.760",
"Id": "505239",
"Score": "0",
"body": "\"I am using Python and I have encountered a multi-threading nightmare\" is, sadly, a little predictable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:05:37.750",
"Id": "505242",
"Score": "0",
"body": "HAHA It seems to be the case, I tried making a threading class, and then do a join on it but still same issue, seems like the files just want special treatment, taken out to dinner and complains if you touch too many files at once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:06:25.197",
"Id": "505244",
"Score": "0",
"body": "The Delay-jitter did work, :D but it's slugish ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:07:18.277",
"Id": "505245",
"Score": "0",
"body": "OK; then my mistake, this is on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:07:46.690",
"Id": "505246",
"Score": "0",
"body": "No, that was my bad, I should have clarified."
}
] |
[
{
"body": "<p>First, I'm pretty sure that it's impossible for</p>\n<pre><code>os.chdir(path)\n</code></pre>\n<p>to meaningfully apply different working directories per thread; and even if it were possible it would be a bad idea. <a href=\"https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.run\" rel=\"noreferrer\">subprocess supports a <code>cwd</code> parameter</a> directly that you should use.</p>\n<p>If you were opening files yourself, you would want to make a <a href=\"https://docs.python.org/3.7/library/threading.html#threading.Semaphore\" rel=\"noreferrer\">semaphore</a> where the lock only applies to the section of the code where the file is opened. However, you aren't opening the files - it's probably your invocation of <code>git</code> that opens the most files.</p>\n<p>I think the only practical way around this is to just limit the number of concurrent threads. You could either estimate this ahead of time, or keep spinning up threads until you hit the first <code>OSError</code> and start no new threads, running one-out-one-in until your work pool is complete.</p>\n<p>If you deeply care about performance, subprocess-ing out to <code>git</code> should be replaced with in-process computation; either calling into a library or manually processing entries in <code>.git</code> (I have not researched either).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:43:23.867",
"Id": "505247",
"Score": "1",
"body": "That sounds about right. So if I understand properly, instead of git describe --tags, open the .git/refs/tags and check for the latest release file there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:45:22.470",
"Id": "505248",
"Score": "0",
"body": "Yep; if that's possible it's basically guaranteed to be faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T17:19:10.960",
"Id": "505257",
"Score": "2",
"body": "Holy Shitballs batman... took a 1-3 min code run to ~3-5 secs"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:37:20.547",
"Id": "255990",
"ParentId": "255985",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "255990",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T15:25:07.383",
"Id": "255985",
"Score": "3",
"Tags": [
"python",
"git"
],
"Title": "Tracking 1400+ client codes, multi-threading nightmare"
}
|
255985
|
<p>I made this little game that tests our language skills. It uses one external module, <a href="https://pypi.org/project/pinyin/" rel="nofollow noreferrer"><code>pinyin</code></a>, which can be installed via the command prompt command</p>
<pre><code>pip install pinyin
</code></pre>
<p>Here is how it goes:</p>
<p><a href="https://i.stack.imgur.com/Spqoq.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Spqoq.gif" alt="enter image description here" /></a></p>
<p>As you can see from the GIF, the game starts with a random selection of characters for the top boxes, and a pronunciation for each corresponding character for the bottom boxes, shuffled, of course.</p>
<p>Every time the user connects a character with the right pronunciation, the score will increase by 10, and the matching boxes will get disabled. Every time the user connects a character with the wrong pronunciation, the score will decrease by 5.</p>
<p>When all the boxes are disabled, the game resets with another random sample of characters, and the score remain the value it was before all the boxes got disabled.</p>
<p>Here is my code:</p>
<pre><code>import pygame
from random import sample, shuffle, choice
import pinyin
pygame.init()
pygame.font.init()
wn = pygame.display.set_mode((600, 400))
words = '的是不我一有大在人了中到資要可以這個你會好為上來就學交也用能如文時沒說他看提那問生過下請天們所多麼小想得之還'
class Text:
def __init__(self, text, borders, font):
self.font = font
self.color = (255, 255, 0)
self.text = self.font.render(text, True, self.color)
width = self.text.get_width()
height = self.text.get_height()
x, y, w, h = borders
self.pos = x + (w - width) / 2, y + (h - height) / 2
def draw(self):
wn.blit(self.text, self.pos)
class Score:
def __init__(self, pos, font=pygame.font.SysFont("Californian FB", 40)):
self.pos = pos
self.font = font
self.value = 0
self.color = (255, 255, 255)
self.up = 10
self.down = 5
self.potential = 0
def score_up(self):
self.value += 10
def score_down(self):
self.value -= 5
self.potential += 10
def draw(self):
wn.blit(self.font.render(str(self.value), True, self.color), self.pos)
class Box:
def __init__(self, bottom, x, y, w, h, word, font=pygame.font.SysFont("microsoftyaheimicrosoftyaheiui", 23)):
self.rect = pygame.Rect(x, y, w, h)
self.inner_rect = pygame.Rect(x + w * .125, y + h * .125, w * .75, h * .75)
self.box_color = (100, 0, 0)
self.port_color = (50, 0, 0)
self.active_color = (20, 0, 0)
self.disabled = False
self.port = pygame.Rect(x + w / 4, y + h, w / 2, h // 8)
self.word = word
if bottom:
self.port.y -= h + h // 8
word = pinyin.get(word)
self.text = Text(word, (x, y, w, h), font)
def over(self, x, y):
return self.rect.collidepoint(x, y)
def disable(self):
self.disabled = True
self.box_color = (255, 50, 50)
def draw(self, active):
if active:
pygame.draw.rect(wn, self.active_color, self.rect)
pygame.draw.rect(wn, self.box_color, self.inner_rect)
else:
pygame.draw.rect(wn, self.box_color, self.rect)
self.text.draw()
if self.disabled:
return
pygame.draw.rect(wn, self.port_color, self.port)
class Game:
def __init__(self, words, x, y):
self.w = 70
self.h = 50
self.box_x_pad = 30
self.box_y_pad = 120
self.words = words
self.in_boxes = list()
self.out_boxes = list()
self.active_in_box = None
self.active_out_box = None
for i, word in enumerate(words):
in_box = Box(False, x + i * (self.w + self.box_x_pad), y, self.w, self.h, word)
self.in_boxes.append(in_box)
shuffle(words)
for i, word in enumerate(words):
out_box = Box(True, x + i * (self.w + self.box_x_pad), y + self.box_y_pad, self.w, self.h, word)
self.out_boxes.append(out_box)
def won(self):
return all(in_box.disabled for in_box in self.in_boxes)
def draw_lines(self, event):
if self.active_in_box:
if self.active_out_box:
pygame.draw.line(wn, (255, 255, 0), self.active_in_box.port.center, self.active_out_box.port.center, 7)
else:
pygame.draw.line(wn, (255, 255, 0), self.active_in_box.port.center, event.pos, 7)
def draw_boxes(self):
for in_box in self.in_boxes:
in_box.draw(in_box == self.active_in_box)
for out_box in self.out_boxes:
out_box.draw(out_box == self.active_out_box)
bg_color = (200, 0, 0)
game = Game(sample(words, 5), 60, 120)
score = Score((60, 50))
running = True
while running:
wn.fill(bg_color)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
for in_box in game.in_boxes:
if in_box.over(*event.pos) and not in_box.disabled:
game.active_in_box = in_box
break
elif event.type == pygame.MOUSEMOTION:
if game.active_in_box:
for out_box in game.out_boxes:
if out_box.over(*event.pos) and not out_box.disabled:
game.active_out_box = out_box
break
else:
game.active_out_box = None
elif event.type == pygame.MOUSEBUTTONUP:
if game.active_in_box and game.active_out_box:
if game.active_out_box.word == game.active_in_box.word:
game.active_out_box.disable()
game.active_in_box.disable()
score.score_up()
if game.won():
game = Game(sample(words, 5), 60, 120)
else:
score.score_down()
game.active_out_box = game.active_in_box = None
game.draw_lines(event)
game.draw_boxes()
score.draw()
pygame.display.update()
pygame.quit()
</code></pre>
<p>I want to improve the efficiency of my code, and improve the DRY concept of my code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:55:05.963",
"Id": "505463",
"Score": "0",
"body": "The first thing to consider before you start optimizing your code: **is the code slow?** Have you done any benchmarking? How fast do you expect it to run? Of course you can always make your code more efficient, but from looking at the code above I see other issues that need to be addressed."
}
] |
[
{
"body": "<p>The two most important things to fix here are:</p>\n<p>Your code is non-reentrant, relying on a global <code>wn</code> surface which prevents coexistence of other surfaces in the same process; this is fairly easily fixed by passing in <code>wn</code> to your classes.</p>\n<p>Also, you've hard-coded a font that many (most?) other people will not have, so your code is non-portable. This might not be easy to fix - in runtime you could attempt to inspect the system fonts to see which ones contain the Mandarin glyphs that you use; or (somewhat more easily) hard-code a priority-ordered list of acceptable fonts and load the first one that's present. For me Droid Sans works well.</p>\n<p>Also you should consider introducing type hints.</p>\n<p>As a first cut (minus any intelligent font handling) this gets us to:</p>\n<pre><code>import pinyin\nimport pygame\nfrom pygame import draw\nfrom pygame.event import Event\nfrom pygame.font import Font, SysFont\nfrom pygame.surface import Surface\nfrom random import sample, shuffle\nfrom typing import List, Tuple, Literal\n\n\nWORDS = (\n '的是不我一有大在人了中到資要可以這個'\n '你會好為上來就學交也用能如文時沒說他'\n '看提那問生過下請天們所多麼小想得之還'\n)\n\n\nclass Text:\n def __init__(self, wn: Surface, text: str, borders: Tuple[int, int, int, int], font: Font):\n self.wn = wn\n self.font = font\n self.color = (255, 255, 0)\n self.text = self.font.render(text, True, self.color)\n width = self.text.get_width()\n height = self.text.get_height()\n x, y, w, h = borders\n self.pos = x + (w - width) / 2, y + (h - height) / 2\n\n def draw(self):\n self.wn.blit(self.text, self.pos)\n\n\nclass Score:\n def __init__(self, wn: Surface, pos: Tuple[int, int], font: Font):\n self.wn = wn\n self.pos = pos\n self.font = font\n self.value = 0\n self.color = (255, 255, 255)\n self.up = 10\n self.down = 5\n self.potential = 0\n\n def score_up(self):\n self.value += 10\n\n def score_down(self):\n self.value -= 5\n self.potential += 10\n\n def draw(self):\n self.wn.blit(self.font.render(str(self.value), True, self.color), self.pos)\n\n\nclass Box:\n def __init__(\n self,\n wn: Surface,\n bottom: bool,\n x: int,\n y: int,\n w: int,\n h: int,\n word: str,\n font: Font,\n ):\n self.wn = wn\n self.rect = pygame.Rect(x, y, w, h)\n self.inner_rect = pygame.Rect(x + w * .125, y + h * .125, w * .75, h * .75)\n self.box_color = (100, 0, 0)\n self.port_color = (50, 0, 0)\n self.active_color = (20, 0, 0)\n self.disabled = False\n self.port = pygame.Rect(x + w / 4, y + h, w / 2, h // 8)\n self.word = word\n\n if bottom:\n self.port.y -= h + h // 8\n word = pinyin.get(word)\n\n self.text = Text(wn, word, (x, y, w, h), font)\n\n def over(self, x: int, y: int) -> bool:\n ret: Literal[0, 1] = self.rect.collidepoint(x, y)\n return bool(ret)\n\n def disable(self):\n self.disabled = True\n self.box_color = (255, 50, 50)\n\n def draw(self, active: bool):\n if active:\n pygame.draw.rect(self.wn, self.active_color, self.rect)\n pygame.draw.rect(self.wn, self.box_color, self.inner_rect)\n else:\n pygame.draw.rect(self.wn, self.box_color, self.rect)\n\n self.text.draw()\n\n if not self.disabled:\n pygame.draw.rect(self.wn, self.port_color, self.port)\n\n\nclass Game:\n def __init__(self, wn: Surface, words: List[str], x: int, y: int):\n self.wn = wn\n self.w = 70\n self.h = 50\n self.box_x_pad = 30\n self.box_y_pad = 120\n self.words = words\n self.in_boxes = list()\n self.out_boxes = list()\n self.active_in_box = None\n self.active_out_box = None\n\n box_font = SysFont("Droid Sans", 23)\n\n for i, word in enumerate(words):\n in_box = Box(\n wn=wn,\n bottom=False,\n x=x + i * (self.w + self.box_x_pad),\n y=y,\n w=self.w, h=self.h, word=word, font=box_font,\n )\n self.in_boxes.append(in_box)\n\n shuffle(words)\n\n for i, word in enumerate(words):\n out_box = Box(\n wn=wn,\n bottom=True,\n x=x + i * (self.w + self.box_x_pad),\n y=y + self.box_y_pad,\n w=self.w, h=self.h, word=word, font=box_font,\n )\n self.out_boxes.append(out_box)\n\n def won(self):\n return all(in_box.disabled for in_box in self.in_boxes)\n\n def draw_lines(self, event: Event):\n if self.active_in_box:\n if self.active_out_box:\n draw.line(self.wn, (255, 255, 0), self.active_in_box.port.center, self.active_out_box.port.center, 7)\n else:\n draw.line(self.wn, (255, 255, 0), self.active_in_box.port.center, event.pos, 7)\n\n def draw_boxes(self):\n for in_box in self.in_boxes:\n in_box.draw(in_box == self.active_in_box)\n for out_box in self.out_boxes:\n out_box.draw(out_box == self.active_out_box)\n\n\ndef main():\n pygame.init()\n pygame.font.init()\n\n wn: Surface = pygame.display.set_mode((600, 400))\n\n bg_color = (200, 0, 0)\n game = Game(wn, sample(WORDS, 5), 60, 120)\n\n score_font = SysFont("Californian FB", 40)\n score = Score(wn, (60, 50), score_font)\n\n running = True\n\n while running:\n wn.fill(bg_color)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.MOUSEBUTTONDOWN:\n for in_box in game.in_boxes:\n if in_box.over(*event.pos) and not in_box.disabled:\n game.active_in_box = in_box\n break\n elif event.type == pygame.MOUSEMOTION:\n if game.active_in_box:\n for out_box in game.out_boxes:\n if out_box.over(*event.pos) and not out_box.disabled:\n game.active_out_box = out_box\n break\n else:\n game.active_out_box = None\n elif event.type == pygame.MOUSEBUTTONUP:\n if game.active_in_box and game.active_out_box:\n if game.active_out_box.word == game.active_in_box.word:\n game.active_out_box.disable()\n game.active_in_box.disable()\n score.score_up()\n if game.won():\n game = Game(wn, sample(WORDS, 5), 60, 120)\n else:\n score.score_down()\n game.active_out_box = game.active_in_box = None\n\n game.draw_lines(event)\n game.draw_boxes()\n score.draw()\n pygame.display.update()\n\n pygame.quit()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T23:28:06.667",
"Id": "505441",
"Score": "0",
"body": "There's a certain irony that you replaced Microsoft YaHei UI, [available on Windows 7+](https://docs.microsoft.com/en-us/typography/fonts/windows_7_font_list), with a font I don't have on Windows. Whilst leaving Californian FB, another Microsoft font which isn't listed as installed on any of Windows 7-10, alone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T01:15:53.620",
"Id": "505442",
"Score": "0",
"body": "@Peilonrayz Enjoy the irony if you want; the fact is that this is non-portable, and it's only a coincidence that you have a compatible font. The general solution is to avoid hard-coding a font name altogether and inspect the font for glyph presence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T01:34:36.927",
"Id": "505443",
"Score": "0",
"body": "I don't really see why I'd enjoy the irony. I have a compatible font just like 75% of other desktop users will, where your answer has made the code _less portable_ as you have an MS font and a non-MS font so now _one font will always be missing_. There is a simpler way to fix this and that is just to provide the fonts with any other assets. Such as what is done on most websites, package managers and installers."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T17:36:11.397",
"Id": "256056",
"ParentId": "255986",
"Score": "2"
}
},
{
"body": "<p>I'd say that your code looks quite nice, but there are definitely things that could be (and need to be) improved. One thing that does not need to be improved is the efficiency of the code. I did some quick benchmarking, and the frame time is about 2-3ms, which is completely fine. Here are the things I would fix:</p>\n<ol>\n<li>Lines should not exceed 80 characters in length.</li>\n<li>You have some global variables at the top, see if you can avoid them.</li>\n<li>You have a massive <code>while</code> loop which looks complicated, refactor.</li>\n<li>Your scoping is a bit wonky for some variables, even if it works.</li>\n</ol>\n<p>To start with the third issue (the first two issues are minor), see if you can describe in words what each <code>if</code> case handles, and move the code into separate functions/methods. With this in mind, you could refactor to something like this:</p>\n<pre><code>while running:\n wn.fill(bg_color)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.MOUSEBUTTONDOWN:\n handle_mouse_down()\n elif event.type == pygame.MOUSEMOTION:\n handle_mouse_motion()\n elif event.type == pygame.MOUSEBUTTONUP:\n handle_mouse_up()\n\n draw_all_and_update(event)\n</code></pre>\n<p>From looking at this, you might also discover that the <code>event</code> variable should only be used in the scope of the <code>for</code> loop, but you use it after the loop when you draw. Structuring your code like this makes it more readable, and easier to debug.</p>\n<p>Actually, when looking at your code, it seems that everything from the line <code>bg_color = (200, 0, 0)</code> and onwards can be encapsulated in some sort of window handler. I took the liberty of writing something together:</p>\n<pre><code>class WindowHandler:\n\n def __init__(self, words):\n self.bg_color = (200, 0, 0)\n self.wn = pygame.display.set_mode((600, 400))\n self.game = Game(sample(words, 5), 60, 120)\n self.score = Score((60, 50))\n self.running = True\n\n def handle_mouse_down(self, event):\n for in_box in self.game.in_boxes:\n if in_box.over(*event.pos) and not in_box.disabled:\n self.game.active_in_box = in_box\n break\n\n def handle_mouse_move(self, event):\n if self.game.active_in_box:\n for out_box in self.game.out_boxes:\n if out_box.over(*event.pos) and not out_box.disabled:\n self.game.active_out_box = out_box\n break\n else:\n self.game.active_out_box = None\n\n def handle_mouse_up(self, event):\n if self.game.active_in_box and self.game.active_out_box:\n if self.game.active_out_box.word == self.game.active_in_box.word:\n self.game.active_out_box.disable()\n self.game.active_in_box.disable()\n self.score.score_up()\n if self.game.won():\n self.game = Game(sample(words, 5), 60, 120)\n else:\n self.score.score_down()\n self.game.active_out_box = self.game.active_in_box = None\n\n def draw_all_and_update(self, event):\n self.game.draw_lines(event, self.wn)\n self.game.draw_boxes(self.wn)\n self.score.draw(self.wn)\n pygame.display.update()\n\n def main_loop(self):\n while self.running:\n self.wn.fill(self.bg_color)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.running = False\n elif event.type == pygame.MOUSEBUTTONDOWN:\n self.handle_mouse_down(event)\n elif event.type == pygame.MOUSEMOTION:\n self.handle_mouse_move(event)\n elif event.type == pygame.MOUSEBUTTONUP:\n self.handle_mouse_up(event)\n\n self.draw_all_and_update(event)\n\n\n pygame.quit()\n\nif __name__ == "__main__":\n handler = WindowHandler(words)\n handler.main_loop()\n</code></pre>\n<p>Here, all the code is easy to find, and we know what each method does from its name (though you could have even more descriptive names). Refactoring the code like this means that you have to send the game window by reference into each draw function, but that's a minor increase in complexity compared to the major benefit of this structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T13:21:46.157",
"Id": "505469",
"Score": "0",
"body": "Thanks! But I want to know, is the major benefit of this structure only for simplicity understanding the code, or would it benefit the finished result as well, such as efficiency?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T07:19:24.067",
"Id": "505532",
"Score": "0",
"body": "I'd say that the finished result of any coding project isn't just the result from running the code, but also the code itself. The improvements I've suggested above do not affect the \"efficiency\" of the code at all, but unless you're going to add more functionality or run your code on a low-powered machine, you don't need it to be more efficient. With that said, if you want to find bottlenecks and see what's slow, I'd scale everything up. Instead of having 5 pairs of boxes, have 100 (or 1000). If your program is slow then, it'll be easier to profile. If there are no issues then, you're good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T13:04:08.820",
"Id": "505661",
"Score": "0",
"body": "Okay. ---------"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T12:25:09.613",
"Id": "256086",
"ParentId": "255986",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256086",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T15:57:13.547",
"Id": "255986",
"Score": "4",
"Tags": [
"python",
"performance",
"game",
"pygame"
],
"Title": "Language skill tester using Pygame"
}
|
255986
|
<p>I am trying to write a script which gets a research paper from a website by calling their API and then traverse it sentence-wise with some conditions.</p>
<p>The paper is accessible in XML format. I am directly using the <code>nltk.sent_tokenize()</code> to break the relevant part of XML document into list of sentences and then searching for <strong>"diseases"(number of diseases in my dataframe is 12000)</strong> in every sentence using regex and if a match is found then i search for <strong>"biomarkers"(this dataframe has 20000 rows and datatype of row is of type list with each list having an average of 2 values i.e. there are more than 40000 values which are to be matched)</strong> in the same sentence. And finally the result is saved in database if disease and biomarker are found in the same sentence.</p>
<p>In the worst case steps taken to accomplish the task would be <strong>900.000</strong>(papers which are to be traversed)*<strong>15</strong>(number of sentences in each paper)*<strong>12.000</strong>(number of disease which are to be searched)*<strong>40.000</strong>(number of marker which are to be searched).</p>
<p>At the moment the code is parsing 60-70 papers in an hour which is a bit too slow.</p>
<p>The following is the code which I have tried. I am searching for the existing bottlenecks in my code. Any suggestions to optimise the code would be highly appreciated.</p>
<pre><code>import timeit
import mysql.connector
from urllib.request import urlopen
import urllib.request
import xml.dom.minidom
import xml.etree.ElementTree as ET
import requests
import xml
import lxml.etree
from lxml import etree
import re
import math
import nltk
import pandas as pd
start = timeit.default_timer()
print("start_time:", start)
mydb = mysql.connector.connect(host="localhost",user="root",password="",database="biomarker")
mycursor = mydb.cursor()
mycursor.execute("DROP TABLE IF EXISTS papers_sentence_com_ppr")
mycursor.execute("create table papers_sentence_com_ppr (id INT AUTO_INCREMENT PRIMARY KEY, paper_id VARCHAR(255), marker VARCHAR(255),marker_id VARCHAR(255), disease_name VARCHAR(255),AUTHORS TEXT, sentence TEXT)")
mycursor.execute("ALTER TABLE biomarker.papers_sentence_com_ppr CONVERT TO CHARACTER SET utf8")
#mycursor.execute("create table papers (id INT AUTO_INCREMENT PRIMARY KEY, paper_id VARCHAR(255), count VARCHAR(255),disease_name VARCHAR(255))")
df1 = pd.read_sql_query("select name from biomarker.disease2", mydb)
df = pd.read_sql_query("select * from biomarker.table_35", mydb)
print(df1)
biomarker_txt = df.at[2,'CA']
biomarker = biomarker_txt.split(" ")
print(len(biomarker))
#mycursor.execute("create table papers (id INT AUTO_INCREMENT PRIMARY KEY, paper_id VARCHAR(255), count VARCHAR(255),disease_name VARCHAR(255))")
urla='https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=(%22biomarker%22%20OR%20%22biomarkers%22%20OR%20%22biological%20marker%22%20OR%20%22biological%20markers%22)%20%20AND%20%20(LANG%3A%22eng%22%20OR%20LANG%3A%22en%22%20OR%20LANG%3A%22us%22)%20AND%20%20(HAS_ABSTRACT%3Ay)%20%20AND%20%20(SRC%3A%22PPR%22)&resultType=idlist&pageSize=1000&format=xml'
urlb='https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=(%22biomarker%22%20OR%20%22biomarkers%22%20OR%20%22biological%20marker%22%20OR%20%22biological%20markers%22)%20%20AND%20%20(LANG%3A%22eng%22%20OR%20LANG%3A%22en%22%20OR%20LANG%3A%22us%22)%20AND%20%20(HAS_ABSTRACT%3Ay)%20%20AND%20%20(SRC%3A%22PPR%22)&resultType=idlist&pageSize=1000&format=xml'
array1 = []
re1=requests.get(urla)
root = ET.fromstring(re1.content)
for hitCount in root.iter('hitCount'):
hit_count=int(hitCount.text)
result_value=hit_count
hit_count1=hit_count/1000
hit_count=math.ceil(hit_count1)
hit_count=10
counter1=0
counter3=0
y=0
i=1
for x in range(hit_count):
re1=requests.get(urla)
root1 = ET.fromstring(re1.content)
for id in root1.iter('id'):
id_text=id.text
array1.append(id.text)
for nextCursorMark in root1.iter('nextCursorMark'):
counter3=counter3+1
print(counter3)
urla=urlb
urla =urla+"&cursorMark="+nextCursorMark.text
for i in range(result_value):# will run 900.000 times for 900.000 papers
print("paper no:", i,)
paper_id=(array1[i]) #array1 contains list of paper ids
print("paper_id:", paper_id)
make_url= 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=ext_id:'+paper_id+'&resultType=core&format=xml'
re2=requests.get(make_url)
root2 = ET.fromstring(re2.content)
for abstractText in root2.iter('abstractText'):
abstract_text_without_tags= re.sub(r"<[^>]*>"," ",abstractText.text )#extract the relevant xml part
nltk_tokens = nltk.sent_tokenize(abstract_text_without_tags)#break the text into sentences
for text in range(len(nltk_tokens)):#depends on the length of text
for zz in range(len(df)):#df has 20.000 rows
biomarker_txt=((df.at[zz,'CA']))
biomarker = biomarker_txt.split(" ")# a cell could have more than value which are separated by an space
for tt in range(len(biomarker)):
if len(biomarker[tt])>2:
matches_for_marker = re.findall(rf"\b{re.escape(biomarker[tt])}\b", nltk_tokens[text])
if len(matches_for_marker)!=0:
for y in range(len(df1)):
disease_name=(df1.at[y,'name'])
regex_for_dis = rf"\b{disease_name}\b"
matches_for_dis= re.findall(regex_for_dis, nltk_tokens[text], re.IGNORECASE | re.MULTILINE)
#matches_for_dis = [re.findall(rf"\b{(df1.at[y,'name'])}\b", nltk_tokens[text], re.IGNORECASE | re.MULTILINE) for y in range(len(df1))]
if len(matches_for_dis)!=0:
for firstPublicationDate in root2.iter('firstPublicationDate'):
firstPublicationDate=firstPublicationDate.text
for authorString in root2.iter('authorString'):
counter1=counter1+1
mycursor.execute("insert into papers_sentence_com_ppr (id, paper_id,firstPublicationDate, marker,marker_id, disease_name, AUTHORS, sentence) values (%s,%s,%s, %s, %s,%s, %s,%s)", (counter1, paper_id,firstPublicationDate, biomarker[tt],(df.at[zz,'Entry']), (df1.at[y,'name']), authorString.text, nltk_tokens[text]))
#print("***********************************************************DATABASE_ENTRY*************************************************************\n")
mydb.commit()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:54:03.800",
"Id": "505252",
"Score": "1",
"body": "Please show all of the code, including where `result_value` is initialized"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T19:17:53.343",
"Id": "505276",
"Score": "0",
"body": "i have added the rest of the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:19:08.250",
"Id": "510466",
"Score": "0",
"body": "15 sentences in a paper? That seems very low."
}
] |
[
{
"body": "<p>Currently all of your code exists in one global pile, with no functions, submodules or classes. Introduce some of those.</p>\n<p>I see that your password is shown as blank for the database. A few things:</p>\n<ul>\n<li>I really hope that the password is not <em>actually</em> blank, and that you've instead omitted it for the purposes of review. Please don't use a blank password.</li>\n<li>This script should not be logging in as root, but rather as a permissions-limited user.</li>\n<li>Store your database login password somewhere else, in some kind of secure wallet, cred store, etc.</li>\n</ul>\n<p>Wrap your connection and cursor objects in <code>with</code> context managers.</p>\n<p>You should definitely not be dropping an entire table in this script. If anything, maybe you should be <code>truncate</code>ing it to delete all of its data; but definitely don't drop it.</p>\n<p>You have a pile of unused imports; all of these:</p>\n<pre><code>from urllib.request import urlopen\nimport urllib.request\nimport xml.dom.minidom\nimport xml\nimport lxml.etree\nfrom lxml import etree\n</code></pre>\n<p>need to be deleted.</p>\n<p>Change your URL construction so that instead of this thing:</p>\n<pre><code>https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=(%22biomarker%22%20OR%20%22biomarkers%22%20OR%20%22biological%20marker%22%20OR%20%22biological%20markers%22)%20%20AND%20%20(LANG%3A%22eng%22%20OR%20LANG%3A%22en%22%20OR%20LANG%3A%22us%22)%20AND%20%20(HAS_ABSTRACT%3Ay)%20%20AND%20%20(SRC%3A%22PPR%22)&resultType=idlist&pageSize=1000&format=xml\n</code></pre>\n<p>you have a well-defined method that accepts a session, forms a parameter dictionary, validates the response and parses an ET:</p>\n<pre><code>def get_ebi(session: Session, **kwargs: str) -> ET.ElementTree:\n query = (\n '("biomarker" OR "biomarkers" OR "biological marker" OR "biological markers") '\n 'AND (LANG:"eng" OR LANG:"en" OR LANG:"us") '\n 'AND (HAS_ABSTRACT:y) '\n 'AND (SRC:"PPR")'\n )\n with session.get(\n 'https://www.ebi.ac.uk/europepmc/webservices/rest/search',\n params={\n 'format': 'xml',\n 'resultType': 'idlist',\n 'pageSize': 1_000,\n 'query': query,\n **kwargs,\n },\n stream=True,\n ) as response:\n response.raise_for_status()\n root = ET.parse(response.raw)\n\n return root\n\n\nwith Session() as sess:\n root = get_ebi(sess)\n for hitCount in root.iter('hitCount'):\n hit_count = int(hitCount.text)\n result_value = hit_count\n hit_count1 = hit_count / 1_000\n hit_count = math.ceil(hit_count1)\n</code></pre>\n<p>That aside, your code is filled with things that simply don't make sense. You overwrite variables:</p>\n<pre><code>hit_count=math.ceil(hit_count1)\nhit_count=10\n</code></pre>\n<p>You have mystical, impenetrable variable names:</p>\n<pre><code>array1 = []\ncounter1=0\ncounter3=0\ny=0\ni=1\n</code></pre>\n<p>You have variables with slightly different names that do completely different things:</p>\n<pre><code>for hitCount in root.iter('hitCount'):\n hit_count=int(hitCount.text)\n</code></pre>\n<p>That last example also improperly iterates through all <code>hitCount</code> elements when it should only pay attention to the first.</p>\n<p>You shadow built-ins:</p>\n<pre><code> for id in root1.iter('id'):\n</code></pre>\n<p>You name variables that are the exact opposite of what they contain; <code>text</code> will actually contain an integer:</p>\n<pre><code>for text in range(len(nltk_tokens)):\n</code></pre>\n<p>You do a commit in your innermost loop, when it should probably hold off until much later, possibly the end of the script.</p>\n<p>You should attempt to address these issues, particularly organization into subroutine methods, and then post a new question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T18:26:21.467",
"Id": "505337",
"Score": "1",
"body": "Many thanks!! I will make the mentioned changes and hopefully the process would get faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:00:04.937",
"Id": "505366",
"Score": "1",
"body": "@sanjeev_gautam You can also post a new question with your updated code. Once you have addressed the obvious shortcomings of your current code, someone might find a good way to speed it up significantly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T11:31:34.140",
"Id": "505380",
"Score": "0",
"body": "yep, i will do that. i have made some changes but i guess the function calling is making the process even slower."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T17:30:52.353",
"Id": "256018",
"ParentId": "255989",
"Score": "2"
}
},
{
"body": "<p>Let's put a <code>FULLTEXT</code> index in the middle of the algorithm. It is likely to be faster than other techniques since it is effectively an inverted index of word=>sentence; this can be used for names of both diseases and biomarkers. Furthermore, it can handle multi-word names.</p>\n<p>Parse the XML, put one sentence per row into the table. That will be only about 14M rows; not bad.</p>\n<pre><code>FULLTEXT(sentence)\n</code></pre>\n<p>Searching for a single combination is easy and very fast:</p>\n<pre><code>SELECT ... WHERE MATCH(sentence)\n AGAINST(+"disease name" +"biomarker" IN BOOLEAN MODE)\n</code></pre>\n<p>But that is not practical, since you would need to do it 480M times.</p>\n<p>So, let's instead search for only one name at time and capture the the info. This will take 40K + 12K queries, something like</p>\n<pre><code>UPDATE t\n SET a_disease = ?\n WHERE MATCH(sentence) AGAINST(+? IN BOOLEAN MODE)\n</code></pre>\n<p>Ditto for another column, <code>a_marker</code>.</p>\n<p>Then, poof, this gives you the entire answer at the sentence level:</p>\n<pre><code>SELECT paper_id, sentence_id, a_disease, a_marker\n FROM t\n WHERE a_disease IS NOT NULL\n AND a_marker IS NOT NULL;\n</code></pre>\n<p>A little more work with a <code>GROUP BY</code> would boil that down to the disease-marker pairs, by "paper":</p>\n<pre><code>SELECT paper_id,\n a_disease,\n GROUP_CONCAT(DISTINCT a_marker SEPARATOR ", " ORDER BY a_marker) AS markers\n FROM (\n SELECT paper_id, a_disease, a_marker\n FROM t\n WHERE a_disease IS NOT NULL\n AND a_marker IS NOT NULL\n ) AS tmp\n GROUP BY a_disease, paper_id\n ORDER BY a_disease, paper_id;\n</code></pre>\n<p>(Or some other grouping/ordering.)</p>\n<p>One flaw: If one sentence mentions multiple diseases or markers, this does not handle it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:38:20.787",
"Id": "258901",
"ParentId": "255989",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:31:37.143",
"Id": "255989",
"Score": "3",
"Tags": [
"python",
"multithreading",
"recursion",
"regex",
"database"
],
"Title": "Downloading and parsing research papers"
}
|
255989
|
<p>I found Conway's game of life. I had heard of it, of course, but didn't think it would be so easy and fun to implement. Anyway, here's my code which I know needs a lot of polish:</p>
<pre><code>#include <iostream>
#include <vector>
#include <windows.h>
#define SIZE 10
using std::vector;
struct Pos {
int x;
int y;
Pos(int ix, int iy) : x(ix), y(iy) {}
};
void printGrid();
int getNeighborCount(Pos cellPos);
void next(int (&universe)[SIZE][SIZE]);
void killOrBirthCells(int (&universe)[SIZE][SIZE], vector<Pos> &toKill, vector<Pos> &toBirth);
void cellFate(int &cell, Pos cellPos, int neighborCount, vector<Pos> &toKill, vector<Pos> &toBirth);
void printUniverse(int (&universe)[SIZE][SIZE]);
int main() {
int universe[SIZE][SIZE] = {0};
// glider
universe[0][2] = 1;
universe[1][2] = 1;
universe[2][2] = 1;
universe[2][1] = 1;
universe[1][0] = 1;
while (1) {
system("cls");
next(universe);
printUniverse(universe);
Sleep(500);
}
return 0;
}
int getNeighborCount(int (&universe)[SIZE][SIZE], Pos cellPos) {
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int x = cellPos.x - 1 + j;
int y = cellPos.y - 1 + i;
// handle cells on the edge
if (x >= 0 && y >= 0 && x < SIZE && y < SIZE
&& universe[cellPos.y - 1 + i][cellPos.x - 1 + j] == 1) {
count++;
}
}
}
// exclude itself
if (universe[cellPos.y][cellPos.x]) {
return count - 1;
}
return count;
}
void next(int (&universe)[SIZE][SIZE]) {
std::vector<Pos> toKill;
std::vector<Pos> toBirth;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
Pos cellPos{j, i};
int neighborCount = getNeighborCount(universe, cellPos);
cellFate(universe[i][j], cellPos, neighborCount, toKill, toBirth);
}
}
killOrBirthCells(universe, toKill, toBirth);
}
// populate toKill and toBirth vectors
void cellFate(int &cell, Pos cellPos, int neighborCount, vector<Pos> &toKill, vector<Pos> &toBirth) {
if (cell == 1) {
// lonely
if (neighborCount == 0 || neighborCount == 1) {
toKill.push_back(cellPos);
// overcrowded
} else if (neighborCount >= 4 && neighborCount <= 8) {
toKill.push_back(cellPos);
}
} else {
if (neighborCount == 3) {
toBirth.push_back(cellPos);
}
}
}
void killOrBirthCells(int (&universe)[SIZE][SIZE], vector<Pos> &toKill, vector<Pos> &toBirth) {
for (Pos cellPos : toKill) {
universe[cellPos.y][cellPos.x] = 0;
}
for (Pos cellPos : toBirth) {
universe[cellPos.y][cellPos.x] = 1;
}
toKill.clear();
toBirth.clear();
}
void printUniverse(int (&universe)[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (universe[i][j] == 1) {
std::cout << 'x';
} else {
std::cout << '.';
}
}
std::cout << '\n';
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If you're going to use C++, make full use of the language. Create a class to hold your universe, then all of your non-<code>main</code> functions can be members. You also won't have to pass around a reference to the <code>universe</code> array as it would be a member of the class.</p>\n<p>One alternative to the <code>toKill</code> and <code>toBirth</code> vectors is to have two "universe" arrays. You'd use one as the source, and copy over and update the values into the second, then trade off which array you modify on the next pass thru. <code>cellFate</code> would return the new (updated) value for that cell, and <code>killOrBirthCells</code> would be eliminated.</p>\n<p><code>getNeighborCount</code> is only using <code>i</code> and <code>j</code> as offsets to the x and y values. You can redo the loops to directly update the x and y values, and also handle the edge clipping by proper tracking of the start and end values for the loops. It would also be easy to exclude the cell itself.</p>\n<p>Combining all that we get a new <code>getNeighborCount</code> (that would be a member of a class):</p>\n<pre><code>int Universe::getNeighborCount(Pos cellPos) const {\n int count = 0;\n int sx = std::max(cellPos.x - 1, 0);\n int ex = std::min(cellPos.x + 1, SIZE - 1);\n int sy = std::max(cellPos.y - 1, 0);\n int ey - std::min(cellPos.y + 1, SIZE - 1);\n for (int y = sy; y <= ey; ++y) {\n for (int x = sx; x <= ex; ++x) {\n if (y != cellPos.y || x != cellPos.x) {\n if (universe[y][x] == 1)\n count++;\n }\n }\n }\n return count;\n}\n</code></pre>\n<p>You may be able to reduce flickering by moving the <code>system("cls");</code> call to immediately before the call to <code>printUniverse</code>. This would reduce the amount of time that you have an empty screen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T11:38:42.557",
"Id": "505316",
"Score": "0",
"body": "The `int y` looked like an obvious typo to me. But then I saw that there is no `sy` at all. I would have added this extra variable to not confuse human readers. The compiler is clever enough to optimize it away. Your current code is asymmetric between the x and y coordinates in a place where there is no actual asymmetry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T16:07:14.943",
"Id": "505326",
"Score": "1",
"body": "@RolandIllig Good points. I've modified the code a bit to improve the readability."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T18:27:22.047",
"Id": "255996",
"ParentId": "255994",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T17:21:37.413",
"Id": "255994",
"Score": "1",
"Tags": [
"c++",
"game-of-life"
],
"Title": "my implementation of conway's game of life in C++"
}
|
255994
|
<p>I have this simple code, but it's messy - how do I do it cleaner?</p>
<p>It works like this: If you click on the <code>menu-btn1</code> the <code>div</code> shows up, and hide others, but if you click on <code>menu-btn1</code> again it will hide as well.</p>
<pre class="lang-js prettyprint-override"><code>let coll = document.getElementsByClassName('collection');
let dis = document.getElementsByClassName('display');
let drop = document.getElementsByClassName('drop');
document.getElementById("menu-btn1").addEventListener("click", function() {
if(coll[0].style.display == 'none') {
coll[0].style.display = 'block';
dis[0].style.display = 'none';
drop[0].style.display = 'none';
} else {
coll[0].style.display = 'none';
}
});
</code></pre>
<pre class="lang-html prettyprint-override"><code><div class="menu">
<span id="text"><span id="menu-btn1">collection</span></span>
</div>
<div class="collection" style="display:none;"></div>
<div class="display" style="display:none;"></div>
<div class="drop style="display:none;"></div>
</code></pre>
<p>There is nothing important in css really, only the grid positioning.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T06:21:08.060",
"Id": "506642",
"Score": "0",
"body": "Your code seems won't work: 1. Your last element (drop) has wrong quote marks. 2. Last 2 elements (display and drop) are always `display: none` in your code."
}
] |
[
{
"body": "<p>First I think that using <code>document.querySelector</code> seems much user friendly than using <code>document.getElementsByClassName</code>. Instead of <code>let coll = document.getElementsByClassName('collection'); coll[0].xxx</code>, we can just use <code>document.querySeletor('collection').xxx</code>.</p>\n<p>So code can refactor a bit to</p>\n<pre><code> let coll = document.querySelector('.collection');\n let dis = document.querySelector('.display');\n let drop = document.querySelector('.drop');\n\n document.getElementById("menu-btn1").addEventListener("click", function() {\n if(coll.style.display == 'none') {\n coll.style.display = 'block';\n dis.style.display = 'none';\n drop.style.display = 'none';\n } else {\n coll.style.display = 'none';\n }\n });\n</code></pre>\n<p>Next, I will place the DOM retrieval code into the event handler, to prevent unnecessary namespace pollution. Though maybe in your working code, you may use the <code>coll</code> for other handling, then it is okay to place there. In addition, I don't think one will change the variable of a DOM to other value, so I would use a <code>constant</code> instead.</p>\n<pre><code> document.getElementById("menu-btn1").addEventListener("click", function() {\n const coll = document.querySelector('.collection');\n const dis = document.querySelector('.display');\n const drop = document.querySelector('.drop');\n if(coll.style.display == 'none') {\n coll.style.display = 'block';\n dis.style.display = 'none';\n drop.style.display = 'none';\n } else {\n coll.style.display = 'none';\n }\n });\n</code></pre>\n<blockquote>\n<p>However these changes does not resolve the fact that <code>display: none</code> is actually scattered in both HTML and Javascript. I think a better idea is just to place the code in one place. That is remove the styling in HTML.</p>\n</blockquote>\n<p>To do so, I think there are possibly 2 approaches, one is the use of <code>RxJS</code>, another way is to use of data driven approach, e.g. <code>React</code>, <code>Angular</code>, <code>Vue</code>, ...</p>\n<h3>Data Driven Approach: Use of VueJS</h3>\n<p>Let's first have a look at How we can implement it in Data Driven Approach.\nI will use Vue for demonstration, as it is the simplest to setup among the three.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>new Vue({\n el: \"#app\",\n template: `\n <div class=\"ui\">\n <div class=\"menu\">\n <span id=\"text\"><span @click=\"show = !show\">collection</span></span>\n </div>\n\n <div class=\"collection\" :style=\"styles\">\n Collection Inside\n </div>\n </div>\n `,\n data: function() {\n return {\n show: false\n }\n },\n computed: {\n styles: function() {\n return {\n \"display\": this.show ? \"block\": \"none\"\n };\n },\n },\n })</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n<div id=\"app\">\n </div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>As you can see, the HTML code is now placed in Javascript as a template, and we make use of <code>:style</code> and <code>@click</code> in the template, instead of normal HTML. These are Vue specific\nsyntax and is used in Vue for easy interaction between the Vue component Javascript and the template.</p>\n<h3>Event Driven Approach: RxJS</h3>\n<p>Another approach would be RxJS, that just work without a framework, so makes it more easy to adopt in a legacy web application.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>rxjs.merge(\n rxjs.of(1), // so that it immediately triggers\n rxjs.fromEvent(document.querySelector(\"#menu-btn1\"), 'click'),\n)\n .pipe(\n rxjs.operators.scan((accum, value, index) => {\n return index % 2 == 1;\n }, false)\n ).subscribe(show => {\n const coll = document.querySelector(\".collection\");\n const value = show ? \"block\" : \"none\";\n coll.style.display = value;\n }\n\n )</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js\"></script>\n<div class=\"menu\">\n <span id=\"text\"><span id=\"menu-btn1\">collection</span></span>\n</div>\n\n<div class=\"collection\">\n Collection Inside\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Here is all the solution I think of, and it is left to you to decide which way is the cleanest code. To me, I just like the way <code>RxJS</code> is constructed, and do not need to maintain an extra data for storage.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T03:52:02.003",
"Id": "256010",
"ParentId": "255995",
"Score": "2"
}
},
{
"body": "<p>There are some things that You could improve:</p>\n<ul>\n<li>Why do You treat a <code>span</code> element as a button when there is a more semantic solution which is a <code>button</code> element</li>\n<li>Another bad practice is an inline styling. It gives too much <code>specificity</code> to the element and it's hard to maintain that. Use stylesheets instead.</li>\n<li>Your variable names should be more descriptive. You want to make Your code reading experience as easy as it's possible so that other devs can easily understand it.</li>\n<li>Instead adding css styles using JS. Add a <code>css class</code> using JS and create those rules in the stylesheet.</li>\n<li>If I understand what You want to achieve correctly, Your code mechanics could be replaced using the <code>event delegation</code> pattern</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T20:45:31.627",
"Id": "256112",
"ParentId": "255995",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T17:46:56.883",
"Id": "255995",
"Score": "0",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Script for showing/hiding on click - how can I write this code cleaner?"
}
|
255995
|
<h1>About</h1>
<p>I've been experimenting with gcc's <code>__cleanup__</code> attribute, and thought it'd be a great fit for a memory-safe smart pointer for C.</p>
<p>This is the implementation. It requires you to use either the helper macros <code>SHARED_PTR_VAR_*</code> or declare a variable as <code>shared_ptr_t __attribute__((__cleanup__(cleanup_shared_ptr))) var={0};</code>, and since it relies on gcc's extensions, it obviously requires a compiler that supports them.</p>
<p>The reference counting is thread-safe, but the pointer access itself is not synchronized.</p>
<h2>shared_ptr.h</h2>
<pre><code>#pragma once
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include "util.h"
typedef struct shared_ptr_cntrl {
void * data;
void (*cleanup)(void*);
pthread_mutex_t mutex;
int64_t count;
int64_t cntrl_count;
} shared_ptr_cntrl_t;
typedef struct shared_ptr {
shared_ptr_cntrl_t * cntrl;
} shared_ptr_t;
shared_ptr_t create_shared_ptr(void ** data,void (*cleanup)(void*));
void cleanup_shared_ptr(shared_ptr_t *);
shared_ptr_t copy_shared_ptr(shared_ptr_t *);
static inline shared_ptr_t move_shared_ptr(shared_ptr_t * p){
shared_ptr_t tmp={p->cntrl};
p->cntrl=NULL;
return tmp;
}
static inline void * get_shared_ptr_ptr(shared_ptr_t * p){
return (p->cntrl)?p->cntrl->data:NULL;
}
#define SHARED_PTR_FROM(type,cleanup,expr) ({\
type * v=calloc(1,sizeof(type));\
if(!v) err_exit("\n\nOUT OF MEMORY\n\n");\
*v=expr;\
create_shared_ptr((void**)&v,(void(*)(void*))cleanup);\
})
#define SHARED_PTR_FROM_E(cleanup,expr) SHARED_PTR_FROM(__typeof__((expr)),cleanup,expr)
#define SHARED_PTR_VAR_FROM_E(name,cleanup,expr) CLEANUP_VAR_E(cleanup_shared_ptr,name,SHARED_PTR_FROM_E(cleanup,expr))
#define SHARED_PTR_VAR_E(name,expr) CLEANUP_VAR_E(cleanup_shared_ptr,name,expr)
#define SHARED_PTR_VAR_FROM(type,name,cleanup,expr) CLEANUP_VAR_E(cleanup_shared_ptr,name,SHARED_PTR_FROM(type,cleanup,expr));
</code></pre>
<h2>util.h</h2>
<pre><code>#define CLEANUP(cleanup) __attribute__((__cleanup__(cleanup)))
#define CLEANUP_VAR(type,cleanup,name) type __attribute__((__cleanup__(cleanup))) name
#define CLEANUP_VAR_E(cleanup,name,expr) CLEANUP_VAR(__typeof__(expr),cleanup,name) = (expr) ;
__attribute__((format(printf,1,2)))
__attribute__((__noreturn__)) void err_exit(const char * fmt,...);
</code></pre>
<h2>shared_ptr.c</h2>
<pre><code>#include "shared_ptr.h"
shared_ptr_t create_shared_ptr(void ** data,void (*cleanup)(void*)){
if(!*data){
return (shared_ptr_t){NULL};//avoid allocation for NULL pointers
}
shared_ptr_cntrl_t * cntrl=calloc(1,sizeof(shared_ptr_cntrl_t));
cntrl->data=*data;
*data=NULL;
cntrl->cleanup=cleanup;
cntrl->count=1;
cntrl->cntrl_count=1;
if(pthread_mutex_init(&cntrl->mutex,NULL)){
err_exit("Failed to create mutex for shared_ptr");
}
return (shared_ptr_t){cntrl};
}
void cleanup_shared_ptr(shared_ptr_t * p){
if(p->cntrl){
if(pthread_mutex_lock(&p->cntrl->mutex)){
err_exit("Failed to lock mutex for shared_ptr");
}
p->cntrl->count--;
p->cntrl->cntrl_count--;
if(p->cntrl->count==0){
if(p->cntrl->cleanup){
p->cntrl->cleanup(p->cntrl->data);
}
free(p->cntrl->data);
p->cntrl->data=NULL;
if(p->cntrl->cntrl_count==0){
pthread_mutex_t m=p->cntrl->mutex;
free(p->cntrl);
p->cntrl=NULL;
if(pthread_mutex_unlock(&m)){
err_exit("Failed to unlock mutex for shared_ptr");
}
if(pthread_mutex_destroy(&m)){
err_exit("Failed to destroy mutex for shared_ptr");
}
return;
}
}
if(pthread_mutex_unlock(&p->cntrl->mutex)){
err_exit("Failed to unlock mutex for shared_ptr");
}
}
}
shared_ptr_t copy_shared_ptr(shared_ptr_t * p){
if(p->cntrl){
if(pthread_mutex_lock(&p->cntrl->mutex)){
err_exit("Failed to lock mutex for shared_ptr");
}
p->cntrl->count++;
p->cntrl->cntrl_count++;
if(pthread_mutex_unlock(&p->cntrl->mutex)){
err_exit("Failed to unlock mutex for shared_ptr");
}
}
return (shared_ptr_t){p->cntrl};
}
</code></pre>
<h2>util.c</h2>
<pre><code>#include "util.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
void err_exit(const char * fmt,...){
va_list arg;
va_start(arg,fmt);
vfprintf(stderr,fmt,arg);
va_end(arg);
exit(1);
}
</code></pre>
<h1>Example Code</h1>
<pre><code>#include <stdio.h>
#include "shared_ptr.h"
static void example_destruct(volatile int * p){
printf("int destruct %d\n",*p);
}
int main(){
SHARED_PTR_VAR_FROM(volatile int,example_ptr,example_destruct,20);
SHARED_PTR_VAR_E(example_ptr_2,copy_shared_ptr(&example_ptr));
printf("%d\n",*(volatile int*)get_shared_ptr_ptr(&example_ptr_2));
SHARED_PTR_VAR_E(example_ptr_3,move_shared_ptr(&example_ptr_2));
(*(volatile int*)get_shared_ptr_ptr(&example_ptr_3))=23;
{
SHARED_PTR_VAR_E(example_ptr_4,copy_shared_ptr(&example_ptr));
SHARED_PTR_VAR_E(example_ptr_5,copy_shared_ptr(&example_ptr));
SHARED_PTR_VAR_E(example_ptr_6,copy_shared_ptr(&example_ptr));
SHARED_PTR_VAR_E(example_ptr_7,copy_shared_ptr(&example_ptr));
SHARED_PTR_VAR_E(example_ptr_8,copy_shared_ptr(&example_ptr));
}
printf("%d\n",*(volatile int*)get_shared_ptr_ptr(&example_ptr));
(*(volatile int*)get_shared_ptr_ptr(&example_ptr_3))=40;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Tolerate <code>NULL</code> during clean-up</strong></p>\n<p>As <code>free(NULL)</code> is OK, consider a <code>NULL</code> test for clean-up</p>\n<pre><code>void cleanup_shared_ptr(shared_ptr_t * p){\n if (p) {\n ....\n }\n}\n</code></pre>\n<p><strong>Lack of documentation</strong></p>\n<p>*.h files deserve some overall comments. Consider users may not to wade through the .c file code to deduce functionality.</p>\n<p><strong>Fixed width</strong></p>\n<p>I see not compelling reasons for <code>int64_t</code> here. Consider <code>int</code>. If concerned that <code>int</code> is insufficient, go for <code>intmax_t</code> or <code>long long</code>.</p>\n<pre><code>// int64_t count, cntrl_count;\nint count, cntrl_count;\n</code></pre>\n<p><strong>Missing guard</strong></p>\n<p><code>util.h</code> lacks a <code>#pragma once</code> or the like.</p>\n<p><strong>Naming</strong></p>\n<p>Some names <code>shared_ptr.h</code> names begin with <em>shared_ptr</em>, others have <em>shared_ptr</em> in the middle. Recommend uniformity, IMO, begin with <em>shared_ptr</em>.</p>\n<p><code>util.h</code> is far too generic and gives no hint that it defines <code>err_exit()</code>.</p>\n<p><code>format()</code> has a high surprising collision potential.</p>\n<p><code>shared_ptr_t</code> is a <code>struct</code> type, yet contains "ptr". Better to not call things that are not pointers as <code>ptr</code>, etc.</p>\n<p><strong>Surprising exits</strong></p>\n<p>Good to have error <em>detection</em>. <code>SHARED_PTR_FROM</code> and others can exit code. I'd find this too draconian for general use as this code is effectively defining error handle for its use. Do the <em>smart pointer</em> task, yet leave <em>final error handling</em> to the application.</p>\n<p><strong>Allocate by object</strong></p>\n<p>Rather that allocate by the type, consider allocating by the referenced object. Easier to code right, review and maintain.</p>\n<pre><code>// shared_ptr_cntrl_t * cntrl=calloc(1,sizeof(shared_ptr_cntrl_t));\nshared_ptr_cntrl_t * cntrl = calloc(1, sizeof * cntrl);\n</code></pre>\n<p><strong>Good use of <code>#include "util.h"</code></strong></p>\n<p>Nice to have <code>uitl.c</code> first include <code>"util.h"</code>. It is a good test of <code>util.h</code> sufficiency.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T23:30:34.070",
"Id": "505352",
"Score": "0",
"body": "thanks for the review! regarding `util.h` the included is only a snippet, the actual header contains a few function and macro definitions that don't quite need a separate header of their own, and when extracting the snippet i missed to copy the `#pragma once`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T17:23:49.280",
"Id": "256016",
"ParentId": "255997",
"Score": "2"
}
},
{
"body": "<p>I don't think these can be negative:</p>\n<blockquote>\n<pre><code>int64_t count;\nint64_t cntrl_count;\n</code></pre>\n</blockquote>\n<p>Consider an unsigned type (perhaps <code>size_t</code> is most appropriate?)</p>\n<p>This cast and associated use are not portable:</p>\n<blockquote>\n<pre><code>create_shared_ptr((void**)&v,(void(*)(void*))cleanup); \n</code></pre>\n</blockquote>\n\n<blockquote>\n<pre><code> p->cntrl->cleanup(p->cntrl->data);\n</code></pre>\n</blockquote>\n<p>Although function pointers can be cast to another function pointer type, calling through such a pointer without casting it back is Undefined Behaviour. Instead, require that the caller provides a function pointer of that accepts <code>void*</code>, as <code>qsort()</code> and <code>bsearch()</code> do.</p>\n<blockquote>\n<pre><code>type * v=calloc(1,sizeof(type));\nshared_ptr_cntrl_t * cntrl=calloc(1,sizeof(shared_ptr_cntrl_t));\n</code></pre>\n</blockquote>\n<p>I'd normally write <code>sizeof *v</code> and <code>sizeof *cntrl</code> respectively. It's not a big deal here, but is a good practice where the pointer's declaration is far away.</p>\n<p>I don't think it's meaningful to copy a pthread mutex like this:</p>\n<blockquote>\n<pre><code> pthread_mutex_t m=p->cntrl->mutex;\n free(p->cntrl);\n p->cntrl=NULL;\n if(pthread_mutex_unlock(&m)){\n err_exit("Failed to unlock mutex for shared_ptr");\n }\n if(pthread_mutex_destroy(&m)){\n err_exit("Failed to destroy mutex for shared_ptr");\n }\n</code></pre>\n</blockquote>\n<p>However, if we're in that code, then we know that there's no other reference in play, so we can simply destroy the mutex we have, before the <code>free()</code>:</p>\n<pre><code> pthread_mutex_t *const m = &p->cntrl->mutex;\n\n ...\n\n if(pthread_mutex_unlock(m)){\n err_exit("Failed to unlock mutex for shared_ptr");\n }\n if(pthread_mutex_destroy(m)){\n err_exit("Failed to destroy mutex for shared_ptr");\n }\n free(p->cntrl);\n p->cntrl=NULL;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T07:53:09.107",
"Id": "505451",
"Score": "1",
"body": "Oh, in that case I was wrong. I believed that function pointers could not be cast to each other. But I looked it up, and I am now better informed!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T11:55:01.627",
"Id": "256044",
"ParentId": "255997",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256016",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T18:40:11.080",
"Id": "255997",
"Score": "2",
"Tags": [
"c",
"memory-management",
"pointers",
"gcc"
],
"Title": "Reference-counted smart pointer in C"
}
|
255997
|
<p>Coming from a Python background, one thing I really miss in C++ is a <a href="https://chialunwu.medium.com/wtf-is-memoization-a2979594fb2a#:%7E:text=From%20wikipedia%2C%20the%20definition%20of,the%20same%20inputs%20occur%20again." rel="nofollow noreferrer">memoization</a> <a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow noreferrer">decorator</a> (like <a href="https://www.geeksforgeeks.org/python-functools-lru_cache/" rel="nofollow noreferrer"><code>functools.lru_cache</code></a>. As I sometimes compete on <a href="https://codeforces.com/" rel="nofollow noreferrer">Codeforces</a>, I found myself implementing a similar thing in C++17 in case I ever need a quick and easy way to memoize function calls. I was wondering whether I could get some feedback on my implementation, and whether something like this could be effective and practical to use in production code.</p>
<p>Thanks!</p>
<pre class="lang-cpp prettyprint-override"><code>#include <bits/stdc++.h>
// Using a map
template <typename RetType, typename... ArgTypes>
auto memoize(std::function<RetType(ArgTypes...)> func) -> decltype(func) {
return [
memo = std::map<std::tuple<ArgTypes...>, RetType>(),
func = std::move(func)
](ArgTypes... args) mutable -> RetType {
auto key = make_tuple(args...);
if (auto it = memo.find(key); it != memo.end()) {
return it->second;
}
auto [it, emplaced] = memo.emplace(key, func(args...));
return it->second;
};
}
// Using an unordered_map
// From boost
template<typename T>
inline void hash_combine(std::size_t& seed, const T& val) {
std::hash<T> hasher;
seed ^= hasher(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template <typename RetType, typename... ArgTypes>
auto memoizeHashed(std::function<RetType(ArgTypes...)> func) -> decltype(func) {
using KeyType = std::tuple<ArgTypes...>;
struct KeyHashFnc {
size_t operator() (const KeyType& key) const {
size_t result = 0;
std::apply([&result](auto&&... args) {
(
hash_combine(result, std::forward<decltype(args)>(args)),
...
);
}, key);
return result;
}
};
return [
memo = std::unordered_map<KeyType, RetType, KeyHashFnc>(),
func = std::move(func)
](ArgTypes... args) mutable -> RetType {
auto key = std::make_tuple(args...);
if (auto it = memo.find(key); it != memo.end()) {
return it->second;
}
auto [it, emplaced] = memo.emplace(key, func(args...));
return it->second;
};
}
// Intended usage (solves the problem: https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/)
using namespace std;
int INF = 1e9+5;
class Solution {
public:
int minDifficulty(const vector<int>& arr, int d) {
int N = arr.size();
using DpFuncType = function<int(int,int)>;
DpFuncType dp = [&dp, &arr, N](int i, int k) {
int n = N-i;
if (k <= 0) {
return -1;
}
else if (k > n) {
return -1;
}
else if (k == n) {
return accumulate(arr.begin()+i, arr.end(), 0);
}
else { // k < n
if (k == 1) {
return *max_element(arr.begin()+i, arr.end());
}
else {
int result = INF;
int maxVal = arr[i];
for (int j = i+1; j < N; ++j) {
int curr = dp(j,k-1);
if (curr != -1) {
result = min(result, maxVal + curr);
}
maxVal = max(maxVal, arr[j]);
}
if (result == INF) {
return -1;
}
else {
return result;
}
}
}
};
dp = memoizeHashed(dp); // memoize(...) can also be used here
return dp(0,d);
}
};
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Only <code>#include</code> public headers from the STL</h1>\n<p>You <a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">should not <code>#include <bits/stdc++.h></code></a>. It is a non-standard header that is not guaranteed to exist or work as you expect it to. If you do this regularly, please unlearn this, and instead <code>#include</code> the proper header files. You only need two for your memoizer:</p>\n<pre><code>#include <map>\n#include <functional>\n</code></pre>\n<h1>No need for trailing return types</h1>\n<p>I see you specify trailing return types for several of the functions and lambdas you define, but I do not think they are not necessary here. The compiler can automatically deduce them, and while returning a lambda with an <code>auto</code> return type is not the same as when the return type is explicitly set to a <code>std::function</code> as mentioned by HTNW, the caller can always do this conversion themselves if necessary, and indeed that is what happens when you write <code>dp = memoize(...)</code> inside <code>minDifficulty()</code>.</p>\n<h1>Consider rewriting it as a <code>class</code></h1>\n<p>Instead of writing <code>memoize()</code> as a function that returns a mutable lambda function, I would just go for the less exciting way of writing a <code>class</code>. The main reason is that more people will be familiar with it, and if you ever want to add functionality to the memoizer, a <code>class</code> makes that much easier. Here is how it could look:</p>\n<pre><code>template <typename RetType, typename... ArgTypes>\nclass memoize {\n std::function<RetType(ArgTypes...)> func;\n std::map<std::tuple<ArgTypes...>, RetType> memo;\npublic:\n memoize(std::function<RetType(ArgTypes...)> func): func(func) {}\n auto operator()(ArgTypes... args) {\n auto key = std::make_tuple(args...);\n if (auto it = memo.find(key); it != memo.end()) {\n return it->second;\n }\n auto [it, emplaced] = memo.emplace(key, func(args...));\n return it->second;\n };\n};\n</code></pre>\n<p>This is actually a complete drop-in replacement for the lambda, even this line will still work:</p>\n<pre><code>dp = memoize(dp);\n</code></pre>\n<h1>Use in production code</h1>\n<p>Your memoizer could be used in production code, sure! However, apart from coding challenges I've found the number of cases where I would ever need this to be vanishingly small. Either things need to be remembered much longer than the lifetime of a program, in which case a proper database is used, or all the values you could probably want are precomputed once and included with the binary, or the algorithm I am implementing would be just as easy to implement by reading/writing to a container directly instead of using a memoizer function.</p>\n<p>A <code>std::map</code> or <code>std::unordered_map</code> is also not always the most efficient way to store things, often a <code>std::vector</code> is much more efficient if the function just gets a single integer argument. And your memoizer also doesn't handle the case where some parameters to the function are not part of the key to be memoized, although you could work around that by using <code>std::bind()</code> or some other form of currying.</p>\n<p>In short, there's nothing wrong with it as far as I can see, but I think there won't be very many occasions where you would need it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T17:33:49.937",
"Id": "505331",
"Score": "1",
"body": "Re: trailing return types: no, they won't be deduced correctly. The `return` statements return lambdas. The declared return types are `std::function`s. The trailing return types specify implicit conversions. Removing the trailing return types will change what the functions return. This may be desirable, maybe not."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T15:26:46.160",
"Id": "256013",
"ParentId": "255998",
"Score": "6"
}
},
{
"body": "<p>In addition to the <a href=\"/a/256013/75307\">answer by G. Sliepen</a>, consider what values the function might return. Clearly the memoizer will not work for copy-only types. It could be made to work for reference types, but will require an overload to memoize a <code>std::reference_wrapper</code> instead - and you may need to think carefully about the lifetime of the referent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:00:42.873",
"Id": "256036",
"ParentId": "255998",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T19:00:57.497",
"Id": "255998",
"Score": "6",
"Tags": [
"c++",
"c++17"
],
"Title": "C++ Implementation of a Python-like memoization decorator"
}
|
255998
|
<p>I have datasetA with 90,000 rows and datasetB with 5,000 rows. Each dataset has a column called "ID" with employee IDs. My goal is to to create another column in datasetA that identifies whether the employee ID in datasetA is also in datasetB with a True/False. Additionally, there are most likely some multiples for certain employees/employee ids in both datasets. I am fairly certain that the code I wrote works, but it is way too slow, and I was wondering what I could change to make it faster? Thanks!</p>
<pre><code>#Creating the new column to identify whether the ID in datasetA is also in datasetB.
datasetA["inB"] = "Empty"
# Looping through
for id_num in datasetA["ID"]:
filt = (datasetA["ID"] == id_num)
if (datasetB["ID"] == id_num).any():
datasetA.loc[filt, "inB"] = True
else:
datasetA.loc[filt, "inB"] = False
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T22:17:40.123",
"Id": "505287",
"Score": "1",
"body": "You can do that with an inner join. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html"
}
] |
[
{
"body": "<p>Is this what you want?</p>\n<pre><code>import pandas as pd\n\ndatasetA = pd.DataFrame(\n [\n [\n 'ID222'\n ],\n [\n 'ID233'\n ],\n [\n 'ID2123'\n ],\n [\n 'ID233'\n ]\n ], columns = ['ID']\n)\n\ndatasetB = pd.DataFrame(\n [\n [\n 'ID222'\n ],\n [\n 'ID233'\n ],\n [\n 'ID212355'\n ],\n [\n 'ID233'\n ]\n ], columns = ['ID']\n)\ndatasetA["inB"] = datasetA.ID.isin(datasetB.ID)\ndatasetA.drop_duplicates()\n\n ID inB\n0 ID222 True\n1 ID233 True\n2 ID2123 False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T23:05:33.673",
"Id": "256005",
"ParentId": "256001",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256005",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T20:09:08.470",
"Id": "256001",
"Score": "1",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "I have code that loops through a column of a dataframe. How can I make this code faster? (Python/Pandas)"
}
|
256001
|
<p>I would like to convert a list <code>A</code></p>
<pre><code>A = {1, 12, 3, 3, 3, 8, 5, 5 }
</code></pre>
<p>into list <code>B</code></p>
<pre><code>B = {1, 12, 3, 8, 5 }
</code></pre>
<p>As you see, items 3 and 5 are repeated in <code>A</code>, and those repetitions are eliminated in <code>B</code>.</p>
<p>The code I've created to do that is the following:</p>
<pre><code>public IEnumerable<int> FilterRepeatingElements(IEnumerable<int> source)
{
return source
.Select(x => (IEnumerable<int>)new[] { x })
.Aggregate((a, b) => a.Last() != b.First() ? a.Concat(b) : a);
}
</code></pre>
<p>It works, but I wonder if there's a better more expressive way to do it using "LINQ", either with the classic .NET methods or the ones in a library like <a href="https://morelinq.github.io/" rel="nofollow noreferrer">morelinq</a>.</p>
<p>Thanks!</p>
<h2>EDIT</h2>
<p>I have found out that my solution has problem with uses case like this:</p>
<pre><code>FilterRepeatingElements(MoreEnumerable.Random()).Take(10)
</code></pre>
<ul>
<li><code>MoreEnumerable.Random()</code> generates an infinite sequence.
Executing code like this, hangs the execution.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T18:00:43.887",
"Id": "505336",
"Score": "2",
"body": "You cannot make a finite set of unique elements of an infinite series. There is no way around it (well in general, for the specific case of int data type you can, at the cost of memory proportional to number of possible values of int). Anyway for finite inputs you can use a set like HashSet or linq offers the Distinct method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T21:18:46.957",
"Id": "505342",
"Score": "0",
"body": "@slepic `non-unique != repetions`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:00:21.440",
"Id": "505367",
"Score": "0",
"body": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:34:16.580",
"Id": "505387",
"Score": "0",
"body": "Can you please clarify whether the repetition you want to avoid is just for elements repeating in a row, or repeating ever?\n\ni.e. is `{3,4,3}` valid or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:32:14.080",
"Id": "505410",
"Score": "0",
"body": "maybe this is related : https://codereview.stackexchange.com/questions/61338/generate-random-numbers-without-repetitions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T16:51:02.853",
"Id": "505414",
"Score": "0",
"body": "@Turksarama i missed that information in my first and second read as well. Then I realized it's in the title. Not the best place to put such a crucial detail, but yep he only wants to remove consecutive repetitions."
}
] |
[
{
"body": "<p>While <a href=\"https://codereview.stackexchange.com/a/256024/52662\">aepot</a> answer is a good answer and got my upvote it does only work for type int. Which I know the question for an example uses int in their code but if wanting it to work for all data types will need to change the code a bit.</p>\n<pre><code>public static class EnumerableExtensions\n{\n public static IEnumerable<TSource> FilterRepeatingElements<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)\n {\n using (var enumerator = source.GetEnumerator())\n {\n if (enumerator.MoveNext())\n {\n var item = enumerator.Current;\n yield return item;\n\n while (enumerator.MoveNext())\n {\n if (!comparer.Equals(item, enumerator.Current))\n {\n item = enumerator.Current;\n yield return item;\n }\n }\n }\n }\n }\n\n public static IEnumerable<TSource> FilterRepeatingElements<TSource>(this IEnumerable<TSource> source)\n {\n return FilterRepeatingElements(source, EqualityComparer<TSource>.Default);\n }\n}\n</code></pre>\n<p>This would work for any type and takes the same parameters as linq Distinct does since we are doing a "kind of" distinct.</p>\n<pre><code>var data = new int[] { 1, 12, 3, 3, 3, 8, 5, 5 };\nvar postData = data.FilterRepeatingElements().ToArray();\n\nvar items = new string[] { "A", "A", "B", "C", "C", "D", "D" };\nvar postItems = items.FilterRepeatingElements().ToArray();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T01:38:59.777",
"Id": "256028",
"ParentId": "256014",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256028",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T16:25:35.030",
"Id": "256014",
"Score": "1",
"Tags": [
"c#",
"algorithm",
".net",
"linq"
],
"Title": "Eliminating repetitions of subsequent items in a list"
}
|
256014
|
<p>I'm working on a coding challenge that tasks me with taking a file with a dictionary, reading from it, and then replacing the matching words from the input file with what is found in the dictionary.</p>
<p>I have a few concerns with my code.</p>
<ol>
<li>I don't want to overengineer a task that seems simple, but I also don't want to trivialize the complexity of certain I/O operations or make trivial tests for it. As a result I've created one data class that processes the dictionary from the input file and two service classes that implement two interfaces. See image below.</li>
</ol>
<p><a href="https://i.stack.imgur.com/0ocEa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ocEa.png" alt="enter image description here" /></a></p>
<ol start="2">
<li>That being said I have concerns about my business logic class, FileContentReplacementService, because the code seems messy and I feel like there are some things that could be improved but I just can't put my fingers on them at this very moment. Below is the full class:</li>
</ol>
<p><strong>FileContentReplacementService</strong></p>
<pre><code>import java.io.*;
import java.util.Map;
import Challenge2.model.FileBasedDictionary;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class FileContentReplacementService implements ContentReplacementService {
private static final Logger LOGGER = LogManager.getLogger(FileContentReplacementService.class);
private final RetrieverService retrieverService;
private final FileBasedDictionary fileBasedDictionary;
private final String outputFileName;
public FileContentReplacementService(RetrieverService retrieverService,
FileBasedDictionary fileBasedDictionary,
String outputFileName) {
this.retrieverService = retrieverService;
this.fileBasedDictionary = fileBasedDictionary;
this.outputFileName = outputFileName;
}
public boolean areMatchingWordsReplace(){
String fileName = "src/main/resources/" + outputFileName;
try {
applyDictionaryToFile(fileBasedDictionary, retrieverService.getBufferedReader(), fileName);
} catch (IOException ioe) {
LOGGER.error(String.format("File not reachable \n %s", ExceptionUtils.getStackTrace(ioe)));
return false;
}
return true;
}
private void applyDictionaryToFile(FileBasedDictionary fileBasedDictionary,
BufferedReader bufferedReader,
String fileName) throws IOException
{
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
LineIterator lineIterator = new LineIterator(bufferedReader);
while (lineIterator.hasNext()) {
String line = lineIterator.nextLine();
bufferedOutputStream.write(replaceWords(line, fileBasedDictionary.getDictionary()));
}
}
private byte[] replaceWords(String line, Map<String, String> dictionary) {
if (line.isEmpty()) {
return "\n\n".getBytes();
}
for (Map.Entry<String, String> entry : dictionary.entrySet()) {
line = line.replaceAll(entry.getKey(), entry.getValue());
}
return line.getBytes();
}
}
</code></pre>
<ol start="3">
<li>Is there any way to trigger the exception from the try/catch block of FileContentReplacementService? I've made a few tries but I could only trigger it by closing the BufferedReader and then flushing it, but I can only do that inside the method. My test, see below, is currently not covering that bit and I would like to know if there's something that can be done to cover it.</li>
</ol>
<p><strong>FileContentReplacementServiceTest</strong></p>
<pre><code>import Challenge2.model.FileBasedDictionary;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.*;
import java.util.Map;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class FileContentReplacementServiceTest {
@Mock
FileBasedDictionary fileBasedDictionary;
@Mock
FileRetrieverService fileRetrieverService;
@Mock
BufferedReader bufferedReader;
FileContentReplacementService fileContentReplacementService;
@Test
public void givenValidFile_WhenWordsAreReplaced_ThenReplaceMatchingWordsIsCalled() throws IOException {
when(fileRetrieverService.getBufferedReader()).thenReturn(bufferedReader);
when(bufferedReader.readLine()).thenReturn("Test2", "", null);
when(fileBasedDictionary.getDictionary()).thenReturn(Map.of("Test1", "Test2"));
fileContentReplacementService = new FileContentReplacementService(fileRetrieverService, fileBasedDictionary, "\\testOutput\\test.txt");
assertTrue(fileContentReplacementService.areMatchingWordsReplace());
}
}
</code></pre>
<ol start="4">
<li>My FileRetrieverService is basically untesteable and, despite my best efforts, I just can't find a way to be able to test it and maintain decent code quality and/or not break a number of SOLID principles.</li>
</ol>
<p><strong>FileRetrieverService</strong></p>
<pre><code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Objects;
public class FileRetrieverService implements RetrieverService {
private final String fileName;
public FileRetrieverService(String fileName) {
this.fileName = fileName;
}
@Override
public BufferedReader getBufferedReader(){
return new BufferedReader(new InputStreamReader(Objects.requireNonNull(
getClass().
getClassLoader().
getResourceAsStream(fileName))));
}
}
</code></pre>
<p><strong>FileRetrieverServiceTest</strong></p>
<pre><code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.BufferedReader;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class FileRetrieverServiceTest{
@Mock
BufferedReader bufferedReader;
@Mock
FileRetrieverService fileRetrieverService;
@Test
public void givenFileName_WhenReturnBufferedReader_ThenReturnReader(){
when(fileRetrieverService.getBufferedReader()).thenReturn(bufferedReader);
assertNotNull(fileRetrieverService.getBufferedReader());
}
@Test(expected = NullPointerException.class)
public void givenInvalidFileName_ThenFailFast(){
doThrow(NullPointerException.class).when(fileRetrieverService).getBufferedReader();
fileRetrieverService.getBufferedReader();
}
}
</code></pre>
<p>I would really appreciate it if someone could take a look at the code above and give me a few pointers as to what improvements could be done to make the code more easily testable and better designed.</p>
|
[] |
[
{
"body": "<p>I don't think you need to test everything around opening the input file, closing it, handling exceptions, etc. For the purpose of this task, I believe you want to test your logic, and trust that <code>FileReader</code> or <code>FileInputStream</code> etc just work.</p>\n<p>I would have a class that that can read the format of the dictionary (not provided, presumably this is <code>FileBasedDictionary</code>), and create a test of that class that it produces the expected <code>Map<String, String></code>.</p>\n<p>Then have a class that does business logic (i.e. the word replacement) that can operate independant of the source of the data (by taking in a flexible type like a <code>BufferedReader</code>). You can add a test case that demonstrates how to create a valid data source, while also demonstrating the business logic - tests are as much about documentation/demonstration as they are about checking.</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.util.Map;\n\npublic class DictionaryReplacementService {\n \n private Map<String, String> dictionary;\n \n public DictionaryReplacementService(Map<String, String> dictionary) {\n this.dictionary = dictionary;\n }\n\n public void replaceWords(BufferedReader input, BufferedWriter output)\n throws IOException {\n String line;\n while ((line = input.readLine()) != null) {\n for (Map.Entry<String, String> entry : dictionary.entrySet()) {\n line = line.replaceAll(entry.getKey(), entry.getValue());\n }\n output.write(line);\n }\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>import static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.junit.jupiter.api.Test;\n\nclass DictionaryReplacementServiceTest {\n\n @Test\n void test() throws IOException {\n String source = "It was the best of times, it was the blurst of times.";\n\n Map<String, String> dictionary = new LinkedHashMap<String, String>();\n dictionary.put("blurst", "worst");\n\n StringWriter outString = new StringWriter();\n try (BufferedReader in = new BufferedReader(new StringReader(source));\n BufferedWriter out = new BufferedWriter(outString)) {\n new DictionaryReplacementService(dictionary).replaceWords(in, out);\n }\n\n assertEquals("It was the best of times, it was the worst of times.",\n outString.toString());\n }\n\n}\n</code></pre>\n<p>In this case, the user of your class would just need to replace <code>StringReader</code> with <code>FileReader</code> if that's what they wanted - the <code>DictionaryReplacementService</code> is not interested in that.</p>\n<p>A last note is about exceptions and return values. Instead of returning <code>true</code> for success and <code>false</code> for failure, I prefer to return void for success and just throw any exceptions that mean the success case is not possible (in my case, the <code>try</code> is just to ensure the resources are closed - it doesn't catch any exceptions, and throwing an exception from a JUnit test means a test failure, which is what we want).</p>\n<p>You said you don't want to trivialize file i/o and you want to test what happens when problems happen, but that's not a concern of <code>DictionaryReplacementService</code> - it only needs to <em>signal</em> that something went wrong. In a full program, you would have logic in the UI layer to try and recover (let the user know there was a problem, prompt them to try again or use a different file etc). You're not writing that UI layer now, so I wouldn't expect to see tests about it now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T22:12:18.407",
"Id": "256025",
"ParentId": "256022",
"Score": "3"
}
},
{
"body": "<p>@Jeremy Hunt's great answer has covered an approach that will make your classes more testable. I'm just going to add a few other things to think about, with your existing code.</p>\n<h2>given..when..then</h2>\n<p>You're naming your tests using a given..when..then approach. If that's your preference, then you may want to consider using Mockito's BDD extensions which might make your test names and their contents easier to link up. The usage is exactly the same, but the commands are aliased, so you end up with:</p>\n<pre><code>import static org.mockito.BDDMockito.given;\n\n// ...\n\n@Test\npublic void givenValidFile_WhenWordsAreReplaced_ThenReplaceMatchingWordsIsCalled() throws IOException {\n given(fileRetrieverService.getBufferedReader()).willReturn(bufferedReader);\n given(bufferedReader.readLine()).willReturn("Test2", "", null);\n given(fileBasedDictionary.getDictionary()).willReturn(Map.of("Test1", "Test2"));\n\n fileContentReplacementService = new FileContentReplacementService(fileRetrieverService, fileBasedDictionary, "\\\\testOutput\\\\test.txt");\n var matchingWordsWereReplaced = fileContentReplacementService.areMatchingWordsReplace();\n\n assertTrue(matchingWordsWereReplaced);\n}\n</code></pre>\n<h2>IsCalled</h2>\n<p>When I see a test that's got 'IsCalled' in its title, it sets my expectation that the test is going to <code>verify</code> that a particular call has taken place. That isn't what your test is doing, so it took me a bit by suprise.</p>\n<h2>Spacing</h2>\n<p>Tests typically consist of three parts.. Arrange/Given, Act/When, Assert/Then. Consider putting a blank line between the three sections. Having it all as one block makes it increasing difficult to identify the important bits when a test fails.</p>\n<h2>Levels of abstraction</h2>\n<p>When writing methods, maintaining the same level of abstraction can make the methods easier to understand/change/reuse. Your <code>replaceWords</code> method takes in a <code>String</code>, a <code>Map<String, String></code>, but it returns a <code>byte[]</code>.</p>\n<pre><code>private byte[] replaceWords(String line, Map<String, String> dictionary)\n</code></pre>\n<p>Consider having it return a <code>String</code> instead and leaving the responsibility of knowing about converting it to a <code>byte[]</code> to the calling bit of code that needs to know how to write to a file.</p>\n<h2>NOP tests</h2>\n<p>You may have added these tests, just to give something to review, however they're a great example of a common pitfall that people can fall into when starting to use mocks.</p>\n<pre><code>@Test\npublic void givenFileName_WhenReturnBufferedReader_ThenReturnReader(){\n when(fileRetrieverService.getBufferedReader()).thenReturn(bufferedReader);\n assertNotNull(fileRetrieverService.getBufferedReader());\n}\n</code></pre>\n<p>You're setting up a mock to do something, then testing that it does what you've told it to do. You're not testing any of your code at all, what you're actually testing is that the mocking framework works as expected.</p>\n<p>An alternative, since your class appears to work with file resources, could be to construct the <code>FileRetrieverService</code> with a known file resource and then verify that the returned buffer worked.</p>\n<h2>Class state</h2>\n<p>For me, <code>filename</code> doesn't feel like it's a property of the <code>FileRetrieverService</code>, instead it feels like it should be an argument to the <code>getBufferedReader</code> method. It may make sense if you're going to be calling <code>getBufferedReader</code> multiple times, but for me, if you're only using a field in one method, it seems like it belongs as a parameter to that method.</p>\n<h2>Testing exceptions</h2>\n<p>@Jeremy Hunt has already addressed this, but generally if something feels hard to test, it's usually a hint that your logic needs to be broken up differently. That said, to test an exception I'll usually look at the dependencies that are being injected into the system under test to see if there's a way to generate the exception via one of them. This is a bit more complicated for your example because you're after and IOException is a checked exception so needs to be declared on method signatures. Looking through the dependencies, one approach that seemed like it might work would be to have <code>bufferedReader.readLine</code>, throw an IOException</p>\n<pre><code>when(bufferedReader.readLine()).thenThrow(new IOException()); \n</code></pre>\n<p>However this doesn't work, because <code>LineReader</code> translates the <code>IOException</code> into a <code>RuntimeException</code> (<code>IllegalStateException</code>), so you don't catch it. This lends some support to Jeremy's suggestion that it's up to the caller to deal with the Exceptions, however if you did want to catch them in the class, then should you be handling errors from the Reader or are you only really interested in writer exceptions.</p>\n<p>If you did want to test the writer, then the next step might be to introduce a <code>FileWriterService</code>. This seems like a similar level of abstraction to the <code>FileReaderService</code>, so could be a valid object. This would allow you to manipulate the constructed output stream and throw exceptions etc. So you would end up with a test something like this:</p>\n<pre><code>@Mock\nprivate BufferedOutputStream bufferedOutputStream;\n@Mock\nprivate FileWriterService fileWriterService;\n\n\n@Test\npublic void givenValidFile_WhenFileIOError_ThenNotReplaced() throws IOException {\n when(fileRetrieverService.getBufferedReader()).thenReturn(bufferedReader);\n when(bufferedReader.readLine()).thenReturn("Test2", "", null);\n when(fileWriterService.getBufferedWriter(any())).thenReturn(bufferedOutputStream);\n when(fileBasedDictionary.getDictionary()).thenReturn(Map.of("Test1", "Test2"));\n\n doThrow(new IOException()).when(bufferedOutputStream).write(any());\n\n fileContentReplacementService = new FileContentReplacementService(fileRetrieverService, fileBasedDictionary, "\\\\testOutput\\\\test.txt", fileWriterService);\n\n assertFalse(fileContentReplacementService.areMatchingWordsReplace());\n}\n</code></pre>\n<p>With the implementation pulled out from the FileContentReplacementService into:</p>\n<pre><code>public class FileWriterService {\n public BufferedOutputStream getBufferedWriter(String fileName) throws FileNotFoundException {\n FileOutputStream fileOutputStream = new FileOutputStream(fileName);\n return new BufferedOutputStream(fileOutputStream);\n }\n}\n</code></pre>\n<p>Again... this might not be the best solution for your current problem, but is the general approach I'd follow for pulling out dependencies in order to facilitate testing of awkward scenarios.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T21:00:17.847",
"Id": "260086",
"ParentId": "256022",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256025",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T19:55:21.953",
"Id": "256022",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"design-patterns",
"unit-testing"
],
"Title": "Replace words from a file with words from a dictionary based file"
}
|
256022
|
<p>I am writing a simple ring buffer for my own education. Below is a crack at a strategy described in <a href="http://www.cse.cuhk.edu.hk/%7Epclee/www/pubs/ancs09poster.pdf" rel="nofollow noreferrer">http://www.cse.cuhk.edu.hk/~pclee/www/pubs/ancs09poster.pdf</a> : Producer and Consumer keep local copies of the write and read indexes on different cache lines and to the extent possible avoid touching the shared versions of the same.</p>
<p>Performance seems to be on par with the boost spspc queue. Any pointers on how to improve this are appreciated. I am using volatile variables rather than std::atomic because, for reasons I do not understand, performance is better with volatile.</p>
<p>Any insight there would be very welcome. I understand that without std::atomic the code might only work on x86_64.</p>
<pre><code>#include <array>
#include <atomic>
#include <limits>
#include <uchar.h>
// Single Producer Single Consumer ring buffer.
// based on http://www.cse.cuhk.edu.hk/~pclee/www/pubs/ancs09poster.pdf
template <class T, size_t MAX_SZ = 10>
class RingBuffer {
static const size_t cache_line = 64;
public:
RingBuffer()
: // Shared control variables
shared_r(0), shared_w(0),
// Consumer state
consumer_w(0), consumer_r(0),
// Producer state
producer_r(0), producer_w(0), uncommited_writes(0) {}
// Called only by the single producer thread
// -----------------------------------------
template <class... ARG>
bool emplace_enqueue_one(ARG &&... arg) {
auto result = emplace_enqueue_batch(std::forward<ARG>(arg)...);
commit_writes();
return result;
}
template <class... ARG>
bool emplace_enqueue_batch(ARG &&... arg) {
// Where would the write position be after we enqueue this element?
size_t next_w = calc_next(producer_w);
// We always keep an empty slot between the read and write
// positions, rather than fill our entire buffer. We do this to
// be able to distinguish between empty (w == r) and full
// (next(w) == r) buffers. Since we are consulting the
// producer's copy of the shared read position (producer_r), not
// the actual read position (shared_r), we might get a false
// positive (that is we might think we are full when we are not)
// but not a false negative (that is we think the queue is not
// full we are right)
if (next_w == producer_r) {
// At this point we might be full. To be sure we need to do
// the more expensive read of the shared read position
// variable
size_t actual_r = get_shared_r();
if (next_w == actual_r) {
// We are indeed full. At this point we might have to
// force a commit so that the consumer can see (and drain)
// uncommited writes.
commit_writes();
return false;
} else
// We are not actually full, update our local copy of the
// read position and carry on.
producer_r = actual_r;
}
// Enqueue
new (&buffer[producer_w]) T(std::forward<ARG>(arg)...);
// Update our copy of the write position but do not actually
// update the shared write position. We leave it up to the
// caller as to when the writes should be visible to the
// consumer. This allows the caller to amortize the expensive
// update fo the shared_w variable over multiple writes.
producer_w = next_w;
uncommited_writes++;
return true;
}
void commit_writes() {
if (uncommited_writes) {
uncommited_writes = 0;
set_shared_w(producer_w);
}
}
// Called only by the single consumer thread
// -----------------------------------------
template <class C>
size_t consume_one(C &&c) {
return consume_(std::forward<C>(c), 1);
}
template <class C>
size_t consume_all(C &&c) {
return consume_(std::forward<C>(c), std::numeric_limits<size_t>::max());
}
private:
template <class C>
size_t consume_(C c, size_t max_consume_count) {
size_t consumed_count = 0;
while (consumed_count < max_consume_count) {
// Could we be empty?
if (consumer_w == consumer_r) {
// We could, but to be sure we have to do the expensive
// read of the shared write position.
size_t actual_w = get_shared_w();
if (consumer_r == actual_w) {
// We are actually empty. If we managed to read
// anything so far then update the shared read
// position.
if (consumed_count)
set_shared_r(consumer_r);
return consumed_count;
} else
// We were not actually empty. Update our copy of the
// write position. We will do the read below.
consumer_w = actual_w;
}
consumed_count++;
c(buffer[consumer_r]);
buffer[consumer_r].~T();
consumer_r = calc_next(consumer_r);
}
// If we reach this point that means we were able to consume
// max_consume_count items, so we need to update the shared_r
// position.
set_shared_r(consumer_r);
return consumed_count;
}
size_t calc_next(size_t p) const {
if (p < (MAX_SZ - 1))
return p + 1;
else
return 0;
}
size_t get_shared_r() { return shared_r; }
void set_shared_r(size_t r) { shared_r = r; }
size_t get_shared_w() { return shared_w; }
void set_shared_w(size_t w) { shared_w = w; }
// cacheline 1 : shared control variables
// read position is known to be larger or equal than this
volatile size_t shared_r;
// write position is known to be larger or equal than this
volatile size_t shared_w;
char padding1[cache_line - 2 * sizeof(size_t)];
// cacheline 2: consumer state
size_t consumer_w; // last known write position (to the consumer)
size_t consumer_r; // current consumer read position
char padding2[cache_line - 2 * sizeof(size_t)];
// cacheline 3: producer state
size_t producer_r; // last known read position (to the producer)
size_t producer_w; // current producer write position
size_t uncommited_writes; // how far ahead is producer_w from shared_w
char padding3[cache_line - 3 * sizeof(size_t)];
// cache line 5: start of actual buffer
std::array<T, MAX_SZ> buffer;
};
</code></pre>
<p>EDIT: In response to feedback I changed the code above to use atomics like this:</p>
<pre><code> size_t get_shared_r() { return shared_r.load(std::memory_order_acquire); }
void set_shared_r(size_t r) { shared_r.store(r, std::memory_order_release); }
size_t get_shared_w() { return shared_w.load(std::memory_order_acquire); }
void set_shared_w(size_t w) { shared_w.store(w, std::memory_order_release); }
</code></pre>
<p>I believe I do not require anything stronger than this (though I could be wrong - I am new to this sort of programming). It is my understanding however, and I have confirmed it by inspecting the generated assembler, that in x86_64, loads always acquire and stores always release. Thus I expected performance to be the same as with the volatile case. Unfortunately this is not the case, the atomic version is roughly twice as slow as the volatile one. I am scratching my head on this one.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:58:47.143",
"Id": "505373",
"Score": "1",
"body": "Wow, I see the paper/poster you linked to using `volatile` too, and I assume that's where you got that terribly misguided idea from. These researchers not understanding basic thread-safety constructs makes me unable to trust a single word they've written. Using modern CPUs (and their various asymmetric cache coherencies) without accounting for [memory order semantics](https://en.cppreference.com/w/cpp/atomic/memory_order) is a recipe for disaster."
}
] |
[
{
"body": "<p>Performance is better with volatile because its unsafe as it doesn't generate a memory barrier and thus has a data race and should not be used in at multi threaded context.</p>\n<p>As such the code is broken for its intended purpose and could be considered of topic for this site. However I will answer, as this is a common fault at heart of many bugs:</p>\n<p><strong><code>volatile</code> does not mean thread safe or atomic!</strong></p>\n<p>Thread safety includes many aspects such as making sure CPU cores see a consistent view of the main memory (e.g. invaliding or updating cache lines cross core) and ensuring that memory operations occur at all (you'd be surprised how much compilers can optimize away, especially clang) and in the right order and atomically. Out of these properties <code>volatile</code> only guarantees order and that the accesses occur. You need memory barriers etc for the rest.</p>\n<p>Volatile only means that the compiler will emit all reads and writes to the variables as written, thus ignoring optimization opportunities and not reordering operations to volatile memory.</p>\n<p><strong>The only reason ever to use volatile is when you're interfacing hardware such as micro controller registers or device drivers.</strong></p>\n<p>I repeat, <code>volatile</code> is almost always wrong AND/OR slow. Unless you're writing drivers or firmware, forget that it ever existed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:25:27.130",
"Id": "505395",
"Score": "0",
"body": "I agree that \"volatile does not mean thread safe or atomic!\" and that most uses of volatile a usually wrong but i think that volatile is useful in a bit more contexts than interacting with hardware. any memory operation that do not need hardware synchronization but is unpredictable for the compiler needs to be volatile. it is also needed when using signal handler and with some uses memory mapping scheems (like multiple pages of virtual memory using the same underlying page in physical memory) and other situation i didn't think about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:06:57.607",
"Id": "505406",
"Score": "0",
"body": "I knew the use of volatile was suspect but I had seen in the paper I referenced and testing/profiling were promising. I am not 100% sure its incorrect in the particular platform I am interested in (x86_64) which has a really strong memory model, but I will definitely establish that before I put this anywhere near production. Thanks for the input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T20:50:33.070",
"Id": "505436",
"Score": "0",
"body": "@Tyker If you ever had to program a device driver for a machine with a DEC Alpha you would know that `volatile` is even useless for interacting with hardware. It still has uses, but I think that in almost all cases, using atomic variables are better. If you know when it is safe to use `volatile` then you probably can probably get the same performance with atomics if you pass the right [memory order](https://en.cppreference.com/w/cpp/atomic/memory_order) parameter to [`load()` and `store()`](https://en.cppreference.com/w/cpp/atomic/atomic/load)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:22:37.923",
"Id": "505515",
"Score": "0",
"body": "@samwise I read the paper and I'm suspicious. They gave no motivation why it would be correct and no mention of verification or checking for correctness in their evaluation. They conveniently omit the mention that they had to use thread affinity to achieve their most prominent result, when the L2 cache is not shared the benefit is seemingly only from the batching..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:29:13.660",
"Id": "505517",
"Score": "0",
"body": "Further they mention that the requirement is that reading control variables is indivisible and they claim that this is generally the case without examples. And unaligned read/writes on x86 are not atomic for example, there's a host of special scenarios that must be considered. They also conveniently ignore the fact that the most likely case this works at all for them is the very convenient memory consistency model on X86(-64). Needless to say, there's a lot of assumptions that need to be just right and it's a literal minefield trying to write code like this..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T23:01:22.283",
"Id": "505521",
"Score": "0",
"body": "Fair enough @Emliy. I made the switch to atomics, lost a little performance, but I will sleep better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T08:30:00.213",
"Id": "505537",
"Score": "0",
"body": "@samwise a favourite saying of mine \"debugging is twice as hard as writing the code in the first place, so if you write code at the top of your ability, you're by definition not smart enough to debug it\" - while one can argue the correctness of whether debugging is twice as hard as coding, there's a point to the saying, don't make your life harder by writing code that will be hard to debug if you can avoid it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T08:39:11.820",
"Id": "505538",
"Score": "0",
"body": "I know you're doing this as an educational experience, so consider this the lesson: 9/10 times, performance is about choosing the right algorithm and not messing up the implementation or by parallelizing. But once in a blue moon you need to go crazy and optimize, or use a fancy non locking data structure, but you should only do that after having explored other, simpler options. Like if you need such thread 2 thread throughout, instead of parallelizing in a pipeline can you let each thread do more of the process and parallelize over the data and avoid the need to hand data over between threads?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T12:37:56.030",
"Id": "505549",
"Score": "0",
"body": "Thanks @Emily but I am only a beginner on lock free programming. I do understand how my domain works and in what cases this type of solution would be appropriate."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T23:42:50.313",
"Id": "256026",
"ParentId": "256023",
"Score": "6"
}
},
{
"body": "<p><code>std::size_t</code> is consistently misspelt throughout the code. It seems your implementation declares <code>size_t</code> as well as <code>std::size_t</code> (which it is allowed to do), but you must not depend on that.</p>\n<p>As Emily says, it's wrong to use <code>volatile</code> where you should use an atomic type.</p>\n<blockquote>\n<pre><code>std::array<T, MAX_SZ> buffer;\n</code></pre>\n</blockquote>\n<p>If <code>T</code> is expensive to construct, then this is a poor choice. You'll need to allocate uninitialized memory and construct in-place as <code>std::vector</code> does. Actually, the logic is all over the place here, because I see that you do construct in-place, but <em>overwrite existing objects</em> without destructing them. That is totally <strong>wrong and dangerous</strong>.</p>\n<blockquote>\n<pre><code>template <class T, std::size_t MAX_SZ = 10>\n</code></pre>\n</blockquote>\n<p>Please use ALL_CAPS naming only for macros. Using for well-behaved C++ identifiers dilutes the warning message that is conveyed by all-caps.</p>\n<blockquote>\n<pre><code> // cacheline 2: consumer state\n std::size_t consumer_w; // last known write position (to the consumer)\n std::size_t consumer_r; // current consumer read position\n char padding2[cache_line - 2 * sizeof(std::size_t)];\n</code></pre>\n</blockquote>\n<p>Rather than counting the size of the variables in the cache line, it is simpler to use an anonymous union:</p>\n<pre><code>// cacheline 2: consumer state\nunion {\n char padding2[cache_line];\n struct {\n std::size_t w = 0; // last known write position (to the consumer)\n std::size_t r = 0; // current consumer read position\n } consumer;\n};\n</code></pre>\n<p>Similarly for the other cache-aligned blocks. Or consider specifying alignment explicitly using <code>alignas()</code>.</p>\n<p>Not sure why we have these private members for simple expressions:</p>\n<blockquote>\n<pre><code> std::size_t get_shared_r();\n void set_shared_r(std::size_t r);\n std::size_t get_shared_w();\n void set_shared_w(std::size_t w);\n</code></pre>\n</blockquote>\n<p>Just write the expressions directly in the code, rather than cluttering the class with these functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:03:16.130",
"Id": "505404",
"Score": "0",
"body": "Thanks you for the input. I agree with the misuse of std::array<T> and I like your union trick. The small helpers were used so I could switch to/from atomics as I profiled."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T08:30:46.910",
"Id": "256037",
"ParentId": "256023",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T20:21:52.410",
"Id": "256023",
"Score": "4",
"Tags": [
"c++",
"performance",
"concurrency"
],
"Title": "Single Producer Single Consumer lockless ring buffer implementation"
}
|
256023
|
<p>It's a cards war game. I'm new to redux and wonder if I use it the correct way, especially when I declare actions in the Game and Main components, and use action's payloads as callbacks to update the state. It feels like a lot code for a small app. Maybe you can help guys and give me some insights, thanks.</p>
<p>store.js:</p>
<pre><code>import { createStore } from "redux";
const state = {
game_ready: false,
cards: [],
player: { name: "", cards: [], points: 0 },
computer: { name: "computer", cards: [], points: 0 },
};
const reducer = (state, action) => {
switch (action.type) {
case "INIT_GAME_CARDS":
return action.payload(state);
case "UPDATE_PLAYER_NAME":
return action.payload(state);
case "SET_GAME_READY":
return action.payload(state);
case "DIST_CARDS":
return action.payload(state);
case "SET_NEXT_CARDS":
return action.payload(state);
case "INCREASE_POINTS":
return action.payload(state);
case "RESET_GAME":
return action.payload(state);
default:
return state;
}
};
const store = createStore(reducer, state);
export default store;
</code></pre>
<p>Main.js:</p>
<pre><code>import React, { useEffect } from "react";
import { Button } from "@material-ui/core";
import { useHistory } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { NUM_OF_CARDS, MAX_CARD_VALUE } from "./constants";
import { shuffle } from "./helpers";
// action creator to initialize the game
const initGameCards = () => ({
type: "INIT_GAME_CARDS",
payload: (state) => {
// creates an array of size 52 filled with 1..13 four times
const cards = Array(NUM_OF_CARDS / MAX_CARD_VALUE)
.fill(
Array(13)
.fill()
.map((_, i) => i + 1)
)
.flat();
// shuffle the cards
shuffle(cards);
return {
...state,
cards,
};
},
});
// action creator to control the player's name
const updatePlayerName = (name) => ({
type: "UPDATE_PLAYER_NAME",
payload: (state) => ({
...state,
player: { ...state.player, name: name },
}),
});
const setGameReady = () => ({
type: "SET_GAME_READY",
payload: (state) => ({
...state,
game_ready: true,
}),
});
function Main() {
const history = useHistory();
const dispatch = useDispatch();
const player = useSelector(({ player }) => player);
// const game_ready = useSelector(({ game_ready }) => game_ready);
const handleClick = React.useCallback(
(e) => {
e.preventDefault();
if (player.name) {
dispatch(setGameReady());
history.replace("./game");
}
},
[dispatch, player.name]
);
useEffect(() => {
dispatch(initGameCards());
}, []);
const handleChange = React.useCallback((e) => {
const target = e.target;
const val = target.value;
switch (target.id) {
case "playerName":
dispatch(updatePlayerName(val));
break;
default:
break;
}
});
return (
<div>
{/* check for valid input */}
<form>
<label htmlFor="playerName">
<h1 className="text-blue-800 text-5xl text-shadow-lg mb-3">
Ready for war
</h1>
</label>
<input
className="border focus:ring-2 focus:outline-none"
id="playerName"
required
onChange={handleChange}
placeholder="Enter your name"
type="text"
value={player.name}
/>
{!player.name ? (
<p className="text-red-700">Please fill the field</p>
) : (
""
)}
<Button
onClick={handleClick}
type="submit"
color="primary"
variant="contained"
>
Start
</Button>
</form>
</div>
);
}
export default Main;
</code></pre>
<p>Game.js:</p>
<pre><code>import { Button } from "@material-ui/core";
import React from "react";
import { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useHistory } from "react-router-dom";
import { NUM_OF_CARDS } from "./constants";
import { shuffle } from "./helpers";
// action creator to distribute the cards at the beginning of the game
const distCards = () => ({
type: "DIST_CARDS",
payload: (state) => {
const cards = [...state.cards];
shuffle(cards);
const computer_cards = cards.slice(0, NUM_OF_CARDS / 2);
const player_cards = cards.slice(NUM_OF_CARDS / 2);
const computer_current_card = computer_cards.pop();
const player_current_card = player_cards.pop();
return {
...state,
cards,
// distributes cards evenly
computer: {
...state.computer,
cards: computer_cards,
current_card: computer_current_card,
points: 0,
},
player: {
...state.player,
cards: player_cards,
current_card: player_current_card,
points: 0,
},
};
},
});
const setNextCards = () => ({
type: "SET_NEXT_CARDS",
payload: (state) => {
let [computer_cards, player_cards] = [
[...state.computer.cards],
[...state.player.cards],
];
const [computer_next_card, player_next_card] = [
computer_cards.pop(),
player_cards.pop(),
];
return {
...state,
player: {
...state.player,
cards: player_cards,
current_card: player_next_card,
},
computer: {
...state.computer,
cards: computer_cards,
current_card: computer_next_card,
},
};
},
});
const pointsIncreament = () => ({
type: "INCREASE_POINTS",
payload: (state) => {
const [player_current_card, computer_current_card] = [
state.player.current_card,
state.computer.current_card,
];
return {
...state,
player: {
...state.player,
points:
player_current_card > computer_current_card
? state.player.points + 1
: state.player.points,
},
computer: {
...state.computer,
points:
player_current_card < computer_current_card
? state.computer.points + 1
: state.computer.points,
},
};
},
});
function Game() {
const player = useSelector(({ player }) => player);
const computer = useSelector(({ computer }) => computer);
const game_ready = useSelector(({ game_ready }) => game_ready);
const dispatch = useDispatch();
const history = useHistory();
const handleReset = React.useCallback(() => {
dispatch(distCards());
}, [dispatch]);
useEffect(() => {
if (game_ready) {
dispatch(distCards());
} else {
history.replace("/");
}
}, [game_ready]);
useEffect(() => {
if (player.current_card && computer.current_card) {
dispatch(pointsIncreament());
}
}, [player.current_card, computer.current_card]);
const handleClick = React.useCallback(() => {
dispatch(setNextCards());
});
return (
<div className="flex justify-center">
<div className="flex flex-col">
<div>
<div>{player.name}</div>
<div>Points: {player.points}</div>
<div>{player.current_card}</div>
</div>
<div>
<div>{computer.current_card}</div>
<div>Points: {computer.points}</div>
<div>{computer.name}</div>
</div>
{!player.cards.length || !computer.cards.length ? (
<Button
onClick={handleReset}
type="submit"
color="primary"
variant="contained"
>
Again?
</Button>
) : (
<Button
onClick={handleClick}
type="submit"
color="primary"
variant="contained"
>
next
</Button>
)}
<div>
{!player.cards.length || !computer.cards.length ? (
player.points === computer.points ? (
<h2>It's a tie</h2>
) : player.points > computer.points ? (
<h2>{player.name} won!</h2>
) : (
<h2>{computer.name} won!</h2>
)
) : (
""
)}
</div>
</div>
</div>
);
}
export default Game;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T07:58:56.513",
"Id": "505365",
"Score": "0",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-24T09:23:31.000",
"Id": "508822",
"Score": "0",
"body": "I'm sorry to say that no, you are not using redux the correct way. [The actions should be plain data objects](https://redux.js.org/style-guide/style-guide#do-not-put-non-serializable-values-in-state-or-actions). The reducer is where you handle applying the changes to state. If you want to be able to create actions and reducers at the same time then the official [Redux Toolkit](https://redux-toolkit.js.org/api/createSlice) has some very helpful tools."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-24T09:31:56.713",
"Id": "508825",
"Score": "0",
"body": "For something like `initGameCards`, you would create the shuffled deck in your action creator function and return an action with a `payload` containing the cards. You want the reducer to always return the same results for a given previous state and actions, so you want to keep random shuffling out of the reducer."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T23:48:43.883",
"Id": "256027",
"Score": "0",
"Tags": [
"react.js",
"redux"
],
"Title": "I'm new to redux and wonder if I use it the correct way"
}
|
256027
|
<p>Please review the code below, which detects discontinuities in Windows system clock in long-running programs.</p>
<pre><code>/*
* Created on Apr 16, 2015
*
* The purpose of this class is to periodically check to see if the time of the Thread.sleep() agrees with the system clock.
* If it does not, we need to send an interrupt to the ***.
*
* This is because after Windows 7, Thread.sleep does not count down in S3 or S4 mode.
* http://stackoverflow.com/questions/29394222/java-thread-sleep-on-windows-10-stops-in-s3-sleep-status
*
*/
package com.sengsational.clockchecker;
import java.io.IOException;
import java.net.Socket;
import java.util.Date;
public class ClockChecker implements Runnable{
private static boolean runFlag = false;
private static Thread runningThread;
private static ClockChecker singleton;
private static Thread runThread;
private static boolean mSimulateClockProblem;
public static long pollIntervalMs = 15000;
public static final int ACCURACY_MS = 1000;
public static ClockChecker getInstance(){
if (singleton == null) {
singleton = new ClockChecker();
}
return singleton;
}
private ClockChecker(){
runningThread = new Thread(this);
runningThread.start();
try {Thread.sleep(100);} catch (Throwable t){};
}
@Override
public void run() {
if (isRunning()) {
System.out.println(new Date() + " ERROR: ClockChecker should only have one run thread.");
return;
} else {
System.out.println(new Date() + " ClockChecker run() is starting.");
setRunning(true);
}
long wakePoint = 0;
long msAccuracy = 0;
ClockChecker.runThread = Thread.currentThread();
while (isRunning()) {
try {
wakePoint = ((new Date().getTime() + pollIntervalMs));
Thread.sleep(pollIntervalMs); // Blocks
if(ClockChecker.mSimulateClockProblem && Math.random() < 0.2d){
wakePoint = wakePoint - 2000;
System.out.println(new Date() + " Simulating a clock problem.");
}
msAccuracy = Math.abs(new Date().getTime() - wakePoint);
if (msAccuracy > ACCURACY_MS) {
System.out.println(new Date() + " ClockChecker has detected a clock accuracy issue of " + msAccuracy + "ms.");
System.out.println(new Date() + " >> Here is where you alert your waiting tasks that depend upon wall-clock accuacy <<");
}
} catch (InterruptedException e) {
System.out.println(new Date() + " ClockChecker run() has been interrupted.");
setRunning(false);
}
}
System.out.println(new Date() + " ClockChecker run() is ending.");
setRunning(false);
}
public synchronized boolean isRunning(){
return runFlag;
}
public synchronized void setRunning(boolean running){
ClockChecker.runFlag = running;
}
private static void setSimulateClockProblem(boolean simulateClockProblem) {
mSimulateClockProblem = simulateClockProblem;
}
public static void shutDown() {
runThread.interrupt();
try {Thread.sleep(100);} catch (Throwable t){}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("\nMAIN: Simulate starting the main app.");
ClockChecker.getInstance();
ClockChecker.setSimulateClockProblem(false); // Set to true on Windows 7 to have a roughly 40% chance of simulating a clock discontinuity.
System.out.println("\nMAIN: Now we have a ClockChecker object. Put Win10 machine into S3 sleep mode NOW!" +
"\n (you have fewer than 30 seconds to do so). Leave in S3 for 1 or more minutes.");
Thread.sleep(30 * 1000);
System.out.println("\nMAIN: Examine the above messages (if any) about clock accuracy after S3 sleep.");
System.out.println("\nMAIN: We will now shutdown.");
ClockChecker.shutDown();
System.out.println(new Date() + " ClockChecker main() ending.");
}
}
</code></pre>
<p>By way of background, when running on Windows versions 8 and 10, but not earlier versions, a Java Thread.sleep(X) will sleep for X milliseconds, <strong>plus the number of milliseconds the machine has been in S3 or S4 sleep</strong>. In other words, when Windows is awake again, it will act as if no time has passed, thus any program requiring a linkage to wall clock time will need a fix. I would like to understand if there are any ideas to improve the above work-around to this problem.</p>
|
[] |
[
{
"body": "<p>Welcome to codereview.se and thanks for sharing your code.</p>\n<p>Here is what I think about it. Please keep in mind, that this is <strong>my personal view</strong> on it.</p>\n<h3>Do not use the Java Singelton pattern.</h3>\n<p>The <em>singelton pattern</em> is just another name for a <em>global variable</em>, which we consider harmful and bad coding since the early days of programming.</p>\n<p>Also the pattern is not that easy to implement correctly and so even your approach is not thread safe.</p>\n<p>For more on this an the static access the <em>singelton pattern</em> requires read: <a href=\"https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/\" rel=\"nofollow noreferrer\">https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/</a></p>\n<h3>Do not do any work in constructors</h3>\n<p>Constructors should only assign its <em>parameters</em> to <em>member variables</em>. Any validation on the parameters should be done before calling the constructor in the first place.</p>\n<p>Also do not instantiate other classes inside the constructor since this is another bad case of <em>static access</em> which makes your code hard to extend, reuse and test.</p>\n<p>Especially the constructor should not pass the the current object to any other method since the object is not fully configured yet until the constructor finished.</p>\n<h3>Do not have top level classes implementing simple (functional) interfaces.</h3>\n<p>This habit vanishes the possibility to separate <em>glue code</em> from the actual business code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T20:27:28.603",
"Id": "256109",
"ParentId": "256029",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T01:53:00.337",
"Id": "256029",
"Score": "2",
"Tags": [
"java",
"windows",
"timer",
"scheduled-tasks"
],
"Title": "Detect discontinuities in Windows clock in Java"
}
|
256029
|
<blockquote>
<p>Using a hash map and vectors, create a text interface to allow a user
to add employee names to a department in a company. For example, “Add
Sally to Engineering” or “Add Amir to Sales.” Then let the user
retrieve a list of all people in a department or all people in the
company by department, sorted alphabetically.</p>
</blockquote>
<p>I implemented a solution for <a href="https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#summary" rel="nofollow noreferrer">the third exercise of Chapter 8 of The Book</a>. I'm still trying to build my intuition for what makes a good Rust program and so would really appreciate some pointers to help me improve. Here's my current solution:</p>
<pre class="lang-rust prettyprint-override"><code>// Using a hash map and vectors, create a text interface to allow a user to
// add employee names to a department in a company. For example, “Add
// Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve
// a list of all people in a department or all people in the company by
// department, sorted alphabetically.
// @todo Add functions to remove people, departments and companies. Add a clear function.
use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::Write;
#[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)]
struct Employee(String);
#[derive(Debug)]
struct Department(HashSet<Employee>);
#[derive(Debug)]
struct Company(HashMap<String, Department>);
fn make_company() -> Company {
Company(HashMap::new())
}
#[derive(Debug)]
struct ExistingDepartment(String);
// This assumes all department names are unique.
fn add_department(company: &mut Company, department: &str) -> Result<(), ExistingDepartment> {
let department_name = String::from(department);
match company.0.contains_key(&department_name) {
true => Err(ExistingDepartment(department_name)),
false => {
company
.0
.insert(department_name, Department(HashSet::<Employee>::new()));
Ok(())
}
}
}
#[derive(Debug)]
enum AddEmployeeError {
NonexistentDepartment(String),
ExistingEmployee(Employee),
}
// This assumes that all employee names in a department are unique.
fn add_employee(
company: &mut Company,
department_name: &str,
employee: Employee,
) -> Result<(), AddEmployeeError> {
match company.0.get_mut(department_name) {
None => Err(AddEmployeeError::NonexistentDepartment(String::from(
department_name,
))),
Some(department) => match department.0.insert(employee.clone()) {
true => Ok(()),
false => Err(AddEmployeeError::ExistingEmployee(employee)),
},
}
}
#[derive(Debug)]
struct NonexistentDepartment(String);
fn get_employees_department(
company: &Company,
department_name: &str,
) -> Result<Vec<Employee>, NonexistentDepartment> {
match company.0.get(department_name) {
None => Err(NonexistentDepartment(String::from(department_name))),
Some(department) => {
let mut result: Vec<Employee> = department.0.iter().cloned().collect();
result.sort_unstable();
Ok(result)
}
}
}
fn get_employees_company(company: &Company) -> Vec<Employee> {
let mut result = company
.0
.keys()
.map(|department| get_employees_department(company, department).unwrap())
.collect::<Vec<Vec<Employee>>>()
.concat();
result.sort_unstable();
result
}
fn format_slice(slice: &[Employee]) -> Option<String> {
match slice.len() {
0 => None,
_ => Some(
slice
.iter()
.map(|employee| employee.0.to_string())
.collect::<Vec<String>>()
.join("\n"),
),
}
}
#[derive(PartialEq)]
enum GetInput {
Print,
Read,
Parse,
}
#[derive(PartialEq)]
enum Mode {
Greet,
GetInput(GetInput),
Quit,
}
struct State {
mode: Mode,
company: Company,
input: String,
}
fn make_state() -> State {
State {
company: make_company(),
mode: Mode::Greet,
input: String::new(),
}
}
fn print_flush(input: &str) -> Result<(), std::io::Error> {
print!("{}", input);
io::stdout().flush()
}
fn read_line(string: &mut String) -> Result<usize, std::io::Error> {
string.clear();
io::stdin().read_line(string)
}
// This assumes that department and employee names don't have whitespace.
fn process_input(state: &mut State) {
let company = &mut state.company;
match state.input.len() {
0 => {
state.mode = Mode::GetInput(GetInput::Print);
}
_ => {
let tokens: Vec<&str> = state.input.split_whitespace().collect();
match tokens.get(0) {
None => {
state.mode = Mode::GetInput(GetInput::Print);
}
Some(token) => match *token {
"quit" => {
println!("Bye for now!");
state.mode = Mode::Quit;
}
command => {
match command {
"add-department" => match tokens[1..].len() {
0 => println!("Command \"{}\" requires at least 1 argument.", command),
_ => tokens[1..].iter().for_each(|element| match add_department(company, element) {
Ok(_) => (),
Err(error) => println!("Error: {:?}", error)
})
},
"add-employee" => match tokens[1..].len() {
0 ..= 1 => println!("Command \"{}\" requires at least 2 arguments.", command),
_ => match company.0.contains_key(tokens[1]) {
true => tokens[2..].iter().for_each(|employee| match add_employee(company, tokens[1], Employee(employee.to_string())) {
Ok(_) => (),
Err(error) => println!("Error: {:?}", error)
}),
false => println!("Department \"{}\" doesn't exist.", tokens[1])
}
},
"get-employees" => match tokens[1..].len() {
0 => println!("Command \"{}\" requires at least 1 argument.", command),
_ => tokens[1..].iter().for_each(|department| match company.0.contains_key(*department) {
true => match format_slice(&get_employees_department(company, department).unwrap()) {
None => println!("Department \"{}\" has no employees.", department),
Some(employees) => println!(
"Employees in \"{}\":
{}", department, employees)
},
false => println!("Department \"{}\" doesn't exist.", department)
})
},
"get-employees-all" => match format_slice(&get_employees_company(company)) {
None => println!("Company has no employees."),
Some(employees) => println!(
"Employees:
{}", employees)
},
"help" => println!(
"Commands:
add-department <department_name [department_name ...]>
Add one or more departments to the company.
add-employee <department_name> <employee_name [employee_name ...]>
Add one or more employees to a department.
get-employees <department_name [department_name ...]>
Print a list of employees from one or more departments.
get-employees-all
Print a list of all employees in the company.
help
Print this message.
quit
Quit."
),
command => {
println!("Invalid command \"{}\".", command);
}
}
state.mode = Mode::GetInput(GetInput::Print);
}
},
}
}
}
}
fn state_machine(state: &mut State) {
match &state.mode {
Mode::Greet => {
println!(
"Database program.
Enter \"help\" for a list of commands."
);
state.mode = Mode::GetInput(GetInput::Print);
}
Mode::GetInput(get_input_step) => match get_input_step {
GetInput::Print => {
println!("Company: {:?}", state.company);
match print_flush("> ") {
Ok(_) => {
state.mode = Mode::GetInput(GetInput::Read);
}
Err(error) => println!("Error {:?}", error),
}
}
GetInput::Read => match read_line(&mut state.input) {
Ok(_) => {
state.mode = Mode::GetInput(GetInput::Parse);
}
Err(error) => println!("Error: {:?}", error),
},
GetInput::Parse => process_input(state),
},
Mode::Quit => (),
}
}
fn repl(function: fn(&mut State), state: &mut State) {
while state.mode != Mode::Quit {
function(state)
}
}
fn main() {
repl(state_machine, &mut make_state())
}
</code></pre>
<p>I previously tried to refactor the <code>process_input</code> function to try to decrease nesting by moving parts of it to different functions, but I ran across borrowing issues so I stopped trying. I also couldn't figure out a nice way to implement it such that it accepts inputs that use the same format as the example (i.e., "Add Amir to Sales"), so I did it a little differently.</p>
<p>I'm also not sure if I'm using the <code>Result</code> type nicely and if the tuple structs and enum I made to pass to them are a good way to do error handling.</p>
<p>I also feel like some of the cloning I did is probably unnecessary, but I'm not sure how I could refactor them away, so it would be nice to know if that is indeed the case and how I might refactor. In fact, I think it would be helpful to know how I might determine when it is appropriate to clone or when to borrow, as I think I'm a little iffy about that topic.</p>
<p>On a related note, how should I go about writing functions? Is it generally better to initially write functions such that they clone their arguments, then try to refactor the cloning away later on, or to try to borrow everything up front then try to fix any borrow-checker issues that crop up and only clone if I can't fix them?</p>
<p>In any case, I'd really appreciate any constructive criticisms and advice.</p>
|
[] |
[
{
"body": "<p>Nice to see you again, nicoty :)</p>\n<h1>Data representation</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)]\nstruct Employee(String);\n#[derive(Debug)]\nstruct Department(HashSet<Employee>);\n#[derive(Debug)]\nstruct Company(HashMap<String, Department>);\n</code></pre>\n<p>Tuple structs should only be used when the meaning of the fields is\nclear, especially when the struct is no more than a thin wrapper\naround an inner value that tweaks certain type-level properties\n— <a href=\"https://doc.rust-lang.org/std/num/struct.Wrapping.html\" rel=\"nofollow noreferrer\"><code>std::num::Wrapping</code></a> and <a href=\"https://doc.rust-lang.org/std/cmp/struct.Reverse.html\" rel=\"nofollow noreferrer\"><code>std::cmp::Reverse</code></a> are\ngood examples. In this case, I would name the fields <code>name</code>,\n<code>employees</code>, and <code>departments</code>, respectively.</p>\n<p><code>Department</code> and <code>Company</code> can have <code>derive(Default)</code>.\nI do not like the fact that <code>Employee</code> implements <code>Ord</code>,\nthough, since names aren't the only logical way to compare employees.\nInstead, I prefer explicitly specifying this order when sorting (via\n<a href=\"https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by_key\" rel=\"nofollow noreferrer\"><code>sort_unstable_by_key</code></a>, among other methods). It's OK to derive\nthem for pragmatic reasons, I guess.</p>\n<h1>Code organization</h1>\n<p>Some of your functions should be made into methods and associated\nfunctions:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>From</th>\n<th>To</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>make_company</code></td>\n<td><code>Company::new</code></td>\n</tr>\n<tr>\n<td><code>add_department</code></td>\n<td><code>Company::add_department</code></td>\n</tr>\n<tr>\n<td><code>add_employee</code></td>\n<td><code>Company::get_department_mut</code> + <code>Department::add_employee</code></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>etc., with ordinary arguments adjusted into <code>self</code> as appropriate.\n<code>Company::new</code>, for example, can be implemented using a <code>Default</code>\nderive:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>impl Company {\n fn new() -> Self {\n Self::default()\n }\n}\n</code></pre>\n<h1>Control flow</h1>\n<blockquote>\n<p>I previously tried to refactor the <code>process_input</code> function to try\nto decrease nesting by moving parts of it to different functions,\nbut I ran across borrowing issues so I stopped trying.</p>\n</blockquote>\n<p>That's unfortunate — separating it into smaller functions is\ndefinitely doable and recommended.</p>\n<p>Overall, your approach here looks complicated — I didn't expect\nto see a state machine. Try a simpler approach. I envision a\n<code>Command</code> struct that parses the first token and dispatches to\ndifferent methods.</p>\n<p>See the rewritten version at the end of this post for inspiration.</p>\n<h1>error handling</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Debug)]\nstruct ExistingDepartment(String);\n</code></pre>\n<p>A full-fledged error type would implement <code>Debug</code>, <code>Display</code>, and\n<code>Error</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::fmt;\n\n#[derive(Debug)]\nstruct ExistingDepartment(String);\n\nimpl fmt::Display for ExistingDepartment {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n format_args!("the department `{:?}` already exists", self.0).fmt(f)\n }\n}\n\nimpl std::error::Error for ExistingDepartment {}\n</code></pre>\n<p>Alternatively, the <a href=\"https://docs.rs/thiserror/1.0.23/thiserror/\" rel=\"nofollow noreferrer\"><code>thiserror</code></a> crate might help. Also, error\ntypes more often come in <code>enum</code>s, like <code>AddEmployeeError</code>:</p>\n<pre><code>use thiserror::Error;\n\n#[derive(Debug, Error)]\nenum AddEmployeeError {\n #[error("the department `{0}` doesn't exist")]\n NonexistentDepartment(String),\n #[error("the employee `{}` already exists", .0.0)]\n ExistingEmployee(Employee),\n}\n</code></pre>\n<p>This is probably an overkill for a simple program.</p>\n<h1><code>HashMap</code> insertion</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>fn add_department(\n company: &mut Company,\n department: &str,\n) -> Result<(), ExistingDepartment> {\n let department_name = String::from(department);\n match company.0.contains_key(&department_name) {\n true => Err(ExistingDepartment(department_name)),\n false => {\n company.0.insert(\n department_name,\n Department(HashSet::<Employee>::new()),\n );\n Ok(())\n }\n }\n}\n</code></pre>\n<p><code>company.0</code> is searched twice — once in <code>contains_key</code>, once in\n<code>insert</code>. The <a href=\"https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html\" rel=\"nofollow noreferrer\"><code>Entry</code></a> interface is the preferred solution:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::collections::hash_map::Entry;\n\nmatch company.0.entry(department_name) {\n Entry::Occupied(entry) => {\n Err(ExistingDepartment(entry.key().to_owned()))\n }\n Entry::Vacant(entry) => {\n entry.insert(Department::new());\n Ok(())\n }\n}\n</code></pre>\n<p>Instead of cloning <code>department</code> within the function, take the argument\nby value so that the caller can pass in values they no longer need.\nIf the insertion fails, ownership can be returned to the caller in the\nerror type. (Unfortunately, the key seems to be discarded if the\nentry is occupied, so I had to use <code>to_owned</code> in that case.)</p>\n<h1>Cloning</h1>\n<blockquote>\n<p>I also feel like some of the cloning I did is probably unnecessary,\nbut I'm not sure how I could refactor them away, so it would be nice\nto know if that is indeed the case and how I might refactor. In\nfact, I think it would be helpful to know how I might determine when\nit is appropriate to clone or when to borrow, as I think I'm a\nlittle iffy about that topic.</p>\n</blockquote>\n<p>In principle, we should clone when it is logically appropriate to do\nso, and avoid cloning otherwise. It all comes down to the semantics.</p>\n<p>In practice, it is OK to occasionally spam <code>.clone()</code> when performance\nis not a big concern — that's what many other languages do\nautomatically under the hood, after all.</p>\n<p>Let's take the two explicit <code>clone</code>s in your code for example:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>// in add_employee\n\nmatch department.0.insert(employee.clone()) {\n true => Ok(()),\n false => Err(AddEmployeeError::ExistingEmployee(employee)),\n}\n</code></pre>\n<p>Here, the <code>clone</code> can be avoided if you use <a href=\"https://doc.rust-lang.org/std/collections/hash_set/struct.HashSet.html#method.replace\" rel=\"nofollow noreferrer\"><code>replace</code></a> instead of\n<code>insert</code>. (In fact, I'm not sure why <code>HashSet::insert</code> returns a\n<code>bool</code> rather than a <code>Result<(), T></code> in the first place.)</p>\n<pre class=\"lang-rust prettyprint-override\"><code>// in get_employees_department\nlet mut result: Vec<Employee> = department.0.iter().cloned().collect();\nresult.sort_unstable();\nOk(result)\n</code></pre>\n<p>In theory, it is possible to work with references instead, where a\n<code>Vec<&Employee></code> is returned. (You can return a reference to the\n<code>Vec</code> of employees, and leave the sorting to the caller, but that\ndoesn't make the issue go away.)</p>\n<blockquote>\n<p>On a related note, how should I go about writing functions? Is it\ngenerally better to initially write functions such that they clone\ntheir arguments, then try to refactor the cloning away later on, or\nto try to borrow everything up front then try to fix any\nborrow-checker issues that crop up and only clone if I can't fix\nthem?</p>\n</blockquote>\n<p>Personally, I generally go with semantics first — cloning and\nborrowing as semantically appropriate. As you gain more experience\nwith Rust memory management, you will feel more comfortable\ntranslating your internal thoughts to code without the borrow checker\nbeing an enemy (from my experience at least).</p>\n<h1><code>flat_map</code></h1>\n<pre class=\"lang-rust prettyprint-override\"><code>fn get_employees_company(company: &Company) -> Vec<Employee> {\n let mut result = company\n .0\n .keys()\n .map(|department| {\n get_employees_department(company, department).unwrap()\n })\n .collect::<Vec<Vec<Employee>>>()\n .concat();\n result.sort_unstable();\n result\n}\n</code></pre>\n<p>You may have realized that using nested <code>Vec</code>s is convoluted and\ninefficient — <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map\" rel=\"nofollow noreferrer\"><code>flat_map</code></a> comes to the rescue.</p>\n<h1>Formatting collections</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>fn format_slice(slice: &[Employee]) -> Option<String> {\n match slice.len() {\n 0 => None,\n _ => Some(\n slice\n .iter()\n .map(|employee| employee.0.to_string())\n .collect::<Vec<String>>()\n .join("\\n"),\n ),\n }\n}\n</code></pre>\n<p><a href=\"https://docs.rs/itertools/0.10.0/itertools/trait.Itertools.html#method.format\" rel=\"nofollow noreferrer\"><code>format</code></a> from the <a href=\"https://docs.rs/itertools/0.10.0/itertools/\" rel=\"nofollow noreferrer\"><code>itertools</code></a> crate simplifies the\nfunction and eliminates unnecessary allocations.</p>\n<p>Checking for empty lists also doesn't seem to belong here.</p>\n<h1><code>use</code> declarations</h1>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::io;\nuse std::io::Write;\n</code></pre>\n<p>You can condense <code>use</code> declarations:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{\n collections::{HashMap, HashSet},\n io::{self, Write},\n};\n</code></pre>\n<p>where <a href=\"https://cheats.rs/#organizing-code\" rel=\"nofollow noreferrer\"><code>self</code></a> (within a path) resolves to the current module.</p>\n<h1>Miscellaneous</h1>\n<blockquote>\n<p>I also couldn't figure out a nice way to implement it such that it\naccepts inputs that use the same format as the example (i.e., "Add\nAmir to Sales"), so I did it a little differently.</p>\n</blockquote>\n<p>That's fine — the formulation of the exercise doesn't seem to\ndictate a particular syntax.</p>\n<blockquote>\n<p>I'm also not sure if I'm using the <code>Result</code> type nicely and if the\ntuple structs and enum I made to pass to them are a good way to do\nerror handling.</p>\n</blockquote>\n<p>See the "Data representation" and "Error handling" sections above.</p>\n<h1>Rewritten version</h1>\n<p>Here's the rewritten version as promised. I made some simplifications for ease of demonstration.\n(External crates used: <a href=\"https://docs.rs/indoc/1.0.3/indoc/\" rel=\"nofollow noreferrer\"><code>indoc</code></a> <a href=\"https://docs.rs/itertools/0.10.0/itertools/\" rel=\"nofollow noreferrer\"><code>itertools</code></a> <a href=\"https://docs.rs/thiserror/1.0.23/thiserror/\" rel=\"nofollow noreferrer\"><code>thiserror</code></a>)</p>\n<p><strong>src/main.rs</strong></p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub mod data;\npub mod repl;\n\nuse repl::Repl;\n\nfn main() {\n Repl::new().run()\n}\n</code></pre>\n<p><strong>src/data.rs</strong></p>\n<pre class=\"lang-rust prettyprint-override\"><code>use {\n itertools::Itertools,\n std::collections::{hash_map, HashMap, HashSet},\n thiserror::Error,\n};\n\n#[derive(Clone, Debug, Default)]\npub struct Company {\n departments: HashMap<String, Department>,\n}\n\nimpl Company {\n pub fn new() -> Self {\n Self::default()\n }\n\n pub fn add_department(&mut self, department: String) -> Result<()> {\n use hash_map::Entry;\n\n match self.departments.entry(department) {\n Entry::Occupied(entry) => {\n Err(Error::ExistingDepartment(entry.key().to_owned()))\n }\n Entry::Vacant(entry) => {\n entry.insert(Department::new());\n Ok(())\n }\n }\n }\n\n pub fn add_employee(\n &mut self,\n department: &str,\n employee: String,\n ) -> Result<()> {\n match self\n .departments\n .get_mut(department)\n .ok_or_else(|| Error::InvalidDepartment(department.to_owned()))?\n .employees\n .replace(employee)\n {\n Some(employee) => Err(Error::ExistingEmployee(employee)),\n None => Ok(()),\n }\n }\n\n pub fn get_departments(&self) -> Vec<String> {\n self.departments.keys().cloned().sorted_unstable().collect()\n }\n\n pub fn get_all_employees(&self) -> Vec<String> {\n self.departments\n .values()\n .flat_map(|department| department.employees.iter().cloned())\n .sorted_unstable()\n .collect()\n }\n\n pub fn get_employees(&self, department: &str) -> Result<Vec<String>> {\n Ok(self\n .departments\n .get(department)\n .ok_or_else(|| Error::InvalidDepartment(department.to_owned()))?\n .employees\n .iter()\n .cloned()\n .sorted_unstable()\n .collect())\n }\n}\n\n#[derive(Clone, Debug, Default)]\npub struct Department {\n employees: HashSet<String>,\n}\n\nimpl Department {\n pub fn new() -> Self {\n Self::default()\n }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n #[error("department `{0}` already exists")]\n ExistingDepartment(String),\n #[error("employee `{0}` already exists")]\n ExistingEmployee(String),\n #[error("invalid department `{0}`")]\n InvalidDepartment(String),\n}\n\ntype Result<T> = std::result::Result<T, Error>;\n</code></pre>\n<p><strong>src/repl.rs</strong></p>\n<pre class=\"lang-rust prettyprint-override\"><code>use {\n crate::data, indoc::indoc, itertools::Itertools, std::ops::RangeInclusive,\n thiserror::Error,\n};\n\n#[derive(Debug, Default)]\npub struct Repl {\n data: data::Company,\n}\n\nimpl Repl {\n pub fn new() -> Self {\n Self::default()\n }\n\n pub fn run(mut self) {\n loop {\n let directive = input("> ");\n let tokens: Vec<&str> = directive.split_whitespace().collect();\n\n let (command, args) = match tokens.split_first() {\n Some((command, args)) => (*command, args),\n None => continue,\n };\n\n let result = match command {\n "add_department" => self.add_department(args),\n "add_employee" => self.add_employee(args),\n "get_departments" => self.get_departments(args),\n "get_employees" => self.get_employees(args),\n "help" => {\n eprint!("\\n{}\\n\\n", HELP_TEXT);\n Ok(())\n }\n "quit" => return,\n _ => Err(Error::InvalidCommand(command.to_owned())),\n };\n\n if let Err(error) = result {\n eprintln!("! Error: {}", error);\n }\n }\n }\n\n fn add_department(&mut self, args: &[&str]) -> Result<()> {\n Self::check_arg_count(args, 1)?;\n\n self.data\n .add_department(args[0].to_owned())\n .map_err(|error| error.into())\n }\n\n fn add_employee(&mut self, args: &[&str]) -> Result<()> {\n Self::check_arg_count(args, 2)?;\n\n self.data\n .add_employee(args[0], args[1].to_owned())\n .map_err(|error| error.into())\n }\n\n fn get_departments(&self, args: &[&str]) -> Result<()> {\n Self::check_arg_count(args, 0)?;\n\n let departments = self.data.get_departments();\n println!("{}", departments.iter().format("\\n"));\n\n Ok(())\n }\n\n fn get_employees(&self, args: &[&str]) -> Result<()> {\n let employees = match &args[..] {\n [] => self.data.get_all_employees(),\n [department] => self.data.get_employees(department)?,\n _ => {\n return Err(Error::ArgumentCountRange {\n expected: 0..=1,\n found: args.len(),\n })\n }\n };\n println!("{}", employees.iter().format("\\n"));\n\n Ok(())\n }\n\n fn check_arg_count(args: &[&str], expected: usize) -> Result<()> {\n let arg_count = args.len();\n\n if arg_count == expected {\n Ok(())\n } else {\n Err(Error::ArgumentCount {\n expected,\n found: arg_count,\n })\n }\n }\n}\n\n#[derive(Debug, Error)]\nenum Error {\n #[error("expected {expected} arguments, found {found}")]\n ArgumentCount { expected: usize, found: usize },\n #[error(\n "expected {} to {} arguments, found {found}",\n .expected.start(), .expected.end(),\n )]\n ArgumentCountRange {\n expected: RangeInclusive<usize>,\n found: usize,\n },\n #[error(transparent)]\n Database(#[from] data::Error),\n #[error("invalid command `{0}`")]\n InvalidCommand(String),\n}\n\ntype Result<T> = std::result::Result<T, Error>;\n\nfn input(prompt: &str) -> String {\n eprint!("{}", prompt);\n\n let mut input = String::new();\n std::io::stdin()\n .read_line(&mut input)\n .expect("cannot read input");\n\n input\n}\n\nconst HELP_TEXT: &str = indoc! { "\n add_department <department_name>\n Add a department to the company.\n\n add_employee <department_name> <employee_name>\n Add an employee to a department.\n\n get_departments\n Print a list of all departments.\n\n get_employees [<department_name>]\n Print a list of all employees or employees from a department.\n\n help\n Print this message.\n\n quit\n Quit.\n" };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T11:53:13.833",
"Id": "256043",
"ParentId": "256030",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T02:33:51.697",
"Id": "256030",
"Score": "1",
"Tags": [
"beginner",
"parsing",
"reinventing-the-wheel",
"console",
"rust"
],
"Title": "Company database REPL program in Rust for Chapter 8 of The Book"
}
|
256030
|
<p>I have written small program in Python which reads the following file and stores the result into a dictionary. I am getting expected output but I think it can be done in a better way. I am using Python 3.</p>
<p>Input</p>
<pre><code>check_name : xa25
not run:
del_l6w_
dl_l4w_
dl_l22w_
de_l3w_
ckt_pw_
ckt_pw_
run:
inv_w_
buf_w_
End
</code></pre>
<p>Code</p>
<pre><code>import collections
def main():
chk_cell = "input.txt"
chk_cell_data = collections.defaultdict(dict)
with open(chk_cell, "r") as fchk_cell:
check_name = ""
not_run_flag = False
run_flag = False
for data in fchk_cell.readlines():
data = data.strip()
if not data:
continue
if data.startswith('check_name'):
data = data.split(":")
check_name = data[1].strip()
continue
elif data.startswith('End') or '-' in data:
check_name = ""
not_run_flag = False
run_flag = False
continue
elif data.startswith('not run'):
chk_cell_data[check_name]['not_run'] = []
not_run_flag = True
continue
elif data.startswith('run'):
chk_cell_data[check_name]['run'] = []
not_run_flag = False
run_flag = True
continue
if not_run_flag:
chk_cell_data[check_name]['not_run'].append(data)
elif run_flag:
chk_cell_data[check_name]['run'].append(data)
print(chk_cell_data)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:02:53.860",
"Id": "505403",
"Score": "0",
"body": "Can you show an example of the output?"
}
] |
[
{
"body": "<h2>Type strength</h2>\n<p>Unless you have a really (really) good reason to use a <code>dict</code> - such as planning to immediately serialize to JSON for some network operation - <code>dict</code> is a poor choice for an internal representation. Use a <code>@dataclass</code>.</p>\n<h2>Parsing strictness</h2>\n<p>You should be a little more strict about your parsing; your current implementation considers</p>\n<pre><code>check_name_for_something_that_makes_no_sense\n</code></pre>\n<p>to be a <code>check_name</code> heading, and a data entry under the <code>run:</code> heading called</p>\n<pre><code>check_name\n</code></pre>\n<p>to be a heading instead of a data entry. Instead, just compare the whole line.</p>\n<p>Your example data do not show any reason for your <code>-</code> check to be there, so I see no reason for it to exist.</p>\n<h2>Parse state</h2>\n<p>Instead of hanging onto flags to remember parse state, you can simply assign a reference to the list currently being populated.</p>\n<h2>Explicit iteration</h2>\n<p>No need to call <code>readlines</code>. Just iterate over the file object itself.</p>\n<h2>Example implementation</h2>\n<pre><code>from dataclasses import dataclass\nfrom typing import TextIO, List\n\n\n@dataclass\nclass RunData:\n name: str\n run: List[str]\n not_run: List[str]\n\n @classmethod\n def from_file(cls, f: TextIO) -> 'RunData':\n run = []\n not_run = []\n current_list = None\n name = None\n\n for line in f:\n line = line.rstrip()\n if line == 'run:':\n current_list = run\n elif line == 'not run:':\n current_list = not_run\n elif line.startswith('check_name :'):\n name = line.split(': ', 1)[1]\n elif line == 'End':\n return cls(name, run, not_run)\n else:\n current_list.append(line)\n\n\ndef main():\n chk_cell = "input.txt"\n with open(chk_cell, "r") as fchk_cell:\n chk_cell_data = RunData.from_file(fchk_cell)\n print(chk_cell_data)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>prints</p>\n<pre><code>RunData(name='xa25', run=['inv_w_', 'buf_w_'], not_run=['del_l6w_', 'dl_l4w_', 'dl_l22w_', 'de_l3w_', 'ckt_pw_', 'ckt_pw_'])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:21:50.657",
"Id": "256053",
"ParentId": "256040",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256053",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T10:50:12.363",
"Id": "256040",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Storing file input into dictionary"
}
|
256040
|
<p>Here's my open source project for testing the latency of gaming computers : <a href="https://github.com/Skewjo/SysLat_Software" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software</a></p>
<p>This software controls the hardware that tests the latency of a gaming computer that can be found at <a href="https://syslat.com/" rel="nofollow noreferrer">https://syslat.com/</a>. The follow up question to this question can be found <a href="https://codereview.stackexchange.com/questions/256063/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-2?noredirect=1&lq=1">here</a>. Since this program is too large to include in a single question here are related questions <a href="https://codereview.stackexchange.com/questions/256149/cleaning-up-usb-implementation-use-syslat-cleanup-3">Cleaning up the USB controller</a> and <a href="https://codereview.stackexchange.com/questions/256151/cleaning-up-static-member-variable-declaration-and-definition">Cleaning up the Main Dialog</a>.</p>
<p>Today I'd like to attempt to clean up my "SysLatData" class.</p>
<p>Header file here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.h" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.h</a><br />
Implementation here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.cpp</a><br />
Definition and use here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp</a></p>
<p>I think the first couple things I need to attack (after a cleanup of typedef and my include guards) are:</p>
<ul>
<li>Moving some functionality out of this class and into the core program (specifically <code>UpdateSLD()</code>) and creating setters.</li>
<li>Moving the export functions into a new static, generic library (specifically <code>CreateJSONSLD()</code> and <code>ExportData()</code>)</li>
<li>Moving the unrelated variables into the core program.(such as <code>m_targetApp</code>, <code>m_RTSSVersion</code>, and <code>m_boxAnchor</code>)</li>
</ul>
<p>But I don't truly know what to do and that's why I'm here!</p>
<pre><code>#pragma once
#ifndef SYSLATDATA_H
#define SYSLATDATA_H
//#define MAX_TESTS 500
#define MOVING_AVERAGE 100
#define EVR_MIN 3
#define EVR_MAX 100
//putting all of this in a struct has got to be unbelievably stupid
typedef struct SYSLAT_DATA {
vector<int> m_allResults;
vector<string> m_v_strRTSSWindow;
vector<string> m_v_strActiveWindow;
int m_counter = 0;
int m_systemLatencyTotal = 0;
double m_systemLatencyAverage = 0;
int m_counterEVR = 0;
int m_systemLatencyTotalEVR = 0; //EVR stands for expected value range
double m_systemLatencyAverageEVR = 0;
int m_a_MovingAverage[MOVING_AVERAGE] = { 0 };//if I end up using a "total tests" var, then this should probably just be split into 2 pointers pointing at the "head" of the totalTests var and head-100 or something...
int m_systemLatencyMedian = 0;
int m_systemLatencyMedianEVR = 0;
int m_systemLatencyMax = 0;
int m_systemLatencyMin = 0;
int m_systemLatencyMaxEVR = 0;
int m_systemLatencyMinEVR = 0;
}SYSLAT_DATA;
class CSysLatData
{
protected:
SYSLAT_DATA sld;
CString m_strSysLatResultsComplete;
HANDLE m_Mutex = NULL;
CString m_strError;
time_t m_startTime, m_endTime;
char m_startDate[26], m_endDate[26];
public:
CSysLatData(); //this constructor only opens a mutex... does the destructor need to close the mutex? Also, do I need to init the struct in the constructor? It should init to all 0's off the bat...
Json::Value jsonSLD; //this is basically a second copy of the data... will probably eat up a BOATLOAD of memory for no reason. There's got to be a better way...
//using getters and setters for all of these seems stupid...
int GetCounter();
int GetTotal();
double GetAverage();
int GetCounterEVR();
int GetTotalEVR();
double GetAverageEVR();
CString GetStringResult();
int GetMedian();
int GetMedianEVR();
int GetMax();
int GetMin();
int GetMaxEVR();
int GetMinEVR();
//int* GetMovingAverage(); //????
string m_targetApp = "Unknown";
string m_RTSSVersion = "0.0.0";
string m_boxAnchor = "Unknown";
struct tm* startTimeUTC;
double m_testDuration;
//double CalculateMovingAverage(); //this function would be for calculating it from scratch...
//double UpdateMovingAverage(); //this function would be used if I'm updating the moving average every time I get a new value
void SetEndTime();
void UpdateSLD(unsigned int loopCounter, const CString& sysLatResults, string RTSSWindow, string activeWindow, DWORD fgPID, DWORD rtssPID);
//mutex functions
void CheckSLDMutex();
BOOL AcquireSLDMutex();
void ReleaseSLDMutex();
void CloseSLDMutex();
void AppendError(const CString& error);
// I think I need to make the following 2 functions return BOOLs or INTs based on whether or not they failed.
void CreateJSONSLD();
void ExportData(int testNumber, string path = ".\\SysLat_Logs", int totalLogs = 10000);
bool dataExported = false;
bool dataUploaded = false;
};
#endif
</code></pre>
<p>Any help you can provide is greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:54:55.437",
"Id": "505388",
"Score": "1",
"body": "It sounds like you already know what can be improved here. You should probably do that first, before asking for a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:56:58.113",
"Id": "505389",
"Score": "0",
"body": "Well, I've included my best guess, but I'm hesitant to attempt to implement it without seeking some kind of review or head nod from... anyone. I guess I can take your comment as that head nod."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:13:43.640",
"Id": "505390",
"Score": "1",
"body": "@TobySpeight is correct it seems like you know what needs to be done. We can't offer advice on what needs to be done, we can only make observations about working code that is already complete. We also need `all of` the code you want reviewed in the question, we can only use linked code repositories as references. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask). One of your options is to break the large class into smaller classes and include those smaller classes in the larger class. [SOLID programming](https://en.wikipedia.org/wiki/SOLID)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:16:19.683",
"Id": "505391",
"Score": "0",
"body": "Don't interpret my comment as a review - just stating that the code should be *finished* to the best of your ability before it's ready for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:18:34.563",
"Id": "505392",
"Score": "0",
"body": "You might want to look at the [Composite Design Pattern](https://en.wikipedia.org/wiki/Composite_pattern)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:42:03.380",
"Id": "505400",
"Score": "0",
"body": "Thanks @pacmaninbw. I'll look into it."
}
] |
[
{
"body": "<h1>Avoid macros</h1>\n<p>You should declare constants as <code>constexpr</code> variables instead of as <code>#define</code>s, like so:</p>\n<pre><code>constexpr std::size_t MOVING_AVERAGE = 100;\n</code></pre>\n<h1>Use <code>std::size_t</code> for sizes, counts and array indices</h1>\n<p>An <code>int</code> might not be large enough to represent all possible sizes of arrays, and negative values don't make sense for sizes and counts either. The proper type is <a href=\"https://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a>.</p>\n<p>If you are not dealing with arrays or loop counters, but just need a variable to count events, you might also use <code>std::size_t</code> for that instead of <code>int</code>, although it might be better to think about how large the number of events might be, and use an <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\">integer type with an explicit size</a>.</p>\n<h1>Use <code>double</code> consistently for latency measurements</h1>\n<p>I recommend you use <code>double</code> for all variables that store latencies, whether it's just a single measurement or an average. You clearly involve <code>double</code>s at some point, and while there might be some overhead of using <code>double</code>s everywhere, you get rid of the overhead of converting between <code>int</code> and <code>double</code>.</p>\n<h1>Be consistent when naming variables</h1>\n<p>You seem to be using <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a> for only a few of the variables, like <code>m_v_strRTSWindow</code> and <code>m_strSysLatResultsComplete</code>, but many of the other variables do not have their types encoded in the name. If you are not doing this consistently, there is no point in using Hungarian notation, and I strongly recommend you stop using it everywhere.</p>\n<p>Furhtermore, you use the <code>m_</code> prefix for member variables almost everywhere, but some variables don't have it, like <code>sld</code>, <code>jsonSLD</code>, <code>startTimeUTC</code>, <code>dataExported</code> and <code>dataUploaded</code>.</p>\n<h1>There is no need to <code>typedef struct</code>s in C++</h1>\n<p>Instead of writing:</p>\n<pre><code>typedef struct SYSLAT_DATA {\n ...\n} SYSLAT_DATA:\n</code></pre>\n<p>You can just write:</p>\n<pre><code>struct SYSLAT_DATA {\n ...\n};\n</code></pre>\n<p>Unlike C, in C++ you can then just use the type <code>SYSLAT_DATA</code> without having to write <code>struct</code> in front of it.</p>\n<h1>Avoid repeating names</h1>\n<p>In <code>struct SYSLAT_DATA</code>, there are many member variables that are named <code>m_systemLatencySomething</code>. Since the <code>struct</code> itself already mentions system latency, you don't have to repeat it. This shortens the variable names considerably.</p>\n<h1>Use <code>std::chrono</code> types for anything time related</h1>\n<p>I see you use various C types for storing time, including <code>time_t</code> and <code>struct tm</code>, and you even have some <code>char</code> arrays to hold dates. Since C++11, there are the excellent <a href=\"https://en.cppreference.com/w/cpp/chrono\" rel=\"nofollow noreferrer\"><code>std::chrono</code></a> facilities of dealing with timepoints and durations. I strongly recommend you start using those consistently.</p>\n<h1>Use <code>std::mutex</code> instead of platform-specific functions</h1>\n<p>Since C++11, <a href=\"https://en.cppreference.com/w/cpp/thread/thread\" rel=\"nofollow noreferrer\">threads</a>, <a href=\"https://en.cppreference.com/w/cpp/thread/mutex\" rel=\"nofollow noreferrer\">mutexes</a> and <a href=\"https://en.cppreference.com/w/cpp/thread\" rel=\"nofollow noreferrer\">other synchronisation primitives</a> have become standardized. I recommend you use the standard functions instead of Windows-specific ones. The types and functions from the STL are much more natural to use in a C++ program, and it will make it easier if you ever want to port your project to other operating systems.</p>\n<p>For example, if you use a <a href=\"https://en.cppreference.com/w/cpp/thread/mutex\" rel=\"nofollow noreferrer\"><code>std::mutex</code></a> for <code>m_Mutex</code>, you don't need a constructor and destructor in <code>class CSysLatData</code> anymore.</p>\n<h1>Who is responsible for locking the mutex?</h1>\n<p>I see you have member functions like <code>AcquireSLDMutex()</code> and <code>ReleaseSLDMutex()</code>. This strongly hints that <code>class CSysLatData</code> itself doesn't lock or release the mutex, but requires other parts of your program to do this. In that case, it is probably more logical to move the mutex out of <code>class CSysLatData</code>, so the <code>class</code> is completely thread-agnostic.</p>\n<h1>Keep your <code>struct</code>s and <code>class</code>es lean</h1>\n<blockquote>\n<p><code>//putting all of this in a struct has got to be unbelievably stupid</code></p>\n</blockquote>\n<p>Probably. What are all these variables for? Do they really need to be all stored? You should only keep those variables that store data that you need later on. Temporary variables used just inside one function most likely do not need to go into a <code>struct</code>,\nand unless there is a performance reason for doing so, you don't need to store anything that can be derived from other variables.</p>\n<h1>Getters and setters</h1>\n<blockquote>\n<p><code>//using getters and setters for all of these seems stupid...</code></p>\n</blockquote>\n<p>Getters and setters have their place, but indeed having to write tens of getters seems silly. In your case, you can replace most getters with a single one that looks like this:</p>\n<pre><code>const SYSLAT_DATA &GetData() {\n return sld;\n}\n</code></pre>\n<p>This returns a <code>const</code> reference to <code>sld</code>. The compiler will enforce that the caller cannot write to <code>sld</code>, only read from it. So instead of the caller writing:</p>\n<pre><code>CSysLatData syslat;\n...\nstd::size_t counter = syslat.GetCounter();\ndouble total = syslat.GetTotal();\n...\n</code></pre>\n<p>It can now write:</p>\n<pre><code>CSysLatData syslat;\n...\nauto &data = syslat.GetData();\nstd::size_t counter = data.m_counter;\ndouble total = data.m_total;\n...\n</code></pre>\n<h1>Duplication of variables in <code>struct SYSLAT_DATA</code></h1>\n<p>Apart from the vectors at the start, there seem to be two copies of each variable, one named <code>m_something</code>, and one named <code>m_somethingEVR</code>. Maybe it makes sense to rewrite it to something like:</p>\n<pre><code>struct SYSLAT_DATA {\n struct Statistics {\n std::size_t counter;\n double total;\n double average;\n double median;\n ...\n };\n\n std::vector<...> ...;\n ...\n\n Statistics m_statistics;\n Statistics m_statisticsEVR;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:08:39.437",
"Id": "505407",
"Score": "0",
"body": "Awesome. Thank you for all of this. I'm going to look through and try to implement most of these and I'll report back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:28:57.813",
"Id": "505409",
"Score": "0",
"body": "Regarding the int vs. double issue... the hardware is currently only able to accurately measure and send values in milliseconds, so until I do operations on multiple measurements I don't need double. Also, I had some speed inconsistency issues with a few operations that I was doing that caused my USB read times to increase when using doubles, so I'm hesitant to move back towards them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T20:41:07.903",
"Id": "505434",
"Score": "0",
"body": "I was able to implement basically all of your suggestions. Thank you. https://github.com/Skewjo/SysLat_Software/commit/662237af6d1529b94015a5ed9e68f72c6c4719b7"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T20:46:49.990",
"Id": "505435",
"Score": "0",
"body": "I'd toss you an upvote, but I don't have that privilege yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T15:51:41.400",
"Id": "505811",
"Score": "0",
"body": "@Skewjo you have enough points to up vote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T16:08:31.657",
"Id": "505812",
"Score": "0",
"body": "Thanks for the reminder @pacmaninbw."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T14:00:11.907",
"Id": "256052",
"ParentId": "256046",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256052",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T12:38:57.013",
"Id": "256046",
"Score": "2",
"Tags": [
"c++",
"embedded"
],
"Title": "Tuning the data class for the SysLat System Latency Testing hardware for gaming computers - SysLat Cleanup #1"
}
|
256046
|
<p>I am trying to write code to determine a win in tic-tac-toe game. In this question, I am not focusing on the whole game, I am only interested in the question of how to determine that the game ended with the victory of one of the players. So I made a synthetic example to test different approaches.</p>
<p>My guess is that a winning line on the board can only appear after the current player has made his move. Therefore, it makes no sense to check all the lines on the board. I only consider those that include the last move made. I assume that the board can be of any size (but only square) and the winning line has the same size. Thus, it is one of the rows, or one of the columns, or one of the two diagonals.</p>
<p>After several attempts, I ended up with the code below:</p>
<pre><code>import java.util.List;
import java.util.function.Predicate;
enum Cell {
X,
O,
B // blank cell
}
public class Board {
private final int size = 3;
private final Cell[][] board;
public Board(Cell[][] board) {
this.board = board;
}
private boolean isLineCompleted(Predicate<Integer> predicate) {
boolean result = true;
int i = 0;
while (result && i < size) {
result = predicate.test(i);
i++;
}
return result;
}
public boolean hasWinningLine(int row, int col) {
if (board[row][col] == Cell.B) return false;
Cell base = board[row][col];
List<Predicate<Integer>> checks = List.of(
i -> board[row][i] == base, //columns
i -> board[i][col] == base, //rows
i -> board[i][i] == base, //top-down diagonal
i -> board[size - i - 1][i] == base //down-top diagonal
);
boolean lineCompleted = false;
for (var check : checks) {
if (!lineCompleted) {
lineCompleted = isLineCompleted(check);
}
}
return lineCompleted;
}
}
</code></pre>
<p>And I wrote some tests that use this code something like this:</p>
<pre><code>Cell[][] xWins = {
{Cell.X, Cell.O, Cell.X},
{Cell.O, Cell.X, Cell.O},
{Cell.X, Cell.B, Cell.B}};
board = new Board(xWins);
AssertTrue(board.hasWinningLine(0, 2));
</code></pre>
<p>I have several questions:</p>
<ol>
<li><p>How easy is this code to read and understand? How can you improve it in this sense?</p>
</li>
<li><p>I try not to make unnecessary checks. The algorithm should return false as soon as it finds an unsuitable cell. Should I handle the loop like this</p>
</li>
</ol>
<pre><code>for (var check : checks) {
if (!lineCompleted) {
lineCompleted = isLineCompleted(check);
} else break; // That's better?
}
</code></pre>
<p>Is it possible to rewrite this loop using a stream API?</p>
<ol start="3">
<li>When checking each line, this code can compare the cell to itself. How can i avoid this without complicating the code? Should I even think about it?</li>
</ol>
<p>I am new to programming and would appreciate any advice that would help me code better.</p>
<p>EDITED:
The predicate checking loop can be rewritten as</p>
<pre><code>return checks.stream()
.map(this::isLineCompleted)
.filter(b -> b == true)
.findFirst()
.orElse(false);
</code></pre>
<p>What are the disadvantages of this approach?</p>
|
[] |
[
{
"body": "<p>First off, considering the small number of lines and items in a line, your (and my following) optimizations are probably not really worth it. That said, as you have noticed, your loops run through all all items, even when not necessary, and that would be bad in more complex situations.</p>\n<p>Generally your code tends to be a bit too complex/verbose. For example, <code>isLineCompleted</code> would be much simpler using a regular <code>for</code> loop and early exit:</p>\n<pre><code>private boolean isLineCompleted(Predicate<Integer> predicate) {\n for (int i = 0; i < size; i++) {\n if (predicate.test(i)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<p>By extracting the <code>checks</code> loop into a separate method, the same pattern could be used there.</p>\n<p>Or Java's <code>Stream</code> has the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#anyMatch-java.util.function.Predicate-\" rel=\"nofollow noreferrer\"><code>.anyMatch()</code></a> method, which simplifies it even more:</p>\n<pre><code>return checks.stream().anyMatch(this::isLineCompleted);\n</code></pre>\n<p>Using a IntStream allows <code>isLineCompleted</code> to do simular using <code>.allMatch()</code>:</p>\n<pre><code>private boolean isLineCompleted(Predicate<Integer> predicate) {\n return IntStream.range(0, size).allMatch(predicate);\n}\n</code></pre>\n<p>One final point: The value <code>B</code> in the <code>Cell</code> enum is badly named considering you need to add the comment "blank cell". Call it <code>BLANK</code> instead. Also it would seem more logical to put it first in the enum, where it would have the cardinal value <code>0</code>. Or you may even want to drop it all together and just use <code>null</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:02:58.747",
"Id": "505472",
"Score": "1",
"body": "`isLineComplete(...)` would need `.allMatch(...)`, not `.anyMatch(...)`, as the existence of just one match does not a complete line make."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:07:26.760",
"Id": "505473",
"Score": "0",
"body": "@AJNeufeld Yes, of course. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:26:32.063",
"Id": "505570",
"Score": "0",
"body": "@RoToRa thanks a lot, it was helpful"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:34:27.567",
"Id": "505574",
"Score": "0",
"body": "@RoToRa \"Or you may even want to drop it all together and just use null.\" -- I try to avoid `null` wherever possible. Many people argue that using the `null` value is bad practice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T15:49:32.163",
"Id": "505588",
"Score": "1",
"body": "Normally I'd agree, but in this case, there are less disadvantages. For example, there are no methods or fields that need to accessed from the instance."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:59:32.880",
"Id": "256085",
"ParentId": "256051",
"Score": "3"
}
},
{
"body": "<h1>Bugs</h1>\n<h2>Board Size</h2>\n<blockquote>\n<p>I assume that the board can be of any size (but only square) ...</p>\n</blockquote>\n<p><code>private final int size = 3;</code></p>\n<p>You mean, the board can be any size as long as it is 3-by-3?</p>\n<p>Perhaps you meant ...</p>\n<pre class=\"lang-java prettyprint-override\"><code> private final int size;\n private final Cell[][] board;\n\n public Board(Cell[][] board) {\n this.board = board;\n this.size = board.length;\n }\n</code></pre>\n<h2>hasWinningLine(row, col)</h2>\n<blockquote>\n<p>I only consider those that include the last move made.</p>\n</blockquote>\n<p>In your test case, <code>board.hasWinningLine(0, 0)</code> would return <code>true</code> despite <code>0, 0</code> not being on a winning line. Your code unconditionally checks the diagonals.</p>\n<p>Instead, your code should only add the diagonal checks if the last move was on those diagonals:</p>\n<pre class=\"lang-java prettyprint-override\"><code> List<Predicate<Integer>> checks = new ArrayList<>();\n checks.add(i -> board[row][i] == base);\n checks.add(i -> board[i][col] == base);\n if (row == col)\n checks.add(i -> board[i][i] == base);\n if (size - row - 1 == col)\n checks.add(i -> board[size - i - 1][i] == base);\n\n ...\n</code></pre>\n<p>Instead of building a temporary list, we could build a stream of predicates directly. For example, using <code>.anyMatch()</code> as suggested in <a href=\"https://codereview.stackexchange.com/a/256085/100620\">RoToRa's answer</a>:</p>\n<pre class=\"lang-java prettyprint-override\"><code> Stream.Builder<Predicate<Integer>> builder = Stream.builder();\n builder.add(i -> board[row][i] == base);\n builder.add(i -> board[i][col] == base);\n if (row == col)\n builder.add(i -> board[i][i] == base);\n if (size - row - 1 == col)\n builder.add(i -> board[size - i - 1][i] == base);\n\n Stream<Predicate<Integer>> stream = builder.build();\n return stream.anyMatch(this::isLineCompleted);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:29:09.443",
"Id": "505572",
"Score": "0",
"body": "\"Instead, your code should only add the diagonal checks if the last move was on those diagonals:\" -- yes, my bad"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:30:41.657",
"Id": "505573",
"Score": "0",
"body": "\"You mean, the board can be any size as long as it is 3-by-3?\" -- I mean, the algorithm is not tied to the board size. It should work at any size. `private final int size = 3` -- just for example. And thank you very much, it was helpful too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:40:34.650",
"Id": "256099",
"ParentId": "256051",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T13:39:10.430",
"Id": "256051",
"Score": "1",
"Tags": [
"java",
"tic-tac-toe"
],
"Title": "Determining winning line in TicTacToe game"
}
|
256051
|
<p>In chapter 3 of <em>Automate the Boring Stuff with Python</em> by Al Sweigart, one exercise asks to write a program which performs the Collatz sequence.</p>
<p>I wrote a basic version first, then added and restructured some of it to account for an invalid input. Any thoughts or criticisms to make it more concise, organized or legible would be appreciated.</p>
<pre><code>def collatz(number): # This evaluates and prints the sequence of numbers.
if number % 2 == 0: # If it's an even number.
print(number // 2)
return number // 2
else: # If it's an odd number.
print(3 * number + 1)
return 3 * number + 1
def main(): # The main loop inside a function so the ValueError message can appear as many times as needed.
try:
user_input = int(input())
while user_input > 1:
user_input = collatz(user_input)
if user_input <= 0: # If a negative integer is entered.
print('Please enter a positive integer.')
else:
print('Enter another integer.')
except ValueError: # If something other than an integer is entered.
print('Please enter a valid integer.')
print('Type any positive integer.') # Main prompt.
while True: # This calls the main loop so you can repeat the equation as many times as needed.
main()
</code></pre>
|
[] |
[
{
"body": "<p>Most of your code deals with obtaining and validating user input. That's\ntedious code to write and maintain. In addition, programs premised on\nuser-interactivity are difficult to execute during development, testing, and\ndebugging: every execution requires a manual dialogue between the user (you,\nthe programmer) and the computer. That get annoying very fast. Moreover, your\nprogram provides no clean way to quit. A more powerful approach based on\ncommand-line arguments and the built-in <code>argparse</code> library is shown below.</p>\n<p>The second issue is that your <code>collatz()</code> function intermixes algorithmic\ncomputation and reporting (i.e. printing). That's almost\nalways a bad idea. A more flexible approach is to restrict <code>collatz()</code> purely to\nthe algorithm and do the printing at a higher level in the program -- either in\n<code>main()</code>, if the reporting remains extremely simple, or in a function called by it.</p>\n<p>The essence of most of these suggestions is to organize your code more\ncarefully to keep different tasks more separated: user input collection; input\nvalidation; computation; and reporting.</p>\n<pre><code>import argparse\nimport sys\n\ndef main(args):\n # Get user arguments.\n opts = parse_args(args)\n\n # Make computations.\n sequences = [list(collatz(val)) for val in opts.initial_values]\n\n # Report to user. Enhance as needed.\n for seq in sequences:\n print(seq)\n\ndef parse_args(args):\n # You want the user to provide one or more integers\n # on the command line. The argparse library will handle that\n # automatically for many use cases (e.g, any integer). In your situation,\n # you do need to write a type validation function, but that process\n # is a bit simpler and more focused than your previous validation\n # code, which was mixed with the rest of the program's logic.\n ap = argparse.ArgumentParser()\n ap.add_argument('initial_values', nargs = '+', type = positive_int)\n return ap.parse_args(args)\n\ndef positive_int(val):\n # You can make this more robust if needed (eg to prevent values like\n # '12.34' from being accepted), but here's the basic technique.\n try:\n n = int(val)\n 1 / n\n return n\n except Exception:\n raise argparse.ArgumentTypeError(f'Invalid positive integer: {val}')\n\ndef collatz(n):\n # Relieved of printing, this function becomes simpler, more testable,\n # and more general purpose.\n while n > 1:\n yield n\n if n % 2 == 0:\n n = n // 2\n else:\n n = 3 * n + 1\n yield n\n\n# Invoke main() if the program was executed rather than imported.\n# This is important for testability, because testing tools need\n# to import your code without executing the script in its entirety.\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T07:50:13.270",
"Id": "505450",
"Score": "0",
"body": "\"code review\" does not mean to write a program but give the user input on his program. How should your program help a user that has written his first python program? Besides that your program contains a lot of things that are really bad, e.g. checking user input with the assert statement.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T08:27:00.753",
"Id": "505453",
"Score": "0",
"body": "@miracle173 I think you misjudge the OP's ability to learn quite a lot from this answer. And your comment implying that using `assert` as a tool for validation is \"bad\" has no basis at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:28:07.347",
"Id": "505516",
"Score": "0",
"body": "Regarding `assert`, there's a discussion on Stack Overflow where the prevailing recommendation is that [asserts should only be used to test conditions that should never happen](https://stackoverflow.com/a/945135) and thus are not appropriate for validating input coming from external sources. From the same discussion, there's also the fact that [`assert` statements are removed when compilation is optimized](https://stackoverflow.com/a/1838411), which could be a big gotcha if you were relying on `assert`s to maintain certain invariants or control program flow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T23:44:57.430",
"Id": "505523",
"Score": "0",
"body": "@Setris I do have a vague recollection of reading that particular StackOverflow question back in the golden age. Most of the discussion strikes me as heavy on dogma (sort of like the narrow view of \"code review\" espoused a few comments up). But you do raise a valid point about optimized compilation. Point taken and code edited – albeit in a slightly sarcastic way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T02:06:37.313",
"Id": "505525",
"Score": "0",
"body": "Thank you all for your help. @FMc There are certain elements of your code I haven't learned yet as I'm an absolute beginner (maybe I shouldn't even be on Code Review at this point) but I appreciate your time and will refer back to it as I learn more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T02:49:53.180",
"Id": "505527",
"Score": "1",
"body": "@astralcheeks You are very welcome. The specific details in my code example are not too important and are easily learned when needed. But keeping different aspects of your program cleanly separated is the key and will serve you very well, both as a beginner and beyond."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T03:41:33.523",
"Id": "256070",
"ParentId": "256054",
"Score": "1"
}
},
{
"body": "<p>Congratulation to your first Python program. As far as I can see it is correct.\nFor comments I obey the following rules:</p>\n<ol>\n<li>comments should be correct and precise and useful</li>\n<li>use as few comments as possible</li>\n</ol>\n<p>The reason for the first rule is that if somebody who reads the code he make wrong assumptions on the code when the comments are wrong. That makes it harder to analyze the code.</p>\n<p>The second rule is a consequence of the first rule. The more comments you have the more incorrect comments you may have. If you modify your code you must modify your comments, too, and check them again. This is unnecessary work and increases the chances of incorrect comments. There is not automatic way to check the comments.</p>\n<p>Lets analyze the program from the highest level using the comments</p>\n<pre><code>def main(): # The main loop inside a function so the ValueError message can appear as many times as needed.\n ...\n\nprint('Type any positive integer.') # Main prompt.\n \nwhile True: # This calls the main loop so you can repeat the equation as many times as needed.\n main()\n</code></pre>\n<p>For me none of these comments obey my rules</p>\n<ul>\n<li><code>def main(): # The main loop inside a function so the ValueError message can appear as many times as needed.</code>: the function <code>main</code> is not a loop, but it is called in the body of a loop. I don't know what you want to say by "the ValueError message can appear as many times as needed." I think if you use a comment like "the user input is requested, checked and if correct a positive integer, the collatz sequence of this number is printed"</li>\n<li><code>print('Type any positive integer.') # Main prompt.</code> I don't know what the meaning of "Main prompt" is, but I see that this statements prints a message to the youuser that he should 'Type any positive integer.' So I think the comment isn't needed here.</li>\n<li><code>while True: # This calls the main loop so you can repeat the equation as many times as needed.</code> I see that this loop calls the function main. If this is what you want to say, it is not necessary to write this down in a comment because this is absolutely clear. This comment is not useful.</li>\n</ul>\n<p>If we go one level deeper we see further comments we see</p>\n<pre><code>def collatz(number): # This evaluates and prints the sequence of numbers.\n</code></pre>\n<p>Is incorrect. The function does not evaluate a sequence of number. It calculates one number and print this one number. So the comment should be something like</p>\n<pre><code># calculates and prints the next Collatz number\n</code></pre>\n<p>I prefer short lines so I would put the comment below the def statement. In this special case one should comment in the following way</p>\n<pre><code>def collatz(number):\n'''calculates and prints the next collatz number'''\n</code></pre>\n<p>according to <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257 -- Docstring Conventions</a>\nThis kind of docstring associates the docstring to Collatz procedure object and some tools can use this fact. e.g. tools that create documentation of code. In this "PEP 257" you may find a lot of other tips how to document the function, like documenting the arguments, the return value and the side effects like printing to the terminal.</p>\n<pre><code>if user_input <= 0: # If a negative integer is entered.\n</code></pre>\n<p>This comment is wrong. The correct formulation is <code># If a negative integer or 0 is entered.</code>. But even the correct is nor really helpful. If the variable name is chosen appropriate the it is clear that user__input holds the user_input. And every programmer knows what "<=0" means. So instead writing an incorrect and unneeded comment remove it.</p>\n<p>But now let's stop with the comments. You can analyze the remaining comments by yourself. From my point of view all of them have problems.</p>\n<p>In your first function</p>\n<pre><code>def collatz(number): \n if number % 2 == 0: # If it's an even number.\n print(number // 2)\n return number // 2\n else: # If it's an odd number.\n print(3 * number + 1)\n return 3 * number + 1\n</code></pre>\n<p>I see that some expression are reused, <code>number // 2</code> and <code>3 * number + 1</code></p>\n<p>Whenever an expression is used more than once I assign it to a variable and use this variable instead. If the expression changes there is only one place where I have to modify it. So I would write</p>\n<pre><code>next_number = number // 2\nprint(next_number)\nreturn next_number\n</code></pre>\n<p>But a second look at this code shows that number is never used after calculating next_number because you call return. So you can use number instead of next_number and get</p>\n<pre><code>number = number // 2\nprint(number)\nreturn number\n</code></pre>\n<p>and the if-block changes to</p>\n<pre><code>if number % 2 == 0: # If it's an even number.\n number = number // 2\n print(number)\n return number\nelse: # If it's an odd number.\n number = 3 * number + 1\n print(number )\n return number \n</code></pre>\n<p>Whenever if have similar code in both branches of an if statement I try to pull this before or after the if statement to redduce the amount of code that must be read and checked. So I prefer</p>\n<pre><code>def collatz(number): \n if number % 2 == 0: # If it's an even number.\n number = number // 2\n else: # If it's an odd number.\n number = 3 * number + 1\n print(number )\n return number \n</code></pre>\n<p>Finally it is always a good idea to separate IO and calculations if this is possible. It is easier to reuse the function that does the calculation, it is easier to test it and it is easier to change the IO behaviour. In this case it is easy to do this. In your code you use the collatz funtion in the follwing way:</p>\n<pre><code>while user_input > 1:\n user_input = collatz(user_input)\n</code></pre>\n<p>Remove the print statement from the collatz function</p>\n<pre><code>def collatz(number): \n if number % 2 == 0: # If it's an even number.\n number = number // 2\n else: # If it's an odd number.\n number = 3 * number + 1\n return number \n</code></pre>\n<p>and change the code to</p>\n<pre><code>while user_input > 1:\n user_input = collatz(user_input)\n print(user_input)\n</code></pre>\n<p>Now you have separated IO and the calculation. If you want to write sequence to a file instead of the terminal, you can change it and do not have to change the collatz function. If you want to calculate the number of iterations that are needed until 1 is reached for a given start value you can use your collatz function without changing it</p>\n<pre><code>cnt=0\nwhile user_input > 1:\n user_input = collatz(user_input)\n cnt+=1\nprint(cnt)\n</code></pre>\n<p>The your initial version of the collatz function would print all numbers taht are calculated to the terminal.</p>\n<p>Naming conventions are proposed in <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a> and I will not discuss them here. But concerning your naming I think <code>user_input</code> is not a goud name for your variable because most of the time and on some places of the program the variable does not contain user input. So I would prefer</p>\n<pre><code>collatz_number=user_input\nwhile collatz_number> 1:\n collatz_number= collatz(collatz_number)\nif collatz_number == 1:\n return\n</code></pre>\n<p>Now let's analyze main.</p>\n<pre><code>try:\n user_input = int(input())\n while user_input > 1:\n user_input = collatz(user_input)\n if user_input <= 0: # If a negative integer is entered.\n print('Please enter a positive integer.')\n else:\n print('Enter another integer.')\n\nexcept ValueError: # If something other than an integer is entered.\n print('Please enter a valid integer.')\n</code></pre>\n<p>If <code>int(input())</code> raise a conversion error because the user entered an invalid string then an error is raised and the user gets the message <code>'Please enter a valid integer.'</code>. That is fine. But the user gets these message even if an error is raised in your collatz function. Of course there will not be such an error in your case as far as I can see. But if the function is more complex this could happen. And if it happens the user will be irritated by a wrong error message on the one hand and on the other hand you will not get an information about where the actual error occurs. So you should restrict the <code>try...except</code> clause to the statements that you really want to guard, so put this clause around the statement containing the input.</p>\n<pre><code>try:\n user_input = int(input())\nexcept ValueError: # If something other than an integer is entered.\n print('Please enter a valid integer.')\n return\nwhile user_input > 1:\n ....\n</code></pre>\n<p>In this block you do two things:</p>\n<ul>\n<li>you check if the user input is correct, that is you check if it is a positive integer number</li>\n<li>you calculate the Collatz sequence, if the input is an integer number greater or equal 2.</li>\n</ul>\n<p>But you mix up these tasks:</p>\n<ul>\n<li>you check if the input is an integer</li>\n<li>if it is an integer greater or equal 2 you print the Colatz sequence of this integer</li>\n<li>then you again check the user input and issue an error if it is negative</li>\n</ul>\n<p>You should not do this. Split these two tasks in two block of consecutive statements. So more clear is the following.</p>\n<pre><code># check user input\ntry:\n user_input = int(input())\nexcept ValueError: # If something other than an integer is entered.\n print('Please enter a valid integer.')\n return\nif user_input <= 0: # If a negative integer is entered.\n print('Please enter a positive integer.')\n return\n\n# print Collatz sequence\nwhile user_input > 1:\n user_input = collatz(user_input)\nprint('Enter another integer.')\nreturn\n</code></pre>\n<p>First check the user input, if it is valid then do the calculations.</p>\n<p>You have three massages to the user that should tell him that he should enter a positive integer:</p>\n<ol>\n<li>'Type any positive integer.'</li>\n<li>'Please enter a valid integer.'</li>\n<li>'Please enter a positive integer.'</li>\n<li>'Enter another integer.'</li>\n</ol>\n<p>They are different an maybe this is intended. But I think this is not necessary, I would replace it yb tthe same text. And therefor I would use a variable for the text. I use upsercase names for the constan according to one of these PEP document:</p>\n<p>INPUT_PROMPT='Please enter a positive integer.'</p>\n<p>and replace the strings by this variable. If one does this, one can remove the "Main Prompt" if one reorders the statement in the procedure main.</p>\n<pre><code># check user input\nprint(INPUT_PROMPT)\ntry:\n user_input = int(input())\nexcept ValueError: # If something other than an integer is entered.\n print(INPUT_PROMPT)\n return\nif user_input <= 0: # If a negative integer is entered.\n print(INPUT_PROMPT)\n return\n\n# print Collatz sequence\nwhile user_input > 1:\n user_input = collatz(user_input)\n# here user_input=1, either because the user entered 1 or the while loop was exited because user_input became 1\nreturn\n</code></pre>\n<p>Both blocks can be put in appropriate functions, and you get the following loop</p>\n<pre><code>while True:\n user_input=get_user_input()\n print_collatz_sequence(user_input)\n</code></pre>\n<p>this make the program more clear and you can test the input-logic and the collatz-sequence calculation independently. Using appropriate function names eliminates the need for comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T15:47:53.637",
"Id": "505587",
"Score": "0",
"body": "This is great and very comprehensive. Thank you for your time and effort; I hadn't even considered how bloated my comments were. I'll revisit my code, make the adjustments and keep these conventions in mind for the future as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T09:52:43.487",
"Id": "256077",
"ParentId": "256054",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T16:36:03.157",
"Id": "256054",
"Score": "6",
"Tags": [
"python",
"beginner",
"collatz-sequence"
],
"Title": "Basic Collatz program with input validation in Python"
}
|
256054
|
<p>I'm embarrassed I spent so much time on this seemingly simple but tricky coding exercise.</p>
<p>The task is this: input is various strings - digits, characters, non-English characters, e.g. some could be Cyrillic. The input must be split into words and then each word must be interpreted numerically if possible.
It should handle actual digits from 1 to 6 as valid numbers. All others should be printed as is.</p>
<p>Valid input includes positive, int or float type numbers 1 to 6, such as the following:</p>
<ul>
<li>1,2,3,4,5,6</li>
<li>+1, +2, ... , +6</li>
<li>1.0, 2.0,... 6.0</li>
<li>any scientific notation that represent numbers 1 to 6.</li>
</ul>
<p>if number is 1 - print "rule1" , 2- "rule2" etc.</p>
<p>Special case is if input number can be interpreted as 0, or any other variation of 0: .0 , 0.0000 or 0.e00. It prints all 6 - "rule1, rule2,.... rule6".</p>
<p><strong>Invalid input</strong> includes negative numbers, they should be printed as-is:
-1 prints '-1', -2 prints -2.</p>
<ul>
<li>any digits in scientific notation that are not in [1 .. 6] should be printed as is.</li>
<li>any single char or string, English and non-English (like dot) is printed as-is; 'nine' is printed 'nine' and "ывъхзъх" is printed "ывъхзъх".</li>
</ul>
<p>Sample input:</p>
<pre class="lang-none prettyprint-override"><code>1.0 03
+5
2.0e0
+.4e1
6.E+00
20e-1 2e1 2ва . 1e-307
</code></pre>
<p>expected output:</p>
<pre class="lang-none prettyprint-override"><code>rule1
rule3
rule5
rule2
rule4
rule6
rule2
2e1
2ва
.
1e-307
</code></pre>
<p>Here is my code. I'm looking to make it more elegant.</p>
<pre><code>from math import modf
import fileinput
rule1 = 'rule1'
rule2 = 'rule2'
rule3 = 'rule3'
rule4 = 'rule4'
rule5 = 'rule5'
rule6 = 'rule6'
def print_rule(n):
if n == 1:
print(rule1)
elif n == 2:
print(rule2)
elif n == 3:
print(rule3)
elif n == 4:
print(rule4)
elif n == 5:
print(rule5)
elif n == 6:
print(rule6)
def print_all():
print(rule1)
print(rule2)
print(rule3)
print(rule4)
print(rule5)
print(rule6)
def get_num(s):
try:
s = int(s)
if s == 0:
print_all()
elif s in [1, 2, 3, 4, 5, 6]:
print_rule(s)
elif s < 1 or s > 6:
print(s)
except ValueError:
try:
saved = s
s = float(s)
if s == 0:
print_all()
elif s < 1 or s > 6:
print(saved)
else:
s = float(s)
s = check_float(s)
if s == 0:
print_all()
elif s in [1, 2, 3, 4, 5, 6]:
print_rule(s)
else:
print(s)
except ValueError:
print(s)
def check_float(n):
frac, _ = modf(n)
if frac != 0:
return n
else:
return n
def test2():
for line in fileinput.input():
line = line.strip().split()
for item in line:
get_num(item)
if __name__ == "__main__":
test2()
</code></pre>
|
[] |
[
{
"body": "<p>Your code for print all and print rule is needlessly verbose. You can convert the float into a integer and fraction part - like you did in <code>check_float</code> but never used. And then just check if the integer is in the bounds and that there is no fraction part.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_rule(number):\n integer, fraction = divmod(number, 0)\n if 1 <= integer <= 6 and not fraction:\n print(f"rule{int(number)}")\n</code></pre>\n<p>Print all can also just be a for loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_all():\n for number in range(1, 7):\n print(f"rule{number}")\n</code></pre>\n<hr />\n<p>The programming challenge is bad. The challenge is just complicated and handling 0 differently to 1-6 is just a gimmick. I'd suggest using a different site, because the challenge is figuring out the challenge is just poorly worded.</p>\n<p>When you get a programming challenge that says "this is ok, this is ok, this is ok" and what is ok is constantly being expanded on then the recommended approach is normally to regex. However we can think of it in a more general way; split the code into three parts:</p>\n<ol>\n<li><p>Extracting raw data.<br />\nYou start with building a means to extract what you need from the input. If the challenge says not to allow something this is a problem for later.\nThis is normally done with regex but sometimes using plain Python can be advantageous.</p>\n</li>\n<li><p>Evaluate the raw data.<br />\nHere we're converting the raw data into something we can use.\nHere this is just using <code>float</code>, but sometimes this can be a bit more hands on.</p>\n</li>\n<li><p>Validate the data.<br />\nHere you're coding the "if number == 0 ...". Since we've parsed the data this makes the code <em>much</em> simpler.</p>\n</li>\n</ol>\n<p>Your code bundles all this together.</p>\n<p>The programming challenge can be reworded to be something far simpler.</p>\n<ul>\n<li><p>Split the input by whitespace into segments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for segment in TEXT.split():\n</code></pre>\n</li>\n<li><p>Evaluate the number from scientific notation; if not possible output the segment.</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n number = float(segment)\nexcept ValueError:\n print(segment)\nelse:\n # ...\n</code></pre>\n</li>\n<li><p>If the evaluated number is 1, 2, 3, 4, 5 or 6 then output "rule{number}".<br />\nIf the evaluated number is 0 output "rule1", "rule2", ... "rule6".</p>\n<pre class=\"lang-py prettyprint-override\"><code>if number in range(0, 7):\n numbers = range(1, 7) if number == 0 else [int(number)]\n for number in numbers:\n print(f"rule{number}")\n</code></pre>\n</li>\n<li><p>Otherwise output the segment.</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(segment)\n</code></pre>\n</li>\n</ul>\n<p>Then the challenge just becomes as simple benign for loop with some horrible conditions. If value is this and value is this and value is this... And ultimately forces you to use the arrow anti-pattern to have clean code. Not a fan.</p>\n<pre class=\"lang-py prettyprint-override\"><code>TEXT = """\\\n1.0 03\n \n +5\n \n 2.0e0\n+.4e1\n6.E+00\n20e-1 2e1 2ва . 1e-307\\\n"""\n\n\ndef main():\n for segment in TEXT.split():\n try:\n number = float(segment)\n except ValueError:\n pass\n else:\n if number in range(0, 7):\n numbers = range(1, 7) if number == 0 else [int(number)]\n for number in numbers:\n print(f"rule{number}")\n continue\n print(segment)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<hr />\n<p>If you think just calling <code>float</code> is cheating then you can manually extract and evaluate the number.</p>\n<p>To extract we should turn to regex. We can build up from the items in the challenge description.</p>\n<ul>\n<li>\n<blockquote>\n<p>1,2,3 ,4,5,6</p>\n</blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>[0-6]\n</code></pre>\n</li>\n<li>\n<blockquote>\n<p>+1, +2, ... +6</p>\n</blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>\\+?[0-6]\n</code></pre>\n</li>\n<li>\n<blockquote>\n<p>1.0, 2.0,... 6.0</p>\n</blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>\\+?[0-6](?:\\.0)?\n</code></pre>\n</li>\n<li>\n<blockquote>\n<p>Negative numbers should simply be printed as-is: -1 prints '-1'</p>\n</blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>[\\-\\+]?[0-6](?:\\.0)?\n</code></pre>\n</li>\n<li>\n<blockquote>\n<p>any scientific notation that represent numbers 1 to 6.</p>\n</blockquote>\n<p>Firstly we now need to accept any digit not just 0 and 0-6, because <code>+.4e1</code> = <code>4</code>.\nAnd the numbers can be any length, <code>.04e2</code> = <code>4</code>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>[\\-\\+]?(?:\\d*\\.\\d*|\\d+)\n</code></pre>\n<p>Then we need to get scientific notation, which is just smacking an e in-between two numbers.</p>\n<pre class=\"lang-none prettyprint-override\"><code>{number}(?:[eE]{number})?\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>[\\-\\+]?(?:\\d*\\.\\d*|\\d+)(?:[eE][\\-\\+]?(?:\\d*\\.\\d*|\\d+))?\n</code></pre>\n</li>\n<li><p>Since we want to check if the segment is completely a number then we can check that the match starts at the start and ends at the end too. Or use <a href=\"https://docs.python.org/3/library/re.html#re.fullmatch\" rel=\"noreferrer\"><code>re.fullmatch</code></a></p>\n<pre class=\"lang-none prettyprint-override\"><code>^[\\-\\+]?(?:\\d*\\.\\d*|\\d+)(?:[eE][\\-\\+]?(?:\\d*\\.\\d*|\\d+))?$\n</code></pre>\n</li>\n</ul>\n<p>Evaluating a number in scientific notation is simple as we split out the base and exponent. We then convert both to floats and then put them in the equation <span class=\"math-container\">\\$b10^e\\$</span>, where b is base and e is exponent. Defaulting the exponent to 0 if it doesn't exist.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def scientific_float(number):\n base, _, exponent = number.partition("e")\n return float(base) * 10**float(exponent or "0")\n</code></pre>\n<p>This automatically handles <code>+\\d</code>, <code>-\\d</code>, <code>.\\d</code> and <code>\\d.</code> if you think this is cheating then you can make your own <code>float</code> function.</p>\n<p>In all this shows the three stages</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\n# Extract\nNUMBER = "[\\-\\+]?(?:\\d*\\.\\d*|\\d+)"\nSCIENTIFIC_NUMBER = f"{NUMBER}(?:[eE]{NUMBER})?"\nNUMBER_MATCHER = re.compile(SCIENTIFIC_NUMBER)\n\n\ndef scientific_float(number): # Evaluate\n base, _, exponent = number.partition("e")\n return float(base) * 10**float(exponent or "0")\n\n\ndef main():\n for segment in TEXT.split(): # Extract\n if None is not (match := NUMBER_MATCHER.fullmatch(segment)): # Extract + Validate\n try:\n number = scientific_float(match.group(0)) # Evaluate\n except ValueError:\n pass\n else:\n if number in range(0, 7):\n numbers = range(1, 7) if number == 0 else [int(number)]\n for number in numbers:\n print(f"rule{number}")\n continue\n print(segment)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T22:06:24.370",
"Id": "505440",
"Score": "0",
"body": "hahah, this print_all is stupid yes"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T21:37:59.333",
"Id": "256061",
"ParentId": "256058",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "256061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T19:11:16.927",
"Id": "256058",
"Score": "6",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Recognise numbers 1 to 6 in various notations"
}
|
256058
|
<p>I am trying to implement <a href="https://play2048.co/" rel="nofollow noreferrer">the game 2048</a> using JavaScript. I am using a two-dimensional array to represent the board. For each row, it is represented using an array of integers.</p>
<p>Here I am focused on implementing the merge left functionality i.e. the merge that happens after the user hits left on their keyboard.</p>
<p>Here are a set of test cases that I came up with</p>
<pre class="lang-js prettyprint-override"><code>const array1 = [2, 2, 2, 0] // [4,2,0,0]
const array2 = [2, 2, 2, 2] // [4,4,0,0]
const array3 = [2, 0, 0, 2] // [4,0,0,0]
const array4 = [2, 2, 4, 16] // [4,4,16,0]
</code></pre>
<p>Here is one workable solution:</p>
<pre class="lang-js prettyprint-override"><code>function mergeLeft(array) {
let startIndex = 0;
for (let endIndex = 1; endIndex < array.length; endIndex++) {
if (array[endIndex] === 0) continue;
let target = array[startIndex];
if (target === 0 || target === array[endIndex]) { // shift or merge
array[startIndex] += array[endIndex];
array[endIndex] = 0;
} else if (startIndex + 1 < endIndex) {
endIndex--; // undo the next for-loop increment
}
if (target !== 0) startIndex++;
}
return array;
}
</code></pre>
<p>This works but there are a lot of if-else checking that makes it hard to extend or adapt to merges in other directions e.g. right, up, down.</p>
<p>Is there a better way to design the algorithm or the function so it can be more easily extensible to other directions? Any other feedback is welcomed!</p>
<p>In addition, I would like to ask a few more questions:</p>
<ol>
<li>If we are going to build this game using a traditional object-oriented way, what are the <code>class</code> we need to design here?</li>
<li>I figured that we can use a 2-dimensional array to represent the board, <strong>or</strong> as one of the answers presented, we can use a 1-dimensional array to hold <code>x,y</code> coordinates, I wonder what are some of the pros and cons with either approach?</li>
<li>I was looking at it from an OOD approach and I was also aware that we can use functional programming instead. Here is my attempt</li>
</ol>
<pre class="lang-js prettyprint-override"><code>const reverse = (array) => [...array].reverse()
const transpose = (grid) => grid[0].map((_, i) => grid.map((r) => r[i]))
const rotateClockwise = (grid) => transpose(reverse(grid))
const rotateCounter = (grid) => reverse(transpose(grid))
// helper functions
const shift = ([n0, n1, ...ns]) =>
n0 == undefined
? []
: n0 == 0
? shift([n1, ...ns])
: n1 == 0
? shift([n0, ...ns])
: n0 == n1
? [n0 + n1, ...shift(ns)]
: [n0, ...shift([n1, ...ns])]
const fillZeros = row =>
row.concat ([0, 0, 0, 0]) .slice (0, 4)
const merge = ([firstItem, secondItem, ...rest]) =>
firstItem == undefined
? []
: firstItem == 0
? merge ([secondItem, ...rest])
: secondItem == 0
? merge ([firstItem, ...rest])
: firstItem == secondItem
? [firstItem + secondItem, ... merge (rest)]
: [firstItem, ...merge ([secondItem, ... rest])]
const mergeRow = (row) =>
merge(row).concat([0, 0, 0, 0]).slice (0, 4)
const mergeLeft = (grid) => grid.map(mergeRow)
const mergeRight = (grid) => grid.map((row) => reverse(mergeRow(reverse(row))))
const mergeUp = (grid) => rotateClockwise(mergeLeft(rotateCounter(grid)))
const mergeDown = (grid) => rotateClockwise(mergeRight(rotateCounter(grid)))
</code></pre>
<p>However I cannot pinpoint exactly which approach i.e. functional programming vs. OOP is better. Can someone give me some concrete benefits for going with either approach?</p>
|
[] |
[
{
"body": "<h2>Review</h2>\n<p>Some review points on your code</p>\n<ul>\n<li><p>Always delimit code blocks with <code>{}</code>. Eg <code>if (target !== 0) startIndex++;</code> is safer as <code>if (target !== 0) { startIndex++; }</code></p>\n</li>\n<li><p>Avoid using <code>continue</code> (Its a goto in disguise). Rather the line <code>if (array[endIndex] === 0) continue;</code> is better as <code>if (array[endIndex]) { /*... loop code ...*/ }</code>. See rewrite.</p>\n</li>\n<li><p>Try to reduce array indexing by storing values in a variable. See rewrite</p>\n</li>\n<li><p><code>0</code> is falsey so <code>if (target !== 0) startIndex++;</code> can be <code>if (target) { startIndex++; }</code> and <code>if (target === 0 || </code> can be <code>if (!target || </code></p>\n</li>\n<li><p>Variables that do not change should be constants. eg <code>let target = array[start];</code> can be <code>const target = array[start];</code></p>\n</li>\n<li><p>Try to keep names short. Long names make code harder to read</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>rewriting your function using the points above.</p>\n<pre><code>\nfunction mergeLeft(row) {\n var start = 0;\n for (let end = 1; end < row.length; end++) {\n const tile = row[end];\n if (tile) {\n const target = row[start];\n if (!target || target === tile ) {\n row[start] += tile ;\n row[end] = 0;\n } else if (start + 1 < end) {\n end--;\n }\n if (target) { start++; }\n }\n }\n return row;\n}\n</code></pre>\n<h2>Coordinate transform</h2>\n<p>Use a single dimension (1D) array to store the game board. The position on the board can be calculated from a coordinate pair. <code>x = 2, y = 1</code> is 3rd column 2nd row. The index in a 1D array is <code>index = x + y * size</code> where <code>size</code> is the number of columns (4 in this case)</p>\n<p>Your merge function moves from left to right, then down (I assume) to the next row and does the same. You can create an inner (columns) and outer (rows) loop, and calculate the board index from the coordinate pairs <code>x,y</code></p>\n<pre><code>\nfor (y = 0; y < 4; y ++) {\n for (x = 0; x < 4; x ++) {\n index = x + y * 4;\n // merge row\n }\n}\n</code></pre>\n<p>The above steps over the arrays in the same direction as your <code>mergeLeft</code> function</p>\n<p>To have it handle different directions you can define some functions that convert (transform) the x, y position to the correct index for the 4 directions. Up, Right, Left, and Down</p>\n<p>For Example</p>\n<pre><code>const size = 4; // width and height of board\nconst tileCount = size * size;\nconst board = new Array(tileCount).fill(0); // Create the array of tiles\n\n// named directions. The name of the key press\nconst moves = {\n up: 0,\n right: 1,\n down: 2,\n left: 3,\n};\n\n// functions that convert x,y position into board index\nconst coordTransform = [\n (x, y) => y + x * size, // up from top down\n (x, y) => (size - 1) - x + y * size, // right for right to left\n (x, y) => y + ((size - 1) - x) * size, // down from bottom up\n (x, y) => x + y * size, // left from left to right\n];\n</code></pre>\n<p>Before merging the rows we get the direction function <code>const move = coordTransform[moves.up];</code></p>\n<p>Then in the loop we use that function to transform the coordinates so that we step over items in the correct direction for the move. <code>const idx = move(x, y);</code> gets the transformed position.</p>\n<p>Example using the above code to merge in any direction.</p>\n<pre><code>// The comments and naming is in terms of rows from left to right. move(moves.left)\n// Call the function with the direction index eg move(moves.up);\nfunction move(dir) { \n // Tiles will stack to the left. \n // left is the idx of the next left free pos\n // prev holds the prev left pos and is used to merge values if same \n var x, y = 0, left, prev;\n\n // get the function to convert coord to board index\n const move = coordTransform[dir]; // transform function for direction\n while (y < size) {\n left = x = 0;\n prev = -1;\n while (x < size) {\n const idx = move(x, y); // Get the tile index using transform function\n const tile = board[idx]; // Get the tile value\n if (tile) { // Does tile have a value\n board[idx] = 0; // Remove the tile from the board\n const idxLeft = move(left, y); // Get next stack pos\n board[idxLeft] = tile; // Set the tile value\n if (prev > -1) { // Is there a tile to left\n if (tile === board[prev]) { // Is tile to left the same\n board[prev] += tile; // Merge the tile values\n board[idxLeft] = 0; // Remove second tile, \n left-- // Move index back \n prev = -1; // Ensure only two merge at a time\n } else { prev = idxLeft } // If tile did not merge remember \n } else { prev = idxLeft } // position of tile\n left ++; // Move stack pos to next tile\n }\n x++; // step to next column\n } \n y++; // step to next row.\n }\n}\n</code></pre>\n<h2>UPDATE Implementing the game.</h2>\n<p>The snippet is an implementation of the game without an in depth study of the original game.</p>\n<p>It uses a partial OO approach</p>\n<blockquote>\n<p><em>"If we are going to build this game using a traditional object-oriented way, what are the class we need to design here?"</em></p>\n</blockquote>\n<h2>Objects used</h2>\n<ul>\n<li><p>Note that JS uses Objects. You should not use the term <code>class</code> due to the significant differences between classes and objects in computer science.</p>\n</li>\n<li><p>I do not use the <code>class</code> syntax due to its very ill though out implementation (incomplete and a syntactical hack)</p>\n</li>\n</ul>\n<p>There is a factory function <code>Game</code> that encapsulates the game, with support code to add the UI for the particular environment (Code review snippet) placed outside <code>Game</code>.</p>\n<p>The <code>Game</code> object uses closure to create private functions and properties. It also reduces the need to add the noisy <code>this.</code> and the even hackier <code>this.#</code></p>\n<p>Within <code>Game</code> is the Object <code>Tile</code> that uses the traditional OO JS prototype object style to implement the display and animation of tiles.</p>\n<p>There are also various simple objects within Game</p>\n<p>. <code>states</code> Holds enumerated game states.\n. <code>moves</code> Holds enumerated game actions (a move is a keyboard (swipe, or mouse, if implemented)) direction to move tiles\n. <code>moveTransform</code> is the transform used to convert 2D tile positions to 1D tile array positions depending on the move direction. (See details in first part of answer)</p>\n<p><strong>Outside the Game object</strong></p>\n<p>The keyboard interface uses a simple static object <code>keys</code> via an immediately invoked factory function (using closure to encapsulate private function) that ensures the will only be one instance of the keyboard interface.</p>\n<h2>Question 2</h2>\n<blockquote>\n<p><em>"I figured that we can use a 2-dimensional array to represent the board, or as one of the answers presented, we can use a 1-dimensional array to hold x,y coordinates, I wonder what are some of the pros and cons with either approach?"</em></p>\n</blockquote>\n<p>The main reason is to reduce complexity. Rather than have to deal with coordinate pairs only a single value is needed to locate a tile. This reduces the complexity .</p>\n<p>This game only has a small number of tiles 16 (though example allows up to 64 (it will handle many more but has be limited in the example to prevent poor performance on low end devices).</p>\n<p>Many games use 2D layouts with 1000s of tiles, using 1D rather than 2D has many advantages</p>\n<ul>\n<li><p>1D arrays reduce the overhead associated with indexing arrays items</p>\n</li>\n<li><p>1D arrays use less memory</p>\n</li>\n<li><p>1D arrays can easily be converted to typed arrays without the need for complex instantiation code. On low end devices a typed array (as a shared array) allows logic in worker threads to share the data.</p>\n</li>\n</ul>\n<h2>Question 3</h2>\n<blockquote>\n<p><em>"I was looking at it from an OOD approach and I was also aware that we can use functional programming instead. Here is my attempt"</em></p>\n</blockquote>\n<p>Functional programming (FP) as a style in JS adds way too much processing and memory overheads to make it a practical for realtime games.</p>\n<p>FP in JS has been adopted as a defense against poor encapsulation that is so common in JS.</p>\n<p>Using a robust encapsulation style there is (in my view) no need to write in FP style in JS</p>\n<p>The example below is written to fit the code review snippet and as such can not use modules.</p>\n<p>Modules add an additional layer of encapsulation to JS code preventing side effects by creating privates scopes per module further reducing the need to use the FP style.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const eCurve = (v, p = 2) => v <= 0 ? 0 : v >= 1 ? 1 : v ** p / (v ** p + (1 - v) ** p);\nconst bellCurve = (v, p = 2) => v <= 0 ? 0 : v >= 1 ? 0 : (v *= 2, (v = v > 1 ? 2 - v : v), v ** p / (v ** p + (1 - v) ** p));\nconst bCurve = (v, a, b) => v <= 0 ? 0 : v >= 1 ? 1 : 3*v*(1-v)*(a*(1-v)+b*v)+v*v*v; // cubic bezier curve\nMath.PI90 = Math.PI / 2;\nMath.TAU = Math.PI * 2;\nMath.PI270 = Math.PI * (3 / 2);\nconst randUI = (min, max) => (max !== undefined ? Math.random() * (max - min) + min : Math.random() * min) | 0;\nconst randPick = arr => arr.splice(randUI(arr.length), 1)[0];\nconst randItem = arr => arr[randUI(arr.length)];\nconst tag = (tag, props = {}) => Object.assign(document.createElement(tag), props);\n\ncanvas.width = innerWidth;\ncanvas.height = innerHeight;\nconst ctx = canvas.getContext(\"2d\");\nconst keys = (()=>{\n const keys = {\n ArrowLeft: false, \n ArrowRight: false, \n ArrowUp: false, \n ArrowDown: false\n };\n document.addEventListener(\"keydown\", keyEvent);\n document.addEventListener(\"keyup\", keyEvent);\n function keyEvent(e) {\n if (keys[e.code] !== undefined) { keys[e.code] = e.type === \"keydown\"; e.preventDefault() }\n }\n return keys;\n})();\nvar pageResized = false, inGame = false, instructionsKnown = 0, gameType = 1;\naddEventListener(\"resize\", () => { if (inGame) { pageResized = true } });\nsel.addEventListener(\"click\", (e) => {\n if (!inGame && e.target.dataset.game !== undefined) {\n gameType = e.target.dataset.game;\n sel.style.display = \"none\";\n playGame(gameType);\n }\n\n});\n\nconst pathRoundBox = (ctx, x, y, w, h, r) => {\n const w2 = w / 2, h2 = h / 2;\n ctx.arc(x - w2 + r, y - h2 + r, r, Math.PI, Math.PI270);\n ctx.arc(x + w2 - r, y - h2 + r, r, Math.PI270, Math.TAU);\n ctx.arc(x + w2 - r, y + h2 - r, r, 0, Math.PI90);\n ctx.arc(x - w2 + r, y + h2 - r, r, Math.PI90, Math.PI);\n}\nfunction Game(size, winTile, speed = 20, tilesPerMove = 2) {\n var state;\n var moveCount = 0, displayDirty = true;\n const animRate = 1 / speed;\n const tileCount = size * size;\n const board = new Array(tileCount).fill(0);\n const mergingTiles = [];\n const freeTiles = [];\n const newTileVal = [];\n const newTileSet = [2,4,2,4,2,4,2,4,2,4,2,4];\n const states = {\n over: 1,\n inPlay: 2,\n animating: 3,\n win: 4,\n };\n state = states.inPlay;\n const moves = {\n up: 0,\n right: 1,\n down: 2,\n left: 3,\n };\n const moveTransform = [\n (x, y) => y + x * size,\n (x, y) => (size - 1) - x + y * size,\n (x, y) => y + ((size - 1) - x) * size,\n (x, y) => x + y * size,\n ];\n function Tile(val, idx, growDelay = 0) {\n this.nx = this.x = idx % size;\n this.ny = this.y = idx / size | 0;\n this.val = val;\n this.anim = 0;\n this.alpha = 1;\n this.animate = true;\n this.merging = false;\n this.grow = true;\n this.size = -growDelay;\n this.flash = false;\n this.flashAlpha = 0;\n }\n Tile.prototype = {\n newPos(idx) {\n this.nx = idx % size;\n this.ny = idx / size | 0;\n this.ax = this.x;\n this.ay = this.y;\n this.anim = 1;\n this.animate = true;\n },\n merge(idx) {\n this.newPos(idx);\n this.merging = true;\n return this;\n },\n mergeFlash(idx) {\n this.animate = true;\n this.flash = true;\n this.flashAlpha = 1;\n this.val *= 2;\n return this;\n },\n update() {\n if (this.merging) {\n this.alpha -= animRate;\n if (this.alpha <= 0) { \n this.alpha = 0;\n this.merging = false;\n } \n }\n if (this.anim > 0) {\n this.anim -= animRate;\n if (this.anim <= 0) { this.anim = 0 }\n }\n if (this.grow) {\n this.size += animRate;\n if (this.size > 1) {\n this.size = 1;\n this.grow = false;\n }\n }\n if (this.flash) {\n this.flashAlpha -= animRate * 2;\n if (this.flashAlpha < 0) {\n this.flashAlpha = 0;\n this.flash = false;\n }\n }\n this.animate = this.flash || this.grow || this.merging || this.anim > 0;\n displayDirty = this.animate ? true : displayDirty;\n if (this.anim > 0) { \n const p = eCurve(1 - this.anim);\n this.x = (this.nx - this.ax) * p + this.ax;\n this.y = (this.ny - this.ay) * p + this.ay;\n } else {\n this.x = this.nx;\n this.y = this.ny;\n }\n },\n render(target) {\n const {ctx, scale, radius, cols, textCol, pad} = target;\n ctx.save()\n const hS = scale / 2;\n var x = this.x * scale;\n var y = this.y * scale;\n const inScale = this.flash ? 1 + bellCurve(this.flashAlpha) * 0.1 : bCurve(this.size, 0, 1.6);\n ctx.transform(inScale, 0, 0 , inScale, x + hS, y + hS);\n ctx.globalAlpha = eCurve(this.alpha);\n ctx.fillStyle = cols[this.val];\n ctx.beginPath();\n pathRoundBox(ctx, 0, 0, scale - pad * 2, scale - pad * 2, radius);\n ctx.fill();\n if (this.flash) {\n ctx.globalCompositeOperation = \"lighter\";\n ctx.globalAlpha = eCurve(this.flashAlpha);\n ctx.fillStyle = \"#FFF\";\n ctx.fill();\n ctx.globalCompositeOperation = \"source-over\";\n ctx.globalAlpha = 1;\n }\n ctx.fillStyle = textCol;\n ctx.fillText(this.val, 0, 0 + scale * 0.05);\n ctx.restore()\n }\n }\n function addTile(growDelay) {\n const pos = randPick(freeTiles);\n if (newTileVal.length === 0) { newTileVal.push(...newTileSet) }\n board[pos] = new Tile(randPick(newTileVal), pos, growDelay);\n }\n function checkBoard() {\n var i = tileCount, s = state;\n freeTiles.length = 0;\n while (i--) {\n const t = board[i];\n if (t?.val === winTile) {\n s = states.win;\n } else if (t === 0) {\n freeTiles.push(i);\n }\n }\n if (freeTiles.length < tilesPerMove && s !== states.win) { s = states.over }\n API.state = s;\n }\n function move(dir) {\n moveCount ++;\n var x, y = 0, f, prev;\n const move = moveTransform[dir];\n while (y < size) {\n f = x = 0;\n prev = -1;\n while (x < size) {\n const idx = move(x, y);\n const tile = board[idx];\n board[idx] = 0;\n if (tile) {\n const idxf = move(f, y);\n board[idxf] = tile;\n idxf !== idx && tile.newPos(idxf);\n if (prev > -1) {\n if (tile.val === board[prev].val) {\n board[prev].mergeFlash();\n mergingTiles.push(tile.merge(prev));\n board[idxf] = 0;\n f--;\n prev = -1;\n } else { prev = idxf }\n } else { prev = idxf }\n f++;\n }\n x++;\n }\n y++;\n }\n }\n const API = {\n states: Object.freeze(states),\n moves: Object.freeze(moves),\n get displayDirty() {\n if (state === states.animating) { displayDirty = true }\n const res = displayDirty;\n displayDirty = false;\n return res;\n },\n get moveCount() { return moveCount },\n get state() { return state },\n set state(s) {\n if (s !== state) {\n if (state === states.animating && s === states.inPlay) {\n state = s;\n checkBoard();\n if (state === states.inPlay) {\n let i = 0\n while (i < tilesPerMove) { addTile(i++ / 2) }\n displayDirty = true;\n }\n } else {\n state = s;\n displayDirty = true;\n }\n }\n },\n set move(dir) {\n if (state === states.inPlay) {\n if (dir >= 0 && dir < 4) {\n move(dir);\n API.state = states.animating;\n }\n }\n },\n reset() {\n board.fill(0);\n API.state = states.animating;\n moveCount = 0;\n checkBoard();\n },\n render(target) {\n var i = 0, tail = 0, animating = false;\n board.forEach(tile => {\n if (tile !== 0) {\n tile.animate && (animating = true, tile.update());\n tile.render(target);\n }\n });\n while (i < mergingTiles.length) {\n const tile = mergingTiles[i];\n tile.update();\n tile.render(target);\n if (tile.animate) {\n animating = true\n mergingTiles[tail++] = tile\n }\n i++;\n }\n mergingTiles.length = tail;\n !animating && state === states.animating && (API.state = states.inPlay);\n },\n }\n return Object.freeze(API);\n}\n\n\nfunction createBGImage(img, tiles, pad, radius) {\n const ctx = img.getContext(\"2d\");\n ctx.fillStyle = \"#222\";\n ctx.beginPath();\n pathRoundBox(ctx, img.width / 2, img.height / 2, img.width, img.height, radius + pad * 2);\n ctx.fill();\n var i = 0;\n const size = img.width / tiles;\n ctx.fillStyle = \"#666\";\n while (i < tiles * tiles) {\n const x = (i % tiles) + 0.5;\n const y = (i / tiles | 0) + 0.5;\n ctx.beginPath();\n pathRoundBox(ctx, x * size, y * size, size - pad * 2, size - pad * 2, radius);\n ctx.fill();\n i++;\n }\n return img;\n} \n\n\nfunction playGame(game = gameType) {\n inGame = true;\n const GAMES = [\n [4, 512, 20, 2],\n [5, 2048, 20, 2],\n [6, 2048, 20, 2],\n [7, 1024, 20, 3],\n [8, 2048, 16, 4],\n ];\n const SIZE = GAMES[game][0];\n const g = Game(...GAMES[game]);\n g.reset();\n ctx.canvas.width = innerWidth;\n ctx.canvas.height = innerHeight;\n requestAnimationFrame(animLoop);\n const minRes = Math.min(ctx.canvas.width, ctx.canvas.height);\n const unit = minRes / 64;\n const RADIUS = minRes / SIZE / 8, PAD = minRes / SIZE / 16;\n const bgImage = createBGImage(tag(\"canvas\", {width: minRes, height: minRes}), SIZE, PAD / 2, RADIUS + PAD / 2);\n const renderTarget = {\n ctx,\n scale: minRes / SIZE,\n radius: RADIUS,\n pad: PAD,\n textCol: \"#000\",\n cols: {\n [2]: \"#F40\",\n [4]: \"#F80\",\n [8]: \"#FA0\",\n [16]: \"#FC0\",\n [32]: \"#FF0\",\n [64]: \"#CF0\",\n [128]: \"#8F0\",\n [256]: \"#0F0\",\n [512]: \"#0F8\",\n [1024]: \"#0FF\",\n [2048]: \"#FFF\",\n } \n }\n ctx.font = (renderTarget.scale * 0.7 | 0) + \"px Arial\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\";\n function animLoop() {\n var m = -1;\n\n // Rather than dynamic resize this just restarts on resize\n if (pageResized) {\n pageResized = false;\n setTimeout(playGame, 0);\n inGame = false;\n return;\n }\n if (keys.ArrowUp) { keys.ArrowUp = false; m = g.moves.up }\n if (keys.ArrowRight) { keys.ArrowRight = false; m = g.moves.right }\n if (keys.ArrowDown) { keys.ArrowDown = false; m = g.moves.down }\n if (keys.ArrowLeft) { keys.ArrowLeft = false; m = g.moves.left }\n \n if (m > -1) { \n g.move = m; \n instructionsKnown++;\n }\n const state = g.state;\n if (g.displayDirty) {\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\";\n ctx.setTransform(1,0,0,1,0,0);\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n ctx.font = (renderTarget.scale * 0.45 | 0) + \"px Arial\";\n ctx.setTransform(1,0,0,1,(canvas.width - SIZE * renderTarget.scale) / 2, 0);\n ctx.drawImage(bgImage, 0, 0);\n g.render(renderTarget);\n if (!(state === g.states.inPlay || state === g.states.animating)) {\n ctx.fillStyle = \"#0008\";\n ctx.setTransform(1,0,0,1,0,0);\n ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n ctx.font = (renderTarget.scale * 0.7 | 0) + \"px Arial\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\"; \n ctx.fillStyle = \"#FFF\";\n ctx.strokeStyle = \"#000\";\n ctx.lineWidth = unit * 2;\n ctx.lineJoin = \"round\";\n const cx = ctx.canvas.width * 0.5;\n const cy = ctx.canvas.height * 0.3\n if (state === g.states.win) {\n ctx.strokeText(\"WINNER!\", cx + unit / 2, cy + unit / 2);\n ctx.fillText(\"WINNER!\",cx, cy)\n ctx.strokeStyle = \"#FED\";\n ctx.lineWidth = unit / 2;\n ctx.lineJoin = \"round\";\n ctx.strokeText(\"WINNER!\", cx, cy)\n ctx.font = (renderTarget.scale * 0.4 | 0) + \"px Arial\";\n ctx.fillStyle = \"#FFF\";\n ctx.strokeStyle = \"#000\";\n ctx.lineWidth = unit;\n const mC = g.moveCount;\n ctx.strokeText(\"Moves: \" + mC, cx + unit / 4, cy + unit * SIZE * 3 + unit / 4);\n ctx.fillText(\"Moves: \" + mC, cx, cy + unit * SIZE * 3);\n \n } else {\n ctx.strokeText(\"GAME OVER\", cx + unit / 2, cy + unit / 2);\n ctx.fillText(\"GAME OVER\", cx, cy)\n ctx.strokeStyle = \"#DEF\";\n ctx.lineWidth = unit / 2;\n ctx.lineJoin = \"round\";\n ctx.strokeText(\"GAME OVER\", cx, cy);\n }\n\n inGame = false;\n return;\n } \n if (instructionsKnown < 2) {\n ctx.setTransform(1,0,0,1,0,0);\n ctx.fillStyle = \"#FFF\";\n ctx.font = \"16px Arial\";\n ctx.fillText(\"Use arrow keys to play\", ctx.canvas.width / 2, 20);\n } \n }\n requestAnimationFrame(animLoop);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas {\n position: absolute;\n top: 0px;\n left: 0px;\n pointer-events: none;\n}\n#sel {\n font-family: arial;\n display: flex;\n}\n.bt {\n flex-wrap: row;\n cursor: pointer;\n width: 50px;\n text-align: center;\n border: 1px solid black;\n margin: 4px;\n padding-top: 3px;\n}\n.bt:hover {\n background: #D92;\n}\n.txt {\n margin-top: 8px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\"></canvas>\n<div id=\"sel\">\n <div class=\"txt\">Select grid size:</div>\n <div class=\"bt\" data-game=\"0\">4 by 4</div>\n <div class=\"bt\" data-game=\"1\">5 by 5</div>\n <div class=\"bt\" data-game=\"2\">6 by 6</div>\n <div class=\"bt\" data-game=\"3\">7 by 7</div>\n <div class=\"bt\" data-game=\"4\">8 by 8</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><sub><strong>Note</strong> Code review pages use a lot of JS and as such impact the performance of snippets. To get a true feel of how the game plays copy the code to a stand alone page..</sub></p>\n<p><sub><strong>Note</strong> as there is a limit to code review answer size the above was coded to fit and as such lost a lot of code and reduced naming length to fit.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:51:43.323",
"Id": "506703",
"Score": "0",
"body": "Hey thanks for the reply. I understand that JS uses objects but it doesn't prevent people from thinking in terms of OO I think. Granted JS's class is not exactly the same as Java or C++'s class, but I think it is still possible to implement the OO paradigm in JS. I am very curious about this particular advantage of using 1d array - \"1D arrays can easily be converted to typed arrays without the need for complex instantiation code. \" Could you elaborate more on this? I guess by typed array you meant something like \"a float32array to allocate a fixed-length contiguous memory area\" right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:15:51.687",
"Id": "506706",
"Score": "0",
"body": "@Joji Yes Float32Array is one if the typed arrays. Fixed length and only 1D. Typed arrays can be transferred to webworkers using zero copy transfer and can be shared between threads via shared array. I did not say OO was not possible in JS just that the convention is not to call objects classes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:22:11.550",
"Id": "506707",
"Score": "0",
"body": "Thanks for the reply. maybe I am just not familiar with web worker. do we have to convert normal arrays to typed arrays if we need to transfer them from the main thread to any worker thread?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:26:56.737",
"Id": "506708",
"Score": "0",
"body": "@Joji Normal arrays need to be copied, You can not use zero copy transfer on normal arrays"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T03:50:45.610",
"Id": "506739",
"Score": "0",
"body": "+1 for the full-fledged game, that was great :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T00:10:05.257",
"Id": "256065",
"ParentId": "256060",
"Score": "3"
}
},
{
"body": "<p>One way to simplify your code a lot is to generate a new board in your <code>mergeLeft()</code> function, instead of trying to modify it in place. It opens up room to use other techniques that would greatly simplify the logic in your function, like, popping results from the source array as you work with them, or filtering out zeros.</p>\n<p>An example of how you might implemented it in this format:</p>\n<pre><code>const peek = array => array[array.length - 1];\n\nfunction mergeRowRight(sparseRow) {\n const row = sparseRow.filter(x => x !== 0);\n const result = [];\n while (row.length) {\n let value = row.pop();\n if (peek(row) === value) value += row.pop();\n result.unshift(value);\n }\n\n while (result.length < 4) result.unshift(0);\n return result;\n}\n</code></pre>\n<p>I see no reason to need to generalize that algorithm to work in all directions. Instead, you can derive the other directions from your original mergeLeft() function, it just takes some reversing and zipping (I'm using zip() in this scenario to flip the board along its diagonal, but a function like this has many other uses).</p>\n<p>Here's how you might derive the different directions from mergeRowRight().</p>\n<pre><code>function zip(arrays) {\n const result = [];\n for (let i = 0; i < arrays[0].length; ++i) {\n result.push(arrays.map(array => array[i]));\n }\n return result;\n}\n\nconst mergeRowLeft = row => mergeRowRight([...row].reverse()).reverse();\n\nconst mergeRight = board => board.map(mergeRowRight);\nconst mergeLeft = board => board.map(mergeRowLeft);\nconst mergeUp = board => zip(zip(board).map(mergeRowLeft));\nconst mergeDown = board => zip(zip(board).map(mergeRowRight));\n</code></pre>\n<h2>Update: Responses to additional questions that the O.P. added</h2>\n<p><strong>I was looking at it from an OOD approach and I was also aware that we can use functional programming instead. However, I cannot pinpoint exactly which approach i.e. functional programming vs. OOP is better. Can someone give me some concrete benefits for going with either approach?</strong></p>\n<p>I wouldn't really call your initial attempt "object-oriented" - you don't have any classes, private data, encapsulation, etc. It looks more like procedural programming - it's a list of instructions that can be followed step by step to achieve the desired outcome. OOP tries to organize logic into different classes of objects while functional programming tries to organize logic into modules and functions. These strengths of the different paradigms tailor to different types of problems being solved. For example:</p>\n<ul>\n<li>If your problem is largely algorithmic in nature (like this one), then functional programming will really shine. Functional programming does a really good job at subdividing an algorithm into smaller parts and organizing the pieces in an easy-to-understand fashion.</li>\n<li>If your problem contains a lot of interaction between discrete objects (like characters and enemies in a game), Object-oriented programming will really shine. Object-oriented programming provides useful facilities to encapsulate the details of how the objects operate and let them interact with each other by only using well-defined interfaces.</li>\n</ul>\n<p>It's good to remember that these paradigms are <em>not</em> mutually exclusive. You can use aspects of both object-oriented and functional programming at the same time. For example, OOP tells you how to structure an entire project, and how the components of that project will interact with each other. But, it doesn't have as much to say on how to structure the logic inside individual methods. You'll find many people writing methods in a more imperative style (similar to your original solution and parts of mine), and many other people reaching for concepts from functional programming to create their methods.</p>\n<p>To answer the actual question here: the problem being presented is entirely algorithmic in nature, therefore, you'll find that the tools that functional programming provides will tend to do a good job of describing the problem in an elegant way. I would much prefer your functional version of the code over your procedural version (once it's cleaned up a bit. You have a couple of unused functions in there, etc).</p>\n<p><strong>If we are going to build this game using a traditional object-oriented way, what are the class we need to design here?</strong></p>\n<p>One of the biggest benefits of OOP is encapsulation. We hide away the implementation details of bits of logic into different classes and only refer to those logical chunks by the interfaces the classes provide. There really isn't a good way to split up the logic behind an algorithm between multiple classes - splitting up the algorithm that way would be unnatural, and much more difficult to understand.</p>\n<p>If you're trying to do this in an OOP way, the most likely scenario is that you would already have classes, such as a class for the 4x4 grid, and this entire algorithm would simply be one function (and maybe some helpers) on that class. Your algorithm wouldn't get smeared across multiple classes. In other words, you'll have to look at the bigger picture of your project to figure out a good class structure. If we look at the algorithm alone, then we're too zoomed in to make any good decisions about what classes should exist.</p>\n<p><strong>I figured that we can use a 2-dimensional array to represent the board, or as one of the answers presented, we can use a 1-dimensional array to hold x,y coordinates, I wonder what are some of the pros and cons with either approach?</strong></p>\n<p>Maybe @Blindman67 will speak for themself as to why they preferred a one-dimensional array, so you can get a less-bias answer to this, but here are my thoughts: I will first note that it doesn't look like their array was holding x,y coordinates, rather, they were just smearing a 2d array into a 1d array, i.e. instead of storing <code>[[4, 2], [16, 8]]</code> they were storing <code>[4, 2, 16, 8]</code> and using some extra math to turn an x, y coordinate into a single index in that 1d array.</p>\n<p>From the looks of it, this data structure was probably done because it made their particular approach to the algorithm easier. However, even that approach could have been done with a 2d-array, if their coordTransform functions returned a coordinate pair instead of a single index, and the consumers of the coordTransform functions were adapted appropriately. This approach could also have been chosen because there (might) be a slight speed improvement to it, but, please don't ever purposely uglify your code for negligible speed improvements and potentially extra buggy code. I would recommend just sticking with a 2d-array - it's a more natural data representation for this problem, it will be easier for other functions to consume this data structure, and it's easier for other programmers to understand as its a less tricky solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T00:20:27.370",
"Id": "506536",
"Score": "0",
"body": "Hi thanks for the reply. Your solution definitely works. But I wonder why you said that \"generate a new board\" is better than mutating it. Like can you give me an example where mutating doesn't work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T06:17:40.750",
"Id": "506641",
"Score": "1",
"body": "When I mentioned that, I was mostly referring to the general idea that it's often easier to follow what code is doing when its values don't mutate very often. This sentiment comes more from a functional mindset, but can be used in any paradigm. You can find plenty of content on the internet to learn more about this idea. As for an example where mutating doesn't work - both ways are equally powerful, though some things are easier in some styles. For example, I wanted to use .filter() to remove zeros, but .filter() doesn't mutate, so my code already had to be non-mutating to a degree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:15:59.933",
"Id": "506810",
"Score": "0",
"body": "hey thanks for the reply. as you said the original problem was more like an algorithmic question. However, if we were trying to build this game, including the logic to determine if the player wins or not, and the logic to spawn the game board, how would you go about designing the class? would you make one class for it or we need to make multiple classes for it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:01:42.597",
"Id": "506822",
"Score": "1",
"body": "I feel like I need to open up a new question for it. could you please take a look at this https://codereview.stackexchange.com/questions/256691/javascript-ood-2048"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T06:25:45.133",
"Id": "256073",
"ParentId": "256060",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T21:03:12.370",
"Id": "256060",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"object-oriented",
"game",
"2048"
],
"Title": "implement the merge functionality for 2048 with JavaScript"
}
|
256060
|
<p>This is a follow up question to <a href="https://codereview.stackexchange.com/questions/256046/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-1">Tuning the data class for the SysLat System Latency Testing hardware for gaming computers - SysLat Cleanup #1</a>.</p>
<p>Since the program is too large and complex to put into one question I have also posted a question about the <a href="https://codereview.stackexchange.com/questions/256149/cleaning-up-usb-implementation-use-syslat-cleanup-3">USB controller</a> and the <a href="https://codereview.stackexchange.com/questions/256151/cleaning-up-static-member-variable-declaration-and-definition">dialog that controls the entire program</a>.</p>
<p>Here's my open source project: <a href="https://github.com/Skewjo/SysLat_Software" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software</a></p>
<p>Today I'm attempting to clean up my "SysLatData" class, and the effort has <a href="https://codereview.stackexchange.com/questions/256046/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-1/256052#256052">gone very well so far</a>, and I'm looking to pretty well finalize it now if possible.</p>
<p>Header file here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.h" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.h</a>
Implementation here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.cpp</a>
Definition and use here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp</a></p>
<pre><code>#pragma once
//Without the following 2 macros the date library spits out 50+ errors about min and max being undefined.
#undef max
#undef min
#include <date/date.h> //Should likely move this to StdAfx.h, but I'm not sure if I can because of the macro issue.
using namespace date;
using namespace std::chrono;
constexpr size_t MOVING_AVERAGE = 100;
constexpr size_t EVR_MIN = 3;
constexpr size_t EVR_MAX = 100;
struct SYSLAT_DATA {
struct Statistics {
std::size_t counter = 0;
int total = 0;
double average = 0.0;
int median = 0;
int max = 0;
int min = 0;
double approxMovingAvg = 0.0;
};
vector<int> m_allResults;
vector<string> m_v_strRTSSWindow;
vector<string> m_v_strActiveWindow;
Statistics m_statistics;
Statistics m_statisticsEVR;
};
class CSysLatData
{
protected:
SYSLAT_DATA m_sld;
Json::Value m_JSONsld; //this is basically a second copy of the data... will probably eat up a BOATLOAD of memory for no reason. There's got to be a better way...
int systemLatency = 0;
std::mutex m_Mutex;
string m_strError = "";
const system_clock::time_point m_startTime = system_clock::now();
system_clock::time_point m_endTime;
duration<int> m_testDuration;
public:
const SYSLAT_DATA& GetData() {return m_sld;}
const Json::Value& GetJSONData() { return m_JSONsld; }
const int& GetSystemLatency() { return systemLatency; }
double CalculateMovingAverage(double currentAvg, int input);
void SetEndTime();
void UpdateSLD(unsigned int loopCounter, const string& sysLatResults, string RTSSWindow, string activeWindow, DWORD fgPID, DWORD rtssPID);
void AppendError(const string& error);
void CreateJSONSLD(); // I think I may need to make this and the following functions return bools or ints based on whether or not they failed.
void ExportData(int testNumber, string path = ".\\SysLat_Logs", int totalLogs = 10000);
string m_RTSSVersion = "0.0.0";
string m_targetApp = "Unknown";
string m_boxAnchor = "Unknown";
bool m_bDataExported = false;
bool m_bDataUploaded = false;
};
</code></pre>
|
[] |
[
{
"body": "<p>Suggestions:</p>\n<ul>\n<li>Make export data a static method, pass in the object to be exported.</li>\n<li>Do not have a member variable just to store JSON data; generate the JSON only as part of the export method.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T10:55:18.853",
"Id": "505459",
"Score": "0",
"body": "Good ideas. I thought that I had fabricated a reason to store JSON... but I certainly can't remember it now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T01:11:06.460",
"Id": "256067",
"ParentId": "256063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T22:24:55.660",
"Id": "256063",
"Score": "1",
"Tags": [
"c++",
"embedded"
],
"Title": "Turning a data class with too much functionality into a POD - SysLat Cleanup #2"
}
|
256063
|
<p>Today in an exam I faced a problem which is Toggled Switches(Hacker Earth) as it is an exam question So, I am unable to send the question or its link (exactly).</p>
<p>Problem: we have to print a number representing the number of times do bulb changed its state. The bulb is attached to the "n" number of switches. So the bulb will be in the "on" state only when half or more than half of the given n of switches to be "on".</p>
<p>1 represents on state</p>
<p>0 for off respectively.</p>
<p>There is also a query that will be given to represent which switch has to be toggled ( change from on to off or vice-versa 1 ->0 or 0->1). So, by toggling may or may not the bulb state change. so we have to return the number of times it changed its state.</p>
<p>input:</p>
<p>1 - number of test case</p>
<p>3 - number of switches (n)</p>
<p>1 1 0 - initial all n switches states</p>
<p>3 - number of switches to be toggled</p>
<p>3 2 1 -> (3 represents third switch i.e as index wise second in switches array.) switches that have to be toggled.</p>
<p>output:</p>
<p>1 - number of times the bulb changed its state
.</p>
<p><strong>explanation</strong>:
initial array or switches state [1, 1, 0] as half or more than half switches are in on. hence bulb is in on state.
as per queries [3,2,1]</p>
<p>we have to toggle the 3 rd switch. As initially third is in off [1,1,0] after toggling it changes to on [1,1,1] present switches state. as all are in on position bulb is on. ( no changes in the state of the bulb)</p>
<p>Now, have to toggle 2 nd switch so [1,1,1] changes to [1,0,1] switches states as half switches are on the bulb is on. ( no changes in the state of the bulb)</p>
<p>Now, 1 st switch to be toggled. Hence [1,0,1] changes to [0,0,1]. as not equal or more than half switches are in on states hence bulb is going to be off. ( now bulb state is changed)</p>
<p>Hence the output is one.</p>
<p>I wrote the answer to this I am only able to solve the sample test case. No hidden test case is got the right answer and some got time exceeds error. so totally 0 marks.</p>
<p>I am a beginner so please explain vividly where I am wrong what is wrong? how it can be efficient ?.</p>
<p>and my code is</p>
<pre><code> import java.util.*;
public class Main{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int test_cases = scan.nextInt();
while(test_cases>0){
//number of switches
int n = scan.nextInt();
// contains on / off positions of switches
int [] switches = new int[n];
for(int i =0;i<n;i++)
switches[i]=scan.nextInt();
//number of queries
int q = scan.nextInt();
// starts at 1 i.e queries[0]=1 but represents switch index 1(queries representing switch position and tha position starts from 1)
int [] queries = new int[q];
for(int i =0;i<q;i++)
queries[i]=scan.nextInt();
int result = toggled(n,switches,q,queries);
System.out.println(result);
test_cases--;
}
}
static int toggled(int n,int switches[],int q,int queries[]){
if(n==1)
return q;
int result =0;
//giving switch state on or off
boolean initial = on(switches);
//System.out.println("initial is "+initial);
//to represent on or off for all toggle including initial
boolean [] states = new boolean[q+1];
states[0] = initial;
int count = 0;
//to represent index of states
int state_count =1;
while(count<q){
if((switches[queries[count]-1] & 1 )== 1)
switches[queries[count]-1] = 0;
else
switches[queries[count]-1] = 1;
states[state_count++]=on(switches);
count++;
}
//System.out.println("state_count is "+state_count);
for(int i =1;i<state_count;i++){
if(initial ^ states[i] )
{
result+=1;
initial = states[i];
}
}
return result;
}
//method to evaluate whether to consider on or off ( to on(bulb) have to on atleast half of the switches)
static boolean on(int arr[]){
int sum = 0;
for(int i =0;i<arr.length;i++)
sum+=arr[i];
if(sum>=arr.length/2.0)
return true;
else
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T05:24:45.967",
"Id": "505448",
"Score": "0",
"body": "Hello! Did the indentation get lost when you copy-pasted the code here? If so, could you please fix the formatting so that the code becomes readable again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T07:04:11.313",
"Id": "505449",
"Score": "0",
"body": "Sorry sir, I am not good at editing after so many times fighting I posted code as a code.\nbut I will try my best again sir."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:08:48.680",
"Id": "505483",
"Score": "2",
"body": "Please do not edit the code after an answer has been posted. Everyone must be able to see the code as the reviewer saw it. Please read [What do I do after someone answers](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:17:19.913",
"Id": "505485",
"Score": "0",
"body": "Ok sir I Will remember next time but the thing is I just need indented it sir so please can roll back it will be help that may some others don't feel hard to understand that sir."
}
] |
[
{
"body": "<h1>Formatting</h1>\n<p>First off, the formatting including indentation is really terrible. For other people to be able to read and understand your code you need to abide to commonly accepted code conventions.</p>\n<p>For example:</p>\n<blockquote>\n<pre><code>if(n==1)\nreturn q;\nint result =0;\n</code></pre>\n</blockquote>\n<p>On a casual read through it is impossible to tell to which line(s) the <code>if</code> applies to. At the very least you need to indent <code>return q;</code>. Better would be to always use braces.</p>\n<p>Also use spaces between keywords and round brackets and around operators. Use blank lines to separate logical parts of code (especially between methods).</p>\n<p>The lines above should look like:</p>\n<pre><code>if (n == 1) {\n return q;\n}\n\nint result = 0;\n</code></pre>\n<p>Look up some Java code conventions (for example, <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">https://google.github.io/styleguide/javaguide.html</a>) and use them. Your editor/IDE should also have a function to format the code for you. If it doesn't, use a different editor/IDE.</p>\n<hr />\n<p><em>NB: I don't know if it is on topic or appropriate, but you have the same problem with your English text. Documentation is an important part of coding and while your text is understandable and contains all information, it appears disorganized. Inconsistent spacing, punctuation and capitalization makes it difficult to read.</em></p>\n<hr />\n<h1>Naming</h1>\n<p>Your variable names could be better. This can easily be seen due to your comments. Instead of the comments use those words as variable names. For example:</p>\n<pre><code>int numberOfSwitches = scan.nextInt(); // or maybe `switchCount`\n\nint[] switchPositions = new int[numberOfSwitches];\nfor (int i = 0; i < numberOfSwitches; i++) {\n switchPositions[i] = scan.nextInt();\n}\n\nint numberOfQueries = scan.nextInt();\n</code></pre>\n<p>Also variable names should be <code>camelCase</code> and not <code>snake_case</code>.</p>\n<hr />\n<h1>Unconventional coding choices</h1>\n<blockquote>\n<pre><code>if((switches[queries[count]-1] & 1 )== 1)\nswitches[queries[count]-1] = 0;\nelse\nswitches[queries[count]-1] = 1;\n</code></pre>\n</blockquote>\n<p>(First again: formatting/indentation) The <code>... & 1</code> seems unnecessary. the <code>switches</code> should only contain <code>0</code> or <code>1</code>. You should consider using <code>boolean</code> for <code>switches</code> anyway.</p>\n<p>Also <code>queries[count]-1</code> is repeated unnecessarily. Better would be for example:</p>\n<pre><code>int switchIndex = querys[count] - 1;\nswitches[switchIndex] = 1 - switches[switchIndex];\n</code></pre>\n<hr />\n<p>The use of <code>^</code> (xor) seems unnecessarily cryptic. You could just use <code>!==</code>.</p>\n<hr />\n<blockquote>\n<pre><code>if(sum>=arr.length/2.0)\n return true;\n else \n return false;\n</code></pre>\n</blockquote>\n<p>This kind of structure is unnecessary. The <code>if</code> expression is already boolean, so you can return its result directly:</p>\n<pre><code>return sum >= arr.length / 2.0;\n</code></pre>\n<p>Personally I would avoid float arithmetic here. I'd write it as:</p>\n<pre><code>return sum * 2 >= arr.length;\n</code></pre>\n<p>(This would be problematic with very large arrays, but that's an unlikely edge case.)</p>\n<hr />\n<h1>Performance</h1>\n<p>The performance problem is probably due to the use of two loops (first caculating all staes and then counting the changes). The whole calculation could be done in a single loop, because you don't need to store all the states. You only need to remember the last state. Also counting the number of switches to check if the light is on, only needs to be once at the beginning. In the loop the number of switches can be implied from the query.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:15:40.200",
"Id": "505474",
"Score": "0",
"body": "I totally agree with your points on indentation sir and I tried to indent but will doing whole half of the code is getting into the coding format while pasting in code review. So I am waiting to who knows very well to indent it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:49:46.237",
"Id": "505480",
"Score": "0",
"body": "Sir, I indended some of the code sir. hope this may resolve some errors. Can you have a look into that? Sir"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:24:26.583",
"Id": "505486",
"Score": "0",
"body": "Sir, The code I edited only I indented it rolled back but bottom of my heart thanks for ur suggestion about naming convention , indentation and want to mention you that I used xor because of I thought like bitwise operators are fast.\nand from my side\ncan you elaborate ur performance sir. It would be a great help sir.\nThank you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:04:26.780",
"Id": "256095",
"ParentId": "256064",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T22:57:37.467",
"Id": "256064",
"Score": "1",
"Tags": [
"java",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "return the number of times is state of bulb changed?"
}
|
256064
|
<p>I've built a read/write lock and have been testing it without encountering any problems. It was made to avoid writer starvation, but I believe it works against reader starvation as well. I've seen alternatives online, but was wondering if this is a solid implementation.</p>
<p>If you use a normal shared mutex, new read actions can still be queued, which will prevent write actions from ever being processed while there is any read action present. This will cause starvation. I used a second mutex which will be locked by the write process and prevents any new read processes to be queued. Thank you!</p>
<pre><code>class unique_priority_mutex
{
public:
void lock_shared(void)
{
// If there is a unique operation running, wait for it to finish.
if( this->_is_blocked ){
// Use a shared lock to let all shared actions through as soon as the unique action finishes.
std::shared_lock<std::shared_mutex> l(this->_unique_mutex);
}
// Allow for multiple shared actions, but no unique actions.
this->_shared_mutex.lock_shared();
}
void unlock_shared(void)
{
this->_shared_mutex.unlock_shared();
}
void lock(void)
{
// Avoid other unique actions and avoid new shared actions from being queued.
this->_unique_mutex.lock();
// Redirect shared actions to the unique lock.
this->_is_blocked = true;
// Perform the unique lock.
this->_shared_mutex.lock();
}
void unlock(void)
{
this->_shared_mutex.unlock();
this->_is_blocked = false;
this->_unique_mutex.unlock();
}
std::shared_mutex _shared_mutex;
std::shared_mutex _unique_mutex;
std::atomic<bool> _is_blocked = false;
};
</code></pre>
|
[] |
[
{
"body": "<p>You'd need <code>_shared_mutex</code> and <code>_is_blocked</code> to flip together 'atomically' in order for this code to work, no?</p>\n<p>Imaging one thread in <code>lock()</code> just flipped <code>_unique_mutex</code> and before it flips <code>_is_blocked</code>, another thread in <code>lock_shared()</code> is testing <code>_is_blocked</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:44:48.157",
"Id": "505576",
"Score": "0",
"body": "Thank you for your answer. The worst thing that can happen is that in between these actions which should happen simultaneously, a few read actions can overtake the write action ... no deadlocks or (writer) starvation, right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T04:32:48.973",
"Id": "256071",
"ParentId": "256066",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T00:53:36.147",
"Id": "256066",
"Score": "0",
"Tags": [
"c++",
"multithreading"
],
"Title": "Simple read/write lock implementation without starvation"
}
|
256066
|
<p>Is this a correct way to copy elements from array origin to array location?</p>
<pre><code> #include <stdio.h>
void copy(const int *origin, int *location, int n){
int i;
for(i=0;i<n;i++){
location[i]=origin[i];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T04:30:07.143",
"Id": "505445",
"Score": "1",
"body": "Short answer, no. But answering a question like this is not code review. Can you show how that function is used in a real program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T04:30:52.283",
"Id": "505446",
"Score": "0",
"body": "This is more of a question for StackOverflow, Code Review is for working programs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T05:23:54.283",
"Id": "505447",
"Score": "2",
"body": "Why is stdio included? Anyway have a look at memcpy function..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T07:34:43.273",
"Id": "505533",
"Score": "0",
"body": "The correct way is to not write this function unless you have specialized requirements. Just do `memcpy(dst, src, n)`."
}
] |
[
{
"body": "<blockquote>\n<pre><code> #include <stdio.h>\n</code></pre>\n</blockquote>\n<p>This function doesn't use anything from <code><stdio.h></code>, so don't waste the compiler's time by including it.</p>\n<blockquote>\n<pre><code> void copy(const int *origin, int *location, int n){\n</code></pre>\n</blockquote>\n<p>I would put the destination argument first, to be consistent with Standard Library functions such as <code>memcpy</code>. And change <code>n</code> to be a <code>size_t</code>, so it will work with any array.</p>\n<blockquote>\n<pre><code> int i;\n for(i=0;i<n;i++){\n</code></pre>\n</blockquote>\n<p>We can reduce the scope of <code>i</code>, by declaring it in the control expression: <code>for (int i = 0; i < n; ++i)</code>.</p>\n<blockquote>\n<pre><code> location[i]=origin[i];\n</code></pre>\n</blockquote>\n<p>We ought to tell the compiler (with <code>restrict</code>) that the arrays don't overlap.</p>\n<hr />\n<p>I think it's simpler just to forward to <code>memcpy()</code>:</p>\n<pre><code>#include <string.h>\nvoid copy(int *restrict dest, int const *restrict origin, size_t count)\n{\n memcpy(dest, origin, sizeof *dest * count);\n}\n</code></pre>\n<p>But that's so simple that I don't think we want a separate function for it (particularly with such a broad name).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T18:31:28.950",
"Id": "505497",
"Score": "1",
"body": "Could be more `memcpy()` like and return `dest`;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T18:33:45.797",
"Id": "505498",
"Score": "0",
"body": "I am not a fan of removing common `<xxx.h>` from .c files. Too much maintenance - so I'd rather waste compiler's time than mine. Some development environments do automate this though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T08:10:49.710",
"Id": "256075",
"ParentId": "256068",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256075",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T01:32:16.807",
"Id": "256068",
"Score": "0",
"Tags": [
"c"
],
"Title": "Copy an array using pointers"
}
|
256068
|
<p>I implemented a simple snake clone in C++, using SDL2 for the graphics part. Gameplay-wise, its pretty much classic snake: The player is able to control the snake with "WASD", food gets spawned randomly and if you eat it, you gain speed and length. The game is lost once you collide with yourself. Any tips?</p>
<p><em>source.cpp</em></p>
<pre><code>#include <SDL.h>
#include "Framework.h"
#include "Game.h"
int main(int argc, char* argv[])
{
Snake::SDL_Framework framework("Snake", 800, 800);
Snake::Game game(framework);
game.run();
return 0;
}
</code></pre>
<p><em>Framework.h</em></p>
<pre><code>#ifndef SDL_FRAMEWORK
#define SDL_FRAMEWORK
#include <SDL.h>
#include <cstdint>
#include <string>
#include <exception>
namespace Snake
{
class SDL_Framework
{
public:
SDL_Framework() : main_window{ nullptr }, renderer{ nullptr }, window_height{ 0 }, window_width{ 0 } {};
SDL_Framework(const std::string& window_name, int32_t height, int32_t width);
~SDL_Framework();
void clear();
void update();
int32_t get_height() const { return window_height; }
int32_t get_width() const { return window_width; }
SDL_Renderer* renderer;
private:
SDL_Window* main_window;
int32_t window_height;
int32_t window_width;
};
}
#endif
</code></pre>
<p><em>Framework.cpp</em></p>
<pre><code>#include "Framework.h"
static void process_error(const std::string& msg)
{
throw std::runtime_error(msg);
}
namespace Snake
{
SDL_Framework::SDL_Framework(const std::string& window_name, int32_t height, int32_t width)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0)
{
process_error(std::string("Error while trying to initialise SDL! SDL_Error: ") + SDL_GetError());
}
main_window = SDL_CreateWindow(window_name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, height, width, SDL_WINDOW_SHOWN);
if (main_window == nullptr)
{
process_error(std::string("Error while trying to create SDL_Window! SDL_Error: ") + SDL_GetError());
}
window_height = height;
window_width = width;
renderer = SDL_CreateRenderer(main_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr)
{
process_error(std::string("Error while trying to create renderer! SDL_Error: ") + SDL_GetError());
}
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
}
SDL_Framework::~SDL_Framework()
{
SDL_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(main_window);
}
void SDL_Framework::clear()
{
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
}
void SDL_Framework::update()
{
SDL_RenderPresent(renderer);
}
}
</code></pre>
<p><em>Game.h</em></p>
<pre><code>#ifndef SNAKE_GAME
#define SNAKE_GAME
#include "Framework.h"
#include "Board.h"
#include "Player.h"
namespace Snake
{
class Game
{
public:
Game(const SDL_Framework& uframework);
void run();
void update();
void render();
private:
SDL_Framework framework;
Board board;
Player player;
int32_t frame;
};
}
#endif
</code></pre>
<p><em>Game.cpp</em></p>
<pre><code>#include "Game.h"
namespace Snake
{
Game::Game(const SDL_Framework& uframework) : frame{0}
{
framework = uframework;
int32_t cells_per_side = 25;
int32_t cell_size = framework.get_height() / cells_per_side;
board = Board(framework.get_height(), framework.get_width(), cell_size);
board.generate_food();
int32_t middle = cell_size * (framework.get_height() / cell_size / 2); // calculating the middle of the board in cell roster, assuming length == width
player = Player(middle, middle);
}
void Game::run()
{
bool running = true;
SDL_Event event;
do {
frame++;
while (SDL_PollEvent(&event) != 0)
{
switch (event.type)
{
case SDL_QUIT:
{
running = false;
break;
}
}
}
update();
framework.clear();
render();
framework.update();
} while (running);
}
void Game::update()
{
if (player.check_food_collision(board.get_food_pos()))
{
board.generate_food();
}
player.update(board.get_borders(), board.get_cell_size(), frame);
}
void Game::render()
{
board.render(framework.renderer);
player.render(framework.renderer, board.get_cell_size());
}
}
</code></pre>
<p><em>Board.h</em></p>
<pre><code>#ifndef SNAKE_BOARD
#define SNAKE_BOARD
#include <SDL.h>
#include <utility>
#include <random>
#include "Cell.h"
namespace Snake
{
class Board
{
public:
Board() = default;
Board(int32_t ulength, int32_t uwidth, int32_t cell_size);
void generate_food();
void render(SDL_Renderer* renderer) const;
std::pair<int32_t, int32_t> get_food_pos() const { return food.get_pos(); }
std::pair<int32_t, int32_t> get_borders() { return { length, width }; }
int32_t get_cell_size() const { return cell_size; }
private:
Cell food;
int32_t length;
int32_t width;
int32_t cell_size;
std::mt19937 gen;
std::uniform_int_distribution<int32_t> distr;
};
}
#endif
</code></pre>
<p><em>Board.cpp</em></p>
<pre><code>#include "Board.h"
namespace Snake
{
Board::Board(int32_t ulength, int32_t uwidth, int32_t ucell_size) : length{ ulength }, width{ uwidth }, cell_size{ ucell_size }
{
gen = std::mt19937(std::random_device{}());
distr = std::uniform_int_distribution<int32_t>(0, (length / cell_size) - 1);
}
void Board::generate_food()
{
int32_t food_x = distr(gen) * cell_size;
int32_t food_y = distr(gen) * cell_size;
food.update_pos(food_x, food_y);
}
void Board::render(SDL_Renderer* renderer) const
{
SDL_SetRenderDrawColor(framework.renderer, 0, 0, 0, 255);
// render cell grid
for (int32_t distance = cell_size; distance < length; distance += cell_size)
{
SDL_RenderDrawLine(renderer, distance, 0, distance, length);
SDL_RenderDrawLine(renderer, 0, distance, width, distance);
}
// render food
food.render(renderer, cell_size, SDL_Color{ 0, 0, 0, 255 });
}
}
</code></pre>
<p><em>Player.h</em></p>
<pre><code>#ifndef SNAKE_PLAYER
#define SNAKE_PLAYER
#include <SDL.h>
#include <vector>
#include "Cell.h"
namespace Snake
{
class Player
{
enum Direction
{
UP, DOWN, RIGHT, LEFT
};
public:
Player() = default;
Player(int32_t x, int32_t y) :
length{ 1 },
growth_remaining{ 2 },
growth_per_cell{ 2 },
cur_direction{LEFT},
speed{ 30 },
speed_gain{2},
max_speed{ 4 }
{
head.update_pos(x, y);
}
void update(std::pair<int32_t, int32_t> borders, int32_t cell_size, int32_t frame);
void render(SDL_Renderer* renderer, int32_t cell_size) const;
bool check_food_collision(std::pair<int32_t, int32_t> food_pos);
private:
void update_position(std::pair<int32_t, int32_t> borders, int32_t cell_size, int32_t frame);
void update_direction();
bool check_self_collision();
void reset();
int32_t length;
int32_t growth_remaining;
int32_t growth_per_cell;
Direction cur_direction;
int32_t speed; // lower is faster, updates player every {speed} frames
int32_t speed_gain;
int32_t max_speed;
Cell head;
std::vector<Cell> body;
std::pair<int32_t, int32_t> get_next_pos(int32_t cell_size, std::pair<int32_t, int32_t> cur_pos);
};
}
#endif
</code></pre>
<p><em>Player.cpp</em></p>
<pre><code>#include "Player.h"
namespace Snake
{
void Player::update(std::pair<int32_t, int32_t> borders, int32_t cell_size, int32_t frame)
{
update_direction();
update_position(borders, cell_size, frame);
if (check_self_collision())
{
reset();
}
}
void Player::update_position(std::pair<int32_t, int32_t> borders, int32_t cell_size, int32_t frame)
{
if (frame % speed) return; // only update when neccessary
if (growth_remaining)
{
body.insert(std::begin(body), Cell(head.get_pos().first, head.get_pos().second));
growth_remaining--;
}
else
{
if (!body.empty())
{
for (uint32_t i = body.size() - 1; i > 0; --i)
{
body[i].update_pos(body[i-1].get_pos().first, body[i - 1].get_pos().second);
}
body[0].update_pos(head.get_pos().first, head.get_pos().second);
}
}
auto new_pos = get_next_pos(cell_size, head.get_pos());
// implement player moving over border
if (new_pos.first > borders.second) { new_pos.first = 0; }
if (new_pos.first < 0) { new_pos.first = borders.second - cell_size; }
if (new_pos.second > borders.first) { new_pos.second = 0; }
if (new_pos.second < 0) { new_pos.second = borders.first - cell_size; }
head.update_pos(new_pos.first, new_pos.second);
}
void Player::update_direction()
{
const Uint8* key_state = SDL_GetKeyboardState(nullptr);
if (key_state[SDL_SCANCODE_W])
{
cur_direction = UP;
}
else if (key_state[SDL_SCANCODE_S])
{
cur_direction = DOWN;
}
else if (key_state[SDL_SCANCODE_A])
{
cur_direction = LEFT;
}
else if (key_state[SDL_SCANCODE_D])
{
cur_direction = RIGHT;
}
}
bool Player::check_self_collision()
{
for (auto& bodypart : body)
{
if (head.get_pos() == bodypart.get_pos())
{
return true;
}
}
return false;
}
void Player::reset()
{
body.clear();
growth_remaining = 2;
speed = 30;
}
void Player::render(SDL_Renderer* renderer, int32_t cell_size) const
{
head.render(renderer, cell_size, SDL_Color{255, 100, 0, 255});
for (auto& cell : body)
{
cell.render(renderer, cell_size);
}
}
bool Player::check_food_collision(std::pair<int32_t, int32_t> food_pos)
{
if (head.get_pos() == food_pos)
{
growth_remaining += growth_per_cell;
speed -= speed_gain; // increase speed
if (speed < max_speed) { speed = max_speed; }
return true;
}
return false;
}
std::pair<int32_t, int32_t> Player::get_next_pos(int32_t cell_size, std::pair<int32_t, int32_t> cur_pos)
{
std::pair<int32_t, int32_t> next_pos(cur_pos);
switch (cur_direction)
{
case UP:
{
next_pos.second -= cell_size;
break;
}
case DOWN:
{
next_pos.second += cell_size;
break;
}
case RIGHT:
{
next_pos.first += cell_size;
break;
}
case LEFT:
{
next_pos.first -= cell_size;
break;
}
}
return next_pos;
}
}
</code></pre>
<p><em>Cell.h</em></p>
<pre><code>#ifndef SNAKE_CELL
#define SNAKE_CELL
#include <SDL.h>
#include <cstdint>
#include <utility>
namespace Snake
{
class Cell
{
public:
Cell() = default;
Cell(int32_t x, int32_t y) :
pos{ x, y }
{}
void render(SDL_Renderer* renderer, int32_t cell_size, SDL_Color color = SDL_Color{ 255, 30, 20, 255 }) const;
void update_pos(int32_t x, int32_t y) { pos.first = x; pos.second = y; }
std::pair<int32_t, int32_t> get_pos() const { return pos; }
private:
std::pair<int32_t, int32_t> pos;
};
}
#endif
</code></pre>
<p><em>Cell.cpp</em></p>
<pre><code>#include "Cell.h"
namespace Snake
{
void Cell::render(SDL_Renderer* renderer, int32_t cell_size, SDL_Color color) const
{
// set draw color to red
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_Rect rect = { pos.first + 1, pos.second + 1, cell_size - 1, cell_size - 1 };
SDL_RenderFillRect(renderer, &rect);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T09:26:00.830",
"Id": "505456",
"Score": "1",
"body": "Well done. Only a few minor things come to mind. \nI would suggest replacing `std::pair<int32_t, int32_t>` with struct or wrapping into `using`. Also, it is a good habit to use forward declarations to reduce compile times. Though it is useful only in huge projects. In a huge project, I would suggest having file with forward declarations and move as much includes from header to source file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:28:18.860",
"Id": "505478",
"Score": "0",
"body": "@xevepisis Thank you for the feedback!"
}
] |
[
{
"body": "<p><strong>double deletion issue</strong>:</p>\n<pre><code>Snake::SDL_Framework framework("Snake", 800, 800);\nSnake::Game game(framework);\n\n...\n\nGame::Game(const SDL_Framework& uframework) : frame{0}\n{\n framework = uframework;\n\n...\n\nSDL_Framework::~SDL_Framework()\n{\n SDL_Quit();\n SDL_DestroyRenderer(renderer);\n SDL_DestroyWindow(main_window);\n}\n</code></pre>\n<p>We have one <code>SDL_Framework</code> object in <code>main()</code>. Then we copy it to a member variable in the <code>Game</code> constructor.</p>\n<p>So now we have two <code>SDL_Framework</code> objects. That means two destructor calls... and we're calling <code>SDL_DestroyRenderer</code> and <code>SDL_DestroyWindow</code> twice with the same handles! We might get away with it right now because the <code>SDL_Quit</code> call is first, otherwise we'd probably be trying to free the same memory twice.</p>\n<p>What we really need is to make <code>SDL_Framework</code> non-copyable and store only a reference or pointer to it in <code>Game</code>. Alternatively we could make <code>SDL_Framework</code> moveable only, and move it into <code>Game</code> instead.</p>\n<hr />\n<p><strong>window size bug</strong>:</p>\n<pre><code>SDL_CreateWindow(window_name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, height, width, SDL_WINDOW_SHOWN);\n</code></pre>\n<p>The <code>height</code> and <code>width</code> parameters are the wrong way around in this call. (It's conventional to use (x, y) for coordinates instead of (y, x)).</p>\n<hr />\n<p><strong>naming nitpick</strong>:</p>\n<pre><code>void SDL_Framework::update()\n{\n SDL_RenderPresent(renderer);\n}\n</code></pre>\n<p><code>update()</code> is very vague and potentially confusing given its use elsewhere. <code>present_buffer()</code> or <code>swap_buffers()</code> or something similar might be a better name.</p>\n<hr />\n<p><strong>access-control nitpick</strong>:</p>\n<pre><code>class Game\n{\npublic:\n\n Game(const SDL_Framework& uframework);\n\n void run();\n void update();\n void render();\n</code></pre>\n<p>We only call the <code>run()</code> function from outside the class, so <code>update()</code> and <code>render()</code> could be <code>private</code>.</p>\n<hr />\n<p><strong>coordinate class</strong>:</p>\n<pre><code>std::pair<int32_t, int32_t>\n</code></pre>\n<p>As the comments point out, it's definitely worth using a simple struct so we know which coordinate is which:</p>\n<pre><code>template<class T>\nstruct Vec2 { T x, y; };\n</code></pre>\n<hr />\n<p><strong>frame-rate (in)dependence</strong>:</p>\n<pre><code> int32_t speed; // lower is faster, updates player every {speed} frames\n\n ...\n\n if (frame % speed) return; // only update when neccessary\n</code></pre>\n<p>This might work if we had a fixed frame-rate. But I don't see anything in the main loop limiting the frame-rate. So on a fast computer, the snake will be much quicker than on a slower one.</p>\n<p>We should use the facilities in the <code><chrono></code> standard header to make an actual timer for this, e.g. in <code>Player::update_position()</code>:</p>\n<pre><code>auto now = std::chrono::high_resolution_clock::now();\nif (now > last_update + time_between_updates) { last_update = now; ... do update ... }\n</code></pre>\n<p>Where <code>time_between_updates</code> works similarly to the <code>speed</code> variable, but represents an actual time.</p>\n<hr />\n<p><strong>unnecessary class</strong>:</p>\n<pre><code>class Cell\n{\npublic:\n\n Cell() = default;\n Cell(int32_t x, int32_t y) : \n pos{ x, y }\n {}\n\n void render(SDL_Renderer* renderer, int32_t cell_size, SDL_Color color = SDL_Color{ 255, 30, 20, 255 }) const;\n void update_pos(int32_t x, int32_t y) { pos.first = x; pos.second = y; }\n std::pair<int32_t, int32_t> get_pos() const { return pos; }\n\nprivate:\n\n std::pair<int32_t, int32_t> pos;\n\n};\n</code></pre>\n<p>I'm not sure we really need this class. It's just a coordinate pair.</p>\n<p>The rendering could be a free function, or inlined where it's used.</p>\n<hr />\n<p><strong>player update improvements</strong>:</p>\n<pre><code> body.insert(std::begin(body), Cell(head.get_pos().first, head.get_pos().second));\n</code></pre>\n<p>Inserting at the front of a vector is quite slow, because we have to move every other element backwards to make room. Perhaps a <code>deque</code> would be a better? (Though iteration may be slightly slower).</p>\n<pre><code> if (!body.empty())\n {\n for (uint32_t i = body.size() - 1; i > 0; --i)\n {\n body[i].update_pos(body[i-1].get_pos().first, body[i - 1].get_pos().second);\n }\n body[0].update_pos(head.get_pos().first, head.get_pos().second);\n }\n</code></pre>\n<p>Every cell simply follows the next cell, right? In that case, can't we just erase the last cell in the vector, and insert a new cell at the front?</p>\n<p>(Perhaps we could use some sort of fancy circular index system, where we just shift over the head index and change the last (now first) coordinate... but that's probably a bit overcomplicated).</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:35:27.410",
"Id": "505479",
"Score": "0",
"body": "Thanks for the feedback! About the framerate-independence: `SDL_RENDERER_PRESENTVSYNC` in the `SDL_CreateRenderer()` call in *Framework.cpp* should cap to 60fps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:12:54.837",
"Id": "505484",
"Score": "1",
"body": "Not 60fps, but whatever your monitor's refresh rate happens to be (and depending on graphics card drivers settings). So anywhere from 50Hz on old monitors, to 240Hz on fancy gaming monitors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:35:37.623",
"Id": "505490",
"Score": "0",
"body": "Of course, you are right, my monitor's refresh rate just happens to be 60Hz."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:40:46.903",
"Id": "256083",
"ParentId": "256069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256083",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T01:43:06.493",
"Id": "256069",
"Score": "1",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"snake-game",
"sdl"
],
"Title": "Snake game in C++17 with SDL2"
}
|
256069
|
<p>I am pretty newbie in Scala, my background expertise is basically Java and Python, and I'd like to know your thoughts about this code snippet written in Scala to know if this is a "regular piece of code written in Scala" or if this is something kind of "obfuscated" and overcomplicated.</p>
<p>The code just implements a simple decision flow to categorize keywords depending on a few rules.</p>
<p>Thanks!</p>
<pre><code>def preprocess(kwd: Keyword): Option[PrepKeyword] = {
val isFoo = kwd.name.exists(_.toLowerCase(locale) == "foo")
for {
filterCategory <- (isFoo, kwd.type) match {
case (true, _) => Some(false)
case (false, 1) => Some(true)
case (false, 2) => Some(false)
case _ => None
}
fooName <- kwd.name match {
case None | Some("name1") => None
case Some("myCategory") if filterCategory => Some("GreatCategory")
case other => other
}
} yield PrepKeyword(
keyword = kwd,
name = fooName,
path = if (isFoo) "Foo1" else "Foo2"
)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T08:18:06.757",
"Id": "505452",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>Overall in terms of style it looks fine to me. The usage of a for comprehension with <code>Option</code> is pretty idiomatic, so I wouldn't call it obfuscated or overcomplicated.</p>\n<p>That being said I do think the logic could be flattened out a bit to make it clearer to the reader which inputs of <code>Keyword</code> to <code>preprocess</code> will result in a <code>Some(PrepKeyword(_))</code>.</p>\n<pre class=\"lang-scala prettyprint-override\"><code>case class Keyword(\n name: Option[String],\n typeCode: Int\n)\n\ncase class PrepKeyword(\n keyword: Keyword,\n name: String,\n path: String\n)\n\ndef preprocess(kwd: Keyword): Option[PrepKeyword] = {\n val isFoo = kwd.name.exists(_.toLowerCase() == "foo")\n val maybeFilterCategory: Option[Boolean] = {\n (isFoo, kwd.typeCode) match {\n case (true, _) => Some(false)\n case (false, 1) => Some(true)\n case (false, 2) => Some(false)\n case _ => None\n }\n }\n \n (kwd.name, maybeFilterCategory) match {\n case (Some(name), Some(filterCategory)) if name != "name1" => {\n val fooName = if (filterCategory && name == "myCategory") {\n "GreatCategory"\n } else {\n name\n }\n val path = if (isFoo) "Foo1" else "Foo2"\n \n Some(PrepKeyword(kwd, fooName, path))\n }\n case _ => None\n }\n}\n</code></pre>\n<p>In the above refactor, it's easier to see that in order to return a <code>Some(PrepKeyword(_))</code>, as a minimum requirement the <code>Option</code>s <code>kwd.name</code> and <code>maybeFilterCategory</code> must both be <code>Some(_)</code>.</p>\n<p>Note: <code>type</code> is a reserved word in Scala so it can't be used as an identifier. You can use backticks as an alternative, e.g.</p>\n<pre class=\"lang-scala prettyprint-override\"><code>case class Keyword(\n name: Option[String],\n `type`: Int\n)\n</code></pre>\n<p>but I personally find this kind of ugly, so in the refactor I used <code>typeCode</code> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:14:14.090",
"Id": "256080",
"ParentId": "256074",
"Score": "0"
}
},
{
"body": "<p>The posted code won't compile without a working definition of <code>Keyword</code> and <code>PrepKeyword</code>. And <code>type</code> is a reserved word so <code>kwd.type</code> isn't allowed (might be version dependent).</p>\n<p>The code, as presented, is inconsistent or just plain wrong in its indenting but, other than that, it's reasonably clear in intent and presentation.</p>\n<p>The logic is, perhaps, overly convoluted. I found that I had to go back and forth to see how output was built from input. I eventually decided that <code>kwd.name</code> was the key value from which most everything else flows. With that in mind I tried to rebuild the logic.</p>\n<pre><code>def preprocess(kwd: Keyword): Option[PrepKeyword] = {\n val fooName = "(?i)(foo)".r\n kwd.name.flatMap{\n case "name1" => None\n case "myCategory" =>\n kwd.typ match {\n case 1 => Some(PrepKeyword(kwd, "GreatCategory", "Foo2"))\n case 2 => Some(PrepKeyword(kwd, "myCategory", "Foo2"))\n case _ => None\n }\n case fooName(fnm) => Some(PrepKeyword(kwd, fnm, "Foo1"))\n case nonFoo => Some(PrepKeyword(kwd, nonFoo, "Foo2"))\n }\n}\n</code></pre>\n<p>This, according to my tests so far, produces the same results. It builds the output in multiple places but in each case it's pretty easy to see how the input directed the output.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:21:44.697",
"Id": "256082",
"ParentId": "256074",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T07:52:03.497",
"Id": "256074",
"Score": "1",
"Tags": [
"scala"
],
"Title": "Keyword classification in Scala... simple?"
}
|
256074
|
<p>A Stream Data Generator which can take data from both a file or just a counter. This is needed for me as a testbench component for interfaces which works on one hand as an AXIS slave and on the other hand as Ethernet.</p>
<p>A struct module</p>
<pre><code>`timescale 1ns / 1ps
module axis_data_generator #
(
parameter integer AXIS_DATA_WIDTH = 32,
parameter [(AXIS_DATA_WIDTH / 8) - 1:0] AXIS_TKEEP = 4'hf,
parameter INIT_FILE = "",
parameter integer BURST_SIZE = 1024
)
(
input wire clk_i,
input wire s_rst_n_i,
input wire enable_i,
output wire [AXIS_DATA_WIDTH - 1 : 0] m_axis_tdata_o,
output wire [(AXIS_DATA_WIDTH / 8) - 1:0] m_axis_tkeep_o,
output wire m_axis_tvalid_o,
output wire m_axis_tlast_o,
input wire m_axis_tready_i
);
wire counter_terminate;
wire counter_enable;
wire [AXIS_DATA_WIDTH - 1 : 0] data;
wire [AXIS_DATA_WIDTH - 1 : 0] counter_value;
COUNTER_TC_MACRO #
(
.COUNT_BY (48'h1 ),
.DEVICE ("7SERIES" ),
.DIRECTION ("UP" ),
.RESET_UPON_TC ("TRUE" ),
.TC_VALUE (BURST_SIZE ),
.WIDTH_DATA (AXIS_DATA_WIDTH )
)
tc_counter_inst_0
(
.Q (counter_value ),
.TC (counter_terminate),
.CLK (clk_i ),
.CE (counter_enable ),
.RST (!s_rst_n_i )
);
generate
if ("" != INIT_FILE)
begin : init_from_file
BRAM_SINGLE_MACRO #
(
.BRAM_SIZE ("18Kb" ),
.DEVICE ("7SERIES" ),
.DO_REG (0 ),
.INIT ({AXIS_DATA_WIDTH{1'h0}}),
.INIT_FILE ("NONE" ),
.WRITE_WIDTH (AXIS_DATA_WIDTH ),
.READ_WIDTH (AXIS_DATA_WIDTH ),
.SRVAL ({AXIS_DATA_WIDTH{1'h0}}),
.WRITE_MODE ("NO_CHANGE" )
)
single_bram_inst_0
(
.DO (data ),
.ADDR (counter_value ),
.CLK (clk_i ),
.DI ({AXIS_DATA_WIDTH{1'h0}}),
.EN (enable_i ),
.REGCE (1'h0 ),
.RST (!s_rst_n_i ),
.WE (1'h0 )
);
end
else
begin : data_from_counter_buf
IBUF #
(
.IBUF_LOW_PWR ("TRUE" ),
.IOSTANDARD ("DEFAULT")
)
ibuf_inst_0
(
.O (data ),
.I (counter_value)
);
end
endgenerate
axis_data_generator_cntr #
(
.AXIS_DATA_WIDTH (AXIS_DATA_WIDTH),
.AXIS_TKEEP (AXIS_TKEEP )
)
(
.clk_i (clk_i ),
.s_rst_n_i (s_rst_n_i ),
.enable_i (enable_i ),
.m_axis_tdata_o (m_axis_tdata_o ),
.m_axis_tkeep_o (m_axis_tkeep_o ),
.m_axis_tvalid_o (m_axis_tvalid_o ),
.m_axis_tlast_o (m_axis_tlast_o ),
.m_axis_tready_i (m_axis_tready_i ),
.data_i (data ),
.counter_terminal_i (counter_terminate),
.counter_enable_o (counter_enable )
);
endmodule
</code></pre>
<p>axi stream controller module</p>
<pre><code>`timescale 1ns / 1ps
module axis_data_generator_cntr #
(
parameter integer AXIS_DATA_WIDTH = 32,
parameter [(AXIS_DATA_WIDTH / 8) - 1:0] AXIS_TKEEP = 'hf
)
(
input wire clk_i,
input wire s_rst_n_i,
input wire enable_i,
output wire [AXIS_DATA_WIDTH - 1 : 0] m_axis_tdata_o,
output wire [(AXIS_DATA_WIDTH / 8) - 1:0] m_axis_tkeep_o,
output wire m_axis_tvalid_o,
output wire m_axis_tlast_o,
input wire m_axis_tready_i,
input wire [AXIS_DATA_WIDTH - 1 : 0] data_i,
input wire counter_terminal_i,
output wire counter_enable_o
);
localparam integer STATE_NUM = 3;
localparam integer STATE_WIDTH = $clog2(STATE_NUM);
localparam [STATE_WIDTH - 1 : 0] IDLE_STATE = 0;
localparam [STATE_WIDTH - 1 : 0] SENDING_STATE = 1;
localparam [STATE_WIDTH - 1 : 0] STOP_STATE = 2;
reg [STATE_WIDTH - 1 : 0] fsm_state;
reg [STATE_WIDTH - 1 : 0] next_fsm_state;
assign m_axis_tvalid_o = enable_i;
assign m_axis_tkeep_o = AXIS_TKEEP;
assign m_axis_tlast_o = counter_terminal_i;
assign counter_enable_o = ((SENDING_STATE == fsm_state) && (1'h1 == m_axis_tready_i));
assign m_axis_tdata_o = data_i;
always @( posedge clk_i )
begin
if(1'h0 == s_rst_n_i)
begin
fsm_state <= IDLE_STATE;
next_fsm_state <= IDLE_STATE;
end
else
begin
fsm_state <= next_fsm_state;
end
end
always @ (*)
begin
next_fsm_state = fsm_state;
if (1'h1 == enable_i)
begin
case (fsm_state)
IDLE_STATE:
begin
if (1'h1 == m_axis_tready_i)
begin
next_fsm_state = SENDING_STATE;
end
end
SENDING_STATE:
begin
if (1'h1 == counter_terminal_i)
begin
next_fsm_state = STOP_STATE;
end
end
STOP_STATE:
begin
next_fsm_state = IDLE_STATE;
end
endcase
end
end
endmodule
</code></pre>
<p>testbench</p>
<pre><code>`timescale 1ns / 1ps
module axis_data_generator_cntr_tb;
localparam integer DATA_WIDTH = 32;
localparam integer CLOCK_PERIOD = 100;
localparam integer PACK_SIZE = 1024;
localparam integer PACK_NUMBER = 1024;
localparam integer ITERATION_NUMBER = PACK_SIZE * PACK_NUMBER;
localparam [DATA_WIDTH / 8 - 1 : 0] KEEP = 'hf;
wire counter_enable;
wire terminate;
wire axis_tvalid;
wire axis_tlast;
wire [DATA_WIDTH - 1 : 0] axis_tdata;
wire [DATA_WIDTH / 8 - 1 : 0] axis_tkeep;
wire [DATA_WIDTH - 1 : 0] data;
reg axis_tready;
reg clk;
reg rst_n;
reg enable;
COUNTER_TC_MACRO #
(
.COUNT_BY (48'h1 ),
.DEVICE ("7SERIES" ),
.DIRECTION ("UP" ),
.RESET_UPON_TC ("TRUE" ),
.TC_VALUE (PACK_SIZE ),
.WIDTH_DATA (DATA_WIDTH)
)
COUNTER_TC_MACRO_inst_0
(
.Q (data ),
.TC (terminate ),
.CLK (clk ),
.CE (counter_enable),
.RST (!rst_n )
);
axis_data_generator_cntr #
(
.AXIS_DATA_WIDTH (DATA_WIDTH),
.AXIS_TKEEP (KEEP )
)
axis_data_generator_cntr_dut_0
(
.clk_i (clk ),
.s_rst_n_i (rst_n ),
.enable_i (enable ),
.m_axis_tdata_o (axis_tdata ),
.m_axis_tkeep_o (axis_tkeep ),
.m_axis_tvalid_o (axis_tvalid ),
.m_axis_tlast_o (axis_tlast ),
.m_axis_tready_i (axis_tready ),
.data_i (data ),
.counter_terminal_i (terminate ),
.counter_enable_o (counter_enable)
);
task check_data;
begin
enable <= 1'h1;
rst_n <= 1'h1;
@(posedge clk);
wait (axis_tvalid);
repeat(100)
begin
if ({DATA_WIDTH{1'h0}} != axis_tdata)
begin
$display("The ready signal error.");
$stop();
end
@(posedge clk);
end
repeat(ITERATION_NUMBER)
begin
axis_tready <= $urandom % 2;
@(posedge clk);
end
enable <= 1'h0;
end
endtask
initial
begin
clk = 1'h0;
forever
begin
#(CLOCK_PERIOD / 2) clk = !clk;
end
end
initial
begin
rst_n = 1'h0;
enable = 1'h0;
@(posedge clk);
check_data;
$display("The test has finished.");
$stop();
end
endmodule
</code></pre>
|
[] |
[
{
"body": "<p>The layout of code the follows good practices, and you have a clean separation between design and testbench.</p>\n<p>There is a syntax error which your compiler should have detected. An instance name is required when you instantiate a module, but your <code>axis_data_generator_cntr</code> instance is missing a name. You should add something like <code>axis_data_generator_cntr_0</code> below:</p>\n<pre><code> axis_data_generator_cntr #\n (\n .AXIS_DATA_WIDTH (AXIS_DATA_WIDTH),\n .AXIS_TKEEP (AXIS_TKEEP )\n )\n axis_data_generator_cntr_0\n (\n .clk_i (clk_i ),\n</code></pre>\n<p>You should not assign to signals from multiple <code>always</code> blocks. The assignment to <code>next_fsm_state</code> should be removed from the sequential logic block:</p>\n<pre><code> next_fsm_state <= IDLE_STATE;\n</code></pre>\n<p>While this might not cause problems during simulation, you will likely get warnings from synthesis.</p>\n<p>In your testbench, it is a good practice to use <em>case equality</em> operators for comparisons when operands are 4-state values (and can have <code>x</code> or <code>z</code>). For example, change <code>!=</code> to <code>!==</code> in the following line:</p>\n<pre><code> if ({DATA_WIDTH{1'h0}} != axis_tdata)\n</code></pre>\n<p>It is also good practice to display the simulation time for your <code>$display</code> messages. For example:</p>\n<pre><code> $display($time, " The ready signal error.");\n</code></pre>\n<p>It doesn't matter much in the code you posted since you immediately stop the simulation after each <code>$display</code>, but if you start displaying messages at different times, it will be helpful for debug.</p>\n<hr />\n<p><code>$urandom</code> is a system task which was introduced as part of the SystemVerilog extensions to the language (IEEE Std 1800). This means that your simulator supports SV to some degree. You could also consider exploring whether your tool chain supports other SV features.</p>\n<hr />\n<p>You could also review <a href=\"https://codereview.stackexchange.com/a/254743/125403\">my Answer to your previous Question</a> regarding some more minor coding style and layout preferences.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T12:52:20.090",
"Id": "505551",
"Score": "1",
"body": "I gratful you for your notices, it will be very useful for me. I use a vivado compiler and yes it missed the error as well as me. All which you indicated was corrected and now it should be better.\n\nUnfortunately, I am not able to refuse \"if (1'h1 == some_net)\". It is my curse..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T13:06:21.233",
"Id": "505556",
"Score": "0",
"body": "@drakonof: Glad I could help. I find it useful to run my Verilog code on multiple simulators. You can get access to a few on https://www.edaplayground.com. You need to sign up for an account, but it is free."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:47:23.710",
"Id": "256103",
"ParentId": "256076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256103",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T08:42:06.257",
"Id": "256076",
"Score": "2",
"Tags": [
"verilog"
],
"Title": "AXI stream data generator"
}
|
256076
|
<pre><code>import math
def luhns_algorithm(num):
argument_is_integer = isinstance(num, int)
number = num #from this number we will get every other digit
every_other_digit = [] #we will append every other digit to this list
not_every_other_digit = [] #we will append the other digits to this list
every_other_digit_times_two = [] #we will append every other digit multiplied by two to this list
sum_of_digits_in_every_other_digit = 0 #Counter to store the sum of the digits of the numbers in the list
#every_other_digit_times_two
valid = False #The default is that the credit card is not valid. If the last digit of the target sum is 0, the card is valid
rem = 1 #We will use rem in the while loop to get the last digits of the number
target_sum = 0
#Checks that the argument is an integer. If not, the credit card number is not valid.
if argument_is_integer != True:
return
else:
#In the following while loop, the goal is to split the digits of the number in two halves and store those
#halves in two separate lists
while number > 1: #We will divide the number until it is less than zero, which means there are no more digits
rem = number % 10
not_every_other_digit.append(rem)
number /= 10
number = math.floor(number)
rem = number % 10
every_other_digit.append(rem)
number /= 10
number = math.floor(number)
#In this for loop we iterate through the digits in every_other_digits and appends those
#digits multiplied by two to a new list
for digit in every_other_digit:
every_other_digit_times_two.append(digit * 2)
#Because we are supposed to add only the digits of the products of every other digit times two, we must create
#two conditionals. The first if- statement is for digits from 0-9. The else- statement is for numbers > 10,
#where we must first split the number into two digits and then sum those digits to sum_of_digits_every_other_digit_times_two
for digit in every_other_digit_times_two:
if digit < 10:
sum_of_digits_in_every_other_digit += digit
else:
second_digit = digit % 10
first_digit = math.floor(digit / 10)
sum_of_digits_in_every_other_digit += first_digit
sum_of_digits_in_every_other_digit += second_digit
#Creates empty counter so that we can add the digits not multiplied by two
sum_of_digits_not_multiplied_by_two = 0
#Iterates through digits in the half that is not multiplied by two, and adds them to counter
for digit in not_every_other_digit:
sum_of_digits_not_multiplied_by_two += digit
#Finally we can get the target sum, which is the sum of the two counters we have made above
target_sum = sum_of_digits_in_every_other_digit + sum_of_digits_not_multiplied_by_two
#If last digit of target sum is 0, the credit card number is legit
if target_sum % 10 == 0:
valid = True
return valid
#In this function we will determine which company has issued the credit card, and use our function luhns_algorithm to
#check if the credit card number is valid
def credit_card(num):
digits = 0
company = ""
number = num
valid = luhns_algorithm(num)
if valid == True:
while number > 1:
digits += 1
number /= 10
first_two_digits = num / 10 ** (digits - 2)
first_two_digits = math.floor(first_two_digits)
first_digit = first_two_digits / 10
if digits == 15:
if first_two_digits == 34 or first_two_digits == 37:
company = "AMEX"
elif digits == 13:
company = "VISA"
elif digits == 16 and first_digit == 4:
company = "VISA"
elif digits == 16 and 51 <= first_two_digits <= 55:
company = "MasterCard"
else:
return print("The credit card number is invalid.")
return print("The credit card is issued by " + company)
credit_card(4003600000000014)
#Output = The credit card is issued by VISA
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T12:41:38.253",
"Id": "505465",
"Score": "0",
"body": "There is a lot of redundant comments and blank lines. I would start there."
}
] |
[
{
"body": "<p>There's a tonne of intermediate variables that don't need to exist, as well as insisting that the credit card number be treated as an integer when a string is probably easier.</p>\n<p>Also, don't bake printing into your functions, and don't require that the company determination logic operate on a valid card. Add type hints, and this brings you to</p>\n<pre><code>from typing import Optional\n\n\ndef is_card_valid(num: str) -> bool:\n if not num.isdigit():\n return False\n\n total = sum(\n int(num[i])\n for i in range(1, len(num), 2)\n )\n\n for i in range(0, len(num), 2):\n d1, d2 = divmod(2*int(num[i]), 10)\n total += d1 + d2\n\n return total % 10 == 0\n\n\ndef get_card_company(num: str) -> Optional[str]:\n digits = len(num)\n\n if digits == 15:\n if num[:2] in {'34', '37'}:\n return 'AMEX'\n if num[:2] == '13':\n return 'VISA'\n\n elif digits == 16:\n if num[0] == '4':\n return 'VISA'\n if num[0] == '5' and num[1] in '12345':\n return 'MasterCard'\n\n\ncard = '4003600000000014'\nif is_card_valid(card):\n print('Card is valid')\n print('The credit card is issued by', get_card_company(card))\nelse:\n print('Card is invalid')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:46:50.197",
"Id": "256100",
"ParentId": "256078",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T09:55:03.817",
"Id": "256078",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "How can I shorten this program using Luhn's algorithm to check credit card number?"
}
|
256078
|
<p>I am writing a piece of code for C# Web Api, letting the clients to pass a column name and sort direction as parameter.
Although there are, like, 30-ish properties, so the following code (despite it works) gets ugly after a while.</p>
<p>What are my options to avoid repeating this seemingly same pieces of code?</p>
<pre><code>if (column == nameof(MyModel.ColumnA).ToLower())
{
if (parameters.IsOrderByAsc)
{
return queryResult.OrderBy(q => q.ColumnA);
}
return queryResult.OrderByDescending(q => q.ColumnA);
}
if (column == nameof(MyModel.ColumnB).ToLower())
{
if (parameters.IsOrderByAsc)
{
return queryResult.OrderBy(q => q.ColumnB);
}
return queryResult.OrderByDescending(q => q.ColumnB);
}
if (column == nameof(MyModel.ColumnC).ToLower())
{
if (parameters.IsOrderByAsc)
{
return queryResult.OrderBy(q => q.ColumnC);
}
return queryResult.OrderByDescending(q => q.ColumnC);
}
....
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T12:39:28.490",
"Id": "505464",
"Score": "2",
"body": "Please write an appropriate tile: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T13:12:14.453",
"Id": "505468",
"Score": "0",
"body": "A single switch-statement to replace each outer-if-statement and a function to do the inner-if-statement and returns should make this pretty short and simple. You could also create a dictionary where the key is the column name and the value is the expression (e.g. `q => q.ColumnA`). Then just look up the expression and plug it into the return value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T14:00:54.047",
"Id": "505471",
"Score": "1",
"body": "https://stackoverflow.com/a/233505/648075 ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:46:23.813",
"Id": "505519",
"Score": "0",
"body": "You probably want to use `ToLowerInvariant()`, otherwise the code will behave weirdly in certain locales (e.g. in Turkey `I` does not lowercase to `i`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T13:34:37.543",
"Id": "505561",
"Score": "0",
"body": "What is `queryResult`? An `IQueryable`, making the orderby go to the translated SQL? Maybe you can add a tag for the specific LINQ flavor you're using (like Entity Framework)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T13:36:02.717",
"Id": "505562",
"Score": "0",
"body": "@CodesInChaos The ordering is probably done by a database, so the collation will be all that matters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T19:13:45.070",
"Id": "505609",
"Score": "0",
"body": "@GertArnold I'm not talking about the ordering, I'm taking about the mapping from property names to properties."
}
] |
[
{
"body": "<p>If you're willing to use the <a href=\"https://archive.codeplex.com/?p=dynamiclinq\" rel=\"nofollow noreferrer\">DynamicLinq</a> library, the problem becomes trivial. It allows you to pass a string parameter to the <code>OrderBy</code> method, bypassing your entire logic:</p>\n<pre><code>queryResult.OrderBy(column)\n</code></pre>\n<p>If this is related to doing a SQL database lookup, if you think about it, the issue you're facing it a bit of a self-imposed issue, because you start from a string value and you're eventually going to generate a string value (in the SQL query). The issue you're facing is that standard LINQ forces you to map it to an actual property of the entity, which in this case is an unnecessary mapping which DynamicLinq allows you to bypass.</p>\n<p>If you want, you could add a bit of validation to confirm that the passed string is a known property of your entity type.</p>\n<pre><code>bool columnIsProperty = typeof(MyModel)\n .GetProperties()\n .Any(prop => prop.Name.ToLower() == column.ToLower());\n\nif(columnIsProperty)\n queryResult = queryResult.OrderBy(column);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:24:33.250",
"Id": "505487",
"Score": "0",
"body": "Change `typeof(MyModel).GetType().GetProperties()` to `typeof(MyModel).GetProperties()`. Also it can be cached to some field because Reflection operations aren't enough fast at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:32:03.977",
"Id": "505489",
"Score": "0",
"body": "@aepot Good catch, I had adapted a different piece of code and forgot to omit the `GetType()`. Caching might be relevant for frequent operations on e.g. an always-on service, but in scope of e.g. a web service where you reflect once for a web request, caching means retaining state, which brings more problems than it solves. I'd be more inclined to generate a list of properties on build instead of caching it at runtime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:50:15.760",
"Id": "505492",
"Score": "0",
"body": "web service can receive many rps (100? 1000? 10k?), btw if you you're fine with Reflection performance, allocating an array of strings is resulting in a GC job. `private static readonly string[] modelPropertyNames = typeof(MyModel).GetProperties().Select(prop => prop.Name.ToLower()).ToArray()` and then `bool columnIsProperty = modelPropertyNames.Any(name => name == column.ToLower())`. That is what means caching for me: storing few data that never changes in memory once and reuse then. Anyway it affects the performance, even for 1rps."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T11:41:14.283",
"Id": "256084",
"ParentId": "256079",
"Score": "5"
}
},
{
"body": "<p>If you don't want to pull in DynamicLinq its not a lot of Expression tree work to get exactly what OP is looking for. In the constructor getting the methods we need to call for the Queryable, I'm assuming this is IQueryable and not IEnumerable. If IEnumerable just swap all the Queryable for Enumerable. For the ToLower matching of the property using the BindingFlag.IgnoreCase. Also threw in ThenBy as a bonus as wasn't a lot of work.</p>\n<pre><code>public static class QueryableExtensions\n{\n private static readonly MethodInfo _orderBy;\n private static readonly MethodInfo _orderByDescending;\n private static readonly MethodInfo _thenBy;\n private static readonly MethodInfo _thenByDescending;\n\n static QueryableExtensions()\n {\n Func<IQueryable<object>, Expression<Func<object, object>>, IOrderedQueryable<object>> orderBy = Queryable.OrderBy;\n _orderBy = orderBy.Method.GetGenericMethodDefinition();\n orderBy = Queryable.OrderByDescending;\n _orderByDescending = orderBy.Method.GetGenericMethodDefinition();\n Func<IOrderedQueryable<object>, Expression<Func<object, object>>, IOrderedQueryable<object>> thenBy = Queryable.ThenBy;\n _thenBy = thenBy.Method.GetGenericMethodDefinition();\n thenBy = Queryable.ThenByDescending;\n _thenByDescending = thenBy.Method.GetGenericMethodDefinition();\n }\n\n public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string propertyName, bool orderByAscending = true)\n {\n return CreateExpression(source, propertyName, orderByAscending ? _orderBy : _orderByDescending);\n }\n\n public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, string propertyName, bool orderByAscending = true)\n {\n return CreateExpression(source, propertyName, orderByAscending ? _thenBy : _thenByDescending);\n }\n \n private static IOrderedQueryable<TSource> CreateExpression<TSource>(IQueryable<TSource> source, string propertyName, MethodInfo method)\n {\n var propInfo = typeof(TSource).GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) ?? throw new ArgumentException(nameof(propertyName));\n var methodInfo = method.MakeGenericMethod(typeof(TSource), propInfo.PropertyType);\n var sourceParam = Expression.Parameter(typeof(TSource), "source");\n var property = Expression.Property(sourceParam, propInfo);\n var lambda = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), propInfo.PropertyType), property, sourceParam);\n var call = Expression.Call(methodInfo, source.Expression, lambda);\n return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>(call);\n }\n}\n</code></pre>\n<p>Now can just call it like <code>return queryResult.OrderBy(column, parameters.IsOrderByAsc)</code></p>\n<p>This doesn't do nested properties but wouldn't be much work to make that w</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T04:04:37.843",
"Id": "256123",
"ParentId": "256079",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256123",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T10:57:12.523",
"Id": "256079",
"Score": "6",
"Tags": [
"c#",
"linq"
],
"Title": "C# - Linq - Techniques for avoiding repeating same pieces of code"
}
|
256079
|
<p>I'm "playing" with ARM assembly on a Raspberry Pi, reading various tutorials and posts to help - no, it's not a college assignment, I'm too old for college! I'm pleased with getting the following code to take a decimal value (between 0 and 255) and output the binary string equivalent to the screen using <code>scanf()</code> and <code>printf()</code> but curious to know though whether those more experienced would consider this a "naive" solution? Are there any "gotchas"? Any better ways of tackling the problem?</p>
<p>I reckon there should be a better way of declaring the string to hold the output and how the string is built from the LSB (using R9)</p>
<pre><code>/* dectobin2.s */
/* ------------------------------------------------------------ */
/* Converts a decimal number to binary and outputs to screen */
/* ============================================================ */
.data
.balign 4
value: .word 0
binStr: .asciz "00000000"
output: .asciz "%d in binary is %s\n"
title: .asciz "DECIMAL TO BINARY CONVERTER\n\n"
lr_temp: .word 0
lr_local: .word 0
prompt: .asciz "Enter a positive value (0-255) > "
pattern: .asciz "%d"
.text
@ function to convert given value into a binary string
decToBin:
@ save the link register
ldr r2, =lr_local
str lr, [r2]
@ set data values
mov r4, r0 @ value in r4 for processing
mov r9, #7 @ LSB position in output string
_loop:
@ repeated division by 2 2
movs r4, r4, lsr #1 @ divide by 2, set carry
bcs _odd @ if carry set, remainder is 1
_even:
mov r5, #0 @ remainder of 0
b _toString
_odd:
mov r5, #1 @ remainder of 1
_toString:
add r5, #48 @ convert remainder to ASCII
ldr r1, =binStr @ address of binary string
strb r5, [r1, r9] @ store remainder in string at pos in r9
sub r9, r9, #1 @ move to next position in output string
cmp r4, #0 @ reached zero?
ble _endloop
b _loop
_endloop:
@ restore the link register
ldr lr, =lr_local
ldr lr, [lr]
bx lr
.global main
main:
@ store the link register
ldr r1, =lr_temp
str lr, [r1]
@ print a title
ldr r0, =title
bl printf
_getValue:
@ get the value to convert
ldr r0, =prompt @ prep the arguments for scanf
bl printf
ldr r0, =pattern
ldr r1, =value
bl scanf
@ check for valid input (0-255)
ldr r0, =value
ldr r0, [r0]
cmp r0, #255 @ must be <= 255
bgt _getValue
cmp r0, #0 @ must be >= 0
blt _getValue
_isValid:
@ call the function, value is in R0
bl decToBin
@ display output
ldr r0, =output @ get address of output string
ldr r1, =value @ get the original value
ldr r1, [r1] @ for first parameter
ldr r2, =binStr @ get the binary string
bl printf @ print the result
@ restore the link register and exit
ldr lr, =lr_temp
ldr lr, [lr]
bx lr
.global printf
.global scanf
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Here are a number of things that may help you improve your program.</p>\n<h2>Understand the calling convention</h2>\n<p>The <a href=\"https://static.docs.arm.com/ihi0042/g/aapcs32.pdf\" rel=\"nofollow noreferrer\">procedure call standard</a> for ARM says that the registers r0, r1, r2, and r3 can be used and not restored by a called function. Further, if we don't alter <code>lr</code>, there's no need to preserve and then restore it. These are all clues for making your program more efficient.</p>\n<h2>Know your instruction set</h2>\n<p>The code currently contains these lines:</p>\n<pre><code> movs r4, r4, lsr #1 @ divide by 2, set carry\n bcs _odd @ if carry set, remainder is 1\n_even:\n mov r5, #0 @ remainder of 0\n b _toString\n_odd:\n mov r5, #1 @ remainder of 1\n_toString: \n add r5, #48 @ convert\n</code></pre>\n<p>That is terribly inefficient. We can simplify considerably:</p>\n<pre><code> mov r5, #48 @ start with ASCII '0'\n movs r4, r4, lsr #1 @ divide by 2, set carry\n adc r5, #0 @ add zero + carry\n \n</code></pre>\n<h2>Minimize branching</h2>\n<p>The code ends with this curious combination:</p>\n<pre><code> ble _endloop\n b _loop\n_endloop:\n</code></pre>\n<p>First, the comment suggests that we're looking for exactly zero and so we should be looking only at the zero flag (<code>beq</code> or <code>bne</code>) rather than doing a signed comparison with <code>ble</code>. Second, why not simply use a single instruction?</p>\n<pre><code> beq _loop\n</code></pre>\n<p>However, better, see the next suggestion.</p>\n<h2>Create reusable code</h2>\n<p>The code currently exits if the shifted value becomes zero. That works, but only once. In other words, if you use the routine to decode 255 and then again to decode the value 3, you will likely be surprised that your routine will falsely give the same binary string for both. The problem is that it relies on the <code>binStr</code> buffer to always contain a string of zeroes. A better approach is to explicitly set each byte of the buffer and instead use the counter you already have in <code>r9</code>. This shortens the code and makes it reusable.</p>\n<pre><code> subs r9, r9, #1 \n bpl _loop\n</code></pre>\n<h2>Move loop invariants outside the loop</h2>\n<p>Every iteration through the loop we load the <code>r1</code> register with the address of <code>binStr</code> even though <code>r1</code> is never changed within the loop. A more efficient approach would be to load <code>r1</code> once outside the loop.</p>\n<h2>Document register usage</h2>\n<p>One of the keys to being a good assembly language programmer is to carefully manage register use. The most basic requirement is to keep track of how you're using registers, and a good way to do that, both for yourself and future readers of the code is to document the use. Based on the observations in the first suggestion above, here's what I used:</p>\n<pre><code>@ Register usage: \n@ r0 - passed value\n@ r1 - pointer to current string digit\n@ r2 - decrementing digit offset\n@ r3 - the current digit\n</code></pre>\n<h2>Results</h2>\n<p>Using all of these suggestions, the resulting routine is only nine instructions.</p>\n<pre><code>decToBin:\n ldr r1, =binStr @ output string location\n mov r2, #7 @ start with the LSB \n_loop:\n mov r3, #48 @ start with ASCII zero\n movs r0, r0, lsr #1 @ divide by 2, set carry\n adc r3, #0 @ add the extracted bit\n strb r3, [r1, r2] @ store remainder in string at pos in r9\n subs r2, r2, #1 @ decrement counter\n bpl _loop @ end if it has gone negative\n bx lr\n</code></pre>\n<p>Armed with these suggestions (pun intended!) see if you can perform a similar cleanup on the rest of the code. In particular, there is a much more efficient way to check if the input value is in the appropriate range (hint: <code>movs r1, r0, lsr #8</code>).</p>\n<p>Also, just for fun, this answer was composed and tested entirely on a Raspberry Pi running on battery power.</p>\n<h2>Other ideas</h2>\n<p>A more generally useful routine would have the caller pass a buffer pointer and buffer length into which the program would put its result rather than using a fixed location. See if you can figure out how to modify the code to do that, and don't forget to place the terminating <code>\\0</code> character.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T16:19:17.720",
"Id": "506065",
"Score": "0",
"body": "Thank you Edward for the detailed comments, it's much appreciated. As I've done some further reading since posting I've now encountered the conditionals that can be suffixed to any of the instructions to remove the need to branch, as you've suggested - they're a nice touch! I shall revisit with your other tips - thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-20T15:42:40.127",
"Id": "256263",
"ParentId": "256087",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T12:29:32.697",
"Id": "256087",
"Score": "4",
"Tags": [
"assembly",
"arm"
],
"Title": "Decimal to binary conversion in ARM assembly"
}
|
256087
|
<p>I use Argo Workflows to dispatch lists of jobs defined in a CSV. I accomplish this by chaining a bunch templates together, which involves:</p>
<ul>
<li>Breaking up the CSV file into individual JSON objects</li>
<li>Parsing the JSON into parameters</li>
<li>Actually passing the parameters to individual pods</li>
</ul>
<p>The YAML which accomplishes this is:</p>
<pre class="lang-yaml prettyprint-override"><code>entrypoint: main
templates:
- name: main
steps:
- - name: get-inputs
# Produces the complete set of work units from the initial input
template: split-csv
arguments:
artifacts:
- name: csv-file
s3: retrieve csv from s3
- - name: process-each
# Iterates over the a set of work units produced by the previous step
template: compute-one
arguments:
parameters:
- name: index
value: "{{item}}"
artifacts:
- name: mappings
from: "{{steps.get-inputs.outputs.artifacts.json-data}}"
withSequence:
count: "{{steps.get-inputs.outputs.parameters.length}}"
- name: compute-one
# Processes a single work unit
inputs:
parameters:
- name: index
artifacts:
- name: mappings
steps:
- - name: get-work-item
# Retrieves the artifact references that are required to process a single unit of work
template: get-work-item
arguments:
parameters:
- name: index
value: "{{inputs.parameters.index}}"
artifacts:
- name: mappings
from: "{{inputs.artifacts.mappings}}"
- - name: big-compute
# Where the parameters accessed from the CSV get used.
template: my-compute-job
arguments:
parameters:
- name: param0
value: "{{steps.get-work-item.outputs.parameters.param0}}"
- name: param1
value: "{{steps.get-work-item.outputs.parameters.param1}}"
- name: param2
value: "{{steps.get-work-item.outputs.parameters.param2}}"
- name: get-work-item
# From a given JSON array, get the item at `index`, which is expected to be an object,
# and output the values of its keys to pass as parameters
inputs:
parameters:
- name: index
artifacts:
- name: mappings
path: /tmp/mappings.json
outputs:
parameters:
- name: param0
valueFrom:
path: /tmp/param0
- name: param1
valueFrom:
path: /tmp/param1
- name: param2
valueFrom:
path: /tmp/param2
script:
image: stedolan/jq
command: [sh]
source: |
jq -r '.[{{inputs.parameters.index}}].param0' {{inputs.artifacts.mappings.path}} > {{outputs.parameters.param0.path}}
jq -r '.[{{inputs.parameters.index}}].param1' {{inputs.artifacts.mappings.path}} > {{outputs.parameters.param1.path}}
jq -r '.[{{inputs.parameters.index}}].param2' {{inputs.artifacts.mappings.path}} > {{outputs.parameters.param2.path}}
- name: split-csv
# Given a CSV file, convert each row into a JSON-formatted object,
# and output the list all resulting objects as an artifact,
# and the length of this list as a parameter
inputs:
artifacts:
- name: csv-file
path: /tmp/input.csv
script:
image: python:alpine
command: [python]
source: |
from csv import reader
import json
with open("{{inputs.artifacts.csv-file.path}}", "r") as f:
rows = reader(f)
next(rows)
data = [ {"param0": r[0], "param1": r[1], "param2": r[2]} for r in list(rows) ]
with open("{{outputs.artifacts.json-data.path}}", "w") as f:
f.write(json.dumps(data))
with open("{{outputs.parameters.length.path}}", "w") as f:
f.write(str(len(data)))
outputs:
parameters:
- name: length
valueFrom:
path: /tmp/length
artifacts:
- name: json-data
path: /tmp/data.json
</code></pre>
<p>Is there a way to do this with fewer steps? I keep needing to paste some form of this into other Argo workflows I create. Is there some way to modularize it and import it?</p>
|
[] |
[
{
"body": "<p>There's no need to use <code>get-work-item</code> to iterate through the JSON.</p>\n<pre><code>apiVersion: argoproj.io/v1alpha1\nkind: Workflow\nspec:\n arguments:\n parameters:\n - name: s3-bucket\n - name: input-csv\n - name: output-path\n\n volumes:\n - name: workdir\n emptyDir: {}\n\n entrypoint: main\n\n templates:\n - name: main\n steps:\n - - name: get-inputs\n # Produces the complete set of work units from the initial input\n template: split-csv\n arguments:\n artifacts:\n - name: csv-file\n s3:\n endpoint: s3.amazonaws.com\n bucket: "{{workflow.parameters.s3-bucket}}"\n key: "{{workflow.parameters.input-csv}}"\n\n - - name: process-each\n # Iterates over the a set of work units produced by the previous step\n template: big-compute\n arguments:\n parameters:\n - name: param0\n value: "{{item.param0}}"\n - name: param1\n value: "{{item.param1}}"\n - name: param2\n value: "{{item.param2}}"\n withParam: "{{steps.get-inputs.outputs.parameters.json-data}}"\n \n - name: split-csv\n # Given a CSV file, convert each row into a JSON-formatted object,\n # and output the list all resulting objects as an artifact,\n # and the length of this list as a parameter\n inputs:\n artifacts:\n - name: csv-file\n path: /tmp/input.csv\n outputs:\n parameters:\n - name: json-data\n valueFrom:\n path: /tmp/data.json\n script:\n image: python:alpine\n command: [python]\n source: |\n from csv import reader\n import json\n from pathlib import Path\n import os\n\n with open("{{inputs.artifacts.csv-file.path}}", "r") as fi:\n rows = reader(fi)\n next(rows)\n data = [{"param0": r[0], "param1": r[1], "param2": r[2]} for r in list(rows)]\n\n with open("{{outputs.parameters.json-data.path}}", "w") as fi:\n json.dump(data, fi)\n\n - name: big-compute\n inputs:\n parameters:\n - name: param0\n - name: param1\n - name: param2\n outputs:\n artifacts:\n - name: collected-outputs\n path: /workdir/out\n archive:\n none: {}\n s3:\n endpoint: s3.amazonaws.com\n bucket: "{{workflow.parameters.s3-bucket}}"\n key: "{{workflow.parameters.output-path}}"\n script:\n image: fedora:33\n command: [bash]\n source: |\n set -xe\n\n mkdir /workdir/out && cd /workdir/out\n echo "{{inputs.parameters.param0}},{{inputs.parameters.param1}},{{inputs.parameters.param2}}" \\\n > {{inputs.parameters.param0}}_{{inputs.parameters.param1}}_{{inputs.parameters.param2}}\n\n resources:\n requests:\n memory: 30Mi\n cpu: 20m\n limits:\n memory: 30Mi\n cpu: 20m\n volumeMounts:\n - name: workdir\n mountPath: /workdir\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T20:08:16.503",
"Id": "261528",
"ParentId": "256091",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T14:07:03.313",
"Id": "256091",
"Score": "0",
"Tags": [
"argo-workflows"
],
"Title": "Dispatch a pod for each entry in CSV"
}
|
256091
|
<p>Argo Workflows facilitates executing a set of actions in Kubernetes. Workflows are <a href="https://github.com/argoproj/argo-workflows" rel="nofollow noreferrer">implemented as Kubernetes Custom Resource Definitions</a> (CRDs). The actions may be defined by connecting "steps" or by describing a directed acyclic graph (DAG).</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T14:16:05.603",
"Id": "256092",
"Score": "0",
"Tags": null,
"Title": null
}
|
256092
|
Use when asking how to improve YAML-based Argo Workflows.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T14:16:05.603",
"Id": "256093",
"Score": "0",
"Tags": null,
"Title": null
}
|
256093
|
Code specifically targeting processors designed by ARM. Generally useful in conjunction with [assembly], but sometimes relevant for other languages.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T15:28:47.707",
"Id": "256098",
"Score": "0",
"Tags": null,
"Title": null
}
|
256098
|
<p>This is my attempt of implementing an efficient, cache-friendly, vector for polymorphic objects.</p>
<p>From now on I will refer to "virtual functions" as functions which are dependent on an object's underlying dynamic type, though they might not be strictly marked "virtual".</p>
<h2>Memory model of polymorphic vector</h2>
<p>Rather than storing a vector of <code>std::unique_ptr</code> (or other smart pointer) which points to an object on the heap, I store polymorphic objects of the same dynamic type together in the same vector (i.e. I have a vector of Bases and a vector of Derived). A tuple stores each vector of each dynamic type.</p>
<p>However, this has the downside that my polymorphic vector is unordered, so I store the vector <code>index_map</code> which stores the necessary information to represent the order.</p>
<p>Also, I store a vector of pointers to the base class (named <code>ptrs</code>) for efficient calls to non-virtual member functions.</p>
<h2>Calling a virtual function at a given index</h2>
<p>First, I lookup in <code>index_map</code> the type number and index number of the object. I then create some sort of static constexpr v-table of function pointers (in the function<code>apply_func_to_tuple</code>). All in all, this requires two levels of indirection, resulting in the same performance as a virtual function.</p>
<hr />
<pre><code>
/* Helper functions */
/* This set functions applies a function an element of a tuple given a runtime index */
template<typename R, int N, class T, class F>
R apply_one(T& p, F& func)
{
static_assert(std::is_same<typename std::result_of<F(decltype(std::get<N>(p)))>::type, R>::value, "Wrong return type for polymorphic function");
return func(std::get<N>(p) );
}
template<typename R, class T, class F, int... Is>
R apply_func_to_tuple(T& p, int index, F& func, seq<Is...>)
{
using FT = R(T&, F&);
/* This is the magic, a v-table is built on the spot here. */
static constexpr FT* arr[] = { &apply_one<R, Is, T, F>... };
return arr[index](p, func);
}
template<typename R, class T, class F>
R apply_func_to_tuple(T& p, int index, F&& func)
{
return apply_func_to_tuple<R>(p, index, func, gen_seq<std::tuple_size<T>::value>{});
}
/* Helper class to find the index of a type from a tuple type list at compile - time */
template <class T, class Tuple>
struct Index;
template <class T, class... Types>
struct Index<T, std::tuple<T, Types...>> {
static consteval int getValue() {
return 0;
}
};
template <class T, class U, class... Types>
struct Index<T, std::tuple<U, Types...>> {
static consteval int getValue() {
return 1 + Index<T, std::tuple<Types...>>::getValue();
}
//static const std::size_t value = 1 + Index<T, std::tuple<Types...>>::value;
};
/* Functions to calculate log at compile time, needed later */
constexpr unsigned floorlog2(unsigned x)
{
return x == 1 ? 0 : 1+floorlog2(x >> 1);
}
constexpr unsigned ceillog2(unsigned x)
{
return x == 1 ? 0 : floorlog2(x - 1) + 1;
}
/* The element class of my "order vector" , I use a bitfield to pack as much data as I can in 8 bytes */
template <typename Base, typename ...Ts>
struct IndexElement {
unsigned long type : ceillog2(sizeof...(Ts) + 1);
unsigned long index: 64 - ceillog2(sizeof...(Ts) + 1);
};
/* Start the class */
template <typename Base, typename ...Ts>
struct PolymorphicVector {
public:
/* Vector which represents the order of the objects */
std::vector<IndexElement<Base, Ts...>> index_map;
/* This contains the actual objects, as you can see they are stored without order, which is why index_map is needed to represent the order */
std::tuple<std::vector<Base>, std::vector<Ts>...> vec;
/* This vector seems a little bit redundant, but is used to apply efficiently a non-virtual method at a given index */
std::vector<Base*> ptrs;
public:
/* Apply a "virtual" functor at a given index */
template <typename Functor>
decltype(auto) apply(int index, Functor&& fn) {
auto true_index = index_map[index].index;
return apply_func_to_tuple<typename std::result_of<Functor(Base&)>::type>
(vec , index_map[index].type , [true_index, &fn] (auto& vec) {return fn(vec[true_index]);});
}
/* Apply a virtual functor to all the elements of my vector in order */
template <typename Functor>
void ordered_apply(Functor&& fn) {
for (int i = 0; i < index_map.size(); i++) {
apply(i, std::move(fn));
}
}
/* Apply a non-virtual method at an index */
template <typename Functor>
inline decltype(auto) apply_method(unsigned long index, Functor&& fn) {
return fn(ptrs[index]);
}
private:
/* Helper methods */
template <typename Functor, typename Head, typename... Tail>
void unordered_apply(Functor& fn) {
for (int i = 0; i < std::get<std::vector<Head>>(vec).size(); i ++) {
fn(std::get<std::vector<Head>>(vec)[i]);
}
unordered_apply<Functor, Tail...>(fn);
}
template <typename Functor>
void unordered_apply(Functor& fn) {
}
public:
/* Apply a functor to all the elements in my vector without committing to a specific order. */
template <typename Functor>
void unordered_apply(Functor&& fn) {
unordered_apply<Functor, Base, Ts...>(fn);
}
/* Add an element to the vector */
template <typename Derived>
PolymorphicVector& append(const Derived& derived) {
// Check if reallocation is necessary
if (std::get<std::vector<Derived>>(vec).capacity() == std::get<std::vector<Derived>>(vec).size()) {
Derived* start = &std::get<std::vector<Derived>>(vec)[0];
std::get<std::vector<Derived>>(vec).push_back(derived);
auto offset = &std::get<std::vector<Derived>>(vec)[0] - start;
// Reinitialise invalidated pointers.
for (int i = 0; i < index_map.size(); i ++) {
ptrs[i] += (index_map[i].type == Index<Derived, std::tuple<Base, Ts...>>::getValue()) * offset;
}
index_map.push_back(IndexElement<Base, Ts...>{Index<Derived, std::tuple<Base, Ts...>>::getValue(), std::get<std::vector<Derived>>(vec).size() - 1});
ptrs.push_back(static_cast<Base*>(&std::get<std::vector<Derived>>(vec).back()));
return *this;
}
std::get<std::vector<Derived>>(vec).push_back(derived);
ptrs.push_back(static_cast<Base*>(&std::get<std::vector<Derived>>(vec).back()));
index_map.push_back(IndexElement<Base, Ts...>{Index<Derived, std::tuple<Base, Ts...>>::getValue(), std::get<std::vector<Derived>>(vec).size() - 1});
return *this;
}
template <typename Derived>
std::vector<Derived>& getVectorOf() {
return std::get<Derived>(vec);
}
template <typename Derived>
inline bool checkIndexIs(unsigned int index) {
return index == Index<Derived, std::tuple<Base, Ts...>>::getValue();
}
private:
template <typename Head, typename First, typename... Tail>
void reserve(unsigned long num) {
std::get<std::vector<Head>>(vec).reserve(num);
reserve<First, Tail...>(num);
}
template <typename Last>
void reserve(unsigned long num) {
std::get<std::vector<Last>>(vec).reserve(num);
}
public:
// Reserve
void reserve(unsigned long num) {
reserve<Base, Ts...>(num);
}
};
</code></pre>
<p>Example use case:</p>
<pre><code>struct Base {
virtual int a_method(int x) {
z += x;
std::cout << z;
}
int z;
};
struct Derived: public Base {
virtual int a_method(int x) {
z*=x;
std::cout << z;
}
};
int main() {
PolymorphicVector<Base, Derived> x;
x.append(Derived{5});
x.append(Base{10});
x.apply(0, [] (auto& base) { return base.a_method(5);}); // 25
return 0;
}
</code></pre>
<h2>Advantages of this implementation over a vector pointer-to-base</h2>
<ul>
<li><p>Huge performance increase when applying a functor to all the elements of my vector without committing to a specific order (4 times faster for a non-virtual method, 20 times faster for a virtual method). This is due to cache-friendliness and not actually having any dynamic dispatch in the virtual case.</p>
</li>
<li><p>Retains all the type information (i.e. we can retrieve all elements of a certain type, check if an object at a certain index has a certain dynamic type)</p>
</li>
<li><p>Small performance increase when adding objects to the vector (heap memory does not need to be found for each object, thereby decreasing heap fragmentation)</p>
</li>
<li><p>Does not require virtual methods to achieve polymorphic behaviour (my implementation allows the use of virtual free function/ functors)</p>
</li>
<li><p>Same performance for applying methods/ virtual methods at a given index.</p>
</li>
</ul>
<h2>Drawbacks</h2>
<ul>
<li><p>Must specify all the polymorphic types you want to store (as opposed to a vector of <code>std::unique_ptr<Base></code> where you can store all the types derived from a single type)</p>
</li>
<li><p>My implementation uses a less user-friendly "visitor" pattern to modify its elements.</p>
</li>
<li><p>Small overhead when the vector undergoes reallocation</p>
</li>
<li><p>Each element is not polymorphic in itself, the vector is polymorphic.</p>
</li>
</ul>
<h2>Questions for code review:</h2>
<ol>
<li>Is the code well defined and portable (no UB) ?</li>
<li>Is my implementation as performant as it could be?</li>
<li>Is my implementation as memory-efficient as it could be?</li>
<li>Can my implementation be made a bit more user-friendly?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T13:03:55.143",
"Id": "505792",
"Score": "0",
"body": "Looks interesting! Besides your core questions: This part void unordered_apply(Functor&& fn) --> I think, you've forgotten to apply std::forward to your forwarding/universal reference within the function body!?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T13:12:00.390",
"Id": "505793",
"Score": "0",
"body": "And this might be a mistake: template <typename Functor>\n void ordered_apply(Functor&& fn) { --> there you are always moving the functor for each array element but you can only do that for the last element. The robust clean solution might require some kind of a case separating forwarding proxy helper I think: always forward the const ref for const ref case, move for the rvalue case but only for the last element/index of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T13:55:38.680",
"Id": "505803",
"Score": "0",
"body": "@Secundi Yes, I should be more careful with my r-value references / universal references ... I'm a bit sloppy with it. For your second comment, I think the solution would be to have a second overload of \"Polymorphic::apply(int index, Functor& func)\" taking a reference so that my the functor r-value reference in ordered_apply could be taken by reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T13:56:38.337",
"Id": "505804",
"Score": "0",
"body": "@Secundi What do you think of my implementation/ memory model of my vector? Could it be improved. Feel free to ask questions if further clarifications are needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-20T17:17:55.560",
"Id": "505884",
"Score": "0",
"body": "I'm going to write an answer here soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T13:43:56.653",
"Id": "506055",
"Score": "0",
"body": "@Secundi Ok thanks!"
}
] |
[
{
"body": "<p>A short analysis of some things that are quite clear to me:</p>\n<h2>Rvalues and Forwarding references</h2>\n<p>At first as already mentioned within the comments, you should refer to a <strong>clean move-semantic/forwarding scheme</strong>. For universal/forwarding references, only refer to <code>std::forward</code>. If no move semantic is effectively involved for all cases, do not refer to it: neither explicit rvalue usage nor forwarding reference usage. Otherwise, it's quite hard to follow data ownership flows for instance, at latest when your code expands later on.</p>\n<p>Moving data for the last iteration step of a loop:</p>\n<pre><code> template <typename Functor>\n void ordered_apply(Functor&& fn) {\n for (int i = 0; i < index_map.size(); i++) {\n apply(i, std::move(fn));\n }\n }\n</code></pre>\n<p>As already mentioned, this is wrong as soon as the functors from calling side are rvalues effectively. You can simply correct it "inline" via</p>\n<pre><code>apply(i, i == index_map.size() - 1 ? std::forward<Functor>(fn) : fn);\n</code></pre>\n<p>The correct behavior here is ensured by the standard, but requires a further temporary in between. Therefore I prefer it more explicitly:</p>\n<pre><code>for (int i = 0; i < index_map.size(); i++) {\n if (i == index_map.size() - 1)\n apply(i, std::forward<Functor>(fn));\n else\n apply(i, fn);\n}\n</code></pre>\n<p>But since this all is a no-op for the const reference argument case, the better overall design approach is to force a clean rvalue vs. lvalue separation via an internal helper struct and write the operations there in a very explicit way:</p>\n<pre><code>template <typename Functor>\nstruct CategorizedApplyForwarder\n{\n // implement doApply(Functor&& fnc);\n // implement doApply(const Functor& fnc);\n};\n</code></pre>\n<p>The first overload would then allow the move for the last element, the second would simply call the final <code>apply()</code> function with your arguments by const reference semantics.</p>\n<p>But since <code>apply()</code> doesn't really take ownership,</p>\n<pre><code>template <typename Functor>\n decltype(auto) apply(int index, Functor&& fn) {\n\n auto true_index = index_map[index].index;\n\n return apply_func_to_tuple<typename std::result_of<Functor(Base&)>::type>\n (vec , index_map[index].type , [true_index, &fn] (auto& vec) {return fn(vec[true_index]);});\n }\n</code></pre>\n<p>the move/forwarding-semantics are no-ops. Being confident about the semantics can prevent you from a lot of trouble in doubt.</p>\n<h2>The concrete questions</h2>\n<blockquote>\n<p>Is the code well defined and portable (no UB) ?</p>\n</blockquote>\n<p>Except the rvalue issues from above, I'd say yes so far. In detail, you should ensure that your subscript operator usage (index-based) is range-safe always. I didn't analyze that deep in detail here. What you should reconsider is the general question about <strong>exception safety</strong>. As far as I know, this is almost one of the most important questions why the standard avoids excessively optimized containers in general.</p>\n<blockquote>\n<p>Is my implementation as performant as it could be?</p>\n</blockquote>\n<p>That question is not specific enough :) If you mean performance in terms of what the actual code is trying to achieve (line-wise granular), I'd say there are not obvious issues here. Maybe this line could be further improved via emplace_back usage:</p>\n<pre><code>index_map.push_back(IndexElement<Base, Ts...>{Index<Derived, std::tuple<Base, Ts...>>::getValue(), std::get<std::vector<Derived>>(vec).size() - 1});\n</code></pre>\n<p>In terms of general performance behavior, you should distinguish at first, what the main purposes of your vector are in detail and how the general proportionality between the advantages and drawbacks should be. A deeper analysis here can become quite intensive in doubt. Accidental vs. theoretical complexity analysis is an important keyword here, as cache-line behavior is in doubt.</p>\n<blockquote>\n<p>Is my implementation as memory-efficient as it could be?</p>\n</blockquote>\n<p>Similar to the performance question, the devil is in the details. But from your internals only seen in general, I'd say you're quite fine since you refer to contiguous storage of "direct objects" only.</p>\n<blockquote>\n<p>Can my implementation be made a bit more user-friendly?</p>\n</blockquote>\n<p>I'd hide the internals of <code>PolymorphicVector</code> as far as possible. Make them private? I also miss a public <code>clear()</code> function.</p>\n<p>Compared to the common visitor approach, I really have to say that I prefer the common visitor on a <code>std::vector</code> of variants in terms of design principles and explicit usage. But I know that the common visitor approach is not as efficient as one might hope it is.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T10:07:14.600",
"Id": "256433",
"ParentId": "256101",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256433",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:18:27.017",
"Id": "256101",
"Score": "4",
"Tags": [
"c++",
"performance",
"cache",
"polymorphism",
"c++20"
],
"Title": "Efficient vector-like polymorphic container which retains type information"
}
|
256101
|
<p>I got an initial array, I am checking against another array to find how many objects have at least one instance of the <code>Domain</code> in data.</p>
<p>I wonder if there is a more performant way to achieve the same goal.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
{
Domain: 'google.com',
'# Reocurring Domains': 0
},
{
Domain: 'apple.com',
'# Reocurring Domains': 0
},
{
Domain: 'facebook.com',
'# Reocurring Domains': 0
}
]
const domains = [
{
'google.com': true,
'microsoft.com': true,
'google.com': true
},
{
'apple.com': true,
'microsoft.com': true,
'twitter.com': true
},
{
'facebook.com': true,
'apple.com': true,
'facebook.com': true
}
]
for (const obj of data) {
let count = 1
for (const entry of domains) {
if (entry[obj.Domain]) {
obj['# Reocurring Domains'] = count++
}
}
}
console.log(data)</code></pre>
</div>
</div>
</p>
<p>In there any way to this with a more performant approach?</p>
|
[] |
[
{
"body": "<p>You could create a look up table (a simple object) where you can pre calculate the amount of times a domain is in the repeated in the domains array, this reduces the algorithmic complexity of your current solution which is <code>n * m</code> (dataElements * domainElements)</p>\n<p>Whereas my suggestion has a lower complexity of <code>(n + m)</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = [\n {\n Domain: 'google.com',\n '# Reocurring Domains': 0\n },\n {\n Domain: 'apple.com',\n '# Reocurring Domains': 0\n },\n {\n Domain: 'facebook.com',\n '# Reocurring Domains': 0\n }\n]\n\nconst domains = [\n {\n 'google.com': true,\n 'microsoft.com': true,\n 'google.com': true\n },\n {\n 'apple.com': true,\n 'microsoft.com': true,\n 'twitter.com': true\n },\n {\n 'facebook.com': true,\n 'apple.com': true,\n 'facebook.com': true\n }\n]\n\nconst domainsObj = {}\n\ndomains.forEach(domain => {\n Object.keys(domain).forEach(key => key in domainsObj ? domainsObj[key] += 1: domainsObj[key] = 1)\n})\n\ndata.forEach(element => element['# Reocurring Domains'] = domainsObj[element.Domain]);\n\nconsole.log(data);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This approach increases memory usage, but improves calculation speed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T10:15:21.130",
"Id": "505543",
"Score": "0",
"body": "Thanks Daniel, when I check in jsbench, it says otherwise https://jsbench.me/7lkl9a1bf5/2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T22:29:45.760",
"Id": "505617",
"Score": "0",
"body": "Well for a small amount of data it could be the case that this approach is not that good, but if we consider the case that your data is going to be large enough, this solution should be better :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:48:28.460",
"Id": "256119",
"ParentId": "256102",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T16:25:18.623",
"Id": "256102",
"Score": "1",
"Tags": [
"javascript",
"performance",
"node.js"
],
"Title": "Lookup an array against another with performance"
}
|
256102
|
<p>I made a very simple interpreter of the untyped lambda calculus in Coq.</p>
<p>I'm still very new with formal methods and I'm sure I'm doing a lot of things very wrong.</p>
<p>The spec is also very very weak currently. For example, a bug with the stack fully permitted by the spec caused an infinite loop.</p>
<p>Fuller repository here that contains a bit of Haskell to actually run the interpreter:</p>
<p><a href="https://github.com/sstewartgallus/experimenting-with-coq" rel="nofollow noreferrer">https://github.com/sstewartgallus/experimenting-with-coq</a></p>
<pre><code>Import IfNotations.
Class EqDec {v : Set} := {
eq_decide (x y : v) : {x = y} + {x <> y}
}.
Section term.
(* I define terms in a parameteric higher order abstract style.
As we go along variables become a sort of address/pointer.
*)
Variable v : Set.
Inductive term :=
| var (_ : v)
| pass (_ : term) (_ : term)
| lam (_ : v -> term)
.
Declare Custom Entry lam.
Notation "_{ e }" := e (e custom lam at level 99).
Notation "x" := x (in custom lam at level 0, x constr at level 0).
Notation "f x" := (pass f x) (in custom lam at level 1, left associativity).
Notation "'fun' x => y" :=
(lam (fun x => y)) (in custom lam at level 90,
x ident,
y custom lam at level 99,
left associativity).
Notation "( x )" := x (in custom lam, x at level 99).
Notation "${ x }" := x (in custom lam, x constr at level 0).
Coercion var : v >-> term.
(* My intuition is that a stack is kind of like a one hole context/evaluation context.
An alternate representation might be:
Definition term' := term -> term.
Definition hole : term' := fun x => x.
Definition lpass (k : term') (e : term) : term' := fun x =>
pass (k x) e.
I'm not totally sure which is better.
*)
Inductive term' :=
| hole
| lpass (_ : term') (_ : term).
Record ck := { control : term ; kont : term' }.
Notation " 'E' [ h | e ]" := {| control := e ; kont := h |} (e custom lam).
(* We use a very simple model of the heap as a function.
Note that this very simple model leaks memory.
*)
Definition heap := v -> term.
Record state := { store : heap ; local : ck }.
(*
I used the turnstile before while figuring things out but really this is a store not an environment.
I need to think up better notation/denotation.
fun store => E[kont|control] ?
*)
Notation "s |- ck" := {| store := s ; local := ck |} (at level 70).
Definition put `{EqDec v} old x e : heap:=
fun x' => if eq_decide x x' then e else old x'.
Reserved Notation "s0 ~> s1 " (at level 80).
Variant step: state -> state -> Prop :=
| step_var s (x: v) k :
s |- E[k| x] ~> s |- E[k| ${s x}]
| step_pass s k e0 e1 :
s |- E[k| e0 e1] ~> s |- E[lpass k e1| e0]
| step_lam `{EqDec v} s k f x e:
s |- E[lpass k e| ${lam f}] ~> put s x e |- E[k|${f x}]
where "st ~> st'" := (step st st').
(* FIXME I need to think of a less misleading name, the spec is very weak currently *)
(*
If an interpreter takes a step (and succeeds!) then that implies that must have been a valid state transition.
*)
Definition valid (tick : state -> option state) := forall c s k,
exists c' s' k',
(tick (s |- E[k|c]) = Some (s |- E[k|c])) -> (s |- E[k|c]) ~> (s' |- E[k'|c']).
(* We use an old trick of lazily threading through new variables *)
CoInductive font : Set := { head : v ; left : font ; right : font }.
Fixpoint go `{EqDec v} (fnt : font) s k c :=
match c with
| var x => Some (s |- E[k |${s x}])
| _{ c0 c1 } => Some (s |- E[lpass k c1 | c0])
| lam f =>
if k is lpass k' e0
then
let x := head fnt in
go (right fnt) (put s x e0) k' (f x)
else None
end.
Definition go_valid `{EqDec v} fnt : valid (fun st => go fnt (store st) (kont (local st)) (control (local st))).
intros c s k.
cbn.
(* Perform induction over all possible cases of control, then all cases of the stack *)
induction c.
+ cbn.
eexists (s v0).
eexists s.
eexists k.
intro.
apply (step_var s v0 k).
+ cbn.
eexists c1.
eexists s.
eexists (lpass k c2).
intro.
apply (step_pass s k c1 c2).
+ cbn.
induction k.
* (* I'm not precisely sure why we have to introduce an arbitrary term here but identity works well enough. *)
eexists _{ fun x => x }.
eexists s.
eexists hole.
discriminate.
* eexists (t (head fnt)).
eexists (put s (head fnt) t0).
eexists k.
intro.
eapply (step_lam s k t (head fnt) t0).
Qed.
End term.
(* My language of choice is Haskell but a runtime of Ocaml or Scheme might be preferable. Not sure. *)
Require Extraction.
Extraction Language Haskell.
Extract Inductive bool => "Prelude.Bool" ["Prelude.True" "Prelude.False"].
Extract Inductive sumbool => "Prelude.Bool" ["Prelude.True" "Prelude.False"].
Extract Inductive sumor => "Prelude.Maybe" ["Prelude.Just" "Prelude.Nothing"].
Extract Inductive option => "Prelude.Maybe" ["Prelude.Just" "Prelude.Nothing"].
Extract Inductive prod => "(,)" ["(,)"].
Extract Inductive unit => "()" ["()"].
Extract Inductive list => "[]" ["[]" "(:)"].
Extraction "./Step.hs" go.
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T19:54:36.950",
"Id": "256108",
"Score": "0",
"Tags": [
"interpreter",
"coq"
],
"Title": "Call by name untyped lambda calculus interpreter in Coq"
}
|
256108
|
<p>I have solved the task of</p>
<blockquote>
<p>Delete the companies that made the least number of flights.</p>
</blockquote>
<p>the visual table diagram is <a href="https://drawsql.app/sql-academy-1/diagrams/airo?ref=embed" rel="nofollow noreferrer">here</a>. The exercise is <a href="https://sql-academy.org/en/trainer/tasks/55" rel="nofollow noreferrer">here</a></p>
<p>This is my source code -it's "arrow antipattern" , what is more elegant solution?</p>
<p>the inner most counts num of flights and groups by company, this is used to compare and find the actual minimum, then just select company names and delete.</p>
<pre><code>DELETE FROM company
WHERE name IN (SELECT name
FROM (SELECT name
FROM trip
INNER JOIN company
ON trip.company = company.id
GROUP BY name
HAVING Count(trip.id) = (SELECT Min(kolv) AS mini
FROM (SELECT
Count(trip.id) AS kolv
FROM trip
INNER JOIN company
ON trip.company
=
company.id
GROUP BY name
ORDER BY kolv)k)) o)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:12:07.783",
"Id": "510307",
"Score": "1",
"body": "\"companies\" and \"least\"?? One company? Several? What cutoff do you want?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:16:11.167",
"Id": "510309",
"Score": "0",
"body": "Delete from the table `company` only? Won't leave dangling references in `trip`? Maybe the task should be \"Delete the company with the _least_ number of flights, plus all associated information.\" But that would probably require 4 `DELETEs`, one per table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:24:23.393",
"Id": "510310",
"Score": "1",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:26:08.017",
"Id": "510312",
"Score": "0",
"body": "@RickJames According to [the linked exercise](https://sql-academy.org/en/trainer/tasks/55), deleting from `Company` only is sufficient, even it leaves dangling references. I verified this by checking @ERJAN's provided query, which returned \"Right answer\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:26:11.460",
"Id": "510313",
"Score": "0",
"body": "Why do you do `SELECT name FROM (SELECT name FROM trip`?"
}
] |
[
{
"body": "<p>If you can with MySQL 8.0, use the WITH Common Table Expression to simplify this query.</p>\n<p><a href=\"https://dev.mysql.com/doc/refman/8.0/en/with.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/refman/8.0/en/with.html</a></p>\n<p>The idea is to extract out the nested queries into ones in the WITH statement before the main query and then use them just like tables in the main query.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:43:58.427",
"Id": "256118",
"ParentId": "256110",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Use the multi-table flavor of <code>DELETE</code>. Why? To avoid the "arrow". And possibly the performance will be better.</li>\n<li>Avoid <code>IN ( SELECT ... )</code>; instead, try to use <code>JOIN</code> (or maybe <code>LEFT JOIN</code>). The Optimizer has been notoriously poor at optimizing <code>IN (SELECT...)</code>. I don't know whether it will do a good job here -- please add <code>EXPLAIN SELECT ...</code>.</li>\n<li>Alternatively, do the task in steps -- Create a temp table with, say, the innermost pair of queries, then use that temp in the rest. When doing this, be sure to explain what that temp table represents. I make this suggestion because my head is still spinning from the "arrow".</li>\n<li>Use CTE, if available, instead of a temp table. (There is a lot of overlap in the benefits/drawbacks between temp tables and CTEs. CTEs are the "modern" answer, where applicable.)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T06:50:50.087",
"Id": "510305",
"Score": "0",
"body": "Welcome to CodeReview. Could you please extend your suggestions with reasonings? Either by explaining yourself why should we prefer *x* over *y* Or by providing links about the related subjects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:10:58.593",
"Id": "510306",
"Score": "1",
"body": "@PeterCsala - Maybe my added text will help. No, I don't happen to have any link to share. Mostly I depend on 22 years of using MySQL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:15:31.197",
"Id": "510308",
"Score": "0",
"body": "That's perfect, thank you. Enjoy your time here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T03:34:20.983",
"Id": "258826",
"ParentId": "256110",
"Score": "2"
}
},
{
"body": "<ul>\n<li>If you look at the visual table diagram on the site you linked, for the <code>Company</code> table, the <code>id</code> is the primary key and therefore is guaranteed to be unique for each row in the table. <code>name</code>, on the other hand, is not guaranteed to be unique. So in your query, you should be grouping and deleting companies by their <code>id</code>, not by their <code>name</code>.</li>\n<li>Your query seems to be doing the work of counting the number of trips per company <em>twice</em> (once at the part <code>HAVING Count(trip.id)</code> and again at the part <code>Count(trip.id) AS kolv</code>) which is not necessary.</li>\n<li>As @Flavian and @RickJames have mentioned, refactoring your query to use Common Table Expressions will save it from the arrow anti-pattern, and make it much more readable.</li>\n</ul>\n<p>An example refactor:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>WITH TripsPerCompany AS (\n SELECT company, COUNT(id) AS num_trips FROM Trip GROUP BY company\n)\n\n,CompaniesWithTheFewestTrips AS (\n SELECT company\n FROM TripsPerCompany\n WHERE num_trips = (SELECT MIN(num_trips) FROM TripsPerCompany)\n)\n\nDELETE Company\nFROM Company\nJOIN CompaniesWithTheFewestTrips\nON Company.id = CompaniesWithTheFewestTrips.company;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T08:25:08.140",
"Id": "258831",
"ParentId": "256110",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T20:34:43.070",
"Id": "256110",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "Delete companies with the least number of flights"
}
|
256110
|
<p>I'm new to JavaScript, and I made a <a href="https://en.wikipedia.org/wiki/Discord_(software)" rel="nofollow noreferrer">Discord</a> bot using <a href="https://discord.js.org/" rel="nofollow noreferrer">discord.js</a> that serves food and drinks and replies without the need of a prefix. My issue is that I want to try cleaning up the code and get rid of all the if-statements, but I don't know how to do so.</p>
<pre><code>bot.on("message", message => {
const reply = [
"Here's your order!",
"Enjoy!",
"Here you go!",
"Let me know if you need anything else!",
"You've been served.",
"That'll be $3.50.",
"That'll be $5.50",
];
const response = reply[Math.floor(Math.random() * reply.length)];
if (message.content.toLowerCase().includes("order coffee")) {
message.channel.send("Coming right up!").then(msg => {
msg.delete({ timeout: 5000 })
})
.catch(console.error);
setTimeout(function(){
message.reply(response);
message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FCoffee%20cropped.gif?v=1613444146008");
}, 5000);
}
if (message.content.toLowerCase().includes("order latte")) {
message.channel.send("Coming right up!").then(msg => {
msg.delete({ timeout: 5000 })
})
.catch(console.error);
setTimeout(function(){
message.reply(response);
message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FLatte.gif?v=1613444145762");
}, 5000);
}
if (message.content.toLowerCase().includes("order muffin")) {
message.channel.send("Coming right up!").then(msg => {
msg.delete({ timeout: 5000 })
})
.catch(console.error);
setTimeout(function(){
message.reply(response);
message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FMuffin.gif?v=1613444146225");
}, 5000);
}
if (message.content.toLowerCase().includes("order strawberry cake roll")) {
message.channel.send("Coming right up!").then(msg => {
msg.delete({ timeout: 5000 })
})
.catch(console.error);
setTimeout(function(){
message.reply(response);
message.channel.send("https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FStrawberry%20cake%20roll.gif?v=1613444145762");
}, 5000);
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T21:39:37.990",
"Id": "505508",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T21:58:02.563",
"Id": "505512",
"Score": "1",
"body": "Hey Joseph. It looks like the only things that are different are: the message content check and the gif you are returning. Maybe you could get rid of the if's all together and have an object that contains key value pairs? Like `const gifs = { coffee: \"link to coffee gif\" }` and then `map` through the gifs and match the key to the message content and send the associated value? If that isn't clear I can post an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:07:54.187",
"Id": "505514",
"Score": "0",
"body": "@BensSteves could you show an example? I am not sure on how to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:42:47.470",
"Id": "505518",
"Score": "0",
"body": "@JosephLee Posted my thoughts on it. Looks like Zsolt beat me to it but his solution looks good as well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T16:51:48.487",
"Id": "505593",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/256114/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>As most of the content is the same in your if statements, you need to check what's changing. It seems it's the image URL only.</p>\n<p>You can update the if statement to only change the image URL and send it in the end:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let img = '';\nlet text = message.content.toLowerCase();\n\nif (text.includes('order coffee')) {\n img = 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FCoffee%20cropped.gif?v=1613444146008';\n}\n\nif (text.includes('order latte')) {\n img = 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FLatte.gif?v=1613444145762';\n}\n\nif (text.includes('order muffin')) {\n img = 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FMuffin.gif?v=1613444146225';\n}\n\n//...\n\nmessage.channel\n .send('Coming right up!')\n .then((msg) => {\n msg.delete({ timeout: 5000 });\n })\n .catch(console.error);\nsetTimeout(function () {\n message.reply(response);\n message.channel.send(img);\n}, 5000);\n</code></pre>\n<p>You could also create an object where the keys are search strings and the values are the image URLs. Maybe you could also create a util function that finds the image by search string:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function findImage(text, images) {\n for (let [query, url] of Object.entries(images)) {\n if (text.toLowerCase().includes(query)) return url;\n }\n}\n\nbot.on('message', (message) => {\n const reply = [\n "Here's your order!",\n 'Enjoy!',\n 'Here you go!',\n 'Let me know if you need anything else!',\n "You've been served.",\n "That'll be $3.50.",\n "That'll be $5.50",\n ];\n const images = {\n 'order coffee': 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FCoffee%20cropped.gif?v=1613444146008',\n 'order latte': 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FLatte.gif?v=1613444145762',\n 'order muffin': 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FMuffin.gif?v=1613444146225',\n 'order strawberry cake roll': 'https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FStrawberry%20cake%20roll.gif?v=1613444145762',\n };\n const response = reply[Math.floor(Math.random() * reply.length)];\n const img = findImage(message.content, images);\n\n if (!img) { /* return? */ }\n\n message.channel\n .send('Coming right up!')\n .then((msg) => msg.delete({ timeout: 5000 }))\n .catch(console.error);\n\n setTimeout(function () {\n message.reply(response);\n message.channel.send(img);\n }, 5000);\n});\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:11:15.903",
"Id": "256115",
"ParentId": "256114",
"Score": "2"
}
},
{
"body": "<p>The first thing to look at is: what is the same for each if statement and what is different. The key differences are:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>message.content.toLowerCase().includes("this string here is what's different")\n</code></pre>\n<p>and</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>message.channel.send("links are different")\n</code></pre>\n<p>To clean it up, we can get rid of the if statements all together and create an object that contains key:value pairs with key <code>message.content</code> you want to check against with and value the associated media link. That would look like this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const gifs = { \n "coffee": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FCoffee%20cropped.gif?v=1613444146008", \n "latte": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FLatte.gif?v=1613444145762",\n "muffin": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FMuffin.gif?v=1613444146225",\n "strawberry cake roll": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FStrawberry%20cake%20roll.gif?v=1613444145762", \n};\n</code></pre>\n<p>We can take out the string "order" because that is also common to all of the keys. If the data you are getting back requires you to check on "order coffee" then change it back.</p>\n<p>Now you can map through the keys of the <code>gifs</code> object to see if that <code>key</code> is included in the message content. If it is, return the <code>value</code> associated with that key.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>Object.keys(gifs).forEach(key => { \n if(message.content.toLowerCase().includes(key)) {\n return gifs[key]; // get the value at key in the gifs object\n }\n}\n</code></pre>\n<p><code>Object.keys()</code> takes an object and returns an array of the keys in that object. <code>_.forEach</code> is a method on an <strong>Array</strong> that loops through an array just like a for loop. It takes a callback function as a param.</p>\n<p>Putting that all together we get:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// can define this in a helper / util file or at the top of this file since it is a constant list\nconst REPLIES_LIST = [\n "Here's your order!",\n "Enjoy!",\n "Here you go!",\n "Let me know if you need anything else!",\n "You've been served.",\n "That'll be $3.50.",\n "That'll be $5.50", \n];\n\nbot.on("message", message => { \n const { channel, content, reply: messageReply} = message; // destructure variables off of message, reply: messageReply renames reply to messageReply\n const response = REPLIES_LIST[Math.floor(Math.random() * REPLIES_LIST.length)];\n\n Object.keys(gifs).map(key => { \n if(content.toLowerCase().includes(key)) {\n channel.send("Coming right up!").then(msg => {\n msg.delete({ timeout: 5000 })\n }).catch(console.error);\n\n setTimeout(() => {\n messageReply(response);\n channel.send(gifs[key]); // get the value at key in the gifs object\n }, 5000);\n }\n });\n});\n\n</code></pre>\n<p><strong>Code Walkthrough</strong></p>\n<ol>\n<li>The bot gets a message "message" we declare temporary variables equal to message.content, message.channel, and message.reply by destructuring</li>\n<li>Create another variable equal to a random response from the reply list or array</li>\n<li>Traverse through the keys in the <code>gifs</code> object using <code>forEach</code></li>\n<li>For each item in the gifs object we check to see if the <code>message.content.toLowerCase()</code> includes that key, if it does we send a message "Coming right up!" to the channel</li>\n<li>Handle some logic and a catch after sending</li>\n<li>Create a setTimeout that waits 5 seconds before replying with the response and <code>channel.send</code>ing the gif url</li>\n</ol>\n<h3>Updated: 02/17/21</h3>\n<p>There were comments questioning the use of <code>_.map</code> over <code>_.forEach</code> or <code>_.some</code>. We should be using <code>_.forEach</code> in this case and I updated the original answer to reflect that. Below I highlighted the differences between the three and ultimately what works best for this scenario.</p>\n<p><strong><code>Array.prototype.map((item) => // do something)</code></strong>\nA method that iterates through every element of an array and returns a <strong>new array</strong> resulting from the callback function you passed.</p>\n<p>Example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> const list = [1, 2, 3, 4, 5];\n const newList = list.map((item) => item + 2); // [1+2, 2+2, 3+2, 4+2, 5+2]\n\n console.log(list); // [1, 2, 3, 4, 5]\n console.log(newList); // [3, 4, 5, 6, 7]\n</code></pre>\n<p>We only use map if we are using the array that the map returns (in this example <code>newList</code>. In the original answer, we were using map <em>without</em> returning anything or using the returned array which is an <strong>anit-pattern</strong>.</p>\n<p><strong><code>Array.prototype.forEach((item) => // do something)</code></strong>\nA method that iterates through an array and uses a callback to <strong>mutate</strong> the array, returning <strong>undefined</strong>.</p>\n<p>Example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> const list = [1, 2, 3, 4, 5];\n list.forEach((item, index, arr) => arr[index] = item + 2);\n \n console.log(list); //[3, 4, 5, 6, 7]\n</code></pre>\n<p>The <code>forEach</code> provides you with the current item (item), index of the current item in the array (index), and the original array (arr).</p>\n<p>We use <code>forEach</code> when we want to use the callback passed to mutate the array without returning a new array. Key thing to note, you cannot exit a <code>forEach</code> without raising an exception.</p>\n<p><strong><code>Array.prototype.some((item) => // do something)</code></strong>\nA method that checks if at <strong>least one element</strong> in the array "passes" the callback you provide, returning a <strong>boolean</strong>.</p>\n<p>Example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> const list = [1, 2, 3, 4, 5];\n list.some((item) => item === 2); // true, stops when it reads 2 in the array because it matches\n \n console.log(list); //[1, 2, 3, 4, 5]\n</code></pre>\n<p>For the question that was asked, <code>forEach</code> is most appropriate. You then have to contemplate, will my data have duplicates or not have anything at all and handle those conditions. If you will have duplicates, you may want to you the <code>find</code> method approach Daniël van den Berg suggests. <code>find</code> is similar to <code>forEach</code> and <code>some</code>. It looks for the <strong>first</strong> item that matches the condition and returns that item.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T06:59:12.983",
"Id": "505531",
"Score": "6",
"body": "Any reason you chose map instead of ```forEach```, or even ```some```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T08:46:31.890",
"Id": "505539",
"Score": "0",
"body": "You could also distill `const cdnSrc = https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2F` (possibly replace the `%2f` with `/`) to increase readability of GIFS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T12:58:08.027",
"Id": "505553",
"Score": "0",
"body": "A beautiful example of how [Configure, Don't Integrate](https://flylib.com/books/en/1.315.1.53/1/) can improve readability, reduce duplication etc!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:42:30.657",
"Id": "505575",
"Score": "0",
"body": "Map is my react framework mind showing up :). `forEach` is more appropriate. Or you can use find like @DaniëlvandenBerg suggested. And I think `some` returns a boolean. Which is fine but you would have to update the code to handle true/false from `some`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:58:28.873",
"Id": "505577",
"Score": "1",
"body": "Please edit your answer to actually use `forEach` or `find`; comments are designed to be temporary and optional reading. And since this is a learning site, it's good to put your best foot forward! Note that performing side-effects in `map` is actually *opposed* to the React mindset - that's what `forEach` is for, after all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T15:12:21.593",
"Id": "505579",
"Score": "0",
"body": "@TheRubberDuck Yea I was updating my answer to reflect the change. Takes some time to update the answer after posting the comment :). And map is not opposed to the React mindset. You use it quite often actually. Depends on what you are doing and trying to solve :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T15:23:17.737",
"Id": "505580",
"Score": "0",
"body": "Whoops! saw that the original comment was 8 hours ago and for some reason assumed your reply was also from that long ago. Sorry about that. Also, I don't mean general `map` usage but rather **side-effects** in a mapper function - `map` usage should compute a value, not change one. It's like making an API call in a component render function - you should move that code to `useEffect`, an event handler, or some lifecycle method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T15:27:35.177",
"Id": "505581",
"Score": "2",
"body": "Your forEach example seems incorrect. forEach will not mutate the list, no matter how hard I try. not even if I do item += 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T16:23:38.357",
"Id": "505591",
"Score": "0",
"body": "Great catch @DaniëlvandenBerg. The way I had it you weren't actually updating the array value with `item + 2`. You have to reassign the array item by getting the current index and updating. `arr[index] = item + 2`. Updated the answer to reflect that."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:40:46.530",
"Id": "256117",
"ParentId": "256114",
"Score": "13"
}
},
{
"body": "<p>Althrough I mostly agree with Ben Stevens' answer, I do think there is room for even more improvement.</p>\n<pre><code>// can define this in a helper / util file or at the top of this file since it is a constant list\nconst REPLIES_LIST = [\n "Here's your order!",\n "Enjoy!",\n "Here you go!",\n "Let me know if you need anything else!",\n "You've been served.",\n "That'll be $3.50.",\n "That'll be $5.50", \n];\n\nbot.on("message", message => { \n const { channel, content, reply: messageReply} = message; // destructure variables off of message, reply: messageReply renames reply to messageReply\n const response = REPLIES_LIST[Math.floor(Math.random() * REPLIES_LIST.length)];\n\n const key = Object.keys(gifs).find(key=>content.toLowerCase().includes(key));\n if (!key){\n //Potentially send a "I did not understand you."\n return;\n }\n channel\n .send("Coming right up!")\n .then(msg => {msg.delete({ timeout: 5000 })})\n .catch(console.error);\n \n setTimeout(() => {\n messageReply(response);\n channel.send(gifs[key]); // get the value at key in the gifs object\n }, 5000);\n});\n</code></pre>\n<p>I changed from using Object.keys(gifs).map to .find. The reason for using find here is that it stops after finding the first occurrence. This ensures that your script won't send two replies if someone puts "order coffee order latte".</p>\n<p>Another advantage is that you have less indentation, as the sending of the message is not inside a lambda (one of those "sub-functions", <code>()=>{}</code>). This adds some readability.</p>\n<p>If you would want to send two messages if someone says <code>order coffee order latte</code> you can use the code as Ben Stevens provides, but I would use <code>.forEach</code> instead of <code>.map</code>. <code>.map</code> is intended to return a (modified) copy of the array, which doesn't fit your use-case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T07:10:26.353",
"Id": "256126",
"ParentId": "256114",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T21:31:06.530",
"Id": "256114",
"Score": "12",
"Tags": [
"javascript"
],
"Title": "Discord bot for ordering food"
}
|
256114
|
<p>Is this code reliable? Is there any extra precaution I should or should not be taking here? How is my code to securely delete a file by repeatedly overwriting the contents?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int Argc, const char *Argv[]) {
srand(time(NULL));
unsigned int *RandBuf = NULL;
for (int I = 1; I < Argc; I++) {
long FileSize;
const char *const Path = Argv[I];
FILE *const File = fopen(Path, "r+");
if (!File || fseek(File, 0, SEEK_END) || (FileSize = ftell(File)) < 0) {
perror(Path);
continue;
}
const unsigned long IntCount = (FileSize+3)>>2;
RandBuf = realloc(RandBuf, IntCount<<2);
const unsigned char WriteCount = ((unsigned int)rand()&0xF)+16;
for (unsigned char Write = 0; Write < WriteCount; Write++) {
for (unsigned long Int = 0; Int < IntCount; Int++) {
RandBuf[Int] ^= (unsigned int)rand();
}
if (fseek(File, 0, SEEK_SET) || fwrite(RandBuf, 1, FileSize, File) < FileSize) {
perror(Path);
continue;
}
}
if (fclose(File) || remove(Path)) {
perror(Path);
continue;
}
}
free(RandBuf);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your description appears to suggest you're reimplementing <code>wipe</code>; I recommend you read its sources to see what an effective implementation looks like. I'll note that the concept could well be flawed if you're writing to a log-structured filesystem or to wear-levelling media - both of those need specific actions to erase data, because overwriting will simply create new data blocks elsewhere.</p>\n<p>The "PascalCase" naming convention makes this code surprisingly hard to read (and not just because capital <code>I</code> looks a lot like <code>1</code>, and <code>Int</code> sounds a lot like <code>int</code>). I would prefer to see more conventional identifiers, so that variables <em>look like</em> variables.</p>\n<p>This include looks pointless:</p>\n<blockquote>\n<pre><code> #include <unistd.h>\n</code></pre>\n</blockquote>\n<p>As we're using only Standard Library, prefer to omit this, for a portable program.</p>\n<blockquote>\n<pre><code> if (!File || fseek(File, 0, SEEK_END) || (FileSize = ftell(File)) < 0) {\n perror(Path);\n continue;\n }\n</code></pre>\n</blockquote>\n<p>I approve of error checking, but there's a problem here. If we open a file but fail to seek (because it's a non-regular file, perhaps), then we fail to close it.</p>\n<blockquote>\n<pre><code> RandBuf = realloc(RandBuf, IntCount<<2);\n</code></pre>\n</blockquote>\n<p>What happens when <code>realloc()</code> returns a null pointer? We have a leak and we have undefined behaviour when we dereference <code>RandBuf</code>. It seems risky to need that much memory, given that files can often be larger than address space. We'd probably prefer to write in sensible size chunks too, given the copying that's involved.</p>\n<blockquote>\n<pre><code> const unsigned long IntCount = (FileSize+3)>>2;\n RandBuf = realloc(RandBuf, IntCount<<2);\n</code></pre>\n</blockquote>\n<p>Where do those magic numbers <code>2</code> and <code>3</code> originate? I'm <em>guessing</em> that perhaps that <code>sizeof (int)</code> is 4 on your platform, and the constants derive from that. But it would be better to calculate from the actual size of <code>int</code> and to name the constants more appropriately.</p>\n<blockquote>\n<pre><code> for (unsigned char Write = 0; Write < WriteCount; Write++) {\n</code></pre>\n</blockquote>\n<p>This loop serves no purpose. We write a variety of values several times, but it's unlikely any of these values go all the way to the disk, given we never <code>fflush()</code> the stream.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T13:37:53.447",
"Id": "256147",
"ParentId": "256116",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T22:25:58.647",
"Id": "256116",
"Score": "1",
"Tags": [
"c",
"file"
],
"Title": "Replacing removed secure empty trash feature"
}
|
256116
|
<p>I'm aware that iterating frames in pandas is a very slow operation. I've heard vectorization speeds things up. I found a project that I'm using for sentiment analysis on reddit.</p>
<p><a href="https://github.com/GonVas/tickerrain/blob/1c701f82353c5d4d7299c5edff1db5da5fa71eaf/process.py#L103" rel="nofollow noreferrer">The Calculate dataframe method</a> wasn't working for some reason, (maybe different version of panda) I wanted to refactor it to use vectorization but Sadly it took me 2 days to even get the code working.</p>
<pre><code>def calculate_df(df):
data_df = df.filter(['tickers', 'score', 'sentiment'])
tickers_processed = pd.DataFrame(df.tickers.explode().value_counts())
tickers_processed = tickers_processed.rename(columns = {'tickers':'counts'})
tickers_processed['score'] = 0.0
tickers_processed['sentiment'] = 0.0
for idx, row_tick in enumerate(tickers_processed.itertuples(), 1):
upd_row_sent = row_tick.sentiment
upd_row_score = row_tick.score
for row_data in data_df.itertuples():
if(row_tick.Index in row_data.tickers):
upd_row_sent += row_data.sentiment['compound'] / row_tick.counts
upd_row_score += int(row_data.score) / row_tick.counts
tickers_processed.set_value(row_tick.Index, 'sentiment', upd_row_sent)
tickers_processed.set_value(row_tick.Index, 'score', upd_row_score)
</code></pre>
<p>Calling set value twice seems redundant, If I could calculate the dataset and update it using vectors I think the code would be a lot nicer</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T05:39:33.230",
"Id": "505528",
"Score": "0",
"body": "Welcome to posting to CodeReview@SE at long last. I can't identify `The Calculate dataframe method` - am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:28:04.053",
"Id": "505571",
"Score": "0",
"body": "@greybeard sorry the code is the contents of the method, ive updated to provide a link to the original code, this is the only portion I would like to refactor"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T15:47:33.977",
"Id": "505586",
"Score": "0",
"body": "I edited the method \"def line\" into your post mainly to show you *can* copy&paste between CR post & (I)DE. I urge you to include the code following that from *process.py*, I'd probably choose a separate code block to tell *supposed* target from [*context*](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T17:16:07.357",
"Id": "505597",
"Score": "0",
"body": "I can include more code, but I mostly just wanted to fix the double for loop, to leverage vertorization, I didn't want to include anything extra to confuse the reviewers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T17:53:30.323",
"Id": "505602",
"Score": "0",
"body": "(Reads like you didn't follow the above hyperlink to *How do I ask a Good Question?*)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T21:37:53.433",
"Id": "505614",
"Score": "0",
"body": "I don't see what i'm missing, the refactor is related to the inner contents of the code only. I've explain what I think is the issue and how it can be fixed. The column names can be easily inferred from the code. So what good would posting unrelated code be to the question, When the only thing that needs to be removed here is the forloops to use vectorization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-20T20:23:35.710",
"Id": "505909",
"Score": "0",
"body": "I can almost guarantee you will get answer quickly if you post a full working example. It's quite tedious to verify what your code does, and to make sure you don't break any logic unless you have a small toy dataset to play around with. This will also make it easy to measure performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-20T20:50:16.203",
"Id": "505911",
"Score": "0",
"body": "@Juho the link in the post provides the full code in, usually I feel like people avoid posts with code dumps, but seeing as this has now been told to me by multiple people I have a feeling I don't understand this community as well as I do Stackoverflow. I'll edit it when I get a chance"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T23:52:28.417",
"Id": "256120",
"Score": "2",
"Tags": [
"python",
"pandas",
"iteration"
],
"Title": "Python speed up dataframe writes"
}
|
256120
|
<blockquote>
<p>Given a smaller strings and a bigger string b, design an algorithm to find all permutations of the shorter string within the longer one.</p>
</blockquote>
<pre><code>def findPermutations(large: String, small: String): Int =
large.sliding(small.length).filter(_.diff(small).isEmpty).length
@ findPermutations("cbabadcbbabbcbabaabccbabc", "abbc")
res11: Int = 7
@ findPermutations("xaabx", "abb")
res12: Int = 0
</code></pre>
<h2>Archived (faulty)</h2>
<pre><code>@ def findPermutations(large: String, small: String): Int =
large.sliding(small.length)
.toList
.filter(_.toSet == small.toSet)
.length
defined function findPermutations
</code></pre>
<p>Please evaluate it for correctness and speed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T09:13:46.040",
"Id": "505541",
"Score": "1",
"body": "Algorithm is faulty: `findPermutations(\"xaabx\", \"abb\")` and the `.toList` doesn't serve any useful purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T02:17:28.573",
"Id": "505761",
"Score": "0",
"body": "Thanks, @jwvh. Please check out my update!"
}
] |
[
{
"body": "<ul>\n<li><strong>correct</strong> - As far as I can tell, yes.</li>\n<li><strong>concise</strong> - A <code>filter()</code> followed by a <code>.length</code> (or <code>.size</code>) can be simplified:\n<code>large.sliding(small.length).count(_.diff(small).isEmpty)</code></li>\n<li><strong>fast</strong> - Could be faster, but it wouldn't be as concise.</li>\n</ul>\n<p>Consider the following: <code>findPermutations("abcxcba", "cab")</code></p>\n<p>Under the current design that would be 5 invocations of <code>_.diff(small).isEmpty</code>, but 3 of the 5 are rather pointless. No test string containing a character not found in the target string is worth the effort.</p>\n<p>It'd be nice if the sliding window could "jump" over non-target characters. Doable, but not trivial.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T04:51:07.760",
"Id": "256285",
"ParentId": "256122",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256285",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T03:56:31.073",
"Id": "256122",
"Score": "1",
"Tags": [
"strings",
"scala"
],
"Title": "Find Permutations of String in Scala"
}
|
256122
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.